Merge from Chromium at DEPS revision 232015

This commit was generated by merge_to_master.py.

Change-Id: I9f9356b47400040c33b19d1ff3837161628089e0
diff --git a/Source/core/accessibility/AXMenuListOption.cpp b/Source/core/accessibility/AXMenuListOption.cpp
index 2635780..7dc61b7 100644
--- a/Source/core/accessibility/AXMenuListOption.cpp
+++ b/Source/core/accessibility/AXMenuListOption.cpp
@@ -51,7 +51,7 @@
 {
     // isDisabledFormControl() returns true if the parent <select> element is disabled,
     // which we don't want.
-    return !toHTMLOptionElement(m_element.get())->ownElementDisabled();
+    return !toHTMLOptionElement(m_element)->ownElementDisabled();
 }
 
 bool AXMenuListOption::isVisible() const
@@ -72,7 +72,7 @@
 
 bool AXMenuListOption::isSelected() const
 {
-    return toHTMLOptionElement(m_element.get())->selected();
+    return toHTMLOptionElement(m_element)->selected();
 }
 
 void AXMenuListOption::setSelected(bool b)
@@ -80,7 +80,7 @@
     if (!canSetSelectedAttribute())
         return;
 
-    toHTMLOptionElement(m_element.get())->setSelected(b);
+    toHTMLOptionElement(m_element)->setSelected(b);
 }
 
 bool AXMenuListOption::canSetSelectedAttribute() const
@@ -106,7 +106,7 @@
 
 String AXMenuListOption::stringValue() const
 {
-    return toHTMLOptionElement(m_element.get())->text();
+    return toHTMLOptionElement(m_element)->text();
 }
 
 } // namespace WebCore
diff --git a/Source/core/accessibility/AXObject.cpp b/Source/core/accessibility/AXObject.cpp
index 140be22..702f279 100644
--- a/Source/core/accessibility/AXObject.cpp
+++ b/Source/core/accessibility/AXObject.cpp
@@ -164,14 +164,12 @@
     return 0;
 }
 
-#if HAVE(ACCESSIBILITY)
 void AXObject::updateBackingStore()
 {
     // Updating the layout may delete this object.
     if (Document* document = this->document())
         document->updateLayoutIgnorePendingStylesheets();
 }
-#endif
 
 bool AXObject::isARIATextControl() const
 {
@@ -315,7 +313,6 @@
     return AccessibilityOrientationHorizontal;
 }
 
-#if HAVE(ACCESSIBILITY)
 static String queryString(WebLocalizedString::Name name)
 {
     return Locale::defaultLocale().queryString(name);
@@ -348,7 +345,6 @@
         return emptyString();
     }
 }
-#endif
 
 AccessibilityButtonState AXObject::checkboxOrRadioValue() const
 {
@@ -491,14 +487,12 @@
     return const_cast<AXObject*>(this);
 }
 
-#if HAVE(ACCESSIBILITY)
 const AXObject::AccessibilityChildrenVector& AXObject::children()
 {
     updateChildrenIfNecessary();
 
     return m_children;
 }
-#endif
 
 AXObject* AXObject::parentObjectUnignored() const
 {
@@ -635,11 +629,6 @@
     return element->fastGetAttribute(attribute);
 }
 
-TextIteratorBehavior AXObject::textIteratorBehaviorForTextRange() const
-{
-    return TextIteratorIgnoresStyleVisibility;
-}
-
 bool AXObject::press() const
 {
     Element* actionElem = actionElement();
@@ -896,7 +885,6 @@
     return true;
 }
 
-#if HAVE(ACCESSIBILITY)
 int AXObject::lineForPosition(const VisiblePosition& visiblePos) const
 {
     if (visiblePos.isNull() || !node())
@@ -923,7 +911,6 @@
 
     return lineCount;
 }
-#endif
 
 // Finds a RenderListItem parent give a node.
 static RenderListItem* renderListItemContainerForNode(Node* node)
diff --git a/Source/core/accessibility/AXObject.h b/Source/core/accessibility/AXObject.h
index ae2d7d7..a1ae0c5 100644
--- a/Source/core/accessibility/AXObject.h
+++ b/Source/core/accessibility/AXObject.h
@@ -30,7 +30,6 @@
 #ifndef AXObject_h
 #define AXObject_h
 
-#include "core/editing/TextIterator.h"
 #include "core/editing/VisiblePosition.h"
 #include "platform/geometry/FloatQuad.h"
 #include "platform/geometry/LayoutRect.h"
@@ -250,43 +249,28 @@
     AccessibilityTextDirectionBottomToTop
 };
 
-struct VisiblePositionRange {
-
-    VisiblePosition start;
-    VisiblePosition end;
-
-    VisiblePositionRange() { }
-
-    VisiblePositionRange(const VisiblePosition& s, const VisiblePosition& e)
-        : start(s)
-        , end(e)
-    { }
-
-    bool isNull() const { return start.isNull() || end.isNull(); }
-};
-
-struct PlainTextRange {
-
-    unsigned start;
-    unsigned length;
-
-    PlainTextRange()
-        : start(0)
-        , length(0)
-    { }
-
-    PlainTextRange(unsigned s, unsigned l)
-        : start(s)
-        , length(l)
-    { }
-
-    bool isNull() const { return !start && !length; }
-};
-
 class AXObject : public RefCounted<AXObject> {
 public:
     typedef Vector<RefPtr<AXObject> > AccessibilityChildrenVector;
 
+    struct PlainTextRange {
+
+        unsigned start;
+        unsigned length;
+
+        PlainTextRange()
+            : start(0)
+            , length(0)
+        { }
+
+        PlainTextRange(unsigned s, unsigned l)
+            : start(s)
+            , length(l)
+        { }
+
+        bool isNull() const { return !start && !length; }
+    };
+
 protected:
     AXObject();
 
@@ -529,10 +513,7 @@
     const AtomicString& getAttribute(const QualifiedName&) const;
 
     // Selected text.
-    TextIteratorBehavior textIteratorBehaviorForTextRange() const;
     virtual PlainTextRange selectedTextRange() const { return PlainTextRange(); }
-    unsigned selectionStart() const { return selectedTextRange().start; }
-    unsigned selectionEnd() const { return selectedTextRange().length; }
     virtual String selectedText() const { return String(); }
 
     // Modify or take an action on an object.
@@ -563,8 +544,6 @@
     virtual void updateAccessibilityRole() { }
 
     // Text metrics. Most of these should be deprecated, needs major cleanup.
-    virtual VisiblePositionRange visiblePositionRange() const { return VisiblePositionRange(); }
-    virtual IntRect boundsForVisiblePositionRange(const VisiblePositionRange&) const { return IntRect(); }
     virtual VisiblePosition visiblePositionForIndex(int) const { return VisiblePosition(); }
     int lineForPosition(const VisiblePosition&) const;
     virtual int index(const VisiblePosition&) const { return -1; }
@@ -599,13 +578,6 @@
     bool m_detached;
 };
 
-#if !HAVE(ACCESSIBILITY)
-inline const AXObject::AccessibilityChildrenVector& AXObject::children() { return m_children; }
-inline String AXObject::actionVerb() const { return emptyString(); }
-inline int AXObject::lineForPosition(const VisiblePosition&) const { return -1; }
-inline void AXObject::updateBackingStore() { }
-#endif
-
 #define DEFINE_AX_OBJECT_TYPE_CASTS(thisType, predicate) \
     DEFINE_TYPE_CASTS(thisType, AXObject, object, object->predicate, object.predicate)
 
diff --git a/Source/core/accessibility/AXObjectCache.cpp b/Source/core/accessibility/AXObjectCache.cpp
index eb784d6..950b465 100644
--- a/Source/core/accessibility/AXObjectCache.cpp
+++ b/Source/core/accessibility/AXObjectCache.cpp
@@ -28,8 +28,6 @@
 
 #include "config.h"
 
-#if HAVE(ACCESSIBILITY)
-
 #include "core/accessibility/AXObjectCache.h"
 
 #include "HTMLNames.h"
@@ -1028,5 +1026,3 @@
 }
 
 } // namespace WebCore
-
-#endif // HAVE(ACCESSIBILITY)
diff --git a/Source/core/accessibility/AXObjectCache.h b/Source/core/accessibility/AXObjectCache.h
index 53d4a62..11df342 100644
--- a/Source/core/accessibility/AXObjectCache.h
+++ b/Source/core/accessibility/AXObjectCache.h
@@ -133,17 +133,10 @@
     void handleAttributeChanged(const QualifiedName& attrName, Element*);
     void recomputeIsIgnored(RenderObject* renderer);
 
-#if HAVE(ACCESSIBILITY)
     static void enableAccessibility() { gAccessibilityEnabled = true; }
     static bool accessibilityEnabled() { return gAccessibilityEnabled; }
     static void setInlineTextBoxAccessibility(bool flag) { gInlineTextBoxAccessibility = flag; }
     static bool inlineTextBoxAccessibility() { return gInlineTextBoxAccessibility; }
-#else
-    static void enableAccessibility() { }
-    static void setInlineTextBoxAccessibility(bool) { }
-    static bool accessibilityEnabled() { return false; }
-    static bool inlineTextBoxAccessibility() { return false; }
-#endif
 
     void removeAXID(AXObject*);
     bool isIDinUse(AXID id) const { return m_idsInUse.contains(id); }
@@ -237,61 +230,6 @@
 // This will let you know if aria-hidden was explicitly set to false.
 bool isNodeAriaVisible(Node*);
 
-#if !HAVE(ACCESSIBILITY)
-inline AXObjectInclusion AXComputedObjectAttributeCache::getIgnored(AXID) const { return DefaultBehavior; }
-inline void AXComputedObjectAttributeCache::setIgnored(AXID, AXObjectInclusion) { }
-inline AXObjectCache::AXObjectCache(const Document* doc) : m_document(const_cast<Document*>(doc)), m_notificationPostTimer(this, 0) { }
-inline AXObjectCache::~AXObjectCache() { }
-inline AXObject* AXObjectCache::focusedUIElementForPage(const Page*) { return 0; }
-inline AXObject* AXObjectCache::get(RenderObject*) { return 0; }
-inline AXObject* AXObjectCache::get(Node*) { return 0; }
-inline AXObject* AXObjectCache::get(Widget*) { return 0; }
-inline AXObject* AXObjectCache::get(AbstractInlineTextBox*) { return 0; }
-inline AXObject* AXObjectCache::getOrCreate(AccessibilityRole) { return 0; }
-inline AXObject* AXObjectCache::getOrCreate(RenderObject*) { return 0; }
-inline AXObject* AXObjectCache::getOrCreate(Node*) { return 0; }
-inline AXObject* AXObjectCache::getOrCreate(Widget*) { return 0; }
-inline AXObject* AXObjectCache::getOrCreate(AbstractInlineTextBox*) { return 0; }
-inline AXObject* AXObjectCache::rootObject() { return 0; }
-inline Element* AXObjectCache::rootAXEditableElement(Node*) { return 0; }
-inline bool nodeHasRole(Node*, const String&) { return false; }
-inline void AXObjectCache::startCachingComputedObjectAttributesUntilTreeMutates() { }
-inline void AXObjectCache::stopCachingComputedObjectAttributes() { }
-inline bool isNodeAriaVisible(Node*) { return true; }
-inline const Element* AXObjectCache::rootAXEditableElement(const Node*) { return 0; }
-inline void AXObjectCache::attachWrapper(AXObject*) { }
-inline void AXObjectCache::checkedStateChanged(Node*) { }
-inline void AXObjectCache::childrenChanged(RenderObject*) { }
-inline void AXObjectCache::childrenChanged(Node*) { }
-inline void AXObjectCache::childrenChanged(AXObject*) { }
-inline void AXObjectCache::textChanged(RenderObject*) { }
-inline void AXObjectCache::textChanged(Node*) { }
-inline void AXObjectCache::textChanged(AXObject*) { }
-inline void AXObjectCache::updateCacheAfterNodeIsAttached(Node*) { }
-inline void AXObjectCache::detachWrapper(AXObject*) { }
-inline void AXObjectCache::handleActiveDescendantChanged(Node*) { }
-inline void AXObjectCache::handleAriaExpandedChange(Node*) { }
-inline void AXObjectCache::handleAriaRoleChanged(Node*) { }
-inline void AXObjectCache::handleFocusedUIElementChanged(Node*, Node*) { }
-inline void AXObjectCache::handleScrollbarUpdate(ScrollView*) { }
-inline void AXObjectCache::handleAttributeChanged(const QualifiedName&, Element*) { }
-inline void AXObjectCache::recomputeIsIgnored(RenderObject*) { }
-inline void AXObjectCache::handleScrolledToAnchor(const Node*) { }
-inline void AXObjectCache::nodeTextChangeNotification(Node*, AXTextChange, unsigned, const String&) { }
-inline void AXObjectCache::nodeTextChangePlatformNotification(AXObject*, AXTextChange, unsigned, const String&) { }
-inline void AXObjectCache::postNotification(AXObject*, Document*, AXNotification, bool, PostType) { }
-inline void AXObjectCache::postNotification(RenderObject*, AXNotification, bool, PostType) { }
-inline void AXObjectCache::postNotification(Node*, AXNotification, bool, PostType) { }
-inline void AXObjectCache::postPlatformNotification(AXObject*, AXNotification) { }
-inline void AXObjectCache::remove(AXID) { }
-inline void AXObjectCache::remove(RenderObject*) { }
-inline void AXObjectCache::remove(Node*) { }
-inline void AXObjectCache::remove(Widget*) { }
-inline void AXObjectCache::remove(AbstractInlineTextBox*) { }
-inline void AXObjectCache::selectedChildrenChanged(RenderObject*) { }
-inline void AXObjectCache::selectedChildrenChanged(Node*) { }
-#endif
-
 }
 
 #endif
diff --git a/Source/core/accessibility/AXRenderObject.cpp b/Source/core/accessibility/AXRenderObject.cpp
index c84daad..f5e58a4 100644
--- a/Source/core/accessibility/AXRenderObject.cpp
+++ b/Source/core/accessibility/AXRenderObject.cpp
@@ -40,6 +40,7 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/RenderedPosition.h"
+#include "core/editing/TextIterator.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/frame/Frame.h"
@@ -1160,7 +1161,7 @@
                 if (frame->document() != node->document())
                     return String();
 
-                return plainText(rangeOfContents(node).get(), textIteratorBehaviorForTextRange());
+                return plainText(rangeOfContents(node).get(), TextIteratorIgnoresStyleVisibility);
             }
         }
 
@@ -1595,7 +1596,7 @@
 // Selected text.
 //
 
-PlainTextRange AXRenderObject::selectedTextRange() const
+AXObject::PlainTextRange AXRenderObject::selectedTextRange() const
 {
     ASSERT(isTextControl());
 
@@ -1912,7 +1913,7 @@
     }
 }
 
-PlainTextRange AXRenderObject::ariaSelectedTextRange() const
+AXObject::PlainTextRange AXRenderObject::ariaSelectedTextRange() const
 {
     Node* node = m_renderer->node();
     if (!node)
diff --git a/Source/core/animation/ActiveAnimations.h b/Source/core/animation/ActiveAnimations.h
index c411b5a..bf2cb9a 100644
--- a/Source/core/animation/ActiveAnimations.h
+++ b/Source/core/animation/ActiveAnimations.h
@@ -42,12 +42,12 @@
 class ActiveAnimations {
 public:
     // Animations that are currently active for this element, their effects will be applied
-    // during a style recalc.
-    AnimationStack* defaultStack() { return &m_defaultStack; }
+    // during a style recalc. CSS Transitions are included in this stack.
+    AnimationStack& defaultStack() { return m_defaultStack; }
     // Tracks the state of active CSS Animations and Transitions. The individual animations
     // will also be part of the default stack, but the mapping betwen animation name and
     // player is kept here.
-    CSSAnimations* cssAnimations() { return &m_cssAnimations; }
+    CSSAnimations& cssAnimations() { return m_cssAnimations; }
     bool isEmpty() const { return m_defaultStack.isEmpty() && m_cssAnimations.isEmpty(); }
 private:
     AnimationStack m_defaultStack;
diff --git a/Source/core/animation/AnimatableColor.h b/Source/core/animation/AnimatableColor.h
index 7969510..57c8fd3 100644
--- a/Source/core/animation/AnimatableColor.h
+++ b/Source/core/animation/AnimatableColor.h
@@ -32,7 +32,7 @@
 #define AnimatableColor_h
 
 #include "core/animation/AnimatableValue.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 
 namespace WebCore {
 
diff --git a/Source/core/animation/AnimatableFilterOperations.cpp b/Source/core/animation/AnimatableFilterOperations.cpp
new file mode 100644
index 0000000..d755442
--- /dev/null
+++ b/Source/core/animation/AnimatableFilterOperations.cpp
@@ -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:
+ *
+ *     * 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/AnimatableFilterOperations.h"
+
+#include <algorithm>
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableFilterOperations::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+    const AnimatableFilterOperations* target = toAnimatableFilterOperations(value);
+    if (!operations().canInterpolateWith(target->operations()))
+        return defaultInterpolateTo(this, value, fraction);
+
+    FilterOperations result;
+    size_t fromSize = operations().size();
+    size_t toSize = target->operations().size();
+    size_t size = std::max(fromSize, toSize);
+    for (size_t i = 0; i < size; i++) {
+        FilterOperation* from = (i < fromSize) ? m_operations.operations()[i].get() : 0;
+        FilterOperation* to = (i < toSize) ? target->m_operations.operations()[i].get() : 0;
+        RefPtr<FilterOperation> blendedOp = FilterOperation::blend(from, to, fraction);
+        if (blendedOp)
+            result.operations().append(blendedOp);
+        else
+            ASSERT_NOT_REACHED();
+    }
+    return AnimatableFilterOperations::create(result);
+}
+
+PassRefPtr<AnimatableValue> AnimatableFilterOperations::addWith(const AnimatableValue* value) const
+{
+    RELEASE_ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: AnimatableFilterOperations::addWith()");
+    return 0;
+}
+
+bool AnimatableFilterOperations::equalTo(const AnimatableValue* value) const
+{
+    return operations() == toAnimatableFilterOperations(value)->operations();
+}
+
+}
diff --git a/Source/core/animation/AnimatableFilterOperations.h b/Source/core/animation/AnimatableFilterOperations.h
new file mode 100644
index 0000000..deda91e
--- /dev/null
+++ b/Source/core/animation/AnimatableFilterOperations.h
@@ -0,0 +1,67 @@
+/*
+ * 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 AnimatableFilterOperations_h
+#define AnimatableFilterOperations_h
+
+#include "core/animation/AnimatableValue.h"
+#include "core/platform/graphics/filters/FilterOperations.h"
+
+namespace WebCore {
+
+class AnimatableFilterOperations : public AnimatableValue {
+public:
+    virtual ~AnimatableFilterOperations() { }
+    static PassRefPtr<AnimatableFilterOperations> create(const FilterOperations& operations)
+    {
+        return adoptRef(new AnimatableFilterOperations(operations));
+    }
+    const FilterOperations& operations() const { return m_operations; }
+
+protected:
+    virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+    virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+    AnimatableFilterOperations(const FilterOperations& operations)
+        : m_operations(operations)
+    {
+    }
+    virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+    virtual AnimatableType type() const OVERRIDE { return TypeFilterOperations; }
+
+    FilterOperations m_operations;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableFilterOperations, isFilterOperations());
+
+} // namespace WebCore
+
+#endif // AnimatableFilterOperations_h
diff --git a/Source/core/animation/AnimatableLengthBoxAndBool.h b/Source/core/animation/AnimatableLengthBoxAndBool.h
index ddfc8fa..9e33797 100644
--- a/Source/core/animation/AnimatableLengthBoxAndBool.h
+++ b/Source/core/animation/AnimatableLengthBoxAndBool.h
@@ -43,7 +43,7 @@
         return adoptRef(new AnimatableLengthBoxAndBool(box, flag));
     }
     const AnimatableValue* box() const { return m_box.get(); }
-    const bool flag() const { return m_flag; }
+    bool flag() const { return m_flag; }
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
diff --git a/Source/core/page/RuntimeEnabledFeaturesCustom.cpp b/Source/core/animation/AnimatableShadow.cpp
similarity index 64%
copy from Source/core/page/RuntimeEnabledFeaturesCustom.cpp
copy to Source/core/animation/AnimatableShadow.cpp
index 2ac204d..4d1a847 100644
--- a/Source/core/page/RuntimeEnabledFeaturesCustom.cpp
+++ b/Source/core/animation/AnimatableShadow.cpp
@@ -29,15 +29,27 @@
  */
 
 #include "config.h"
-#include "RuntimeEnabledFeatures.h"
-
-#include "core/workers/SharedWorkerRepository.h"
+#include "core/animation/AnimatableShadow.h"
 
 namespace WebCore {
 
-bool RuntimeEnabledFeatures::sharedWorkerEnabled()
+PassRefPtr<AnimatableValue> AnimatableShadow::interpolateTo(const AnimatableValue* value, double fraction) const
 {
-    return SharedWorkerRepository::isAvailable();
+    const AnimatableShadow* shadowList = toAnimatableShadow(value);
+    return AnimatableShadow::create(ShadowList::blend(m_shadowList.get(), shadowList->m_shadowList.get(), fraction));
+}
+
+PassRefPtr<AnimatableValue> AnimatableShadow::addWith(const AnimatableValue* value) const
+{
+    // FIXME: The spec doesn't specify anything for shadow in particular, but
+    // the default behaviour is probably not what one would expect.
+    return AnimatableValue::defaultAddWith(this, value);
+}
+
+bool AnimatableShadow::equalTo(const AnimatableValue* value) const
+{
+    const ShadowList* shadowList = toAnimatableShadow(value)->m_shadowList.get();
+    return m_shadowList == shadowList || (m_shadowList && shadowList && *m_shadowList == *shadowList);
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderingNodeProxy.h b/Source/core/animation/AnimatableShadow.h
similarity index 60%
copy from Source/core/rendering/RenderingNodeProxy.h
copy to Source/core/animation/AnimatableShadow.h
index ac5cb6d..23fb59b 100644
--- a/Source/core/rendering/RenderingNodeProxy.h
+++ b/Source/core/animation/AnimatableShadow.h
@@ -28,44 +28,40 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef RenderingNodeProxy_h
-#define RenderingNodeProxy_h
+#ifndef AnimatableShadow_h
+#define AnimatableShadow_h
 
-#include "core/rendering/LayoutIndicator.h"
-#include "wtf/Noncopyable.h"
+#include "core/animation/AnimatableValue.h"
+#include "core/rendering/style/ShadowList.h"
 
 namespace WebCore {
 
-class QualifiedName;
-class Node;
-
-#define STRICT_LAYOUT_THREADING 0
-
-class RenderingNodeProxy {
-    WTF_MAKE_NONCOPYABLE(RenderingNodeProxy);
+class AnimatableShadow : public AnimatableValue {
 public:
-    explicit RenderingNodeProxy(Node*);
-    ~RenderingNodeProxy();
-
-    bool hasTagName(const QualifiedName&) const;
-
-    Node* unsafeNode() const
+    virtual ~AnimatableShadow() { }
+    static PassRefPtr<AnimatableShadow> create(PassRefPtr<ShadowList> shadowList)
     {
-#if STRICT_LAYOUT_THREADING
-        ASSERT(!LayoutIndicator::inLayout());
-#endif
-        return m_node;
+        return adoptRef(new AnimatableShadow(shadowList));
     }
+    ShadowList* shadowList() const { return m_shadowList.get(); }
 
-    void clear() { m_node = 0; }
-    void set(Node* node) { m_node = node; }
+protected:
+    virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+    virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
 
 private:
-    Node* m_node;
+    explicit AnimatableShadow(PassRefPtr<ShadowList> shadowList)
+        : m_shadowList(shadowList)
+    {
+    }
+    virtual AnimatableType type() const OVERRIDE { return TypeShadow; }
+    virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+    const RefPtr<ShadowList> m_shadowList;
 };
 
-#undef STRICT_LAYOUT_THREADING
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableShadow, isShadow());
 
-}
+} // namespace WebCore
 
-#endif // RenderingNodeProxy_h
+#endif // AnimatableShadow_h
diff --git a/Source/core/animation/AnimatableStrokeDasharrayList.cpp b/Source/core/animation/AnimatableStrokeDasharrayList.cpp
index 62dde8e..7feff52 100644
--- a/Source/core/animation/AnimatableStrokeDasharrayList.cpp
+++ b/Source/core/animation/AnimatableStrokeDasharrayList.cpp
@@ -84,7 +84,7 @@
 
     Vector<RefPtr<AnimatableValue> > interpolatedValues;
     bool success = interpolateLists(from, to, fraction, interpolatedValues);
-    ASSERT(success);
+    ASSERT_UNUSED(success, success);
     return adoptRef(new AnimatableStrokeDasharrayList(interpolatedValues));
 }
 
diff --git a/Source/core/animation/AnimatableTransform.h b/Source/core/animation/AnimatableTransform.h
index 0bd6e4e..7fa8532 100644
--- a/Source/core/animation/AnimatableTransform.h
+++ b/Source/core/animation/AnimatableTransform.h
@@ -32,7 +32,7 @@
 #define AnimatableTransform_h
 
 #include "core/animation/AnimatableValue.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
+#include "platform/transforms/TransformOperations.h"
 
 namespace WebCore {
 
diff --git a/Source/core/animation/AnimatableValue.h b/Source/core/animation/AnimatableValue.h
index 023b1ff..2e52c32 100644
--- a/Source/core/animation/AnimatableValue.h
+++ b/Source/core/animation/AnimatableValue.h
@@ -58,6 +58,7 @@
     bool isClipPathOperation() const { return type() == TypeClipPathOperation; }
     bool isColor() const { return type() == TypeColor; }
     bool isDouble() const { return type() == TypeDouble; }
+    bool isFilterOperations() const { return type() == TypeFilterOperations; }
     bool isImage() const { return type() == TypeImage; }
     bool isLength() const { return type() == TypeLength; }
     bool isLengthBox() const { return type() == TypeLengthBox; }
@@ -68,6 +69,7 @@
     bool isRepeatable() const { return type() == TypeRepeatable; }
     bool isSVGLength() const { return type() == TypeSVGLength; }
     bool isSVGPaint() const { return type() == TypeSVGPaint; }
+    bool isShadow() const { return type() == TypeShadow; }
     bool isShapeValue() const { return type() == TypeShapeValue; }
     bool isStrokeDasharrayList() const { return type() == TypeStrokeDasharrayList; }
     bool isTransform() const { return type() == TypeTransform; }
@@ -90,6 +92,7 @@
         TypeClipPathOperation,
         TypeColor,
         TypeDouble,
+        TypeFilterOperations,
         TypeImage,
         TypeLength,
         TypeLengthBox,
@@ -100,6 +103,7 @@
         TypeRepeatable,
         TypeSVGLength,
         TypeSVGPaint,
+        TypeShadow,
         TypeShapeValue,
         TypeStrokeDasharrayList,
         TypeTransform,
diff --git a/Source/core/animation/AnimatableValueTestHelperTest.cpp b/Source/core/animation/AnimatableValueTestHelperTest.cpp
index c875fc4..13d4b83 100644
--- a/Source/core/animation/AnimatableValueTestHelperTest.cpp
+++ b/Source/core/animation/AnimatableValueTestHelperTest.cpp
@@ -32,11 +32,11 @@
 
 #include "core/animation/AnimatableValueTestHelper.h"
 
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
 #include "core/rendering/ClipPathOperation.h"
 #include "core/rendering/style/BasicShapes.h"
 #include "core/svg/SVGLengthContext.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/TranslateTransformOperation.h"
 
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
diff --git a/Source/core/animation/Animation.cpp b/Source/core/animation/Animation.cpp
index 2cbce79..7e28321 100644
--- a/Source/core/animation/Animation.cpp
+++ b/Source/core/animation/Animation.cpp
@@ -31,22 +31,23 @@
 #include "config.h"
 #include "core/animation/Animation.h"
 
-#include "core/animation/DocumentTimeline.h"
+#include "core/animation/ActiveAnimations.h"
 #include "core/animation/Player.h"
 #include "core/dom/Element.h"
 
 namespace WebCore {
 
-PassRefPtr<Animation> Animation::create(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
+PassRefPtr<Animation> Animation::create(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, Priority priority, PassOwnPtr<EventDelegate> eventDelegate)
 {
-    return adoptRef(new Animation(target, effect, timing, eventDelegate));
+    return adoptRef(new Animation(target, effect, timing, priority, eventDelegate));
 }
 
-Animation::Animation(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
+Animation::Animation(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, Priority priority, PassOwnPtr<EventDelegate> eventDelegate)
     : TimedItem(timing, eventDelegate)
     , m_target(target)
     , m_effect(effect)
     , m_activeInAnimationStack(false)
+    , m_priority(priority)
 {
 }
 
@@ -56,7 +57,7 @@
         clearEffects();
 }
 
-static AnimationStack* ensureAnimationStack(Element* element)
+static AnimationStack& ensureAnimationStack(Element* element)
 {
     return element->ensureActiveAnimations()->defaultStack();
 }
@@ -68,7 +69,7 @@
         return;
 
     if (!previouslyInEffect) {
-        ensureAnimationStack(m_target.get())->add(this);
+        ensureAnimationStack(m_target.get()).add(this);
         m_activeInAnimationStack = true;
     }
 
@@ -80,7 +81,7 @@
 {
     ASSERT(player());
     ASSERT(m_activeInAnimationStack);
-    ensureAnimationStack(m_target.get())->remove(this);
+    ensureAnimationStack(m_target.get()).remove(this);
     m_activeInAnimationStack = false;
     m_compositableValues.clear();
     m_target->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
diff --git a/Source/core/animation/Animation.h b/Source/core/animation/Animation.h
index 671d801..ee96c46 100644
--- a/Source/core/animation/Animation.h
+++ b/Source/core/animation/Animation.h
@@ -42,7 +42,9 @@
 class Animation FINAL : public TimedItem {
 
 public:
-    static PassRefPtr<Animation> create(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, PassOwnPtr<EventDelegate> = nullptr);
+    enum Priority { DefaultPriority, TransitionPriority };
+
+    static PassRefPtr<Animation> create(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, Priority = DefaultPriority, PassOwnPtr<EventDelegate> = nullptr);
 
     const AnimationEffect::CompositableValueMap* compositableValues() const
     {
@@ -51,6 +53,7 @@
     }
 
     const AnimationEffect* effect() const { return m_effect.get(); }
+    Priority priority() const { return m_priority; }
 
 protected:
     virtual void applyEffects(bool previouslyInEffect);
@@ -60,13 +63,15 @@
     virtual double calculateTimeToEffectChange(double inheritedTime, double activeTime, Phase) const OVERRIDE FINAL;
 
 private:
-    Animation(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, PassOwnPtr<EventDelegate>);
+    Animation(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, Priority, PassOwnPtr<EventDelegate>);
 
     RefPtr<Element> m_target;
     RefPtr<AnimationEffect> m_effect;
 
     bool m_activeInAnimationStack;
     OwnPtr<AnimationEffect::CompositableValueMap> m_compositableValues;
+
+    Priority m_priority;
 };
 
 } // namespace WebCore
diff --git a/Source/core/animation/AnimationClock.h b/Source/core/animation/AnimationClock.h
index b5d3dcd..c2585db 100644
--- a/Source/core/animation/AnimationClock.h
+++ b/Source/core/animation/AnimationClock.h
@@ -53,20 +53,22 @@
     double currentTime()
     {
         if (!m_frozen)
-            updateTime(monotonicallyIncreasingTime());
+            updateTime(m_monotonicallyIncreasingTime());
         return m_time;
     }
 
     void unfreeze() { m_frozen = false; }
 
+    void resetTimeForTesting() { m_time = 0; m_frozen = true; }
+
 private:
     AnimationClock(WTF::TimeFunction monotonicallyIncreasingTime)
-        : monotonicallyIncreasingTime(monotonicallyIncreasingTime)
+        : m_monotonicallyIncreasingTime(monotonicallyIncreasingTime)
         , m_time(0)
         , m_frozen(false)
     {
     }
-    WTF::TimeFunction monotonicallyIncreasingTime;
+    WTF::TimeFunction m_monotonicallyIncreasingTime;
     double m_time;
     bool m_frozen;
 };
diff --git a/Source/core/animation/AnimationStack.cpp b/Source/core/animation/AnimationStack.cpp
new file mode 100644
index 0000000..c48e914
--- /dev/null
+++ b/Source/core/animation/AnimationStack.cpp
@@ -0,0 +1,74 @@
+/*
+ * 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/AnimationStack.h"
+
+#include "core/animation/css/CSSAnimations.h"
+
+namespace WebCore {
+
+namespace {
+
+void copyToCompositableValueMap(const AnimationEffect::CompositableValueMap* source, AnimationEffect::CompositableValueMap& target)
+{
+    if (!source)
+        return;
+    for (AnimationEffect::CompositableValueMap::const_iterator iter = source->begin(); iter != source->end(); ++iter)
+        target.set(iter->key, iter->value);
+}
+
+} // namespace
+
+AnimationEffect::CompositableValueMap AnimationStack::compositableValues(const AnimationStack* animationStack, const Vector<InertAnimation*>* newAnimations, const HashSet<const Player*>* cancelledPlayers, Animation::Priority priority)
+{
+    AnimationEffect::CompositableValueMap result;
+
+    if (animationStack) {
+        const Vector<Animation*>& animations = animationStack->m_activeAnimations;
+        for (size_t i = 0; i < animations.size(); ++i) {
+            Animation* animation = animations[i];
+            if (animation->priority() != priority)
+                continue;
+            if (cancelledPlayers && cancelledPlayers->contains(animation->player()))
+                continue;
+            copyToCompositableValueMap(animation->compositableValues(), result);
+        }
+    }
+
+    if (newAnimations) {
+        for (size_t i = 0; i < newAnimations->size(); ++i)
+            copyToCompositableValueMap(newAnimations->at(i)->sample().get(), result);
+    }
+
+    return result;
+}
+
+} // namespace WebCore
diff --git a/Source/core/animation/AnimationStack.h b/Source/core/animation/AnimationStack.h
index b046cd4..fe1ffc5 100644
--- a/Source/core/animation/AnimationStack.h
+++ b/Source/core/animation/AnimationStack.h
@@ -31,14 +31,14 @@
 #ifndef AnimationStack_h
 #define AnimationStack_h
 
-#include "wtf/HashMap.h"
-#include "wtf/RefPtr.h"
+#include "core/animation/Animation.h"
+#include "core/animation/AnimationEffect.h"
+#include "wtf/HashSet.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
-class Element;
-class Animation;
+class InertAnimation;
 
 class AnimationStack {
 
@@ -51,8 +51,7 @@
         m_activeAnimations.remove(position);
     }
     bool isEmpty() const { return m_activeAnimations.isEmpty(); }
-    // FIXME: This should be PassRefPtr<CompositableValue> composite(Element*, CSSPropertyId)
-    const Vector<Animation*>& activeAnimations(const Element* element) const { return m_activeAnimations; }
+    static AnimationEffect::CompositableValueMap compositableValues(const AnimationStack*, const Vector<InertAnimation*>* newAnimations, const HashSet<const Player*>* cancelledPlayers, Animation::Priority);
 
 private:
     Vector<Animation*> m_activeAnimations;
diff --git a/Source/core/animation/ThreadedAnimation.cpp b/Source/core/animation/CompositorAnimations.cpp
similarity index 60%
rename from Source/core/animation/ThreadedAnimation.cpp
rename to Source/core/animation/CompositorAnimations.cpp
index 987bb3e..505e294 100644
--- a/Source/core/animation/ThreadedAnimation.cpp
+++ b/Source/core/animation/CompositorAnimations.cpp
@@ -29,34 +29,39 @@
  */
 
 #include "config.h"
-#include "core/animation/ThreadedAnimation.h"
+#include "core/animation/CompositorAnimations.h"
+
+#include "core/rendering/CompositedLayerMapping.h"
+#include "core/rendering/RenderBoxModelObject.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderObject.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebAnimation.h"
+#include "public/platform/WebCompositorSupport.h"
+#include "public/platform/WebFloatAnimationCurve.h"
+#include "public/platform/WebFloatKeyframe.h"
 
 namespace WebCore {
 
-ThreadedAnimation::IsCandidateForThreadedAnimationFunction ThreadedAnimation::s_isCandidateForThreadedAnimationFunction = *ThreadedAnimation::isCandidateForThreadedAnimationImpl;
-ThreadedAnimation::CanStartThreadedAnimationFunction ThreadedAnimation::s_canStartThreadedAnimationFunction = *ThreadedAnimation::canStartThreadedAnimationImpl;
-ThreadedAnimation::StartThreadedAnimationFunction ThreadedAnimation::s_startThreadedAnimationFunction = *ThreadedAnimation::startThreadedAnimationImpl;
-ThreadedAnimation::CancelThreadedAnimationFunction ThreadedAnimation::s_cancelThreadedAnimationFunction = *ThreadedAnimation::cancelThreadedAnimationImpl;
+bool CompositorAnimations::isCandidateForCompositorAnimation(const Timing& timing, const AnimationEffect* effect)
+{
+    // FIXME: Implement.
+    ASSERT_NOT_REACHED();
+    return false;
+}
 
-void ThreadedAnimation::isCandidateForThreadedAnimationImpl(const Timing* timing, const AnimationEffect* effect)
+bool CompositorAnimations::canStartCompositorAnimation(const Element* element)
+{
+    return element->renderer() && element->renderer()->compositingState() == PaintsIntoOwnBacking;
+}
+
+void CompositorAnimations::startCompositorAnimation(const Element* element, const Timing&, const AnimationEffect*, Vector<int>& startedAnimationIds)
 {
     // FIXME: Implement.
     ASSERT_NOT_REACHED();
 }
 
-void ThreadedAnimation::canStartThreadedAnimationImpl(const Element* element)
-{
-    // FIXME: Implement.
-    ASSERT_NOT_REACHED();
-}
-
-void ThreadedAnimation::startThreadedAnimationImpl(const Element*, const Timing*, const AnimationEffect*, Vector<int>& threadedAnimationIds)
-{
-    // FIXME: Implement.
-    ASSERT_NOT_REACHED();
-}
-
-void ThreadedAnimation::cancelThreadedAnimationImpl(const Element* element, int id)
+void CompositorAnimations::cancelCompositorAnimation(const Element* element, int id)
 {
     // FIXME: Implement.
     ASSERT_NOT_REACHED();
diff --git a/Source/core/rendering/RenderingNodeProxy.h b/Source/core/animation/CompositorAnimations.h
similarity index 60%
copy from Source/core/rendering/RenderingNodeProxy.h
copy to Source/core/animation/CompositorAnimations.h
index ac5cb6d..d95196d 100644
--- a/Source/core/rendering/RenderingNodeProxy.h
+++ b/Source/core/animation/CompositorAnimations.h
@@ -28,44 +28,42 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef RenderingNodeProxy_h
-#define RenderingNodeProxy_h
+#ifndef CompositorAnimations_h
+#define CompositorAnimations_h
 
-#include "core/rendering/LayoutIndicator.h"
-#include "wtf/Noncopyable.h"
+#include "core/animation/Timing.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
-class QualifiedName;
-class Node;
+class Element;
+class AnimationEffect;
 
-#define STRICT_LAYOUT_THREADING 0
+class CompositorAnimations {
 
-class RenderingNodeProxy {
-    WTF_MAKE_NONCOPYABLE(RenderingNodeProxy);
 public:
-    explicit RenderingNodeProxy(Node*);
-    ~RenderingNodeProxy();
+    static CompositorAnimations* instance() { return instance(0); }
+    static void setInstanceForTesting(CompositorAnimations* newInstance) { instance(newInstance); }
 
-    bool hasTagName(const QualifiedName&) const;
+    virtual bool isCandidateForCompositorAnimation(const Timing&, const AnimationEffect*);
+    virtual bool canStartCompositorAnimation(const Element*);
+    virtual void startCompositorAnimation(const Element*, const Timing&, const AnimationEffect*, Vector<int>& startedAnimationIds);
+    virtual void cancelCompositorAnimation(const Element*, int id);
 
-    Node* unsafeNode() const
-    {
-#if STRICT_LAYOUT_THREADING
-        ASSERT(!LayoutIndicator::inLayout());
-#endif
-        return m_node;
-    }
-
-    void clear() { m_node = 0; }
-    void set(Node* node) { m_node = node; }
+protected:
+    CompositorAnimations() { }
 
 private:
-    Node* m_node;
+    static CompositorAnimations* instance(CompositorAnimations* newInstance = 0)
+    {
+        static CompositorAnimations* instance = new CompositorAnimations();
+        if (newInstance) {
+            instance = newInstance;
+        }
+        return instance;
+    }
 };
 
-#undef STRICT_LAYOUT_THREADING
+} // namespace WebCore
 
-}
-
-#endif // RenderingNodeProxy_h
+#endif
diff --git a/Source/core/animation/DocumentTimeline.cpp b/Source/core/animation/DocumentTimeline.cpp
index c46729c..1681ef4 100644
--- a/Source/core/animation/DocumentTimeline.cpp
+++ b/Source/core/animation/DocumentTimeline.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/animation/DocumentTimeline.h"
 
+#include "core/animation/ActiveAnimations.h"
 #include "core/animation/AnimationClock.h"
 #include "core/animation/Player.h"
 #include "core/dom/Document.h"
@@ -38,65 +39,104 @@
 
 namespace WebCore {
 
-PassRefPtr<DocumentTimeline> DocumentTimeline::create(Document* document)
+// This value represents 1 frame at 30Hz plus a little bit of wiggle room.
+// TODO: Plumb a nominal framerate through and derive this value from that.
+const double DocumentTimeline::s_minimumDelay = 0.04;
+
+
+PassRefPtr<DocumentTimeline> DocumentTimeline::create(Document* document, PassOwnPtr<PlatformTiming> timing)
 {
-    return adoptRef(new DocumentTimeline(document));
+    return adoptRef(new DocumentTimeline(document, timing));
 }
 
-DocumentTimeline::DocumentTimeline(Document* document)
-    : m_document(document)
-    , m_zeroTimeAsPerfTime(nullValue())
+DocumentTimeline::DocumentTimeline(Document* document, PassOwnPtr<PlatformTiming> timing)
+    : m_zeroTime(nullValue())
+    , m_document(document)
 {
+    if (!timing)
+        m_timing = adoptPtr(new DocumentTimelineTiming(this));
+    else
+        m_timing = timing;
+
     ASSERT(document);
 }
 
 PassRefPtr<Player> DocumentTimeline::play(TimedItem* child)
 {
-    RefPtr<Player> player = Player::create(this, child);
+    RefPtr<Player> player = Player::create(*this, child);
     m_players.append(player);
 
     if (m_document->view())
-        m_document->view()->scheduleAnimation();
+        m_timing->serviceOnNextFrame();
 
     return player.release();
 }
 
-void DocumentTimeline::serviceAnimations(double monotonicAnimationStartTime)
+void DocumentTimeline::wake()
 {
-    {
-        TRACE_EVENT0("webkit", "DocumentTimeline::serviceAnimations");
-
-        m_document->animationClock().updateTime(monotonicAnimationStartTime);
-
-        double timeToNextEffect = -1;
-        for (int i = m_players.size() - 1; i >= 0; --i) {
-            if (!m_players[i]->update(&timeToNextEffect))
-                m_players.remove(i);
-        }
-
-        if (m_document->view() && !m_players.isEmpty())
-            m_document->view()->scheduleAnimation();
-    }
-
-    dispatchEvents();
+    m_timing->serviceOnNextFrame();
 }
 
-void DocumentTimeline::setZeroTimeAsPerfTime(double zeroTime)
+void DocumentTimeline::serviceAnimations(double monotonicAnimationStartTime)
 {
-    ASSERT(isNull(m_zeroTimeAsPerfTime));
-    m_zeroTimeAsPerfTime = zeroTime;
-    ASSERT(!isNull(m_zeroTimeAsPerfTime));
+    TRACE_EVENT0("webkit", "DocumentTimeline::serviceAnimations");
+
+    m_timing->cancelWake();
+
+    m_document->animationClock().updateTime(monotonicAnimationStartTime);
+
+    double timeToNextEffect = std::numeric_limits<double>::infinity();
+    double playerNextEffect;
+    for (int i = m_players.size() - 1; i >= 0; --i) {
+        if (!m_players[i]->update(&playerNextEffect))
+            m_players.remove(i);
+        if (playerNextEffect < timeToNextEffect)
+            timeToNextEffect = playerNextEffect;
+    }
+
+    if (!m_players.isEmpty()) {
+        if (timeToNextEffect < s_minimumDelay)
+            m_timing->serviceOnNextFrame();
+        else if (timeToNextEffect != std::numeric_limits<double>::infinity())
+            m_timing->wakeAfter(timeToNextEffect - s_minimumDelay);
+    }
+
+    if (m_document->view() && !m_players.isEmpty())
+        m_document->view()->scheduleAnimation();
+}
+
+void DocumentTimeline::setZeroTime(double zeroTime)
+{
+    ASSERT(isNull(m_zeroTime));
+    m_zeroTime = zeroTime;
+    ASSERT(!isNull(m_zeroTime));
+}
+
+void DocumentTimeline::DocumentTimelineTiming::wakeAfter(double duration)
+{
+    m_timer.startOneShot(duration);
+}
+
+void DocumentTimeline::DocumentTimelineTiming::cancelWake()
+{
+    m_timer.stop();
+}
+
+void DocumentTimeline::DocumentTimelineTiming::serviceOnNextFrame()
+{
+    if (m_timeline->m_document->view())
+        m_timeline->m_document->view()->scheduleAnimation();
 }
 
 double DocumentTimeline::currentTime()
 {
-    return m_document->animationClock().currentTime() - m_zeroTimeAsPerfTime;
+    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]->setPaused(true);
+        m_players[i]->pauseForTesting();
         m_players[i]->setCurrentTime(pauseTime);
     }
 }
@@ -113,7 +153,7 @@
 {
     // Includes all players whose directly associated timed items
     // are current or in effect.
-    return isNull(m_zeroTimeAsPerfTime) ? 0 : m_players.size();
+    return isNull(m_zeroTime) ? 0 : m_players.size();
 }
 
 } // namespace
diff --git a/Source/core/animation/DocumentTimeline.h b/Source/core/animation/DocumentTimeline.h
index 1cddc56..21bfc6f 100644
--- a/Source/core/animation/DocumentTimeline.h
+++ b/Source/core/animation/DocumentTimeline.h
@@ -31,10 +31,11 @@
 #ifndef DocumentTimeline_h
 #define DocumentTimeline_h
 
-#include "core/animation/ActiveAnimations.h"
+#include "core/animation/AnimationEffect.h"
 #include "core/animation/Player.h"
 #include "core/dom/Element.h"
 #include "core/events/Event.h"
+#include "platform/Timer.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
@@ -46,35 +47,45 @@
 
 // DocumentTimeline is constructed and owned by Document, and tied to its lifecycle.
 class DocumentTimeline : public RefCounted<DocumentTimeline> {
-
 public:
-    static PassRefPtr<DocumentTimeline> create(Document*);
+    class PlatformTiming {
+
+    public:
+        // Calls DocumentTimeline's wake() method after duration seconds.
+        virtual void wakeAfter(double duration) = 0;
+        virtual void cancelWake() = 0;
+        virtual void serviceOnNextFrame() = 0;
+        virtual ~PlatformTiming() { }
+
+    };
+
+    static PassRefPtr<DocumentTimeline> create(Document*, PassOwnPtr<PlatformTiming> = nullptr);
     void serviceAnimations(double);
     PassRefPtr<Player> play(TimedItem*);
-    // Called from setReadyState() in Document.cpp to set m_zeroTimeAsPerfTime to
-    // performance.timing.domInteractive.
-    void setZeroTimeAsPerfTime(double);
+    // Called from setReadyState() in Document.cpp to set m_zeroTime to
+    // performance.timing.domInteractive
+    void setZeroTime(double);
     double currentTime();
     void pauseAnimationsForTesting(double);
     size_t numberOfActiveAnimationsForTesting() const;
-    AnimationStack* animationStack(const Element* element) const
-    {
-        if (ActiveAnimations* animations = element->activeAnimations())
-            return animations->defaultStack();
-        return 0;
-    }
+
     void addEventToDispatch(EventTarget* target, PassRefPtr<Event> event)
     {
         m_events.append(EventToDispatch(target, event));
     }
 
-private:
-    DocumentTimeline(Document*);
     void dispatchEvents();
-    double m_zeroTimeAsPerfTime;
+
+protected:
+    DocumentTimeline(Document*, PassOwnPtr<PlatformTiming>);
+
+private:
+    double m_zeroTime;
     Document* m_document;
     Vector<RefPtr<Player> > m_players;
 
+    void wake();
+
     struct EventToDispatch {
         EventToDispatch(EventTarget* target, PassRefPtr<Event> event)
             : target(target)
@@ -85,6 +96,33 @@
         RefPtr<Event> event;
     };
     Vector<EventToDispatch> m_events;
+
+    static const double s_minimumDelay;
+
+    OwnPtr<PlatformTiming> m_timing;
+
+    class DocumentTimelineTiming : public PlatformTiming {
+    public:
+        DocumentTimelineTiming(DocumentTimeline* documentTimeline)
+            : m_timeline(documentTimeline)
+            , m_timer(this, &DocumentTimelineTiming::timerFired)
+        {
+            ASSERT(m_timeline);
+        }
+
+        virtual void wakeAfter(double duration) OVERRIDE;
+        virtual void cancelWake() OVERRIDE;
+        virtual void serviceOnNextFrame() OVERRIDE;
+
+        void timerFired(Timer<DocumentTimelineTiming>*) { m_timeline->wake(); }
+
+    private:
+        DocumentTimeline* m_timeline;
+        Timer<DocumentTimelineTiming> m_timer;
+
+    };
+
+    friend class CoreAnimationDocumentTimelineTest;
 };
 
 } // namespace
diff --git a/Source/core/animation/DocumentTimelineTest.cpp b/Source/core/animation/DocumentTimelineTest.cpp
index eb40e00..1b5f8f7 100644
--- a/Source/core/animation/DocumentTimelineTest.cpp
+++ b/Source/core/animation/DocumentTimelineTest.cpp
@@ -39,28 +39,82 @@
 #include "core/dom/Element.h"
 #include "core/dom/QualifiedName.h"
 #include "weborigin/KURL.h"
+
+#include <gmock/gmock.h>
 #include <gtest/gtest.h>
 
-using namespace WebCore;
+namespace WebCore {
 
-namespace {
+class MockPlatformTiming : public DocumentTimeline::PlatformTiming {
+public:
+
+    MOCK_METHOD1(wakeAfter, void(double));
+    MOCK_METHOD0(cancelWake, void());
+    MOCK_METHOD0(serviceOnNextFrame, void());
+
+    /**
+     * DocumentTimelines should do one of the following things after servicing animations:
+     *  - cancel the timer and not request to be woken again (expectNoMoreActions)
+     *  - cancel the timer and request to be woken on the next frame (expectNextFrameAction)
+     *  - cancel the timer and request to be woken at some point in the future (expectDelayedAction)
+     */
+
+    void expectNoMoreActions()
+    {
+        EXPECT_CALL(*this, cancelWake());
+    }
+
+    void expectNextFrameAction()
+    {
+        ::testing::Sequence sequence;
+        EXPECT_CALL(*this, cancelWake()).InSequence(sequence);
+        EXPECT_CALL(*this, serviceOnNextFrame()).InSequence(sequence);
+    }
+
+    void expectDelayedAction(double when)
+    {
+        ::testing::Sequence sequence;
+        EXPECT_CALL(*this, cancelWake()).InSequence(sequence);
+        EXPECT_CALL(*this, wakeAfter(when)).InSequence(sequence);
+    }
+};
 
 class CoreAnimationDocumentTimelineTest : public ::testing::Test {
 protected:
     virtual void SetUp()
     {
         document = Document::create();
+        document->animationClock().resetTimeForTesting();
         element = Element::create(nullQName() , document.get());
-        timeline = DocumentTimeline::create(document.get());
-        timeline->setZeroTimeAsPerfTime(0);
-        document->animationClock().updateTime(0);
+        platformTiming = new MockPlatformTiming;
+        timeline = DocumentTimeline::create(document.get(), adoptPtr(platformTiming));
+        timeline->setZeroTime(0);
         ASSERT_EQ(0, timeline->currentTime());
     }
 
+    virtual void TearDown()
+    {
+        timeline.release();
+        document.release();
+        element.release();
+    }
+
     RefPtr<Document> document;
     RefPtr<Element> element;
     RefPtr<DocumentTimeline> timeline;
     Timing timing;
+    MockPlatformTiming* platformTiming;
+
+    void wake()
+    {
+        timeline->wake();
+    }
+
+    double minimumDelay()
+    {
+        return DocumentTimeline::s_minimumDelay;
+    }
+
 };
 
 TEST_F(CoreAnimationDocumentTimelineTest, EmptyKeyframeAnimation)
@@ -70,10 +124,12 @@
 
     timeline->play(anim.get());
 
+    platformTiming->expectNoMoreActions();
     timeline->serviceAnimations(0);
     EXPECT_FLOAT_EQ(0, timeline->currentTime());
     EXPECT_TRUE(anim->compositableValues()->isEmpty());
 
+    platformTiming->expectNoMoreActions();
     timeline->serviceAnimations(100);
     EXPECT_FLOAT_EQ(100, timeline->currentTime());
 }
@@ -88,7 +144,7 @@
     timeline->serviceAnimations(200);
     EXPECT_TRUE(isNull(timeline->currentTime()));
 
-    timeline->setZeroTimeAsPerfTime(300);
+    timeline->setZeroTime(300);
     document->animationClock().updateTime(300);
     timeline->serviceAnimations(300);
     EXPECT_EQ(0, timeline->currentTime());
@@ -143,14 +199,43 @@
     RefPtr<Player> player3 = timeline->play(anim3.get());
     RefPtr<Player> player4 = timeline->play(anim4.get());
 
+    platformTiming->expectNextFrameAction();
     timeline->serviceAnimations(0);
     EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
+    platformTiming->expectNextFrameAction();
     timeline->serviceAnimations(0.5);
     EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
+    platformTiming->expectNextFrameAction();
     timeline->serviceAnimations(1.5);
     EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
+    platformTiming->expectNoMoreActions();
     timeline->serviceAnimations(3);
     EXPECT_EQ(1U, timeline->numberOfActiveAnimationsForTesting());
 }
 
+TEST_F(CoreAnimationDocumentTimelineTest, DelayBeforeAnimationStart)
+{
+
+    timing.hasIterationDuration = true;
+    timing.iterationDuration = 2;
+    timing.startDelay = 5;
+
+    RefPtr<Animation> anim = Animation::create(element.get(), 0, timing);
+
+    RefPtr<Player> player = timeline->play(anim.get());
+
+    // TODO: Put the player startTime in the future when we add the capability to change player startTime
+    platformTiming->expectDelayedAction(timing.startDelay - minimumDelay());
+    timeline->serviceAnimations(0);
+
+    platformTiming->expectDelayedAction(timing.startDelay - minimumDelay() - 1.5);
+    timeline->serviceAnimations(1.5);
+
+    EXPECT_CALL(*platformTiming, serviceOnNextFrame());
+    wake();
+
+    platformTiming->expectNextFrameAction();
+    timeline->serviceAnimations(4.98);
+}
+
 }
diff --git a/Source/core/animation/InertAnimation.cpp b/Source/core/animation/InertAnimation.cpp
index 9bfc829..ef613d3 100644
--- a/Source/core/animation/InertAnimation.cpp
+++ b/Source/core/animation/InertAnimation.cpp
@@ -33,14 +33,15 @@
 
 namespace WebCore {
 
-PassRefPtr<InertAnimation> InertAnimation::create(PassRefPtr<AnimationEffect> effect, const Timing& timing)
+PassRefPtr<InertAnimation> InertAnimation::create(PassRefPtr<AnimationEffect> effect, const Timing& timing, bool paused)
 {
-    return adoptRef(new InertAnimation(effect, timing));
+    return adoptRef(new InertAnimation(effect, timing, paused));
 }
 
-InertAnimation::InertAnimation(PassRefPtr<AnimationEffect> effect, const Timing& timing)
+InertAnimation::InertAnimation(PassRefPtr<AnimationEffect> effect, const Timing& timing, bool paused)
     : TimedItem(timing)
     , m_effect(effect)
+    , m_paused(paused)
 {
 }
 
diff --git a/Source/core/animation/InertAnimation.h b/Source/core/animation/InertAnimation.h
index a5154fd..b4f31e4 100644
--- a/Source/core/animation/InertAnimation.h
+++ b/Source/core/animation/InertAnimation.h
@@ -40,9 +40,10 @@
 class InertAnimation FINAL : public TimedItem {
 
 public:
-    static PassRefPtr<InertAnimation> create(PassRefPtr<AnimationEffect>, const Timing&);
+    static PassRefPtr<InertAnimation> create(PassRefPtr<AnimationEffect>, const Timing&, bool paused);
     PassOwnPtr<AnimationEffect::CompositableValueMap> sample();
     AnimationEffect* effect() const { return m_effect.get(); }
+    bool paused() const { return m_paused; }
 
 protected:
     virtual void updateChildrenAndEffects() const OVERRIDE { };
@@ -50,8 +51,9 @@
     virtual double calculateTimeToEffectChange(double inheritedTime, double activeTime, Phase) const OVERRIDE FINAL;
 
 private:
-    InertAnimation(PassRefPtr<AnimationEffect>, const Timing&);
+    InertAnimation(PassRefPtr<AnimationEffect>, const Timing&, bool paused);
     RefPtr<AnimationEffect> m_effect;
+    bool m_paused;
 };
 
 } // namespace WebCore
diff --git a/Source/core/animation/KeyframeAnimationEffect.cpp b/Source/core/animation/KeyframeAnimationEffect.cpp
index 9131077..240cbf4 100644
--- a/Source/core/animation/KeyframeAnimationEffect.cpp
+++ b/Source/core/animation/KeyframeAnimationEffect.cpp
@@ -265,7 +265,7 @@
     for (int i = m_keyframes.size() - 1; i >= 0; --i) {
         double offset = m_keyframes[i]->offset();
         bool hasSameOffsetAsPreviousNeighbor = !i || m_keyframes[i - 1]->offset() == offset;
-        bool hasSameOffsetAsNextNeighbor = i == m_keyframes.size() - 1 || m_keyframes[i + 1]->offset() == offset;
+        bool hasSameOffsetAsNextNeighbor = i == static_cast<int>(m_keyframes.size() - 1) || m_keyframes[i + 1]->offset() == offset;
         if (hasSameOffsetAsPreviousNeighbor && hasSameOffsetAsNextNeighbor)
             m_keyframes.remove(i);
     }
diff --git a/Source/core/animation/Player.cpp b/Source/core/animation/Player.cpp
index 9e62536..c3f1449 100644
--- a/Source/core/animation/Player.cpp
+++ b/Source/core/animation/Player.cpp
@@ -37,19 +37,25 @@
 
 namespace WebCore {
 
-PassRefPtr<Player> Player::create(DocumentTimeline* timeline, TimedItem* content)
+namespace {
+
+double effectiveTime(double time) { return isNull(time) ? 0 : time; }
+
+} // namespace
+
+PassRefPtr<Player> Player::create(DocumentTimeline& timeline, TimedItem* content)
 {
-    ASSERT(timeline);
     return adoptRef(new Player(timeline, content));
 }
 
-Player::Player(DocumentTimeline* timeline, TimedItem* content)
+Player::Player(DocumentTimeline& timeline, TimedItem* content)
     : m_pauseStartTime(nullValue())
     , m_playbackRate(1)
     , m_timeDrift(0)
-    , m_startTime(effectiveTime(timeline->currentTime()))
+    , m_startTime(effectiveTime(timeline.currentTime()))
     , m_content(content)
     , m_timeline(timeline)
+    , m_isPausedForTesting(false)
 {
     ASSERT(m_startTime >= 0);
     if (m_content)
@@ -65,18 +71,18 @@
 
 double Player::currentTimeBeforeDrift() const
 {
-    return (effectiveTime(m_timeline->currentTime()) - m_startTime) * m_playbackRate;
+    return (effectiveTime(m_timeline.currentTime()) - m_startTime) * m_playbackRate;
 }
 
 double Player::pausedTimeDrift() const
 {
-    ASSERT(paused());
+    ASSERT(pausedInternal());
     return currentTimeBeforeDrift() - m_pauseStartTime;
 }
 
 double Player::timeDrift() const
 {
-    return paused() ? pausedTimeDrift() : m_timeDrift;
+    return pausedInternal() ? pausedTimeDrift() : m_timeDrift;
 }
 
 double Player::currentTime() const
@@ -92,7 +98,7 @@
         return false;
     }
 
-    double newTime = isNull(m_timeline->currentTime()) ? nullValue() : currentTime();
+    double newTime = isNull(m_timeline.currentTime()) ? nullValue() : currentTime();
     m_content->updateInheritedTime(newTime);
     if (timeToEffectChange)
         *timeToEffectChange = m_content->timeToEffectChange();
@@ -111,7 +117,7 @@
 
 void Player::setCurrentTime(double seekTime)
 {
-    if (paused())
+    if (pausedInternal())
         m_pauseStartTime = seekTime;
     else
         m_timeDrift = currentTimeBeforeDrift() - seekTime;
@@ -119,9 +125,22 @@
     update();
 }
 
+void Player::pauseForTesting()
+{
+    ASSERT(!paused());
+    m_isPausedForTesting = true;
+    setPausedImpl(true);
+}
+
 void Player::setPaused(bool newValue)
 {
-    if (paused() == newValue)
+    ASSERT(!m_isPausedForTesting);
+    setPausedImpl(newValue);
+}
+
+void Player::setPausedImpl(bool newValue)
+{
+    if (pausedInternal() == newValue)
         return;
 
     if (newValue)
diff --git a/Source/core/animation/Player.h b/Source/core/animation/Player.h
index 5f975b4..0efa5e5 100644
--- a/Source/core/animation/Player.h
+++ b/Source/core/animation/Player.h
@@ -42,7 +42,7 @@
 
 public:
     ~Player();
-    static PassRefPtr<Player> create(DocumentTimeline*, TimedItem*);
+    static PassRefPtr<Player> create(DocumentTimeline&, TimedItem*);
 
     // Returns whether this player is still current or in effect.
     // timeToEffectChange returns:
@@ -54,28 +54,36 @@
     void cancel();
     double currentTime() const;
     void setCurrentTime(double);
-    bool paused() const { return !isNull(m_pauseStartTime); }
+    bool paused() const { return !m_isPausedForTesting && pausedInternal(); }
     void setPaused(bool);
     double playbackRate() const { return m_playbackRate; }
     void setPlaybackRate(double);
     double startTime() const { return m_startTime; }
     double timeDrift() const;
-    DocumentTimeline* timeline() { return m_timeline; }
+    DocumentTimeline& timeline() { return m_timeline; }
     TimedItem* source() { return m_content.get(); }
 
+    // Pausing via this method is not reflected in the value returned by
+    // paused() and must never overlap with pausing via setPaused().
+    void pauseForTesting();
+    // Reflects all pausing, including via pauseForTesting().
+    bool pausedInternal() const { return !isNull(m_pauseStartTime); }
+
 private:
-    Player(DocumentTimeline*, TimedItem*);
-    static double effectiveTime(double time) { return isNull(time) ? 0 : time; }
+    Player(DocumentTimeline&, TimedItem*);
     inline double pausedTimeDrift() const;
     inline double currentTimeBeforeDrift() const;
 
+    void setPausedImpl(bool);
+
     double m_pauseStartTime;
     double m_playbackRate;
     double m_timeDrift;
     const double m_startTime;
 
     RefPtr<TimedItem> m_content;
-    DocumentTimeline* const m_timeline;
+    DocumentTimeline& m_timeline;
+    bool m_isPausedForTesting;
 };
 
 } // namespace
diff --git a/Source/core/animation/PlayerTest.cpp b/Source/core/animation/PlayerTest.cpp
index 3aef0eb..5296d2f 100644
--- a/Source/core/animation/PlayerTest.cpp
+++ b/Source/core/animation/PlayerTest.cpp
@@ -48,10 +48,10 @@
     virtual void SetUp()
     {
         document = Document::create();
+        document->animationClock().resetTimeForTesting();
         timeline = DocumentTimeline::create(document.get());
-        document->animationClock().updateTime(0);
-        player = Player::create(timeline.get(), 0);
-        timeline->setZeroTimeAsPerfTime(0);
+        player = Player::create(*timeline, 0);
+        timeline->setZeroTime(0);
     }
 
     bool updateTimeline(double time, double* timeToEffectChange = 0)
@@ -80,7 +80,7 @@
 {
     updateTimeline(1234);
     EXPECT_EQ(1234, timeline->currentTime());
-    RefPtr<Player> player = Player::create(timeline.get(), 0);
+    RefPtr<Player> player = Player::create(*timeline, 0);
     EXPECT_EQ(1234, player->startTime());
     EXPECT_EQ(0, player->currentTime());
 }
@@ -279,7 +279,7 @@
     timing.iterationDuration = 1;
     timing.hasIterationDuration = true;
     RefPtr<Animation> animation = Animation::create(0, 0, timing);
-    player = Player::create(timeline.get(), animation.get());
+    player = Player::create(*timeline, animation.get());
 
     double timeToNextEffect;
     updateTimeline(0, &timeToNextEffect);
diff --git a/Source/core/animation/ThreadedAnimation.h b/Source/core/animation/ThreadedAnimation.h
deleted file mode 100644
index 877fc71..0000000
--- a/Source/core/animation/ThreadedAnimation.h
+++ /dev/null
@@ -1,71 +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 ThreadedAnimation_h
-#define ThreadedAnimation_h
-
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class Element;
-class Timing;
-class AnimationEffect;
-
-class ThreadedAnimation FINAL {
-
-public:
-    // Note that the implementation of these functions is indirected for mocking during unit testing.
-    static void isCandidateForThreadedAnimation(const Timing* timing, const AnimationEffect* effect) { (*s_isCandidateForThreadedAnimationFunction)(timing, effect); }
-    static void canStartThreadedAnimation(const Element* element) { (*s_canStartThreadedAnimationFunction)(element); }
-    static void startThreadedAnimation(const Element* element, const Timing* timing, const AnimationEffect* effect, Vector<int>& threadedAnimationIds) { (*s_startThreadedAnimationFunction)(element, timing, effect, threadedAnimationIds); }
-    static void cancelThreadedAnimation(const Element* element, int id) { (*s_cancelThreadedAnimationFunction)(element, id); }
-
-private:
-    ThreadedAnimation() { }
-    static void isCandidateForThreadedAnimationImpl(const Timing*, const AnimationEffect*);
-    static void canStartThreadedAnimationImpl(const Element*);
-    static void startThreadedAnimationImpl(const Element*, const Timing*, const AnimationEffect*, Vector<int>& threadedAnimationIds);
-    static void cancelThreadedAnimationImpl(const Element*, int threadedAnimationId);
-
-    typedef void (*IsCandidateForThreadedAnimationFunction)(const Timing*, const AnimationEffect*);
-    typedef void (*CanStartThreadedAnimationFunction)(const Element*);
-    typedef void (*StartThreadedAnimationFunction)(const Element*, const Timing*, const AnimationEffect*, Vector<int>&);
-    typedef void (*CancelThreadedAnimationFunction)(const Element*, int);
-
-    static IsCandidateForThreadedAnimationFunction s_isCandidateForThreadedAnimationFunction;
-    static CanStartThreadedAnimationFunction s_canStartThreadedAnimationFunction;
-    static StartThreadedAnimationFunction s_startThreadedAnimationFunction;
-    static CancelThreadedAnimationFunction s_cancelThreadedAnimationFunction;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/animation/TimedItem.cpp b/Source/core/animation/TimedItem.cpp
index 3bca022..4be5749 100644
--- a/Source/core/animation/TimedItem.cpp
+++ b/Source/core/animation/TimedItem.cpp
@@ -36,11 +36,11 @@
 
 TimedItem::TimedItem(const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
     : m_parent(0)
-    , m_player(0)
     , m_startTime(0)
+    , m_player(0)
     , m_specified(timing)
-    , m_calculated()
     , m_eventDelegate(eventDelegate)
+    , m_calculated()
     , m_isFirstSample(true)
 {
     timing.assertValid();
diff --git a/Source/core/animation/TimedItem.h b/Source/core/animation/TimedItem.h
index 614e3b0..eac8859 100644
--- a/Source/core/animation/TimedItem.h
+++ b/Source/core/animation/TimedItem.h
@@ -82,6 +82,7 @@
     double activeDuration() const { return ensureCalculated().activeDuration; }
     double timeFraction() const { return ensureCalculated().timeFraction; }
     const Player* player() const { return m_player; }
+    Player* player() { return m_player; }
 
     const Timing& specified() const { return m_specified; }
 
diff --git a/Source/core/animation/css/CSSAnimatableValueFactory.cpp b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
index 4c26bd2..1453631 100644
--- a/Source/core/animation/css/CSSAnimatableValueFactory.cpp
+++ b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
@@ -35,6 +35,7 @@
 #include "core/animation/AnimatableClipPathOperation.h"
 #include "core/animation/AnimatableColor.h"
 #include "core/animation/AnimatableDouble.h"
+#include "core/animation/AnimatableFilterOperations.h"
 #include "core/animation/AnimatableImage.h"
 #include "core/animation/AnimatableLength.h"
 #include "core/animation/AnimatableLengthBox.h"
@@ -44,6 +45,7 @@
 #include "core/animation/AnimatableRepeatable.h"
 #include "core/animation/AnimatableSVGLength.h"
 #include "core/animation/AnimatableSVGPaint.h"
+#include "core/animation/AnimatableShadow.h"
 #include "core/animation/AnimatableShapeValue.h"
 #include "core/animation/AnimatableStrokeDasharrayList.h"
 #include "core/animation/AnimatableTransform.h"
@@ -130,6 +132,13 @@
         createFromLength(lengthSize.height(), style));
 }
 
+inline static PassRefPtr<AnimatableValue> createFromStyleImage(StyleImage* image)
+{
+    if (image)
+        return AnimatableImage::create(image);
+    return AnimatableUnknown::create(CSSValueNone);
+}
+
 inline static PassRefPtr<AnimatableValue> createFromFillSize(const FillSize& fillSize, const RenderStyle* style)
 {
     switch (fillSize.type) {
@@ -154,11 +163,7 @@
         if (property == CSSPropertyBackgroundImage || property == CSSPropertyWebkitMaskImage) {
             if (!fillLayer->isImageSet())
                 break;
-            StyleImage* image = fillLayer->image();
-            if (image)
-                values.append(AnimatableImage::create(image));
-            else
-                values.append(AnimatableUnknown::create(CSSValueNone));
+            values.append(createFromStyleImage(fillLayer->image()));
         } else if (property == CSSPropertyBackgroundPositionX || property == CSSPropertyWebkitMaskPositionX) {
             if (!fillLayer->isXPositionSet())
                 break;
@@ -228,7 +233,7 @@
     case CSSPropertyBorderImageSlice:
         return createFromLengthBox(style->borderImageSlices(), style);
     case CSSPropertyBorderImageSource:
-        return AnimatableImage::create(style->borderImageSource());
+        return createFromStyleImage(style->borderImageSource());
     case CSSPropertyBorderImageWidth:
         return createFromLengthBox(style->borderImageWidth(), style);
     case CSSPropertyBorderLeftColor:
@@ -249,6 +254,9 @@
         return createFromDouble(style->borderTopWidth());
     case CSSPropertyBottom:
         return createFromLength(style->bottom(), style);
+    case CSSPropertyBoxShadow:
+    case CSSPropertyWebkitBoxShadow:
+        return AnimatableShadow::create(style->boxShadow());
     case CSSPropertyClip:
         if (style->hasClip())
             return createFromLengthBox(style->clip(), style);
@@ -282,7 +290,7 @@
     case CSSPropertyLightingColor:
         return createFromColor(property, style);
     case CSSPropertyListStyleImage:
-        return AnimatableImage::create(style->listStyleImage());
+        return createFromStyleImage(style->listStyleImage());
     case CSSPropertyLeft:
         return createFromLength(style->left(), style);
     case CSSPropertyLetterSpacing:
@@ -345,6 +353,8 @@
         return createFromColor(property, style);
     case CSSPropertyTextIndent:
         return createFromLength(style->textIndent(), style);
+    case CSSPropertyTextShadow:
+        return AnimatableShadow::create(style->textShadow());
     case CSSPropertyTop:
         return createFromLength(style->top(), style);
     case CSSPropertyWebkitBorderHorizontalSpacing:
@@ -363,12 +373,14 @@
         return createFromDouble(style->columnRuleWidth());
     case CSSPropertyWebkitColumnWidth:
         return createFromDouble(style->columnWidth());
+    case CSSPropertyWebkitFilter:
+        return AnimatableFilterOperations::create(style->filter());
     case CSSPropertyWebkitMaskBoxImageOutset:
         return createFromLengthBox(style->maskBoxImageOutset(), style);
     case CSSPropertyWebkitMaskBoxImageSlice:
         return createFromLengthBoxAndBool(style->maskBoxImageSlices(), style->maskBoxImageSlicesFill(), style);
     case CSSPropertyWebkitMaskBoxImageSource:
-        return AnimatableImage::create(style->maskBoxImageSource());
+        return createFromStyleImage(style->maskBoxImageSource());
     case CSSPropertyWebkitMaskBoxImageWidth:
         return createFromLengthBox(style->maskBoxImageWidth(), style);
     case CSSPropertyWebkitMaskImage:
@@ -391,8 +403,6 @@
         return AnimatableShapeValue::create(style->shapeOutside());
     case CSSPropertyShapeMargin:
         return createFromLength(style->shapeMargin(), style);
-    case CSSPropertyWebkitTextEmphasisColor:
-        return createFromColor(property, style);
     case CSSPropertyWebkitTextStrokeColor:
         return createFromColor(property, style);
     case CSSPropertyWebkitTransform:
diff --git a/Source/core/animation/css/CSSAnimations.cpp b/Source/core/animation/css/CSSAnimations.cpp
index 1293893..2a3fb08 100644
--- a/Source/core/animation/css/CSSAnimations.cpp
+++ b/Source/core/animation/css/CSSAnimations.cpp
@@ -79,7 +79,7 @@
 }
 
 // Returns the default timing function.
-const PassRefPtr<TimingFunction> timingFromAnimationData(const CSSAnimationData* animationData, Timing& timing)
+const PassRefPtr<TimingFunction> timingFromAnimationData(const CSSAnimationData* animationData, Timing& timing, bool& isPaused)
 {
     if (animationData->isDelaySet())
         timing.startDelay = animationData->delay();
@@ -131,6 +131,7 @@
             ASSERT_NOT_REACHED();
         }
     }
+    isPaused = animationData->isPlayStateSet() && animationData->playState() == AnimPlayStatePaused;
     return animationData->isTimingFunctionSet() ? animationData->timingFunction() : CSSAnimationData::initialAnimationTimingFunction();
 }
 
@@ -160,6 +161,8 @@
         ASSERT(animateAll || mode == CSSAnimationData::AnimateSingleProperty);
         const StylePropertyShorthand& propertyList = animateAll ? CSSAnimations::animatableProperties() : shorthandForProperty(anim->property());
         if (!propertyList.length()) {
+            if (!CSSAnimations::isAnimatableProperty(anim->property()))
+                continue;
             listedProperties.add(anim->property());
             calculateCandidateTransitionForProperty(anim, anim->property(), oldStyle, newStyle, candidateMap);
         } else {
@@ -181,23 +184,19 @@
 {
     if (!m_target)
         return;
-    ActiveAnimations* activeAnimations = m_target->activeAnimations();
-    CSSAnimations* cssAnimations = activeAnimations ? activeAnimations->cssAnimations() : 0;
     // It's possible than an update was created outside an update scope. That's harmless
     // but we must clear it now to avoid applying it if an updated replacement is not
     // created in this scope.
-    if (cssAnimations)
-        cssAnimations->setPendingUpdate(nullptr);
+    if (ActiveAnimations* activeAnimations = m_target->activeAnimations())
+        activeAnimations->cssAnimations().setPendingUpdate(nullptr);
 }
 
 CSSAnimationUpdateScope::~CSSAnimationUpdateScope()
 {
     if (!m_target)
         return;
-    ActiveAnimations* activeAnimations = m_target->activeAnimations();
-    CSSAnimations* cssAnimations = activeAnimations ? activeAnimations->cssAnimations() : 0;
-    if (cssAnimations)
-        cssAnimations->maybeApplyPendingUpdate(m_target);
+    if (ActiveAnimations* activeAnimations = m_target->activeAnimations())
+        activeAnimations->cssAnimations().maybeApplyPendingUpdate(m_target);
 }
 
 PassOwnPtr<CSSAnimationUpdate> CSSAnimations::calculateUpdate(Element* element, const RenderStyle* style, StyleResolver* resolver)
@@ -211,9 +210,8 @@
 
 void CSSAnimations::calculateAnimationUpdate(CSSAnimationUpdate* update, Element* element, const RenderStyle* style, StyleResolver* resolver)
 {
-    ActiveAnimations* activeAnimations = element->activeAnimations();
     const CSSAnimationDataList* animationDataList = style->animations();
-    const CSSAnimations* cssAnimations = activeAnimations ? activeAnimations->cssAnimations() : 0;
+    const CSSAnimations* cssAnimations = element->activeAnimations() ? &element->activeAnimations()->cssAnimations() : 0;
 
     HashSet<AtomicString> inactive;
     if (cssAnimations)
@@ -228,17 +226,29 @@
             ASSERT(animationData->isValidAnimation());
             AtomicString animationName(animationData->name());
 
+            // Keyframes and animation properties are snapshotted when the
+            // animation starts, so we don't need to track changes to these,
+            // with the exception of play-state.
             if (cssAnimations) {
                 AnimationMap::const_iterator existing(cssAnimations->m_animations.find(animationName));
                 if (existing != cssAnimations->m_animations.end()) {
-                    // FIXME: The play-state of this animation might have changed, record the change in the update.
                     inactive.remove(animationName);
+                    const HashSet<RefPtr<Player> >& players = existing->value;
+                    ASSERT(!players.isEmpty());
+                    bool isFirstPlayerPaused = (*players.begin())->paused();
+#ifndef NDEBUG
+                    for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter)
+                        ASSERT((*iter)->paused() == isFirstPlayerPaused);
+#endif
+                    if ((animationData->playState() == AnimPlayStatePaused) != isFirstPlayerPaused)
+                        update->toggleAnimationPaused(animationName);
                     continue;
                 }
             }
 
             Timing timing;
-            RefPtr<TimingFunction> defaultTimingFunction = timingFromAnimationData(animationData, timing);
+            bool isPaused;
+            RefPtr<TimingFunction> defaultTimingFunction = timingFromAnimationData(animationData, timing, isPaused);
             Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > > keyframesAndTimingFunctions;
             resolver->resolveKeyframes(element, style, animationName, defaultTimingFunction.get(), keyframesAndTimingFunctions);
             if (!keyframesAndTimingFunctions.isEmpty()) {
@@ -247,7 +257,7 @@
                     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));
+                    animations.add(InertAnimation::create(KeyframeAnimationEffect::create(keyframesAndTimingFunctions[j].first), timing, isPaused));
                 }
                 update->startAnimation(animationName, animations);
             }
@@ -274,7 +284,16 @@
             (*iter)->cancel();
     }
 
-    // FIXME: Apply updates to play-state.
+    for (Vector<AtomicString>::const_iterator iter = update->animationsWithPauseToggled().begin(); iter != update->animationsWithPauseToggled().end(); ++iter) {
+        const HashSet<RefPtr<Player> >& players = m_animations.get(*iter);
+        ASSERT(!players.isEmpty());
+        bool isFirstPlayerPaused = (*players.begin())->paused();
+        for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter) {
+            Player* player = iter->get();
+            ASSERT(player->paused() == isFirstPlayerPaused);
+            player->setPaused(!isFirstPlayerPaused);
+        }
+    }
 
     for (Vector<CSSAnimationUpdate::NewAnimation>::const_iterator iter = update->newAnimations().begin(); iter != update->newAnimations().end(); ++iter) {
         OwnPtr<AnimationEventDelegate> eventDelegate = adoptPtr(new AnimationEventDelegate(element, iter->name));
@@ -283,15 +302,17 @@
             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(), eventDelegate.release());
-            players.add(element->document().timeline()->play(animation.get()));
+            RefPtr<Animation> animation = Animation::create(element, inertAnimation->effect(), inertAnimation->specified(), Animation::DefaultPriority, eventDelegate.release());
+            RefPtr<Player> player = element->document().timeline()->play(animation.get());
+            player->setPaused(inertAnimation->paused());
+            players.add(player.release());
         }
         m_animations.set(iter->name, players);
     }
 
     for (HashSet<CSSPropertyID>::iterator iter = update->cancelledTransitions().begin(); iter != update->cancelledTransitions().end(); ++iter) {
         ASSERT(m_transitions.contains(*iter));
-        m_transitions.take(*iter).player->cancel();
+        m_transitions.take(*iter).transition->player()->cancel();
     }
 
     for (size_t i = 0; i < update->newTransitions().size(); ++i) {
@@ -304,9 +325,9 @@
         CSSPropertyID id = newTransition.id;
         InertAnimation* inertAnimation = newTransition.animation.get();
         OwnPtr<TransitionEventDelegate> eventDelegate = adoptPtr(new TransitionEventDelegate(element, id));
-        RefPtr<Animation> transition = Animation::create(element, inertAnimation->effect(), inertAnimation->specified(), eventDelegate.release());
-        // FIXME: Transitions need to be added to a separate timeline.
-        runningTransition.player = element->document().timeline()->play(transition.get());
+        RefPtr<Animation> transition = Animation::create(element, inertAnimation->effect(), inertAnimation->specified(), Animation::TransitionPriority, eventDelegate.release());
+        element->document().transitionTimeline()->play(transition.get());
+        runningTransition.transition = transition.get();
         m_transitions.set(id, runningTransition);
     }
 }
@@ -341,19 +362,20 @@
     RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
 
     Timing timing;
-    RefPtr<TimingFunction> timingFunction = timingFromAnimationData(newTransition.anim, timing);
+    bool isPaused;
+    RefPtr<TimingFunction> timingFunction = timingFromAnimationData(newTransition.anim, timing, isPaused);
+    ASSERT(!isPaused);
     timing.timingFunction = timingFunction;
     // Note that the backwards part is required for delay to work.
     timing.fillMode = Timing::FillModeBoth;
 
-    update->startTransition(id, newTransition.from.get(), newTransition.to.get(), InertAnimation::create(effect, timing));
+    update->startTransition(id, newTransition.from.get(), newTransition.to.get(), InertAnimation::create(effect, timing, isPaused));
 }
 
 void CSSAnimations::calculateTransitionUpdate(CSSAnimationUpdate* update, const Element* element, const RenderStyle* style)
 {
     ActiveAnimations* activeAnimations = element->activeAnimations();
-    const CSSAnimations* cssAnimations = activeAnimations ? activeAnimations->cssAnimations() : 0;
-    const TransitionMap* transitions = cssAnimations ? &cssAnimations->m_transitions : 0;
+    const TransitionMap* transitions = activeAnimations ? &activeAnimations->cssAnimations().m_transitions : 0;
 
     HashSet<CSSPropertyID> listedProperties;
     if (style->display() != NONE && element->renderer() && element->renderer()->style()) {
@@ -365,7 +387,7 @@
 
     if (transitions) {
         for (TransitionMap::const_iterator iter = transitions->begin(); iter != transitions->end(); ++iter) {
-            const TimedItem* timedItem = iter->value.player->source();
+            const TimedItem* timedItem = iter->value.transition;
             CSSPropertyID id = iter->key;
             if (timedItem->phase() == TimedItem::PhaseAfter || !listedProperties.contains(id))
                 update->cancelTransition(id);
@@ -382,13 +404,55 @@
     }
 
     for (TransitionMap::iterator iter = m_transitions.begin(); iter != m_transitions.end(); ++iter)
-        iter->value.player->cancel();
+        iter->value.transition->player()->cancel();
 
     m_animations.clear();
     m_transitions.clear();
     m_pendingUpdate = nullptr;
 }
 
+AnimationEffect::CompositableValueMap CSSAnimations::compositableValuesForAnimations(const Element* element, const CSSAnimationUpdate* update)
+{
+    ActiveAnimations* activeAnimations = element->activeAnimations();
+    AnimationStack* animationStack = activeAnimations ? &activeAnimations->defaultStack() : 0;
+
+    if (!update)
+        return AnimationStack::compositableValues(animationStack, 0, 0, Animation::DefaultPriority);
+
+    Vector<InertAnimation*> newAnimations;
+    for (size_t i = 0; i < update->newAnimations().size(); ++i) {
+        HashSet<RefPtr<InertAnimation> > animations = update->newAnimations()[i].animations;
+        for (HashSet<RefPtr<InertAnimation> >::const_iterator animationsIter = animations.begin(); animationsIter != animations.end(); ++animationsIter)
+            newAnimations.append(animationsIter->get());
+    }
+
+    return AnimationStack::compositableValues(animationStack, &newAnimations, &update->cancelledAnimationPlayers(), Animation::DefaultPriority);
+}
+
+AnimationEffect::CompositableValueMap CSSAnimations::compositableValuesForTransitions(const Element* element, const CSSAnimationUpdate* update)
+{
+    ActiveAnimations* activeAnimations = element->activeAnimations();
+    AnimationStack* animationStack = activeAnimations ? &activeAnimations->defaultStack() : 0;
+
+    if (!update)
+        return AnimationStack::compositableValues(animationStack, 0, 0, Animation::TransitionPriority);
+
+    Vector<InertAnimation*> newTransitions;
+    for (size_t i = 0; i < update->newTransitions().size(); ++i)
+        newTransitions.append(update->newTransitions()[i].animation.get());
+
+    HashSet<const Player*> cancelledPlayers;
+    if (!update->cancelledTransitions().isEmpty()) {
+        const TransitionMap& transitionMap = activeAnimations->cssAnimations().m_transitions;
+        for (HashSet<CSSPropertyID>::iterator iter = update->cancelledTransitions().begin(); iter != update->cancelledTransitions().end(); ++iter) {
+            ASSERT(transitionMap.contains(*iter));
+            cancelledPlayers.add(transitionMap.get(*iter).transition->player());
+        }
+    }
+
+    return AnimationStack::compositableValues(animationStack, &newTransitions, &cancelledPlayers, Animation::TransitionPriority);
+}
+
 void CSSAnimations::AnimationEventDelegate::maybeDispatch(Document::ListenerType listenerType, const AtomicString& eventName, double elapsedTime)
 {
     if (m_target->document().hasListenerType(listenerType))
@@ -441,7 +505,7 @@
         double elapsedTime = timing.iterationDuration;
         const AtomicString& eventType = EventTypeNames::transitionend;
         String pseudoElement = PseudoElement::pseudoElementNameForEvents(m_target->pseudoId());
-        m_target->document().timeline()->addEventToDispatch(m_target, TransitionEvent::create(eventType, propertyName, elapsedTime, pseudoElement));
+        m_target->document().transitionTimeline()->addEventToDispatch(m_target, TransitionEvent::create(eventType, propertyName, elapsedTime, pseudoElement));
     }
 }
 
@@ -477,10 +541,6 @@
     case CSSPropertyColor:
     case CSSPropertyFill:
     case CSSPropertyFillOpacity:
-    // FIXME: Shorthands should not be present in this list, but
-    // CSSPropertyAnimation implements animation of flex directly and
-    // makes use of this method.
-    case CSSPropertyFlex:
     case CSSPropertyFlexBasis:
     case CSSPropertyFlexGrow:
     case CSSPropertyFlexShrink:
@@ -521,6 +581,7 @@
     case CSSPropertyStrokeMiterlimit:
     case CSSPropertyStrokeOpacity:
     case CSSPropertyStrokeWidth:
+    case CSSPropertyTextDecorationColor:
     case CSSPropertyTextIndent:
     case CSSPropertyTextShadow:
     case CSSPropertyTop:
@@ -536,10 +597,6 @@
     case CSSPropertyWebkitColumnRuleWidth:
     case CSSPropertyWebkitColumnWidth:
     case CSSPropertyWebkitFilter:
-    // FIXME: Shorthands should not be present in this list, but
-    // CSSPropertyAnimation implements animation of -webkit-mask-box-image
-    // directly and makes use of this method.
-    case CSSPropertyWebkitMaskBoxImage:
     case CSSPropertyWebkitMaskBoxImageOutset:
     case CSSPropertyWebkitMaskBoxImageSlice:
     case CSSPropertyWebkitMaskBoxImageSource:
@@ -565,6 +622,12 @@
     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:
+    case CSSPropertyWebkitMaskBoxImage:
+        return !RuntimeEnabledFeatures::webAnimationsCSSEnabled();
     default:
         return false;
     }
@@ -577,10 +640,6 @@
     if (properties.isEmpty()) {
         for (int i = firstCSSProperty; i < lastCSSProperty; ++i) {
             CSSPropertyID id = convertToCSSPropertyID(i);
-            // FIXME: This is the only shorthand marked as animatable,
-            // it'll be removed from the list once we switch to the new implementation.
-            if (id == CSSPropertyFlex)
-                continue;
             if (isAnimatableProperty(id))
                 properties.append(id);
         }
diff --git a/Source/core/animation/css/CSSAnimations.h b/Source/core/animation/css/CSSAnimations.h
index 0853351..b32cb37 100644
--- a/Source/core/animation/css/CSSAnimations.h
+++ b/Source/core/animation/css/CSSAnimations.h
@@ -44,7 +44,7 @@
 
 namespace WebCore {
 
-class CandidateTransition;
+struct CandidateTransition;
 class Element;
 class StylePropertyShorthand;
 class StyleResolver;
@@ -75,6 +75,10 @@
         for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter)
             m_cancelledAnimationPlayers.add(iter->get());
     }
+    void toggleAnimationPaused(const AtomicString& name)
+    {
+        m_animationsWithPauseToggled.append(name);
+    }
 
     void startTransition(CSSPropertyID id, const AnimatableValue* from, const AnimatableValue* to, PassRefPtr<InertAnimation> animation)
     {
@@ -85,6 +89,7 @@
         newTransition.animation = animation;
         m_newTransitions.append(newTransition);
     }
+    bool isCancelledTransition(CSSPropertyID id) const { return m_cancelledTransitions.contains(id); }
     void cancelTransition(CSSPropertyID id) { m_cancelledTransitions.add(id); }
 
     struct NewAnimation {
@@ -93,6 +98,8 @@
     };
     const Vector<NewAnimation>& newAnimations() const { return m_newAnimations; }
     const Vector<AtomicString>& cancelledAnimationNames() const { return m_cancelledAnimationNames; }
+    const HashSet<const Player*>& cancelledAnimationPlayers() const { return m_cancelledAnimationPlayers; }
+    const Vector<AtomicString>& animationsWithPauseToggled() const { return m_animationsWithPauseToggled; }
 
     struct NewTransition {
         CSSPropertyID id;
@@ -108,6 +115,7 @@
         return m_newAnimations.isEmpty()
             && m_cancelledAnimationNames.isEmpty()
             && m_cancelledAnimationPlayers.isEmpty()
+            && m_animationsWithPauseToggled.isEmpty()
             && m_newTransitions.isEmpty()
             && m_cancelledTransitions.isEmpty();
     }
@@ -119,6 +127,7 @@
     Vector<NewAnimation> m_newAnimations;
     Vector<AtomicString> m_cancelledAnimationNames;
     HashSet<const Player*> m_cancelledAnimationPlayers;
+    Vector<AtomicString> m_animationsWithPauseToggled;
 
     Vector<NewTransition> m_newTransitions;
     HashSet<CSSPropertyID> m_cancelledTransitions;
@@ -136,6 +145,9 @@
     void maybeApplyPendingUpdate(Element*);
     bool isEmpty() const { return m_animations.isEmpty() && m_transitions.isEmpty() && !m_pendingUpdate; }
     void cancel();
+
+    static AnimationEffect::CompositableValueMap compositableValuesForAnimations(const Element*, const CSSAnimationUpdate*);
+    static AnimationEffect::CompositableValueMap compositableValuesForTransitions(const Element*, const CSSAnimationUpdate*);
 private:
     // Note that a single animation name may map to multiple players due to
     // the way in which we split up animations with incomplete keyframes.
@@ -143,7 +155,7 @@
     // ParGroup to drive multiple animations from a single Player.
     typedef HashMap<AtomicString, HashSet<RefPtr<Player> > > AnimationMap;
     struct RunningTransition {
-        RefPtr<Player> player;
+        Animation* transition; // The TransitionTimeline keeps the Players alive
         const AnimatableValue* from;
         const AnimatableValue* to;
     };
diff --git a/Source/core/page/RuntimeEnabledFeaturesCustom.cpp b/Source/core/animation/css/TransitionTimeline.cpp
similarity index 72%
copy from Source/core/page/RuntimeEnabledFeaturesCustom.cpp
copy to Source/core/animation/css/TransitionTimeline.cpp
index 2ac204d..33ec27f 100644
--- a/Source/core/page/RuntimeEnabledFeaturesCustom.cpp
+++ b/Source/core/animation/css/TransitionTimeline.cpp
@@ -29,15 +29,24 @@
  */
 
 #include "config.h"
-#include "RuntimeEnabledFeatures.h"
+#include "core/animation/css/TransitionTimeline.h"
 
-#include "core/workers/SharedWorkerRepository.h"
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/AnimationClock.h"
+#include "core/animation/AnimationStack.h"
 
 namespace WebCore {
 
-bool RuntimeEnabledFeatures::sharedWorkerEnabled()
+PassRefPtr<TransitionTimeline> TransitionTimeline::create(Document* document, PassOwnPtr<PlatformTiming> timing)
 {
-    return SharedWorkerRepository::isAvailable();
+    return adoptRef(new TransitionTimeline(document, timing));
+}
+
+TransitionTimeline::TransitionTimeline(Document* document, PassOwnPtr<PlatformTiming> timing)
+    : DocumentTimeline(document, timing)
+{
+    setZeroTime(document->animationClock().currentTime());
+    document->animationClock().unfreeze();
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/RuntimeEnabledFeaturesCustom.cpp b/Source/core/animation/css/TransitionTimeline.h
similarity index 81%
copy from Source/core/page/RuntimeEnabledFeaturesCustom.cpp
copy to Source/core/animation/css/TransitionTimeline.h
index 2ac204d..6d55f48 100644
--- a/Source/core/page/RuntimeEnabledFeaturesCustom.cpp
+++ b/Source/core/animation/css/TransitionTimeline.h
@@ -28,16 +28,21 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "RuntimeEnabledFeatures.h"
+#ifndef TransitionTimeline_h
+#define TransitionTimeline_h
 
-#include "core/workers/SharedWorkerRepository.h"
+#include "core/animation/DocumentTimeline.h"
 
 namespace WebCore {
 
-bool RuntimeEnabledFeatures::sharedWorkerEnabled()
-{
-    return SharedWorkerRepository::isAvailable();
-}
+class TransitionTimeline FINAL : public DocumentTimeline {
+public:
+    static PassRefPtr<TransitionTimeline> create(Document*, PassOwnPtr<PlatformTiming> = nullptr);
+
+private:
+    TransitionTimeline(Document*, PassOwnPtr<PlatformTiming>);
+};
 
 } // namespace WebCore
+
+#endif
diff --git a/Source/core/core.gyp b/Source/core/core.gyp
index 4ca980b..ab5f8ac 100644
--- a/Source/core/core.gyp
+++ b/Source/core/core.gyp
@@ -32,6 +32,7 @@
   'includes': [
     '../build/win/precompile.gypi',
     '../build/features.gypi',
+    '../build/scripts/scripts.gypi',
     '../modules/modules.gypi',
     '../bindings/bindings.gypi',
     'core.gypi',
@@ -218,6 +219,7 @@
         'injected_canvas_script_source',
         'injected_script_source',
         'debugger_script_source',
+        '../platform/platform_derived_sources.gyp:make_platform_derived_sources',
         '../wtf/wtf.gyp:wtf',
         '<(DEPTH)/skia/skia.gyp:skia',
         '<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg',
@@ -252,7 +254,6 @@
         '<@(bindings_files)',
 
         # Additional .cpp files for HashTools.h
-        '<(SHARED_INTERMEDIATE_DIR)/blink/ColorData.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/CSSPropertyNames.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/CSSValueKeywords.cpp',
 
@@ -286,9 +287,6 @@
         # Generated from HTMLEntityNames.in
         '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLEntityTable.cpp',
 
-        # Generated from RuntimeEnabledFeatures.in
-        '<(SHARED_INTERMEDIATE_DIR)/blink/RuntimeEnabledFeatures.cpp',
-
         # Generated from CSSParser-in.cpp
         '<(SHARED_INTERMEDIATE_DIR)/blink/CSSParser.cpp',
 
@@ -738,6 +736,7 @@
             ['exclude', 'Posix\\.cpp$'],
 
             ['include', 'platform/ScrollbarThemeWin\\.(cpp|h)$'],
+            ['include', 'platform/graphics/chromium/FontFallbackWin\\.(cpp|h)$'],
             ['include', 'platform/graphics/chromium/TransparencyWin\\.(cpp|h)$'],
             ['include', 'platform/graphics/opentype/'],
             ['include', 'platform/graphics/skia/SkiaFontWin\\.(cpp|h)$'],
@@ -758,15 +757,14 @@
             },{ # ENABLE_GDI_FONTS_ON_WINDOWS!=1
               'sources/': [
                 ['include', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
-                ['exclude', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
+                ['include', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
                 ['include', 'platform/graphics/skia/FontCacheSkiaWin\\.cpp$'],
                 ['include', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
                 ['include', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
                 ['exclude', 'platform/graphics/chromium/SimpleFontDataChromiumWin\\.cpp$'],
-                ['include', 'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin\\.cpp$'],
+                ['exclude', 'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin\\.cpp$'],
                 ['exclude', 'platform/graphics/chromium/FontCacheChromiumWin\\.cpp$'],
                 ['exclude', 'platform/graphics/win/FontCustomPlatformDataWin\\.cpp$'],
-                ['exclude', 'platform/graphics/win/FontCustomPlatformDataWin\\.cpp$'],
               ],
             }],
           ],
@@ -807,16 +805,6 @@
         }],
       ],
     },
-    {
-      'target_name': 'webcore_platform_geometry',
-      'type': 'static_library',
-      'dependencies': [
-        'webcore_prerequisites',
-      ],
-      'sources': [
-        '<@(webcore_platform_geometry_files)',
-      ],
-    },
     # The *NEON.cpp files fail to compile when -mthumb is passed. Force
     # them to build in ARM mode.
     # See https://bugs.webkit.org/show_bug.cgi?id=62916.
@@ -994,7 +982,6 @@
         'webcore_dom',
         'webcore_html',
         'webcore_platform',
-        'webcore_platform_geometry',
         'webcore_remaining',
         'webcore_rendering',
         'webcore_svg',
diff --git a/Source/core/core.gypi b/Source/core/core.gypi
index 4169d4d..b143f7d 100644
--- a/Source/core/core.gypi
+++ b/Source/core/core.gypi
@@ -27,6 +27,7 @@
             'css/CSSVariablesMapForEachCallback.idl',
             'css/CSSViewportRule.idl',
             'css/Counter.idl',
+            'css/DocumentFontFaceSet.idl',
             'css/FontFace.idl',
             'css/FontFaceSet.idl',
             'css/MediaList.idl',
@@ -140,6 +141,7 @@
             'frame/WebKitPoint.idl',
             'frame/Window.idl',
             'frame/WindowBase64.idl',
+            'frame/WindowEventHandlers.idl',
             'frame/WindowTimers.idl',
             'html/FormData.idl',
             'html/HTMLAllCollection.idl',
@@ -535,6 +537,8 @@
             'animation/AnimatableColor.h',
             'animation/AnimatableDouble.cpp',
             'animation/AnimatableDouble.h',
+            'animation/AnimatableFilterOperations.cpp',
+            'animation/AnimatableFilterOperations.h',
             'animation/AnimatableImage.cpp',
             'animation/AnimatableImage.h',
             'animation/AnimatableLength.cpp',
@@ -554,6 +558,8 @@
             'animation/AnimatableSVGLength.h',
             'animation/AnimatableSVGPaint.cpp',
             'animation/AnimatableSVGPaint.h',
+            'animation/AnimatableShadow.cpp',
+            'animation/AnimatableShadow.h',
             'animation/AnimatableShapeValue.cpp',
             'animation/AnimatableShapeValue.h',
             'animation/AnimatableStrokeDasharrayList.cpp',
@@ -569,7 +575,10 @@
             'animation/Animation.h',
             'animation/AnimationClock.h',
             'animation/AnimationEffect.h',
+            'animation/AnimationStack.cpp',
             'animation/AnimationStack.h',
+            'animation/CompositorAnimations.cpp',
+            'animation/CompositorAnimations.h',
             'animation/DocumentTimeline.cpp',
             'animation/DocumentTimeline.h',
             'animation/InertAnimation.cpp',
@@ -578,8 +587,6 @@
             'animation/KeyframeAnimationEffect.h',
             'animation/Player.cpp',
             'animation/Player.h',
-            'animation/ThreadedAnimation.cpp',
-            'animation/ThreadedAnimation.h',
             'animation/TimedItem.cpp',
             'animation/TimedItem.h',
             'animation/TimedItemCalculations.h',
@@ -588,6 +595,8 @@
             'animation/css/CSSAnimatableValueFactory.h',
             'animation/css/CSSAnimations.cpp',
             'animation/css/CSSAnimations.h',
+            'animation/css/TransitionTimeline.cpp',
+            'animation/css/TransitionTimeline.h',
             'css/BasicShapeFunctions.cpp',
             'css/CSSArrayFunctionValue.cpp',
             'css/CSSArrayFunctionValue.h',
@@ -723,6 +732,8 @@
             'css/Counter.h',
             'css/DOMWindowCSS.cpp',
             'css/DOMWindowCSS.h',
+            'css/DocumentFontFaceSet.h',
+            'css/DocumentFontFaceSet.cpp',
             'css/DocumentRuleSets.cpp',
             'css/DocumentRuleSets.h',
             'css/ElementRuleCollector.cpp',
@@ -733,6 +744,7 @@
             'css/FontFace.h',
             'css/FontSize.cpp',
             'css/FontSize.h',
+            'css/HashTools.h',
             'css/InspectorCSSOMWrappers.cpp',
             'css/InspectorCSSOMWrappers.h',
             'css/MediaFeatureNames.cpp',
@@ -818,6 +830,7 @@
             'css/resolver/StyleBuilderCustom.h',
             'css/resolver/StyleResolver.cpp',
             'css/resolver/StyleResolver.h',
+            'css/resolver/StyleResolverIncludes.h',
             'css/resolver/StyleResolverState.cpp',
             'css/resolver/StyleResolverState.h',
             'css/resolver/StyleResourceLoader.cpp',
@@ -873,6 +886,8 @@
             'editing/ModifySelectionListLevel.cpp',
             'editing/ModifySelectionListLevel.h',
             'editing/MoveSelectionCommand.cpp',
+            'editing/PlainTextRange.h',
+            'editing/PlainTextRange.cpp',
             'editing/RemoveCSSPropertyCommand.cpp',
             'editing/RemoveCSSPropertyCommand.h',
             'editing/RemoveFormatCommand.cpp',
@@ -1150,8 +1165,8 @@
             'loader/NavigationScheduler.cpp',
             'loader/PingLoader.cpp',
             'loader/PingLoader.h',
-            'loader/Prerenderer.cpp',
-            'loader/Prerenderer.h',
+            'loader/PrerenderHandle.cpp',
+            'loader/PrerenderHandle.h',
             'loader/PrerendererClient.cpp',
             'loader/PrerendererClient.h',
             'loader/ProgressTracker.cpp',
@@ -1205,6 +1220,7 @@
             'frame/DOMWindow.h',
             'frame/DOMWindowBase64.cpp',
             'frame/DOMWindowBase64.h',
+            'frame/DOMWindowEventHandlers.h',
             'frame/DOMWindowLifecycleNotifier.cpp',
             'frame/DOMWindowLifecycleNotifier.h',
             'frame/DOMWindowLifecycleObserver.cpp',
@@ -1280,7 +1296,6 @@
             'timing/ResourceTimingInfo.h',
             'page/RuntimeCSSEnabled.cpp',
             'page/RuntimeCSSEnabled.h',
-            'page/RuntimeEnabledFeaturesCustom.cpp',
             'frame/Screen.cpp',
             'frame/Screen.h',
             'page/Settings.cpp',
@@ -1431,6 +1446,8 @@
             'rendering/RenderLayerFilterInfo.h',
             'rendering/RenderLayerScrollableArea.cpp',
             'rendering/RenderLayerStackingNode.cpp',
+            'rendering/RenderLayerStackingNodeIterator.cpp',
+            'rendering/RenderLayerReflectionInfo.cpp',
             'rendering/RenderLayerRepainter.cpp',
             'rendering/RenderLayerModelObject.cpp',
             'rendering/RenderLineBoxList.cpp',
@@ -1540,8 +1557,6 @@
             'rendering/RenderWordBreak.h',
             'rendering/RenderingConfiguration.cpp',
             'rendering/RenderingConfiguration.h',
-            'rendering/RenderingNodeProxy.cpp',
-            'rendering/RenderingNodeProxy.h',
             'rendering/RootInlineBox.cpp',
             'rendering/ScrollBehavior.cpp',
             'rendering/SubtreeLayoutScope.cpp',
@@ -1582,6 +1597,9 @@
             'rendering/style/RenderStyle.cpp',
             'rendering/style/RenderStyle.h',
             'rendering/style/ShadowData.cpp',
+            'rendering/style/ShadowData.h',
+            'rendering/style/ShadowList.cpp',
+            'rendering/style/ShadowList.h',
             'rendering/style/StyleBackgroundData.cpp',
             'rendering/style/StyleBoxData.cpp',
             'rendering/style/StyleFetchedImage.cpp',
@@ -1678,7 +1696,7 @@
             'workers/SharedWorker.h',
             'workers/SharedWorkerGlobalScope.cpp',
             'workers/SharedWorkerGlobalScope.h',
-            'workers/SharedWorkerRepository.h',
+            'workers/SharedWorkerRepositoryClient.h',
             'workers/SharedWorkerThread.cpp',
             'workers/SharedWorkerThread.h',
             'workers/Worker.cpp',
@@ -1856,6 +1874,8 @@
             'dom/DOMURLUtilsReadOnly.h',
             'dom/Element.cpp',
             'dom/Element.h',
+            'dom/ElementData.cpp',
+            'dom/ElementData.h',
             'dom/ElementRareData.cpp',
             'dom/ElementRareData.h',
             'dom/ElementTraversal.h',
@@ -2047,8 +2067,8 @@
             'events/CompositionEvent.h',
             'events/CustomEvent.cpp',
             'events/CustomEvent.h',
-            'events/DocumentEventQueue.cpp',
-            'events/DocumentEventQueue.h',
+            'events/DOMWindowEventQueue.cpp',
+            'events/DOMWindowEventQueue.h',
             'events/ErrorEvent.cpp',
             'events/ErrorEvent.h',
             'events/Event.cpp',
@@ -2233,7 +2253,7 @@
             'html/HTMLParamElement.cpp',
             'html/HTMLParamElement.h',
             'html/HTMLPlugInElement.cpp',
-            'html/HTMLPlugInImageElement.cpp',
+            'html/HTMLPlugInElement.h',
             'html/HTMLPreElement.cpp',
             'html/HTMLPreElement.h',
             'html/HTMLProgressElement.cpp',
@@ -2629,24 +2649,17 @@
             'html/track/WebVTTTokenizer.h',
         ],
         'webcore_platform_files': [
-            'platform/AsyncFileSystemCallbacks.h',
             'platform/ContextMenu.cpp',
             'platform/ContextMenuItem.cpp',
             'platform/Cursor.cpp',
             'platform/DragData.cpp',
             'platform/DragImage.cpp',
-            'platform/HashTools.h',
             'platform/KillRing.h',
             'platform/KillRingNone.cpp',
-            'platform/LifecycleContext.cpp',
-            'platform/LifecycleContext.h',
-            'platform/LifecycleNotifier.cpp',
-            'platform/LifecycleNotifier.h',
-            'platform/LifecycleObserver.cpp',
-            'platform/LifecycleObserver.h',
             'platform/MIMETypeFromURL.cpp',
             'platform/MIMETypeFromURL.h',
-            'platform/ParsingUtilities.h',
+            'platform/OverscrollTheme.cpp',
+            'platform/OverscrollTheme.h',
             'platform/Pasteboard.cpp',
             'platform/Pasteboard.h',
             'platform/PlatformInstrumentation.cpp',
@@ -2657,9 +2670,6 @@
             'platform/PlatformSpeechSynthesisVoice.h',
             'platform/PlatformSpeechSynthesizer.cpp',
             'platform/PlatformSpeechSynthesizer.h',
-            'platform/Prerender.cpp',
-            'platform/Prerender.h',
-            'platform/PrerenderClient.h',
             'platform/ScrollAnimator.cpp',
             'platform/ScrollAnimator.h',
             'platform/ScrollAnimatorNone.cpp',
@@ -2700,12 +2710,10 @@
             'platform/chromium/FramelessScrollView.cpp',
             'platform/chromium/FramelessScrollView.h',
             'platform/chromium/FramelessScrollViewClient.h',
-            'platform/chromium/HistogramSupportChromium.cpp',
             'platform/chromium/KeyCodeConversion.h',
             'platform/chromium/KeyCodeConversionAndroid.cpp',
             'platform/chromium/KeyCodeConversionGtk.cpp',
             'platform/chromium/KeyboardCodes.h',
-            'platform/chromium/MemoryUsageSupportChromium.cpp',
             'platform/chromium/MIMETypeRegistryChromium.cpp',
             'platform/graphics/AlternateFontFamily.h',
             'platform/graphics/BitmapImage.cpp',
@@ -2713,19 +2721,14 @@
             'platform/graphics/ContentDecryptionModule.h',
             'platform/graphics/ContentDecryptionModuleSession.cpp',
             'platform/graphics/ContentDecryptionModuleSession.h',
-            'platform/graphics/Color.cpp',
             'platform/graphics/CrossfadeGeneratedImage.cpp',
             'platform/graphics/CrossfadeGeneratedImage.h',
             'platform/graphics/GradientGeneratedImage.cpp',
             'platform/graphics/GradientGeneratedImage.h',
-            'platform/graphics/DrawLooper.cpp',
-            'platform/graphics/DrawLooper.h',
             'platform/graphics/Extensions3D.cpp',
             'platform/graphics/Extensions3D.h',
             'platform/graphics/Font.cpp',
             'platform/graphics/FontCache.cpp',
-            'platform/graphics/FontCacheKey.h',
-            'platform/graphics/FontDescription.cpp',
             'platform/graphics/FontFallbackList.cpp',
             'platform/graphics/FontFastPath.cpp',
             'platform/graphics/FontPlatformData.cpp',
@@ -2741,7 +2744,6 @@
             'platform/graphics/GraphicsContext3DImagePacking.cpp',
             'platform/graphics/GraphicsContextAnnotation.cpp',
             'platform/graphics/GraphicsLayer.cpp',
-            'platform/graphics/GraphicsTypes.cpp',
             'platform/graphics/Image.cpp',
             'platform/graphics/ImageBuffer.cpp',
             'platform/graphics/ImageSource.cpp',
@@ -2754,8 +2756,6 @@
             'platform/graphics/Pattern.cpp',
             'platform/graphics/SegmentedFontData.cpp',
             'platform/graphics/SegmentedFontData.h',
-            'platform/graphics/ShadowBlur.cpp',
-            'platform/graphics/ShadowBlur.h',
             'platform/graphics/SimpleFontData.cpp',
             'platform/graphics/SVGGlyph.cpp',
             'platform/graphics/StringTruncator.cpp',
@@ -2782,11 +2782,11 @@
             'platform/graphics/chromium/FontCacheChromiumLinux.cpp',
             'platform/graphics/chromium/FontCacheChromiumWin.cpp',
             'platform/graphics/chromium/FontChromiumWin.cpp',
+            'platform/graphics/chromium/FontFallbackWin.cpp',
+            'platform/graphics/chromium/FontFallbackWin.h',
             'platform/graphics/chromium/FontPlatformDataChromiumWin.cpp',
             'platform/graphics/chromium/FontPlatformDataChromiumWin.h',
             'platform/graphics/chromium/FontRenderStyle.h',
-            'platform/graphics/chromium/FontUtilsChromiumWin.cpp',
-            'platform/graphics/chromium/FontUtilsChromiumWin.h',
             'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp',
             'platform/graphics/chromium/ImageDecodingStore.cpp',
             'platform/graphics/chromium/ImageDecodingStore.h',
@@ -2946,24 +2946,6 @@
             'platform/graphics/skia/SkiaSharedBufferStream.h',
             'platform/graphics/skia/SkiaUtils.cpp',
             'platform/graphics/skia/SkiaUtils.h',
-            'platform/graphics/transforms/IdentityTransformOperation.h',
-            'platform/graphics/transforms/InterpolatedTransformOperation.h',
-            'platform/graphics/transforms/InterpolatedTransformOperation.cpp',
-            'platform/graphics/transforms/Matrix3DTransformOperation.cpp',
-            'platform/graphics/transforms/Matrix3DTransformOperation.h',
-            'platform/graphics/transforms/MatrixTransformOperation.cpp',
-            'platform/graphics/transforms/MatrixTransformOperation.h',
-            'platform/graphics/transforms/PerspectiveTransformOperation.cpp',
-            'platform/graphics/transforms/PerspectiveTransformOperation.h',
-            'platform/graphics/transforms/RotateTransformOperation.cpp',
-            'platform/graphics/transforms/RotateTransformOperation.h',
-            'platform/graphics/transforms/ScaleTransformOperation.cpp',
-            'platform/graphics/transforms/ScaleTransformOperation.h',
-            'platform/graphics/transforms/SkewTransformOperation.cpp',
-            'platform/graphics/transforms/SkewTransformOperation.h',
-            'platform/graphics/transforms/TransformOperations.cpp',
-            'platform/graphics/transforms/TranslateTransformOperation.cpp',
-            'platform/graphics/transforms/TranslateTransformOperation.h',
             'platform/graphics/win/FontCustomPlatformDataWin.cpp',
             'platform/image-decoders/ImageDecoder.cpp',
             'platform/image-decoders/ImageDecoder.h',
@@ -3033,9 +3015,6 @@
             'platform/mock/ScrollbarThemeOverlayMock.h',
             'platform/text/RegularExpression.cpp',
         ],
-        'webcore_platform_geometry_files': [
-            'platform/graphics/FloatPolygon.cpp',
-        ],
         'webcore_svg_files': [
             'rendering/style/SVGRenderStyle.cpp',
             'rendering/style/SVGRenderStyleDefs.cpp',
@@ -3525,22 +3504,15 @@
         'webcore_platform_support_files': [
             'platform/chromium/support/WebArrayBuffer.cpp',
             'platform/chromium/support/WebCrypto.cpp',
-            'platform/chromium/support/WebCryptoAlgorithm.cpp',
             'platform/chromium/support/WebCryptoKey.cpp',
             'platform/chromium/support/WebCursorInfo.cpp',
             'platform/chromium/support/WebDeviceMotionData.cpp',
             'platform/chromium/support/WebDeviceOrientationData.cpp',
-            'platform/chromium/support/WebFileSystemCallbacks.cpp',
-            'platform/chromium/support/WebFloatQuad.cpp',
-            'platform/chromium/support/WebFilterKeyframe.cpp',
             'platform/chromium/support/WebMediaConstraints.cpp',
             'platform/chromium/support/WebMediaStream.cpp',
             'platform/chromium/support/WebMediaStreamSource.cpp',
             'platform/chromium/support/WebMediaStreamTrack.cpp',
-            'platform/chromium/support/WebPrerender.cpp',
-            'platform/chromium/support/WebPrerenderingSupport.cpp',
             'platform/chromium/support/WebRTCConfiguration.cpp',
-            'platform/chromium/support/WebRTCICECandidate.cpp',
             'platform/chromium/support/WebRTCSessionDescription.cpp',
             'platform/chromium/support/WebRTCSessionDescriptionRequest.cpp',
             'platform/chromium/support/WebRTCStatsRequest.cpp',
@@ -3552,12 +3524,10 @@
             'platform/chromium/support/WebScrollbarThemeClientImpl.h',
             'platform/chromium/support/WebScrollbarThemeGeometryNative.cpp',
             'platform/chromium/support/WebScrollbarThemeGeometryNative.h',
-            'platform/chromium/support/WebSourceInfo.cpp',
             'platform/chromium/support/WebSpeechSynthesisUtterance.cpp',
             'platform/chromium/support/WebSpeechSynthesisVoice.cpp',
             'platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp',
             'platform/chromium/support/WebSpeechSynthesizerClientImpl.h',
-            'platform/chromium/support/WebTransformKeyframe.cpp',
             'platform/chromium/support/WrappedResourceRequest.h',
             'platform/chromium/support/WrappedResourceResponse.h',
         ],
@@ -3606,60 +3576,5 @@
             'platform/testing/FakeWebGraphicsContext3D.h',
             'rendering/RenderOverflowTest.cpp',
         ],
-        'scripts_for_in_files': [
-            # jinja2/__init__.py contains version string, so sufficient as
-            # dependency for whole jinja2 package
-            '<(DEPTH)/third_party/jinja2/__init__.py',
-            '<(DEPTH)/third_party/markupsafe/__init__.py',  # jinja2 dep
-            '../build/scripts/hasher.py',
-            '../build/scripts/in_file.py',
-            '../build/scripts/in_generator.py',
-            '../build/scripts/license.py',
-            '../build/scripts/name_macros.py',
-            '../build/scripts/name_utilities.py',
-            '../build/scripts/template_expander.py',
-            '../build/scripts/templates/macros.tmpl',
-        ],
-        'make_names_files': [
-            '<@(scripts_for_in_files)',
-            '../build/scripts/make_names.py',
-            '../build/scripts/templates/MakeNames.cpp.tmpl',
-            '../build/scripts/templates/MakeNames.h.tmpl',
-        ],
-        'make_qualified_names_files': [
-            '<@(scripts_for_in_files)',
-            '../build/scripts/make_qualified_names.py',
-            '../build/scripts/templates/MakeQualifiedNames.cpp.tmpl',
-            '../build/scripts/templates/MakeQualifiedNames.h.tmpl',
-        ],
-        'make_element_factory_files': [
-            '<@(make_qualified_names_files)',
-            '../build/scripts/make_element_factory.py',
-            '../build/scripts/templates/ElementFactory.cpp.tmpl',
-            '../build/scripts/templates/ElementFactory.h.tmpl',
-            '../build/scripts/templates/ElementWrapperFactory.cpp.tmpl',
-            '../build/scripts/templates/ElementWrapperFactory.h.tmpl',
-        ],
-        'conditions': [
-            ['OS=="win"', {
-                # Using native perl rather than cygwin perl cuts execution time
-                # of idl preprocessing rules by a bit more than 50%.
-                'perl_exe': '<(DEPTH)/third_party/perl/perl/bin/perl.exe',
-                'gperf_exe': '<(DEPTH)/third_party/gperf/bin/gperf.exe',
-                'bison_exe': '<(DEPTH)/third_party/bison/bin/bison.exe',
-                # Using cl instead of cygwin gcc cuts the processing time from
-                # 1m58s to 0m52s.
-                'preprocessor': '--preprocessor "cl.exe -nologo -EP -TP"',
-              },{
-                'perl_exe': 'perl',
-                'gperf_exe': 'gperf',
-                'bison_exe': 'bison',
-                # We specify a preprocess so it happens locally and won't get
-                # distributed to goma.
-                # FIXME: /usr/bin/gcc won't exist on OSX forever. We want to
-                # use /usr/bin/clang once we require Xcode 4.x.
-                'preprocessor': '--preprocessor "/usr/bin/gcc -E -P -x c++"'
-              }],
-         ],
     }
 }
diff --git a/Source/core/core_derived_sources.gyp b/Source/core/core_derived_sources.gyp
index 1f8ac12..01b695c 100644
--- a/Source/core/core_derived_sources.gyp
+++ b/Source/core/core_derived_sources.gyp
@@ -33,6 +33,7 @@
     'core.gypi',
     '../bindings/bindings.gypi',
     '../build/features.gypi',
+    '../build/scripts/scripts.gypi',
   ],
 
   'targets': [
@@ -43,7 +44,12 @@
         {
           'action_name': 'Settings',
           'inputs': [
-            'page/make_settings.pl',
+            '<@(scripts_for_in_files)',
+            '../build/scripts/make_settings.py',
+            '../build/scripts/templates/InternalSettingsGenerated.idl.tmpl',
+            '../build/scripts/templates/InternalSettingsGenerated.cpp.tmpl',
+            '../build/scripts/templates/InternalSettingsGenerated.h.tmpl',
+            '../build/scripts/templates/SettingsMacros.h.tmpl',
             'page/Settings.in',
           ],
           'outputs': [
@@ -54,19 +60,18 @@
           ],
           'action': [
             'python',
-            '../build/scripts/action_makenames.py',
-            '<@(_outputs)',
-            '--',
-            '<@(_inputs)',
+            '../build/scripts/make_settings.py',
+            'page/Settings.in',
+            '--output_dir',
+            '<(SHARED_INTERMEDIATE_DIR)/blink',
           ],
-          'msvs_cygwin_shell': 1,
         },
         {
           'action_name': 'InternalRuntimeFlags',
           'inputs': [
             '<@(scripts_for_in_files)',
             '../build/scripts/make_internal_runtime_flags.py',
-            'page/RuntimeEnabledFeatures.in',
+            '../platform/RuntimeEnabledFeatures.in',
             '../build/scripts/templates/InternalRuntimeFlags.h.tmpl',
             '../build/scripts/templates/InternalRuntimeFlags.idl.tmpl',
           ],
@@ -77,7 +82,7 @@
           'action': [
             'python',
             '../build/scripts/make_internal_runtime_flags.py',
-            'page/RuntimeEnabledFeatures.in',
+            '../platform/RuntimeEnabledFeatures.in',
             '--output_dir',
             '<(SHARED_INTERMEDIATE_DIR)/blink',
           ],
@@ -93,11 +98,8 @@
       ],
       'sources': [
         # bison rule
-        '<(SHARED_INTERMEDIATE_DIR)/blink/CSSGrammar.y',
+        'css/CSSGrammar.y',
         'xml/XPathGrammar.y',
-
-        # gperf rule
-        'platform/ColorData.gperf',
       ],
       'actions': [
         {
@@ -108,15 +110,15 @@
           'outputs': [
             '<(SHARED_INTERMEDIATE_DIR)/blink/V8ArrayBufferViewCustomScript.h',
           ],
-          'msvs_cygwin_shell': 0,
           'action': [
-            '<(perl_exe)',
-            '../build/scripts/xxd.pl',
+            'python',
+            '../build/scripts/xxd.py',
             'V8ArrayBufferViewCustomScript_js',
             '<@(_inputs)',
             '<@(_outputs)'
           ],
           'message': 'Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js',
+          'msvs_cygwin_shell': 0,
         },
         {
           'action_name': 'generateXMLViewerCSS',
@@ -126,14 +128,14 @@
           'outputs': [
             '<(SHARED_INTERMEDIATE_DIR)/blink/XMLViewerCSS.h',
           ],
-          'msvs_cygwin_shell': 0,
           'action': [
-            '<(perl_exe)',
-            '../build/scripts/xxd.pl',
+            'python',
+            '../build/scripts/xxd.py',
             'XMLViewer_css',
             '<@(_inputs)',
             '<@(_outputs)'
           ],
+          'msvs_cygwin_shell': 0,
         },
         {
           'action_name': 'generateXMLViewerJS',
@@ -143,14 +145,14 @@
           'outputs': [
             '<(SHARED_INTERMEDIATE_DIR)/blink/XMLViewerJS.h',
           ],
-          'msvs_cygwin_shell': 0,
           'action': [
-            '<(perl_exe)',
-            '../build/scripts/xxd.pl',
+            'python',
+            '../build/scripts/xxd.py',
             'XMLViewer_js',
             '<@(_inputs)',
             '<@(_outputs)'
           ],
+          'msvs_cygwin_shell': 0,
         },
         {
           'action_name': 'HTMLEntityTable',
@@ -170,27 +172,6 @@
           ],
         },
         {
-          'action_name': 'RuntimeEnabledFeatures',
-          'inputs': [
-            '<@(scripts_for_in_files)',
-            '../build/scripts/make_runtime_features.py',
-            'page/RuntimeEnabledFeatures.in',
-            '../build/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl',
-            '../build/scripts/templates/RuntimeEnabledFeatures.h.tmpl',
-          ],
-          'outputs': [
-            '<(SHARED_INTERMEDIATE_DIR)/blink/RuntimeEnabledFeatures.cpp',
-            '<(SHARED_INTERMEDIATE_DIR)/blink/RuntimeEnabledFeatures.h',
-          ],
-          'action': [
-            'python',
-            '../build/scripts/make_runtime_features.py',
-            'page/RuntimeEnabledFeatures.in',
-            '--output_dir',
-            '<(SHARED_INTERMEDIATE_DIR)/blink',
-          ],
-        },
-        {
           'action_name': 'CSSPropertyNames',
           'variables': {
             'in_files': [
@@ -314,31 +295,26 @@
         {
           'action_name': 'SVGNames',
           'inputs': [
-            '../build/scripts/Hasher.pm',
-            '../build/scripts/StaticString.pm',
-            '../build/scripts/make_names.pl',
+            '<@(make_element_factory_files)',
             'svg/SVGTagNames.in',
             'svg/SVGAttributeNames.in',
           ],
           'outputs': [
-            '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.cpp',
-            '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.h',
             '<(SHARED_INTERMEDIATE_DIR)/blink/SVGElementFactory.cpp',
             '<(SHARED_INTERMEDIATE_DIR)/blink/SVGElementFactory.h',
+            '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.cpp',
+            '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.h',
             '<(SHARED_INTERMEDIATE_DIR)/blink/V8SVGElementWrapperFactory.cpp',
             '<(SHARED_INTERMEDIATE_DIR)/blink/V8SVGElementWrapperFactory.h',
           ],
           'action': [
             'python',
-            '../build/scripts/action_makenames.py',
-            '<@(_outputs)',
-            '--',
-            '<@(_inputs)',
-            '--',
-            '--factory',
-            '--extraDefines', '<(feature_defines)'
+            '../build/scripts/make_element_factory.py',
+            'svg/SVGTagNames.in',
+            'svg/SVGAttributeNames.in',
+            '--output_dir',
+            '<(SHARED_INTERMEDIATE_DIR)/blink',
           ],
-          'msvs_cygwin_shell': 1,
         },
         {
           'action_name': 'EventFactory',
@@ -573,24 +549,6 @@
           ],
         },
         {
-          'action_name': 'preprocess_grammar',
-          'inputs': [
-            'css/CSSGrammar.y.in',
-            'css/CSSGrammar.y.includes',
-          ],
-          'outputs': [
-            '<(SHARED_INTERMEDIATE_DIR)/blink/CSSGrammar.y',
-          ],
-          'action': [
-            '<(perl_exe)',
-            '-I../build/scripts',
-            'css/makegrammar.pl',
-            '--outputDir',
-            '<(SHARED_INTERMEDIATE_DIR)/blink',
-            '<@(_inputs)',
-          ],
-        },
-        {
           'action_name': 'MakeTokenMatcher',
           'inputs': [
             '<@(scripts_for_in_files)',
@@ -642,24 +600,6 @@
           ],
           'msvs_cygwin_shell': 1,
         },
-        {
-          'rule_name': 'gperf',
-          'extension': 'gperf',
-          'outputs': [
-            '<(SHARED_INTERMEDIATE_DIR)/blink/<(RULE_INPUT_ROOT).cpp',
-          ],
-          'inputs': [
-            '../build/scripts/make-hash-tools.pl',
-          ],
-          'msvs_cygwin_shell': 0,
-          'action': [
-            '<(perl_exe)',
-            '../build/scripts/make-hash-tools.pl',
-            '<(SHARED_INTERMEDIATE_DIR)/blink',
-            '<(RULE_INPUT_PATH)',
-            '<(gperf_exe)',
-          ],
-        },
       ],
     },
   ],
diff --git a/Source/core/css/CSSBasicShapes.h b/Source/core/css/CSSBasicShapes.h
index e739ab0..ca8c661 100644
--- a/Source/core/css/CSSBasicShapes.h
+++ b/Source/core/css/CSSBasicShapes.h
@@ -31,7 +31,7 @@
 #define CSSBasicShapes_h
 
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/platform/graphics/WindRule.h"
+#include "platform/graphics/WindRule.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/css/CSSComputedStyleDeclaration.cpp b/Source/core/css/CSSComputedStyleDeclaration.cpp
index d064e69..8852d36 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -65,6 +65,7 @@
 #include "core/rendering/style/CounterContent.h"
 #include "core/rendering/style/CursorList.h"
 #include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/style/ShadowList.h"
 #include "core/rendering/style/ShapeValue.h"
 #include "platform/fonts/FontFeatureSettings.h"
 #include "wtf/text/StringBuilder.h"
@@ -602,12 +603,12 @@
 static PassRefPtr<CSSValueList> createPositionListForLayer(CSSPropertyID propertyID, const FillLayer* layer, const RenderStyle* style)
 {
     RefPtr<CSSValueList> positionList = CSSValueList::createSpaceSeparated();
-    if (layer->isBackgroundOriginSet()) {
+    if (layer->isBackgroundXOriginSet()) {
         ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPosition || propertyID == CSSPropertyWebkitMaskPosition);
         positionList->append(cssValuePool().createValue(layer->backgroundXOrigin()));
     }
     positionList->append(zoomAdjustedPixelValueForLength(layer->xPosition(), style));
-    if (layer->isBackgroundOriginSet()) {
+    if (layer->isBackgroundYOriginSet()) {
         ASSERT(propertyID == CSSPropertyBackgroundPosition || propertyID == CSSPropertyWebkitMaskPosition);
         positionList->append(cssValuePool().createValue(layer->backgroundYOrigin()));
     }
@@ -656,7 +657,7 @@
     return zoomAdjustedPixelValueForLength(l, style);
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(RenderStyle* style, const Color& color) const
+PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(const RenderStyle* style, const Color& color) const
 {
     // This function does NOT look at visited information, so that computed style doesn't expose that.
     if (!color.isValid())
@@ -664,36 +665,29 @@
     return cssValuePool().createColorValue(color.rgb());
 }
 
-static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderObject* renderer, RenderView* renderView)
+static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle* style)
 {
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    LayoutUnit width = 0;
-    LayoutUnit height = 0;
-    if (radius.width().isCalculated() || radius.height().isCalculated()) {
-        LayoutRect layoutRect = (renderer && renderer->isBox()) ? toRenderBox(renderer)->borderBoxRect() : LayoutRect();
-        width = layoutRect.width();
-        height = layoutRect.height();
-    }
     if (radius.width().type() == Percent)
         list->append(cssValuePool().createValue(radius.width().percent(), CSSPrimitiveValue::CSS_PERCENTAGE));
     else
-        list->append(zoomAdjustedPixelValue(valueForLength(radius.width(), width, renderView), style));
+        list->append(zoomAdjustedPixelValueForLength(radius.width(), style));
     if (radius.height().type() == Percent)
         list->append(cssValuePool().createValue(radius.height().percent(), CSSPrimitiveValue::CSS_PERCENTAGE));
     else
-        list->append(zoomAdjustedPixelValue(valueForLength(radius.height(), height, renderView), style));
+        list->append(zoomAdjustedPixelValueForLength(radius.height(), style));
     return list.release();
 }
 
-static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderObject* renderer, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle* style)
 {
-    RefPtr<CSSValueList> list = valuesForBorderRadiusCorner(radius, style, renderer, renderView);
+    RefPtr<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, RenderObject* renderer, RenderView* renderView)
+static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle* style)
 {
     RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
 
@@ -704,12 +698,11 @@
     bool showVerticalBottomLeft = style->borderTopRightRadius().height() != style->borderBottomLeftRadius().height();
     bool showVerticalBottomRight = showVerticalBottomLeft || (style->borderBottomRightRadius().height() != style->borderTopLeftRadius().height());
     bool showVerticalTopRight = showVerticalBottomRight || (style->borderTopRightRadius().height() != style->borderTopLeftRadius().height());
-    bool showVerticalTopLeft = (style->borderTopLeftRadius().width() != style->borderTopLeftRadius().height());
 
-    RefPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style->borderTopLeftRadius(), style, renderer, renderView);
-    RefPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style->borderTopRightRadius(), style, renderer, renderView);
-    RefPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style->borderBottomRightRadius(), style, renderer, renderView);
-    RefPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style->borderBottomLeftRadius(), style, renderer, renderView);
+    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);
 
     RefPtr<CSSValueList> horizontalRadii = CSSValueList::createSpaceSeparated();
     horizontalRadii->append(topLeftRadius->item(0));
@@ -926,8 +919,8 @@
             DropShadowFilterOperation* dropShadowOperation = static_cast<DropShadowFilterOperation*>(filterOperation);
             filterValue = CSSFilterValue::create(CSSFilterValue::DropShadowFilterOperation);
             // We want our computed style to look like that of a text shadow (has neither spread nor inset style).
-            OwnPtr<ShadowData> shadow = ShadowData::create(dropShadowOperation->location(), dropShadowOperation->stdDeviation(), 0, Normal, dropShadowOperation->color());
-            filterValue->append(valueForShadow(shadow.get(), CSSPropertyTextShadow, style));
+            ShadowData shadow(dropShadowOperation->location(), dropShadowOperation->stdDeviation(), 0, Normal, dropShadowOperation->color());
+            filterValue->append(valueForShadowData(shadow, style, false));
             break;
         }
         case FilterOperation::VALIDATED_CUSTOM:
@@ -1315,21 +1308,26 @@
     return style->fontDescription().useFixedDefaultSize();
 }
 
-PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadow(const ShadowData* shadow, CSSPropertyID propertyID, const RenderStyle* style) const
+PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadowData(const ShadowData& shadow, const RenderStyle* style, bool useSpread) const
 {
-    if (!shadow)
+    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());
+    return CSSShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), shadowStyle.release(), color.release());
+}
+
+PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadowList(const ShadowList* shadowList, const RenderStyle* style, bool useSpread) const
+{
+    if (!shadowList)
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
-    for (const ShadowData* s = shadow; s; s = s->next()) {
-        RefPtr<CSSPrimitiveValue> x = zoomAdjustedPixelValue(s->x(), style);
-        RefPtr<CSSPrimitiveValue> y = zoomAdjustedPixelValue(s->y(), style);
-        RefPtr<CSSPrimitiveValue> blur = zoomAdjustedPixelValue(s->blur(), style);
-        RefPtr<CSSPrimitiveValue> spread = propertyID == CSSPropertyTextShadow ? PassRefPtr<CSSPrimitiveValue>() : zoomAdjustedPixelValue(s->spread(), style);
-        RefPtr<CSSPrimitiveValue> style = propertyID == CSSPropertyTextShadow || s->style() == Normal ? PassRefPtr<CSSPrimitiveValue>() : cssValuePool().createIdentifierValue(CSSValueInset);
-        RefPtr<CSSPrimitiveValue> color = cssValuePool().createColorValue(s->color().rgb());
-        list->prepend(CSSShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), style.release(), color.release()));
-    }
+    size_t shadowCount = shadowList->shadows().size();
+    for (size_t i = 0; i < shadowCount; ++i)
+        list->append(valueForShadowData(shadowList->shadows()[i], style, useSpread));
     return list.release();
 }
 
@@ -1340,17 +1338,17 @@
 
 static CSSValueID identifierForFamily(const AtomicString& family)
 {
-    if (family == cursiveFamily)
+    if (family == FontFamilyNames::webkit_cursive)
         return CSSValueCursive;
-    if (family == fantasyFamily)
+    if (family == FontFamilyNames::webkit_fantasy)
         return CSSValueFantasy;
-    if (family == monospaceFamily)
+    if (family == FontFamilyNames::webkit_monospace)
         return CSSValueMonospace;
-    if (family == pictographFamily)
+    if (family == FontFamilyNames::webkit_pictograph)
         return CSSValueWebkitPictograph;
-    if (family == sansSerifFamily)
+    if (family == FontFamilyNames::webkit_sans_serif)
         return CSSValueSansSerif;
-    if (family == serifFamily)
+    if (family == FontFamilyNames::webkit_serif)
         return CSSValueSerif;
     return CSSValueInvalid;
 }
@@ -1576,19 +1574,6 @@
     case CSSPropertyWidth:
     case CSSPropertyWebkitFilter:
         return true;
-    case CSSPropertyBorderBottomLeftRadius:
-        return renderer && (style->borderBottomLeftRadius().width().isCalculated() || style->borderBottomLeftRadius().height().isCalculated());
-    case CSSPropertyBorderBottomRightRadius:
-        return renderer && (style->borderBottomRightRadius().width().isCalculated() || style->borderBottomRightRadius().height().isCalculated());
-    case CSSPropertyBorderRadius:
-        return isLayoutDependent(CSSPropertyBorderBottomLeftRadius, style.get(), renderer)
-            || isLayoutDependent(CSSPropertyBorderBottomRightRadius, style.get(), renderer)
-            || isLayoutDependent(CSSPropertyBorderTopLeftRadius, style.get(), renderer)
-            || isLayoutDependent(CSSPropertyBorderTopRightRadius, style, renderer);
-    case CSSPropertyBorderTopLeftRadius:
-        return renderer && (style->borderTopLeftRadius().width().isCalculated() || style->borderTopLeftRadius().height().isCalculated());
-    case CSSPropertyBorderTopRightRadius:
-        return renderer && (style->borderTopRightRadius().width().isCalculated() || style->borderTopRightRadius().height().isCalculated());
     case CSSPropertyMargin:
         return renderer && renderer->isBox() && (!style || !style->marginBottom().isFixed() || !style->marginTop().isFixed() || !style->marginLeft().isFixed() || !style->marginRight().isFixed());
     case CSSPropertyMarginLeft:
@@ -1636,7 +1621,7 @@
     if (!m_node)
         return 0;
     if (m_node->isElementNode()) {
-        if (PseudoElement* element = toElement(m_node.get())->pseudoElement(m_pseudoElementSpecifier))
+        if (PseudoElement* element = toElement(m_node)->pseudoElement(m_pseudoElementSpecifier))
             return element;
     }
     return m_node.get();
@@ -1898,7 +1883,7 @@
             return valueForReflection(style->boxReflect(), style.get());
         case CSSPropertyBoxShadow:
         case CSSPropertyWebkitBoxShadow:
-            return valueForShadow(style->boxShadow(), propertyID, style.get());
+            return valueForShadowList(style->boxShadow(), style.get(), true);
         case CSSPropertyCaptionSide:
             return cssValuePool().createValue(style->captionSide());
         case CSSPropertyClear:
@@ -2315,7 +2300,7 @@
             return textIndent.release();
         }
         case CSSPropertyTextShadow:
-            return valueForShadow(style->textShadow(), propertyID, style.get());
+            return valueForShadowList(style->textShadow(), style.get(), false);
         case CSSPropertyTextRendering:
             return cssValuePool().createValue(style->fontDescription().textRenderingMode());
         case CSSPropertyTextOverflow:
@@ -2617,13 +2602,13 @@
         case CSSPropertyWebkitUserSelect:
             return cssValuePool().createValue(style->userSelect());
         case CSSPropertyBorderBottomLeftRadius:
-            return valueForBorderRadiusCorner(style->borderBottomLeftRadius(), style.get(), renderer, m_node->document().renderView());
+            return valueForBorderRadiusCorner(style->borderBottomLeftRadius(), style.get());
         case CSSPropertyBorderBottomRightRadius:
-            return valueForBorderRadiusCorner(style->borderBottomRightRadius(), style.get(), renderer, m_node->document().renderView());
+            return valueForBorderRadiusCorner(style->borderBottomRightRadius(), style.get());
         case CSSPropertyBorderTopLeftRadius:
-            return valueForBorderRadiusCorner(style->borderTopLeftRadius(), style.get(), renderer, m_node->document().renderView());
+            return valueForBorderRadiusCorner(style->borderTopLeftRadius(), style.get());
         case CSSPropertyBorderTopRightRadius:
-            return valueForBorderRadiusCorner(style->borderTopRightRadius(), style.get(), renderer, m_node->document().renderView());
+            return valueForBorderRadiusCorner(style->borderTopRightRadius(), style.get());
         case CSSPropertyClip: {
             if (!style->hasClip())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
@@ -2810,7 +2795,7 @@
         case CSSPropertyBorderImage:
             return valueForNinePieceImage(style->borderImage(), style.get());
         case CSSPropertyBorderRadius:
-            return valueForBorderRadiusShorthand(style.get(), renderer, m_node->document().renderView());
+            return valueForBorderRadiusShorthand(style.get());
         case CSSPropertyBorderRight:
             return valuesForShorthandProperty(borderRightShorthand());
         case CSSPropertyBorderStyle:
diff --git a/Source/core/css/CSSComputedStyleDeclaration.h b/Source/core/css/CSSComputedStyleDeclaration.h
index 3a2f76b..74b881d 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/Source/core/css/CSSComputedStyleDeclaration.h
@@ -43,6 +43,7 @@
 class RenderStyle;
 class SVGPaint;
 class ShadowData;
+class ShadowList;
 class StylePropertySet;
 class StylePropertyShorthand;
 
@@ -127,8 +128,9 @@
 
     virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const OVERRIDE;
 
-    PassRefPtr<CSSValue> valueForShadow(const ShadowData*, CSSPropertyID, const RenderStyle*) const;
-    PassRefPtr<CSSPrimitiveValue> currentColorOrValidColor(RenderStyle*, const Color&) const;
+    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;
 
     PassRefPtr<CSSValue> valueForFilter(const RenderObject*, const RenderStyle*) const;
diff --git a/Source/core/css/CSSDefaultStyleSheets.cpp b/Source/core/css/CSSDefaultStyleSheets.cpp
index e5fda36..2799cff 100644
--- a/Source/core/css/CSSDefaultStyleSheets.cpp
+++ b/Source/core/css/CSSDefaultStyleSheets.cpp
@@ -57,7 +57,7 @@
 StyleSheetContents* CSSDefaultStyleSheets::fullscreenStyleSheet;
 
 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
-static const char* simpleUserAgentStyleSheet = "html,body,div{display:block}head{display:none}body{margin:8px}div:focus,span:focus,a:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}body:-webkit-seamless-document{margin:0}body:-webkit-full-page-media{background-color:black}@viewport{min-width:980px}@page{size:auto;margin:auto;padding:0;border-width:0}";
+static const char simpleUserAgentStyleSheet[] = "html,body,div{display:block}head{display:none}body{margin:8px}div:focus,span:focus,a:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}body:-webkit-seamless-document{margin:0}body:-webkit-full-page-media{background-color:black}@viewport{min-width:980px}@page{size:auto;margin:auto;padding:0;border-width:0}";
 
 static inline bool elementCanUseSimpleDefaultStyle(Element* e)
 {
diff --git a/Source/core/css/CSSFontFace.cpp b/Source/core/css/CSSFontFace.cpp
index ce3d142..affaa14 100644
--- a/Source/core/css/CSSFontFace.cpp
+++ b/Source/core/css/CSSFontFace.cpp
@@ -141,7 +141,6 @@
         return;
 
     ASSERT(m_segmentedFontFace);
-    CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
 
     size_t size = m_sources.size();
     for (size_t i = 0; i < size; ++i) {
@@ -164,13 +163,13 @@
 
     switch (newStatus) {
     case FontFace::Loading:
-        document->fonts()->beginFontLoading(m_fontFace.get());
+        FontFaceSet::from(document)->beginFontLoading(m_fontFace.get());
         break;
     case FontFace::Loaded:
-        document->fonts()->fontLoaded(m_fontFace.get());
+        FontFaceSet::from(document)->fontLoaded(m_fontFace.get());
         break;
     case FontFace::Error:
-        document->fonts()->loadError(m_fontFace.get());
+        FontFaceSet::from(document)->loadError(m_fontFace.get());
         break;
     default:
         break;
diff --git a/Source/core/css/CSSFontFaceSource.cpp b/Source/core/css/CSSFontFaceSource.cpp
index c0bdb7c..48b5257 100644
--- a/Source/core/css/CSSFontFaceSource.cpp
+++ b/Source/core/css/CSSFontFaceSource.cpp
@@ -30,10 +30,10 @@
 #include "core/css/CSSFontFace.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/fetch/FontResource.h"
-#include "core/platform/HistogramSupport.h"
 #include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/SimpleFontData.h"
+#include "platform/fonts/FontDescription.h"
+#include "public/platform/Platform.h"
 #include "wtf/CurrentTime.h"
 
 #if ENABLE(SVG_FONTS)
@@ -280,7 +280,7 @@
 void CSSFontFaceSource::FontLoadHistograms::recordLocalFont(bool loadSuccess)
 {
     if (!m_loadStartTime) {
-        HistogramSupport::histogramEnumeration("WebFont.LocalFontUsed", loadSuccess ? 1 : 0, 2);
+        WebKit::Platform::current()->histogramEnumeration("WebFont.LocalFontUsed", loadSuccess ? 1 : 0, 2);
         m_loadStartTime = -1; // Do not count this font again.
     }
 }
@@ -289,14 +289,14 @@
 {
     if (m_loadStartTime > 0 && font && !font->isLoading()) {
         int duration = static_cast<int>(currentTimeMS() - m_loadStartTime);
-        HistogramSupport::histogramCustomCounts(histogramName(font), duration, 0, 10000, 50);
+        WebKit::Platform::current()->histogramCustomCounts(histogramName(font), duration, 0, 10000, 50);
         m_loadStartTime = -1;
 
         enum { Miss, Hit, DataUrl, CacheHitEnumMax };
         int histogramValue = font->url().protocolIsData() ? DataUrl
             : font->response().wasCached() ? Hit
             : Miss;
-        HistogramSupport::histogramEnumeration("WebFont.CacheHit", histogramValue, CacheHitEnumMax);
+        WebKit::Platform::current()->histogramEnumeration("WebFont.CacheHit", histogramValue, CacheHitEnumMax);
     }
 }
 
diff --git a/Source/core/css/CSSFontSelector.h b/Source/core/css/CSSFontSelector.h
index 1733964..6df1ac6 100644
--- a/Source/core/css/CSSFontSelector.h
+++ b/Source/core/css/CSSFontSelector.h
@@ -28,8 +28,8 @@
 
 #include "core/css/CSSSegmentedFontFaceCache.h"
 #include "core/fetch/ResourcePtr.h"
-#include "core/platform/graphics/FontSelector.h"
 #include "platform/Timer.h"
+#include "platform/fonts/FontSelector.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
diff --git a/Source/core/css/CSSGrammar.y.in b/Source/core/css/CSSGrammar.y
similarity index 96%
rename from Source/core/css/CSSGrammar.y.in
rename to Source/core/css/CSSGrammar.y
index 1fc7d7a..ad5e331 100644
--- a/Source/core/css/CSSGrammar.y.in
+++ b/Source/core/css/CSSGrammar.y
@@ -1,3 +1,5 @@
+%{
+
 /*
  *  Copyright (C) 2002-2003 Lars Knoll (knoll@kde.org)
  *  Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
@@ -21,6 +23,43 @@
  *
  */
 
+#include "config.h"
+
+#include "CSSPropertyNames.h"
+#include "HTMLNames.h"
+#include "core/css/CSSKeyframeRule.h"
+#include "core/css/CSSKeyframesRule.h"
+#include "core/css/CSSParser.h"
+#include "core/css/CSSParserMode.h"
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSSelector.h"
+#include "core/css/CSSSelectorList.h"
+#include "core/css/MediaList.h"
+#include "core/css/MediaQueryExp.h"
+#include "core/css/StyleRule.h"
+#include "core/css/StyleSheetContents.h"
+#include "core/dom/Document.h"
+#include "wtf/FastMalloc.h"
+#include <stdlib.h>
+#include <string.h>
+
+using namespace WebCore;
+using namespace HTMLNames;
+
+#define YYMALLOC fastMalloc
+#define YYFREE fastFree
+
+#define YYENABLE_NLS 0
+#define YYLTYPE_IS_TRIVIAL 1
+#define YYMAXDEPTH 10000
+#define YYDEBUG 0
+
+#if YYDEBUG > 0
+#define YYPRINT(File,Type,Value) if (isCSSTokenAString(Type)) YYFPRINTF(File, "%s", String((Value).string).utf8().data())
+#endif
+
+%}
+
 %pure_parser
 
 %parse-param { CSSParser* parser }
@@ -1124,9 +1163,19 @@
 
 combinator:
     '+' maybe_space { $$ = CSSSelector::DirectAdjacent; }
-  | '~' maybe_space { $$ = CSSSelector::IndirectAdjacent; }
-  | '>' maybe_space { $$ = CSSSelector::Child; }
-  ;
+    | '~' maybe_space { $$ = CSSSelector::IndirectAdjacent; }
+    | '>' maybe_space { $$ = CSSSelector::Child; }
+    | '^' maybe_space {
+        if (!RuntimeEnabledFeatures::shadowDOMEnabled())
+            YYERROR;
+        $$ = CSSSelector::ChildTree;
+    }
+    | '^' '^' maybe_space {
+        if (!RuntimeEnabledFeatures::shadowDOMEnabled())
+            YYERROR;
+        $$ = CSSSelector::DescendantTree;
+    }
+    ;
 
 maybe_unary_operator:
     unary_operator
@@ -1225,7 +1274,7 @@
 
 namespace_selector:
     /* empty */ '|' { $$.clear(); }
-    | '*' '|' { static LChar star = '*'; $$.init(&star, 1); }
+    | '*' '|' { static const LChar star = '*'; $$.init(&star, 1); }
     | IDENT '|'
     ;
 
@@ -1278,7 +1327,7 @@
         $$ = $1;
     }
     | '*' {
-        static LChar star = '*';
+        static const LChar star = '*';
         $$.init(&star, 1);
     }
   ;
@@ -1294,7 +1343,7 @@
     IDSEL {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::Id);
-        if (parser->m_context.mode == CSSQuirksMode)
+        if (isQuirksModeBehavior(parser->m_context.mode))
             parser->tokenToLowerCase($1);
         $$->setValue($1);
     }
@@ -1304,7 +1353,7 @@
         } else {
             $$ = parser->createFloatingSelector();
             $$->setMatch(CSSSelector::Id);
-            if (parser->m_context.mode == CSSQuirksMode)
+            if (isQuirksModeBehavior(parser->m_context.mode))
                 parser->tokenToLowerCase($1);
             $$->setValue($1);
         }
@@ -1318,7 +1367,7 @@
     '.' IDENT {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::Class);
-        if (parser->m_context.mode == CSSQuirksMode)
+        if (isQuirksModeBehavior(parser->m_context.mode))
             parser->tokenToLowerCase($2);
         $$->setValue($2);
     }
diff --git a/Source/core/css/CSSGrammar.y.includes b/Source/core/css/CSSGrammar.y.includes
deleted file mode 100644
index 708e08b..0000000
--- a/Source/core/css/CSSGrammar.y.includes
+++ /dev/null
@@ -1,60 +0,0 @@
-%{
-
-/*
- *  Copyright (C) 2002-2003 Lars Knoll (knoll@kde.org)
- *  Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- *  Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
- *  Copyright (C) 2008 Eric Seidel <eric@webkit.org>
- *
- *  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 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
- *
- */
-
-#include "config.h"
-
-#include "CSSPropertyNames.h"
-#include "HTMLNames.h"
-#include "core/css/CSSKeyframeRule.h"
-#include "core/css/CSSKeyframesRule.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSParserMode.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSSelector.h"
-#include "core/css/CSSSelectorList.h"
-#include "core/css/MediaList.h"
-#include "core/css/MediaQueryExp.h"
-#include "core/css/StyleRule.h"
-#include "core/css/StyleSheetContents.h"
-#include "core/dom/Document.h"
-#include "wtf/FastMalloc.h"
-#include <stdlib.h>
-#include <string.h>
-
-using namespace WebCore;
-using namespace HTMLNames;
-
-#define YYMALLOC fastMalloc
-#define YYFREE fastFree
-
-#define YYENABLE_NLS 0
-#define YYLTYPE_IS_TRIVIAL 1
-#define YYMAXDEPTH 10000
-#define YYDEBUG 0
-
-#if YYDEBUG > 0
-#define YYPRINT(File,Type,Value) if (isCSSTokenAString(Type)) YYFPRINTF(File, "%s", String((Value).string).utf8().data())
-#endif
-
-%}
diff --git a/Source/core/css/CSSImageValue.cpp b/Source/core/css/CSSImageValue.cpp
index f8ee0e5..39a1b6e 100644
--- a/Source/core/css/CSSImageValue.cpp
+++ b/Source/core/css/CSSImageValue.cpp
@@ -24,6 +24,7 @@
 #include "FetchInitiatorTypeNames.h"
 #include "core/css/CSSParser.h"
 #include "core/dom/Document.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ImageResource.h"
 #include "core/fetch/ResourceFetcher.h"
@@ -67,6 +68,10 @@
         m_accessedImage = true;
 
         FetchRequest request(ResourceRequest(loader->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, options);
+
+        if (options.requestOriginPolicy == PotentiallyCrossOriginEnabled)
+            updateRequestForAccessControl(request.mutableResourceRequest(), loader->document()->securityOrigin(), options.allowCredentials);
+
         if (ResourcePtr<ImageResource> cachedImage = loader->fetchImage(request))
             m_image = StyleFetchedImage::create(cachedImage.get());
     }
diff --git a/Source/core/css/CSSKeyframeRule.cpp b/Source/core/css/CSSKeyframeRule.cpp
index 2b1a1fd..e665e9e 100644
--- a/Source/core/css/CSSKeyframeRule.cpp
+++ b/Source/core/css/CSSKeyframeRule.cpp
@@ -76,7 +76,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(CSSStrictMode).parseKeyframeKeyList(m_keyText);
+        m_keys = CSSParser(HTMLStandardMode).parseKeyframeKeyList(m_keyText);
     }
     // If an invalid key string was set, m_keys may be empty.
     ASSERT(m_keys);
diff --git a/Source/core/css/CSSMatrix.cpp b/Source/core/css/CSSMatrix.cpp
index 780feab..c4b90d7 100644
--- a/Source/core/css/CSSMatrix.cpp
+++ b/Source/core/css/CSSMatrix.cpp
@@ -49,17 +49,13 @@
     setMatrixValue(s, es);
 }
 
-CSSMatrix::~CSSMatrix()
-{
-}
-
 void CSSMatrix::setMatrixValue(const String& string, ExceptionState& es)
 {
     if (string.isEmpty())
         return;
 
     RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create();
-    if (CSSParser::parseValue(styleDeclaration.get(), CSSPropertyWebkitTransform, string, true, CSSStrictMode, 0)) {
+    if (CSSParser::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);
diff --git a/Source/core/css/CSSMatrix.h b/Source/core/css/CSSMatrix.h
index 201c234..e4b4e1f 100644
--- a/Source/core/css/CSSMatrix.h
+++ b/Source/core/css/CSSMatrix.h
@@ -35,7 +35,7 @@
 
 class ExceptionState;
 
-class CSSMatrix : public ScriptWrappable, public RefCounted<CSSMatrix> {
+class CSSMatrix FINAL : public ScriptWrappable, public RefCounted<CSSMatrix> {
 public:
     static PassRefPtr<CSSMatrix> create(const TransformationMatrix& m)
     {
@@ -46,8 +46,6 @@
         return adoptRef(new CSSMatrix(s, es));
     }
 
-    virtual ~CSSMatrix();
-
     double a() const { return m_matrix.a(); }
     double b() const { return m_matrix.b(); }
     double c() const { return m_matrix.c(); }
diff --git a/Source/core/css/CSSParser-in.cpp b/Source/core/css/CSSParser-in.cpp
index 130dce0..06a5c79 100644
--- a/Source/core/css/CSSParser-in.cpp
+++ b/Source/core/css/CSSParser-in.cpp
@@ -65,6 +65,7 @@
 #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"
 #include "core/css/MediaQueryExp.h"
 #include "core/css/Pair.h"
@@ -78,7 +79,6 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/PageConsole.h"
 #include "core/page/Settings.h"
-#include "core/platform/HashTools.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/svg/SVGParserUtilities.h"
 #include "platform/FloatConversion.h"
@@ -196,7 +196,7 @@
 
 const CSSParserContext& strictCSSParserContext()
 {
-    DEFINE_STATIC_LOCAL(CSSParserContext, strictContext, (CSSStrictMode));
+    DEFINE_STATIC_LOCAL(CSSParserContext, strictContext, (HTMLStandardMode));
     return strictContext;
 }
 
@@ -212,7 +212,7 @@
 CSSParserContext::CSSParserContext(const Document& document, const KURL& baseURL, const String& charset)
     : baseURL(baseURL.isNull() ? document.baseURL() : baseURL)
     , charset(charset)
-    , mode(document.inQuirksMode() ? CSSQuirksMode : CSSStrictMode)
+    , mode(document.inQuirksMode() ? HTMLQuirksMode : HTMLStandardMode)
     , isHTMLDocument(document.isHTMLDocument())
     , needsSiteSpecificQuirks(document.settings() ? document.settings()->needsSiteSpecificQuirks() : false)
     , useLegacyBackgroundSizeShorthandBehavior(document.settings() ? document.settings()->useLegacyBackgroundSizeShorthandBehavior() : false)
@@ -439,19 +439,19 @@
 static bool parseColorValue(MutableStylePropertySet* declaration, CSSPropertyID propertyId, const String& string, bool important, CSSParserMode cssParserMode)
 {
     ASSERT(!string.isEmpty());
-    bool strict = isStrictParserMode(cssParserMode);
+    bool quirksMode = isQuirksModeBehavior(cssParserMode);
     if (!isColorPropertyID(propertyId))
         return false;
     CSSParserString cssString;
     cssString.init(string);
     CSSValueID valueID = cssValueKeywordID(cssString);
     bool validPrimitive = false;
-    if (valueID == CSSValueWebkitText)
+    if (valueID == CSSValueWebkitText) {
         validPrimitive = true;
-    else if (valueID == CSSValueCurrentcolor)
+    } else if (valueID == CSSValueCurrentcolor) {
         validPrimitive = true;
-    else if ((valueID >= CSSValueAqua && valueID <= CSSValueWindowtext) || valueID == CSSValueMenu
-             || (valueID >= CSSValueWebkitFocusRingColor && valueID < CSSValueWebkitText && !strict)) {
+    } else if ((valueID >= CSSValueAqua && valueID <= CSSValueWindowtext) || valueID == CSSValueMenu
+        || (quirksMode && valueID >= CSSValueWebkitFocusRingColor && valueID < CSSValueWebkitText)) {
         validPrimitive = true;
     }
 
@@ -461,7 +461,7 @@
         return true;
     }
     RGBA32 color;
-    if (!CSSParser::fastParseColor(color, string, strict && string[0] != '#'))
+    if (!CSSParser::fastParseColor(color, string, !quirksMode && string[0] != '#'))
         return false;
     RefPtr<CSSValue> value = cssValuePool().createColorValue(color);
     declaration->addParsedProperty(CSSProperty(propertyId, value.release(), important));
@@ -536,8 +536,9 @@
 {
     ASSERT(!string.isEmpty());
     bool acceptsNegativeNumbers;
-    // In ViewportMode, width and height are shorthands, not simple length values.
-    if (cssParserMode == ViewportMode || !isSimpleLengthPropertyID(propertyId, acceptsNegativeNumbers))
+
+    // In @viewport, width and height are shorthands, not simple length values.
+    if (isCSSViewportParsingEnabledForMode(cssParserMode) || !isSimpleLengthPropertyID(propertyId, acceptsNegativeNumbers))
         return false;
 
     unsigned length = string.length();
@@ -553,7 +554,8 @@
     }
 
     if (unit == CSSPrimitiveValue::CSS_NUMBER) {
-        if (number && isStrictParserMode(cssParserMode))
+        bool quirksMode = isQuirksModeBehavior(cssParserMode);
+        if (number && !quirksMode)
             return false;
         unit = CSSPrimitiveValue::CSS_PX;
     }
@@ -1175,7 +1177,7 @@
     if (string.isEmpty())
         return 0;
     RefPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
-    if (!parseValue(dummyStyle.get(), CSSPropertyFontFamily, string, false, CSSQuirksMode, 0))
+    if (!parseValue(dummyStyle.get(), CSSPropertyFontFamily, string, false, HTMLQuirksMode, 0))
         return 0;
 
     RefPtr<CSSValue> fontFamily = dummyStyle->getPropertyCSSValue(CSSPropertyFontFamily);
@@ -1267,7 +1269,7 @@
     if (fastParseColor(color, string, strict))
         return true;
 
-    CSSParser parser(CSSStrictMode);
+    CSSParser parser(HTMLStandardMode);
 
     // In case the fast-path parser didn't understand the color, try the full parser.
     if (!parser.parseColor(string))
@@ -1324,7 +1326,7 @@
 {
     Document& document = element->document();
     CSSParserContext context = document.elementSheet()->contents()->parserContext();
-    context.mode = strictToCSSParserMode(element->isHTMLElement() && !document.inQuirksMode());
+    context.mode = (element->isHTMLElement() && !document.inQuirksMode()) ? HTMLStandardMode : HTMLQuirksMode;
     return CSSParser(context, UseCounter::getFrom(&document)).parseDeclaration(string, document.elementSheet()->contents());
 }
 
@@ -1429,7 +1431,7 @@
     if (unusedEntries)
         results.remove(0, unusedEntries);
 
-    CSSParserMode mode = inViewport() ? ViewportMode : m_context.mode;
+    CSSParserMode mode = inViewport() ? CSSViewportRuleMode : m_context.mode;
 
     return ImmutableStylePropertySet::create(results.data(), results.size(), mode);
 }
@@ -1542,7 +1544,7 @@
 inline bool CSSParser::shouldAcceptUnitLessValues(CSSParserValue* value, Units unitflags, CSSParserMode cssParserMode)
 {
     // Quirks mode and presentation attributes accept unit less values.
-    return (unitflags & (FLength | FAngle | FTime)) && (!value->fValue || cssParserMode == CSSQuirksMode || cssParserMode == SVGAttributeMode || cssParserMode == CSSAttributeMode);
+    return (unitflags & (FLength | FAngle | FTime)) && (!value->fValue || isUnitLessLengthParsingEnabledForMode(cssParserMode));
 }
 
 bool CSSParser::validUnit(CSSParserValue* value, Units unitflags, CSSParserMode cssParserMode, ReleaseParsedCalcValueCondition releaseCalc)
@@ -1709,7 +1711,7 @@
 
 bool CSSParser::parseValue(CSSPropertyID propId, bool important)
 {
-    if ((m_context.mode != UASheetMode && m_context.mode != CSSAttributeMode) && isInternalProperty(propId))
+    if (!isInternalPropertyAndValueParsingEnabledForMode(m_context.mode) && isInternalProperty(propId))
         return false;
 
     // We don't count the UA style sheet in our statistics.
@@ -1726,7 +1728,7 @@
 
     if (inViewport()) {
         // Allow @viewport rules from UA stylesheets even if the feature is disabled.
-        if (!RuntimeEnabledFeatures::cssViewportEnabled() && m_context.mode != UASheetMode)
+        if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode))
             return false;
 
         return parseViewportProperty(propId, important);
@@ -1861,7 +1863,7 @@
         break;
     case CSSPropertyOutlineColor:        // <color> | invert | inherit
         // Outline color has "invert" as additional keyword.
-        // Also, we want to allow the special focus color even in strict parsing mode.
+        // Also, we want to allow the special focus color even in HTML Standard parsing mode.
         if (id == CSSValueInvert || id == CSSValueWebkitFocusRingColor) {
             validPrimitive = true;
             break;
@@ -2150,7 +2152,7 @@
         if (id == CSSValueAuto)
             validPrimitive = true;
         else
-            validPrimitive = (!id && validUnit(value, FInteger, CSSQuirksMode));
+            validPrimitive = (!id && validUnit(value, FInteger, HTMLQuirksMode));
         break;
 
     case CSSPropertyLineHeight:
@@ -2201,7 +2203,7 @@
         if (id == CSSValueNormal || id == CSSValueReset || id == CSSValueDocument)
             validPrimitive = true;
         else
-            validPrimitive = (!id && validUnit(value, FNumber | FPercent | FNonNeg, CSSStrictMode));
+            validPrimitive = (!id && validUnit(value, FNumber | FPercent | FNonNeg, HTMLStandardMode));
         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.
@@ -2325,10 +2327,10 @@
         validPrimitive = validUnit(value, FNumber);
         break;
     case CSSPropertyWebkitBoxFlexGroup:
-        validPrimitive = validUnit(value, FInteger | FNonNeg, CSSStrictMode);
+        validPrimitive = validUnit(value, FInteger | FNonNeg, HTMLStandardMode);
         break;
     case CSSPropertyWebkitBoxOrdinalGroup:
-        validPrimitive = validUnit(value, FInteger | FNonNeg, CSSStrictMode) && value->fValue;
+        validPrimitive = validUnit(value, FInteger | FNonNeg, HTMLStandardMode) && value->fValue;
         break;
     case CSSPropertyWebkitFilter:
         if (id == CSSValueNone)
@@ -2370,7 +2372,7 @@
         validPrimitive = validUnit(value, FNumber | FNonNeg);
         break;
     case CSSPropertyOrder:
-        if (validUnit(value, FInteger, CSSStrictMode)) {
+        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),
@@ -2599,7 +2601,7 @@
     case CSSPropertyWebkitLineClamp:
         // When specifying number of lines, don't allow 0 as a valid value
         // When specifying either type of unit, require non-negative integers
-        validPrimitive = (!id && (value->unit == CSSPrimitiveValue::CSS_PERCENTAGE || value->fValue) && validUnit(value, FInteger | FPercent | FNonNeg, CSSQuirksMode));
+        validPrimitive = (!id && (value->unit == CSSPrimitiveValue::CSS_PERCENTAGE || value->fValue) && validUnit(value, FInteger | FPercent | FNonNeg, HTMLQuirksMode));
         break;
 
     case CSSPropertyWebkitFontSizeDelta:           // <length>
@@ -2914,9 +2916,9 @@
         // These properties should be handled before in isValidKeywordPropertyAndValue().
         ASSERT_NOT_REACHED();
         return false;
-    // Properties bellow are validated inside parseViewportProperty, because we
-    // check for parser state inViewportScope. We need to invalidate if someone
-    // adds them outside a @viewport rule.
+    // Properties below are validated inside parseViewportProperty, because we
+    // check for parser state. We need to invalidate if someone adds them outside
+    // a @viewport rule.
     case CSSPropertyMaxZoom:
     case CSSPropertyMinZoom:
     case CSSPropertyOrientation:
@@ -3295,7 +3297,7 @@
     // Always parse lengths in strict mode here, since it would be ambiguous otherwise when used in
     // the 'columns' shorthand property.
     if (value->id == CSSValueAuto
-        || (validUnit(value, FLength | FNonNeg, CSSStrictMode) && value->fValue)) {
+        || (validUnit(value, FLength | FNonNeg, HTMLStandardMode) && value->fValue)) {
         RefPtr<CSSValue> parsedValue = parseValidPrimitive(value->id, value);
         m_valueList->next();
         return parsedValue;
@@ -3307,7 +3309,7 @@
 {
     CSSParserValue* value = m_valueList->current();
     if (value->id == CSSValueAuto
-        || (!value->id && validUnit(value, FPositiveInteger, CSSQuirksMode))) {
+        || (!value->id && validUnit(value, FPositiveInteger, HTMLQuirksMode))) {
         RefPtr<CSSValue> parsedValue = parseValidPrimitive(value->id, value);
         m_valueList->next();
         return parsedValue;
@@ -4775,7 +4777,7 @@
 
     ShorthandScope scope(this, CSSPropertyGridArea);
     const StylePropertyShorthand& shorthand = gridAreaShorthand();
-    ASSERT(shorthand.length() == 4);
+    ASSERT_UNUSED(shorthand, shorthand.length() == 4);
 
     RefPtr<CSSValue> rowStartValue = parseGridPosition();
     if (!rowStartValue)
@@ -4894,7 +4896,7 @@
         arguments->next();
     }
 
-    while (CSSParserValue* argumentValue = arguments->current()) {
+    while (arguments->current()) {
         RefPtr<CSSValue> trackSize = parseGridTrackSize(*arguments);
         if (!trackSize)
             return false;
@@ -5706,7 +5708,7 @@
         addProperty(CSSPropertyFontWeight, cssValuePool().createIdentifierValue(value->id), important);
         return true;
     }
-    if (validUnit(value, FInteger | FNonNeg, CSSQuirksMode)) {
+    if (validUnit(value, FInteger | FNonNeg, HTMLQuirksMode)) {
         int weight = static_cast<int>(value->fValue);
         if (!(weight % 100) && weight >= 100 && weight <= 900) {
             addProperty(CSSPropertyFontWeight, cssValuePool().createIdentifierValue(static_cast<CSSValueID>(CSSValue100 + weight / 100 - 1)), important);
@@ -6251,9 +6253,9 @@
     CSSParserValue* v = args->current();
     Units unitType = FUnknown;
     // Get the first value and its type
-    if (validUnit(v, FInteger, CSSStrictMode))
+    if (validUnit(v, FInteger, HTMLStandardMode))
         unitType = FInteger;
-    else if (validUnit(v, FPercent, CSSStrictMode))
+    else if (validUnit(v, FPercent, HTMLStandardMode))
         unitType = FPercent;
     else
         return false;
@@ -6264,7 +6266,7 @@
         if (v->unit != CSSParserValue::Operator && v->iValue != ',')
             return false;
         v = args->next();
-        if (!validUnit(v, unitType, CSSStrictMode))
+        if (!validUnit(v, unitType, HTMLStandardMode))
             return false;
         colorArray[i] = colorIntFromValue(v);
     }
@@ -6273,7 +6275,7 @@
         if (v->unit != CSSParserValue::Operator && v->iValue != ',')
             return false;
         v = args->next();
-        if (!validUnit(v, FNumber, CSSStrictMode))
+        if (!validUnit(v, FNumber, HTMLStandardMode))
             return false;
         const double value = parsedDouble(v, ReleaseParsedCalcValue);
         // Convert the floating pointer number of alpha to an integer in the range [0, 256),
@@ -6293,7 +6295,7 @@
     CSSParserValueList* args = value->function->args.get();
     CSSParserValue* v = args->current();
     // Get the first value
-    if (!validUnit(v, FNumber, CSSStrictMode))
+    if (!validUnit(v, FNumber, HTMLStandardMode))
         return false;
     // normalize the Hue value and change it to be between 0 and 1.0
     colorArray[0] = (((static_cast<int>(parsedDouble(v, ReleaseParsedCalcValue)) % 360) + 360) % 360) / 360.0;
@@ -6302,7 +6304,7 @@
         if (v->unit != CSSParserValue::Operator && v->iValue != ',')
             return false;
         v = args->next();
-        if (!validUnit(v, FPercent, CSSStrictMode))
+        if (!validUnit(v, FPercent, HTMLStandardMode))
             return false;
         colorArray[i] = max(0.0, min(100.0, parsedDouble(v, ReleaseParsedCalcValue))) / 100.0; // needs to be value between 0 and 1.0
     }
@@ -6311,7 +6313,7 @@
         if (v->unit != CSSParserValue::Operator && v->iValue != ',')
             return false;
         v = args->next();
-        if (!validUnit(v, FNumber, CSSStrictMode))
+        if (!validUnit(v, FNumber, HTMLStandardMode))
             return false;
         colorArray[3] = max(0.0, min(1.0, parsedDouble(v, ReleaseParsedCalcValue)));
     }
@@ -6332,12 +6334,12 @@
         && value->fValue >= 0. && value->fValue < 1000000.) {
         String str = String::format("%06d", static_cast<int>((value->fValue+.5)));
         // FIXME: This should be strict parsing for SVG as well.
-        if (!fastParseColor(c, str, inStrictMode()))
+        if (!fastParseColor(c, str, !inQuirksMode()))
             return false;
     } else if (value->unit == CSSPrimitiveValue::CSS_PARSER_HEXCOLOR ||
                 value->unit == CSSPrimitiveValue::CSS_IDENT ||
                 (inQuirksMode() && value->unit == CSSPrimitiveValue::CSS_DIMENSION)) {
-        if (!fastParseColor(c, value->string, inStrictMode() && value->unit == CSSPrimitiveValue::CSS_IDENT))
+        if (!fastParseColor(c, value->string, !inQuirksMode() && value->unit == CSSPrimitiveValue::CSS_IDENT))
             return false;
     } else if (value->unit == CSSParserValue::Function &&
                 value->function->args != 0 &&
@@ -6513,13 +6515,13 @@
                 return 0;
             // The value is good.  Commit it.
             context.commitValue();
-        } else if (validUnit(val, FLength, CSSStrictMode)) {
+        } else if (validUnit(val, FLength, HTMLStandardMode)) {
             // We required a length and didn't get one. Invalid.
             if (!context.allowLength())
                 return 0;
 
             // Blur radius must be non-negative.
-            if (context.allowBlur && !validUnit(val, FLength | FNonNeg, CSSStrictMode))
+            if (context.allowBlur && !validUnit(val, FLength | FNonNeg, HTMLStandardMode))
                 return 0;
 
             // A length is allowed here.  Construct the value and add it.
@@ -6982,7 +6984,7 @@
     CSSParserValue* val;
     while ((val = m_valueList->current())) {
         // FIXME calc() http://webkit.org/b/16662 : calc is parsed but values are not created yet.
-        if (context.allowNumber() && !isCalculation(val) && validUnit(val, FInteger | FNonNeg | FPercent, CSSStrictMode)) {
+        if (context.allowNumber() && !isCalculation(val) && validUnit(val, FInteger | FNonNeg | FPercent, HTMLStandardMode)) {
             context.commitNumber(val);
         } else if (context.allowFill() && val->id == CSSValueFill)
             context.commitFill();
@@ -7095,7 +7097,7 @@
     BorderImageQuadParseContext context(this);
     CSSParserValue* val;
     while ((val = m_valueList->current())) {
-        if (context.allowNumber() && (validUnit(val, validUnits, CSSStrictMode) || val->id == CSSValueAuto)) {
+        if (context.allowNumber() && (validUnit(val, validUnits, HTMLStandardMode) || val->id == CSSValueAuto)) {
             context.commitNumber(val);
         } else if (!inShorthand()) {
             // If we're not parsing a shorthand then we are invalid.
@@ -7527,7 +7529,7 @@
 
     bool expectComma = false;
     // Look for angle.
-    if (validUnit(a, FAngle, CSSStrictMode)) {
+    if (validUnit(a, FAngle, HTMLStandardMode)) {
         result->setAngle(createPrimitiveNumericValue(a));
 
         args->next();
@@ -7712,7 +7714,7 @@
 
     bool expectComma = false;
     // Look for angle.
-    if (validUnit(a, FAngle, CSSStrictMode)) {
+    if (validUnit(a, FAngle, HTMLStandardMode)) {
         result->setAngle(createPrimitiveNumericValue(a));
 
         args->next();
@@ -8301,21 +8303,21 @@
 
         if (info.type() == CSSTransformValue::Rotate3DTransformOperation && argNumber == 3) {
             // 4th param of rotate3d() is an angle rather than a bare number, validate it as such
-            if (!validUnit(a, FAngle, CSSStrictMode))
+            if (!validUnit(a, FAngle, HTMLStandardMode))
                 return 0;
         } else if (info.type() == CSSTransformValue::Translate3DTransformOperation && argNumber == 2) {
             // 3rd param of translate3d() cannot be a percentage
-            if (!validUnit(a, FLength, CSSStrictMode))
+            if (!validUnit(a, FLength, HTMLStandardMode))
                 return 0;
         } else if (info.type() == CSSTransformValue::TranslateZTransformOperation && !argNumber) {
             // 1st param of translateZ() cannot be a percentage
-            if (!validUnit(a, FLength, CSSStrictMode))
+            if (!validUnit(a, FLength, HTMLStandardMode))
                 return 0;
         } else if (info.type() == CSSTransformValue::PerspectiveTransformOperation && !argNumber) {
             // 1st param of perspective() must be a non-negative number (deprecated) or length.
-            if (!validUnit(a, FNumber | FLength | FNonNeg, CSSStrictMode))
+            if (!validUnit(a, FNumber | FLength | FNonNeg, HTMLStandardMode))
                 return 0;
-        } else if (!validUnit(a, unit, CSSStrictMode))
+        } else if (!validUnit(a, unit, HTMLStandardMode))
             return 0;
 
         // Add the value to the current transform operation.
@@ -8401,7 +8403,7 @@
     while (true) {
         // We parse pairs <Value, Comma> at each step.
         CSSParserValue* currentParserValue = arrayArgsParserValueList->current();
-        if (!currentParserValue || !validUnit(currentParserValue, FNumber, CSSStrictMode))
+        if (!currentParserValue || !validUnit(currentParserValue, FNumber, HTMLStandardMode))
             return 0;
 
         RefPtr<CSSValue> arrayValue = cssValuePool().createValue(currentParserValue->fValue, CSSPrimitiveValue::CSS_NUMBER);
@@ -8520,7 +8522,7 @@
                 // If we hit a comma, it means that we finished this parameter's values.
                 if (isComma(arg))
                     break;
-                if (!validUnit(arg, FNumber, CSSStrictMode))
+                if (!validUnit(arg, FNumber, HTMLStandardMode))
                     return 0;
                 paramValueList->append(cssValuePool().createValue(arg->fValue, CSSPrimitiveValue::CSS_NUMBER));
                 arg = argsList->next();
@@ -8645,7 +8647,7 @@
     RefPtr<CSSValueList> meshSizeList = CSSValueList::createSpaceSeparated();
 
     for (arg = argsList->current(); arg; arg = argsList->next()) {
-        if (!validUnit(arg, FInteger | FNonNeg, CSSStrictMode))
+        if (!validUnit(arg, FInteger | FNonNeg, HTMLStandardMode))
             break;
         int integerValue = clampToInteger(arg->fValue);
         // According to the specification we can only accept positive non-zero values.
@@ -8806,7 +8808,7 @@
 
         if (args->size()) {
             CSSParserValue* value = args->current();
-            if (!validUnit(value, FNumber | FPercent | FNonNeg, CSSStrictMode))
+            if (!validUnit(value, FNumber | FPercent | FNonNeg, HTMLStandardMode))
                 return 0;
 
             double amount = value->fValue;
@@ -8830,7 +8832,7 @@
 
         if (args->size()) {
             CSSParserValue* value = args->current();
-            if (!validUnit(value, FNumber | FPercent, CSSStrictMode))
+            if (!validUnit(value, FNumber | FPercent, HTMLStandardMode))
                 return 0;
 
             filterValue->append(cssValuePool().createValue(value->fValue, static_cast<CSSPrimitiveValue::UnitTypes>(value->unit)));
@@ -8844,7 +8846,7 @@
 
         if (args->size()) {
             CSSParserValue* argument = args->current();
-            if (!validUnit(argument, FAngle, CSSStrictMode))
+            if (!validUnit(argument, FAngle, HTMLStandardMode))
                 return 0;
 
             filterValue->append(createPrimitiveNumericValue(argument));
@@ -8858,7 +8860,7 @@
 
         if (args->size()) {
             CSSParserValue* argument = args->current();
-            if (!validUnit(argument, FLength | FNonNeg, CSSStrictMode))
+            if (!validUnit(argument, FLength | FNonNeg, HTMLStandardMode))
                 return 0;
 
             filterValue->append(createPrimitiveNumericValue(argument));
@@ -10502,7 +10504,7 @@
 template <typename CharacterType>
 inline void CSSParser::detectCSSVariableDefinitionToken(int length)
 {
-    static const unsigned prefixLength = sizeof("var-") - 1;
+    static const int prefixLength = static_cast<int>(sizeof("var-") - 1);
     if (length <= prefixLength)
         return;
     CharacterType* name = tokenStart<CharacterType>();
@@ -10633,7 +10635,7 @@
         }
 
         // Use SVG parser for numbers on SVG presentation attributes.
-        if (m_context.mode == SVGAttributeMode) {
+        if (isSVGNumberParsingEnabledForMode(m_context.mode)) {
             // We need to take care of units like 'em' or 'ex'.
             SrcCharacterType* character = currentCharacter<SrcCharacterType>();
             if (isASCIIAlphaCaselessEqual(*character, 'e')) {
@@ -11707,7 +11709,7 @@
 StyleRuleBase* CSSParser::createViewportRule()
 {
     // Allow @viewport rules from UA stylesheets even if the feature is disabled.
-    if (!RuntimeEnabledFeatures::cssViewportEnabled() && m_context.mode != UASheetMode) {
+    if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode)) {
         endRuleBody(true);
         return 0;
     }
@@ -11728,7 +11730,7 @@
 
 bool CSSParser::parseViewportProperty(CSSPropertyID propId, bool important)
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || m_context.mode == UASheetMode);
+    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode));
 
     CSSParserValue* value = m_valueList->current();
     if (!value)
@@ -11788,7 +11790,7 @@
 
 bool CSSParser::parseViewportShorthand(CSSPropertyID propId, CSSPropertyID first, CSSPropertyID second, bool important)
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || m_context.mode == UASheetMode);
+    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode));
     unsigned numValues = m_valueList->size();
 
     if (numValues > 2)
@@ -11810,7 +11812,7 @@
 template <typename CharacterType>
 static CSSPropertyID cssPropertyID(const CharacterType* propertyName, unsigned length)
 {
-    char buffer[maxCSSPropertyNameLength + 1 + 1]; // 1 to turn "apple"/"khtml" into "webkit", 1 for null character
+    char buffer[maxCSSPropertyNameLength + 1]; // 1 for null character
 
     for (unsigned i = 0; i != length; ++i) {
         CharacterType c = propertyName[i];
@@ -11852,7 +11854,7 @@
 template <typename CharacterType>
 static CSSValueID cssValueKeywordID(const CharacterType* valueKeyword, unsigned length)
 {
-    char buffer[maxCSSValueKeywordLength + 1 + 1]; // 1 to turn "apple"/"khtml" into "webkit", 1 for null character
+    char buffer[maxCSSValueKeywordLength + 1]; // 1 for null character
 
     for (unsigned i = 0; i != length; ++i) {
         CharacterType c = valueKeyword[i];
@@ -11862,16 +11864,6 @@
     }
     buffer[length] = '\0';
 
-    if (buffer[0] == '-') {
-        // If the prefix is -apple- or -khtml-, change it to -webkit-.
-        // This makes the string one character longer.
-        if (hasPrefix(buffer, length, "-apple-") || hasPrefix(buffer, length, "-khtml-")) {
-            memmove(buffer + 7, buffer + 6, length + 1 - 6);
-            memcpy(buffer, "-webkit", 7);
-            ++length;
-        }
-    }
-
     const Value* hashTableEntry = findValue(buffer, length);
     return hashTableEntry ? static_cast<CSSValueID>(hashTableEntry->id) : CSSValueInvalid;
 }
diff --git a/Source/core/css/CSSParser.h b/Source/core/css/CSSParser.h
index 8ca92c9..58153a1 100644
--- a/Source/core/css/CSSParser.h
+++ b/Source/core/css/CSSParser.h
@@ -36,7 +36,7 @@
 #include "core/css/MediaQuery.h"
 #include "core/css/StylePropertySet.h"
 #include "core/page/UseCounter.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/Vector.h"
@@ -469,7 +469,7 @@
             : m_parser(parser)
             , m_mode(declaration->cssParserMode())
         {
-            if (m_mode == ViewportMode) {
+            if (isCSSViewportParsingEnabledForMode(m_mode)) {
                 ASSERT(!m_parser->inViewport());
                 m_parser->markViewportRuleBodyStart();
             }
@@ -477,7 +477,7 @@
 
         ~StyleDeclarationScope()
         {
-            if (m_mode == ViewportMode)
+            if (isCSSViewportParsingEnabledForMode(m_mode))
                 m_parser->markViewportRuleBodyEnd();
         }
 
@@ -563,8 +563,8 @@
 
     void setStyleSheet(StyleSheetContents* styleSheet) { m_styleSheet = styleSheet; }
 
-    inline bool inStrictMode() const { return isStrictParserMode(m_context.mode); }
-    inline bool inQuirksMode() const { return m_context.mode == CSSQuirksMode || m_context.mode == CSSAttributeMode; }
+    bool inQuirksMode() const { return isQuirksModeBehavior(m_context.mode); }
+    bool inViewport() const { return m_inViewport; }
 
     KURL completeURL(const String& url) const;
 
@@ -639,7 +639,6 @@
     bool parseViewportProperty(CSSPropertyID propId, bool important);
     bool parseViewportShorthand(CSSPropertyID propId, CSSPropertyID first, CSSPropertyID second, bool important);
 
-    bool inViewport() const { return m_inViewport; }
     bool m_inViewport;
 
     CSSParserLocation m_locationLabel;
diff --git a/Source/core/css/CSSParserMode.h b/Source/core/css/CSSParserMode.h
index 3914554..e093976 100644
--- a/Source/core/css/CSSParserMode.h
+++ b/Source/core/css/CSSParserMode.h
@@ -37,29 +37,55 @@
 
 class Document;
 
+// Must not grow beyond 3 bytes, due to packing in StylePropertySet.
 enum CSSParserMode {
-    CSSQuirksMode,
-    CSSStrictMode,
-    // SVG should always be in strict mode. For SVG attributes, the rules differ to strict sometimes.
+    HTMLStandardMode,
+    HTMLQuirksMode,
+    // HTML attributes are parsed in quirks mode but also allows internal properties and values.
+    HTMLAttributeMode,
+    // SVG attributes are parsed in quirks mode but rules differ slightly.
     SVGAttributeMode,
-    // CSS attribute are parsed in quirks mode. They also allow internal only properties and values.
-    CSSAttributeMode,
-    // User agent style sheet should always be in strict mode. Enables internal
-    // only properties and values.
-    UASheetMode,
-    // Parsing @viewport descriptors. Always strict. Set as mode on StylePropertySet
-    // to make sure CSSOM modifications use CSSParser::parseViewportProperty.
-    ViewportMode
+    // @viewport rules are parsed in standards mode but CSSOM modifications (via StylePropertySet)
+    // must call parseViewportProperties so needs a special mode.
+    CSSViewportRuleMode,
+    // User agent stylesheets are parsed in standards mode but also allows internal properties and values.
+    UASheetMode
 };
 
-inline CSSParserMode strictToCSSParserMode(bool inStrictMode)
+inline bool isQuirksModeBehavior(CSSParserMode mode)
 {
-    return inStrictMode ? CSSStrictMode : CSSQuirksMode;
+    return mode == HTMLQuirksMode; // || mode == HTMLAttributeMode;
 }
 
-inline bool isStrictParserMode(CSSParserMode cssParserMode)
+inline bool isUASheetBehavior(CSSParserMode mode)
 {
-    return cssParserMode != CSSQuirksMode;
+    return mode == UASheetMode;
+}
+
+inline bool isInternalPropertyAndValueParsingEnabledForMode(CSSParserMode mode)
+{
+    return mode == HTMLAttributeMode || mode == UASheetMode;
+}
+
+inline bool isUnitLessLengthParsingEnabledForMode(CSSParserMode mode)
+{
+    return mode == HTMLQuirksMode || mode == HTMLAttributeMode || mode == SVGAttributeMode;
+}
+
+inline bool isCSSViewportParsingEnabledForMode(CSSParserMode mode)
+{
+    return mode == CSSViewportRuleMode;
+}
+
+inline bool isSVGNumberParsingEnabledForMode(CSSParserMode mode)
+{
+    return mode == SVGAttributeMode;
+}
+
+inline bool isUseCounterEnabledForMode(CSSParserMode mode)
+{
+    // We don't count the UA style sheet in our statistics.
+    return mode != UASheetMode;
 }
 
 struct CSSParserContext {
diff --git a/Source/core/css/CSSPrimitiveValue.cpp b/Source/core/css/CSSPrimitiveValue.cpp
index b82a78f..2bc98a8 100644
--- a/Source/core/css/CSSPrimitiveValue.cpp
+++ b/Source/core/css/CSSPrimitiveValue.cpp
@@ -35,9 +35,9 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/Node.h"
-#include "core/platform/graphics/Color.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "platform/LayoutUnit.h"
+#include "platform/graphics/Color.h"
 #include "wtf/DecimalNumber.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/StringBuffer.h"
diff --git a/Source/core/css/CSSPrimitiveValue.h b/Source/core/css/CSSPrimitiveValue.h
index 70b4f6b..c4f2e36 100644
--- a/Source/core/css/CSSPrimitiveValue.h
+++ b/Source/core/css/CSSPrimitiveValue.h
@@ -25,7 +25,7 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "core/css/CSSValue.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/Forward.h"
 #include "wtf/MathExtras.h"
 #include "wtf/PassRefPtr.h"
diff --git a/Source/core/css/CSSPrimitiveValueMappings.h b/Source/core/css/CSSPrimitiveValueMappings.h
index 41cf0a7..d169e38 100644
--- a/Source/core/css/CSSPrimitiveValueMappings.h
+++ b/Source/core/css/CSSPrimitiveValueMappings.h
@@ -34,16 +34,16 @@
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSReflectionDirection.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/FontSmoothingMode.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/ThemeTypes.h"
 #include "core/platform/graphics/Path.h"
-#include "core/platform/graphics/TextRenderingMode.h"
 #include "core/rendering/style/LineClampValue.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "core/rendering/style/SVGRenderStyleDefs.h"
 #include "platform/Length.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/fonts/FontSmoothingMode.h"
+#include "platform/fonts/TextRenderingMode.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "platform/text/TextDirection.h"
 #include "platform/text/UnicodeBidi.h"
 #include "platform/text/WritingMode.h"
diff --git a/Source/core/css/CSSProperties.in b/Source/core/css/CSSProperties.in
index d2c81a9..f6eb0ee 100644
--- a/Source/core/css/CSSProperties.in
+++ b/Source/core/css/CSSProperties.in
@@ -39,6 +39,7 @@
 border-top-style type_name=EBorderStyle, initial=initialBorderStyle
 border-top-width type_name=unsigned, initial=initialBorderWidth, converter=convertLineWidth<unsigned>
 bottom type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
+box-shadow converter=convertShadow
 box-sizing
 caption-side
 clear
@@ -124,6 +125,7 @@
 text-justify type_name=TextJustify
 text-overflow type_name=TextOverflow
 text-rendering custom_all
+text-shadow converter=convertShadow
 text-transform
 top type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
 touch-action type_name=TouchAction, initial=initialTouchAction
@@ -169,6 +171,7 @@
 -webkit-box-ordinal-group type_name=unsigned int
 -webkit-box-orient
 -webkit-box-pack
+-webkit-box-shadow use_handlers_for=CSSPropertyBoxShadow
 -webkit-clip-path custom_value
 -webkit-column-axis type_name=ColumnAxis
 -webkit-column-break-after type_name=EPageBreak, initial=initialPageBreak
diff --git a/Source/core/css/CSSSegmentedFontFace.cpp b/Source/core/css/CSSSegmentedFontFace.cpp
index 127d69c..7db0e79 100644
--- a/Source/core/css/CSSSegmentedFontFace.cpp
+++ b/Source/core/css/CSSSegmentedFontFace.cpp
@@ -29,9 +29,9 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSFontFace.h"
 #include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/SegmentedFontData.h"
 #include "core/platform/graphics/SimpleFontData.h"
+#include "platform/fonts/FontDescription.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSSegmentedFontFace.h b/Source/core/css/CSSSegmentedFontFace.h
index 7cfa61d..7c9b0d2 100644
--- a/Source/core/css/CSSSegmentedFontFace.h
+++ b/Source/core/css/CSSSegmentedFontFace.h
@@ -26,7 +26,7 @@
 #ifndef CSSSegmentedFontFace_h
 #define CSSSegmentedFontFace_h
 
-#include "core/platform/graphics/FontTraitsMask.h"
+#include "platform/fonts/FontTraitsMask.h"
 #include "wtf/HashMap.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
diff --git a/Source/core/css/CSSSegmentedFontFaceCache.cpp b/Source/core/css/CSSSegmentedFontFaceCache.cpp
index 160bcdf..84ecc07 100644
--- a/Source/core/css/CSSSegmentedFontFaceCache.cpp
+++ b/Source/core/css/CSSSegmentedFontFaceCache.cpp
@@ -41,15 +41,12 @@
 #include "core/frame/Frame.h"
 #include "core/page/Settings.h"
 #include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/SimpleFontData.h"
+#include "platform/fonts/FontDescription.h"
 #include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
-using namespace FontFamilyNames;
-
-
 CSSSegmentedFontFaceCache::CSSSegmentedFontFaceCache()
     : m_version(0)
 {
@@ -115,19 +112,19 @@
 #if OS(ANDROID)
     genericFamily = FontCache::getGenericFamilyNameForScript(familyName, script);
 #else
-    if (familyName == serifFamily)
+    if (familyName == FontFamilyNames::webkit_serif)
         genericFamily = settings->serifFontFamily(script);
-    else if (familyName == sansSerifFamily)
+    else if (familyName == FontFamilyNames::webkit_sans_serif)
         genericFamily = settings->sansSerifFontFamily(script);
-    else if (familyName == cursiveFamily)
+    else if (familyName == FontFamilyNames::webkit_cursive)
         genericFamily = settings->cursiveFontFamily(script);
-    else if (familyName == fantasyFamily)
+    else if (familyName == FontFamilyNames::webkit_fantasy)
         genericFamily = settings->fantasyFontFamily(script);
-    else if (familyName == monospaceFamily)
+    else if (familyName == FontFamilyNames::webkit_monospace)
         genericFamily = settings->fixedFontFamily(script);
-    else if (familyName == pictographFamily)
+    else if (familyName == FontFamilyNames::webkit_pictograph)
         genericFamily = settings->pictographFontFamily(script);
-    else if (familyName == standardFamily)
+    else if (familyName == FontFamilyNames::webkit_standard)
         genericFamily = settings->standardFontFamily(script);
 #endif
 
diff --git a/Source/core/css/CSSSelector.cpp b/Source/core/css/CSSSelector.cpp
index b2ea820..2d5c336 100644
--- a/Source/core/css/CSSSelector.cpp
+++ b/Source/core/css/CSSSelector.cpp
@@ -280,7 +280,6 @@
     DEFINE_STATIC_LOCAL(AtomicString, valid, ("valid", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, invalid, ("invalid", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, drag, ("-webkit-drag", AtomicString::ConstructFromLiteral));
-    DEFINE_STATIC_LOCAL(AtomicString, dragAlias, ("-khtml-drag", AtomicString::ConstructFromLiteral)); // was documented with this name in Apple documentation, so keep an alia
     DEFINE_STATIC_LOCAL(AtomicString, empty, ("empty", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, enabled, ("enabled", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, firstChild, ("first-child", AtomicString::ConstructFromLiteral));
@@ -366,7 +365,6 @@
         nameToPseudoType->set(valid.impl(), CSSSelector::PseudoValid);
         nameToPseudoType->set(invalid.impl(), CSSSelector::PseudoInvalid);
         nameToPseudoType->set(drag.impl(), CSSSelector::PseudoDrag);
-        nameToPseudoType->set(dragAlias.impl(), CSSSelector::PseudoDrag);
         nameToPseudoType->set(enabled.impl(), CSSSelector::PseudoEnabled);
         nameToPseudoType->set(empty.impl(), CSSSelector::PseudoEmpty);
         nameToPseudoType->set(firstChild.impl(), CSSSelector::PseudoFirstChild);
@@ -736,6 +734,10 @@
             if (cs->relationIsAffectedByPseudoContent() && tagHistory->pseudoType() != CSSSelector::PseudoContent)
                 return tagHistory->selectorText("::-webkit-distributed(> " + str.toString() + rightSide + ")");
             return tagHistory->selectorText(" > " + str.toString() + rightSide);
+        case CSSSelector::ChildTree:
+            return tagHistory->selectorText(" ^ " + str.toString() + rightSide);
+        case CSSSelector::DescendantTree:
+            return tagHistory->selectorText(" ^^ " + str.toString() + rightSide);
         case CSSSelector::DirectAdjacent:
             return tagHistory->selectorText(" + " + str.toString() + rightSide);
         case CSSSelector::IndirectAdjacent:
diff --git a/Source/core/css/CSSSelector.h b/Source/core/css/CSSSelector.h
index 3f8b7e8..8897261 100644
--- a/Source/core/css/CSSSelector.h
+++ b/Source/core/css/CSSSelector.h
@@ -76,7 +76,10 @@
             DirectAdjacent,
             IndirectAdjacent,
             SubSelector,
-            ShadowPseudo
+            ShadowPseudo,
+            // FIXME: rename ChildTree and DescendantTree when the spec for this is written down.
+            ChildTree,
+            DescendantTree
         };
 
         enum PseudoType {
@@ -218,6 +221,7 @@
         bool matchesPseudoElement() const;
         bool isUnknownPseudoElement() const;
         bool isCustomPseudoElement() const;
+        bool isDirectAdjacentSelector() const { return m_relation == DirectAdjacent; }
         bool isSiblingSelector() const;
         bool isAttributeSelector() const;
         bool isDistributedPseudoElement() const;
diff --git a/Source/core/css/CSSSelectorList.cpp b/Source/core/css/CSSSelectorList.cpp
index 30ac8eb..3f183e1 100644
--- a/Source/core/css/CSSSelectorList.cpp
+++ b/Source/core/css/CSSSelectorList.cpp
@@ -179,4 +179,18 @@
     return forEachTagSelector(functor, selectorAt(index));
 }
 
+class SelectorHasCombinatorCrossingTreeBoundary {
+public:
+    bool operator()(const CSSSelector* selector)
+    {
+        return selector->relation() == CSSSelector::ChildTree || selector->relation() == CSSSelector::DescendantTree;
+    }
+};
+
+bool CSSSelectorList::hasCombinatorCrossingTreeBoundaryAt(size_t index) const
+{
+    SelectorHasCombinatorCrossingTreeBoundary functor;
+    return forEachTagSelector(functor, selectorAt(index));
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSSelectorList.h b/Source/core/css/CSSSelectorList.h
index 562e649..320de3b 100644
--- a/Source/core/css/CSSSelectorList.h
+++ b/Source/core/css/CSSSelectorList.h
@@ -61,6 +61,7 @@
     bool selectorsNeedNamespaceResolution();
 
     bool hasShadowDistributedAt(size_t index) const;
+    bool hasCombinatorCrossingTreeBoundaryAt(size_t index) const;
 
     String selectorsText() const;
 
diff --git a/Source/core/css/CSSStyleSheet.cpp b/Source/core/css/CSSStyleSheet.cpp
index 9737560..02e6f54 100644
--- a/Source/core/css/CSSStyleSheet.cpp
+++ b/Source/core/css/CSSStyleSheet.cpp
@@ -28,6 +28,7 @@
 #include "core/css/CSSImportRule.h"
 #include "core/css/CSSParser.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"
@@ -117,12 +118,39 @@
         if (m_childRuleCSSOMWrappers[i])
             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()
 {
     // If we are the only client it is safe to mutate.
@@ -133,6 +161,9 @@
     // 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();
@@ -141,7 +172,7 @@
     m_contents->setMutable();
 
     // Any existing CSSOM wrappers need to be connected to the copied child rules.
-    reattachChildRuleCSSOMWrappers();
+    reattachChildRuleCSSOMWrappers(indices);
 }
 
 void CSSStyleSheet::didMutateRules()
@@ -164,8 +195,17 @@
     owner->modifiedStyleSheet(this, RecalcStyleDeferred, updateMode);
 }
 
-void CSSStyleSheet::reattachChildRuleCSSOMWrappers()
+void CSSStyleSheet::registerExtraChildRuleCSSOMWrapper(PassRefPtr<CSSRule> rule)
 {
+    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;
diff --git a/Source/core/css/CSSStyleSheet.h b/Source/core/css/CSSStyleSheet.h
index c0eeb6f..6740a6b 100644
--- a/Source/core/css/CSSStyleSheet.h
+++ b/Source/core/css/CSSStyleSheet.h
@@ -103,7 +103,8 @@
     void didMutate(StyleSheetUpdateType = PartialRuleUpdate);
 
     void clearChildRuleCSSOMWrappers();
-    void reattachChildRuleCSSOMWrappers();
+
+    void registerExtraChildRuleCSSOMWrapper(PassRefPtr<CSSRule>);
 
     StyleSheetContents* contents() const { return m_contents.get(); }
 
@@ -117,6 +118,9 @@
     virtual bool isCSSStyleSheet() const { return true; }
     virtual String type() const { return "text/css"; }
 
+    void extraCSSOMWrapperIndices(Vector<unsigned>& indices);
+    void reattachChildRuleCSSOMWrappers(const Vector<unsigned>& extraCSSOMWrapperIndices);
+
     bool canAccessRules() const;
 
     RefPtr<StyleSheetContents> m_contents;
@@ -132,6 +136,9 @@
 
     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/CSSToStyleMap.cpp b/Source/core/css/CSSToStyleMap.cpp
index 4dacaa7..180d310 100644
--- a/Source/core/css/CSSToStyleMap.cpp
+++ b/Source/core/css/CSSToStyleMap.cpp
@@ -227,11 +227,6 @@
 
 void CSSToStyleMap::mapFillXPosition(CSSPropertyID propertyID, FillLayer* layer, CSSValue* value) const
 {
-    if (value->isInitialValue()) {
-        layer->setXPosition(FillLayer::initialFillXPosition(layer->type()));
-        return;
-    }
-
     if (!value->isPrimitiveValue())
         return;
 
@@ -263,11 +258,6 @@
 
 void CSSToStyleMap::mapFillYPosition(CSSPropertyID propertyID, FillLayer* layer, CSSValue* value) const
 {
-    if (value->isInitialValue()) {
-        layer->setYPosition(FillLayer::initialFillYPosition(layer->type()));
-        return;
-    }
-
     if (!value->isPrimitiveValue())
         return;
 
diff --git a/Source/core/css/CSSValueKeywords.in b/Source/core/css/CSSValueKeywords.in
index 7ae5f27..586cb3d 100644
--- a/Source/core/css/CSSValueKeywords.in
+++ b/Source/core/css/CSSValueKeywords.in
@@ -3,8 +3,8 @@
 //
 
 // The mode argument is used to limit the keyword to be used only for certain
-// CSSParserModes. Values that have the prefix -internal- are automatically
-// only for UASheetMode or CSSAttributeMode.
+// CSSParserModes. Values that have the prefix -internal- are only allowed by
+// CSSParserModes listed in allowInternalPropertyAndValue()
 
 inherit
 initial
diff --git a/Source/core/css/CSSVariablesMap.h b/Source/core/css/CSSVariablesMap.h
index 3bd9460..8f1ef88 100644
--- a/Source/core/css/CSSVariablesMap.h
+++ b/Source/core/css/CSSVariablesMap.h
@@ -39,10 +39,8 @@
 class CSSVariablesIterator;
 class ExceptionState;
 
-class CSSVariablesMap : public RefCounted<CSSVariablesMap> {
+class CSSVariablesMap FINAL : public RefCounted<CSSVariablesMap> {
 public:
-    virtual ~CSSVariablesMap() { }
-
     static PassRefPtr<CSSVariablesMap> create(CSSStyleDeclaration* styleDeclaration)
     {
         return adoptRef(new CSSVariablesMap(styleDeclaration));
diff --git a/Source/core/css/DOMWindowCSS.cpp b/Source/core/css/DOMWindowCSS.cpp
index b417c4a..69b7a32 100644
--- a/Source/core/css/DOMWindowCSS.cpp
+++ b/Source/core/css/DOMWindowCSS.cpp
@@ -75,12 +75,12 @@
         return false;
 
     RefPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
-    return CSSParser::parseValue(dummyStyle.get(), propertyID, normalizedValue, false, CSSStrictMode, 0);
+    return CSSParser::parseValue(dummyStyle.get(), propertyID, normalizedValue, false, HTMLStandardMode, 0);
 }
 
 bool DOMWindowCSS::supports(const String& conditionText) const
 {
-    CSSParserContext context(CSSStrictMode);
+    CSSParserContext context(HTMLStandardMode);
     CSSParser parser(context);
     return parser.parseSupportsCondition(conditionText);
 }
diff --git a/Source/core/css/DocumentFontFaceSet.cpp b/Source/core/css/DocumentFontFaceSet.cpp
new file mode 100644
index 0000000..408668f
--- /dev/null
+++ b/Source/core/css/DocumentFontFaceSet.cpp
@@ -0,0 +1,38 @@
+/*
+ * 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 "core/css/DocumentFontFaceSet.h"
+
+#include "core/css/FontFaceSet.h"
+
+namespace WebCore {
+
+PassRefPtr<FontFaceSet> DocumentFontFaceSet::fonts(Document* document)
+{
+    return FontFaceSet::from(document);
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/DocumentFontFaceSet.h b/Source/core/css/DocumentFontFaceSet.h
new file mode 100644
index 0000000..910d878
--- /dev/null
+++ b/Source/core/css/DocumentFontFaceSet.h
@@ -0,0 +1,43 @@
+/*
+ * 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 DocumentFontFaceSet_h
+#define DocumentFontFaceSet_h
+
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class Document;
+class FontFaceSet;
+
+class DocumentFontFaceSet {
+public:
+    static PassRefPtr<FontFaceSet> fonts(Document*);
+};
+
+} // namespace WebCore
+
+#endif // DocumentFontFaceSet_h
diff --git a/Source/core/page/RuntimeEnabledFeaturesCustom.cpp b/Source/core/css/DocumentFontFaceSet.idl
similarity index 85%
rename from Source/core/page/RuntimeEnabledFeaturesCustom.cpp
rename to Source/core/css/DocumentFontFaceSet.idl
index 2ac204d..820fdc8 100644
--- a/Source/core/page/RuntimeEnabledFeaturesCustom.cpp
+++ b/Source/core/css/DocumentFontFaceSet.idl
@@ -28,16 +28,6 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "RuntimeEnabledFeatures.h"
-
-#include "core/workers/SharedWorkerRepository.h"
-
-namespace WebCore {
-
-bool RuntimeEnabledFeatures::sharedWorkerEnabled()
-{
-    return SharedWorkerRepository::isAvailable();
-}
-
-} // namespace WebCore
+partial interface Document {
+    [RuntimeEnabled=FontLoadEvents] readonly attribute FontFaceSet fonts;
+};
diff --git a/Source/core/css/DocumentRuleSets.cpp b/Source/core/css/DocumentRuleSets.cpp
index 00df1c0..d8811bc 100644
--- a/Source/core/css/DocumentRuleSets.cpp
+++ b/Source/core/css/DocumentRuleSets.cpp
@@ -38,26 +38,30 @@
 
 namespace WebCore {
 
-void ShadowDistributedRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags addRuleFlags)
+void TreeBoundaryCrossingRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags addRuleFlags)
 {
-    if (m_shadowDistributedRuleSetMap.contains(scopingNode))
-        m_shadowDistributedRuleSetMap.get(scopingNode)->addRule(rule, selectorIndex, addRuleFlags);
+    if (m_treeBoundaryCrossingRuleSetMap.contains(scopingNode))
+        m_treeBoundaryCrossingRuleSetMap.get(scopingNode)->addRule(rule, selectorIndex, addRuleFlags);
     else {
         OwnPtr<RuleSet> ruleSetForScope = RuleSet::create();
         ruleSetForScope->addRule(rule, selectorIndex, addRuleFlags);
-        m_shadowDistributedRuleSetMap.add(scopingNode, ruleSetForScope.release());
+        m_treeBoundaryCrossingRuleSetMap.add(scopingNode, ruleSetForScope.release());
+        m_scopingNodes.add(scopingNode);
     }
 }
 
-void ShadowDistributedRules::reset(const ContainerNode* scopingNode)
+void TreeBoundaryCrossingRules::reset(const ContainerNode* scopingNode)
 {
-    m_shadowDistributedRuleSetMap.remove(scopingNode);
+    m_treeBoundaryCrossingRuleSetMap.remove(scopingNode);
+    m_scopingNodes.remove(scopingNode);
 }
 
-void ShadowDistributedRules::collectFeaturesTo(RuleFeatureSet& features)
+void TreeBoundaryCrossingRules::collectFeaturesTo(RuleFeatureSet& features)
 {
-    for (ShadowDistributedRuleSetMap::iterator it = m_shadowDistributedRuleSetMap.begin(); it != m_shadowDistributedRuleSetMap.end(); ++it)
-        features.add(it->value->features());
+    for (TreeBoundaryCrossingRuleSetMap::iterator::Values it = m_treeBoundaryCrossingRuleSetMap.values().begin(); it != m_treeBoundaryCrossingRuleSetMap.values().end(); ++it) {
+        RuleSet* ruleSet = it->get();
+        features.add(ruleSet->features());
+    }
 }
 
 DocumentRuleSets::DocumentRuleSets()
@@ -95,7 +99,7 @@
 
 void DocumentRuleSets::resetAuthorStyle()
 {
-    m_shadowDistributedRules.clear();
+    m_treeBoundaryCrossingRules.clear();
 }
 
 void DocumentRuleSets::collectFeaturesTo(RuleFeatureSet& features, bool isViewSource)
@@ -112,7 +116,7 @@
     if (m_userStyle)
         features.add(m_userStyle->features());
 
-    m_shadowDistributedRules.collectFeaturesTo(features);
+    m_treeBoundaryCrossingRules.collectFeaturesTo(features);
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/DocumentRuleSets.h b/Source/core/css/DocumentRuleSets.h
index 3b38ac5..3bec3e9 100644
--- a/Source/core/css/DocumentRuleSets.h
+++ b/Source/core/css/DocumentRuleSets.h
@@ -25,6 +25,7 @@
 
 #include "core/css/RuleFeature.h"
 #include "core/css/RuleSet.h"
+#include "core/dom/DocumentOrderedList.h"
 
 #include "wtf/OwnPtr.h"
 #include "wtf/RefPtr.h"
@@ -40,21 +41,22 @@
 class RuleSet;
 class StyleEngine;
 
-class ShadowDistributedRules {
+class TreeBoundaryCrossingRules {
 public:
     void addRule(StyleRule*, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags);
-    void clear() { m_shadowDistributedRuleSetMap.clear(); }
+    void clear() { m_treeBoundaryCrossingRuleSetMap.clear(); }
     void reset(const ContainerNode* scopingNode);
-    bool isEmpty() const { return m_shadowDistributedRuleSetMap.isEmpty(); }
+    bool isEmpty() const { return m_treeBoundaryCrossingRuleSetMap.isEmpty(); }
     void collectFeaturesTo(RuleFeatureSet&);
 
-    typedef HashMap<const ContainerNode*, OwnPtr<RuleSet> >::iterator iterator;
-    iterator begin() { return m_shadowDistributedRuleSetMap.begin(); }
-    iterator end() { return m_shadowDistributedRuleSetMap.end(); }
+    DocumentOrderedList::iterator begin() { return m_scopingNodes.begin(); }
+    DocumentOrderedList::iterator end() { return m_scopingNodes.end(); }
+    RuleSet* ruleSetScopedBy(const ContainerNode* scopingNode) { return m_treeBoundaryCrossingRuleSetMap.get(scopingNode); }
 
 private:
-    typedef HashMap<const ContainerNode*, OwnPtr<RuleSet> > ShadowDistributedRuleSetMap;
-    ShadowDistributedRuleSetMap m_shadowDistributedRuleSetMap;
+    DocumentOrderedList m_scopingNodes;
+    typedef HashMap<const ContainerNode*, OwnPtr<RuleSet> > TreeBoundaryCrossingRuleSetMap;
+    TreeBoundaryCrossingRuleSetMap m_treeBoundaryCrossingRuleSetMap;
 };
 
 class DocumentRuleSets {
@@ -67,13 +69,13 @@
     void resetAuthorStyle();
     void collectFeaturesTo(RuleFeatureSet&, bool isViewSource);
 
-    ShadowDistributedRules& shadowDistributedRules() { return m_shadowDistributedRules; }
+    TreeBoundaryCrossingRules& treeBoundaryCrossingRules() { return m_treeBoundaryCrossingRules; }
 
 private:
     void collectRulesFromUserStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&, RuleSet& userStyle, const MediaQueryEvaluator&, StyleResolver&);
     void collectRulesFromWatchedSelectors(const Vector<RefPtr<StyleRule> >&, RuleSet& userStyle);
     OwnPtr<RuleSet> m_userStyle;
-    ShadowDistributedRules m_shadowDistributedRules;
+    TreeBoundaryCrossingRules m_treeBoundaryCrossingRules;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/ElementRuleCollector.cpp b/Source/core/css/ElementRuleCollector.cpp
index deff32a..9f7c998 100644
--- a/Source/core/css/ElementRuleCollector.cpp
+++ b/Source/core/css/ElementRuleCollector.cpp
@@ -31,6 +31,7 @@
 
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSSelector.h"
+#include "core/css/CSSStyleRule.h"
 #include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/css/StylePropertySet.h"
@@ -41,7 +42,7 @@
 namespace WebCore {
 
 ElementRuleCollector::ElementRuleCollector(const ElementResolveContext& context,
-    const SelectorFilter& filter, RenderStyle* style)
+    const SelectorFilter& filter, RenderStyle* style, ShouldIncludeStyleSheetInCSSOMWrapper includeStyleSheet)
     : m_context(context)
     , m_selectorFilter(filter)
     , m_style(style)
@@ -51,6 +52,7 @@
     , m_canUseFastReject(m_selectorFilter.parentStackIsConsistent(context.parentNode()))
     , m_sameOriginOnly(false)
     , m_matchingUARules(false)
+    , m_includeStyleSheet(includeStyleSheet)
 { }
 
 ElementRuleCollector::~ElementRuleCollector()
@@ -178,6 +180,38 @@
     }
 }
 
+
+static CSSStyleSheet* findStyleSheet(StyleEngine* styleEngine, StyleRule* rule)
+{
+    // 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;
+            CSSStyleRule* cssStyleRule = toCSSStyleRule(cssRule);
+            if (cssStyleRule->styleRule() == rule)
+                return sheet;
+        }
+    }
+    return 0;
+}
+
+void ElementRuleCollector::appendCSSOMWrapperForRule(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);
+    ensureRuleList()->rules().append(cssRule);
+}
+
 void ElementRuleCollector::sortAndTransferMatchedRules()
 {
     if (!m_matchedRules || m_matchedRules->isEmpty())
@@ -187,8 +221,9 @@
 
     Vector<MatchedRule, 32>& matchedRules = *m_matchedRules;
     if (m_mode == SelectorChecker::CollectingRules) {
-        for (unsigned i = 0; i < matchedRules.size(); ++i)
-            ensureRuleList()->rules().append(matchedRules[i].ruleData()->rule()->createCSSOMWrapper());
+        for (unsigned i = 0; i < matchedRules.size(); ++i) {
+            appendCSSOMWrapperForRule(matchedRules[i].ruleData()->rule());
+        }
         return;
     }
 
@@ -206,7 +241,8 @@
 {
     // They can't match because the fast path uses a pool of tag/class/ids, collected from
     // elements in that tree and those will never match the host, since it's in a different pool.
-    if (ruleData.hasFastCheckableSelector() && SelectorChecker::isHostInItsShadowTree(m_context.element(), behaviorAtBoundary, scope)) {
+    // So when adding scoped rules to RuleSet, RuleCanUseFastCheckSelector is not used.
+    if (ruleData.hasFastCheckableSelector()) {
         // We know this selector does not include any pseudo elements.
         if (m_pseudoStyleRequest.pseudoId != NOPSEUDO)
             return false;
diff --git a/Source/core/css/ElementRuleCollector.h b/Source/core/css/ElementRuleCollector.h
index bf83216..8a540d9 100644
--- a/Source/core/css/ElementRuleCollector.h
+++ b/Source/core/css/ElementRuleCollector.h
@@ -27,6 +27,7 @@
 #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"
 
@@ -76,7 +77,7 @@
 class ElementRuleCollector {
     WTF_MAKE_NONCOPYABLE(ElementRuleCollector);
 public:
-    ElementRuleCollector(const ElementResolveContext&, const SelectorFilter&, RenderStyle* = 0);
+    ElementRuleCollector(const ElementResolveContext&, const SelectorFilter&, RenderStyle* = 0, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
     ~ElementRuleCollector();
 
     void setCanUseFastReject(bool canUseFastReject) { m_canUseFastReject = canUseFastReject; }
@@ -109,6 +110,8 @@
     void collectMatchingRulesForList(const RuleData*, SelectorChecker::BehaviorAtBoundary, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
     bool ruleMatches(const RuleData&, const ContainerNode* scope, PseudoId&, SelectorChecker::BehaviorAtBoundary);
 
+    void appendCSSOMWrapperForRule(StyleRule*);
+
     void sortMatchedRules();
     void addMatchedRule(const RuleData*, CascadeScope, CascadeOrder);
 
@@ -125,6 +128,7 @@
     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 b462bb1..c7018f8 100644
--- a/Source/core/css/FontFace.cpp
+++ b/Source/core/css/FontFace.cpp
@@ -47,8 +47,8 @@
 #include "core/dom/Document.h"
 #include "core/frame/Frame.h"
 #include "core/page/Settings.h"
-#include "core/platform/graphics/FontTraitsMask.h"
 #include "core/svg/SVGFontFaceElement.h"
+#include "platform/fonts/FontTraitsMask.h"
 
 namespace WebCore {
 
@@ -57,7 +57,7 @@
     if (s.isEmpty())
         return 0;
     RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
-    CSSParser::parseValue(parsedStyle.get(), propertyID, s, true, CSSStrictMode, 0);
+    CSSParser::parseValue(parsedStyle.get(), propertyID, s, true, HTMLStandardMode, 0);
     return parsedStyle->getPropertyCSSValue(propertyID);
 }
 
@@ -261,22 +261,22 @@
         // defining what font to use for those types.
         switch (familyValue->getValueID()) {
         case CSSValueSerif:
-            family =  FontFamilyNames::serifFamily;
+            family =  FontFamilyNames::webkit_serif;
             break;
         case CSSValueSansSerif:
-            family =  FontFamilyNames::sansSerifFamily;
+            family =  FontFamilyNames::webkit_sans_serif;
             break;
         case CSSValueCursive:
-            family =  FontFamilyNames::cursiveFamily;
+            family =  FontFamilyNames::webkit_cursive;
             break;
         case CSSValueFantasy:
-            family =  FontFamilyNames::fantasyFamily;
+            family =  FontFamilyNames::webkit_fantasy;
             break;
         case CSSValueMonospace:
-            family =  FontFamilyNames::monospaceFamily;
+            family =  FontFamilyNames::webkit_monospace;
             break;
         case CSSValueWebkitPictograph:
-            family =  FontFamilyNames::pictographFamily;
+            family =  FontFamilyNames::webkit_pictograph;
             break;
         default:
             return false;
diff --git a/Source/core/css/FontFaceSet.cpp b/Source/core/css/FontFaceSet.cpp
index b0c6b33..f7dfa54 100644
--- a/Source/core/css/FontFaceSet.cpp
+++ b/Source/core/css/FontFaceSet.cpp
@@ -41,12 +41,12 @@
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/frame/FrameView.h"
-#include "core/platform/HistogramSupport.h"
+#include "public/platform/Platform.h"
 
 namespace WebCore {
 
 static const int defaultFontSize = 10;
-static const char* const defaultFontFamily = "sans-serif";
+static const char defaultFontFamily[] = "sans-serif";
 
 class LoadFontPromiseResolver : public CSSSegmentedFontFace::LoadFontCallback {
 public:
@@ -84,7 +84,7 @@
     if (m_numLoading || !document)
         return;
 
-    document->fonts()->scheduleResolve(this);
+    FontFaceSet::from(document)->scheduleResolve(this);
 }
 
 void LoadFontPromiseResolver::error(Document* document)
@@ -137,8 +137,7 @@
 FontFaceSet::FontFaceSet(Document* document)
     : ActiveDOMObject(document)
     , m_loadingCount(0)
-    , m_shouldFireDoneEvent(false)
-    , m_timer(this, &FontFaceSet::timerFired)
+    , m_asyncRunner(this, &FontFaceSet::handlePendingEventsAndPromises)
 {
     suspendIfNeeded();
 }
@@ -166,7 +165,14 @@
 {
     DEFINE_STATIC_LOCAL(AtomicString, loading, ("loading", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, loaded, ("loaded", AtomicString::ConstructFromLiteral));
-    return (m_loadingCount > 0 || m_shouldFireDoneEvent) ? loading : loaded;
+    return (m_loadingCount > 0 || hasLoadedFonts()) ? loading : loaded;
+}
+
+void FontFaceSet::handlePendingEventsAndPromisesSoon()
+{
+    // setPendingActivity() is unnecessary because m_asyncRunner will be
+    // automatically stopped on destruction.
+    m_asyncRunner.runAsync();
 }
 
 void FontFaceSet::didLayout()
@@ -176,13 +182,12 @@
         m_histogram.record();
     if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
         return;
-    if (m_loadingCount || (!m_shouldFireDoneEvent && m_readyResolvers.isEmpty()))
+    if (m_loadingCount || (!hasLoadedFonts() && m_readyResolvers.isEmpty()))
         return;
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
+    handlePendingEventsAndPromisesSoon();
 }
 
-void FontFaceSet::timerFired(Timer<FontFaceSet>*)
+void FontFaceSet::handlePendingEventsAndPromises()
 {
     firePendingEvents();
     resolvePendingLoadPromises();
@@ -192,8 +197,7 @@
 void FontFaceSet::scheduleEvent(PassRefPtr<Event> event)
 {
     m_pendingEvents.append(event);
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
+    handlePendingEventsAndPromisesSoon();
 }
 
 void FontFaceSet::firePendingEvents()
@@ -207,11 +211,25 @@
         dispatchEvent(pendingEvents[index].release());
 }
 
+void FontFaceSet::suspend()
+{
+    m_asyncRunner.suspend();
+}
+
+void FontFaceSet::resume()
+{
+    m_asyncRunner.resume();
+}
+
+void FontFaceSet::stop()
+{
+    m_asyncRunner.stop();
+}
+
 void FontFaceSet::scheduleResolve(LoadFontPromiseResolver* resolver)
 {
     m_pendingLoadResolvers.append(resolver);
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
+    handlePendingEventsAndPromisesSoon();
 }
 
 void FontFaceSet::resolvePendingLoadPromises()
@@ -231,10 +249,9 @@
     if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
         return;
 
-    ++m_loadingCount;
-    if (m_loadingCount == 1 && !m_shouldFireDoneEvent)
+    if (!m_loadingCount && !hasLoadedFonts())
         scheduleEvent(CSSFontFaceLoadEvent::createForFontFaces(EventTypeNames::loading));
-    m_shouldFireDoneEvent = false;
+    ++m_loadingCount;
 }
 
 void FontFaceSet::fontLoaded(FontFace* fontFace)
@@ -257,12 +274,8 @@
 {
     ASSERT(m_loadingCount > 0);
     --m_loadingCount;
-    if (!m_loadingCount) {
-        ASSERT(!m_shouldFireDoneEvent);
-        m_shouldFireDoneEvent = true;
-        if (!m_timer.isActive())
-            m_timer.startOneShot(0);
-    }
+    if (!m_loadingCount)
+        handlePendingEventsAndPromisesSoon();
 }
 
 ScriptPromise FontFaceSet::ready()
@@ -270,8 +283,7 @@
     ScriptPromise promise = ScriptPromise::createPending(executionContext());
     OwnPtr<FontsReadyPromiseResolver> resolver = FontsReadyPromiseResolver::create(promise, executionContext());
     m_readyResolvers.append(resolver.release());
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
+    handlePendingEventsAndPromisesSoon();
     return promise;
 }
 
@@ -279,7 +291,7 @@
 {
     if (!m_pendingEvents.isEmpty() || !m_pendingLoadResolvers.isEmpty())
         return;
-    if (m_loadingCount || (!m_shouldFireDoneEvent && m_readyResolvers.isEmpty()))
+    if (m_loadingCount || (!hasLoadedFonts() && m_readyResolvers.isEmpty()))
         return;
 
     // If the layout was invalidated in between when we thought layout
@@ -289,8 +301,7 @@
     if (!d->view() || d->view()->needsLayout())
         return;
 
-    if (m_shouldFireDoneEvent) {
-        m_shouldFireDoneEvent = false;
+    if (hasLoadedFonts()) {
         RefPtr<CSSFontFaceLoadEvent> doneEvent;
         RefPtr<CSSFontFaceLoadEvent> errorEvent;
         doneEvent = CSSFontFaceLoadEvent::createForFontFaces(EventTypeNames::loadingdone, m_loadedFonts);
@@ -381,7 +392,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, CSSStrictMode, 0);
+    CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, HTMLStandardMode, 0);
     if (parsedStyle->isEmpty())
         return false;
 
@@ -425,7 +436,30 @@
     if (m_recorded)
         return;
     m_recorded = true;
-    HistogramSupport::histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
+    WebKit::Platform::current()->histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
 }
 
+static const char* supplementName()
+{
+    return "FontFaceSet";
+}
+
+PassRefPtr<FontFaceSet> FontFaceSet::from(Document* document)
+{
+    RefPtr<FontFaceSet> fonts = static_cast<FontFaceSet*>(SupplementType::from(document, supplementName()));
+    if (!fonts) {
+        fonts = FontFaceSet::create(document);
+        SupplementType::provideTo(document, supplementName(), fonts);
+    }
+
+    return fonts.release();
+}
+
+void FontFaceSet::didLayout(Document* document)
+{
+    if (FontFaceSet* fonts = static_cast<FontFaceSet*>(SupplementType::from(document, supplementName())))
+        fonts->didLayout();
+}
+
+
 } // namespace WebCore
diff --git a/Source/core/css/FontFaceSet.h b/Source/core/css/FontFaceSet.h
index 6a52349..e95c049 100644
--- a/Source/core/css/FontFaceSet.h
+++ b/Source/core/css/FontFaceSet.h
@@ -32,7 +32,8 @@
 #include "core/events/EventListener.h"
 #include "core/events/EventTarget.h"
 #include "core/events/ThreadLocalEventNames.h"
-#include "platform/Timer.h"
+#include "core/platform/RefCountedSupplement.h"
+#include "platform/AsyncMethodRunner.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
@@ -55,13 +56,9 @@
 class LoadFontPromiseResolver;
 class ExecutionContext;
 
-class FontFaceSet : public RefCounted<FontFaceSet>, public ActiveDOMObject, public EventTargetWithInlineData {
+class FontFaceSet : public RefCountedSupplement<Document, FontFaceSet>, public ActiveDOMObject, public EventTargetWithInlineData {
     REFCOUNTED_EVENT_TARGET(FontFaceSet);
 public:
-    static PassRefPtr<FontFaceSet> create(Document* document)
-    {
-        return adoptRef<FontFaceSet>(new FontFaceSet(document));
-    }
     virtual ~FontFaceSet();
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(loading);
@@ -86,7 +83,22 @@
     void loadError(FontFace*);
     void scheduleResolve(LoadFontPromiseResolver*);
 
+    // ActiveDOMObject
+    virtual void suspend() OVERRIDE;
+    virtual void resume() OVERRIDE;
+    virtual void stop() OVERRIDE;
+
+    static PassRefPtr<FontFaceSet> from(Document*);
+    static void didLayout(Document*);
+
 private:
+    typedef RefCountedSupplement<Document, FontFaceSet> SupplementType;
+
+    static PassRefPtr<FontFaceSet> create(Document* document)
+    {
+        return adoptRef<FontFaceSet>(new FontFaceSet(document));
+    }
+
     class FontLoadHistogram {
     public:
         FontLoadHistogram() : m_count(0), m_recorded(false) { }
@@ -100,13 +112,16 @@
 
     FontFaceSet(Document*);
 
+    bool hasLoadedFonts() const { return !m_loadedFonts.isEmpty() || !m_failedFonts.isEmpty(); }
+
     void scheduleEvent(PassRefPtr<Event>);
     void queueDoneEvent(FontFace*);
     void firePendingEvents();
     void resolvePendingLoadPromises();
     void fireDoneEventIfPossible();
     bool resolveFontStyle(const String&, Font&);
-    void timerFired(Timer<FontFaceSet>*);
+    void handlePendingEventsAndPromisesSoon();
+    void handlePendingEventsAndPromises();
 
     unsigned m_loadingCount;
     Vector<RefPtr<Event> > m_pendingEvents;
@@ -114,8 +129,9 @@
     Vector<OwnPtr<FontsReadyPromiseResolver> > m_readyResolvers;
     FontFaceArray m_loadedFonts;
     FontFaceArray m_failedFonts;
-    bool m_shouldFireDoneEvent;
-    Timer<FontFaceSet> m_timer;
+
+    AsyncMethodRunner<FontFaceSet> m_asyncRunner;
+
     FontLoadHistogram m_histogram;
 };
 
diff --git a/Source/core/css/FontFaceSet.idl b/Source/core/css/FontFaceSet.idl
index da6a824..daa2e8e 100644
--- a/Source/core/css/FontFaceSet.idl
+++ b/Source/core/css/FontFaceSet.idl
@@ -43,8 +43,8 @@
 
     [RaisesException] sequence<FontFace> match(DOMString font, [Default=NullString] optional DOMString text);
     [RaisesException] boolean check(DOMString font, [Default=NullString] optional DOMString text);
-    [RuntimeEnabled=Promise, RaisesException] Promise load(DOMString font, [Default=NullString] optional DOMString text);
-    [RuntimeEnabled=Promise] Promise ready();
+    [RaisesException] Promise load(DOMString font, [Default=NullString] optional DOMString text);
+    Promise ready();
 
     readonly attribute FontFaceSetLoadStatus status;
 };
diff --git a/Source/core/platform/HashTools.h b/Source/core/css/HashTools.h
similarity index 88%
rename from Source/core/platform/HashTools.h
rename to Source/core/css/HashTools.h
index c376470..c86f62d 100644
--- a/Source/core/platform/HashTools.h
+++ b/Source/core/css/HashTools.h
@@ -22,11 +22,6 @@
 
 namespace WebCore {
 
-struct NamedColor {
-    const char* name;
-    unsigned ARGBValue;
-};
-
 struct Property {
     int nameOffset;
     int id;
@@ -37,7 +32,6 @@
     int id;
 };
 
-const NamedColor* findColor(register const char* str, register unsigned int len);
 const Property* findProperty(register const char* str, register unsigned int len);
 const Value* findValue(register const char* str, register unsigned int len);
 
diff --git a/Source/core/css/InspectorCSSOMWrappers.cpp b/Source/core/css/InspectorCSSOMWrappers.cpp
index 324c012..7474b7f 100644
--- a/Source/core/css/InspectorCSSOMWrappers.cpp
+++ b/Source/core/css/InspectorCSSOMWrappers.cpp
@@ -105,7 +105,10 @@
 
 void InspectorCSSOMWrappers::collectFromStyleEngine(StyleEngine* styleSheetCollection)
 {
-    collectFromStyleSheets(styleSheetCollection->activeAuthorStyleSheets());
+    Vector<const Vector<RefPtr<CSSStyleSheet> >*> activeAuthorStyleSheets;
+    styleSheetCollection->getActiveAuthorStyleSheets(activeAuthorStyleSheets);
+    for (size_t i = 0; i < activeAuthorStyleSheets.size(); ++i)
+        collectFromStyleSheets(*activeAuthorStyleSheets[i]);
     collect(styleSheetCollection->pageUserSheet());
     collectFromStyleSheets(styleSheetCollection->documentUserStyleSheets());
 }
diff --git a/Source/core/css/MediaList.cpp b/Source/core/css/MediaList.cpp
index ce88391..00a30e7 100644
--- a/Source/core/css/MediaList.cpp
+++ b/Source/core/css/MediaList.cpp
@@ -74,7 +74,7 @@
     if (mediaString.isEmpty())
         return MediaQuerySet::create();
 
-    CSSParser parser(CSSStrictMode);
+    CSSParser parser(HTMLStandardMode);
     return parser.parseMediaQueryList(mediaString);
 }
 
diff --git a/Source/core/css/MediaQueryMatcher.cpp b/Source/core/css/MediaQueryMatcher.cpp
index 3d50338..61fc729 100644
--- a/Source/core/css/MediaQueryMatcher.cpp
+++ b/Source/core/css/MediaQueryMatcher.cpp
@@ -140,7 +140,8 @@
 
 void MediaQueryMatcher::styleResolverChanged()
 {
-    ASSERT(m_document);
+    if (!m_document)
+        return;
 
     ScriptState* scriptState = m_document->frame() ? mainWorldScriptState(m_document->frame()) : 0;
     if (!scriptState)
diff --git a/Source/core/css/Pair.h b/Source/core/css/Pair.h
index 2c1940f..fc2edaa 100644
--- a/Source/core/css/Pair.h
+++ b/Source/core/css/Pair.h
@@ -32,7 +32,7 @@
 // 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 : public RefCounted<Pair> {
+class Pair FINAL : public RefCounted<Pair> {
 public:
     enum IdenticalValuesPolicy { DropIdenticalValues, KeepIdenticalValues };
 
@@ -44,7 +44,6 @@
     {
         return adoptRef(new Pair(first, second, identicalValuesPolicy));
     }
-    virtual ~Pair() { }
 
     CSSPrimitiveValue* first() const { return m_first.get(); }
     CSSPrimitiveValue* second() const { return m_second.get(); }
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.cpp b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
index 92ae66c..87cc928 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.cpp
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
@@ -59,7 +59,7 @@
 
         bool shouldReadOldValue = false;
 
-        m_mutationRecipients = MutationObserverInterestGroup::createForAttributesMutation(s_currentDecl->parentElement(), HTMLNames::styleAttr);
+        m_mutationRecipients = MutationObserverInterestGroup::createForAttributesMutation(*s_currentDecl->parentElement(), HTMLNames::styleAttr);
         if (m_mutationRecipients && m_mutationRecipients->isOldValueRequested())
             shouldReadOldValue = true;
 
diff --git a/Source/core/css/RGBColor.h b/Source/core/css/RGBColor.h
index 5cc591c..5cd4697 100644
--- a/Source/core/css/RGBColor.h
+++ b/Source/core/css/RGBColor.h
@@ -27,7 +27,7 @@
 #ifndef RGBColor_h
 #define RGBColor_h
 
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/RefCounted.h"
 
 namespace WebCore {
diff --git a/Source/core/css/RuleFeature.cpp b/Source/core/css/RuleFeature.cpp
index 7d7879f..e75d8fe 100644
--- a/Source/core/css/RuleFeature.cpp
+++ b/Source/core/css/RuleFeature.cpp
@@ -84,6 +84,7 @@
     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()
@@ -94,6 +95,7 @@
     siblingRules.clear();
     uncommonAttributeRules.clear();
     m_usesFirstLineRules = false;
+    m_maxDirectAdjacentSelectors = 0;
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/RuleFeature.h b/Source/core/css/RuleFeature.h
index c8d35fc..b51863c 100644
--- a/Source/core/css/RuleFeature.h
+++ b/Source/core/css/RuleFeature.h
@@ -48,6 +48,7 @@
 public:
     RuleFeatureSet()
         : m_usesFirstLineRules(false)
+        , m_maxDirectAdjacentSelectors(0)
     { }
 
     void add(const RuleFeatureSet&);
@@ -58,6 +59,9 @@
     bool usesSiblingRules() const { return !siblingRules.isEmpty(); }
     bool usesFirstLineRules() const { return m_usesFirstLineRules; }
 
+    unsigned maxDirectAdjacentSelectors() const { return m_maxDirectAdjacentSelectors; }
+    void setMaxDirectAdjacentSelectors(unsigned value)  { m_maxDirectAdjacentSelectors = std::max(value, m_maxDirectAdjacentSelectors); }
+
     inline bool hasSelectorForAttribute(const AtomicString& attributeName) const
     {
         ASSERT(!attributeName.isEmpty());
@@ -85,6 +89,7 @@
     void collectFeaturesFromSelectorList(const CSSSelectorList*);
 
     bool m_usesFirstLineRules;
+    unsigned m_maxDirectAdjacentSelectors;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/RuleSet.cpp b/Source/core/css/RuleSet.cpp
index 3509682..cce6f47 100644
--- a/Source/core/css/RuleSet.cpp
+++ b/Source/core/css/RuleSet.cpp
@@ -224,18 +224,27 @@
 static void collectFeaturesFromRuleData(RuleFeatureSet& features, 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;
+        } 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())
@@ -325,7 +334,7 @@
     m_viewportRules.append(rule);
 }
 
-void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
+void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin, const ContainerNode* scope)
 {
     ensurePendingRules(); // So that m_regionSelectorsAndRuleSets.shrinkToFit() gets called.
     OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
@@ -338,7 +347,7 @@
     // 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 | RuleCanUseFastCheckSelector | RuleIsInRegionRule);
+    addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleIsInRegionRule | (!scope ? RuleCanUseFastCheckSelector : 0));
     for (unsigned i = 0; i < childRules.size(); ++i) {
         StyleRuleBase* regionStylingRule = childRules[i].get();
         if (regionStylingRule->isStyleRule())
@@ -360,10 +369,12 @@
 
             const CSSSelectorList& selectorList = styleRule->selectorList();
             for (size_t selectorIndex = 0; selectorIndex != kNotFound; selectorIndex = selectorList.indexOfNextSelectorAfter(selectorIndex)) {
-                if (selectorList.hasShadowDistributedAt(selectorIndex)) {
+                if (selectorList.hasCombinatorCrossingTreeBoundaryAt(selectorIndex)) {
+                    resolver->ruleSets().treeBoundaryCrossingRules().addRule(styleRule, selectorIndex, const_cast<ContainerNode*>(scope), addRuleFlags);
+                } else if (selectorList.hasShadowDistributedAt(selectorIndex)) {
                     if (isDocumentScope(scope))
                         continue;
-                    resolver->ruleSets().shadowDistributedRules().addRule(styleRule, selectorIndex, const_cast<ContainerNode*>(scope), addRuleFlags);
+                    resolver->ruleSets().treeBoundaryCrossingRules().addRule(styleRule, selectorIndex, const_cast<ContainerNode*>(scope), addRuleFlags);
                 } else
                     addRule(styleRule, selectorIndex, addRuleFlags);
             }
@@ -385,7 +396,7 @@
             resolver->ensureScopedStyleResolver(scope)->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(rule));
         } else if (rule->isRegionRule() && resolver) {
             // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
-            addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin);
+            addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin, scope);
         } else if (rule->isHostRule() && resolver) {
             if (!isScopingNodeInShadowTree(scope))
                 continue;
diff --git a/Source/core/css/RuleSet.h b/Source/core/css/RuleSet.h
index f8867f8..7bae0c0 100644
--- a/Source/core/css/RuleSet.h
+++ b/Source/core/css/RuleSet.h
@@ -156,7 +156,7 @@
     void addToRuleSet(StringImpl* key, PendingRuleMap&, const RuleData&);
     void addPageRule(StyleRulePage*);
     void addViewportRule(StyleRuleViewport*);
-    void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
+    void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin, const ContainerNode* scope);
 
     void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, StyleResolver*, const ContainerNode* scope, bool hasDocumentSecurityOrigin, AddRuleFlags);
     bool findBestRuleSetAndAdd(const CSSSelector*, RuleData&);
diff --git a/Source/core/css/SelectorChecker.cpp b/Source/core/css/SelectorChecker.cpp
index d5326b9..cfe37cb 100644
--- a/Source/core/css/SelectorChecker.cpp
+++ b/Source/core/css/SelectorChecker.cpp
@@ -260,17 +260,33 @@
         return match(nextContext, dynamicPseudo, siblingTraversalStrategy);
 
     case CSSSelector::ShadowPseudo:
+    case CSSSelector::ChildTree:
         {
             // If we're in the same tree-scope as the scoping element, then following a shadow descendant combinator would escape that and thus the scope.
             if (context.scope && context.scope->treeScope() == context.element->treeScope() && (context.behaviorAtBoundary & BoundaryBehaviorMask) != StaysWithinTreeScope)
                 return SelectorFailsCompletely;
-            Element* shadowHostNode = context.element->shadowHost();
-            if (!shadowHostNode)
+
+            Element* shadowHost = context.element->shadowHost();
+            if (!shadowHost)
                 return SelectorFailsCompletely;
-            nextContext.element = shadowHostNode;
+            nextContext.element = shadowHost;
             nextContext.isSubSelector = false;
             nextContext.elementStyle = 0;
-            return match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+            return this->match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+        }
+
+    case CSSSelector::DescendantTree:
+        {
+            nextContext.isSubSelector = false;
+            nextContext.elementStyle = 0;
+            for (nextContext.element = parentElement(context); nextContext.element; nextContext.element = parentElement(nextContext)) {
+                Match match = this->match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+                if (match == SelectorMatches || match == SelectorFailsCompletely)
+                    return match;
+                if (nextContext.element == nextContext.scope && (nextContext.behaviorAtBoundary & BoundaryBehaviorMask) != StaysWithinTreeScope)
+                    return SelectorFailsCompletely;
+            }
+            return SelectorFailsCompletely;
         }
     }
 
diff --git a/Source/core/css/SelectorFilter.cpp b/Source/core/css/SelectorFilter.cpp
index d24cdd3..0530099 100644
--- a/Source/core/css/SelectorFilter.cpp
+++ b/Source/core/css/SelectorFilter.cpp
@@ -148,6 +148,8 @@
         case CSSSelector::DirectAdjacent:
         case CSSSelector::IndirectAdjacent:
         case CSSSelector::ShadowPseudo:
+        case CSSSelector::ChildTree:
+        case CSSSelector::DescendantTree:
             skipOverSubselectors = true;
             break;
         case CSSSelector::Descendant:
diff --git a/Source/core/css/SiblingTraversalStrategies.h b/Source/core/css/SiblingTraversalStrategies.h
index 5e0bc09..b49a56b 100644
--- a/Source/core/css/SiblingTraversalStrategies.h
+++ b/Source/core/css/SiblingTraversalStrategies.h
@@ -98,14 +98,8 @@
 inline int DOMSiblingTraversalStrategy::countElementsAfter(Element* element) const
 {
     int count = 0;
-    for (const Element* sibling = element->nextElementSibling(); sibling; sibling = sibling->nextElementSibling()) {
-        unsigned index = sibling->childIndex();
-        if (index) {
-            count += index;
-            break;
-        }
+    for (const Element* sibling = element->nextElementSibling(); sibling; sibling = sibling->nextElementSibling())
         ++count;
-    }
 
     return count;
 }
diff --git a/Source/core/css/StyleColor.h b/Source/core/css/StyleColor.h
index eb893e4..1f58584 100644
--- a/Source/core/css/StyleColor.h
+++ b/Source/core/css/StyleColor.h
@@ -31,7 +31,7 @@
 #ifndef StyleColor_h
 #define StyleColor_h
 
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/FastAllocBase.h"
 
 namespace WebCore {
diff --git a/Source/core/css/StyleInvalidationAnalysis.cpp b/Source/core/css/StyleInvalidationAnalysis.cpp
index 6fa9e01..b0053cb 100644
--- a/Source/core/css/StyleInvalidationAnalysis.cpp
+++ b/Source/core/css/StyleInvalidationAnalysis.cpp
@@ -119,6 +119,37 @@
     return ownerElement->isRegisteredInShadowRoot() ? ownerElement->containingShadowRoot()->shadowHost() : ownerElement->parentNode();
 }
 
+static bool ruleAdditionMightRequireDocumentStyleRecalc(StyleRuleBase* rule)
+{
+    // This funciton is conservative. We only return false when we know that
+    // the added @rule can't require style recalcs.
+    switch (rule->type()) {
+    case StyleRule::Import: // Whatever we import should do its own analysis, we don't need to invalidate the document here!
+    case StyleRule::Keyframes: // Keyframes never cause style invalidations and are handled during sheet insertion.
+    case StyleRule::Page: // Page rules apply only during printing, we force a full-recalc before printing.
+        return false;
+
+    case StyleRule::Media: // If the media rule doesn't apply, we could avoid recalc.
+    case StyleRule::FontFace: // If the fonts aren't in use, we could avoid recalc.
+    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:
+    case StyleRule::HostInternal:
+        return true;
+
+    // These should all be impossible to reach:
+    case StyleRule::Unknown:
+    case StyleRule::Charset:
+    case StyleRule::Keyframe:
+    case StyleRule::Style:
+        break;
+    }
+    ASSERT_NOT_REACHED();
+    return true;
+}
+
 void StyleInvalidationAnalysis::analyzeStyleSheet(StyleSheetContents* styleSheetContents)
 {
     ASSERT(!styleSheetContents->isLoading());
@@ -145,9 +176,11 @@
     for (unsigned i = 0; i < rules.size(); i++) {
         StyleRuleBase* rule = rules[i].get();
         if (!rule->isStyleRule()) {
-            // FIXME: Media rules and maybe some others could be allowed.
-            m_dirtiesAllStyle = true;
-            return;
+            if (ruleAdditionMightRequireDocumentStyleRecalc(rule)) {
+                m_dirtiesAllStyle = true;
+                return;
+            }
+            continue;
         }
         StyleRule* styleRule = toStyleRule(rule);
         if (!determineSelectorScopes(styleRule->selectorList(), m_idScopes, m_classScopes)) {
diff --git a/Source/core/css/StylePropertySet.cpp b/Source/core/css/StylePropertySet.cpp
index 3bbd748..270bd4b 100644
--- a/Source/core/css/StylePropertySet.cpp
+++ b/Source/core/css/StylePropertySet.cpp
@@ -69,7 +69,7 @@
 }
 
 MutableStylePropertySet::MutableStylePropertySet(const CSSProperty* properties, unsigned length)
-    : StylePropertySet(CSSStrictMode)
+    : StylePropertySet(HTMLStandardMode)
 {
     m_propertyVector.reserveInitialCapacity(length);
     for (unsigned i = 0; i < length; ++i)
diff --git a/Source/core/css/StylePropertySet.h b/Source/core/css/StylePropertySet.h
index 81b5ad1..30a8c50 100644
--- a/Source/core/css/StylePropertySet.h
+++ b/Source/core/css/StylePropertySet.h
@@ -176,7 +176,7 @@
 class MutableStylePropertySet : public StylePropertySet {
 public:
     ~MutableStylePropertySet() { }
-    static PassRefPtr<MutableStylePropertySet> create(CSSParserMode = CSSQuirksMode);
+    static PassRefPtr<MutableStylePropertySet> create(CSSParserMode = HTMLQuirksMode);
     static PassRefPtr<MutableStylePropertySet> create(const CSSProperty* properties, unsigned count);
 
     unsigned propertyCount() const { return m_propertyVector.size(); }
diff --git a/Source/core/css/StyleRuleImport.cpp b/Source/core/css/StyleRuleImport.cpp
index 331cdf7..5167a42 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() : CSSStrictMode;
+    CSSParserContext context = m_parentStyleSheet ? m_parentStyleSheet->parserContext() : HTMLStandardMode;
     context.charset = charset;
     if (!baseURL.isNull())
         context.baseURL = baseURL;
diff --git a/Source/core/css/StyleSheetContents.cpp b/Source/core/css/StyleSheetContents.cpp
index 07d3430..1bcbbda 100644
--- a/Source/core/css/StyleSheetContents.cpp
+++ b/Source/core/css/StyleSheetContents.cpp
@@ -274,7 +274,9 @@
 {
     TRACE_EVENT0("webkit", "StyleSheetContents::parseAuthorStyleSheet");
 
-    bool enforceMIMEType = isStrictParserMode(m_parserContext.mode);
+    bool quirksMode = isQuirksModeBehavior(m_parserContext.mode);
+
+    bool enforceMIMEType = !quirksMode;
     bool hasValidMIMEType = false;
     String sheetText = cachedStyleSheet->sheetText(enforceMIMEType, &hasValidMIMEType);
 
@@ -291,7 +293,7 @@
             return;
         }
     }
-    if (m_parserContext.needsSiteSpecificQuirks && isStrictParserMode(m_parserContext.mode)) {
+    if (!quirksMode && m_parserContext.needsSiteSpecificQuirks) {
         // Work around <https://bugs.webkit.org/show_bug.cgi?id=28350>.
         DEFINE_STATIC_LOCAL(const String, mediaWikiKHTMLFixesStyleSheet, ("/* KHTML fix stylesheet */\n/* work around the horizontal scrollbars */\n#column-content { margin-left: 0; }\n\n"));
         // There are two variants of KHTMLFixes.css. One is equal to mediaWikiKHTMLFixesStyleSheet,
diff --git a/Source/core/css/StyleSheetContents.h b/Source/core/css/StyleSheetContents.h
index 02bf850..e9ec47e 100644
--- a/Source/core/css/StyleSheetContents.h
+++ b/Source/core/css/StyleSheetContents.h
@@ -43,7 +43,7 @@
 
 class StyleSheetContents : public RefCounted<StyleSheetContents> {
 public:
-    static PassRefPtr<StyleSheetContents> create(const CSSParserContext& context = CSSParserContext(CSSStrictMode))
+    static PassRefPtr<StyleSheetContents> create(const CSSParserContext& context = CSSParserContext(HTMLStandardMode))
     {
         return adoptRef(new StyleSheetContents(0, String(), context));
     }
diff --git a/Source/core/css/makegrammar.pl b/Source/core/css/makegrammar.pl
deleted file mode 100644
index eb47022..0000000
--- a/Source/core/css/makegrammar.pl
+++ /dev/null
@@ -1,58 +0,0 @@
-#! /usr/bin/perl
-#
-#   This file is part of the WebKit project
-#
-#   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.
-use strict;
-use warnings;
-
-use File::Basename;
-use File::Spec;
-use Getopt::Long;
-
-my $outputDir = ".";
-
-GetOptions(
-    'outputDir=s' => \$outputDir,
-);
-
-my $grammarFilePath = $ARGV[0];
-my $grammarIncludesFilePath = @ARGV > 0 ? $ARGV[1] : "";
-
-my ($filename, $basePath, $suffix) = fileparse($grammarFilePath, (".y", ".y.in"));
-
-my $grammarFileOutPath = File::Spec->join($outputDir, "$filename.y");
-if (!$grammarIncludesFilePath) {
-    $grammarIncludesFilePath = "${basePath}${filename}.y.includes";
-}
-
-open GRAMMAR, ">$grammarFileOutPath" or die;
-open INCLUDES, "<$grammarIncludesFilePath" or die;
-
-while (<INCLUDES>) {
-    print GRAMMAR;
-}
-
-open GRAMMARFILE, "<$grammarFilePath" or die;
-while (<GRAMMARFILE>) {
-    print GRAMMAR;
-}
-
-close GRAMMAR;
-
-$grammarFilePath = $grammarFileOutPath;
diff --git a/Source/core/css/resolver/AnimatedStyleBuilder.cpp b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
index bfa3eef..c44ca17 100644
--- a/Source/core/css/resolver/AnimatedStyleBuilder.cpp
+++ b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
@@ -34,6 +34,7 @@
 #include "core/animation/AnimatableClipPathOperation.h"
 #include "core/animation/AnimatableColor.h"
 #include "core/animation/AnimatableDouble.h"
+#include "core/animation/AnimatableFilterOperations.h"
 #include "core/animation/AnimatableImage.h"
 #include "core/animation/AnimatableLength.h"
 #include "core/animation/AnimatableLengthBox.h"
@@ -43,6 +44,7 @@
 #include "core/animation/AnimatableRepeatable.h"
 #include "core/animation/AnimatableSVGLength.h"
 #include "core/animation/AnimatableSVGPaint.h"
+#include "core/animation/AnimatableShadow.h"
 #include "core/animation/AnimatableShapeValue.h"
 #include "core/animation/AnimatableStrokeDasharrayList.h"
 #include "core/animation/AnimatableTransform.h"
@@ -288,6 +290,10 @@
     case CSSPropertyBottom:
         style->setBottom(animatableValueToLength(value, state));
         return;
+    case CSSPropertyBoxShadow:
+    case CSSPropertyWebkitBoxShadow:
+        style->setBoxShadow(toAnimatableShadow(value)->shadowList());
+        return;
     case CSSPropertyClip:
         style->setClip(animatableValueToLengthBox(value, state));
         style->setHasClip(true);
@@ -433,6 +439,9 @@
     case CSSPropertyTextIndent:
         style->setTextIndent(animatableValueToLength(value, state));
         return;
+    case CSSPropertyTextShadow:
+        style->setTextShadow(toAnimatableShadow(value)->shadowList());
+        return;
     case CSSPropertyTop:
         style->setTop(animatableValueToLength(value, state));
         return;
@@ -464,6 +473,9 @@
     case CSSPropertyWebkitColumnRuleWidth:
         style->setColumnRuleWidth(animatableValueRoundClampTo<unsigned short>(value));
         return;
+    case CSSPropertyWebkitFilter:
+        style->setFilter(toAnimatableFilterOperations(value)->operations());
+        return;
     case CSSPropertyWebkitMaskBoxImageOutset:
         style->setMaskBoxImageOutset(animatableValueToLengthBox(value, state, NonNegativeValues));
         return;
@@ -507,10 +519,6 @@
     case CSSPropertyShapeMargin:
         style->setShapeMargin(animatableValueToLength(value, state, NonNegativeValues));
         return;
-    case CSSPropertyWebkitTextEmphasisColor:
-        style->setTextEmphasisColor(toAnimatableColor(value)->color());
-        style->setVisitedLinkTextEmphasisColor(toAnimatableColor(value)->visitedLinkColor());
-        return;
     case CSSPropertyWebkitTextStrokeColor:
         style->setTextStrokeColor(toAnimatableColor(value)->color());
         style->setVisitedLinkTextStrokeColor(toAnimatableColor(value)->visitedLinkColor());
diff --git a/Source/core/css/resolver/ElementResolveContext.cpp b/Source/core/css/resolver/ElementResolveContext.cpp
index 408475f9..75a1ab1 100644
--- a/Source/core/css/resolver/ElementResolveContext.cpp
+++ b/Source/core/css/resolver/ElementResolveContext.cpp
@@ -31,7 +31,7 @@
 
 ElementResolveContext::ElementResolveContext(Element& element)
     : m_element(&element)
-    , m_elementLinkState(element.document().visitedLinkState()->determineLinkState(element))
+    , m_elementLinkState(element.document().visitedLinkState().determineLinkState(element))
     , m_distributedToInsertionPoint(false)
     , m_resetStyleInheritance(false)
 {
diff --git a/Source/core/css/resolver/ElementStyleResources.h b/Source/core/css/resolver/ElementStyleResources.h
index db1c57d..354b022 100644
--- a/Source/core/css/resolver/ElementStyleResources.h
+++ b/Source/core/css/resolver/ElementStyleResources.h
@@ -24,7 +24,7 @@
 #define ElementStyleResources_h
 
 #include "CSSPropertyNames.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
 
diff --git a/Source/core/css/resolver/FontBuilder.cpp b/Source/core/css/resolver/FontBuilder.cpp
index b9655fc..024390b 100644
--- a/Source/core/css/resolver/FontBuilder.cpp
+++ b/Source/core/css/resolver/FontBuilder.cpp
@@ -185,27 +185,27 @@
                 face = settings->standardFontFamily();
                 break;
             case CSSValueSerif:
-                face = serifFamily;
+                face = FontFamilyNames::webkit_serif;
                 scope.fontDescription().setGenericFamily(FontDescription::SerifFamily);
                 break;
             case CSSValueSansSerif:
-                face = sansSerifFamily;
+                face = FontFamilyNames::webkit_sans_serif;
                 scope.fontDescription().setGenericFamily(FontDescription::SansSerifFamily);
                 break;
             case CSSValueCursive:
-                face = cursiveFamily;
+                face = FontFamilyNames::webkit_cursive;
                 scope.fontDescription().setGenericFamily(FontDescription::CursiveFamily);
                 break;
             case CSSValueFantasy:
-                face = fantasyFamily;
+                face = FontFamilyNames::webkit_fantasy;
                 scope.fontDescription().setGenericFamily(FontDescription::FantasyFamily);
                 break;
             case CSSValueMonospace:
-                face = monospaceFamily;
+                face = FontFamilyNames::webkit_monospace;
                 scope.fontDescription().setGenericFamily(FontDescription::MonospaceFamily);
                 break;
             case CSSValueWebkitPictograph:
-                face = pictographFamily;
+                face = FontFamilyNames::webkit_pictograph;
                 scope.fontDescription().setGenericFamily(FontDescription::PictographFamily);
                 break;
             default:
diff --git a/Source/core/css/resolver/FontBuilder.h b/Source/core/css/resolver/FontBuilder.h
index 847fed9..b573b51 100644
--- a/Source/core/css/resolver/FontBuilder.h
+++ b/Source/core/css/resolver/FontBuilder.h
@@ -25,7 +25,7 @@
 
 #include "CSSValueKeywords.h"
 
-#include "core/platform/graphics/FontDescription.h"
+#include "platform/fonts/FontDescription.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/css/resolver/ScopedStyleResolver.cpp b/Source/core/css/resolver/ScopedStyleResolver.cpp
index 3a3f8e6..26170fa 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -272,8 +272,7 @@
     RuleSet* rule = ensureAtHostRuleSetFor(shadowRoot);
 
     const Vector<RefPtr<StyleRuleBase> >& childRules = hostRule->childRules();
-    AddRuleFlags addRuleFlags = hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
-    addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleCanUseFastCheckSelector);
+    AddRuleFlags addRuleFlags = static_cast<AddRuleFlags>(hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState);
     for (unsigned i = 0; i < childRules.size(); ++i) {
         StyleRuleBase* hostStylingRule = childRules[i].get();
         if (hostStylingRule->isStyleRule())
diff --git a/Source/core/css/resolver/SharedStyleFinder.cpp b/Source/core/css/resolver/SharedStyleFinder.cpp
index a7f7cc9..cfff3f7 100644
--- a/Source/core/css/resolver/SharedStyleFinder.cpp
+++ b/Source/core/css/resolver/SharedStyleFinder.cpp
@@ -45,7 +45,6 @@
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLOptGroupElement.h"
-#include "core/html/track/WebVTTElement.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "core/svg/SVGElement.h"
 #include "wtf/HashSet.h"
@@ -165,14 +164,12 @@
     RenderStyle* style = candidate.renderStyle();
     if (!style)
         return false;
+    if (!style->isSharable())
+        return false;
     if (!parent)
         return false;
     if (element().parentElement()->renderStyle() != parent->renderStyle())
         return false;
-    if (style->unique())
-        return false;
-    if (style->hasUniquePseudoStyle())
-        return false;
     if (candidate.tagQName() != element().tagQName())
         return false;
     if (candidate.inlineStyle())
@@ -212,9 +209,6 @@
     if (isControl && !canShareStyleWithControl(candidate))
         return false;
 
-    if (style->transitions() || style->animations())
-        return false;
-
     // FIXME: This line is surprisingly hot, we may wish to inline hasDirectionAuto into StyleResolver.
     if (candidate.isHTMLElement() && toHTMLElement(candidate).hasDirectionAuto())
         return false;
@@ -225,13 +219,6 @@
     if (candidate.isUnresolvedCustomElement() != element().isUnresolvedCustomElement())
         return false;
 
-    // Deny sharing styles between WebVTT and non-WebVTT nodes.
-    if (candidate.isWebVTTElement() != element().isWebVTTElement())
-        return false;
-
-    if (candidate.isWebVTTElement() && element().isWebVTTElement() && toWebVTTElement(candidate).isPastNode() != toWebVTTElement(element()).isPastNode())
-        return false;
-
     if (element().parentElement() != parent) {
         if (!parent->isStyledElement())
             return false;
diff --git a/Source/core/css/resolver/StyleBuilderCustom.cpp b/Source/core/css/resolver/StyleBuilderCustom.cpp
index 4392b7b..8b4e12b 100644
--- a/Source/core/css/resolver/StyleBuilderCustom.cpp
+++ b/Source/core/css/resolver/StyleBuilderCustom.cpp
@@ -71,7 +71,6 @@
 #include "core/css/resolver/TransformBuilder.h"
 #include "core/frame/Frame.h"
 #include "core/page/Settings.h"
-#include "core/platform/graphics/FontDescription.h"
 #include "core/rendering/style/CounterContent.h"
 #include "core/rendering/style/CursorList.h"
 #include "core/rendering/style/QuotesData.h"
@@ -79,11 +78,11 @@
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "core/rendering/style/SVGRenderStyle.h"
 #include "core/rendering/style/SVGRenderStyleDefs.h"
-#include "core/rendering/style/ShadowData.h"
 #include "core/rendering/style/StyleGeneratedImage.h"
 #include "core/svg/SVGColor.h"
 #include "core/svg/SVGPaint.h"
 #include "core/svg/SVGURIReference.h"
+#include "platform/fonts/FontDescription.h"
 #include "wtf/MathExtras.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/Vector.h"
@@ -894,6 +893,37 @@
     return LengthSize(radiusWidth, radiusHeight);
 }
 
+PassRefPtr<ShadowList> StyleBuilderConverter::convertShadow(StyleResolverState& state, CSSValue* value)
+{
+    if (value->isPrimitiveValue()) {
+        ASSERT(toCSSPrimitiveValue(value)->getValueID() == CSSValueNone);
+        return PassRefPtr<ShadowList>();
+    }
+
+    const CSSValueList* valueList = toCSSValueList(value);
+    size_t shadowCount = valueList->length();
+    float zoom = state.style()->effectiveZoom();
+    ShadowDataVector shadows;
+    for (size_t i = 0; i < shadowCount; ++i) {
+        const CSSShadowValue* item = toCSSShadowValue(valueList->item(i));
+        int x = item->x->computeLength<int>(state.style(), state.rootElementStyle(), zoom);
+        int y = item->y->computeLength<int>(state.style(), state.rootElementStyle(), zoom);
+        int blur = item->blur ? item->blur->computeLength<int>(state.style(), state.rootElementStyle(), zoom) : 0;
+        int spread = item->spread ? item->spread->computeLength<int>(state.style(), state.rootElementStyle(), zoom) : 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()->visitedDependentColor(CSSPropertyColor));
+        else
+            color = state.style()->color();
+
+        if (!color.isValid())
+            color = Color::transparent;
+        shadows.append(ShadowData(IntPoint(x, y), blur, spread, shadowStyle, color));
+    }
+    return ShadowList::adopt(shadows);
+}
+
 float StyleBuilderConverter::convertSpacing(StyleResolverState& state, CSSValue* value)
 {
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
@@ -1485,46 +1515,6 @@
         break;
 
     // CSS3 Properties
-    case CSSPropertyTextShadow:
-    case CSSPropertyBoxShadow:
-    case CSSPropertyWebkitBoxShadow: {
-        if (isInherit) {
-            if (id == CSSPropertyTextShadow)
-                return state.style()->setTextShadow(cloneShadow(state.parentStyle()->textShadow()));
-            return state.style()->setBoxShadow(cloneShadow(state.parentStyle()->boxShadow()));
-        }
-        if (isInitial || primitiveValue) // initial | none
-            return id == CSSPropertyTextShadow ? state.style()->setTextShadow(nullptr) : state.style()->setBoxShadow(nullptr);
-
-        if (!value->isValueList())
-            return;
-
-        for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
-            CSSValue* currValue = i.value();
-            if (!currValue->isShadowValue())
-                continue;
-            CSSShadowValue* item = toCSSShadowValue(currValue);
-            int x = item->x->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor);
-            int y = item->y->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor);
-            int blur = item->blur ? item->blur->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor) : 0;
-            int spread = item->spread ? item->spread->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor) : 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()->visitedDependentColor(CSSPropertyColor));
-            else if (state.style())
-                color = state.style()->color();
-
-            if (!color.isValid())
-                color = Color::transparent;
-            OwnPtr<ShadowData> shadow = ShadowData::create(IntPoint(x, y), blur, spread, shadowStyle, color);
-            if (id == CSSPropertyTextShadow)
-                state.style()->setTextShadow(shadow.release(), i.index()); // add to the list if this is not the first entry
-            else
-                state.style()->setBoxShadow(shadow.release(), i.index()); // add to the list if this is not the first entry
-        }
-        return;
-    }
     case CSSPropertyWebkitBoxReflect: {
         HANDLE_INHERIT_AND_INITIAL(boxReflect, BoxReflect)
         if (primitiveValue) {
@@ -1929,6 +1919,7 @@
     case CSSPropertyBorderTopStyle:
     case CSSPropertyBorderTopWidth:
     case CSSPropertyBottom:
+    case CSSPropertyBoxShadow:
     case CSSPropertyBoxSizing:
     case CSSPropertyCaptionSide:
     case CSSPropertyClear:
@@ -1998,6 +1989,7 @@
     case CSSPropertyTextJustify:
     case CSSPropertyTextOverflow:
     case CSSPropertyTextRendering:
+    case CSSPropertyTextShadow:
     case CSSPropertyTextTransform:
     case CSSPropertyTop:
     case CSSPropertyTouchAction:
@@ -2034,6 +2026,7 @@
     case CSSPropertyWebkitBoxOrdinalGroup:
     case CSSPropertyWebkitBoxOrient:
     case CSSPropertyWebkitBoxPack:
+    case CSSPropertyWebkitBoxShadow:
     case CSSPropertyWebkitColumnAxis:
     case CSSPropertyWebkitColumnBreakAfter:
     case CSSPropertyWebkitColumnBreakBefore:
diff --git a/Source/core/css/resolver/StyleBuilderCustom.h b/Source/core/css/resolver/StyleBuilderCustom.h
index 1f65b23..d384c51 100644
--- a/Source/core/css/resolver/StyleBuilderCustom.h
+++ b/Source/core/css/resolver/StyleBuilderCustom.h
@@ -30,6 +30,7 @@
 #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"
 
@@ -47,6 +48,7 @@
     static Length convertLengthMaxSizing(StyleResolverState&, CSSValue*);
     static LengthPoint convertLengthPoint(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*);
 };
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index 9a81118..2ca8c2a 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -33,6 +33,7 @@
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "StylePropertyShorthand.h"
+#include "core/animation/ActiveAnimations.h"
 #include "core/animation/AnimatableLength.h"
 #include "core/animation/AnimatableValue.h"
 #include "core/animation/Animation.h"
@@ -192,7 +193,11 @@
             continue;
 
         StyleSheetContents* sheet = cssSheet->contents();
-        ScopedStyleResolver* resolver = ensureScopedStyleResolver(ScopedStyleResolver::scopingNodeFor(cssSheet));
+        const ContainerNode* scopingNode = ScopedStyleResolver::scopingNodeFor(cssSheet);
+        if (!scopingNode && cssSheet->ownerNode() && cssSheet->ownerNode()->isInShadowTree())
+            continue;
+
+        ScopedStyleResolver* resolver = ensureScopedStyleResolver(scopingNode);
         ASSERT(resolver);
         resolver->addRulesFromSheet(sheet, *m_medium, this);
         m_inspectorCSSOMWrappers.collectFromStyleSheetIfNeeded(cssSheet);
@@ -217,7 +222,7 @@
     if (!resolver)
         return;
 
-    m_ruleSets.shadowDistributedRules().reset(scopingNode);
+    m_ruleSets.treeBoundaryCrossingRules().reset(scopingNode);
 
     resolver->resetAuthorStyle();
     if (!scopingNode)
@@ -343,9 +348,9 @@
     m_viewportStyleResolver->clearDocument();
 }
 
-inline void StyleResolver::collectShadowDistributedRules(ElementRuleCollector& collector, bool includeEmptyRules)
+inline void StyleResolver::collectTreeBoundaryCrossingRules(ElementRuleCollector& collector, bool includeEmptyRules)
 {
-    if (m_ruleSets.shadowDistributedRules().isEmpty())
+    if (m_ruleSets.treeBoundaryCrossingRules().isEmpty())
         return;
 
     bool previousCanUseFastReject = collector.canUseFastReject();
@@ -353,15 +358,21 @@
 
     RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
 
-    for (ShadowDistributedRules::iterator it = m_ruleSets.shadowDistributedRules().begin(); it != m_ruleSets.shadowDistributedRules().end(); ++it) {
+    TreeBoundaryCrossingRules& rules = m_ruleSets.treeBoundaryCrossingRules();
+    CascadeOrder cascadeOrder = 0;
+
+    DocumentOrderedList::iterator it = rules.end();
+    while (it != rules.begin()) {
+        --it;
+        const ContainerNode* scopingNode = toContainerNode(*it);
+        RuleSet* ruleSet = rules.ruleSetScopedBy(scopingNode);
         unsigned boundaryBehavior = SelectorChecker::CrossesBoundary | SelectorChecker::ScopeContainsLastMatchedElement;
-        const ContainerNode* scopingNode = it->key;
 
         if (scopingNode && scopingNode->isShadowRoot()) {
             boundaryBehavior |= SelectorChecker::ScopeIsShadowHost;
             scopingNode = toShadowRoot(scopingNode)->host();
         }
-        collector.collectMatchingRules(MatchRequest(it->value.get(), includeEmptyRules, scopingNode), ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(boundaryBehavior), ignoreCascadeScope);
+        collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, scopingNode), ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(boundaryBehavior), ignoreCascadeScope, cascadeOrder++);
     }
     collector.setCanUseFastReject(previousCanUseFastReject);
 }
@@ -396,7 +407,7 @@
     for (unsigned i = 0; i < resolvers.size(); ++i)
         resolvers.at(i)->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope++, --cascadeOrder);
 
-    collectShadowDistributedRules(collector, includeEmptyRules);
+    collectTreeBoundaryCrossingRules(collector, includeEmptyRules);
     collector.sortAndTransferMatchedRules();
 
     if (!resolvers.isEmpty())
@@ -407,6 +418,11 @@
 {
     if (m_styleTree.hasOnlyScopedResolverForDocument()) {
         m_styleTree.scopedStyleResolverForDocument()->matchAuthorRules(collector, includeEmptyRules, applyAuthorStylesOf(element));
+
+        collector.clearMatchedRules();
+        collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
+        collectTreeBoundaryCrossingRules(collector, includeEmptyRules);
+        collector.sortAndTransferMatchedRules();
         return;
     }
 
@@ -435,7 +451,7 @@
         resolver->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope++, resolver->treeScope() == element->treeScope() && resolver->scopingNode().isShadowRoot() ? 0 : cascadeOrder);
     }
 
-    collectShadowDistributedRules(collector, includeEmptyRules);
+    collectTreeBoundaryCrossingRules(collector, includeEmptyRules);
     collector.sortAndTransferMatchedRules();
 
     matchHostRules(element, resolvers.first(), collector, includeEmptyRules);
@@ -682,7 +698,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())
-        element->ensureActiveAnimations()->cssAnimations()->setPendingUpdate(state.takeAnimationUpdate());
+        element->ensureActiveAnimations()->cssAnimations().setPendingUpdate(state.takeAnimationUpdate());
 
     // Now return the style.
     return state.takeStyle();
@@ -966,7 +982,7 @@
         keyframesAndTimingFunctions.append(std::make_pair(splitOutKeyframes, generateTimingFunction(splitOutKeyframes, perKeyframeTimingFunctions)));
     }
 
-    size_t numPropertiesSpecifiedInAllKeyframes = keyframes.first()->properties().size();
+    int numPropertiesSpecifiedInAllKeyframes = keyframes.first()->properties().size();
 #ifndef NDEBUG
     for (size_t i = 1; i < numKeyframes; ++i)
         ASSERT(keyframes[i]->properties().size() == numPropertiesSpecifiedInAllKeyframes);
@@ -1146,12 +1162,12 @@
     state.fontBuilder().createFont(m_fontSelector, state.parentStyle(), state.style());
 }
 
-PassRefPtr<CSSRuleList> StyleResolver::styleRulesForElement(Element* e, unsigned rulesToInclude)
+PassRefPtr<CSSRuleList> StyleResolver::styleRulesForElement(Element* e, unsigned rulesToInclude, ShouldIncludeStyleSheetInCSSOMWrapper includeDocument)
 {
-    return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
+    return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude, includeDocument);
 }
 
-PassRefPtr<CSSRuleList> StyleResolver::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
+PassRefPtr<CSSRuleList> StyleResolver::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude, ShouldIncludeStyleSheetInCSSOMWrapper includeDocument)
 {
     if (!e || !e->document().haveStylesheetsLoaded())
         return 0;
@@ -1160,7 +1176,7 @@
         resetDirectionAndWritingModeOnDocument(document());
     StyleResolverState state(document(), e);
 
-    ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style());
+    ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style(), includeDocument);
     collector.setMode(SelectorChecker::CollectingRules);
     collector.setPseudoStyleRequest(PseudoStyleRequest(pseudoId));
 
@@ -1187,64 +1203,24 @@
 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
 
 template <StyleResolver::StyleApplicationPass pass>
-bool StyleResolver::applyAnimatedProperties(StyleResolverState& state, const DocumentTimeline* timeline)
+bool StyleResolver::applyAnimatedProperties(StyleResolverState& state, const AnimationEffect::CompositableValueMap& compositableValues)
 {
     ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
     ASSERT(pass != VariableDefinitions);
     ASSERT(pass != AnimationProperties);
-    const Element* element = state.element();
-    const CSSAnimationUpdate* update = state.animationUpdate();
-    AnimationStack* animationStack = timeline->animationStack(element);
     bool didApply = false;
 
-    if (animationStack) {
-        const Vector<Animation*>& animations = animationStack->activeAnimations(element);
-        for (size_t i = 0; i < animations.size(); ++i) {
-            RefPtr<Animation> animation = animations.at(i);
-            if (update && update->isCancelledAnimation(animation->player()))
-                continue;
-            const AnimationEffect::CompositableValueMap* compositableValues = animation->compositableValues();
-            for (AnimationEffect::CompositableValueMap::const_iterator iter = compositableValues->begin(); iter != compositableValues->end(); ++iter) {
-                CSSPropertyID property = iter->key;
-                if (!isPropertyForPass<pass>(property))
-                    continue;
-                RELEASE_ASSERT_WITH_MESSAGE(!iter->value->dependsOnUnderlyingValue(), "Web Animations not yet implemented: An interface for compositing onto the underlying value.");
-                RefPtr<AnimatableValue> animatableValue = iter->value->compositeOnto(0);
-                if (pass == HighPriorityProperties && property == CSSPropertyLineHeight)
-                    state.setLineHeightValue(toAnimatableLength(animatableValue.get())->toCSSValue().get());
-                else
-                    AnimatedStyleBuilder::applyProperty(property, state, animatableValue.get());
-                didApply = true;
-            }
-        }
-    }
-
-    if (!update)
-        return didApply;
-
-    // FIXME: Remove this repetition by incorporating a merge of newAnimations with AnimationStack.
-    // Then resolve the stack before calling applyAnimatedProperties, eg.
-    //     CompositableValueMap* resolved = timeline->animationStack()->resolveWith(newAnimations);
-    //     applyAnimatedProperties(state, resolved);
-    const Vector<CSSAnimationUpdate::NewAnimation>& newAnimations = update->newAnimations();
-    for (size_t i = 0; i < newAnimations.size(); ++i) {
-        const HashSet<RefPtr<InertAnimation> >& animations = newAnimations.at(i).animations;
-        for (HashSet<RefPtr<InertAnimation> >::const_iterator animationsIter = animations.begin(); animationsIter != animations.end(); ++animationsIter) {
-            OwnPtr<AnimationEffect::CompositableValueMap> compositableValues = (*animationsIter)->sample();
-            if (!compositableValues)
-                continue;
-            for (AnimationEffect::CompositableValueMap::const_iterator iter = compositableValues->begin(); iter != compositableValues->end(); ++iter) {
-                CSSPropertyID property = iter->key;
-                if (!isPropertyForPass<pass>(property))
-                    continue;
-                RefPtr<AnimatableValue> animatableValue = iter->value->compositeOnto(AnimatableValue::neutralValue());
-                if (pass == HighPriorityProperties && property == CSSPropertyLineHeight)
-                    state.setLineHeightValue(toAnimatableLength(animatableValue.get())->toCSSValue().get());
-                else
-                    AnimatedStyleBuilder::applyProperty(property, state, animatableValue.get());
-                didApply = true;
-            }
-        }
+    for (AnimationEffect::CompositableValueMap::const_iterator iter = compositableValues.begin(); iter != compositableValues.end(); ++iter) {
+        CSSPropertyID property = iter->key;
+        if (!isPropertyForPass<pass>(property))
+            continue;
+        RELEASE_ASSERT_WITH_MESSAGE(!iter->value->dependsOnUnderlyingValue(), "Web Animations not yet implemented: An interface for compositing onto the underlying value.");
+        RefPtr<AnimatableValue> animatableValue = iter->value->compositeOnto(0);
+        if (pass == HighPriorityProperties && property == CSSPropertyLineHeight)
+            state.setLineHeightValue(toAnimatableLength(animatableValue.get())->toCSSValue().get());
+        else
+            AnimatedStyleBuilder::applyProperty(property, state, animatableValue.get());
+        didApply = true;
     }
     return didApply;
 }
@@ -1497,19 +1473,23 @@
 
     if (RuntimeEnabledFeatures::webAnimationsEnabled() && !applyInheritedOnly) {
         state.setAnimationUpdate(CSSAnimations::calculateUpdate(state.element(), state.style(), this));
+        const AnimationEffect::CompositableValueMap& compositableValuesForAnimations = CSSAnimations::compositableValuesForAnimations(state.element(), state.animationUpdate());
+        const AnimationEffect::CompositableValueMap& compositableValuesForTransitions = CSSAnimations::compositableValuesForTransitions(state.element(), state.animationUpdate());
         // Apply animated properties, then reapply any rules marked important.
-        if (applyAnimatedProperties<HighPriorityProperties>(state, element->document().timeline())) {
+        if (applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForAnimations)) {
             bool important = true;
             applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
             applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
             applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
         }
-        if (applyAnimatedProperties<LowPriorityProperties>(state, element->document().timeline())) {
+        applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForTransitions);
+        if (applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForAnimations)) {
             bool important = true;
             applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
             applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
             applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
         }
+        applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForTransitions);
     }
 
     // Start loading resources referenced by this style.
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index d4d449e..3e6127b 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -34,6 +34,7 @@
 #include "core/css/resolver/MatchedPropertiesCache.h"
 #include "core/css/resolver/ScopedStyleResolver.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"
@@ -236,8 +237,8 @@
         AllButEmptyCSSRules = UAAndUserCSSRules | AuthorCSSRules | CrossOriginCSSRules,
         AllCSSRules         = AllButEmptyCSSRules | EmptyCSSRules,
     };
-    PassRefPtr<CSSRuleList> styleRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules);
-    PassRefPtr<CSSRuleList> pseudoStyleRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules);
+    PassRefPtr<CSSRuleList> styleRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
+    PassRefPtr<CSSRuleList> pseudoStyleRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
 
     // |properties| is an array with |count| elements.
     void applyPropertiesToStyle(const CSSPropertyValue* properties, size_t count, RenderStyle*);
@@ -285,13 +286,13 @@
 
     void matchUARules(ElementRuleCollector&, RuleSet*);
     void matchAuthorRules(Element*, ElementRuleCollector&, bool includeEmptyRules);
-    void collectShadowDistributedRules(ElementRuleCollector&, bool includeEmptyRules);
     void matchAuthorRulesForShadowHost(Element*, ElementRuleCollector&, bool includeEmptyRules, Vector<ScopedStyleResolver*, 8>& resolvers, Vector<ScopedStyleResolver*, 8>& resolversInShadowTree);
     void matchHostRules(Element*, ScopedStyleResolver*, ElementRuleCollector&, bool includeEmptyRules);
     void matchAllRules(StyleResolverState&, ElementRuleCollector&, bool matchAuthorAndUserStyles, bool includeSMILProperties);
     void matchUARules(ElementRuleCollector&);
     void matchUserRules(ElementRuleCollector&, bool includeEmptyRules);
     void collectFeatures();
+    void collectTreeBoundaryCrossingRules(ElementRuleCollector&, bool includeEmptyRules);
 
     bool fastRejectSelector(const RuleData&) const;
 
@@ -310,7 +311,7 @@
     template <StyleApplicationPass pass>
     void applyProperties(StyleResolverState&, const StylePropertySet* properties, StyleRule*, bool isImportant, bool inheritedOnly, PropertyWhitelistType = PropertyWhitelistNone);
     template <StyleApplicationPass pass>
-    bool applyAnimatedProperties(StyleResolverState&, const DocumentTimeline*);
+    bool applyAnimatedProperties(StyleResolverState&, const AnimationEffect::CompositableValueMap&);
     void matchPageRules(MatchResult&, RuleSet*, bool isLeftPage, bool isFirstPage, const String& pageName);
     void matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>&, bool isLeftPage, bool isFirstPage, const String& pageName);
     void collectViewportRules();
diff --git a/Source/core/css/resolver/StyleResolverIncludes.h b/Source/core/css/resolver/StyleResolverIncludes.h
new file mode 100644
index 0000000..380c1eb
--- /dev/null
+++ b/Source/core/css/resolver/StyleResolverIncludes.h
@@ -0,0 +1,13 @@
+#ifndef StyleResolverIncludes_h
+#define StyleResolverIncludes_h
+
+namespace WebCore {
+
+enum ShouldIncludeStyleSheetInCSSOMWrapper {
+    IncludeStyleSheetInCSSOMWrapper,
+    DoNotIncludeStyleSheetInCSSOMWrapper,
+};
+
+}
+
+#endif // StyleResolverIncludes_h
diff --git a/Source/core/css/resolver/StyleResolverState.h b/Source/core/css/resolver/StyleResolverState.h
index b97071d..cedd3a4 100644
--- a/Source/core/css/resolver/StyleResolverState.h
+++ b/Source/core/css/resolver/StyleResolverState.h
@@ -132,8 +132,6 @@
 private:
     friend class StyleResolveScope;
 
-    void initElement(Element*);
-
     ElementResolveContext m_elementContext;
     Document& m_document;
 
diff --git a/Source/core/css/resolver/StyleResourceLoader.cpp b/Source/core/css/resolver/StyleResourceLoader.cpp
index 2acf990..3d29773 100644
--- a/Source/core/css/resolver/StyleResourceLoader.cpp
+++ b/Source/core/css/resolver/StyleResourceLoader.cpp
@@ -47,8 +47,8 @@
 namespace WebCore {
 
 StyleResourceLoader::StyleResourceLoader(ResourceFetcher* fetcher)
-    : m_fetcher(fetcher)
-    , m_customFilterProgramCache(StyleCustomFilterProgramCache::create())
+    : m_customFilterProgramCache(StyleCustomFilterProgramCache::create())
+    , m_fetcher(fetcher)
 {
 }
 
@@ -115,7 +115,8 @@
     CSSImageValue* cssImageValue =  pendingImage->cssImageValue();
 
     ResourceLoaderOptions options = ResourceFetcher::defaultResourceOptions();
-    options.requestOriginPolicy = RestrictToSameOrigin;
+    options.requestOriginPolicy = PotentiallyCrossOriginEnabled;
+    options.allowCredentials = DoNotAllowStoredCredentials;
 
     shapeValue->setImage(cssImageValue->cachedImage(m_fetcher, options));
 }
diff --git a/Source/core/css/resolver/TransformBuilder.cpp b/Source/core/css/resolver/TransformBuilder.cpp
index d65b7ed..4538fcd 100644
--- a/Source/core/css/resolver/TransformBuilder.cpp
+++ b/Source/core/css/resolver/TransformBuilder.cpp
@@ -31,15 +31,15 @@
 
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/CSSTransformValue.h"
-#include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
-#include "core/platform/graphics/transforms/MatrixTransformOperation.h"
-#include "core/platform/graphics/transforms/PerspectiveTransformOperation.h"
-#include "core/platform/graphics/transforms/RotateTransformOperation.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-#include "core/platform/graphics/transforms/SkewTransformOperation.h"
-#include "platform/transforms/TransformationMatrix.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
 #include "core/rendering/style/RenderStyle.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"
 
 namespace WebCore {
 
diff --git a/Source/core/css/resolver/TransformBuilder.h b/Source/core/css/resolver/TransformBuilder.h
index d582465..7e265c1 100644
--- a/Source/core/css/resolver/TransformBuilder.h
+++ b/Source/core/css/resolver/TransformBuilder.h
@@ -31,7 +31,7 @@
 #ifndef TransformBuilder_h
 #define TransformBuilder_h
 
-#include "core/platform/graphics/transforms/TransformOperations.h"
+#include "platform/transforms/TransformOperations.h"
 #include "wtf/Noncopyable.h"
 
 namespace WebCore {
diff --git a/Source/core/debugger_script_source.target.darwin-arm.mk b/Source/core/debugger_script_source.target.darwin-arm.mk
index cf2968b..e21ce73 100644
--- a/Source/core/debugger_script_source.target.darwin-arm.mk
+++ b/Source/core/debugger_script_source.target.darwin-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.darwin-mips.mk b/Source/core/debugger_script_source.target.darwin-mips.mk
index cf2968b..e21ce73 100644
--- a/Source/core/debugger_script_source.target.darwin-mips.mk
+++ b/Source/core/debugger_script_source.target.darwin-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.darwin-x86.mk b/Source/core/debugger_script_source.target.darwin-x86.mk
index cf2968b..e21ce73 100644
--- a/Source/core/debugger_script_source.target.darwin-x86.mk
+++ b/Source/core/debugger_script_source.target.darwin-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.linux-arm.mk b/Source/core/debugger_script_source.target.linux-arm.mk
index cf2968b..e21ce73 100644
--- a/Source/core/debugger_script_source.target.linux-arm.mk
+++ b/Source/core/debugger_script_source.target.linux-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.linux-mips.mk b/Source/core/debugger_script_source.target.linux-mips.mk
index cf2968b..e21ce73 100644
--- a/Source/core/debugger_script_source.target.linux-mips.mk
+++ b/Source/core/debugger_script_source.target.linux-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.linux-x86.mk b/Source/core/debugger_script_source.target.linux-x86.mk
index cf2968b..e21ce73 100644
--- a/Source/core/debugger_script_source.target.linux-x86.mk
+++ b/Source/core/debugger_script_source.target.linux-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/dom/ActiveDOMObject.cpp b/Source/core/dom/ActiveDOMObject.cpp
index 15ac7be..be52d0f 100644
--- a/Source/core/dom/ActiveDOMObject.cpp
+++ b/Source/core/dom/ActiveDOMObject.cpp
@@ -63,7 +63,7 @@
     m_suspendIfNeededCalled = true;
 #endif
     if (ExecutionContext* context = executionContext())
-        executionContext()->suspendActiveDOMObjectIfNeeded(this);
+        context->suspendActiveDOMObjectIfNeeded(this);
 }
 
 bool ActiveDOMObject::hasPendingActivity() const
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index e962c77..6b0e04e 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -85,7 +85,7 @@
         // This does everything appendChild() would do in this situation (assuming m_ignoreChildrenChanged was set),
         // but much more efficiently.
         textNode->setParentOrShadowHostNode(this);
-        treeScope().adoptIfNeeded(textNode.get());
+        treeScope().adoptIfNeeded(*textNode);
         setFirstChild(textNode.get());
         setLastChild(textNode.get());
     }
diff --git a/Source/core/dom/CSSSelectorWatch.cpp b/Source/core/dom/CSSSelectorWatch.cpp
index d746adb..4f8b781 100644
--- a/Source/core/dom/CSSSelectorWatch.cpp
+++ b/Source/core/dom/CSSSelectorWatch.cpp
@@ -77,7 +77,7 @@
         Vector<String> removedSelectors;
         copyToVector(m_addedSelectors, addedSelectors);
         copyToVector(m_removedSelectors, removedSelectors);
-        m_document.frame()->loader()->client()->selectorMatchChanged(addedSelectors, removedSelectors);
+        m_document.frame()->loader().client()->selectorMatchChanged(addedSelectors, removedSelectors);
     }
     m_addedSelectors.clear();
     m_removedSelectors.clear();
diff --git a/Source/core/dom/CharacterData.cpp b/Source/core/dom/CharacterData.cpp
index 4df25c9..305cad6 100644
--- a/Source/core/dom/CharacterData.cpp
+++ b/Source/core/dom/CharacterData.cpp
@@ -188,7 +188,7 @@
 
 void CharacterData::didModifyData(const String& oldData)
 {
-    if (OwnPtr<MutationObserverInterestGroup> mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(this))
+    if (OwnPtr<MutationObserverInterestGroup> mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(*this))
         mutationRecipients->enqueueMutationRecord(MutationRecord::createCharacterData(this, oldData));
 
     if (parentNode())
diff --git a/Source/core/dom/ChildListMutationScope.cpp b/Source/core/dom/ChildListMutationScope.cpp
index 6acb5b1..47e296e 100644
--- a/Source/core/dom/ChildListMutationScope.cpp
+++ b/Source/core/dom/ChildListMutationScope.cpp
@@ -62,14 +62,14 @@
     accumulatorMap().remove(m_target.get());
 }
 
-PassRefPtr<ChildListMutationAccumulator> ChildListMutationAccumulator::getOrCreate(Node* target)
+PassRefPtr<ChildListMutationAccumulator> ChildListMutationAccumulator::getOrCreate(Node& target)
 {
-    AccumulatorMap::AddResult result = accumulatorMap().add(target, 0);
+    AccumulatorMap::AddResult result = accumulatorMap().add(&target, 0);
     RefPtr<ChildListMutationAccumulator> accumulator;
     if (!result.isNewEntry)
         accumulator = result.iterator->value;
     else {
-        accumulator = adoptRef(new ChildListMutationAccumulator(target, MutationObserverInterestGroup::createForChildListMutation(target)));
+        accumulator = adoptRef(new ChildListMutationAccumulator(PassRefPtr<Node>(target), MutationObserverInterestGroup::createForChildListMutation(target)));
         result.iterator->value = accumulator.get();
     }
     return accumulator.release();
diff --git a/Source/core/dom/ChildListMutationScope.h b/Source/core/dom/ChildListMutationScope.h
index 442df97..d847d82 100644
--- a/Source/core/dom/ChildListMutationScope.h
+++ b/Source/core/dom/ChildListMutationScope.h
@@ -45,7 +45,7 @@
 // ChildListMutationAccumulator is not meant to be used directly; ChildListMutationScope is the public interface.
 class ChildListMutationAccumulator : public RefCounted<ChildListMutationAccumulator> {
 public:
-    static PassRefPtr<ChildListMutationAccumulator> getOrCreate(Node*);
+    static PassRefPtr<ChildListMutationAccumulator> getOrCreate(Node&);
     ~ChildListMutationAccumulator();
 
     void childAdded(PassRefPtr<Node>);
@@ -75,22 +75,22 @@
 class ChildListMutationScope {
     WTF_MAKE_NONCOPYABLE(ChildListMutationScope);
 public:
-    explicit ChildListMutationScope(Node* target)
+    explicit ChildListMutationScope(Node& target)
     {
-        if (target->document().hasMutationObserversOfType(MutationObserver::ChildList))
+        if (target.document().hasMutationObserversOfType(MutationObserver::ChildList))
             m_accumulator = ChildListMutationAccumulator::getOrCreate(target);
     }
 
-    void childAdded(Node* child)
+    void childAdded(Node& child)
     {
         if (m_accumulator && m_accumulator->hasObservers())
-            m_accumulator->childAdded(child);
+            m_accumulator->childAdded(PassRefPtr<Node>(child));
     }
 
-    void willRemoveChild(Node* child)
+    void willRemoveChild(Node& child)
     {
         if (m_accumulator && m_accumulator->hasObservers())
-            m_accumulator->willRemoveChild(child);
+            m_accumulator->willRemoveChild(PassRefPtr<Node>(child));
     }
 
 private:
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index 13140b6..676aac1 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -49,9 +49,9 @@
 
 namespace WebCore {
 
-static void dispatchChildInsertionEvents(Node*);
-static void dispatchChildRemovalEvents(Node*);
-static void updateTreeAfterInsertion(ContainerNode*, Node*);
+static void dispatchChildInsertionEvents(Node&);
+static void dispatchChildRemovalEvents(Node&);
+static void updateTreeAfterInsertion(ContainerNode&, Node&);
 
 ChildNodesLazySnapshot* ChildNodesLazySnapshot::latestSnapshot = 0;
 
@@ -82,22 +82,21 @@
             child->updateAncestorConnectedSubframeCountForRemoval();
     }
     // FIXME: We should be able to ASSERT(!confusingAndOftenMisusedAttached()) here: https://bugs.webkit.org/show_bug.cgi?id=107801
-    removeDetachedChildrenInContainer<Node, ContainerNode>(this);
+    removeDetachedChildrenInContainer<Node, ContainerNode>(*this);
 }
 
 void ContainerNode::parserTakeAllChildrenFrom(ContainerNode* oldParent)
 {
     while (RefPtr<Node> child = oldParent->firstChild()) {
-        oldParent->parserRemoveChild(child.get());
-        treeScope().adoptIfNeeded(child.get());
+        oldParent->parserRemoveChild(*child);
+        treeScope().adoptIfNeeded(*child);
         parserAppendChild(child.get());
     }
 }
 
 ContainerNode::~ContainerNode()
 {
-    if (Document* document = documentInternal())
-        willBeDeletedFrom(document);
+    willBeDeletedFromDocument();
     removeDetachedChildren();
 }
 
@@ -235,9 +234,10 @@
 
     InspectorInstrumentation::willInsertDOMNode(this);
 
-    ChildListMutationScope mutation(this);
+    ChildListMutationScope mutation(*this);
     for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
-        Node* child = it->get();
+        ASSERT(*it);
+        Node& child = **it;
 
         // Due to arbitrary code running in response to a DOM mutation event it's
         // possible that "next" is no longer a child of "this".
@@ -245,43 +245,42 @@
         // In either of those cases, we'll just stop.
         if (next->parentNode() != this)
             break;
-        if (child->parentNode())
+        if (child.parentNode())
             break;
 
         treeScope().adoptIfNeeded(child);
 
-        insertBeforeCommon(next.get(), child);
+        insertBeforeCommon(*next, child);
 
-        updateTreeAfterInsertion(this, child);
+        updateTreeAfterInsertion(*this, child);
     }
 
     dispatchSubtreeModifiedEvent();
 }
 
-void ContainerNode::insertBeforeCommon(Node* nextChild, Node* newChild)
+void ContainerNode::insertBeforeCommon(Node& nextChild, Node& newChild)
 {
     NoEventDispatchAssertion assertNoEventDispatch;
 
-    ASSERT(newChild);
-    ASSERT(!newChild->parentNode()); // Use insertBefore if you need to handle reparenting (and want DOM mutation events).
-    ASSERT(!newChild->nextSibling());
-    ASSERT(!newChild->previousSibling());
-    ASSERT(!newChild->isShadowRoot());
+    ASSERT(!newChild.parentNode()); // Use insertBefore if you need to handle reparenting (and want DOM mutation events).
+    ASSERT(!newChild.nextSibling());
+    ASSERT(!newChild.previousSibling());
+    ASSERT(!newChild.isShadowRoot());
 
-    Node* prev = nextChild->previousSibling();
+    Node* prev = nextChild.previousSibling();
     ASSERT(m_lastChild != prev);
-    nextChild->setPreviousSibling(newChild);
+    nextChild.setPreviousSibling(&newChild);
     if (prev) {
         ASSERT(m_firstChild != nextChild);
         ASSERT(prev->nextSibling() == nextChild);
-        prev->setNextSibling(newChild);
+        prev->setNextSibling(&newChild);
     } else {
         ASSERT(m_firstChild == nextChild);
-        m_firstChild = newChild;
+        m_firstChild = &newChild;
     }
-    newChild->setParentOrShadowHostNode(this);
-    newChild->setPreviousSibling(prev);
-    newChild->setNextSibling(nextChild);
+    newChild.setParentOrShadowHostNode(this);
+    newChild.setPreviousSibling(prev);
+    newChild.setNextSibling(&nextChild);
 }
 
 void ContainerNode::parserInsertBefore(PassRefPtr<Node> newChild, Node* nextChild)
@@ -298,15 +297,15 @@
     if (document() != newChild->document())
         document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
 
-    insertBeforeCommon(nextChild, newChild.get());
+    insertBeforeCommon(*nextChild, *newChild);
 
     newChild->updateAncestorConnectedSubframeCountForInsertion();
 
-    ChildListMutationScope(this).childAdded(newChild.get());
+    ChildListMutationScope(*this).childAdded(*newChild);
 
     childrenChanged(true, newChild->previousSibling(), nextChild, 1);
 
-    ChildNodeInsertionNotifier(this).notify(newChild.get());
+    ChildNodeInsertionNotifier(*this).notify(*newChild);
 }
 
 void ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& es)
@@ -335,7 +334,7 @@
         return;
     }
 
-    ChildListMutationScope mutation(this);
+    ChildListMutationScope mutation(*this);
 
     RefPtr<Node> next = oldChild->nextSibling();
 
@@ -365,7 +364,8 @@
 
     // Add the new child(ren)
     for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
-        Node* child = it->get();
+        ASSERT(*it);
+        Node& child = **it;
 
         // Due to arbitrary code running in response to a DOM mutation event it's
         // possible that "next" is no longer a child of "this".
@@ -373,7 +373,7 @@
         // In either of those cases, we'll just stop.
         if (next && next->parentNode() != this)
             break;
-        if (child->parentNode())
+        if (child.parentNode())
             break;
 
         treeScope().adoptIfNeeded(child);
@@ -382,37 +382,38 @@
         {
             NoEventDispatchAssertion assertNoEventDispatch;
             if (next)
-                insertBeforeCommon(next.get(), child);
+                insertBeforeCommon(*next, child);
             else
-                appendChildToContainer(child, this);
+                appendChildToContainer(child, *this);
         }
 
-        updateTreeAfterInsertion(this, child);
+        updateTreeAfterInsertion(*this, child);
     }
 
     dispatchSubtreeModifiedEvent();
 }
 
-static void willRemoveChild(Node* child)
+static void willRemoveChild(Node& child)
 {
-    ASSERT(child->parentNode());
-    ChildListMutationScope(child->parentNode()).willRemoveChild(child);
-    child->notifyMutationObserversNodeWillDetach();
+    ASSERT(child.parentNode());
+    ChildListMutationScope(*child.parentNode()).willRemoveChild(child);
+    child.notifyMutationObserversNodeWillDetach();
     dispatchChildRemovalEvents(child);
-    child->document().nodeWillBeRemoved(child); // e.g. mutation event listener can create a new range.
+    child.document().nodeWillBeRemoved(&child); // e.g. mutation event listener can create a new range.
     ChildFrameDisconnector(child).disconnect();
 }
 
-static void willRemoveChildren(ContainerNode* container)
+static void willRemoveChildren(ContainerNode& container)
 {
     NodeVector children;
-    getChildNodes(container, children);
+    getChildNodes(&container, children);
 
     ChildListMutationScope mutation(container);
     for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) {
-        Node* child = it->get();
+        ASSERT(*it);
+        Node& child = **it;
         mutation.willRemoveChild(child);
-        child->notifyMutationObserversNodeWillDetach();
+        child.notifyMutationObserversNodeWillDetach();
 
         // fire removed from document mutation events.
         dispatchChildRemovalEvents(child);
@@ -423,7 +424,7 @@
 
 void ContainerNode::disconnectDescendantFrames()
 {
-    ChildFrameDisconnector(this).disconnect();
+    ChildFrameDisconnector(*this).disconnect();
 }
 
 void ContainerNode::removeChild(Node* oldChild, ExceptionState& es)
@@ -454,7 +455,7 @@
         return;
     }
 
-    willRemoveChild(child.get());
+    willRemoveChild(*child);
 
     // Mutation events might have moved this child into a different parent.
     if (child->parentNode() != this) {
@@ -467,23 +468,22 @@
 
         Node* prev = child->previousSibling();
         Node* next = child->nextSibling();
-        removeBetween(prev, next, child.get());
+        removeBetween(prev, next, *child);
         childrenChanged(false, prev, next, -1);
-        ChildNodeRemovalNotifier(this).notify(child.get());
+        ChildNodeRemovalNotifier(*this).notify(*child);
     }
     dispatchSubtreeModifiedEvent();
 }
 
-void ContainerNode::removeBetween(Node* previousChild, Node* nextChild, Node* oldChild)
+void ContainerNode::removeBetween(Node* previousChild, Node* nextChild, Node& oldChild)
 {
     NoEventDispatchAssertion assertNoEventDispatch;
 
-    ASSERT(oldChild);
-    ASSERT(oldChild->parentNode() == this);
+    ASSERT(oldChild.parentNode() == this);
 
     // Remove from rendering tree
-    if (oldChild->confusingAndOftenMisusedAttached())
-        oldChild->detach();
+    if (oldChild.confusingAndOftenMisusedAttached())
+        oldChild.detach();
 
     if (nextChild)
         nextChild->setPreviousSibling(previousChild);
@@ -494,31 +494,30 @@
     if (m_lastChild == oldChild)
         m_lastChild = previousChild;
 
-    oldChild->setPreviousSibling(0);
-    oldChild->setNextSibling(0);
-    oldChild->setParentOrShadowHostNode(0);
+    oldChild.setPreviousSibling(0);
+    oldChild.setNextSibling(0);
+    oldChild.setParentOrShadowHostNode(0);
 
     document().adoptIfNeeded(oldChild);
 }
 
-void ContainerNode::parserRemoveChild(Node* oldChild)
+void ContainerNode::parserRemoveChild(Node& oldChild)
 {
-    ASSERT(oldChild);
-    ASSERT(oldChild->parentNode() == this);
-    ASSERT(!oldChild->isDocumentFragment());
+    ASSERT(oldChild.parentNode() == this);
+    ASSERT(!oldChild.isDocumentFragment());
 
-    Node* prev = oldChild->previousSibling();
-    Node* next = oldChild->nextSibling();
+    Node* prev = oldChild.previousSibling();
+    Node* next = oldChild.nextSibling();
 
-    oldChild->updateAncestorConnectedSubframeCountForRemoval();
+    oldChild.updateAncestorConnectedSubframeCountForRemoval();
 
-    ChildListMutationScope(this).willRemoveChild(oldChild);
-    oldChild->notifyMutationObserversNodeWillDetach();
+    ChildListMutationScope(*this).willRemoveChild(oldChild);
+    oldChild.notifyMutationObserversNodeWillDetach();
 
     removeBetween(prev, next, oldChild);
 
     childrenChanged(true, prev, next, -1);
-    ChildNodeRemovalNotifier(this).notify(oldChild);
+    ChildNodeRemovalNotifier(*this).notify(oldChild);
 }
 
 // this differs from other remove functions because it forcibly removes all the children,
@@ -536,7 +535,7 @@
 
     // Do any prep work needed before actually starting to detach
     // and remove... e.g. stop loading frames, fire unload events.
-    willRemoveChildren(protect.get());
+    willRemoveChildren(*this);
 
     {
         // Removing focus can cause frames to load, either via events (focusout, blur)
@@ -548,9 +547,11 @@
         // This must be later than willRemoveChildren, which might change focus
         // state of a child.
         document().removeFocusedElementOfSubtree(this, true);
+
+        // Removing a node from a selection can cause widget updates.
+        document().nodeChildrenWillBeRemoved(this);
     }
 
-    document().nodeChildrenWillBeRemoved(this);
 
     NodeVector removedChildren;
     {
@@ -560,14 +561,14 @@
             removedChildren.reserveInitialCapacity(childNodeCount());
             while (m_firstChild) {
                 removedChildren.append(m_firstChild);
-                removeBetween(0, m_firstChild->nextSibling(), m_firstChild);
+                removeBetween(0, m_firstChild->nextSibling(), *m_firstChild);
             }
         }
 
         childrenChanged(false, 0, 0, -static_cast<int>(removedChildren.size()));
 
         for (size_t i = 0; i < removedChildren.size(); ++i)
-            ChildNodeRemovalNotifier(this).notify(removedChildren[i].get());
+            ChildNodeRemovalNotifier(*this).notify(*removedChildren[i]);
     }
 
     dispatchSubtreeModifiedEvent();
@@ -603,14 +604,15 @@
     InspectorInstrumentation::willInsertDOMNode(this);
 
     // Now actually add the child(ren)
-    ChildListMutationScope mutation(this);
+    ChildListMutationScope mutation(*this);
     for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
-        Node* child = it->get();
+        ASSERT(*it);
+        Node& child = **it;
 
         // If the child has a parent again, just stop what we're doing, because
         // that means someone is doing something with DOM mutation -- can't re-parent
         // a child that already has a parent.
-        if (child->parentNode())
+        if (child.parentNode())
             break;
 
         treeScope().adoptIfNeeded(child);
@@ -618,10 +620,10 @@
         // Append child to the end of the list
         {
             NoEventDispatchAssertion assertNoEventDispatch;
-            appendChildToContainer(child, this);
+            appendChildToContainer(child, *this);
         }
 
-        updateTreeAfterInsertion(this, child);
+        updateTreeAfterInsertion(*this, child);
     }
 
     dispatchSubtreeModifiedEvent();
@@ -641,16 +643,16 @@
     {
         NoEventDispatchAssertion assertNoEventDispatch;
         // FIXME: This method should take a PassRefPtr.
-        appendChildToContainer(newChild.get(), this);
-        treeScope().adoptIfNeeded(newChild.get());
+        appendChildToContainer(*newChild, *this);
+        treeScope().adoptIfNeeded(*newChild);
     }
 
     newChild->updateAncestorConnectedSubframeCountForInsertion();
 
-    ChildListMutationScope(this).childAdded(newChild.get());
+    ChildListMutationScope(*this).childAdded(*newChild);
 
     childrenChanged(true, last, 0, 1);
-    ChildNodeInsertionNotifier(this).notify(newChild.get());
+    ChildNodeInsertionNotifier(*this).notify(*newChild);
 }
 
 void ContainerNode::attach(const AttachContext& context)
@@ -872,7 +874,7 @@
 
 PassRefPtr<HTMLCollection> ContainerNode::children()
 {
-    return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, NodeChildren);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, NodeChildren);
 }
 
 Element* ContainerNode::firstElementChild() const
@@ -917,62 +919,62 @@
     return n;
 }
 
-static void dispatchChildInsertionEvents(Node* child)
+static void dispatchChildInsertionEvents(Node& child)
 {
-    if (child->isInShadowTree())
+    if (child.isInShadowTree())
         return;
 
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
 
-    RefPtr<Node> c = child;
-    RefPtr<Document> document(child->document());
+    RefPtr<Node> c(child);
+    RefPtr<Document> document(child.document());
 
     if (c->parentNode() && document->hasListenerType(Document::DOMNODEINSERTED_LISTENER))
         c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeInserted, true, c->parentNode()));
 
     // dispatch the DOMNodeInsertedIntoDocument event to all descendants
     if (c->inDocument() && document->hasListenerType(Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER)) {
-        for (; c; c = NodeTraversal::next(c.get(), child))
+        for (; c; c = NodeTraversal::next(c.get(), &child))
             c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeInsertedIntoDocument, false));
     }
 }
 
-static void dispatchChildRemovalEvents(Node* child)
+static void dispatchChildRemovalEvents(Node& child)
 {
-    if (child->isInShadowTree()) {
-        InspectorInstrumentation::willRemoveDOMNode(child);
+    if (child.isInShadowTree()) {
+        InspectorInstrumentation::willRemoveDOMNode(&child);
         return;
     }
 
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
 
-    InspectorInstrumentation::willRemoveDOMNode(child);
+    InspectorInstrumentation::willRemoveDOMNode(&child);
 
-    RefPtr<Node> c = child;
-    RefPtr<Document> document(child->document());
+    RefPtr<Node> c(child);
+    RefPtr<Document> document(child.document());
 
     // dispatch pre-removal mutation events
     if (c->parentNode() && document->hasListenerType(Document::DOMNODEREMOVED_LISTENER)) {
-        NodeChildRemovalTracker scope(child);
+        NodeChildRemovalTracker scope(&child);
         c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeRemoved, true, c->parentNode()));
     }
 
     // dispatch the DOMNodeRemovedFromDocument event to all descendants
     if (c->inDocument() && document->hasListenerType(Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER)) {
-        NodeChildRemovalTracker scope(child);
-        for (; c; c = NodeTraversal::next(c.get(), child))
+        NodeChildRemovalTracker scope(&child);
+        for (; c; c = NodeTraversal::next(c.get(), &child))
             c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeRemovedFromDocument, false));
     }
 }
 
-static void updateTreeAfterInsertion(ContainerNode* parent, Node* child)
+static void updateTreeAfterInsertion(ContainerNode& parent, Node& child)
 {
-    ASSERT(parent->refCount());
-    ASSERT(child->refCount());
+    ASSERT(parent.refCount());
+    ASSERT(child.refCount());
 
     ChildListMutationScope(parent).childAdded(child);
 
-    parent->childrenChanged(false, child->previousSibling(), child->nextSibling(), 1);
+    parent.childrenChanged(false, child.previousSibling(), child.nextSibling(), 1);
 
     ChildNodeInsertionNotifier(parent).notify(child);
 
diff --git a/Source/core/dom/ContainerNode.h b/Source/core/dom/ContainerNode.h
index 61034cb..16d0942 100644
--- a/Source/core/dom/ContainerNode.h
+++ b/Source/core/dom/ContainerNode.h
@@ -37,8 +37,8 @@
 
 namespace Private {
     template<class GenericNode, class GenericNodeContainer>
-    void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer*);
-};
+    void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
+}
 
 class NoEventDispatchAssertion {
 public:
@@ -105,7 +105,7 @@
     // They don't send DOM mutation events or handle reparenting.
     // However, arbitrary code may be run by beforeload handlers.
     void parserAppendChild(PassRefPtr<Node>);
-    void parserRemoveChild(Node*);
+    void parserRemoveChild(Node&);
     void parserInsertBefore(PassRefPtr<Node> newChild, Node* refChild);
     void parserTakeAllChildrenFrom(ContainerNode*);
 
@@ -135,18 +135,18 @@
     ContainerNode(TreeScope*, ConstructionType = CreateContainer);
 
     template<class GenericNode, class GenericNodeContainer>
-    friend void appendChildToContainer(GenericNode* child, GenericNodeContainer*);
+    friend void appendChildToContainer(GenericNode& child, GenericNodeContainer&);
 
     template<class GenericNode, class GenericNodeContainer>
-    friend void Private::addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer*);
+    friend void Private::addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
 
     void removeDetachedChildren();
     void setFirstChild(Node* child) { m_firstChild = child; }
     void setLastChild(Node* child) { m_lastChild = child; }
 
 private:
-    void removeBetween(Node* previousChild, Node* nextChild, Node* oldChild);
-    void insertBeforeCommon(Node* nextChild, Node* oldChild);
+    void removeBetween(Node* previousChild, Node* nextChild, Node& oldChild);
+    void insertBeforeCommon(Node& nextChild, Node& oldChild);
 
     void attachChildren(const AttachContext& = AttachContext());
     void detachChildren(const AttachContext& = AttachContext());
@@ -246,8 +246,8 @@
     WTF_MAKE_NONCOPYABLE(ChildNodesLazySnapshot);
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit ChildNodesLazySnapshot(Node* parentNode)
-        : m_currentNode(parentNode->firstChild())
+    explicit ChildNodesLazySnapshot(Node& parentNode)
+        : m_currentNode(parentNode.firstChild())
         , m_currentIndex(0)
     {
         m_nextSnapshot = latestSnapshot;
diff --git a/Source/core/dom/ContainerNodeAlgorithms.cpp b/Source/core/dom/ContainerNodeAlgorithms.cpp
index ab67eef..1caa683 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.cpp
+++ b/Source/core/dom/ContainerNodeAlgorithms.cpp
@@ -42,115 +42,115 @@
     }
 };
 
-void ChildNodeInsertionNotifier::notifyDescendantInsertedIntoDocument(ContainerNode* node)
+void ChildNodeInsertionNotifier::notifyDescendantInsertedIntoDocument(ContainerNode& node)
 {
     ChildNodesLazySnapshot snapshot(node);
     while (RefPtr<Node> child = snapshot.nextNode()) {
         // If we have been removed from the document during this loop, then
         // we don't want to tell the rest of our children that they've been
         // inserted into the document because they haven't.
-        if (node->inDocument() && child->parentNode() == node)
-            notifyNodeInsertedIntoDocument(child.get());
+        if (node.inDocument() && child->parentNode() == node)
+            notifyNodeInsertedIntoDocument(*child);
     }
 
-    if (!node->isElementNode())
+    if (!node.isElementNode())
         return;
 
-    if (ElementShadow* shadow = toElement(node)->shadow()) {
+    if (ElementShadow* shadow = toElement(node).shadow()) {
         ShadowRootVector roots(shadow);
         for (size_t i = 0; i < roots.size(); ++i) {
-            if (node->inDocument() && roots[i]->host() == node)
-                notifyNodeInsertedIntoDocument(roots[i].get());
+            if (node.inDocument() && roots[i]->host() == node)
+                notifyNodeInsertedIntoDocument(*roots[i]);
         }
     }
 }
 
-void ChildNodeInsertionNotifier::notifyDescendantInsertedIntoTree(ContainerNode* node)
+void ChildNodeInsertionNotifier::notifyDescendantInsertedIntoTree(ContainerNode& node)
 {
-    for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
+    for (Node* child = node.firstChild(); child; child = child->nextSibling()) {
         if (child->isContainerNode())
-            notifyNodeInsertedIntoTree(toContainerNode(child));
+            notifyNodeInsertedIntoTree(toContainerNode(*child));
     }
 
-    for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
-        notifyNodeInsertedIntoTree(root);
+    for (ShadowRoot* root = node.youngestShadowRoot(); root; root = root->olderShadowRoot())
+        notifyNodeInsertedIntoTree(*root);
 }
 
-void ChildNodeRemovalNotifier::notifyDescendantRemovedFromDocument(ContainerNode* node)
+void ChildNodeRemovalNotifier::notifyDescendantRemovedFromDocument(ContainerNode& node)
 {
     ChildNodesLazySnapshot snapshot(node);
     while (RefPtr<Node> child = snapshot.nextNode()) {
         // If we have been added to the document during this loop, then we
         // don't want to tell the rest of our children that they've been
         // removed from the document because they haven't.
-        if (!node->inDocument() && child->parentNode() == node)
-            notifyNodeRemovedFromDocument(child.get());
+        if (!node.inDocument() && child->parentNode() == node)
+            notifyNodeRemovedFromDocument(*child);
     }
 
-    if (!node->isElementNode())
+    if (!node.isElementNode())
         return;
 
-    if (node->document().cssTarget() == node)
-        node->document().setCSSTarget(0);
+    if (node.document().cssTarget() == node)
+        node.document().setCSSTarget(0);
 
-    if (ElementShadow* shadow = toElement(node)->shadow()) {
+    if (ElementShadow* shadow = toElement(node).shadow()) {
         ShadowRootVector roots(shadow);
         for (size_t i = 0; i < roots.size(); ++i) {
-            if (!node->inDocument() && roots[i]->host() == node)
-                notifyNodeRemovedFromDocument(roots[i].get());
+            if (!node.inDocument() && roots[i]->host() == node)
+                notifyNodeRemovedFromDocument(*roots[i]);
         }
     }
 }
 
-void ChildNodeRemovalNotifier::notifyDescendantRemovedFromTree(ContainerNode* node)
+void ChildNodeRemovalNotifier::notifyDescendantRemovedFromTree(ContainerNode& node)
 {
-    for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
+    for (Node* child = node.firstChild(); child; child = child->nextSibling()) {
         if (child->isContainerNode())
-            notifyNodeRemovedFromTree(toContainerNode(child));
+            notifyNodeRemovedFromTree(toContainerNode(*child));
     }
 
-    if (!node->isElementNode())
+    if (!node.isElementNode())
         return;
 
-    if (ElementShadow* shadow = toElement(node)->shadow()) {
+    if (ElementShadow* shadow = toElement(node).shadow()) {
         ShadowRootVector roots(shadow);
         for (size_t i = 0; i < roots.size(); ++i)
-            notifyNodeRemovedFromTree(roots[i].get());
+            notifyNodeRemovedFromTree(*roots[i]);
     }
 }
 
-void ChildFrameDisconnector::collectFrameOwners(ElementShadow* shadow)
+void ChildFrameDisconnector::collectFrameOwners(ElementShadow& shadow)
 {
-    for (ShadowRoot* root = shadow->youngestShadowRoot(); root; root = root->olderShadowRoot())
-        collectFrameOwners(root);
+    for (ShadowRoot* root = shadow.youngestShadowRoot(); root; root = root->olderShadowRoot())
+        collectFrameOwners(*root);
 }
 
 #ifndef NDEBUG
-unsigned assertConnectedSubrameCountIsConsistent(Node* node)
+unsigned assertConnectedSubrameCountIsConsistent(Node& node)
 {
     unsigned count = 0;
 
-    if (node->isElementNode()) {
-        if (node->isFrameOwnerElement() && toHTMLFrameOwnerElement(node)->contentFrame())
+    if (node.isElementNode()) {
+        if (node.isFrameOwnerElement() && toHTMLFrameOwnerElement(node).contentFrame())
             count++;
 
-        if (ElementShadow* shadow = toElement(node)->shadow()) {
+        if (ElementShadow* shadow = toElement(node).shadow()) {
             for (ShadowRoot* root = shadow->youngestShadowRoot(); root; root = root->olderShadowRoot())
-                count += assertConnectedSubrameCountIsConsistent(root);
+                count += assertConnectedSubrameCountIsConsistent(*root);
         }
     }
 
-    for (Node* child = node->firstChild(); child; child = child->nextSibling())
-        count += assertConnectedSubrameCountIsConsistent(child);
+    for (Node* child = node.firstChild(); child; child = child->nextSibling())
+        count += assertConnectedSubrameCountIsConsistent(*child);
 
     // If we undercount there's possibly a security bug since we'd leave frames
     // in subtrees outside the document.
-    ASSERT(node->connectedSubframeCount() >= count);
+    ASSERT(node.connectedSubframeCount() >= count);
 
     // If we overcount it's safe, but not optimal because it means we'll traverse
     // through the document in ChildFrameDisconnector looking for frames that have
     // already been disconnected.
-    ASSERT(node->connectedSubframeCount() == count);
+    ASSERT(node.connectedSubframeCount() == count);
 
     return count;
 }
diff --git a/Source/core/dom/ContainerNodeAlgorithms.h b/Source/core/dom/ContainerNodeAlgorithms.h
index a6683fd..a0b7dbe 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.h
+++ b/Source/core/dom/ContainerNodeAlgorithms.h
@@ -31,52 +31,52 @@
 
 class ChildNodeInsertionNotifier {
 public:
-    explicit ChildNodeInsertionNotifier(ContainerNode* insertionPoint)
+    explicit ChildNodeInsertionNotifier(ContainerNode& insertionPoint)
         : m_insertionPoint(insertionPoint)
     {
     }
 
-    void notify(Node*);
+    void notify(Node&);
 
 private:
-    void notifyDescendantInsertedIntoDocument(ContainerNode*);
-    void notifyDescendantInsertedIntoTree(ContainerNode*);
-    void notifyNodeInsertedIntoDocument(Node*);
-    void notifyNodeInsertedIntoTree(ContainerNode*);
+    void notifyDescendantInsertedIntoDocument(ContainerNode&);
+    void notifyDescendantInsertedIntoTree(ContainerNode&);
+    void notifyNodeInsertedIntoDocument(Node&);
+    void notifyNodeInsertedIntoTree(ContainerNode&);
 
-    ContainerNode* m_insertionPoint;
+    ContainerNode& m_insertionPoint;
     Vector< RefPtr<Node> > m_postInsertionNotificationTargets;
 };
 
 class ChildNodeRemovalNotifier {
 public:
-    explicit ChildNodeRemovalNotifier(ContainerNode* insertionPoint)
+    explicit ChildNodeRemovalNotifier(ContainerNode& insertionPoint)
         : m_insertionPoint(insertionPoint)
     {
     }
 
-    void notify(Node*);
+    void notify(Node&);
 
 private:
-    void notifyDescendantRemovedFromDocument(ContainerNode*);
-    void notifyDescendantRemovedFromTree(ContainerNode*);
-    void notifyNodeRemovedFromDocument(Node*);
-    void notifyNodeRemovedFromTree(ContainerNode*);
+    void notifyDescendantRemovedFromDocument(ContainerNode&);
+    void notifyDescendantRemovedFromTree(ContainerNode&);
+    void notifyNodeRemovedFromDocument(Node&);
+    void notifyNodeRemovedFromTree(ContainerNode&);
 
-    ContainerNode* m_insertionPoint;
+    ContainerNode& m_insertionPoint;
 };
 
 namespace Private {
 
     template<class GenericNode, class GenericNodeContainer>
-    void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer*);
+    void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
 
 }
 
 // Helper functions for TreeShared-derived classes, which have a 'Node' style interface
 // This applies to 'ContainerNode' and 'SVGElementInstance'
 template<class GenericNode, class GenericNodeContainer>
-inline void removeDetachedChildrenInContainer(GenericNodeContainer* container)
+inline void removeDetachedChildrenInContainer(GenericNodeContainer& container)
 {
     // List of nodes to be deleted.
     GenericNode* head = 0;
@@ -97,25 +97,26 @@
             tail = 0;
 
         if (n->hasChildNodes())
-            Private::addChildNodesToDeletionQueue<GenericNode, GenericNodeContainer>(head, tail, static_cast<GenericNodeContainer*>(n));
+            Private::addChildNodesToDeletionQueue<GenericNode, GenericNodeContainer>(head, tail, static_cast<GenericNodeContainer&>(*n));
 
         delete n;
     }
 }
 
 template<class GenericNode, class GenericNodeContainer>
-inline void appendChildToContainer(GenericNode* child, GenericNodeContainer* container)
+inline void appendChildToContainer(GenericNode& child, GenericNodeContainer& container)
 {
-    child->setParentOrShadowHostNode(container);
+    child.setParentOrShadowHostNode(&container);
 
-    GenericNode* lastChild = container->lastChild();
+    GenericNode* lastChild = container.lastChild();
     if (lastChild) {
-        child->setPreviousSibling(lastChild);
-        lastChild->setNextSibling(child);
-    } else
-        container->setFirstChild(child);
+        child.setPreviousSibling(lastChild);
+        lastChild->setNextSibling(&child);
+    } else {
+        container.setFirstChild(&child);
+    }
 
-    container->setLastChild(child);
+    container.setLastChild(&child);
 }
 
 // Helper methods for removeDetachedChildrenInContainer, hidden from WebCore namespace
@@ -123,7 +124,7 @@
 
     template<class GenericNode, class GenericNodeContainer, bool dispatchRemovalNotification>
     struct NodeRemovalDispatcher {
-        static void dispatch(GenericNode*, GenericNodeContainer*)
+        static void dispatch(GenericNode&, GenericNodeContainer&)
         {
             // no-op, by default
         }
@@ -131,12 +132,12 @@
 
     template<class GenericNode, class GenericNodeContainer>
     struct NodeRemovalDispatcher<GenericNode, GenericNodeContainer, true> {
-        static void dispatch(GenericNode* node, GenericNodeContainer* container)
+        static void dispatch(GenericNode& node, GenericNodeContainer& container)
         {
             // Clean up any TreeScope to a removed tree.
-            if (Document* containerDocument = container->ownerDocument())
+            if (Document* containerDocument = container.ownerDocument())
                 containerDocument->adoptIfNeeded(node);
-            if (node->inDocument())
+            if (node.inDocument())
                 ChildNodeRemovalNotifier(container).notify(node);
         }
     };
@@ -152,17 +153,17 @@
     };
 
     template<class GenericNode, class GenericNodeContainer>
-    void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer* container)
+    void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer& container)
     {
         // We have to tell all children that their parent has died.
         GenericNode* next = 0;
-        for (GenericNode* n = container->firstChild(); n != 0; n = next) {
+        for (GenericNode* n = container.firstChild(); n; n = next) {
             ASSERT_WITH_SECURITY_IMPLICATION(!n->m_deletionHasBegun);
 
             next = n->nextSibling();
             n->setNextSibling(0);
             n->setParentOrShadowHostNode(0);
-            container->setFirstChild(next);
+            container.setFirstChild(next);
             if (next)
                 next->setPreviousSibling(0);
 
@@ -180,47 +181,47 @@
                 tail = n;
             } else {
                 RefPtr<GenericNode> protect(n); // removedFromDocument may remove remove all references to this node.
-                NodeRemovalDispatcher<GenericNode, GenericNodeContainer, ShouldDispatchRemovalNotification<GenericNode>::value>::dispatch(n, container);
+                NodeRemovalDispatcher<GenericNode, GenericNodeContainer, ShouldDispatchRemovalNotification<GenericNode>::value>::dispatch(*n, container);
             }
         }
 
-        container->setLastChild(0);
+        container.setLastChild(0);
     }
 
 } // namespace Private
 
-inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoDocument(Node* node)
+inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoDocument(Node& node)
 {
-    ASSERT(m_insertionPoint->inDocument());
+    ASSERT(m_insertionPoint.inDocument());
     RefPtr<Node> protect(node);
-    if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node->insertedInto(m_insertionPoint))
-        m_postInsertionNotificationTargets.append(node);
-    if (node->isContainerNode())
+    if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(&m_insertionPoint))
+        m_postInsertionNotificationTargets.append(&node);
+    if (node.isContainerNode())
         notifyDescendantInsertedIntoDocument(toContainerNode(node));
 }
 
-inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoTree(ContainerNode* node)
+inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoTree(ContainerNode& node)
 {
     NoEventDispatchAssertion assertNoEventDispatch;
-    ASSERT(!m_insertionPoint->inDocument());
+    ASSERT(!m_insertionPoint.inDocument());
 
-    if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node->insertedInto(m_insertionPoint))
-        m_postInsertionNotificationTargets.append(node);
+    if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(&m_insertionPoint))
+        m_postInsertionNotificationTargets.append(&node);
     notifyDescendantInsertedIntoTree(node);
 }
 
-inline void ChildNodeInsertionNotifier::notify(Node* node)
+inline void ChildNodeInsertionNotifier::notify(Node& node)
 {
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
 
-    InspectorInstrumentation::didInsertDOMNode(node);
+    InspectorInstrumentation::didInsertDOMNode(&node);
 
-    RefPtr<Document> protectDocument(node->document());
+    RefPtr<Document> protectDocument(node.document());
     RefPtr<Node> protectNode(node);
 
-    if (m_insertionPoint->inDocument())
+    if (m_insertionPoint.inDocument())
         notifyNodeInsertedIntoDocument(node);
-    else if (node->isContainerNode())
+    else if (node.isContainerNode())
         notifyNodeInsertedIntoTree(toContainerNode(node));
 
     // Script runs in didNotifySubtreeInsertions so we should lazy attach before
@@ -228,40 +229,40 @@
     // were inserted.
     // FIXME: We should merge the lazy attach logic into the tree traversal in
     // notifyNodeInsertedIntoDocument.
-    if (!node->confusingAndOftenMisusedAttached() && node->parentNode() && node->parentNode()->confusingAndOftenMisusedAttached())
-        node->lazyAttach();
+    if (!node.confusingAndOftenMisusedAttached() && node.parentNode() && node.parentNode()->confusingAndOftenMisusedAttached())
+        node.lazyAttach();
 
     for (size_t i = 0; i < m_postInsertionNotificationTargets.size(); ++i) {
-        Node* node = m_postInsertionNotificationTargets[i].get();
-        if (node->inDocument())
-            node->didNotifySubtreeInsertionsToDocument();
+        Node* targetNode = m_postInsertionNotificationTargets[i].get();
+        if (targetNode->inDocument())
+            targetNode->didNotifySubtreeInsertionsToDocument();
     }
 }
 
-inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromDocument(Node* node)
+inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromDocument(Node& node)
 {
-    ASSERT(m_insertionPoint->inDocument());
-    node->removedFrom(m_insertionPoint);
+    ASSERT(m_insertionPoint.inDocument());
+    node.removedFrom(&m_insertionPoint);
 
-    if (node->isContainerNode())
+    if (node.isContainerNode())
         notifyDescendantRemovedFromDocument(toContainerNode(node));
 }
 
-inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromTree(ContainerNode* node)
+inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromTree(ContainerNode& node)
 {
     NoEventDispatchAssertion assertNoEventDispatch;
-    ASSERT(!m_insertionPoint->inDocument());
+    ASSERT(!m_insertionPoint.inDocument());
 
-    node->removedFrom(m_insertionPoint);
+    node.removedFrom(&m_insertionPoint);
     notifyDescendantRemovedFromTree(node);
 }
 
-inline void ChildNodeRemovalNotifier::notify(Node* node)
+inline void ChildNodeRemovalNotifier::notify(Node& node)
 {
-    if (node->inDocument()) {
+    if (node.inDocument()) {
         notifyNodeRemovedFromDocument(node);
-        node->document().notifyRemovePendingSheetIfNeeded();
-    } else if (node->isContainerNode())
+        node.document().notifyRemovePendingSheetIfNeeded();
+    } else if (node.isContainerNode())
         notifyNodeRemovedFromTree(toContainerNode(node));
 }
 
@@ -272,7 +273,7 @@
         DescendantsOnly
     };
 
-    explicit ChildFrameDisconnector(Node* root)
+    explicit ChildFrameDisconnector(Node& root)
         : m_root(root)
     {
     }
@@ -280,45 +281,45 @@
     void disconnect(DisconnectPolicy = RootAndDescendants);
 
 private:
-    void collectFrameOwners(Node* root);
-    void collectFrameOwners(ElementShadow*);
+    void collectFrameOwners(Node& root);
+    void collectFrameOwners(ElementShadow&);
     void disconnectCollectedFrameOwners();
 
     Vector<RefPtr<HTMLFrameOwnerElement>, 10> m_frameOwners;
-    Node* m_root;
+    Node& m_root;
 };
 
 #ifndef NDEBUG
-unsigned assertConnectedSubrameCountIsConsistent(Node*);
+unsigned assertConnectedSubrameCountIsConsistent(Node&);
 #endif
 
-inline void ChildFrameDisconnector::collectFrameOwners(Node* root)
+inline void ChildFrameDisconnector::collectFrameOwners(Node& root)
 {
-    if (!root->connectedSubframeCount())
+    if (!root.connectedSubframeCount())
         return;
 
-    if (root->isHTMLElement() && root->isFrameOwnerElement())
-        m_frameOwners.append(toHTMLFrameOwnerElement(root));
+    if (root.isHTMLElement() && root.isFrameOwnerElement())
+        m_frameOwners.append(&toHTMLFrameOwnerElement(root));
 
-    for (Node* child = root->firstChild(); child; child = child->nextSibling())
-        collectFrameOwners(child);
+    for (Node* child = root.firstChild(); child; child = child->nextSibling())
+        collectFrameOwners(*child);
 
-    ElementShadow* shadow = root->isElementNode() ? toElement(root)->shadow() : 0;
+    ElementShadow* shadow = root.isElementNode() ? toElement(root).shadow() : 0;
     if (shadow)
-        collectFrameOwners(shadow);
+        collectFrameOwners(*shadow);
 }
 
 inline void ChildFrameDisconnector::disconnectCollectedFrameOwners()
 {
     // Must disable frame loading in the subtree so an unload handler cannot
     // insert more frames and create loaded frames in detached subtrees.
-    SubframeLoadingDisabler disabler(m_root);
+    SubframeLoadingDisabler disabler(&m_root);
 
     for (unsigned i = 0; i < m_frameOwners.size(); ++i) {
         HTMLFrameOwnerElement* owner = m_frameOwners[i].get();
         // Don't need to traverse up the tree for the first owner since no
         // script could have moved it.
-        if (!i || m_root->containsIncludingShadowDOM(owner))
+        if (!i || m_root.containsIncludingShadowDOM(owner))
             owner->disconnectContentFrame();
     }
 }
@@ -329,14 +330,14 @@
     assertConnectedSubrameCountIsConsistent(m_root);
 #endif
 
-    if (!m_root->connectedSubframeCount())
+    if (!m_root.connectedSubframeCount())
         return;
 
     if (policy == RootAndDescendants)
         collectFrameOwners(m_root);
     else {
-        for (Node* child = m_root->firstChild(); child; child = child->nextSibling())
-            collectFrameOwners(child);
+        for (Node* child = m_root.firstChild(); child; child = child->nextSibling())
+            collectFrameOwners(*child);
     }
 
     disconnectCollectedFrameOwners();
diff --git a/Source/core/dom/ContextLifecycleNotifier.cpp b/Source/core/dom/ContextLifecycleNotifier.cpp
index bf319bd..7b96fbe 100644
--- a/Source/core/dom/ContextLifecycleNotifier.cpp
+++ b/Source/core/dom/ContextLifecycleNotifier.cpp
@@ -34,7 +34,7 @@
 namespace WebCore {
 
 ContextLifecycleNotifier::ContextLifecycleNotifier(ExecutionContext* context)
-    : LifecycleNotifier(context)
+    : LifecycleNotifier<ExecutionContext>(context)
 {
 }
 
@@ -42,23 +42,23 @@
 {
 }
 
-void ContextLifecycleNotifier::addObserver(LifecycleObserver* observer)
+void ContextLifecycleNotifier::addObserver(ContextLifecycleNotifier::Observer* observer)
 {
     LifecycleNotifier::addObserver(observer);
 
     RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
-    if (observer->observerType() == LifecycleObserver::ActiveDOMObjectType) {
+    if (observer->observerType() == Observer::ActiveDOMObjectType) {
         RELEASE_ASSERT(m_iterating != IteratingOverActiveDOMObjects);
         m_activeDOMObjects.add(static_cast<ActiveDOMObject*>(observer));
     }
 }
 
-void ContextLifecycleNotifier::removeObserver(LifecycleObserver* observer)
+void ContextLifecycleNotifier::removeObserver(ContextLifecycleNotifier::Observer* observer)
 {
     LifecycleNotifier::removeObserver(observer);
 
     RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
-    if (observer->observerType() == LifecycleObserver::ActiveDOMObjectType) {
+    if (observer->observerType() == Observer::ActiveDOMObjectType) {
         RELEASE_ASSERT(m_iterating != IteratingOverActiveDOMObjects);
         m_activeDOMObjects.remove(static_cast<ActiveDOMObject*>(observer));
     }
diff --git a/Source/core/dom/ContextLifecycleNotifier.h b/Source/core/dom/ContextLifecycleNotifier.h
index 342b57f..93d8540 100644
--- a/Source/core/dom/ContextLifecycleNotifier.h
+++ b/Source/core/dom/ContextLifecycleNotifier.h
@@ -28,7 +28,7 @@
 #define ContextLifecycleNotifier_h
 
 #include "core/dom/ActiveDOMObject.h"
-#include "core/platform/LifecycleNotifier.h"
+#include "platform/LifecycleNotifier.h"
 #include "wtf/HashSet.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -38,7 +38,7 @@
 class ContextLifecycleObserver;
 class ExecutionContext;
 
-class ContextLifecycleNotifier : public LifecycleNotifier {
+class ContextLifecycleNotifier : public LifecycleNotifier<ExecutionContext> {
 public:
     static PassOwnPtr<ContextLifecycleNotifier> create(ExecutionContext*);
 
@@ -48,8 +48,8 @@
 
     const ActiveDOMObjectSet& activeDOMObjects() const { return m_activeDOMObjects; }
 
-    virtual void addObserver(LifecycleObserver*) OVERRIDE;
-    virtual void removeObserver(LifecycleObserver*) OVERRIDE;
+    virtual void addObserver(Observer*) OVERRIDE;
+    virtual void removeObserver(Observer*) OVERRIDE;
 
     void notifyResumingActiveDOMObjects();
     void notifySuspendingActiveDOMObjects();
diff --git a/Source/core/dom/ContextLifecycleObserver.cpp b/Source/core/dom/ContextLifecycleObserver.cpp
index f10c7ca..b534648 100644
--- a/Source/core/dom/ContextLifecycleObserver.cpp
+++ b/Source/core/dom/ContextLifecycleObserver.cpp
@@ -31,8 +31,18 @@
 
 namespace WebCore {
 
+template<> void observerContext(ExecutionContext* context, LifecycleObserver<ExecutionContext>* observer)
+{
+    context->wasObservedBy(observer);
+}
+
+template<> void unobserverContext(ExecutionContext* context, LifecycleObserver<ExecutionContext>* observer)
+{
+    context->wasUnobservedBy(observer);
+}
+
 ContextLifecycleObserver::ContextLifecycleObserver(ExecutionContext* executionContext, Type type)
-    : LifecycleObserver(executionContext, type)
+    : LifecycleObserver<ExecutionContext>(executionContext, type)
 {
 }
 
@@ -40,9 +50,4 @@
 {
 }
 
-ExecutionContext* ContextLifecycleObserver::executionContext() const
-{
-    return static_cast<ExecutionContext*>(m_lifecycleContext);
-}
-
 } // namespace WebCore
diff --git a/Source/core/dom/ContextLifecycleObserver.h b/Source/core/dom/ContextLifecycleObserver.h
index 932b021..adde88c 100644
--- a/Source/core/dom/ContextLifecycleObserver.h
+++ b/Source/core/dom/ContextLifecycleObserver.h
@@ -27,17 +27,19 @@
 #ifndef ContextLifecycleObserver_h
 #define ContextLifecycleObserver_h
 
-#include "core/platform/LifecycleObserver.h"
+#include "platform/LifecycleContext.h"
 
 namespace WebCore {
 
 class ExecutionContext;
 
-class ContextLifecycleObserver : public LifecycleObserver {
+template<> void observerContext(ExecutionContext*, LifecycleObserver<ExecutionContext>*);
+template<> void unobserverContext(ExecutionContext*, LifecycleObserver<ExecutionContext>*);
+
+class ContextLifecycleObserver : public LifecycleObserver<ExecutionContext> {
 public:
     explicit ContextLifecycleObserver(ExecutionContext*, Type = GenericType);
-    ExecutionContext* executionContext() const;
-
+    ExecutionContext* executionContext() const { return lifecycleContext(); }
 protected:
     virtual ~ContextLifecycleObserver();
 };
diff --git a/Source/core/dom/DOMException.cpp b/Source/core/dom/DOMException.cpp
index 348a94e..ebb5b20 100644
--- a/Source/core/dom/DOMException.cpp
+++ b/Source/core/dom/DOMException.cpp
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-static struct CoreException {
+static const struct CoreException {
     const char* const name;
     const char* const message;
     const int code;
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index b4690e4..756cbb1 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -321,43 +321,48 @@
 
 PassRefPtr<Document> DOMImplementation::createDocument(const String& type, Frame* frame, const KURL& url, bool inViewSourceMode)
 {
+    return createDocument(type, DocumentInit(url, frame), inViewSourceMode);
+}
+
+PassRefPtr<Document> DOMImplementation::createDocument(const String& type, const DocumentInit& init, bool inViewSourceMode)
+{
     if (inViewSourceMode)
-        return HTMLViewSourceDocument::create(DocumentInit(url, frame), type);
+        return HTMLViewSourceDocument::create(init, type);
 
     // Plugins cannot take HTML and XHTML from us, and we don't even need to initialize the plugin database for those.
     if (type == "text/html")
-        return HTMLDocument::create(DocumentInit(url, frame));
+        return HTMLDocument::create(init);
     if (type == "application/xhtml+xml")
-        return Document::createXHTML(DocumentInit(url, frame));
+        return Document::createXHTML(init);
 
     PluginData* pluginData = 0;
-    if (frame && frame->page() && frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
-        pluginData = frame->page()->pluginData();
+    if (init.frame() && init.frame()->page() && init.frame()->loader().allowPlugins(NotAboutToInstantiatePlugin))
+        pluginData = init.frame()->page()->pluginData();
 
     // PDF is one image type for which a plugin can override built-in support.
     // We do not want QuickTime to take over all image types, obviously.
     if ((type == "application/pdf" || type == "text/pdf") && pluginData && pluginData->supportsMimeType(type))
-        return PluginDocument::create(DocumentInit(url, frame));
+        return PluginDocument::create(init);
     if (Image::supportsType(type))
-        return ImageDocument::create(DocumentInit(url, frame));
+        return ImageDocument::create(init);
 
     // Check to see if the type can be played by our MediaPlayer, if so create a MediaDocument
     if (HTMLMediaElement::supportsType(ContentType(type)))
-        return MediaDocument::create(DocumentInit(url, frame));
+        return MediaDocument::create(init);
 
     // Everything else except text/plain can be overridden by plugins. In particular, Adobe SVG Viewer should be used for SVG, if installed.
     // Disallowing plug-ins to use text/plain prevents plug-ins from hijacking a fundamental type that the browser is expected to handle,
     // and also serves as an optimization to prevent loading the plug-in database in the common case.
     if (type != "text/plain" && pluginData && pluginData->supportsMimeType(type))
-        return PluginDocument::create(DocumentInit(url, frame));
+        return PluginDocument::create(init);
     if (isTextMIMEType(type))
-        return TextDocument::create(DocumentInit(url, frame));
+        return TextDocument::create(init);
     if (type == "image/svg+xml")
-        return SVGDocument::create(DocumentInit(url, frame));
+        return SVGDocument::create(init);
     if (isXMLMIMEType(type))
-        return Document::create(DocumentInit(url, frame));
+        return Document::create(init);
 
-    return HTMLDocument::create(DocumentInit(url, frame));
+    return HTMLDocument::create(init);
 }
 
 }
diff --git a/Source/core/dom/DOMImplementation.h b/Source/core/dom/DOMImplementation.h
index 153f4c4..5fb1f51 100644
--- a/Source/core/dom/DOMImplementation.h
+++ b/Source/core/dom/DOMImplementation.h
@@ -32,6 +32,7 @@
 
 class CSSStyleSheet;
 class Document;
+class DocumentInit;
 class DocumentType;
 class ExceptionState;
 class Frame;
@@ -62,6 +63,7 @@
 
     // 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 bool isXMLMIMEType(const String& MIMEType);
     static bool isTextMIMEType(const String& MIMEType);
diff --git a/Source/core/dom/DOMURL.h b/Source/core/dom/DOMURL.h
index f197a11..1736990 100644
--- a/Source/core/dom/DOMURL.h
+++ b/Source/core/dom/DOMURL.h
@@ -42,7 +42,7 @@
 class ExecutionContext;
 class URLRegistrable;
 
-class DOMURL : public ScriptWrappable, public DOMURLUtils, public RefCounted<DOMURL> {
+class DOMURL FINAL : public ScriptWrappable, public DOMURLUtils, public RefCounted<DOMURL> {
 
 public:
     static PassRefPtr<DOMURL> create(const String& url, ExceptionState& es)
diff --git a/Source/core/dom/DOMURLUtils.h b/Source/core/dom/DOMURLUtils.h
index b7b128e..1987ecd 100644
--- a/Source/core/dom/DOMURLUtils.h
+++ b/Source/core/dom/DOMURLUtils.h
@@ -39,6 +39,7 @@
 public:
     virtual void setURL(const KURL&) = 0;
     virtual void setInput(const String&) = 0;
+    virtual ~DOMURLUtils() { };
 
     static void setHref(DOMURLUtils*, const String&);
 
diff --git a/Source/core/dom/DOMURLUtilsReadOnly.h b/Source/core/dom/DOMURLUtilsReadOnly.h
index 74f1d1c..9ddfd40 100644
--- a/Source/core/dom/DOMURLUtilsReadOnly.h
+++ b/Source/core/dom/DOMURLUtilsReadOnly.h
@@ -37,6 +37,7 @@
 public:
     virtual KURL url() const = 0;
     virtual String input() const = 0;
+    virtual ~DOMURLUtilsReadOnly() { };
 
     static String href(DOMURLUtilsReadOnly*);
 
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index 38504b3..2f97a3f 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -44,11 +44,11 @@
 #include "core/accessibility/AXObjectCache.h"
 #include "core/animation/AnimationClock.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"
-#include "core/css/FontFaceSet.h"
 #include "core/css/MediaQueryMatcher.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleSheetContents.h"
@@ -100,13 +100,11 @@
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
 #include "core/events/BeforeUnloadEvent.h"
-#include "core/events/DocumentEventQueue.h"
 #include "core/events/Event.h"
 #include "core/events/EventFactory.h"
 #include "core/events/EventListener.h"
 #include "core/events/HashChangeEvent.h"
 #include "core/events/PageTransitionEvent.h"
-#include "core/events/PopStateEvent.h"
 #include "core/events/ScopedEventQueue.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/fetch/ResourceFetcher.h"
@@ -167,7 +165,6 @@
 #include "core/rendering/TextAutosizer.h"
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGStyleElement.h"
-#include "core/workers/SharedWorkerRepository.h"
 #include "core/xml/XSLTProcessor.h"
 #include "core/xml/parser/XMLDocumentParser.h"
 #include "platform/DateComponents.h"
@@ -197,8 +194,6 @@
 
 using namespace HTMLNames;
 
-static const double cDefaultIncrementalRenderingSuppressionTimeoutInSeconds = 5;
-
 static const unsigned cMaxWriteRecursionDepth = 21;
 
 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
@@ -292,40 +287,37 @@
     return url.isEmpty() || url.isBlankURL();
 }
 
-static Widget* widgetForElement(Element* focusedElement)
+static Widget* widgetForElement(const Element& focusedElement)
 {
-    if (!focusedElement)
-        return 0;
-    RenderObject* renderer = focusedElement->renderer();
+    RenderObject* renderer = focusedElement.renderer();
     if (!renderer || !renderer->isWidget())
         return 0;
     return toRenderWidget(renderer)->widget();
 }
 
-static bool acceptsEditingFocus(Element* element)
+static bool acceptsEditingFocus(const Element& element)
 {
-    ASSERT(element);
-    ASSERT(element->rendererIsEditable());
+    ASSERT(element.rendererIsEditable());
 
-    return element->document().frame() && element->rootEditableElement();
+    return element.document().frame() && element.rootEditableElement();
 }
 
-static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
+static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame* targetFrame)
 {
     // targetFrame can be 0 when we're trying to navigate a top-level frame
     // that has a 0 opener.
     if (!targetFrame)
         return false;
 
-    const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
-    for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
+    const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
+    for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
         Document* ancestorDocument = ancestorFrame->document();
         // FIXME: Should be an ASSERT? Frames should alway have documents.
         if (!ancestorDocument)
             return true;
 
         const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
-        if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
+        if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
             return true;
 
         // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
@@ -338,12 +330,12 @@
     return false;
 }
 
-static void printNavigationErrorMessage(Frame* frame, const KURL& activeURL, const char* reason)
+static void printNavigationErrorMessage(const Frame& frame, const KURL& activeURL, const char* reason)
 {
-    String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
+    String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
 
     // FIXME: should we print to the console of the document performing the navigation instead?
-    frame->domWindow()->printErrorMessage(message);
+    frame.domWindow()->printErrorMessage(message);
 }
 
 uint64_t Document::s_globalTreeVersion = 0;
@@ -385,13 +377,13 @@
     , m_styleResolverAccessCount(0)
     , m_lastStyleResolverAccessCount(0)
     , m_didCalculateStyleResolver(false)
+    , m_hasNodesWithPlaceholderStyle(false)
+    , m_needsNotifyRemoveAllPendingStylesheet(false)
     , m_ignorePendingStylesheets(false)
     , m_evaluateMediaQueriesOnStyleRecalc(false)
-    , m_needsNotifyRemoveAllPendingStylesheet(false)
-    , m_hasNodesWithPlaceholderStyle(false)
     , m_pendingSheetLayout(NoLayoutWithPendingSheets)
     , m_frame(initializer.frame())
-    , m_domWindow(0)
+    , m_domWindow(m_frame ? m_frame->domWindow() : 0)
     , m_import(initializer.import())
     , m_activeParserCount(0)
     , m_contextFeatures(ContextFeatures::defaultSwitch())
@@ -437,7 +429,6 @@
     , m_isMobileDocument(false)
     , m_mayDisplaySeamlesslyWithParent(false)
     , m_renderView(0)
-    , m_eventQueue(DocumentEventQueue::create(this))
     , m_weakFactory(this)
     , m_contextDocument(initializer.contextDocument())
     , m_idAttributeName(idAttr)
@@ -447,13 +438,12 @@
     , m_referrerPolicy(ReferrerPolicyDefault)
     , m_directionSetOnDocumentElement(false)
     , m_writingModeSetOnDocumentElement(false)
-    , m_didAllowNavigationViaBeforeUnloadConfirmationPanel(false)
     , m_writeRecursionIsTooDeep(false)
     , m_writeRecursionDepth(0)
     , m_lastHandledUserGestureTimestamp(0)
+    , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
     , m_textAutosizer(TextAutosizer::create(this))
     , m_registrationContext(initializer.registrationContext(this))
-    , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
     , m_scheduledTasksAreSuspended(false)
     , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
 #ifndef NDEBUG
@@ -461,8 +451,8 @@
 #endif
     , m_animationClock(AnimationClock::create())
     , m_timeline(DocumentTimeline::create(this))
+    , m_transitionTimeline(TransitionTimeline::create(this))
     , m_templateDocumentHost(0)
-    , m_fonts(0)
     , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
 {
     setClient(this);
@@ -471,7 +461,7 @@
     if (m_frame) {
         provideContextFeaturesToDocumentFrom(this, m_frame->page());
 
-        m_fetcher = m_frame->loader()->activeDocumentLoader()->fetcher();
+        m_fetcher = m_frame->loader().activeDocumentLoader()->fetcher();
     }
 
     if (!m_fetcher)
@@ -620,21 +610,21 @@
         accessSVGExtensions()->pauseAnimations();
 
     m_lifecyle.advanceTo(DocumentLifecycle::Disposed);
-    lifecycleNotifier()->notifyDocumentWasDisposed();
+    lifecycleNotifier().notifyDocumentWasDisposed();
 }
 
-SelectorQueryCache* Document::selectorQueryCache()
+SelectorQueryCache& Document::selectorQueryCache()
 {
     if (!m_selectorQueryCache)
         m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
-    return m_selectorQueryCache.get();
+    return *m_selectorQueryCache;
 }
 
-MediaQueryMatcher* Document::mediaQueryMatcher()
+MediaQueryMatcher& Document::mediaQueryMatcher()
 {
     if (!m_mediaQueryMatcher)
         m_mediaQueryMatcher = MediaQueryMatcher::create(this);
-    return m_mediaQueryMatcher.get();
+    return *m_mediaQueryMatcher;
 }
 
 void Document::setCompatibilityMode(CompatibilityMode mode)
@@ -643,7 +633,7 @@
         return;
     bool wasInQuirksMode = inQuirksMode();
     m_compatibilityMode = mode;
-    selectorQueryCache()->invalidate();
+    selectorQueryCache().invalidate();
     if (inQuirksMode() != wasInQuirksMode) {
         // All user stylesheets have to reparse using the different mode.
         m_styleEngine->clearPageUserSheet();
@@ -662,7 +652,7 @@
     ASSERT(!m_docType || !docType);
     m_docType = docType;
     if (m_docType) {
-        this->adoptIfNeeded(m_docType.get());
+        this->adoptIfNeeded(*m_docType);
         if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
             m_isMobileDocument = true;
     }
@@ -952,7 +942,7 @@
 
         if (source->isFrameOwnerElement()) {
             HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
-            if (frame() && frame()->tree()->isDescendantOf(frameOwnerElement->contentFrame())) {
+            if (frame() && frame()->tree().isDescendantOf(frameOwnerElement->contentFrame())) {
                 es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
                 return 0;
             }
@@ -964,7 +954,7 @@
         }
     }
 
-    this->adoptIfNeeded(source.get());
+    this->adoptIfNeeded(*source);
 
     return source;
 }
@@ -1092,7 +1082,7 @@
         if (!m_documentTiming.domLoading) {
             m_documentTiming.domLoading = monotonicallyIncreasingTime();
             if (RuntimeEnabledFeatures::webAnimationsEnabled())
-                m_timeline->setZeroTimeAsPerfTime(m_documentTiming.domLoading);
+                m_timeline->setZeroTime(m_documentTiming.domLoading);
         }
         break;
     case Interactive:
@@ -1109,6 +1099,11 @@
     dispatchEvent(Event::create(EventTypeNames::readystatechange));
 }
 
+bool Document::isLoadCompleted()
+{
+    return m_readyState == Complete;
+}
+
 String Document::encodingName() const
 {
     // TextEncoding::name() returns a char*, no need to allocate a new
@@ -1306,7 +1301,7 @@
 
     if (!m_frame || oldTitle == m_title)
         return;
-    m_frame->loader()->client()->dispatchDidReceiveTitle(m_title);
+    m_frame->loader().client()->dispatchDidReceiveTitle(m_title);
 }
 
 void Document::setTitle(const String& title)
@@ -1325,7 +1320,7 @@
     updateTitle(title);
 
     if (m_titleElement && isHTMLTitleElement(m_titleElement.get()))
-        toHTMLTitleElement(m_titleElement.get())->setText(title);
+        toHTMLTitleElement(m_titleElement)->setText(title);
 }
 
 void Document::setTitleElement(const String& title, Element* titleElement)
@@ -1629,12 +1624,10 @@
     }
 
     WritingMode rootWritingMode = documentElementStyle->writingMode();
-    bool isHorizontalWritingMode = documentElementStyle->isHorizontalWritingMode();
     TextDirection rootDirection = documentElementStyle->direction();
 
     if (!writingModeSetOnDocumentElement() && body()) {
         rootWritingMode = bodyStyle->writingMode();
-        isHorizontalWritingMode = bodyStyle->isHorizontalWritingMode();
     }
 
     if (!directionSetOnDocumentElement() && body())
@@ -1667,8 +1660,8 @@
     // we should not enter style recalc while painting
     RELEASE_ASSERT(!view() || !view()->isPainting());
 
-    // FIXME: We should never enter here without a FrameView or a RenderView.
-    if (!renderer() || !view())
+    // FIXME: We should never enter here without a FrameView or with an inactive document.
+    if (!isActive() || !view())
         return;
 
     if (m_inStyleRecalc)
@@ -1734,8 +1727,8 @@
         if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
             setNeedsStyleRecalc();
 
-        // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
         if (m_styleResolver) {
+            // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
             m_styleEngine->resetCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
             m_styleResolver->clearStyleSharingList();
         }
@@ -1750,7 +1743,7 @@
     // 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();
+        frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
 }
 
 void Document::updateStyleIfNeeded()
@@ -1994,7 +1987,6 @@
         clearAXObjectCache();
 
     stopActiveDOMObjects();
-    m_eventQueue->close();
 
     // FIXME: consider using ActiveDOMObject.
     if (m_scriptedAnimationController)
@@ -2008,8 +2000,6 @@
 
     documentWillBecomeInactive();
 
-    SharedWorkerRepository::documentDetached(this);
-
     if (m_frame) {
         FrameView* view = m_frame->view();
         if (view)
@@ -2048,7 +2038,7 @@
     if (m_mediaQueryMatcher)
         m_mediaQueryMatcher->documentDestroyed();
 
-    lifecycleNotifier()->notifyDocumentWasDetached();
+    lifecycleNotifier().notifyDocumentWasDetached();
     m_lifecyle.advanceTo(DocumentLifecycle::Stopped);
 }
 
@@ -2171,8 +2161,8 @@
             }
         }
 
-        if (m_frame->loader()->state() == FrameStateProvisional)
-            m_frame->loader()->stopAllLoaders();
+        if (m_frame->loader().state() == FrameStateProvisional)
+            m_frame->loader().stopAllLoaders();
     }
 
     removeAllEventListeners();
@@ -2181,7 +2171,7 @@
         parser->setWasCreatedByScript(true);
 
     if (m_frame)
-        m_frame->loader()->didExplicitOpen();
+        m_frame->loader().didExplicitOpen();
     if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
         m_loadEventProgress = LoadEventNotRun;
 }
@@ -2303,14 +2293,14 @@
         return;
     }
 
-    m_frame->loader()->checkCompleted();
+    m_frame->loader().checkCompleted();
 }
 
 void Document::implicitClose()
 {
     ASSERT(!inStyleRecalc());
 
-    bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
+    bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
     bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
 
     // If the load was blocked because of a pending location change and the location change triggers a same document
@@ -2322,7 +2312,7 @@
 
     // The call to dispatchWindowLoadEvent can detach the DOMWindow and cause it (and its
     // attached Document) to be destroyed.
-    RefPtr<DOMWindow> protect(this->domWindow());
+    RefPtr<DOMWindow> protectedWindow(this->domWindow());
 
     m_loadEventProgress = LoadEventInProgress;
 
@@ -2334,7 +2324,7 @@
     detachParser();
 
     Frame* f = frame();
-    if (f && f->script()->canExecuteScripts(NotAboutToExecuteScript)) {
+    if (f && f->script().canExecuteScripts(NotAboutToExecuteScript)) {
         ImageLoader::dispatchPendingBeforeLoadEvents();
         ImageLoader::dispatchPendingLoadEvents();
         ImageLoader::dispatchPendingErrorEvents();
@@ -2349,12 +2339,11 @@
     if (svgExtensions())
         accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
 
-    dispatchWindowLoadEvent();
-    enqueuePageshowEvent(PageshowEventNotPersisted);
-    enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
+    if (protectedWindow)
+        protectedWindow->documentWasClosed();
 
     if (frame()) {
-        frame()->loader()->client()->dispatchDidHandleOnloadEvents();
+        frame()->loader().client()->dispatchDidHandleOnloadEvents();
         loader()->applicationCacheHost()->stopDeferringEvents();
     }
 
@@ -2368,7 +2357,7 @@
     // fires. This will improve onload scores, and other browsers do it.
     // If they wanna cheat, we can too. -dwh
 
-    if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
+    if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
         // 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;
@@ -2413,7 +2402,7 @@
         accessSVGExtensions()->startAnimations();
 }
 
-bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, Document* navigatingDocument)
+bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigation)
 {
     if (!m_domWindow)
         return true;
@@ -2425,21 +2414,21 @@
 
     RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
     m_loadEventProgress = BeforeUnloadEventInProgress;
-    dispatchWindowEvent(beforeUnloadEvent.get(), this);
+    m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
     m_loadEventProgress = BeforeUnloadEventCompleted;
     if (!beforeUnloadEvent->defaultPrevented())
         defaultEventHandler(beforeUnloadEvent.get());
     if (beforeUnloadEvent->returnValue().isNull())
         return true;
 
-    if (navigatingDocument->m_didAllowNavigationViaBeforeUnloadConfirmationPanel) {
+    if (didAllowNavigation) {
         addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
         return true;
     }
 
     String text = beforeUnloadEvent->returnValue();
     if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
-        navigatingDocument->m_didAllowNavigationViaBeforeUnloadConfirmationPanel = true;
+        didAllowNavigation = true;
         return true;
     }
     return false;
@@ -2457,21 +2446,22 @@
             toHTMLInputElement(currentFocusedElement)->endEditing();
         if (m_loadEventProgress < PageHideInProgress) {
             m_loadEventProgress = PageHideInProgress;
-            dispatchWindowEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
+            if (DOMWindow* window = domWindow())
+                window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
             if (!m_frame)
                 return;
 
             // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
             // while dispatching the event, so protect it to prevent writing the end
             // time into freed memory.
-            RefPtr<DocumentLoader> documentLoader =  m_frame->loader()->provisionalDocumentLoader();
+            RefPtr<DocumentLoader> documentLoader =  m_frame->loader().provisionalDocumentLoader();
             m_loadEventProgress = UnloadEventInProgress;
             RefPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
             if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
                 DocumentLoadTiming* timing = documentLoader->timing();
                 ASSERT(timing->navigationStart());
                 timing->markUnloadEventStart();
-                dispatchWindowEvent(unloadEvent, this);
+                m_frame->domWindow()->dispatchEvent(unloadEvent, this);
                 timing->markUnloadEventEnd();
             } else {
                 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
@@ -2485,8 +2475,8 @@
         return;
 
     // Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
-    bool keepEventListeners = m_frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader()->provisionalDocumentLoader()
-        && isSecureTransitionTo(m_frame->loader()->provisionalDocumentLoader()->url());
+    bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
+        && isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
     if (!keepEventListeners)
         removeAllEventListeners();
 }
@@ -2593,7 +2583,7 @@
 {
     Page* p = page();
     if (!p)
-        return ExecutionContext::timerAlignmentInterval();
+        return DOMTimer::visiblePageAlignmentInterval();
     return p->timerAlignmentInterval();
 }
 
@@ -2636,7 +2626,7 @@
         // FIXME: Now that we don't support Objective-C this can probably be removed.
         m_baseURL = KURL(ParsedURLString, documentURI());
     }
-    selectorQueryCache()->invalidate();
+    selectorQueryCache().invalidate();
 
     if (!m_baseURL.isValid())
         m_baseURL = KURL();
@@ -2705,7 +2695,7 @@
 
 String Document::userAgent(const KURL& url) const
 {
-    return frame() ? frame()->loader()->userAgent(url) : String();
+    return frame() ? frame()->loader().userAgent(url) : String();
 }
 
 void Document::disableEval(const String& errorMessage)
@@ -2713,7 +2703,7 @@
     if (!frame())
         return;
 
-    frame()->script()->disableEval(errorMessage);
+    frame()->script().disableEval(errorMessage);
 }
 
 bool Document::canNavigate(Frame* targetFrame)
@@ -2728,21 +2718,24 @@
         return true;
 
     // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
-    if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
+    if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
         return true;
 
     if (isSandboxed(SandboxNavigation)) {
-        if (targetFrame->tree()->isDescendantOf(m_frame))
+        if (targetFrame->tree().isDescendantOf(m_frame))
             return true;
 
         const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
-        if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
+        if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
             reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
 
-        printNavigationErrorMessage(targetFrame, url(), reason);
+        printNavigationErrorMessage(*targetFrame, url(), reason);
         return false;
     }
 
+    ASSERT(securityOrigin());
+    SecurityOrigin& origin = *securityOrigin();
+
     // This is the normal case. A document can navigate its decendant frames,
     // or, more generally, a document can navigate a frame if the document is
     // in the same origin as any of that frame's ancestors (in the frame
@@ -2750,7 +2743,7 @@
     //
     // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
     // historical information about this security check.
-    if (canAccessAncestor(securityOrigin(), targetFrame))
+    if (canAccessAncestor(origin, targetFrame))
         return true;
 
     // Top-level frames are easier to navigate than other frames because they
@@ -2764,28 +2757,28 @@
     // some way related to the frame being navigate (e.g., by the "opener"
     // and/or "parent" relation). Requiring some sort of relation prevents a
     // document from navigating arbitrary, unrelated top-level frames.
-    if (!targetFrame->tree()->parent()) {
-        if (targetFrame == m_frame->loader()->opener())
+    if (!targetFrame->tree().parent()) {
+        if (targetFrame == m_frame->loader().opener())
             return true;
 
-        if (canAccessAncestor(securityOrigin(), targetFrame->loader()->opener()))
+        if (canAccessAncestor(origin, targetFrame->loader().opener()))
             return true;
     }
 
-    printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
+    printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
     return false;
 }
 
 Frame* Document::findUnsafeParentScrollPropagationBoundary()
 {
     Frame* currentFrame = m_frame;
-    Frame* ancestorFrame = currentFrame->tree()->parent();
+    Frame* ancestorFrame = currentFrame->tree().parent();
 
     while (ancestorFrame) {
         if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
             return currentFrame;
         currentFrame = ancestorFrame;
-        ancestorFrame = ancestorFrame->tree()->parent();
+        ancestorFrame = ancestorFrame->tree().parent();
     }
     return 0;
 }
@@ -2905,7 +2898,7 @@
         addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
         return;
     }
-    m_frame->navigationScheduler()->scheduleRedirect(delay, refreshURL);
+    m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
 }
 
 void Document::processHttpEquivSetCookie(const String& content)
@@ -2924,15 +2917,15 @@
     if (!frame)
         return;
 
-    FrameLoader* frameLoader = frame->loader();
+    FrameLoader& frameLoader = frame->loader();
     unsigned long requestIdentifier = loader()->mainResourceIdentifier();
-    if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
+    if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
         String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
-        frameLoader->stopAllLoaders();
+        frameLoader.stopAllLoaders();
         // 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(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
         addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
     }
 }
@@ -3211,7 +3204,7 @@
         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()) {
+    for (Frame* child = frame()->tree().firstChild(); child; child = child->tree().nextSibling()) {
         Document* childDocument = child->document();
         if (childDocument->shouldDisplaySeamlesslyWithParent()) {
             ASSERT(childDocument->seamlessParentIFrame()->document() == this);
@@ -3273,7 +3266,7 @@
         return;
 
     if (frame())
-        frame()->eventHandler()->scheduleHoverStateUpdate();
+        frame()->eventHandler().scheduleHoverStateUpdate();
 }
 
 void Document::activeChainNodeDetached(Node* node)
@@ -3354,7 +3347,7 @@
         }
 
         if (view()) {
-            Widget* oldWidget = widgetForElement(oldFocusedElement.get());
+            Widget* oldWidget = widgetForElement(*oldFocusedElement);
             if (oldWidget)
                 oldWidget->setFocus(false);
             else
@@ -3368,7 +3361,7 @@
     }
 
     if (newFocusedElement && newFocusedElement->isFocusable()) {
-        if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
+        if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
             // delegate blocks focus change
             focusChangeBlocked = true;
             goto SetFocusedElementDone;
@@ -3410,14 +3403,14 @@
         // eww, I suck. set the qt focus correctly
         // ### find a better place in the code for this
         if (view()) {
-            Widget* focusWidget = widgetForElement(m_focusedElement.get());
+            Widget* focusWidget = widgetForElement(*m_focusedElement);
             if (focusWidget) {
                 // Make sure a widget has the right size before giving it focus.
                 // Otherwise, we are testing edge cases of the Widget code.
                 // Specifically, in WebCore this does not work well for text fields.
                 updateLayout();
                 // Re-get the widget in case updating the layout changed things.
-                focusWidget = widgetForElement(m_focusedElement.get());
+                focusWidget = widgetForElement(*m_focusedElement);
             }
             if (focusWidget)
                 focusWidget->setFocus(true);
@@ -3506,6 +3499,7 @@
 
 void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
 {
+    NoEventDispatchAssertion assertNoEventDispatch;
     if (!m_ranges.isEmpty()) {
         HashSet<Range*>::const_iterator end = m_ranges.end();
         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
@@ -3520,7 +3514,7 @@
 
     if (Frame* frame = this->frame()) {
         for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
-            frame->eventHandler()->nodeWillBeRemoved(n);
+            frame->eventHandler().nodeWillBeRemoved(n);
             frame->selection().nodeWillBeRemoved(n);
             frame->page()->dragCaretController().nodeWillBeRemoved(n);
         }
@@ -3540,7 +3534,7 @@
     }
 
     if (Frame* frame = this->frame()) {
-        frame->eventHandler()->nodeWillBeRemoved(n);
+        frame->eventHandler().nodeWillBeRemoved(n);
         frame->selection().nodeWillBeRemoved(n);
         frame->page()->dragCaretController().nodeWillBeRemoved(n);
     }
@@ -3616,30 +3610,11 @@
     return domWindow->getAttributeEventListener(eventType, isolatedWorld);
 }
 
-void Document::dispatchWindowEvent(PassRefPtr<Event> event,  PassRefPtr<EventTarget> target)
-{
-    ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
-    DOMWindow* domWindow = this->domWindow();
-    if (!domWindow)
-        return;
-    domWindow->dispatchEvent(event, target);
-}
-
 EventQueue* Document::eventQueue() const
 {
-    return m_eventQueue.get();
-}
-
-void Document::enqueueWindowEvent(PassRefPtr<Event> event)
-{
-    event->setTarget(domWindow());
-    m_eventQueue->enqueueEvent(event);
-}
-
-void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
-{
-    event->setTarget(this);
-    m_eventQueue->enqueueEvent(event);
+    if (!m_domWindow)
+        return 0;
+    return m_domWindow->eventQueue();
 }
 
 void Document::scheduleAnimationFrameEvent(PassRefPtr<Event> event)
@@ -3665,15 +3640,6 @@
     return 0;
 }
 
-void Document::dispatchWindowLoadEvent()
-{
-    ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
-    DOMWindow* domWindow = this->domWindow();
-    if (!domWindow)
-        return;
-    domWindow->dispatchLoadEvent();
-}
-
 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
 {
     if (ContextFeatures::mutationEventsEnabled(this))
@@ -3711,7 +3677,7 @@
     } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
         addListenerType(TRANSITIONEND_LISTENER);
     } else if (eventType == EventTypeNames::beforeload) {
-        if (m_frame && m_frame->script()->shouldBypassMainWorldContentSecurityPolicy()) {
+        if (m_frame && m_frame->script().shouldBypassMainWorldContentSecurityPolicy()) {
             UseCounter::count(*this, UseCounter::BeforeLoadEventInIsolatedWorld);
         } else {
             UseCounter::count(*this, UseCounter::BeforeLoadEvent);
@@ -3819,7 +3785,7 @@
     if (equalIgnoringCase(domain(), newDomain)) {
         securityOrigin()->setDomainFromDOM(newDomain);
         if (m_frame)
-            m_frame->script()->updateSecurityOrigin();
+            m_frame->script().updateSecurityOrigin();
         return;
     }
 
@@ -3849,7 +3815,7 @@
 
     securityOrigin()->setDomainFromDOM(newDomain);
     if (m_frame)
-        m_frame->script()->updateSecurityOrigin();
+        m_frame->script().updateSecurityOrigin();
 }
 
 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
@@ -4114,15 +4080,15 @@
 
 KURL Document::openSearchDescriptionURL()
 {
-    static const char* const openSearchMIMEType = "application/opensearchdescription+xml";
-    static const char* const openSearchRelation = "search";
+    static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
+    static const char openSearchRelation[] = "search";
 
     // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
-    if (!frame() || frame()->tree()->parent())
+    if (!frame() || frame()->tree().parent())
         return KURL();
 
     // FIXME: Why do we need to wait for FrameStateComplete?
-    if (frame()->loader()->state() != FrameStateComplete)
+    if (frame()->loader().state() != FrameStateComplete)
         return KURL();
 
     if (!head())
@@ -4180,7 +4146,7 @@
 void Document::setDesignMode(InheritedBool value)
 {
     m_designMode = value;
-    for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree()->traverseNext(m_frame))
+    for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
         frame->document()->setNeedsStyleRecalc();
 }
 
@@ -4202,7 +4168,7 @@
 {
     if (!m_frame)
         return 0;
-    Frame* parent = m_frame->tree()->parent();
+    Frame* parent = m_frame->tree().parent();
     if (!parent)
         return 0;
     return parent->document();
@@ -4267,7 +4233,7 @@
 
 PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
 {
-    return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, type);
 }
 
 PassRefPtr<HTMLCollection> Document::images()
@@ -4319,17 +4285,17 @@
 
 PassRefPtr<HTMLCollection> Document::all()
 {
-    return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLAllCollection>(this, DocAll);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLAllCollection>(this, DocAll);
 }
 
 PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
 {
-    return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLNameCollection>(this, WindowNamedItems, name);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLNameCollection>(this, WindowNamedItems, name);
 }
 
 PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
 {
-    return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLNameCollection>(this, DocumentNamedItems, name);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLNameCollection>(this, DocumentNamedItems, name);
 }
 
 void Document::finishedParsing()
@@ -4358,7 +4324,7 @@
         // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
         updateStyleIfNeeded();
 
-        f->loader()->finishedParsing();
+        f->loader().finishedParsing();
 
         InspectorInstrumentation::domContentLoadedEventFired(f.get());
     }
@@ -4436,20 +4402,6 @@
     return m_useSecureKeyboardEntryWhenActive;
 }
 
-static bool isEligibleForSeamless(Document* parent, Document* child)
-{
-    // It should not matter what we return for the top-most document.
-    if (!parent)
-        return false;
-    if (parent->isSandboxed(SandboxSeamlessIframes))
-        return false;
-    if (child->isSrcdocDocument())
-        return true;
-    if (parent->securityOrigin()->canAccess(child->securityOrigin()))
-        return true;
-    return parent->securityOrigin()->canRequest(child->url());
-}
-
 void Document::initSecurityContext()
 {
     initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_import));
@@ -4496,15 +4448,14 @@
         }
     }
 
-    Document* parentDocument = ownerElement() ? &ownerElement()->document() : 0;
-    if (parentDocument && initializer.shouldTreatURLAsSrcdocDocument()) {
+    if (initializer.shouldTreatURLAsSrcdocDocument()) {
         m_isSrcdocDocument = true;
-        setBaseURLOverride(parentDocument->baseURL());
+        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 = isEligibleForSeamless(parentDocument, this);
+    m_mayDisplaySeamlesslyWithParent = initializer.isSeamlessAllowedFor(this);
 
     if (!shouldInheritSecurityOriginFromOwner(m_url))
         return;
@@ -4512,8 +4463,7 @@
     // If we do not obtain a meaningful origin from the URL, then we try to
     // find one via the frame hierarchy.
 
-    Frame* ownerFrame = initializer.ownerFrame();
-    if (!ownerFrame) {
+    if (!initializer.owner()) {
         didFailToInitializeSecurityOrigin();
         return;
     }
@@ -4523,21 +4473,21 @@
         // but we're also sandboxed, the only thing we inherit is the ability
         // to load local resources. This lets about:blank iframes in file://
         // URL documents load images and other resources from the file system.
-        if (ownerFrame->document()->securityOrigin()->canLoadLocalResources())
+        if (initializer.owner()->securityOrigin()->canLoadLocalResources())
             securityOrigin()->grantLoadLocalResources();
         return;
     }
 
-    m_cookieURL = ownerFrame->document()->cookieURL();
+    m_cookieURL = initializer.owner()->cookieURL();
     // We alias the SecurityOrigins to match Firefox, see Bug 15313
     // https://bugs.webkit.org/show_bug.cgi?id=15313
-    setSecurityOrigin(ownerFrame->document()->securityOrigin());
+    setSecurityOrigin(initializer.owner()->securityOrigin());
 }
 
 void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
 {
-    if (m_frame && m_frame->tree()->parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
-        contentSecurityPolicy()->copyStateFrom(m_frame->tree()->parent()->document()->contentSecurityPolicy());
+    if (m_frame && m_frame->tree().parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
+        contentSecurityPolicy()->copyStateFrom(m_frame->tree().parent()->document()->contentSecurityPolicy());
     contentSecurityPolicy()->didReceiveHeaders(headers);
 }
 
@@ -4552,7 +4502,7 @@
     // we also need to ask the owner document of the node.
     if (!m_frame)
         return false;
-    if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+    if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript))
         return false;
     if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
         return false;
@@ -4569,16 +4519,22 @@
         return false;
     if (!node->document().frame() && !node->document().import())
         return false;
-    if (!contextDocument().get()->frame()->script()->canExecuteScripts(AboutToExecuteScript))
+    if (!contextDocument().get()->frame()->script().canExecuteScripts(AboutToExecuteScript))
         return false;
     return true;
 }
 
+void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
+{
+    setSecurityOrigin(origin);
+    didUpdateSecurityOrigin();
+}
+
 void Document::didUpdateSecurityOrigin()
 {
     if (!m_frame)
         return;
-    m_frame->script()->updateSecurityOrigin();
+    m_frame->script().updateSecurityOrigin();
 }
 
 bool Document::isContextThread() const
@@ -4586,19 +4542,6 @@
     return isMainThread();
 }
 
-void Document::statePopped(PassRefPtr<SerializedScriptValue> stateObject)
-{
-    if (!frame())
-        return;
-
-    // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
-    // defer firing of popstate until we're in the complete state.
-    if (m_readyState == Complete)
-        enqueuePopstateEvent(stateObject);
-    else
-        m_pendingStateObject = stateObject;
-}
-
 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
 {
     m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
@@ -4678,6 +4621,11 @@
     m_haveExplicitlyDisabledDNSPrefetch = true;
 }
 
+void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
+{
+    InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
+}
+
 void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
 {
     internalAddMessage(source, level, message, sourceURL, lineNumber, 0, state);
@@ -4804,26 +4752,6 @@
         m_scriptedAnimationController->resume();
 }
 
-void Document::enqueuePageshowEvent(PageshowEventPersistence persisted)
-{
-    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
-    dispatchWindowEvent(PageTransitionEvent::create(EventTypeNames::pageshow, persisted), this);
-}
-
-void Document::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
-{
-    enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
-}
-
-void Document::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
-{
-    if (!ContextFeatures::pushStateEnabled(this))
-        return;
-
-    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
-    dispatchWindowEvent(PopStateEvent::create(stateObject, domWindow() ? domWindow()->history() : 0));
-}
-
 void Document::addToTopLayer(Element* element, const Element* before)
 {
     if (element->isInTopLayer())
@@ -4891,7 +4819,7 @@
 void Document::loadEventDelayTimerFired(Timer<Document>*)
 {
     if (frame())
-        frame()->loader()->checkCompleted();
+        frame()->loader().checkCompleted();
 }
 
 ScriptedAnimationController& Document::ensureScriptedAnimationController()
@@ -4974,7 +4902,7 @@
         scrollingCoordinator->touchEventTargetRectsDidChange(this);
     if (m_touchEventTargets->size())
         return;
-    for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
         if (frame->document() && frame->document()->hasTouchEventHandlers())
             return;
     }
@@ -5021,7 +4949,7 @@
     if (!m_frame)
         return 0;
 
-    DocumentLoader* loader = m_frame->loader()->documentLoader();
+    DocumentLoader* loader = m_frame->loader().documentLoader();
     if (!loader)
         return 0;
 
@@ -5090,7 +5018,7 @@
     // http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
     // see http://webkit.org/b/110554 and http://webkit.org/b/110401
     loader()->checkLoadComplete();
-    frame()->loader()->checkLoadComplete();
+    frame()->loader().checkLoadComplete();
 }
 
 void Document::setContextFeatures(PassRefPtr<ContextFeatures> features)
@@ -5292,13 +5220,6 @@
     return *m_templateDocument.get();
 }
 
-FontFaceSet* Document::fonts()
-{
-    if (!m_fonts)
-        m_fonts = FontFaceSet::create(this);
-    return m_fonts.get();
-}
-
 void Document::didAssociateFormControl(Element* element)
 {
     if (!frame() || !frame()->page())
@@ -5326,14 +5247,14 @@
     return m_frame ? m_frame->devicePixelRatio() : 1.0;
 }
 
-PassOwnPtr<LifecycleNotifier> Document::createLifecycleNotifier()
+PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
 {
     return DocumentLifecycleNotifier::create(this);
 }
 
-DocumentLifecycleNotifier* Document::lifecycleNotifier()
+DocumentLifecycleNotifier& Document::lifecycleNotifier()
 {
-    return static_cast<DocumentLifecycleNotifier*>(ExecutionContext::lifecycleNotifier());
+    return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
 }
 
 void Document::removedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index c82c6d8..12e5c3f 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -44,7 +44,6 @@
 #include "core/dom/UserActionElementSet.h"
 #include "core/dom/ViewportDescription.h"
 #include "core/dom/custom/CustomElement.h"
-#include "core/events/DocumentEventQueue.h"
 #include "core/html/CollectionType.h"
 #include "core/page/FocusDirection.h"
 #include "core/page/PageVisibilityState.h"
@@ -81,7 +80,6 @@
 class DOMWrapperWorld;
 class Database;
 class DatabaseThread;
-class DocumentEventQueue;
 class DocumentFragment;
 class DocumentLifecycleNotifier;
 class DocumentLifecycleObserver;
@@ -168,11 +166,6 @@
 
 typedef int ExceptionCode;
 
-enum PageshowEventPersistence {
-    PageshowEventNotPersisted = 0,
-    PageshowEventPersisted = 1
-};
-
 enum RecalcStyleTime {
     RecalcStyleImmediately, // synchronous
     RecalcStyleDeferred // asynchronous
@@ -212,7 +205,8 @@
 
 typedef unsigned char DocumentClassFlags;
 
-class Document : public ContainerNode, public TreeScope, public ExecutionContext, public ExecutionContextClient, public DocumentSupplementable {
+class Document : public ContainerNode, public TreeScope, public SecurityContext, public ExecutionContext, public ExecutionContextClient
+    , public DocumentSupplementable, public LifecycleContext<Document> {
 public:
     static PassRefPtr<Document> create(const DocumentInit& initializer = DocumentInit())
     {
@@ -224,94 +218,39 @@
     }
     virtual ~Document();
 
-    MediaQueryMatcher* mediaQueryMatcher();
+    MediaQueryMatcher& mediaQueryMatcher();
 
     using ContainerNode::ref;
     using ContainerNode::deref;
+    using SecurityContext::securityOrigin;
+    using SecurityContext::contentSecurityPolicy;
+    using ExecutionContextClient::addConsoleMessage;
 
     virtual bool canContainRangeEndPoint() const { return true; }
 
-    SelectorQueryCache* selectorQueryCache();
+    SelectorQueryCache& selectorQueryCache();
 
     // DOM methods & attributes for Document
 
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(blur);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(cancel);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(canplay);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(canplaythrough);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(close);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(contextmenu);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(cuechange);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dblclick);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(drag);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragend);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragenter);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragleave);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragover);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(drop);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(durationchange);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(emptied);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(ended);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(focus);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(input);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(invalid);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(keydown);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(keypress);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(keyup);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadeddata);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadedmetadata);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mousedown);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseenter);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseleave);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mousemove);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseout);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseover);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseup);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mousewheel);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(pause);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(play);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(playing);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(ratechange);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(reset);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(securitypolicyviolation);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(seeked);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(seeking);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(selectionchange);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(show);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(stalled);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(suspend);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(timeupdate);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(volumechange);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(waiting);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockchange);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockerror);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitvisibilitychange);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
 
     bool shouldMergeWithLegacyDescription(ViewportDescription::Type);
@@ -569,7 +508,7 @@
     // implicitClose() actually does the work of closing the input stream.
     void implicitClose();
 
-    bool dispatchBeforeUnloadEvent(Chrome&, Document* navigatingDocument);
+    bool dispatchBeforeUnloadEvent(Chrome&, bool&);
     void dispatchUnloadEvents();
 
     enum PageDismissalType {
@@ -641,6 +580,8 @@
         Complete
     };
     void setReadyState(ReadyState);
+    bool isLoadCompleted();
+
     void setParsing(bool);
     bool parsing() const { return m_bParsing; }
     int minimumLayoutDelay();
@@ -650,7 +591,7 @@
     int elapsedTime() const;
 
     TextLinkColors& textLinkColors() { return m_textLinkColors; }
-    VisitedLinkState* visitedLinkState() const { return m_visitedLinkState.get(); }
+    VisitedLinkState& visitedLinkState() const { return *m_visitedLinkState; }
 
     MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const LayoutPoint&, const PlatformMouseEvent&);
 
@@ -715,13 +656,12 @@
     void didMergeTextNodes(Text* oldNode, unsigned offset);
     void didSplitTextNode(Text* oldNode);
 
-    void setDOMWindow(DOMWindow* domWindow) { m_domWindow = domWindow; }
+    void clearDOMWindow() { m_domWindow = 0; }
     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 dispatchWindowEvent(PassRefPtr<Event>, PassRefPtr<EventTarget> = 0);
 
     PassRefPtr<Event> createEvent(const String& eventType, ExceptionState&);
 
@@ -950,11 +890,6 @@
     bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
     void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
 
-    void enqueueWindowEvent(PassRefPtr<Event>);
-    void enqueueDocumentEvent(PassRefPtr<Event>);
-    void enqueuePageshowEvent(PageshowEventPersistence);
-    void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
-    void enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject);
     void enqueueScrollEventForNode(Node*);
     void scheduleAnimationFrameEvent(PassRefPtr<Event>);
 
@@ -1042,6 +977,7 @@
 
     AnimationClock& animationClock() { return *m_animationClock; }
     DocumentTimeline* timeline() const { return m_timeline.get(); }
+    DocumentTimeline* transitionTimeline() const { return m_transitionTimeline.get(); }
 
     void addToTopLayer(Element*, const Element* before = 0);
     void removeFromTopLayer(Element*);
@@ -1060,9 +996,7 @@
     virtual DOMWindow* executingWindow() OVERRIDE { return domWindow(); }
     virtual void userEventWasHandled() OVERRIDE { resetLastHandledUserGestureTimestamp(); }
 
-    // Can never return null.
-    FontFaceSet* fonts();
-    DocumentLifecycleNotifier* lifecycleNotifier();
+    DocumentLifecycleNotifier& lifecycleNotifier();
     bool isActive() const { return m_lifecyle.state() == DocumentLifecycle::Active; }
 
     enum HttpRefreshType {
@@ -1071,6 +1005,9 @@
     };
     void maybeHandleHttpRefresh(const String&, HttpRefreshType);
 
+    void updateSecurityOrigin(PassRefPtr<SecurityOrigin>);
+    PassOwnPtr<LifecycleNotifier<Document> > createLifecycleNotifier();
+
 protected:
     Document(const DocumentInit&, DocumentClassFlags = DefaultDocumentClass);
 
@@ -1087,6 +1024,7 @@
     friend class IgnoreDestructiveWriteCountIncrementer;
 
     ScriptedAnimationController& ensureScriptedAnimationController();
+    virtual SecurityContext& securityContext() OVERRIDE { return *this; }
     virtual EventQueue* eventQueue() const FINAL;
 
     void updateDistributionIfNeeded();
@@ -1105,11 +1043,11 @@
 
     virtual void refExecutionContext() { ref(); }
     virtual void derefExecutionContext() { deref(); }
-    virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
 
     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 void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE;
     virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*);
     void internalAddMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
 
@@ -1238,7 +1176,7 @@
     OwnPtr<FormController> m_formController;
 
     TextLinkColors m_textLinkColors;
-    OwnPtr<VisitedLinkState> m_visitedLinkState;
+    const OwnPtr<VisitedLinkState> m_visitedLinkState;
 
     bool m_loadingSheet;
     bool m_visuallyOrdered;
@@ -1271,7 +1209,6 @@
 
     LoadEventProgress m_loadEventProgress;
 
-    RefPtr<SerializedScriptValue> m_pendingStateObject;
     double m_startTime;
     bool m_overMinimumLayoutThreshold;
 
@@ -1322,7 +1259,6 @@
     bool m_mayDisplaySeamlesslyWithParent;
 
     RenderView* m_renderView;
-    RefPtr<DocumentEventQueue> m_eventQueue;
 
     WeakPtrFactory<Document> m_weakFactory;
     WeakPtr<Document> m_contextDocument;
@@ -1343,9 +1279,6 @@
 
     bool m_directionSetOnDocumentElement;
     bool m_writingModeSetOnDocumentElement;
-
-    bool m_didAllowNavigationViaBeforeUnloadConfirmationPanel;
-
     DocumentTiming m_documentTiming;
     RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
     bool m_writeRecursionIsTooDeep;
@@ -1384,12 +1317,11 @@
 
     OwnPtr<AnimationClock> m_animationClock;
     RefPtr<DocumentTimeline> m_timeline;
+    RefPtr<DocumentTimeline> m_transitionTimeline;
 
     RefPtr<Document> m_templateDocument;
     Document* m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
 
-    RefPtr<FontFaceSet> m_fonts;
-
     Timer<Document> m_didAssociateFormControlsTimer;
     HashSet<RefPtr<Element> > m_associatedFormControls;
 };
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index 75fe4a7..ba1e205 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -167,8 +167,6 @@
 
     [RuntimeEnabled=CSSRegions] WebKitNamedFlowCollection webkitGetNamedFlows();
 
-    [RuntimeEnabled=FontLoadEvents] readonly attribute FontFaceSet fonts;
-
     // Event handler attributes
     attribute EventHandler onbeforecopy;
     attribute EventHandler onbeforecut;
diff --git a/Source/core/dom/DocumentInit.cpp b/Source/core/dom/DocumentInit.cpp
index a52dfd3..90b4dd9 100644
--- a/Source/core/dom/DocumentInit.cpp
+++ b/Source/core/dom/DocumentInit.cpp
@@ -31,14 +31,41 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/Document.h"
 #include "core/dom/custom/CustomElementRegistrationContext.h"
+#include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLImportsController.h"
 #include "core/frame/Frame.h"
 
 namespace WebCore {
 
+static Document* parentDocument(Frame* frame)
+{
+    if (!frame)
+        return 0;
+    Element* ownerElement = frame->ownerElement();
+    if (!ownerElement)
+        return 0;
+    return &ownerElement->document();
+}
+
+
+static Document* ownerDocument(Frame* frame)
+{
+    if (!frame)
+        return 0;
+
+    Frame* ownerFrame = frame->tree().parent();
+    if (!ownerFrame)
+        ownerFrame = frame->loader().opener();
+    if (!ownerFrame)
+        return 0;
+    return ownerFrame->document();
+}
+
 DocumentInit::DocumentInit(const KURL& url, Frame* frame, WeakPtr<Document> contextDocument, HTMLImport* import)
     : m_url(url)
     , m_frame(frame)
+    , m_parent(parentDocument(frame))
+    , m_owner(ownerDocument(frame))
     , m_contextDocument(contextDocument)
     , m_import(import)
 {
@@ -47,6 +74,8 @@
 DocumentInit::DocumentInit(const DocumentInit& other)
     : m_url(other.m_url)
     , m_frame(other.m_frame)
+    , m_parent(other.m_parent)
+    , m_owner(other.m_owner)
     , m_contextDocument(other.m_contextDocument)
     , m_import(other.m_import)
     , m_registrationContext(other.m_registrationContext)
@@ -65,8 +94,20 @@
 
 bool DocumentInit::shouldTreatURLAsSrcdocDocument() const
 {
-    ASSERT(m_frame);
-    return m_frame->loader()->shouldTreatURLAsSrcdocDocument(m_url);
+    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
@@ -81,7 +122,7 @@
 SandboxFlags DocumentInit::sandboxFlags() const
 {
     ASSERT(frameForSecurityContext());
-    return frameForSecurityContext()->loader()->effectiveSandboxFlags();
+    return frameForSecurityContext()->loader().effectiveSandboxFlags();
 }
 
 Settings* DocumentInit::settings() const
@@ -90,15 +131,9 @@
     return frameForSecurityContext()->settings();
 }
 
-Frame* DocumentInit::ownerFrame() const
+KURL DocumentInit::parentBaseURL() const
 {
-    if (!m_frame)
-        return 0;
-
-    Frame* ownerFrame = m_frame->tree()->parent();
-    if (!ownerFrame)
-        ownerFrame = m_frame->loader()->opener();
-    return ownerFrame;
+    return m_parent->baseURL();
 }
 
 DocumentInit& DocumentInit::withRegistrationContext(CustomElementRegistrationContext* registrationContext)
diff --git a/Source/core/dom/DocumentInit.h b/Source/core/dom/DocumentInit.h
index ee7d4b1..136d400 100644
--- a/Source/core/dom/DocumentInit.h
+++ b/Source/core/dom/DocumentInit.h
@@ -56,12 +56,17 @@
     bool hasSecurityContext() const { return frameForSecurityContext(); }
     bool shouldTreatURLAsSrcdocDocument() const;
     bool shouldSetURL() const;
+    bool isSeamlessAllowedFor(Document* child) const;
     SandboxFlags sandboxFlags() const;
 
+    Document* parent() const { return m_parent.get(); }
+    Document* owner() const { return m_owner.get(); }
+    KURL parentBaseURL() const;
     Frame* ownerFrame() const;
     Settings* settings() const;
 
     DocumentInit& withRegistrationContext(CustomElementRegistrationContext*);
+
     PassRefPtr<CustomElementRegistrationContext> registrationContext(Document*) const;
     WeakPtr<Document> contextDocument() const;
 
@@ -72,6 +77,8 @@
 
     KURL m_url;
     Frame* m_frame;
+    RefPtr<Document> m_parent;
+    RefPtr<Document> m_owner;
     WeakPtr<Document> m_contextDocument;
     HTMLImport* m_import;
     RefPtr<CustomElementRegistrationContext> m_registrationContext;
diff --git a/Source/core/dom/DocumentLifecycleNotifier.cpp b/Source/core/dom/DocumentLifecycleNotifier.cpp
index ddf28a2..36c7997 100644
--- a/Source/core/dom/DocumentLifecycleNotifier.cpp
+++ b/Source/core/dom/DocumentLifecycleNotifier.cpp
@@ -32,29 +32,29 @@
 
 namespace WebCore {
 
-DocumentLifecycleNotifier::DocumentLifecycleNotifier(ExecutionContext* context)
-    : ContextLifecycleNotifier(context)
+DocumentLifecycleNotifier::DocumentLifecycleNotifier(Document* document)
+    : LifecycleNotifier<Document>(document)
 {
 }
 
-void DocumentLifecycleNotifier::addObserver(LifecycleObserver* observer)
+void DocumentLifecycleNotifier::addObserver(DocumentLifecycleNotifier::Observer* observer)
 {
-    if (observer->observerType() == LifecycleObserver::DocumentLifecycleObserverType) {
+    if (observer->observerType() == Observer::DocumentLifecycleObserverType) {
         RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
         m_documentObservers.add(static_cast<DocumentLifecycleObserver*>(observer));
     }
 
-    ContextLifecycleNotifier::addObserver(observer);
+    LifecycleNotifier<Document>::addObserver(observer);
 }
 
-void DocumentLifecycleNotifier::removeObserver(LifecycleObserver* observer)
+void DocumentLifecycleNotifier::removeObserver(DocumentLifecycleNotifier::Observer* observer)
 {
-    if (observer->observerType() == LifecycleObserver::DocumentLifecycleObserverType) {
+    if (observer->observerType() == Observer::DocumentLifecycleObserverType) {
         RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
         m_documentObservers.remove(static_cast<DocumentLifecycleObserver*>(observer));
     }
 
-    ContextLifecycleNotifier::removeObserver(observer);
+    LifecycleNotifier<Document>::removeObserver(observer);
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentLifecycleNotifier.h b/Source/core/dom/DocumentLifecycleNotifier.h
index 6c730eb..07888bd 100644
--- a/Source/core/dom/DocumentLifecycleNotifier.h
+++ b/Source/core/dom/DocumentLifecycleNotifier.h
@@ -26,33 +26,34 @@
 #ifndef DocumentLifecycleNotifier_h
 #define DocumentLifecycleNotifier_h
 
-#include "core/dom/ContextLifecycleNotifier.h"
 #include "core/dom/DocumentLifecycleObserver.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/TemporaryChange.h"
 
 namespace WebCore {
 
-class DocumentLifecycleNotifier : public ContextLifecycleNotifier {
+class Document;
+
+class DocumentLifecycleNotifier : public LifecycleNotifier<Document> {
 public:
-    static PassOwnPtr<DocumentLifecycleNotifier> create(ExecutionContext*);
+    static PassOwnPtr<DocumentLifecycleNotifier> create(Document*);
 
     void notifyDocumentWasDetached();
     void notifyDocumentWasDisposed();
 
-    virtual void addObserver(LifecycleObserver*) OVERRIDE;
-    virtual void removeObserver(LifecycleObserver*) OVERRIDE;
+    virtual void addObserver(Observer*) OVERRIDE;
+    virtual void removeObserver(Observer*) OVERRIDE;
 
 private:
-    explicit DocumentLifecycleNotifier(ExecutionContext*);
+    explicit DocumentLifecycleNotifier(Document*);
 
     typedef HashSet<DocumentLifecycleObserver*> DocumentObserverSet;
     DocumentObserverSet m_documentObservers;
 };
 
-inline PassOwnPtr<DocumentLifecycleNotifier> DocumentLifecycleNotifier::create(ExecutionContext* context)
+inline PassOwnPtr<DocumentLifecycleNotifier> DocumentLifecycleNotifier::create(Document* document)
 {
-    return adoptPtr(new DocumentLifecycleNotifier(context));
+    return adoptPtr(new DocumentLifecycleNotifier(document));
 }
 
 inline void DocumentLifecycleNotifier::notifyDocumentWasDetached()
diff --git a/Source/core/dom/DocumentLifecycleObserver.cpp b/Source/core/dom/DocumentLifecycleObserver.cpp
index 413d1ce..b0abbfd 100644
--- a/Source/core/dom/DocumentLifecycleObserver.cpp
+++ b/Source/core/dom/DocumentLifecycleObserver.cpp
@@ -31,8 +31,18 @@
 
 namespace WebCore {
 
+template<> void observerContext(Document* context, LifecycleObserver<Document>* observer)
+{
+    static_cast<LifecycleContext<Document>*>(context)->wasObservedBy(observer);
+}
+
+template<> void unobserverContext(Document* context, LifecycleObserver<Document>* observer)
+{
+    static_cast<LifecycleContext<Document>*>(context)->wasUnobservedBy(observer);
+}
+
 DocumentLifecycleObserver::DocumentLifecycleObserver(Document* document)
-    : ContextLifecycleObserver(document, DocumentLifecycleObserverType)
+    : LifecycleObserver<Document>(document, DocumentLifecycleObserverType)
 {
 }
 
diff --git a/Source/core/dom/DocumentLifecycleObserver.h b/Source/core/dom/DocumentLifecycleObserver.h
index 3005f72..47233c5 100644
--- a/Source/core/dom/DocumentLifecycleObserver.h
+++ b/Source/core/dom/DocumentLifecycleObserver.h
@@ -26,14 +26,16 @@
 #ifndef DocumentLifecycleObserver_h
 #define DocumentLifecycleObserver_h
 
-#include "core/dom/ContextLifecycleNotifier.h"
-#include "core/dom/ContextLifecycleObserver.h"
+#include "platform/LifecycleContext.h"
 
 namespace WebCore {
 
 class Document;
 
-class DocumentLifecycleObserver : public ContextLifecycleObserver {
+template<> void observerContext(Document*, LifecycleObserver<Document>*);
+template<> void unobserverContext(Document*, LifecycleObserver<Document>*);
+
+class DocumentLifecycleObserver : public LifecycleObserver<Document> {
 public:
     explicit DocumentLifecycleObserver(Document*);
     virtual ~DocumentLifecycleObserver();
diff --git a/Source/core/dom/DocumentOrderedList.cpp b/Source/core/dom/DocumentOrderedList.cpp
index 62802cc..49520e6 100644
--- a/Source/core/dom/DocumentOrderedList.cpp
+++ b/Source/core/dom/DocumentOrderedList.cpp
@@ -64,9 +64,9 @@
     m_nodes.add(node);
 }
 
-void DocumentOrderedList::remove(Node* node)
+void DocumentOrderedList::remove(const Node* node)
 {
-    m_nodes.remove(node);
+    m_nodes.remove(const_cast<Node*>(node));
 }
 
 }
diff --git a/Source/core/dom/DocumentOrderedList.h b/Source/core/dom/DocumentOrderedList.h
index 8dde172..133a34d 100644
--- a/Source/core/dom/DocumentOrderedList.h
+++ b/Source/core/dom/DocumentOrderedList.h
@@ -42,7 +42,7 @@
 
     void add(Node*);
     void parserAdd(Node*);
-    void remove(Node*);
+    void remove(const Node*);
     bool isEmpty() const { return m_nodes.isEmpty(); }
     void clear() { m_nodes.clear(); }
 
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index cb09066..41c734a 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -193,14 +193,10 @@
 
 Element::~Element()
 {
-#ifndef NDEBUG
-    if (document().renderer()) {
-        // 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(!inNamedFlow());
-    }
-#endif
+    // 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());
 
     if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
         cssomWrapper->clearParentElement();
@@ -214,7 +210,7 @@
 
         if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
             if (ActiveAnimations* activeAnimations = data->activeAnimations())
-                activeAnimations->cssAnimations()->cancel();
+                activeAnimations->cssAnimations().cancel();
         }
     }
 
@@ -294,12 +290,6 @@
     return true;
 }
 
-DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
-DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
-DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
-DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
-DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, scroll);
-
 PassRefPtr<Node> Element::cloneNode(bool deep)
 {
     return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
@@ -980,7 +970,7 @@
     document().incDOMTreeVersion();
 
     StyleResolver* styleResolver = document().styleResolverIfExists();
-    bool testShouldInvalidateStyle = confusingAndOftenMisusedAttached() && styleResolver && styleChangeType() < SubtreeStyleChange;
+    bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
     bool shouldInvalidateStyle = false;
 
     if (isStyledElement() && name == styleAttr) {
@@ -1095,7 +1085,7 @@
 void Element::classAttributeChanged(const AtomicString& newClassString)
 {
     StyleResolver* styleResolver = document().styleResolverIfExists();
-    bool testShouldInvalidateStyle = confusingAndOftenMisusedAttached() && styleResolver && styleChangeType() < SubtreeStyleChange;
+    bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
     bool shouldInvalidateStyle = false;
 
     if (classStringHasClassName(newClassString)) {
@@ -1451,7 +1441,7 @@
 
         if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
             if (ActiveAnimations* activeAnimations = data->activeAnimations())
-                activeAnimations->cssAnimations()->cancel();
+                activeAnimations->cssAnimations().cancel();
         }
     }
     if (ElementShadow* shadow = this->shadow())
@@ -1578,9 +1568,11 @@
     if (RenderObject* renderer = this->renderer()) {
         if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles()) {
             renderer->setAnimatableStyle(newStyle.get());
-        } else if (needsStyleRecalc()) {
+        } 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.
+            // FIXME: We may be able to remove this hack, see discussion in
+            // https://codereview.chromium.org/30453002/
             renderer->setStyleInternal(newStyle.get());
         }
     }
@@ -1615,12 +1607,9 @@
     if (shouldRecalcStyle(change, this))
         updatePseudoElement(BEFORE, change);
 
-    // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
-    // For now we will just worry about the common case, since it's a lot trickier to get the second case right
-    // without doing way too much re-resolution.
     bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
     bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
-    bool forceCheckOfNextElementSibling = false;
+    unsigned forceCheckOfNextElementCount = 0;
     bool forceCheckOfAnyElementSibling = false;
     if (hasDirectAdjacentRules || hasIndirectAdjacentRules) {
         for (Node* child = firstChild(); child; child = child->nextSibling()) {
@@ -1628,9 +1617,16 @@
                 continue;
             Element* element = toElement(child);
             bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
-            if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
+
+            if (forceCheckOfNextElementCount || forceCheckOfAnyElementSibling)
                 element->setNeedsStyleRecalc();
-            forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
+
+            if (forceCheckOfNextElementCount)
+                forceCheckOfNextElementCount--;
+
+            if (childRulesChanged && hasDirectAdjacentRules)
+                forceCheckOfNextElementCount = document().styleEngine()->maxDirectAdjacentSelectors();
+
             forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
         }
     }
@@ -1692,7 +1688,7 @@
         ensureUserAgentShadowRoot();
 
     if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
-        return ensureShadow().addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
+        return 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
@@ -1701,7 +1697,7 @@
         es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
         return 0;
     }
-    return ensureShadow().addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
+    return ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot);
 }
 
 ShadowRoot* Element::shadowRoot() const
@@ -1735,7 +1731,7 @@
 {
     if (ShadowRoot* shadowRoot = userAgentShadowRoot())
         return shadowRoot;
-    ShadowRoot* shadowRoot = ensureShadow().addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
+    ShadowRoot* shadowRoot = ensureShadow().addShadowRoot(*this, ShadowRoot::UserAgentShadowRoot);
     didAddUserAgentShadowRoot(shadowRoot);
     return shadowRoot;
 }
@@ -1767,7 +1763,7 @@
 static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
                                         Node* beforeChange, Node* afterChange, int childCountDelta)
 {
-    if (!e->confusingAndOftenMisusedAttached() || e->document().hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
+    if (!e->inActiveDocument() || e->document().hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
         return;
 
     // :empty selector.
@@ -1935,7 +1931,7 @@
     setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
 
     attrNode->attachToElement(this);
-    treeScope().adoptIfNeeded(attrNode);
+    treeScope().adoptIfNeeded(*attrNode);
     ensureAttrNodeListForElement(this).append(attrNode);
 
     return oldAttrNode.release();
@@ -2311,7 +2307,7 @@
             return usedStyle;
     }
 
-    if (!confusingAndOftenMisusedAttached())
+    if (!inActiveDocument())
         // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
         // document tree and figure out when to destroy the computed style for such elements.
         return 0;
@@ -2608,7 +2604,7 @@
         return false;
     }
 
-    SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selector, document(), es);
+    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selector, document(), es);
     if (!selectorQuery)
         return false;
     return selectorQuery->matches(this);
@@ -2929,14 +2925,14 @@
     }
 
     if (oldValue != newValue) {
-        if (confusingAndOftenMisusedAttached() && hasSelectorForAttribute(&document(), name.localName()))
+        if (inActiveDocument() && hasSelectorForAttribute(&document(), name.localName()))
            setNeedsStyleRecalc();
 
         if (isUpgradedCustomElement())
             CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
     }
 
-    if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
+    if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(*this, name))
         recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
 
     InspectorInstrumentation::willModifyDOMAttr(this, oldValue, newValue);
@@ -3010,15 +3006,15 @@
     RefPtr<HTMLCollection> collection;
     if (type == TableRows) {
         ASSERT(hasTagName(tableTag));
-        return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
+        return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
     } else if (type == SelectOptions) {
         ASSERT(hasTagName(selectTag));
-        return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
+        return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
     } else if (type == FormControls) {
         ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
-        return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
+        return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
     }
-    return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, type);
 }
 
 static void scheduleLayerUpdateCallback(Node* node)
@@ -3066,7 +3062,7 @@
     RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
     if (!attrNode) {
         attrNode = Attr::create(*this, name);
-        treeScope().adoptIfNeeded(attrNode.get());
+        treeScope().adoptIfNeeded(*attrNode);
         attrNodeList.append(attrNode);
     }
     return attrNode.release();
@@ -3226,8 +3222,10 @@
 {
     ASSERT(isStyledElement());
     RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
-    if (!inlineStyle)
-        inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document().inQuirksMode()));
+    if (!inlineStyle) {
+        CSSParserMode mode = (!isHTMLElement() || document().inQuirksMode()) ? HTMLQuirksMode : HTMLStandardMode;
+        inlineStyle = MutableStylePropertySet::create(mode);
+    }
     else if (!inlineStyle->isMutable())
         inlineStyle = inlineStyle->mutableCopy();
     ASSERT(inlineStyle->isMutable());
@@ -3433,206 +3431,4 @@
     return true;
 }
 
-void ElementData::deref()
-{
-    if (!derefBase())
-        return;
-
-    if (m_isUnique)
-        delete static_cast<UniqueElementData*>(this);
-    else
-        delete static_cast<ShareableElementData*>(this);
-}
-
-ElementData::ElementData()
-    : m_isUnique(true)
-    , m_arraySize(0)
-    , m_presentationAttributeStyleIsDirty(false)
-    , m_styleAttributeIsDirty(false)
-    , m_animatedSVGAttributesAreDirty(false)
-{
-}
-
-ElementData::ElementData(unsigned arraySize)
-    : m_isUnique(false)
-    , m_arraySize(arraySize)
-    , m_presentationAttributeStyleIsDirty(false)
-    , m_styleAttributeIsDirty(false)
-    , m_animatedSVGAttributesAreDirty(false)
-{
-}
-
-struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
-    unsigned bitfield;
-    void* refPtrs[3];
-};
-
-COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
-
-static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
-{
-    return sizeof(ShareableElementData) + sizeof(Attribute) * count;
-}
-
-PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
-{
-    void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
-    return adoptRef(new (slot) ShareableElementData(attributes));
-}
-
-PassRefPtr<UniqueElementData> UniqueElementData::create()
-{
-    return adoptRef(new UniqueElementData);
-}
-
-ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
-    : ElementData(attributes.size())
-{
-    for (unsigned i = 0; i < m_arraySize; ++i)
-        new (&m_attributeArray[i]) Attribute(attributes[i]);
-}
-
-ShareableElementData::~ShareableElementData()
-{
-    for (unsigned i = 0; i < m_arraySize; ++i)
-        m_attributeArray[i].~Attribute();
-}
-
-ShareableElementData::ShareableElementData(const UniqueElementData& other)
-    : ElementData(other, false)
-{
-    ASSERT(!other.m_presentationAttributeStyle);
-
-    if (other.m_inlineStyle) {
-        ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
-        m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
-    }
-
-    for (unsigned i = 0; i < m_arraySize; ++i)
-        new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
-}
-
-ElementData::ElementData(const ElementData& other, bool isUnique)
-    : m_isUnique(isUnique)
-    , m_arraySize(isUnique ? 0 : other.length())
-    , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
-    , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
-    , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
-    , m_classNames(other.m_classNames)
-    , m_idForStyleResolution(other.m_idForStyleResolution)
-{
-    // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
-}
-
-UniqueElementData::UniqueElementData()
-{
-}
-
-UniqueElementData::UniqueElementData(const UniqueElementData& other)
-    : ElementData(other, true)
-    , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
-    , m_attributeVector(other.m_attributeVector)
-{
-    m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
-}
-
-UniqueElementData::UniqueElementData(const ShareableElementData& other)
-    : ElementData(other, true)
-{
-    // An ShareableElementData should never have a mutable inline StylePropertySet attached.
-    ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
-    m_inlineStyle = other.m_inlineStyle;
-
-    m_attributeVector.reserveCapacity(other.length());
-    for (unsigned i = 0; i < other.length(); ++i)
-        m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
-}
-
-PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
-{
-    if (isUnique())
-        return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
-    return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
-}
-
-PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
-{
-    void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
-    return adoptRef(new (slot) ShareableElementData(*this));
-}
-
-void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
-{
-    m_attributeVector.append(Attribute(attributeName, value));
-}
-
-void UniqueElementData::removeAttribute(size_t index)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(index < length());
-    m_attributeVector.remove(index);
-}
-
-bool ElementData::isEquivalent(const ElementData* other) const
-{
-    if (!other)
-        return isEmpty();
-
-    unsigned len = length();
-    if (len != other->length())
-        return false;
-
-    for (unsigned i = 0; i < len; i++) {
-        const Attribute* attribute = attributeItem(i);
-        const Attribute* otherAttr = other->getAttributeItem(attribute->name());
-        if (!otherAttr || attribute->value() != otherAttr->value())
-            return false;
-    }
-
-    return true;
-}
-
-size_t ElementData::getAttrIndex(Attr* attr) const
-{
-    // This relies on the fact that Attr's QualifiedName == the Attribute's name.
-    for (unsigned i = 0; i < length(); ++i) {
-        if (attributeItem(i)->name() == attr->qualifiedName())
-            return i;
-    }
-    return kNotFound;
-}
-
-size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
-{
-    // Continue to checking case-insensitively and/or full namespaced names if necessary:
-    for (unsigned i = 0; i < length(); ++i) {
-        const Attribute* attribute = attributeItem(i);
-        if (!attribute->name().hasPrefix()) {
-            if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
-                return i;
-        } else {
-            // FIXME: Would be faster to do this comparison without calling toString, which
-            // generates a temporary string by concatenation. But this branch is only reached
-            // if the attribute name has a prefix, which is rare in HTML.
-            if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
-                return i;
-        }
-    }
-    return kNotFound;
-}
-
-Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
-{
-    for (unsigned i = 0; i < length(); ++i) {
-        if (m_attributeVector.at(i).name().matches(name))
-            return &m_attributeVector.at(i);
-    }
-    return 0;
-}
-
-Attribute* UniqueElementData::attributeItem(unsigned index)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(index < length());
-    return &m_attributeVector.at(index);
-}
-
 } // namespace WebCore
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index e28bdd2..c35fe66 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -30,6 +30,7 @@
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/Document.h"
+#include "core/dom/ElementData.h"
 #include "core/dom/SpaceSplitString.h"
 #include "core/html/CollectionType.h"
 #include "core/page/FocusDirection.h"
@@ -45,7 +46,6 @@
 class ClientRectList;
 class DOMStringMap;
 class DOMTokenList;
-class Element;
 class ElementRareData;
 class ElementShadow;
 class ExceptionState;
@@ -58,111 +58,7 @@
 class PseudoElement;
 class RenderRegion;
 class ShadowRoot;
-class ShareableElementData;
 class StylePropertySet;
-class UniqueElementData;
-
-class ElementData : public RefCounted<ElementData> {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    // Override RefCounted's deref() to ensure operator delete is called on
-    // the appropriate subclass type.
-    void deref();
-
-    void clearClass() const { m_classNames.clear(); }
-    void setClass(const AtomicString& className, bool shouldFoldCase) const { m_classNames.set(className, shouldFoldCase); }
-    const SpaceSplitString& classNames() const { return m_classNames; }
-
-    const AtomicString& idForStyleResolution() const { return m_idForStyleResolution; }
-    void setIdForStyleResolution(const AtomicString& newId) const { m_idForStyleResolution = newId; }
-
-    const StylePropertySet* inlineStyle() const { return m_inlineStyle.get(); }
-
-    const StylePropertySet* presentationAttributeStyle() const;
-
-    size_t length() const;
-    bool isEmpty() const { return !length(); }
-
-    const Attribute* attributeItem(unsigned index) const;
-    const Attribute* getAttributeItem(const QualifiedName&) const;
-    size_t getAttributeItemIndex(const QualifiedName&, bool shouldIgnoreCase = false) const;
-    size_t getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
-    size_t getAttrIndex(Attr*) const;
-
-    bool hasID() const { return !m_idForStyleResolution.isNull(); }
-    bool hasClass() const { return !m_classNames.isNull(); }
-
-    bool isEquivalent(const ElementData* other) const;
-
-    bool isUnique() const { return m_isUnique; }
-
-protected:
-    ElementData();
-    ElementData(unsigned arraySize);
-    ElementData(const ElementData&, bool isUnique);
-
-    unsigned m_isUnique : 1;
-    unsigned m_arraySize : 28;
-    mutable unsigned m_presentationAttributeStyleIsDirty : 1;
-    mutable unsigned m_styleAttributeIsDirty : 1;
-    mutable unsigned m_animatedSVGAttributesAreDirty : 1;
-
-    mutable RefPtr<StylePropertySet> m_inlineStyle;
-    mutable SpaceSplitString m_classNames;
-    mutable AtomicString m_idForStyleResolution;
-
-private:
-    friend class Element;
-    friend class ShareableElementData;
-    friend class UniqueElementData;
-    friend class SVGElement;
-
-    const Attribute* attributeBase() const;
-    const Attribute* getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
-    size_t getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
-
-    PassRefPtr<UniqueElementData> makeUniqueCopy() const;
-};
-
-#if COMPILER(MSVC)
-#pragma warning(push)
-#pragma warning(disable: 4200) // Disable "zero-sized array in struct/union" warning
-#endif
-
-class ShareableElementData : public ElementData {
-public:
-    static PassRefPtr<ShareableElementData> createWithAttributes(const Vector<Attribute>&);
-
-    explicit ShareableElementData(const Vector<Attribute>&);
-    explicit ShareableElementData(const UniqueElementData&);
-    ~ShareableElementData();
-
-    Attribute m_attributeArray[0];
-};
-
-#if COMPILER(MSVC)
-#pragma warning(pop)
-#endif
-
-class UniqueElementData : public ElementData {
-public:
-    static PassRefPtr<UniqueElementData> create();
-    PassRefPtr<ShareableElementData> makeShareableCopy() const;
-
-    // These functions do no error/duplicate checking.
-    void addAttribute(const QualifiedName&, const AtomicString&);
-    void removeAttribute(size_t index);
-
-    Attribute* attributeItem(unsigned index);
-    Attribute* getAttributeItem(const QualifiedName&);
-
-    UniqueElementData();
-    explicit UniqueElementData(const ShareableElementData&);
-    explicit UniqueElementData(const UniqueElementData&);
-
-    mutable RefPtr<StylePropertySet> m_presentationAttributeStyle;
-    Vector<Attribute, 4> m_attributeVector;
-};
 
 enum AffectedSelectorType {
     AffectedSelectorChecked = 1,
@@ -186,82 +82,22 @@
     static PassRefPtr<Element> create(const QualifiedName&, Document*);
     virtual ~Element();
 
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(cancel);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(canplay);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(canplaythrough);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(close);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(contextmenu);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(cuechange);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dblclick);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(drag);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragend);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragenter);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragleave);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragover);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(drop);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(durationchange);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(emptied);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(ended);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(input);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(invalid);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(keydown);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(keypress);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(keyup);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadeddata);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadedmetadata);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mousedown);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseenter);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseleave);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mousemove);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseout);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseover);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseup);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(mousewheel);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(pause);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(play);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(playing);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(ratechange);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(reset);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(seeked);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(seeking);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(show);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(stalled);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(suspend);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(timeupdate);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(volumechange);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(waiting);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
 
-    // These four attribute event handler attributes are overridden by HTMLBodyElement
-    // and HTMLFrameSetElement to forward to the DOMWindow.
-    DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(blur);
-    DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(error);
-    DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(focus);
-    DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(load);
-    DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(scroll);
-
     bool hasAttribute(const QualifiedName&) const;
     const AtomicString& getAttribute(const QualifiedName&) const;
     void setAttribute(const QualifiedName&, const AtomicString& value);
@@ -472,7 +308,7 @@
     virtual void didAddShadowRoot(ShadowRoot&);
     ShadowRoot* userAgentShadowRoot() const;
     ShadowRoot* ensureUserAgentShadowRoot();
-    virtual const AtomicString& shadowPseudoId() const { return !part().isEmpty() ? part() : pseudo(); }
+    const AtomicString& shadowPseudoId() const;
 
     RenderStyle* computedStyle(PseudoId = NOPSEUDO);
 
@@ -876,6 +712,15 @@
     return elementData()->idForStyleResolution();
 }
 
+inline const AtomicString& Element::shadowPseudoId() const
+{
+    // FIXME: We should remove both part() and pseudo(), neither are in the new spec.
+    const AtomicString& part = this->part();
+    if (!part.isEmpty())
+        return part;
+    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
@@ -1015,86 +860,6 @@
     return element && element->shadow();
 }
 
-inline size_t ElementData::length() const
-{
-    if (isUnique())
-        return static_cast<const UniqueElementData*>(this)->m_attributeVector.size();
-    return m_arraySize;
-}
-
-inline const StylePropertySet* ElementData::presentationAttributeStyle() const
-{
-    if (!m_isUnique)
-        return 0;
-    return static_cast<const UniqueElementData*>(this)->m_presentationAttributeStyle.get();
-}
-
-inline const Attribute* ElementData::getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const
-{
-    size_t index = getAttributeItemIndex(name, shouldIgnoreAttributeCase);
-    if (index != kNotFound)
-        return attributeItem(index);
-    return 0;
-}
-
-inline const Attribute* ElementData::attributeBase() const
-{
-    if (m_isUnique)
-        return static_cast<const UniqueElementData*>(this)->m_attributeVector.begin();
-    return static_cast<const ShareableElementData*>(this)->m_attributeArray;
-}
-
-inline size_t ElementData::getAttributeItemIndex(const QualifiedName& name, bool shouldIgnoreCase) const
-{
-    const Attribute* begin = attributeBase();
-    for (unsigned i = 0; i < length(); ++i) {
-        const Attribute& attribute = begin[i];
-        if (attribute.name().matchesPossiblyIgnoringCase(name, shouldIgnoreCase))
-            return i;
-    }
-    return kNotFound;
-}
-
-// We use a boolean parameter instead of calling shouldIgnoreAttributeCase so that the caller
-// can tune the behavior (hasAttribute is case sensitive whereas getAttribute is not).
-inline size_t ElementData::getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const
-{
-    unsigned len = length();
-    bool doSlowCheck = shouldIgnoreAttributeCase;
-
-    // Optimize for the case where the attribute exists and its name exactly matches.
-    const Attribute* begin = attributeBase();
-    for (unsigned i = 0; i < len; ++i) {
-        const Attribute& attribute = begin[i];
-        if (!attribute.name().hasPrefix()) {
-            if (name == attribute.localName())
-                return i;
-        } else
-            doSlowCheck = true;
-    }
-
-    if (doSlowCheck)
-        return getAttributeItemIndexSlowCase(name, shouldIgnoreAttributeCase);
-    return kNotFound;
-}
-
-inline const Attribute* ElementData::getAttributeItem(const QualifiedName& name) const
-{
-    const Attribute* begin = attributeBase();
-    for (unsigned i = 0; i < length(); ++i) {
-        const Attribute& attribute = begin[i];
-        if (attribute.name().matches(name))
-            return &attribute;
-    }
-    return 0;
-}
-
-inline const Attribute* ElementData::attributeItem(unsigned index) const
-{
-    RELEASE_ASSERT(index < length());
-    return attributeBase() + index;
-}
-
 } // namespace
 
 #endif
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index 8d08592..8d45e7d 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -122,10 +122,10 @@
 
     // Mozilla version
     const unsigned short ALLOW_KEYBOARD_INPUT = 1;
-    [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=AccessForAllWorlds] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
+    [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=AccessForAllWorlds, MeasureAs=PrefixedElementRequestFullScreen] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
 
     // W3C version
-    [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=AccessForAllWorlds] void webkitRequestFullscreen();
+    [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=AccessForAllWorlds, MeasureAs=PrefixedElementRequestFullscreen] void webkitRequestFullscreen();
 
     void webkitRequestPointerLock();
 
diff --git a/Source/core/dom/ElementData.cpp b/Source/core/dom/ElementData.cpp
new file mode 100644
index 0000000..9248276
--- /dev/null
+++ b/Source/core/dom/ElementData.cpp
@@ -0,0 +1,244 @@
+/*
+ * 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/dom/ElementData.h"
+
+#include "core/css/StylePropertySet.h"
+#include "core/dom/Attr.h"
+#include "core/dom/QualifiedName.h"
+#include "wtf/Vector.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
+    unsigned bitfield;
+    void* refPtrs[3];
+};
+
+COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
+
+static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
+{
+    return sizeof(ShareableElementData) + sizeof(Attribute) * count;
+}
+
+ElementData::ElementData()
+    : m_isUnique(true)
+    , m_arraySize(0)
+    , m_presentationAttributeStyleIsDirty(false)
+    , m_styleAttributeIsDirty(false)
+    , m_animatedSVGAttributesAreDirty(false)
+{
+}
+
+ElementData::ElementData(unsigned arraySize)
+    : m_isUnique(false)
+    , m_arraySize(arraySize)
+    , m_presentationAttributeStyleIsDirty(false)
+    , m_styleAttributeIsDirty(false)
+    , m_animatedSVGAttributesAreDirty(false)
+{
+}
+
+ElementData::ElementData(const ElementData& other, bool isUnique)
+    : m_isUnique(isUnique)
+    , m_arraySize(isUnique ? 0 : other.length())
+    , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
+    , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
+    , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
+    , m_classNames(other.m_classNames)
+    , m_idForStyleResolution(other.m_idForStyleResolution)
+{
+    // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
+}
+
+void ElementData::deref()
+{
+    if (!derefBase())
+        return;
+
+    if (m_isUnique)
+        delete static_cast<UniqueElementData*>(this);
+    else
+        delete static_cast<ShareableElementData*>(this);
+}
+
+PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
+{
+    if (isUnique())
+        return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
+    return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
+}
+
+bool ElementData::isEquivalent(const ElementData* other) const
+{
+    if (!other)
+        return isEmpty();
+
+    unsigned len = length();
+    if (len != other->length())
+        return false;
+
+    for (unsigned i = 0; i < len; i++) {
+        const Attribute* attribute = attributeItem(i);
+        const Attribute* otherAttr = other->getAttributeItem(attribute->name());
+        if (!otherAttr || attribute->value() != otherAttr->value())
+            return false;
+    }
+
+    return true;
+}
+
+size_t ElementData::getAttrIndex(Attr* attr) const
+{
+    // This relies on the fact that Attr's QualifiedName == the Attribute's name.
+    for (unsigned i = 0; i < length(); ++i) {
+        if (attributeItem(i)->name() == attr->qualifiedName())
+            return i;
+    }
+    return kNotFound;
+}
+
+size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
+{
+    // Continue to checking case-insensitively and/or full namespaced names if necessary:
+    for (unsigned i = 0; i < length(); ++i) {
+        const Attribute* attribute = attributeItem(i);
+        if (!attribute->name().hasPrefix()) {
+            if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
+                return i;
+        } else {
+            // FIXME: Would be faster to do this comparison without calling toString, which
+            // generates a temporary string by concatenation. But this branch is only reached
+            // if the attribute name has a prefix, which is rare in HTML.
+            if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
+                return i;
+        }
+    }
+    return kNotFound;
+}
+
+ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
+    : ElementData(attributes.size())
+{
+    for (unsigned i = 0; i < m_arraySize; ++i)
+        new (&m_attributeArray[i]) Attribute(attributes[i]);
+}
+
+ShareableElementData::~ShareableElementData()
+{
+    for (unsigned i = 0; i < m_arraySize; ++i)
+        m_attributeArray[i].~Attribute();
+}
+
+ShareableElementData::ShareableElementData(const UniqueElementData& other)
+    : ElementData(other, false)
+{
+    ASSERT(!other.m_presentationAttributeStyle);
+
+    if (other.m_inlineStyle) {
+        ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
+        m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
+    }
+
+    for (unsigned i = 0; i < m_arraySize; ++i)
+        new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
+}
+
+PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
+{
+    void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
+    return adoptRef(new (slot) ShareableElementData(attributes));
+}
+
+UniqueElementData::UniqueElementData()
+{
+}
+
+UniqueElementData::UniqueElementData(const UniqueElementData& other)
+    : ElementData(other, true)
+    , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
+    , m_attributeVector(other.m_attributeVector)
+{
+    m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
+}
+
+UniqueElementData::UniqueElementData(const ShareableElementData& other)
+    : ElementData(other, true)
+{
+    // An ShareableElementData should never have a mutable inline StylePropertySet attached.
+    ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
+    m_inlineStyle = other.m_inlineStyle;
+
+    m_attributeVector.reserveCapacity(other.length());
+    for (unsigned i = 0; i < other.length(); ++i)
+        m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
+}
+
+PassRefPtr<UniqueElementData> UniqueElementData::create()
+{
+    return adoptRef(new UniqueElementData);
+}
+
+PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
+{
+    void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
+    return adoptRef(new (slot) ShareableElementData(*this));
+}
+
+void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
+{
+    m_attributeVector.append(Attribute(attributeName, value));
+}
+
+void UniqueElementData::removeAttribute(size_t index)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(index < length());
+    m_attributeVector.remove(index);
+}
+
+Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
+{
+    for (unsigned i = 0; i < length(); ++i) {
+        if (m_attributeVector.at(i).name().matches(name))
+            return &m_attributeVector.at(i);
+    }
+    return 0;
+}
+
+Attribute* UniqueElementData::attributeItem(unsigned index)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(index < length());
+    return &m_attributeVector.at(index);
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/ElementData.h b/Source/core/dom/ElementData.h
new file mode 100644
index 0000000..50c2879
--- /dev/null
+++ b/Source/core/dom/ElementData.h
@@ -0,0 +1,230 @@
+/*
+ * 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 ElementData_h
+#define ElementData_h
+
+#include "core/dom/Attribute.h"
+#include "core/dom/SpaceSplitString.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class Attr;
+class ShareableElementData;
+class StylePropertySet;
+class UniqueElementData;
+
+class ElementData : public RefCounted<ElementData> {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    // Override RefCounted's deref() to ensure operator delete is called on
+    // the appropriate subclass type.
+    void deref();
+
+    void clearClass() const { m_classNames.clear(); }
+    void setClass(const AtomicString& className, bool shouldFoldCase) const { m_classNames.set(className, shouldFoldCase); }
+    const SpaceSplitString& classNames() const { return m_classNames; }
+
+    const AtomicString& idForStyleResolution() const { return m_idForStyleResolution; }
+    void setIdForStyleResolution(const AtomicString& newId) const { m_idForStyleResolution = newId; }
+
+    const StylePropertySet* inlineStyle() const { return m_inlineStyle.get(); }
+
+    const StylePropertySet* presentationAttributeStyle() const;
+
+    size_t length() const;
+    bool isEmpty() const { return !length(); }
+
+    const Attribute* attributeItem(unsigned index) const;
+    const Attribute* getAttributeItem(const QualifiedName&) const;
+    size_t getAttributeItemIndex(const QualifiedName&, bool shouldIgnoreCase = false) const;
+    size_t getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
+    size_t getAttrIndex(Attr*) const;
+
+    bool hasID() const { return !m_idForStyleResolution.isNull(); }
+    bool hasClass() const { return !m_classNames.isNull(); }
+
+    bool isEquivalent(const ElementData* other) const;
+
+    bool isUnique() const { return m_isUnique; }
+
+protected:
+    ElementData();
+    explicit ElementData(unsigned arraySize);
+    ElementData(const ElementData&, bool isUnique);
+
+    unsigned m_isUnique : 1;
+    unsigned m_arraySize : 28;
+    mutable unsigned m_presentationAttributeStyleIsDirty : 1;
+    mutable unsigned m_styleAttributeIsDirty : 1;
+    mutable unsigned m_animatedSVGAttributesAreDirty : 1;
+
+    mutable RefPtr<StylePropertySet> m_inlineStyle;
+    mutable SpaceSplitString m_classNames;
+    mutable AtomicString m_idForStyleResolution;
+
+private:
+    friend class Element;
+    friend class ShareableElementData;
+    friend class UniqueElementData;
+    friend class SVGElement;
+
+    const Attribute* attributeBase() const;
+    const Attribute* getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
+    size_t getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
+
+    PassRefPtr<UniqueElementData> makeUniqueCopy() const;
+};
+
+#if COMPILER(MSVC)
+#pragma warning(push)
+#pragma warning(disable: 4200) // Disable "zero-sized array in struct/union" warning
+#endif
+
+class ShareableElementData : public ElementData {
+public:
+    static PassRefPtr<ShareableElementData> createWithAttributes(const Vector<Attribute>&);
+
+    explicit ShareableElementData(const Vector<Attribute>&);
+    explicit ShareableElementData(const UniqueElementData&);
+    ~ShareableElementData();
+
+    Attribute m_attributeArray[0];
+};
+
+#if COMPILER(MSVC)
+#pragma warning(pop)
+#endif
+
+class UniqueElementData : public ElementData {
+public:
+    static PassRefPtr<UniqueElementData> create();
+    PassRefPtr<ShareableElementData> makeShareableCopy() const;
+
+    // These functions do no error/duplicate checking.
+    void addAttribute(const QualifiedName&, const AtomicString&);
+    void removeAttribute(size_t index);
+
+    Attribute* attributeItem(unsigned index);
+    Attribute* getAttributeItem(const QualifiedName&);
+
+    UniqueElementData();
+    explicit UniqueElementData(const ShareableElementData&);
+    explicit UniqueElementData(const UniqueElementData&);
+
+    mutable RefPtr<StylePropertySet> m_presentationAttributeStyle;
+    Vector<Attribute, 4> m_attributeVector;
+};
+
+inline size_t ElementData::length() const
+{
+    if (isUnique())
+        return static_cast<const UniqueElementData*>(this)->m_attributeVector.size();
+    return m_arraySize;
+}
+
+inline const StylePropertySet* ElementData::presentationAttributeStyle() const
+{
+    if (!m_isUnique)
+        return 0;
+    return static_cast<const UniqueElementData*>(this)->m_presentationAttributeStyle.get();
+}
+
+inline const Attribute* ElementData::getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const
+{
+    size_t index = getAttributeItemIndex(name, shouldIgnoreAttributeCase);
+    if (index != kNotFound)
+        return attributeItem(index);
+    return 0;
+}
+
+inline const Attribute* ElementData::attributeBase() const
+{
+    if (m_isUnique)
+        return static_cast<const UniqueElementData*>(this)->m_attributeVector.begin();
+    return static_cast<const ShareableElementData*>(this)->m_attributeArray;
+}
+
+inline size_t ElementData::getAttributeItemIndex(const QualifiedName& name, bool shouldIgnoreCase) const
+{
+    const Attribute* begin = attributeBase();
+    for (unsigned i = 0; i < length(); ++i) {
+        const Attribute& attribute = begin[i];
+        if (attribute.name().matchesPossiblyIgnoringCase(name, shouldIgnoreCase))
+            return i;
+    }
+    return kNotFound;
+}
+
+// We use a boolean parameter instead of calling shouldIgnoreAttributeCase so that the caller
+// can tune the behavior (hasAttribute is case sensitive whereas getAttribute is not).
+inline size_t ElementData::getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const
+{
+    unsigned len = length();
+    bool doSlowCheck = shouldIgnoreAttributeCase;
+
+    // Optimize for the case where the attribute exists and its name exactly matches.
+    const Attribute* begin = attributeBase();
+    for (unsigned i = 0; i < len; ++i) {
+        const Attribute& attribute = begin[i];
+        if (!attribute.name().hasPrefix()) {
+            if (name == attribute.localName())
+                return i;
+        } else {
+            doSlowCheck = true;
+        }
+    }
+
+    if (doSlowCheck)
+        return getAttributeItemIndexSlowCase(name, shouldIgnoreAttributeCase);
+    return kNotFound;
+}
+
+inline const Attribute* ElementData::getAttributeItem(const QualifiedName& name) const
+{
+    const Attribute* begin = attributeBase();
+    for (unsigned i = 0; i < length(); ++i) {
+        const Attribute& attribute = begin[i];
+        if (attribute.name().matches(name))
+            return &attribute;
+    }
+    return 0;
+}
+
+inline const Attribute* ElementData::attributeItem(unsigned index) const
+{
+    RELEASE_ASSERT(index < length());
+    return attributeBase() + index;
+}
+
+} // namespace WebCore
+
+#endif // ElementData_h
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index 0608531..d9be4ce 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -271,12 +271,10 @@
 
     InspectorInstrumentation::pseudoElementDestroyed(element);
 
-    if (element->confusingAndOftenMisusedAttached())
-        element->detach();
-
     ASSERT(!element->nextSibling());
     ASSERT(!element->previousSibling());
 
+    element->detach();
     element->document().removeFromTopLayer(element);
     element->setParentOrShadowHostNode(0);
 }
diff --git a/Source/core/dom/ExecutionContext.cpp b/Source/core/dom/ExecutionContext.cpp
index 8f1a50f..321fe69 100644
--- a/Source/core/dom/ExecutionContext.cpp
+++ b/Source/core/dom/ExecutionContext.cpp
@@ -137,7 +137,7 @@
 
 bool ExecutionContext::hasPendingActivity()
 {
-    if (lifecycleNotifier()->hasPendingActivity())
+    if (lifecycleNotifier().hasPendingActivity())
         return true;
 
     HashSet<MessagePort*>::const_iterator messagePortsEnd = m_messagePorts.end();
@@ -151,27 +151,27 @@
 
 void ExecutionContext::suspendActiveDOMObjects()
 {
-    lifecycleNotifier()->notifySuspendingActiveDOMObjects();
+    lifecycleNotifier().notifySuspendingActiveDOMObjects();
     m_activeDOMObjectsAreSuspended = true;
 }
 
 void ExecutionContext::resumeActiveDOMObjects()
 {
     m_activeDOMObjectsAreSuspended = false;
-    lifecycleNotifier()->notifyResumingActiveDOMObjects();
+    lifecycleNotifier().notifyResumingActiveDOMObjects();
 }
 
 void ExecutionContext::stopActiveDOMObjects()
 {
     m_activeDOMObjectsAreStopped = true;
-    lifecycleNotifier()->notifyStoppingActiveDOMObjects();
+    lifecycleNotifier().notifyStoppingActiveDOMObjects();
     // Also close MessagePorts. If they were ActiveDOMObjects (they could be) then they could be stopped instead.
     closeMessagePorts();
 }
 
 void ExecutionContext::suspendActiveDOMObjectIfNeeded(ActiveDOMObject* object)
 {
-    ASSERT(lifecycleNotifier()->contains(object));
+    ASSERT(lifecycleNotifier().contains(object));
     // Ensure all ActiveDOMObjects are suspended also newly created ones.
     if (m_activeDOMObjectsAreSuspended)
         object->suspend();
@@ -294,11 +294,16 @@
         iter->value->didChangeAlignmentInterval();
 }
 
-EventQueue* ExecutionContext::eventQueue() const
+SecurityOrigin* ExecutionContext::securityOrigin() const
 {
-    if (!m_client)
-        return 0;
-    return m_client->eventQueue();
+    RELEASE_ASSERT(m_client);
+    return m_client->securityContext().securityOrigin();
+}
+
+ContentSecurityPolicy* ExecutionContext::contentSecurityPolicy() const
+{
+    RELEASE_ASSERT(m_client);
+    return m_client->securityContext().contentSecurityPolicy();
 }
 
 const KURL& ExecutionContext::url() const
@@ -338,8 +343,7 @@
 
 DOMWindow* ExecutionContext::executingWindow() const
 {
-    if (!m_client)
-        return 0;
+    RELEASE_ASSERT(m_client);
     return m_client->executingWindow();
 }
 
@@ -364,16 +368,14 @@
     m_client->postTask(task);
 }
 
-PassOwnPtr<LifecycleNotifier> ExecutionContext::createLifecycleNotifier()
+PassOwnPtr<LifecycleNotifier<ExecutionContext> > ExecutionContext::createLifecycleNotifier()
 {
-    if (!m_client)
-        return PassOwnPtr<LifecycleNotifier>();
-    return m_client->createLifecycleNotifier();
+    return ContextLifecycleNotifier::create(this);
 }
 
-ContextLifecycleNotifier* ExecutionContext::lifecycleNotifier()
+ContextLifecycleNotifier& ExecutionContext::lifecycleNotifier()
 {
-    return static_cast<ContextLifecycleNotifier*>(LifecycleContext::lifecycleNotifier());
+    return static_cast<ContextLifecycleNotifier&>(LifecycleContext<ExecutionContext>::lifecycleNotifier());
 }
 
 bool ExecutionContext::isIteratingOverObservers() const
@@ -385,9 +387,10 @@
 {
     m_sandboxFlags |= mask;
 
+    RELEASE_ASSERT(m_client);
     // The SandboxOrigin is stored redundantly in the security origin.
-    if (isSandboxed(SandboxOrigin) && securityOrigin() && !securityOrigin()->isUnique()) {
-        setSecurityOrigin(SecurityOrigin::createUnique());
+    if (isSandboxed(SandboxOrigin) && m_client->securityContext().securityOrigin() && !m_client->securityContext().securityOrigin()->isUnique()) {
+        m_client->securityContext().setSecurityOrigin(SecurityOrigin::createUnique());
         m_client->didUpdateSecurityOrigin();
     }
 }
diff --git a/Source/core/dom/ExecutionContext.h b/Source/core/dom/ExecutionContext.h
index b5b7bb9..ac26fdf 100644
--- a/Source/core/dom/ExecutionContext.h
+++ b/Source/core/dom/ExecutionContext.h
@@ -36,7 +36,7 @@
 #include "core/fetch/CrossOriginAccessControl.h"
 #include "core/frame/ConsoleTypes.h"
 #include "core/frame/DOMTimer.h"
-#include "core/platform/LifecycleContext.h"
+#include "platform/LifecycleContext.h"
 #include "weborigin/KURL.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
@@ -56,10 +56,11 @@
 class ExecutionContextTask;
 class MessagePort;
 class PublicURLManager;
+class SecurityOrigin;
 class ScriptCallStack;
 class ScriptState;
 
-class ExecutionContext : public LifecycleContext, public SecurityContext {
+class ExecutionContext : public LifecycleContext<ExecutionContext> {
 public:
     ExecutionContext();
     virtual ~ExecutionContext();
@@ -69,7 +70,8 @@
     bool isDocument() const { return m_client && m_client->isDocument(); }
     bool isWorkerGlobalScope() { return m_client && m_client->isWorkerGlobalScope(); }
     bool isJSExecutionForbidden() { return m_client && m_client->isJSExecutionForbidden(); }
-    EventQueue* eventQueue() const;
+    SecurityOrigin* securityOrigin() const;
+    ContentSecurityPolicy* contentSecurityPolicy() const;
     const KURL& url() const;
     KURL completeURL(const String& url) const;
     void userEventWasHandled();
@@ -120,9 +122,13 @@
     bool isSandboxed(SandboxFlags mask) const { return m_sandboxFlags & mask; }
     void enforceSandboxFlags(SandboxFlags mask);
 
+    PassOwnPtr<LifecycleNotifier<ExecutionContext> > createLifecycleNotifier();
+
+    virtual EventQueue* eventQueue() const = 0;
+
 protected:
 
-    ContextLifecycleNotifier* lifecycleNotifier();
+    ContextLifecycleNotifier& lifecycleNotifier();
 
 private:
     friend class DOMTimer; // For installNewTimeout() and removeTimeoutByID() below.
@@ -133,7 +139,7 @@
 
     virtual void refExecutionContext() = 0;
     virtual void derefExecutionContext() = 0;
-    virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
+    // LifecycleContext implementation.
 
     // Implementation details for DOMTimer. No other classes should call these functions.
     int installNewTimeout(PassOwnPtr<ScheduledAction>, int timeout, bool singleShot);
diff --git a/Source/core/dom/ExecutionContextClient.h b/Source/core/dom/ExecutionContextClient.h
index d27dec9..f9cd303 100644
--- a/Source/core/dom/ExecutionContextClient.h
+++ b/Source/core/dom/ExecutionContextClient.h
@@ -28,7 +28,8 @@
 #define ExecutionContextClient_h
 
 #include "core/frame/ConsoleTypes.h"
-#include "core/platform/LifecycleNotifier.h"
+#include "platform/LifecycleNotifier.h"
+#include "weborigin/KURL.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/text/WTFString.h"
@@ -40,7 +41,7 @@
 class EventTarget;
 class ExecutionContextTask;
 class KURL;
-class LifecycleNotifier;
+template<class T> class LifecycleNotifier;
 class ScriptCallStack;
 class ScriptState;
 class SecurityContext;
@@ -51,25 +52,32 @@
 
     virtual bool isDocument() const { return false; }
     virtual bool isWorkerGlobalScope() const { return false; }
-
     virtual bool isJSExecutionForbidden() const = 0;
     virtual DOMWindow* executingWindow() { return 0; }
     virtual void userEventWasHandled() { }
     virtual String userAgent(const KURL&) const = 0;
     virtual void disableEval(const String& errorMessage) = 0;
-    virtual EventQueue* eventQueue() const = 0;
+    virtual SecurityContext& securityContext() = 0;
     virtual const KURL& virtualURL() const = 0;
     virtual KURL virtualCompleteURL(const String&) const = 0;
     virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*) = 0;
+    virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) = 0;
     virtual EventTarget* errorEventTarget() = 0;
     virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) = 0;
     virtual double timerAlignmentInterval() const = 0;
-    virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() = 0;
     virtual void didUpdateSecurityOrigin() = 0;
+
+    void addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber) { addMessage(source, level, message, sourceURL, lineNumber, 0); }
+    void addConsoleMessage(MessageSource source, MessageLevel level, const String& message, ScriptState* state = 0) { addMessage(source, level, message, String(), 0, state); }
+    KURL contextURL() const { return virtualURL(); }
+    KURL contextCompleteURL(const String& url) const { return virtualCompleteURL(url); }
+
 protected:
     virtual ~ExecutionContextClient() { }
+
 };
 
+
 } // namespace
 
 #endif
diff --git a/Source/core/dom/FullscreenElementStack.cpp b/Source/core/dom/FullscreenElementStack.cpp
index 550bd42..6d0b514 100644
--- a/Source/core/dom/FullscreenElementStack.cpp
+++ b/Source/core/dom/FullscreenElementStack.cpp
@@ -113,7 +113,7 @@
 
 inline Document* FullscreenElementStack::document()
 {
-    return toDocument(executionContext());
+    return lifecycleContext();
 }
 
 void FullscreenElementStack::documentWasDetached()
@@ -171,7 +171,7 @@
 
         // A descendant browsing context's document has a non-empty fullscreen element stack.
         bool descendentHasNonEmptyStack = false;
-        for (Frame* descendant = document()->frame() ? document()->frame()->tree()->traverseNext() : 0; descendant; descendant = descendant->tree()->traverseNext()) {
+        for (Frame* descendant = document()->frame() ? document()->frame()->tree().traverseNext() : 0; descendant; descendant = descendant->tree().traverseNext()) {
             if (fullscreenElementFrom(descendant->document())) {
                 descendentHasNonEmptyStack = true;
                 break;
@@ -285,7 +285,7 @@
     // element stack (if any), ordered so that the child of the doc is last and the document furthest
     // away from the doc is first.
     Deque<RefPtr<Document> > descendants;
-    for (Frame* descendant = document()->frame() ?  document()->frame()->tree()->traverseNext() : 0; descendant; descendant = descendant->tree()->traverseNext()) {
+    for (Frame* descendant = document()->frame() ?  document()->frame()->tree().traverseNext() : 0; descendant; descendant = descendant->tree().traverseNext()) {
         if (fullscreenElementFrom(descendant->document()))
             descendants.prepend(descendant->document());
     }
@@ -353,7 +353,7 @@
 
 void FullscreenElementStack::webkitWillEnterFullScreenForElement(Element* element)
 {
-    if (!document()->confusingAndOftenMisusedAttached())
+    if (!document()->isActive())
         return;
 
     ASSERT(element);
@@ -393,7 +393,7 @@
     if (!m_fullScreenElement)
         return;
 
-    if (!document()->confusingAndOftenMisusedAttached())
+    if (!document()->isActive())
         return;
 
     m_fullScreenElement->didBecomeFullscreenElement();
@@ -406,7 +406,7 @@
     if (!m_fullScreenElement)
         return;
 
-    if (!document()->confusingAndOftenMisusedAttached())
+    if (!document()->isActive())
         return;
 
     m_fullScreenElement->willStopBeingFullscreenElement();
@@ -417,7 +417,7 @@
     if (!m_fullScreenElement)
         return;
 
-    if (!document()->confusingAndOftenMisusedAttached())
+    if (!document()->isActive())
         return;
 
     m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
diff --git a/Source/core/dom/GlobalEventHandlers.h b/Source/core/dom/GlobalEventHandlers.h
index 4df0ef0..8da83b9 100644
--- a/Source/core/dom/GlobalEventHandlers.h
+++ b/Source/core/dom/GlobalEventHandlers.h
@@ -30,9 +30,68 @@
 #ifndef GlobalEventHandlers_h
 #define GlobalEventHandlers_h
 
+#include "core/events/EventTarget.h"
+
 namespace WebCore {
 
 namespace GlobalEventHandlers {
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(abort);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(blur);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cancel);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canplay);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canplaythrough);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(change);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(click);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(close);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(contextmenu);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cuechange);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dblclick);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(drag);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragend);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragenter);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragleave);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragover);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragstart);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(drop);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(durationchange);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(emptied);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(ended);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(error);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(focus);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(input);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(invalid);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keydown);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keypress);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keyup);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(load);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadeddata);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadedmetadata);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadstart);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousedown);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseenter);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseleave);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousemove);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseout);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseover);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseup);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousewheel);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pause);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(play);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(playing);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(progress);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(ratechange);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(reset);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(scroll);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeked);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeking);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(select);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(show);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(stalled);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(submit);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(suspend);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(timeupdate);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(volumechange);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(waiting);
 }
 
 } // namespace
diff --git a/Source/core/dom/MutationObserverInterestGroup.cpp b/Source/core/dom/MutationObserverInterestGroup.cpp
index 7169bb2..48cd761 100644
--- a/Source/core/dom/MutationObserverInterestGroup.cpp
+++ b/Source/core/dom/MutationObserverInterestGroup.cpp
@@ -38,11 +38,11 @@
 
 namespace WebCore {
 
-PassOwnPtr<MutationObserverInterestGroup> MutationObserverInterestGroup::createIfNeeded(Node* target, MutationObserver::MutationType type, MutationRecordDeliveryOptions oldValueFlag, const QualifiedName* attributeName)
+PassOwnPtr<MutationObserverInterestGroup> MutationObserverInterestGroup::createIfNeeded(Node& target, MutationObserver::MutationType type, MutationRecordDeliveryOptions oldValueFlag, const QualifiedName* attributeName)
 {
     ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
     HashMap<MutationObserver*, MutationRecordDeliveryOptions> observers;
-    target->getRegisteredMutationObserversOfType(observers, type, attributeName);
+    target.getRegisteredMutationObserversOfType(observers, type, attributeName);
     if (observers.isEmpty())
         return nullptr;
 
diff --git a/Source/core/dom/MutationObserverInterestGroup.h b/Source/core/dom/MutationObserverInterestGroup.h
index 4950f31..b149afc 100644
--- a/Source/core/dom/MutationObserverInterestGroup.h
+++ b/Source/core/dom/MutationObserverInterestGroup.h
@@ -42,26 +42,26 @@
 
 class MutationObserverInterestGroup {
 public:
-    static PassOwnPtr<MutationObserverInterestGroup> createForChildListMutation(Node* target)
+    static PassOwnPtr<MutationObserverInterestGroup> createForChildListMutation(Node& target)
     {
-        if (!target->document().hasMutationObserversOfType(MutationObserver::ChildList))
+        if (!target.document().hasMutationObserversOfType(MutationObserver::ChildList))
             return nullptr;
 
         MutationRecordDeliveryOptions oldValueFlag = 0;
         return createIfNeeded(target, MutationObserver::ChildList, oldValueFlag);
     }
 
-    static PassOwnPtr<MutationObserverInterestGroup> createForCharacterDataMutation(Node* target)
+    static PassOwnPtr<MutationObserverInterestGroup> createForCharacterDataMutation(Node& target)
     {
-        if (!target->document().hasMutationObserversOfType(MutationObserver::CharacterData))
+        if (!target.document().hasMutationObserversOfType(MutationObserver::CharacterData))
             return nullptr;
 
         return createIfNeeded(target, MutationObserver::CharacterData, MutationObserver::CharacterDataOldValue);
     }
 
-    static PassOwnPtr<MutationObserverInterestGroup> createForAttributesMutation(Node* target, const QualifiedName& attributeName)
+    static PassOwnPtr<MutationObserverInterestGroup> createForAttributesMutation(Node& target, const QualifiedName& attributeName)
     {
-        if (!target->document().hasMutationObserversOfType(MutationObserver::Attributes))
+        if (!target.document().hasMutationObserversOfType(MutationObserver::Attributes))
             return nullptr;
 
         return createIfNeeded(target, MutationObserver::Attributes, MutationObserver::AttributeOldValue, &attributeName);
@@ -71,7 +71,7 @@
     void enqueueMutationRecord(PassRefPtr<MutationRecord>);
 
 private:
-    static PassOwnPtr<MutationObserverInterestGroup> createIfNeeded(Node* target, MutationObserver::MutationType, MutationRecordDeliveryOptions oldValueFlag, const QualifiedName* attributeName = 0);
+    static PassOwnPtr<MutationObserverInterestGroup> createIfNeeded(Node& target, MutationObserver::MutationType, MutationRecordDeliveryOptions oldValueFlag, const QualifiedName* attributeName = 0);
     MutationObserverInterestGroup(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, MutationRecordDeliveryOptions oldValueFlag);
 
     bool hasOldValue(MutationRecordDeliveryOptions options) { return options & m_oldValueFlag; }
diff --git a/Source/core/dom/NamedFlowCollection.cpp b/Source/core/dom/NamedFlowCollection.cpp
index 49a975c..b9ae4b3 100644
--- a/Source/core/dom/NamedFlowCollection.cpp
+++ b/Source/core/dom/NamedFlowCollection.cpp
@@ -41,7 +41,7 @@
 namespace WebCore {
 
 NamedFlowCollection::NamedFlowCollection(Document* document)
-    : ContextLifecycleObserver(document)
+    : DocumentLifecycleObserver(document)
 {
     ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
 }
@@ -103,8 +103,7 @@
 
 Document* NamedFlowCollection::document() const
 {
-    ExecutionContext* context = ContextLifecycleObserver::executionContext();
-    return toDocument(context);
+    return lifecycleContext();
 }
 
 PassRefPtr<DOMNamedFlowCollection> NamedFlowCollection::createCSSOMSnapshot()
diff --git a/Source/core/dom/NamedFlowCollection.h b/Source/core/dom/NamedFlowCollection.h
index 8d8d32c..f9c4b9c 100644
--- a/Source/core/dom/NamedFlowCollection.h
+++ b/Source/core/dom/NamedFlowCollection.h
@@ -30,7 +30,7 @@
 #ifndef NamedFlowCollection_h
 #define NamedFlowCollection_h
 
-#include "core/dom/ContextLifecycleObserver.h"
+#include "core/dom/DocumentLifecycleObserver.h"
 #include "core/dom/NamedFlow.h"
 #include "wtf/Forward.h"
 #include "wtf/ListHashSet.h"
@@ -43,7 +43,7 @@
 class Document;
 class DOMNamedFlowCollection;
 
-class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public ContextLifecycleObserver {
+class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public DocumentLifecycleObserver {
 public:
     static PassRefPtr<NamedFlowCollection> create(Document* doc) { return adoptRef(new NamedFlowCollection(doc)); }
 
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 9059929..89f80b5 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -48,6 +48,7 @@
 #include "core/dom/NodeRareData.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/TemplateContentDocumentFragment.h"
@@ -292,10 +293,8 @@
 
     RELEASE_ASSERT(!renderer());
 
-    if (!isContainerNode()) {
-        if (Document* document = documentInternal())
-            willBeDeletedFrom(document);
-    }
+    if (!isContainerNode())
+        willBeDeletedFromDocument();
 
     if (m_previous)
         m_previous->setNextSibling(0);
@@ -307,18 +306,19 @@
     InspectorCounters::decrementCounter(InspectorCounters::NodeCounter);
 }
 
-void Node::willBeDeletedFrom(Document* document)
+void Node::willBeDeletedFromDocument()
 {
+    Document* document = documentInternal();
+    if (!document)
+        return;
+
     if (hasEventTargetData()) {
-        if (document)
-            document->didRemoveEventTargetNode(this);
+        document->didRemoveEventTargetNode(this);
         clearEventTargetData();
     }
 
-    if (document) {
-        if (AXObjectCache* cache = document->existingAXObjectCache())
-            cache->remove(this);
-    }
+    if (AXObjectCache* cache = document->existingAXObjectCache())
+        cache->remove(this);
 }
 
 NodeRareData* Node::rareData() const
@@ -380,7 +380,7 @@
 
 PassRefPtr<NodeList> Node::childNodes()
 {
-    return ensureRareData().ensureNodeLists()->ensureChildNodeList(this);
+    return ensureRareData().ensureNodeLists().ensureChildNodeList(this);
 }
 
 Node *Node::lastDescendant() const
@@ -504,13 +504,13 @@
     while (node) {
         NodeType type = node->nodeType();
         if (type == ELEMENT_NODE)
-            toElement(node.get())->normalizeAttributes();
+            toElement(node)->normalizeAttributes();
 
         if (node == this)
             break;
 
         if (type == TEXT_NODE)
-            node = toText(node.get())->mergeNextSiblingNodesIfPossible();
+            node = toText(node)->mergeNextSiblingNodesIfPossible();
         else
             node = NodeTraversal::nextPostOrder(node.get());
     }
@@ -734,6 +734,11 @@
         markAncestorsWithChildNeedsStyleRecalc();
 }
 
+bool Node::inActiveDocument() const
+{
+    return inDocument() && document().isActive();
+}
+
 void Node::lazyAttach()
 {
     markAncestorsWithChildNeedsStyleRecalc();
@@ -1203,8 +1208,8 @@
         return 0;
 
     if (document().isHTMLDocument())
-        return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<HTMLTagNodeList>(this, HTMLTagNodeListType, localName);
-    return ensureRareData().ensureNodeLists()->addCacheWithAtomicName<TagNodeList>(this, TagNodeListType, localName);
+        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)
@@ -1215,23 +1220,23 @@
     if (namespaceURI == starAtom)
         return getElementsByTagName(localName);
 
-    return ensureRareData().ensureNodeLists()->addCacheWithQualifiedName(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, 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);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<NameNodeList>(this, NameNodeListType, elementName);
 }
 
 PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
 {
-    return ensureRareData().ensureNodeLists()->addCacheWithName<ClassNodeList>(this, ClassNodeListType, 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);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<RadioNodeList>(this, RadioNodeListType, name);
 }
 
 PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionState& es)
@@ -1241,7 +1246,7 @@
         return 0;
     }
 
-    SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selectors, document(), es);
+    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), es);
     if (!selectorQuery)
         return 0;
     return selectorQuery->queryFirst(this);
@@ -1254,7 +1259,7 @@
         return 0;
     }
 
-    SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selectors, document(), es);
+    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), es);
     if (!selectorQuery)
         return 0;
     return selectorQuery->queryAll(this);
@@ -1559,7 +1564,7 @@
         case ENTITY_NODE:
         case DOCUMENT_FRAGMENT_NODE: {
             RefPtr<ContainerNode> container = toContainerNode(this);
-            ChildListMutationScope mutation(this);
+            ChildListMutationScope mutation(*this);
             container->removeChildren();
             if (!text.isEmpty())
                 container->appendChild(document().createTextNode(text), es);
@@ -2160,7 +2165,7 @@
 void Node::registerMutationObserver(MutationObserver* observer, MutationObserverOptions options, const HashSet<AtomicString>& attributeFilter)
 {
     MutationObserverRegistration* registration = 0;
-    Vector<OwnPtr<MutationObserverRegistration> >& registry = ensureRareData().ensureMutationObserverData()->registry;
+    Vector<OwnPtr<MutationObserverRegistration> >& registry = ensureRareData().ensureMutationObserverData().registry;
     for (size_t i = 0; i < registry.size(); ++i) {
         if (registry[i]->observer() == observer) {
             registration = registry[i].get();
@@ -2197,7 +2202,7 @@
 
 void Node::registerTransientMutationObserver(MutationObserverRegistration* registration)
 {
-    ensureRareData().ensureMutationObserverData()->transientRegistry.add(registration);
+    ensureRareData().ensureMutationObserverData().transientRegistry.add(registration);
 }
 
 void Node::unregisterTransientMutationObserver(MutationObserverRegistration* registration)
@@ -2254,9 +2259,9 @@
 bool Node::dispatchEvent(PassRefPtr<Event> event)
 {
     if (event->isMouseEvent())
-        return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(adoptRef(toMouseEvent(event.leakRef())), MouseEventDispatchMediator::SyntheticMouseEvent));
+        return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(static_pointer_cast<MouseEvent>(event), MouseEventDispatchMediator::SyntheticMouseEvent));
     if (event->isTouchEvent())
-        return dispatchTouchEvent(adoptRef(toTouchEvent(event.leakRef())));
+        return dispatchTouchEvent(static_pointer_cast<TouchEvent>(event));
     return EventDispatcher::dispatchEvent(this, EventDispatchMediator::create(event));
 }
 
@@ -2345,7 +2350,7 @@
     if (eventType == EventTypeNames::keydown || eventType == EventTypeNames::keypress) {
         if (event->isKeyboardEvent()) {
             if (Frame* frame = document().frame())
-                frame->eventHandler()->defaultKeyboardEventHandler(toKeyboardEvent(event));
+                frame->eventHandler().defaultKeyboardEventHandler(toKeyboardEvent(event));
         }
     } else if (eventType == EventTypeNames::click) {
         int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
@@ -2357,7 +2362,7 @@
     } else if (eventType == EventTypeNames::textInput) {
         if (event->hasInterface(EventNames::TextEvent)) {
             if (Frame* frame = document().frame())
-                frame->eventHandler()->defaultTextInputEventHandler(toTextEvent(event));
+                frame->eventHandler().defaultTextInputEventHandler(toTextEvent(event));
         }
 #if OS(WIN)
     } else if (eventType == EventTypeNames::mousedown && event->isMouseEvent()) {
@@ -2372,7 +2377,7 @@
 
             if (renderer) {
                 if (Frame* frame = document().frame())
-                    frame->eventHandler()->startPanScrolling(renderer);
+                    frame->eventHandler().startPanScrolling(renderer);
             }
         }
 #endif
@@ -2385,9 +2390,10 @@
         while (startNode && !startNode->renderer())
             startNode = startNode->parentOrShadowHostNode();
 
-        if (startNode && startNode->renderer())
+        if (startNode && startNode->renderer()) {
             if (Frame* frame = document().frame())
-                frame->eventHandler()->defaultWheelEventHandler(startNode, wheelEvent);
+                frame->eventHandler().defaultWheelEventHandler(startNode, wheelEvent);
+        }
     } else if (event->type() == EventTypeNames::webkitEditableContentChanged) {
         dispatchInputEvent();
     }
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index 068334d..1fe0467 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -163,7 +163,6 @@
     static void dumpStatistics();
 
     virtual ~Node();
-    void willBeDeletedFrom(Document*);
 
     // DOM methods & attributes for Node
 
@@ -408,7 +407,6 @@
     void setV8CollectableDuringMinorGC(bool flag) { setFlag(flag, V8CollectableDuringMinorGCFlag); }
 
     void lazyAttach();
-    void lazyReattach();
 
     virtual void setFocus(bool flag);
     virtual void setActive(bool flag = true, bool pause = false);
@@ -482,6 +480,8 @@
 
     TreeScope& treeScope() const { return *m_treeScope; }
 
+    bool inActiveDocument() const;
+
     // Returns true if this node is associated with a document and is in its associated document's
     // node tree, false otherwise.
     bool inDocument() const
@@ -792,6 +792,8 @@
 
     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const { }
 
+    void willBeDeletedFromDocument();
+
     bool hasRareData() const { return getFlag(HasRareDataFlag); }
 
     NodeRareData* rareData() const;
@@ -896,20 +898,15 @@
 
 inline void Node::lazyReattachIfAttached()
 {
-    if (confusingAndOftenMisusedAttached())
-        lazyReattach();
-}
-
-inline void Node::lazyReattach()
-{
     if (styleChangeType() == NeedsReattachStyleChange)
         return;
+    if (!inActiveDocument())
+        return;
 
     AttachContext context;
     context.performingReattach = true;
 
-    if (confusingAndOftenMisusedAttached())
-        detach(context);
+    detach(context);
     lazyAttach();
 }
 
@@ -932,8 +929,14 @@
 
 
 #define DEFINE_NODE_TYPE_CASTS(thisType, predicate) \
+    template<typename T> inline thisType* to##thisType(const RefPtr<T>& node) { return to##thisType(node.get()); } \
     DEFINE_TYPE_CASTS(thisType, Node, node, node->predicate, node.predicate)
 
+// This requires isClassName(const Node&).
+#define DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(thisType) \
+    template<typename T> inline thisType* to##thisType(const RefPtr<T>& node) { return to##thisType(node.get()); } \
+    DEFINE_TYPE_CASTS(thisType, Node, node, is##thisType(*node), is##thisType(node))
+
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/dom/NodeRareData.h b/Source/core/dom/NodeRareData.h
index 120a15b..8d310c3 100644
--- a/Source/core/dom/NodeRareData.h
+++ b/Source/core/dom/NodeRareData.h
@@ -249,19 +249,19 @@
 
     void clearNodeLists() { m_nodeLists.clear(); }
     NodeListsNodeData* nodeLists() const { return m_nodeLists.get(); }
-    NodeListsNodeData* ensureNodeLists()
+    NodeListsNodeData& ensureNodeLists()
     {
         if (!m_nodeLists)
             m_nodeLists = NodeListsNodeData::create();
-        return m_nodeLists.get();
+        return *m_nodeLists;
     }
 
     NodeMutationObserverData* mutationObserverData() { return m_mutationObserverData.get(); }
-    NodeMutationObserverData* ensureMutationObserverData()
+    NodeMutationObserverData& ensureMutationObserverData()
     {
         if (!m_mutationObserverData)
             m_mutationObserverData = NodeMutationObserverData::create();
-        return m_mutationObserverData.get();
+        return *m_mutationObserverData;
     }
 
     unsigned connectedSubframeCount() const { return m_connectedFrameCount; }
diff --git a/Source/core/dom/Position.cpp b/Source/core/dom/Position.cpp
index 75d8070..4ceb136 100644
--- a/Source/core/dom/Position.cpp
+++ b/Source/core/dom/Position.cpp
@@ -161,7 +161,7 @@
 {
     switch (anchorType()) {
     case PositionIsOffsetInAnchor:
-        return m_anchorNode && m_anchorNode->isTextNode() ? toText(m_anchorNode.get()) : 0;
+        return m_anchorNode && m_anchorNode->isTextNode() ? toText(m_anchorNode) : 0;
     case PositionIsBeforeAnchor:
     case PositionIsAfterAnchor:
         return 0;
diff --git a/Source/core/dom/PresentationAttributeStyle.cpp b/Source/core/dom/PresentationAttributeStyle.cpp
index 8bc83cc..8adfd77 100644
--- a/Source/core/dom/PresentationAttributeStyle.cpp
+++ b/Source/core/dom/PresentationAttributeStyle.cpp
@@ -177,7 +177,7 @@
         style = cacheIterator->value->value;
         cacheCleaner.didHitPresentationAttributeCache();
     } else {
-        style = MutableStylePropertySet::create(element.isSVGElement() ? SVGAttributeMode : CSSAttributeMode);
+        style = MutableStylePropertySet::create(element.isSVGElement() ? SVGAttributeMode : HTMLAttributeMode);
         unsigned size = element.attributeCount();
         for (unsigned i = 0; i < size; ++i) {
             const Attribute* attribute = element.attributeItem(i);
diff --git a/Source/core/dom/Promise.idl b/Source/core/dom/Promise.idl
index 41f5d9f..77b3976 100644
--- a/Source/core/dom/Promise.idl
+++ b/Source/core/dom/Promise.idl
@@ -33,7 +33,6 @@
 [
    GlobalContext=Window&WorkerGlobalScope,
    CustomConstructor(PromiseInit init),
-   RuntimeEnabled=Promise
 ] interface Promise {
    [Custom] Promise then(optional AnyCallback fulfillCallback, optional AnyCallback rejectCallback);
    [Custom] Promise catch(optional AnyCallback rejectCallback);
diff --git a/Source/core/dom/QualifiedName.cpp b/Source/core/dom/QualifiedName.cpp
index b2e9369..21e97ae 100644
--- a/Source/core/dom/QualifiedName.cpp
+++ b/Source/core/dom/QualifiedName.cpp
@@ -45,7 +45,7 @@
     + XMLNames::XMLAttrsCount;
 
 struct QualifiedNameHashTraits : public HashTraits<QualifiedName::QualifiedNameImpl*> {
-    static const int minimumTableSize = WTF::HashTableCapacityForSize<staticQualifiedNamesCount>::value;
+    static const unsigned minimumTableSize = WTF::HashTableCapacityForSize<staticQualifiedNamesCount>::value;
 };
 
 typedef HashSet<QualifiedName::QualifiedNameImpl*, QualifiedNameHash, QualifiedNameHashTraits> QualifiedNameCache;
diff --git a/Source/core/dom/Range.cpp b/Source/core/dom/Range.cpp
index f7bb066..74a0ca9 100644
--- a/Source/core/dom/Range.cpp
+++ b/Source/core/dom/Range.cpp
@@ -304,7 +304,7 @@
         return false;
     }
 
-    if (!refNode->confusingAndOftenMisusedAttached() || refNode->document() != m_ownerDocument) {
+    if (!refNode->inActiveDocument() || refNode->document() != m_ownerDocument) {
         return false;
     }
 
@@ -332,7 +332,7 @@
         return 0;
     }
 
-    if (!refNode->confusingAndOftenMisusedAttached() || refNode->document() != m_ownerDocument) {
+    if (!refNode->inActiveDocument() || refNode->document() != m_ownerDocument) {
         es.throwUninformativeAndGenericDOMException(WrongDocumentError);
         return 0;
     }
@@ -367,12 +367,12 @@
         return NODE_BEFORE;
     }
 
-    if (!m_start.container() && refNode->confusingAndOftenMisusedAttached()) {
+    if (!m_start.container() && refNode->inActiveDocument()) {
         es.throwUninformativeAndGenericDOMException(InvalidStateError);
         return NODE_BEFORE;
     }
 
-    if (m_start.container() && !refNode->confusingAndOftenMisusedAttached()) {
+    if (m_start.container() && !refNode->inActiveDocument()) {
         // Firefox doesn't throw an exception for this case; it returns 0.
         return NODE_BEFORE;
     }
@@ -581,7 +581,7 @@
         return false;
     }
 
-    if (!refNode->confusingAndOftenMisusedAttached() || refNode->document() != m_ownerDocument) {
+    if (!refNode->inActiveDocument() || refNode->document() != m_ownerDocument) {
         // Firefox doesn't throw an exception for these cases; it returns false.
         return false;
     }
@@ -1025,7 +1025,7 @@
     RefPtr<Node> container;
     if (startIsText) {
         container = m_start.container();
-        RefPtr<Text> newText = toText(container.get())->splitText(m_start.offset(), es);
+        RefPtr<Text> newText = toText(container)->splitText(m_start.offset(), es);
         if (es.hadException())
             return;
 
@@ -1108,7 +1108,7 @@
 
     Node* element = m_start.container()->isElementNode() ? m_start.container() : m_start.container()->parentNode();
     if (!element || !element->isHTMLElement()) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range's container must be an HTML element."));
         return 0;
     }
 
@@ -1442,7 +1442,7 @@
     }
 
     while (Node* n = newParent->firstChild()) {
-        toContainerNode(newParent.get())->removeChild(n, es);
+        toContainerNode(newParent)->removeChild(n, es);
         if (es.hadException())
             return;
     }
diff --git a/Source/core/dom/RawDataDocumentParser.h b/Source/core/dom/RawDataDocumentParser.h
index b56a694..343842d 100644
--- a/Source/core/dom/RawDataDocumentParser.h
+++ b/Source/core/dom/RawDataDocumentParser.h
@@ -54,8 +54,6 @@
 
     virtual void insert(const SegmentedString&)
     {
-        // <https://bugs.webkit.org/show_bug.cgi?id=25397>: JS code can always call document.write, we need to handle it.
-        ASSERT_NOT_REACHED();
     }
 
     virtual void append(PassRefPtr<StringImpl>)
diff --git a/Source/core/dom/ScriptLoader.cpp b/Source/core/dom/ScriptLoader.cpp
index 7af7738..d90456f 100644
--- a/Source/core/dom/ScriptLoader.cpp
+++ b/Source/core/dom/ScriptLoader.cpp
@@ -308,7 +308,7 @@
 
     Frame* frame = contextDocument->frame();
 
-    bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script()->shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr));
+    bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source());
 
     if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber)))
         return;
@@ -331,7 +331,7 @@
         // Create a script from the script element node, using the script
         // block's source and the script block's type.
         // Note: This is where the script is compiled and actually executed.
-        frame->script()->executeScriptInMainWorld(sourceCode, corsCheck);
+        frame->script().executeScriptInMainWorld(sourceCode, corsCheck);
 
         if (isHTMLScriptLoader(m_element)) {
             ASSERT(contextDocument->currentScript() == m_element);
diff --git a/Source/core/dom/StyleEngine.cpp b/Source/core/dom/StyleEngine.cpp
index 25f0337..7c908b9 100644
--- a/Source/core/dom/StyleEngine.cpp
+++ b/Source/core/dom/StyleEngine.cpp
@@ -57,13 +57,14 @@
     , m_pendingStylesheets(0)
     , m_injectedStyleSheetCacheValid(false)
     , m_needsUpdateActiveStylesheetsOnStyleRecalc(false)
+    , m_documentStyleSheetCollection(document)
+    , m_needsDocumentStyleSheetsUpdate(true)
     , m_usesSiblingRules(false)
     , m_usesSiblingRulesOverride(false)
     , m_usesFirstLineRules(false)
     , m_usesFirstLetterRules(false)
     , m_usesRemUnits(false)
-    , m_documentStyleSheetCollection(document)
-    , m_needsDocumentStyleSheetsUpdate(true)
+    , m_maxDirectAdjacentSelectors(0)
 {
 }
 
@@ -159,12 +160,14 @@
     // 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).
     m_usesSiblingRules = m_usesSiblingRules || features.usesSiblingRules();
     m_usesFirstLineRules = m_usesFirstLineRules || features.usesFirstLineRules();
+    m_maxDirectAdjacentSelectors = max(m_maxDirectAdjacentSelectors, features.maxDirectAdjacentSelectors());
 }
 
 void StyleEngine::resetCSSFeatureFlags(const RuleFeatureSet& features)
 {
     m_usesSiblingRules = features.usesSiblingRules();
     m_usesFirstLineRules = features.usesFirstLineRules();
+    m_maxDirectAdjacentSelectors = features.maxDirectAdjacentSelectors();
 }
 
 CSSStyleSheet* StyleEngine::pageUserSheet()
diff --git a/Source/core/dom/StyleEngine.h b/Source/core/dom/StyleEngine.h
index b7bfd78..0df22e4 100644
--- a/Source/core/dom/StyleEngine.h
+++ b/Source/core/dom/StyleEngine.h
@@ -94,6 +94,7 @@
 
     bool hasPendingSheets() const { return m_pendingStylesheets > 0; }
 
+    unsigned maxDirectAdjacentSelectors() const { return m_maxDirectAdjacentSelectors; }
     bool usesSiblingRules() const { return m_usesSiblingRules || m_usesSiblingRulesOverride; }
     void setUsesSiblingRulesOverride(bool b) { m_usesSiblingRulesOverride = b; }
     bool usesFirstLineRules() const { return m_usesFirstLineRules; }
@@ -155,6 +156,7 @@
     bool m_usesFirstLineRules;
     bool m_usesFirstLetterRules;
     bool m_usesRemUnits;
+    unsigned m_maxDirectAdjacentSelectors;
 };
 
 }
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index eab7ece..2d5d6d3 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -332,11 +332,11 @@
 
 void Text::updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, RecalcStyleBehavior recalcStyleBehavior)
 {
-    if (!confusingAndOftenMisusedAttached())
+    if (!inActiveDocument())
         return;
     RenderText* textRenderer = toRenderText(renderer());
     if (!textRenderer || !textRendererIsNeeded(NodeRenderingContext(this, textRenderer->style()))) {
-        lazyReattach();
+        lazyReattachIfAttached();
         // FIXME: Editing should be updated so this is not neccesary.
         if (recalcStyleBehavior == DeprecatedRecalcStyleImmediatlelyForEditing)
             document().updateStyleIfNeeded();
diff --git a/Source/core/dom/TextLinkColors.h b/Source/core/dom/TextLinkColors.h
index 6d2728c..a03a1b8 100644
--- a/Source/core/dom/TextLinkColors.h
+++ b/Source/core/dom/TextLinkColors.h
@@ -28,7 +28,7 @@
 #ifndef TextLinkColors_h
 #define TextLinkColors_h
 
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/Noncopyable.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/TouchController.cpp b/Source/core/dom/TouchController.cpp
index ef6b65f..a24bc81 100644
--- a/Source/core/dom/TouchController.cpp
+++ b/Source/core/dom/TouchController.cpp
@@ -97,7 +97,7 @@
         scrollingCoordinator->touchEventTargetRectsDidChange(document);
     if (m_touchEventTargets->size())
         return;
-    for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
         if (frame->document() && TouchController::from(frame->document())->hasTouchEventHandlers())
             return;
     }
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index 9fea036..8c11f4d 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -333,21 +333,20 @@
     return !rootNode()->isShadowRoot() || toShadowRoot(rootNode())->applyAuthorStyles();
 }
 
-void TreeScope::adoptIfNeeded(Node* node)
+void TreeScope::adoptIfNeeded(Node& node)
 {
     ASSERT(this);
-    ASSERT(node);
-    ASSERT(!node->isDocumentNode());
-    ASSERT_WITH_SECURITY_IMPLICATION(!node->m_deletionHasBegun);
-    TreeScopeAdopter adopter(node, this);
+    ASSERT(!node.isDocumentNode());
+    ASSERT_WITH_SECURITY_IMPLICATION(!node.m_deletionHasBegun);
+    TreeScopeAdopter adopter(node, *this);
     if (adopter.needsScopeChange())
         adopter.execute();
 }
 
 static Element* focusedFrameOwnerElement(Frame* focusedFrame, Frame* currentFrame)
 {
-    for (; focusedFrame; focusedFrame = focusedFrame->tree()->parent()) {
-        if (focusedFrame->tree()->parent() == currentFrame)
+    for (; focusedFrame; focusedFrame = focusedFrame->tree().parent()) {
+        if (focusedFrame->tree().parent() == currentFrame)
             return focusedFrame->ownerElement();
     }
     return 0;
@@ -487,7 +486,7 @@
     Element* result = 0;
     Node* root = rootNode();
     for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(element, root)) {
-        if (element->fastGetAttribute(accesskeyAttr) == key)
+        if (equalIgnoringCase(element->fastGetAttribute(accesskeyAttr), key))
             result = element;
         for (ShadowRoot* shadowRoot = element->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
             if (Element* shadowResult = shadowRoot->getElementByAccessKey(key))
diff --git a/Source/core/dom/TreeScope.h b/Source/core/dom/TreeScope.h
index 74798c7..664db15 100644
--- a/Source/core/dom/TreeScope.h
+++ b/Source/core/dom/TreeScope.h
@@ -90,7 +90,7 @@
     bool applyAuthorStyles() const;
 
     // Used by the basic DOM mutation methods (e.g., appendChild()).
-    void adoptIfNeeded(Node*);
+    void adoptIfNeeded(Node&);
 
     Node* rootNode() const { return m_rootNode; }
 
diff --git a/Source/core/dom/TreeScopeAdopter.cpp b/Source/core/dom/TreeScopeAdopter.cpp
index 309a0e5..6561b09 100644
--- a/Source/core/dom/TreeScopeAdopter.cpp
+++ b/Source/core/dom/TreeScopeAdopter.cpp
@@ -34,28 +34,28 @@
 
 namespace WebCore {
 
-void TreeScopeAdopter::moveTreeToNewScope(Node* root) const
+void TreeScopeAdopter::moveTreeToNewScope(Node& root) const
 {
     ASSERT(needsScopeChange());
 
-    m_oldScope->guardRef();
+    m_oldScope.guardRef();
 
     // If an element is moved from a document and then eventually back again the collection cache for
     // 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();
+    Document* oldDocument = m_oldScope.documentScope();
     ASSERT(oldDocument);
-    Document* newDocument = m_newScope->documentScope();
+    Document* newDocument = m_newScope.documentScope();
     bool willMoveToNewDocument = oldDocument != newDocument;
     if (willMoveToNewDocument)
         oldDocument->incDOMTreeVersion();
 
-    for (Node* node = root; node; node = NodeTraversal::next(node, root)) {
-        updateTreeScope(node);
+    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())
@@ -68,25 +68,25 @@
         if (node->hasSyntheticAttrChildNodes()) {
             const Vector<RefPtr<Attr> >& attrs = toElement(node)->attrNodeList();
             for (unsigned i = 0; i < attrs.size(); ++i)
-                moveTreeToNewScope(attrs[i].get());
+                moveTreeToNewScope(*attrs[i]);
         }
 
         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();
+    m_oldScope.guardDeref();
 }
 
-void TreeScopeAdopter::moveTreeToNewDocument(Node* root, Document* oldDocument, Document* newDocument) const
+void TreeScopeAdopter::moveTreeToNewDocument(Node& root, Document& oldDocument, Document* newDocument) const
 {
-    for (Node* node = root; node; node = NodeTraversal::next(node, root)) {
-        moveNodeToNewDocument(node, 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())
-            moveTreeToNewDocument(shadow, oldDocument, newDocument);
+            moveTreeToNewDocument(*shadow, oldDocument, newDocument);
     }
 }
 
@@ -102,37 +102,36 @@
 }
 #endif
 
-inline void TreeScopeAdopter::updateTreeScope(Node* node) const
+inline void TreeScopeAdopter::updateTreeScope(Node& node) const
 {
-    ASSERT(!node->isTreeScope());
-    ASSERT(node->treeScope() == m_oldScope);
-    m_newScope->guardRef();
-    m_oldScope->guardDeref();
-    node->setTreeScope(m_newScope);
+    ASSERT(!node.isTreeScope());
+    ASSERT(node.treeScope() == m_oldScope);
+    m_newScope.guardRef();
+    m_oldScope.guardDeref();
+    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);
+    ASSERT(!node.inDocument() || oldDocument != newDocument);
 
-    if (node->hasRareData()) {
-        NodeRareData* rareData = node->rareData();
+    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);
+    if (node.isShadowRoot())
+        toShadowRoot(node).setDocumentScope(newDocument);
 
 #ifndef NDEBUG
     didMoveToNewDocumentWasCalled = false;
-    oldDocumentDidMoveToNewDocumentWasCalledWith = oldDocument;
+    oldDocumentDidMoveToNewDocumentWasCalledWith = &oldDocument;
 #endif
 
-    node->didMoveToNewDocument(*oldDocument);
+    node.didMoveToNewDocument(oldDocument);
     ASSERT(didMoveToNewDocumentWasCalled);
 }
 
diff --git a/Source/core/dom/TreeScopeAdopter.h b/Source/core/dom/TreeScopeAdopter.h
index a83d178..17742ba 100644
--- a/Source/core/dom/TreeScopeAdopter.h
+++ b/Source/core/dom/TreeScopeAdopter.h
@@ -33,7 +33,7 @@
 
 class TreeScopeAdopter {
 public:
-    explicit TreeScopeAdopter(Node* toAdopt, TreeScope* newScope);
+    TreeScopeAdopter(Node& toAdopt, TreeScope& newScope);
 
     void execute() const { moveTreeToNewScope(m_toAdopt); }
     bool needsScopeChange() const { return m_oldScope != m_newScope; }
@@ -45,23 +45,21 @@
 #endif
 
 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 updateTreeScope(Node&) const;
+    void moveTreeToNewScope(Node&) const;
+    void moveTreeToNewDocument(Node&, Document& oldDocument, Document* newDocument) const;
+    void moveNodeToNewDocument(Node&, Document& oldDocument, Document* newDocument) const;
 
-    Node* m_toAdopt;
-    TreeScope* m_newScope;
-    TreeScope* m_oldScope;
+    Node& m_toAdopt;
+    TreeScope& m_newScope;
+    TreeScope& m_oldScope;
 };
 
-// FIXME: Should take |TreeScope&| instead of |TreeScope*|.
-inline TreeScopeAdopter::TreeScopeAdopter(Node* toAdopt, TreeScope* newScope)
+inline TreeScopeAdopter::TreeScopeAdopter(Node& toAdopt, TreeScope& newScope)
     : m_toAdopt(toAdopt)
     , m_newScope(newScope)
-    , m_oldScope(&toAdopt->treeScope())
+    , m_oldScope(toAdopt.treeScope())
 {
-    ASSERT(newScope);
 }
 
 }
diff --git a/Source/core/dom/ViewportDescription.cpp b/Source/core/dom/ViewportDescription.cpp
index 80a7e78..77f924e 100644
--- a/Source/core/dom/ViewportDescription.cpp
+++ b/Source/core/dom/ViewportDescription.cpp
@@ -28,11 +28,6 @@
 #include "config.h"
 #include "core/dom/ViewportDescription.h"
 
-#include "core/dom/Document.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "wtf/text/WTFString.h"
-
 using namespace std;
 
 namespace WebCore {
diff --git a/Source/core/dom/ViewportDescription.h b/Source/core/dom/ViewportDescription.h
index 8b51f94..96cccc0 100644
--- a/Source/core/dom/ViewportDescription.h
+++ b/Source/core/dom/ViewportDescription.h
@@ -31,12 +31,9 @@
 #include "core/page/PageScaleConstraints.h"
 #include "platform/Length.h"
 #include "platform/geometry/FloatSize.h"
-#include "wtf/Forward.h"
 
 namespace WebCore {
 
-class Document;
-
 struct ViewportDescription {
 
     enum Type {
diff --git a/Source/core/dom/custom/CustomElement.cpp b/Source/core/dom/custom/CustomElement.cpp
index a2a150c..39dd599 100644
--- a/Source/core/dom/custom/CustomElement.cpp
+++ b/Source/core/dom/custom/CustomElement.cpp
@@ -71,7 +71,9 @@
         DEFINE_STATIC_LOCAL(Vector<AtomicString>, reservedNames, ());
         if (reservedNames.isEmpty()) {
             reservedNames.append(MathMLNames::annotation_xmlTag.localName());
-            reservedNames.append(SVGNames::color_profileTag.localName());
+            // In principle, "color-profile" should exist in the SVGNames
+            // namespace, but we don't implement the color-profile element.
+            reservedNames.append("color-profile");
             reservedNames.append(SVGNames::font_faceTag.localName());
             reservedNames.append(SVGNames::font_face_srcTag.localName());
             reservedNames.append(SVGNames::font_face_uriTag.localName());
@@ -168,7 +170,7 @@
 {
     ASSERT(definition.get());
     DefinitionMap::ElementDefinitionHashMap::AddResult result = m_definitions.add(element, definition);
-    ASSERT(result.isNewEntry);
+    ASSERT_UNUSED(result, result.isNewEntry);
 }
 
 CustomElement::DefinitionMap& CustomElement::definitions()
diff --git a/Source/core/dom/custom/CustomElementDefinition.h b/Source/core/dom/custom/CustomElementDefinition.h
index 601f671..72e4121 100644
--- a/Source/core/dom/custom/CustomElementDefinition.h
+++ b/Source/core/dom/custom/CustomElementDefinition.h
@@ -39,12 +39,10 @@
 
 namespace WebCore {
 
-class CustomElementDefinition : public RefCounted<CustomElementDefinition> {
+class CustomElementDefinition FINAL : public RefCounted<CustomElementDefinition> {
 public:
     static PassRefPtr<CustomElementDefinition> create(const CustomElementDescriptor&, PassRefPtr<CustomElementLifecycleCallbacks>);
 
-    virtual ~CustomElementDefinition() { }
-
     const CustomElementDescriptor& descriptor() const { return m_descriptor; }
     CustomElementLifecycleCallbacks* callbacks() const { return m_callbacks.get(); }
 
diff --git a/Source/core/dom/custom/CustomElementObserver.cpp b/Source/core/dom/custom/CustomElementObserver.cpp
index 0710995..94247fc 100644
--- a/Source/core/dom/custom/CustomElementObserver.cpp
+++ b/Source/core/dom/custom/CustomElementObserver.cpp
@@ -58,13 +58,13 @@
 void CustomElementObserver::observe(Element* element)
 {
     ElementObserverMap::AddResult result = elementObservers().add(element, this);
-    ASSERT(result.isNewEntry);
+    ASSERT_UNUSED(result, result.isNewEntry);
 }
 
 void CustomElementObserver::unobserve(Element* element)
 {
     CustomElementObserver* observer = elementObservers().take(element);
-    ASSERT(observer == this);
+    ASSERT_UNUSED(observer, observer == this);
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElementRegistry.h b/Source/core/dom/custom/CustomElementRegistry.h
index 11642dd..c6acc8e 100644
--- a/Source/core/dom/custom/CustomElementRegistry.h
+++ b/Source/core/dom/custom/CustomElementRegistry.h
@@ -47,13 +47,12 @@
 class Document;
 class ExceptionState;
 
-class CustomElementRegistry {
+class CustomElementRegistry FINAL {
     WTF_MAKE_NONCOPYABLE(CustomElementRegistry);
 protected:
     friend class CustomElementRegistrationContext;
 
     CustomElementRegistry() { }
-    virtual ~CustomElementRegistry() { }
 
     CustomElementDefinition* registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& name, CustomElement::NameSet validNames, ExceptionState&);
     CustomElementDefinition* find(const CustomElementDescriptor&) const;
diff --git a/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp b/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
index c907831..df2033f 100644
--- a/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
+++ b/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
@@ -47,7 +47,7 @@
     observe(element);
 
     UpgradeCandidateMap::AddResult result = m_upgradeCandidates.add(element, descriptor);
-    ASSERT(result.isNewEntry);
+    ASSERT_UNUSED(result, result.isNewEntry);
 
     UnresolvedDefinitionMap::iterator it = m_unresolvedDefinitions.find(descriptor);
     if (it == m_unresolvedDefinitions.end())
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 757e808..a75da1b 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -131,23 +131,23 @@
     removeAllShadowRoots();
 }
 
-ShadowRoot* ElementShadow::addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType type)
+ShadowRoot* ElementShadow::addShadowRoot(Element& shadowHost, ShadowRoot::ShadowRootType type)
 {
-    RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(&shadowHost->document(), type);
+    RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(&shadowHost.document(), type);
 
-    shadowRoot->setParentOrShadowHostNode(shadowHost);
-    shadowRoot->setParentTreeScope(&shadowHost->treeScope());
+    shadowRoot->setParentOrShadowHostNode(&shadowHost);
+    shadowRoot->setParentTreeScope(&shadowHost.treeScope());
     m_shadowRoots.push(shadowRoot.get());
-    ChildNodeInsertionNotifier(shadowHost).notify(shadowRoot.get());
+    ChildNodeInsertionNotifier(shadowHost).notify(*shadowRoot);
     setNeedsDistributionRecalc();
-    shadowHost->lazyReattachIfAttached();
+    shadowHost.lazyReattachIfAttached();
 
     // addShadowRoot() affects apply-author-styles. However, we know that the youngest shadow root has not had any children yet.
     // The youngest shadow root's apply-author-styles is default (false). So we can just set m_applyAuthorStyles false.
     m_applyAuthorStyles = false;
 
-    shadowHost->didAddShadowRoot(*shadowRoot);
-    InspectorInstrumentation::didPushShadowRoot(shadowHost, shadowRoot.get());
+    shadowHost.didAddShadowRoot(*shadowRoot);
+    InspectorInstrumentation::didPushShadowRoot(&shadowHost, shadowRoot.get());
 
     return shadowRoot.get();
 }
@@ -156,20 +156,17 @@
 {
     // Dont protect this ref count.
     Element* shadowHost = host();
+    ASSERT(shadowHost);
 
     while (RefPtr<ShadowRoot> oldRoot = m_shadowRoots.head()) {
         InspectorInstrumentation::willPopShadowRoot(shadowHost, oldRoot.get());
         shadowHost->document().removeFocusedElementOfSubtree(oldRoot.get());
-
-        if (oldRoot->confusingAndOftenMisusedAttached())
-            oldRoot->detach();
-
         m_shadowRoots.removeHead();
         oldRoot->setParentOrShadowHostNode(0);
         oldRoot->setParentTreeScope(&shadowHost->document());
         oldRoot->setPrev(0);
         oldRoot->setNext(0);
-        ChildNodeRemovalNotifier(shadowHost).notify(oldRoot.get());
+        ChildNodeRemovalNotifier(*shadowHost).notify(*oldRoot);
     }
 }
 
@@ -189,10 +186,8 @@
     Node::AttachContext childrenContext(context);
     childrenContext.resolvedStyle = 0;
 
-    for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
-        if (root->confusingAndOftenMisusedAttached())
-            root->detach(childrenContext);
-    }
+    for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot())
+        root->detach(childrenContext);
 }
 
 void ElementShadow::removeAllEventListeners()
@@ -259,7 +254,7 @@
     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
         HTMLShadowElement* firstActiveShadowInsertionPoint = 0;
 
-        const Vector<RefPtr<InsertionPoint> >& insertionPoints = root->childInsertionPoints();
+        const Vector<RefPtr<InsertionPoint> >& insertionPoints = root->descendantInsertionPoints();
         for (size_t i = 0; i < insertionPoints.size(); ++i) {
             InsertionPoint* point = insertionPoints[i].get();
             if (!point->isActive())
diff --git a/Source/core/dom/shadow/ElementShadow.h b/Source/core/dom/shadow/ElementShadow.h
index 1e915a3..a8e040e 100644
--- a/Source/core/dom/shadow/ElementShadow.h
+++ b/Source/core/dom/shadow/ElementShadow.h
@@ -51,7 +51,7 @@
     ShadowRoot* oldestShadowRoot() const { return m_shadowRoots.tail(); }
     ElementShadow* containingShadow() const;
 
-    ShadowRoot* addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType);
+    ShadowRoot* addShadowRoot(Element& shadowHost, ShadowRoot::ShadowRootType);
 
     bool applyAuthorStyles() const { return m_applyAuthorStyles; }
     bool didAffectApplyAuthorStyles();
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
index 673d040..3023d66 100644
--- a/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -177,7 +177,7 @@
             rootOwner->setNeedsDistributionRecalc();
             if (isActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
                 m_registeredWithShadowRoot = true;
-                root->addInsertionPoint(this);
+                root->didAddInsertionPoint(this);
                 rootOwner->didAffectApplyAuthorStyles();
                 if (canAffectSelector())
                     rootOwner->willAffectSelector();
@@ -208,7 +208,7 @@
     if (m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
         ASSERT(root);
         m_registeredWithShadowRoot = false;
-        root->removeInsertionPoint(this);
+        root->didRemoveInsertionPoint(this);
         if (rootOwner) {
             rootOwner->didAffectApplyAuthorStyles();
             if (canAffectSelector())
@@ -222,7 +222,7 @@
 void InsertionPoint::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (name == reset_style_inheritanceAttr) {
-        if (!inDocument() || !confusingAndOftenMisusedAttached() || !isActive())
+        if (!inDocument() || !isActive())
             return;
         containingShadowRoot()->host()->setNeedsStyleRecalc();
     } else
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index b438adb..508585a 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -39,7 +39,7 @@
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRootRareData.h"
 #include "core/editing/markup.h"
-#include "core/platform/HistogramSupport.h"
+#include "public/platform/Platform.h"
 
 namespace WebCore {
 
@@ -73,7 +73,7 @@
 
     if (type == ShadowRoot::AuthorShadowRoot) {
         ShadowRootUsageOriginType usageType = document->url().protocolIsInHTTPFamily() ? ShadowRootUsageOriginWeb : ShadowRootUsageOriginNotWeb;
-        HistogramSupport::histogramEnumeration("WebCore.ShadowRoot.constructor", usageType, ShadowRootUsageOriginMax);
+        WebKit::Platform::current()->histogramEnumeration("WebCore.ShadowRoot.constructor", usageType, ShadowRootUsageOriginMax);
     }
 }
 
@@ -87,11 +87,11 @@
 
     documentInternal()->styleEngine()->didRemoveShadowRoot(this);
 
-    // We cannot let ContainerNode destructor call willBeDeletedFrom()
+    // We cannot let ContainerNode destructor call willBeDeletedFromDocument()
     // for this ShadowRoot instance because TreeScope destructor
     // clears Node::m_treeScope thus ContainerNode is no longer able
     // to access it Document reference after that.
-    willBeDeletedFrom(documentInternal());
+    willBeDeletedFromDocument();
 
     // We must remove all of our children first before the TreeScope destructor
     // runs so we don't go through TreeScopeAdopter for each child with a
@@ -145,7 +145,7 @@
         return;
     }
 
-    if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, host(), AllowScriptingContent, es))
+    if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, host(), AllowScriptingContent, "innerHTML", es))
         replaceChildrenWithFragment(this, fragment.release(), es);
 }
 
@@ -171,11 +171,6 @@
     StyleResolver* styleResolver = document().styleResolver();
     styleResolver->pushParentShadowRoot(*this);
 
-    if (!confusingAndOftenMisusedAttached()) {
-        attach();
-        return;
-    }
-
     // When we're set to lazyAttach we'll have a SubtreeStyleChange and we'll need
     // to promote the change to a Force for all our descendants so they get a
     // recalc and will attach.
@@ -201,6 +196,7 @@
     styleResolver->popParentShadowRoot(*this);
     clearNeedsStyleRecalc();
     clearChildNeedsStyleRecalc();
+    setAttached();
 }
 
 bool ShadowRoot::isActive() const
@@ -328,17 +324,17 @@
 
 bool ShadowRoot::containsShadowElements() const
 {
-    return m_shadowRootRareData ? m_shadowRootRareData->hasShadowElementChildren() : 0;
+    return m_shadowRootRareData ? m_shadowRootRareData->containsShadowElements() : 0;
 }
 
 bool ShadowRoot::containsContentElements() const
 {
-    return m_shadowRootRareData ? m_shadowRootRareData->hasContentElementChildren() : 0;
+    return m_shadowRootRareData ? m_shadowRootRareData->containsContentElements() : 0;
 }
 
 bool ShadowRoot::containsShadowRoots() const
 {
-    return m_shadowRootRareData ? m_shadowRootRareData->hasShadowRootChildren() : 0;
+    return m_shadowRootRareData ? m_shadowRootRareData->containsShadowRoots() : 0;
 }
 
 InsertionPoint* ShadowRoot::insertionPoint() const
@@ -353,21 +349,21 @@
     ensureShadowRootRareData()->setInsertionPoint(insertionPoint);
 }
 
-void ShadowRoot::addInsertionPoint(InsertionPoint* insertionPoint)
+void ShadowRoot::didAddInsertionPoint(InsertionPoint* insertionPoint)
 {
-    ensureShadowRootRareData()->addInsertionPoint(insertionPoint);
+    ensureShadowRootRareData()->didAddInsertionPoint(insertionPoint);
     invalidateChildInsertionPoints();
 }
 
-void ShadowRoot::removeInsertionPoint(InsertionPoint* insertionPoint)
+void ShadowRoot::didRemoveInsertionPoint(InsertionPoint* insertionPoint)
 {
-    m_shadowRootRareData->removeInsertionPoint(insertionPoint);
+    m_shadowRootRareData->didRemoveInsertionPoint(insertionPoint);
     invalidateChildInsertionPoints();
 }
 
 void ShadowRoot::addChildShadowRoot()
 {
-    ensureShadowRootRareData()->addChildShadowRoot();
+    ensureShadowRootRareData()->didAddChildShadowRoot();
 }
 
 void ShadowRoot::removeChildShadowRoot()
@@ -375,7 +371,7 @@
     // FIXME: Why isn't this an ASSERT?
     if (!m_shadowRootRareData)
         return;
-    m_shadowRootRareData->removeChildShadowRoot();
+    m_shadowRootRareData->didRemoveChildShadowRoot();
 }
 
 unsigned ShadowRoot::childShadowRootCount() const
@@ -386,15 +382,15 @@
 void ShadowRoot::invalidateChildInsertionPoints()
 {
     m_childInsertionPointsIsValid = false;
-    m_shadowRootRareData->clearChildInsertionPoints();
+    m_shadowRootRareData->clearDescendantInsertionPoints();
 }
 
-const Vector<RefPtr<InsertionPoint> >& ShadowRoot::childInsertionPoints()
+const Vector<RefPtr<InsertionPoint> >& ShadowRoot::descendantInsertionPoints()
 {
     DEFINE_STATIC_LOCAL(const Vector<RefPtr<InsertionPoint> >, emptyList, ());
 
     if (m_shadowRootRareData && m_childInsertionPointsIsValid)
-        return m_shadowRootRareData->childInsertionPoints();
+        return m_shadowRootRareData->descendantInsertionPoints();
 
     m_childInsertionPointsIsValid = true;
 
@@ -407,9 +403,9 @@
             insertionPoints.append(toInsertionPoint(element));
     }
 
-    ensureShadowRootRareData()->setChildInsertionPoints(insertionPoints);
+    ensureShadowRootRareData()->setDescendantInsertionPoints(insertionPoints);
 
-    return m_shadowRootRareData->childInsertionPoints();
+    return m_shadowRootRareData->descendantInsertionPoints();
 }
 
 StyleSheetList* ShadowRoot::styleSheets()
diff --git a/Source/core/dom/shadow/ShadowRoot.h b/Source/core/dom/shadow/ShadowRoot.h
index 738c7be..84ad90b 100644
--- a/Source/core/dom/shadow/ShadowRoot.h
+++ b/Source/core/dom/shadow/ShadowRoot.h
@@ -91,9 +91,9 @@
     InsertionPoint* insertionPoint() const;
     void setInsertionPoint(PassRefPtr<InsertionPoint>);
 
-    void addInsertionPoint(InsertionPoint*);
-    void removeInsertionPoint(InsertionPoint*);
-    const Vector<RefPtr<InsertionPoint> >& childInsertionPoints();
+    void didAddInsertionPoint(InsertionPoint*);
+    void didRemoveInsertionPoint(InsertionPoint*);
+    const Vector<RefPtr<InsertionPoint> >& descendantInsertionPoints();
 
     ShadowRootType type() const { return static_cast<ShadowRootType>(m_type); }
 
@@ -166,6 +166,12 @@
     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());
diff --git a/Source/core/dom/shadow/ShadowRoot.idl b/Source/core/dom/shadow/ShadowRoot.idl
index 502f939..fd06913 100644
--- a/Source/core/dom/shadow/ShadowRoot.idl
+++ b/Source/core/dom/shadow/ShadowRoot.idl
@@ -46,4 +46,5 @@
                              [Default=Undefined] optional long y);
 
     [RuntimeEnabled=ShadowDOM] readonly attribute StyleSheetList styleSheets;
+    [RuntimeEnabled=ShadowDOM] readonly attribute Element host;
 };
diff --git a/Source/core/dom/shadow/ShadowRootRareData.h b/Source/core/dom/shadow/ShadowRootRareData.h
index df74d2b..6ed6376 100644
--- a/Source/core/dom/shadow/ShadowRootRareData.h
+++ b/Source/core/dom/shadow/ShadowRootRareData.h
@@ -42,8 +42,8 @@
 class ShadowRootRareData {
 public:
     ShadowRootRareData()
-        : m_childShadowElementCount(0)
-        , m_childContentElementCount(0)
+        : m_descendantShadowElementCount(0)
+        , m_descendantContentElementCount(0)
         , m_childShadowRootCount(0)
     {
     }
@@ -51,55 +51,55 @@
     InsertionPoint* insertionPoint() const { return m_insertionPoint.get(); }
     void setInsertionPoint(PassRefPtr<InsertionPoint> insertionPoint) { m_insertionPoint = insertionPoint; }
 
-    void addInsertionPoint(InsertionPoint*);
-    void removeInsertionPoint(InsertionPoint*);
+    void didAddInsertionPoint(InsertionPoint*);
+    void didRemoveInsertionPoint(InsertionPoint*);
 
-    bool hasShadowElementChildren() const { return m_childShadowElementCount; }
-    bool hasContentElementChildren() const { return m_childContentElementCount; }
-    bool hasShadowRootChildren() const { return m_childShadowRootCount; }
+    bool containsShadowElements() const { return m_descendantShadowElementCount; }
+    bool containsContentElements() const { return m_descendantContentElementCount; }
+    bool containsShadowRoots() const { return m_childShadowRootCount; }
 
-    void addChildShadowRoot() { ++m_childShadowRootCount; }
-    void removeChildShadowRoot() { ASSERT(m_childShadowRootCount > 0); --m_childShadowRootCount; }
+    void didAddChildShadowRoot() { ++m_childShadowRootCount; }
+    void didRemoveChildShadowRoot() { ASSERT(m_childShadowRootCount > 0); --m_childShadowRootCount; }
 
     unsigned childShadowRootCount() const { return m_childShadowRootCount; }
 
-    const Vector<RefPtr<InsertionPoint> >& childInsertionPoints() { return m_childInsertionPoints; }
-    void setChildInsertionPoints(Vector<RefPtr<InsertionPoint> >& list) { m_childInsertionPoints.swap(list); }
-    void clearChildInsertionPoints() { m_childInsertionPoints.clear(); }
+    const Vector<RefPtr<InsertionPoint> >& descendantInsertionPoints() { return m_descendantInsertionPoints; }
+    void setDescendantInsertionPoints(Vector<RefPtr<InsertionPoint> >& list) { m_descendantInsertionPoints.swap(list); }
+    void clearDescendantInsertionPoints() { m_descendantInsertionPoints.clear(); }
 
     StyleSheetList* styleSheets() { return m_styleSheetList.get(); }
     void setStyleSheets(PassRefPtr<StyleSheetList> styleSheetList) { m_styleSheetList = styleSheetList; }
 
 private:
     RefPtr<InsertionPoint> m_insertionPoint;
-    unsigned m_childShadowElementCount;
-    unsigned m_childContentElementCount;
+    unsigned m_descendantShadowElementCount;
+    unsigned m_descendantContentElementCount;
     unsigned m_childShadowRootCount;
-    Vector<RefPtr<InsertionPoint> > m_childInsertionPoints;
+    Vector<RefPtr<InsertionPoint> > m_descendantInsertionPoints;
     RefPtr<StyleSheetList> m_styleSheetList;
 };
 
-inline void ShadowRootRareData::addInsertionPoint(InsertionPoint* point)
+inline void ShadowRootRareData::didAddInsertionPoint(InsertionPoint* point)
 {
     if (isHTMLShadowElement(point))
-        ++m_childShadowElementCount;
+        ++m_descendantShadowElementCount;
     else if (isHTMLContentElement(point))
-        ++m_childContentElementCount;
+        ++m_descendantContentElementCount;
     else
         ASSERT_NOT_REACHED();
 }
 
-inline void ShadowRootRareData::removeInsertionPoint(InsertionPoint* point)
+inline void ShadowRootRareData::didRemoveInsertionPoint(InsertionPoint* point)
 {
     if (isHTMLShadowElement(point))
-        --m_childShadowElementCount;
+        --m_descendantShadowElementCount;
     else if (isHTMLContentElement(point))
-        --m_childContentElementCount;
+        --m_descendantContentElementCount;
     else
         ASSERT_NOT_REACHED();
 
-    ASSERT(m_childContentElementCount >= 0);
-    ASSERT(m_childShadowElementCount >= 0);
+    ASSERT(m_descendantContentElementCount >= 0);
+    ASSERT(m_descendantShadowElementCount >= 0);
 }
 
 } // namespace WebCore
diff --git a/Source/core/editing/AppendNodeCommand.cpp b/Source/core/editing/AppendNodeCommand.cpp
index 4d4d59e..0120ec0 100644
--- a/Source/core/editing/AppendNodeCommand.cpp
+++ b/Source/core/editing/AppendNodeCommand.cpp
@@ -40,12 +40,12 @@
     ASSERT(m_node);
     ASSERT(!m_node->parentNode());
 
-    ASSERT(m_parent->rendererIsEditable() || !m_parent->confusingAndOftenMisusedAttached());
+    ASSERT(m_parent->rendererIsEditable() || !m_parent->inActiveDocument());
 }
 
 void AppendNodeCommand::doApply()
 {
-    if (!m_parent->rendererIsEditable() && m_parent->confusingAndOftenMisusedAttached())
+    if (!m_parent->rendererIsEditable() && m_parent->inActiveDocument())
         return;
 
     m_parent->appendChild(m_node.get(), IGNORE_EXCEPTION);
diff --git a/Source/core/editing/ApplyStyleCommand.cpp b/Source/core/editing/ApplyStyleCommand.cpp
index 33a153a..35656f9 100644
--- a/Source/core/editing/ApplyStyleCommand.cpp
+++ b/Source/core/editing/ApplyStyleCommand.cpp
@@ -39,6 +39,7 @@
 #include "core/dom/Text.h"
 #include "core/editing/EditingStyle.h"
 #include "core/editing/HTMLInterchange.h"
+#include "core/editing/PlainTextRange.h"
 #include "core/editing/TextIterator.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
@@ -272,9 +273,9 @@
             }
             ASSERT(!block || block->isHTMLElement());
             if (block && block->isHTMLElement()) {
-                removeCSSStyle(style, toHTMLElement(block.get()));
+                removeCSSStyle(style, toHTMLElement(block));
                 if (!m_removeOnly)
-                    addBlockStyle(styleChange, toHTMLElement(block.get()));
+                    addBlockStyle(styleChange, toHTMLElement(block));
             }
 
             if (nextParagraphStart.isOrphan())
@@ -285,8 +286,8 @@
         nextParagraphStart = endOfParagraph(paragraphStart).next();
     }
 
-    startRange = TextIterator::rangeFromLocationAndLength(toContainerNode(scope), startIndex, 0, true);
-    endRange = TextIterator::rangeFromLocationAndLength(toContainerNode(scope), endIndex, 0, true);
+    startRange = PlainTextRange(startIndex).createRangeForSelection(*toContainerNode(scope));
+    endRange = PlainTextRange(endIndex).createRangeForSelection(*toContainerNode(scope));
     if (startRange && endRange)
         updateStartEnd(startRange->startPosition(), endRange->startPosition());
 }
@@ -758,7 +759,7 @@
             if (pastEndNode && pastEndNode->isDescendantOf(node.get()))
                 break;
             // Add to this element's inline style and skip over its contents.
-            HTMLElement* element = toHTMLElement(node.get());
+            HTMLElement* element = toHTMLElement(node);
             next = NodeTraversal::nextSkippingChildren(node.get());
             if (!style->style())
                 continue;
@@ -855,7 +856,7 @@
         RefPtr<Node> previousSibling = node->previousSibling();
         RefPtr<Node> nextSibling = node->nextSibling();
         RefPtr<ContainerNode> parent = node->parentNode();
-        removeInlineStyleFromElement(style, toHTMLElement(node.get()), RemoveAlways);
+        removeInlineStyleFromElement(style, toHTMLElement(node), RemoveAlways);
         if (!node->inDocument()) {
             // FIXME: We might need to update the start and the end of current selection here but need a test.
             if (runStart == node)
@@ -1029,14 +1030,14 @@
         NodeVector currentChildren;
         getChildNodes(current.get(), currentChildren);
         RefPtr<Element> styledElement;
-        if (current->isStyledElement() && isStyledInlineElementToRemove(toElement(current.get()))) {
-            styledElement = toElement(current.get());
+        if (current->isStyledElement() && isStyledInlineElementToRemove(toElement(current))) {
+            styledElement = toElement(current);
             elementsToPushDown.append(styledElement);
         }
 
         RefPtr<EditingStyle> styleToPushDown = EditingStyle::create();
         if (current->isHTMLElement())
-            removeInlineStyleFromElement(style, toHTMLElement(current.get()), RemoveIfNeeded, styleToPushDown.get());
+            removeInlineStyleFromElement(style, toHTMLElement(current), RemoveIfNeeded, styleToPushDown.get());
 
         // The inner loop will go through children on each level
         // FIXME: we should aggregate inline child elements together so that we don't wrap each child separately.
@@ -1110,7 +1111,7 @@
             next = NodeTraversal::next(node.get());
         }
         if (node->isHTMLElement() && nodeFullySelected(node.get(), start, end)) {
-            RefPtr<HTMLElement> elem = toHTMLElement(node.get());
+            RefPtr<HTMLElement> elem = toHTMLElement(node);
             RefPtr<Node> prev = NodeTraversal::previousPostOrder(elem.get());
             RefPtr<Node> next = NodeTraversal::next(elem.get());
             RefPtr<EditingStyle> styleToPushDown;
@@ -1353,14 +1354,14 @@
     RefPtr<Node> nextSibling = element->nextSibling();
     RefPtr<Node> previousSibling = element->previousSibling();
     if (nextSibling && nextSibling->isElementNode() && nextSibling->rendererIsEditable()
-        && areIdenticalElements(element.get(), toElement(nextSibling.get())))
-        mergeIdenticalElements(element.get(), toElement(nextSibling.get()));
+        && areIdenticalElements(element.get(), toElement(nextSibling)))
+        mergeIdenticalElements(element.get(), toElement(nextSibling));
 
     if (previousSibling && previousSibling->isElementNode() && previousSibling->rendererIsEditable()) {
         Node* mergedElement = previousSibling->nextSibling();
         if (mergedElement->isElementNode() && mergedElement->rendererIsEditable()
-            && areIdenticalElements(toElement(previousSibling.get()), toElement(mergedElement)))
-            mergeIdenticalElements(toElement(previousSibling.get()), toElement(mergedElement));
+            && areIdenticalElements(toElement(previousSibling), toElement(mergedElement)))
+            mergeIdenticalElements(toElement(previousSibling), toElement(mergedElement));
     }
 
     // FIXME: We should probably call updateStartEnd if the start or end was in the node
diff --git a/Source/core/editing/CompositeEditCommand.cpp b/Source/core/editing/CompositeEditCommand.cpp
index 0f5cb1b..ae7cebf 100644
--- a/Source/core/editing/CompositeEditCommand.cpp
+++ b/Source/core/editing/CompositeEditCommand.cpp
@@ -45,6 +45,7 @@
 #include "core/editing/InsertNodeBeforeCommand.h"
 #include "core/editing/InsertParagraphSeparatorCommand.h"
 #include "core/editing/MergeIdenticalElementsCommand.h"
+#include "core/editing/PlainTextRange.h"
 #include "core/editing/RemoveCSSPropertyCommand.h"
 #include "core/editing/RemoveNodeCommand.h"
 #include "core/editing/RemoveNodePreservingChildrenCommand.h"
@@ -992,7 +993,7 @@
         for (size_t i = ancestors.size(); i != 0; --i) {
             Node* item = ancestors[i - 1].get();
             RefPtr<Node> child = item->cloneNode(isTableElement(item));
-            appendNode(child, toElement(lastNode.get()));
+            appendNode(child, toElement(lastNode));
             lastNode = child.release();
         }
     }
@@ -1242,8 +1243,8 @@
         // causes spaces to be collapsed during the move operation.  This results
         // in a call to rangeFromLocationAndLength with a location past the end
         // of the document (which will return null).
-        RefPtr<Range> start = TextIterator::rangeFromLocationAndLength(document().documentElement(), destinationIndex + startIndex, 0, true);
-        RefPtr<Range> end = TextIterator::rangeFromLocationAndLength(document().documentElement(), destinationIndex + endIndex, 0, true);
+        RefPtr<Range> start = PlainTextRange(destinationIndex + startIndex).createRangeForSelection(*document().documentElement());
+        RefPtr<Range> end = PlainTextRange(destinationIndex + endIndex).createRangeForSelection(*document().documentElement());
         if (start && end)
             setEndingSelection(VisibleSelection(start->startPosition(), end->startPosition(), DOWNSTREAM, originalIsDirectional));
     }
@@ -1287,12 +1288,12 @@
     if (!newBlock)
         newBlock = createDefaultParagraphElement(document());
 
-    RefPtr<Node> previousListNode = emptyListItem->isElementNode() ? toElement(emptyListItem.get())->previousElementSibling(): emptyListItem->previousSibling();
-    RefPtr<Node> nextListNode = emptyListItem->isElementNode() ? toElement(emptyListItem.get())->nextElementSibling(): emptyListItem->nextSibling();
+    RefPtr<Node> previousListNode = emptyListItem->isElementNode() ? toElement(emptyListItem)->previousElementSibling(): emptyListItem->previousSibling();
+    RefPtr<Node> nextListNode = emptyListItem->isElementNode() ? toElement(emptyListItem)->nextElementSibling(): 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()))
-            splitElement(toElement(listNode.get()), emptyListItem);
+            splitElement(toElement(listNode), emptyListItem);
 
         // If emptyListItem is followed by other list item or nested list, then insert newBlock before the list node.
         // Because we have splitted the element, emptyListItem is the first element in the list node.
diff --git a/Source/core/editing/CompositionUnderline.h b/Source/core/editing/CompositionUnderline.h
index 5f97ac7..025ee75 100644
--- a/Source/core/editing/CompositionUnderline.h
+++ b/Source/core/editing/CompositionUnderline.h
@@ -26,7 +26,7 @@
 #ifndef CompositionUnderline_h
 #define CompositionUnderline_h
 
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 
 namespace WebCore {
 
diff --git a/Source/core/editing/DeleteSelectionCommand.cpp b/Source/core/editing/DeleteSelectionCommand.cpp
index 62c7004..4ccf525 100644
--- a/Source/core/editing/DeleteSelectionCommand.cpp
+++ b/Source/core/editing/DeleteSelectionCommand.cpp
@@ -430,7 +430,7 @@
     RefPtr<Node> node = range->firstNode();
     while (node && node != range->pastLastNode()) {
         RefPtr<Node> nextNode = NodeTraversal::next(node.get());
-        if ((node->hasTagName(styleTag) && !(toElement(node.get())->hasAttribute(scopedAttr))) || node->hasTagName(linkTag)) {
+        if ((node->hasTagName(styleTag) && !(toElement(node)->hasAttribute(scopedAttr))) || node->hasTagName(linkTag)) {
             nextNode = NodeTraversal::nextSkippingChildren(node.get());
             RefPtr<ContainerNode> rootEditableElement = node->rootEditableElement();
             if (rootEditableElement.get()) {
@@ -499,7 +499,7 @@
         if (startOffset > 0) {
             if (startNode->isTextNode()) {
                 // in a text node that needs to be trimmed
-                Text* text = toText(node.get());
+                Text* text = toText(node);
                 deleteTextFromNode(text, startOffset, text->length() - startOffset);
                 node = NodeTraversal::next(node.get());
             } else {
diff --git a/Source/core/editing/EditingBehavior.h b/Source/core/editing/EditingBehavior.h
index 6c2f994..395ebe6 100644
--- a/Source/core/editing/EditingBehavior.h
+++ b/Source/core/editing/EditingBehavior.h
@@ -79,6 +79,10 @@
     // But ctrl+right arrow moves caret to "abc |def |hij |opq" on Windows and "abc| def| hij| opq|" on Mac and Linux.
     bool shouldSkipSpaceWhenMovingRight() const { return m_type == EditingWindowsBehavior; }
 
+    // On Mac, undo of delete/forward-delete of text should select the deleted text. On other platforms deleted text
+    // should not be selected and the cursor should be placed where the deletion started.
+    bool shouldUndoOfDeleteSelectText() const { return m_type == EditingMacBehavior; }
+
 private:
     EditingBehaviorType m_type;
 };
diff --git a/Source/core/editing/Editor.cpp b/Source/core/editing/Editor.cpp
index 8b12846..bb5ffec 100644
--- a/Source/core/editing/Editor.cpp
+++ b/Source/core/editing/Editor.cpp
@@ -813,7 +813,7 @@
 
 bool Editor::insertText(const String& text, Event* triggeringEvent)
 {
-    return m_frame.eventHandler()->handleTextInputEvent(text, triggeringEvent);
+    return m_frame.eventHandler().handleTextInputEvent(text, triggeringEvent);
 }
 
 bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
diff --git a/Source/core/editing/EditorCommand.cpp b/Source/core/editing/EditorCommand.cpp
index 76bbdd9..9661fa2 100644
--- a/Source/core/editing/EditorCommand.cpp
+++ b/Source/core/editing/EditorCommand.cpp
@@ -481,7 +481,7 @@
 
 static bool executeInsertBacktab(Frame& frame, Event* event, EditorCommandSource, const String&)
 {
-    return targetFrame(frame, event)->eventHandler()->handleTextInputEvent("\t", event, TextEventInputBackTab);
+    return targetFrame(frame, event)->eventHandler().handleTextInputEvent("\t", event, TextEventInputBackTab);
 }
 
 static bool executeInsertHorizontalRule(Frame& frame, Event*, EditorCommandSource, const String& value)
@@ -512,7 +512,7 @@
 {
     switch (source) {
     case CommandFromMenuOrKeyBinding:
-        return targetFrame(frame, event)->eventHandler()->handleTextInputEvent("\n", event, TextEventInputLineBreak);
+        return targetFrame(frame, event)->eventHandler().handleTextInputEvent("\n", event, TextEventInputLineBreak);
     case CommandFromDOM:
     case CommandFromDOMWithUserInterface:
         // Doesn't scroll to make the selection visible, or modify the kill ring.
@@ -529,7 +529,7 @@
 static bool executeInsertNewline(Frame& frame, Event* event, EditorCommandSource, const String&)
 {
     Frame* targetFrame = WebCore::targetFrame(frame, event);
-    return targetFrame->eventHandler()->handleTextInputEvent("\n", event, targetFrame->editor().canEditRichly() ? TextEventInputKeyboard : TextEventInputLineBreak);
+    return targetFrame->eventHandler().handleTextInputEvent("\n", event, targetFrame->editor().canEditRichly() ? TextEventInputKeyboard : TextEventInputLineBreak);
 }
 
 static bool executeInsertNewlineInQuotedContent(Frame& frame, Event*, EditorCommandSource, const String&)
@@ -555,7 +555,7 @@
 
 static bool executeInsertTab(Frame& frame, Event* event, EditorCommandSource, const String&)
 {
-    return targetFrame(frame, event)->eventHandler()->handleTextInputEvent("\t", event);
+    return targetFrame(frame, event)->eventHandler().handleTextInputEvent("\t", event);
 }
 
 static bool executeInsertText(Frame& frame, Event*, EditorCommandSource, const String& value)
@@ -975,32 +975,32 @@
 
 static bool executeScrollPageBackward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler()->logicalScrollRecursively(ScrollBlockDirectionBackward, ScrollByPage);
+    return frame.eventHandler().logicalScrollRecursively(ScrollBlockDirectionBackward, ScrollByPage);
 }
 
 static bool executeScrollPageForward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler()->logicalScrollRecursively(ScrollBlockDirectionForward, ScrollByPage);
+    return frame.eventHandler().logicalScrollRecursively(ScrollBlockDirectionForward, ScrollByPage);
 }
 
 static bool executeScrollLineUp(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler()->scrollRecursively(ScrollUp, ScrollByLine);
+    return frame.eventHandler().scrollRecursively(ScrollUp, ScrollByLine);
 }
 
 static bool executeScrollLineDown(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler()->scrollRecursively(ScrollDown, ScrollByLine);
+    return frame.eventHandler().scrollRecursively(ScrollDown, ScrollByLine);
 }
 
 static bool executeScrollToBeginningOfDocument(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler()->logicalScrollRecursively(ScrollBlockDirectionBackward, ScrollByDocument);
+    return frame.eventHandler().logicalScrollRecursively(ScrollBlockDirectionBackward, ScrollByDocument);
 }
 
 static bool executeScrollToEndOfDocument(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler()->logicalScrollRecursively(ScrollBlockDirectionForward, ScrollByDocument);
+    return frame.eventHandler().logicalScrollRecursively(ScrollBlockDirectionForward, ScrollByDocument);
 }
 
 static bool executeSelectAll(Frame& frame, Event*, EditorCommandSource, const String&)
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index 4fb8a6e..649efb9 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -46,6 +46,7 @@
 #include "core/editing/TypingCommand.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
+#include "core/frame/DOMWindow.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/html/HTMLInputElement.h"
@@ -294,7 +295,7 @@
     }
 
     notifyAccessibilityForSelectionChange();
-    m_frame->document()->enqueueDocumentEvent(Event::create(EventTypeNames::selectionchange));
+    m_frame->domWindow()->enqueueDocumentEvent(Event::create(EventTypeNames::selectionchange));
 }
 
 static bool removingNodeRemovesPosition(Node* node, const Position& position)
@@ -1342,7 +1343,7 @@
 void FrameSelection::selectFrameElementInParentIfFullySelected()
 {
     // Find the parent frame; if there is none, then we have nothing to do.
-    Frame* parent = m_frame->tree()->parent();
+    Frame* parent = m_frame->tree().parent();
     if (!parent)
         return;
     Page* page = m_frame->page();
@@ -1478,7 +1479,7 @@
     setCaretVisibility(activeAndFocused ? Visible : Hidden);
 
     // Update for caps lock state
-    m_frame->eventHandler()->capsLockStateMayHaveChanged();
+    m_frame->eventHandler().capsLockStateMayHaveChanged();
 
     // Because StyleResolver::checkOneSelector() and
     // RenderTheme::isFocused() check if the frame is active, we have to
diff --git a/Source/core/editing/IndentOutdentCommand.cpp b/Source/core/editing/IndentOutdentCommand.cpp
index a98c166..9348405 100644
--- a/Source/core/editing/IndentOutdentCommand.cpp
+++ b/Source/core/editing/IndentOutdentCommand.cpp
@@ -69,10 +69,16 @@
     RefPtr<Element> previousList = selectedListItem->previousElementSibling();
     RefPtr<Element> nextList = selectedListItem->nextElementSibling();
 
+    // We should calculate visible range in list item because inserting new
+    // list element will change visibility of list item, e.g. :first-child
+    // CSS selector.
+    VisiblePosition startOfMove(start);
+    VisiblePosition endOfMove(end);
+
     RefPtr<Element> newList = document().createElement(listNode->tagQName(), false);
     insertNodeBefore(newList, selectedListItem.get());
 
-    moveParagraphWithClones(start, end, newList.get(), selectedListItem.get());
+    moveParagraphWithClones(startOfMove, endOfMove, newList.get(), selectedListItem.get());
 
     if (canMergeLists(previousList.get(), newList.get()))
         mergeIdenticalElements(previousList.get(), newList.get());
diff --git a/Source/core/editing/InputMethodController.cpp b/Source/core/editing/InputMethodController.cpp
index a2d22ed..daf2226 100644
--- a/Source/core/editing/InputMethodController.cpp
+++ b/Source/core/editing/InputMethodController.cpp
@@ -42,23 +42,6 @@
 
 namespace WebCore {
 
-PlainTextOffsets::PlainTextOffsets()
-    : m_start(kNotFound)
-    , m_end(kNotFound)
-{
-}
-
-PlainTextOffsets::PlainTextOffsets(int start, int end)
-    : m_start(start)
-    , m_end(end)
-{
-    ASSERT(start != kNotFound);
-    ASSERT(end != kNotFound);
-    ASSERT(start <= end);
-}
-
-// ----------------------------
-
 InputMethodController::SelectionOffsetsScope::SelectionOffsetsScope(InputMethodController* inputMethodController)
     : m_inputMethodController(inputMethodController)
     , m_offsets(inputMethodController->getSelectionOffsets())
@@ -111,7 +94,7 @@
 
 bool InputMethodController::insertTextForConfirmedComposition(const String& text)
 {
-    return m_frame.eventHandler()->handleTextInputEvent(text, 0, TextEventInputComposition);
+    return m_frame.eventHandler().handleTextInputEvent(text, 0, TextEventInputComposition);
 }
 
 void InputMethodController::selectComposition() const
@@ -358,7 +341,7 @@
 
     Editor::RevealSelectionScope revealSelectionScope(&editor());
     SelectionOffsetsScope selectionOffsetsScope(this);
-    setSelectionOffsets(PlainTextOffsets(compositionStart, compositionEnd));
+    setSelectionOffsets(PlainTextRange(compositionStart, compositionEnd));
     setComposition(m_frame.selectedText(), underlines, 0, 0);
 }
 
@@ -374,20 +357,17 @@
     return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
 }
 
-PlainTextOffsets InputMethodController::getSelectionOffsets() const
+PlainTextRange InputMethodController::getSelectionOffsets() const
 {
     RefPtr<Range> range = m_frame.selection().selection().firstRange();
     if (!range)
-        return PlainTextOffsets();
-    size_t location;
-    size_t length;
-    // FIXME: We should change TextIterator::getLocationAndLengthFromRange() returns PlainTextOffsets.
-    if (TextIterator::getLocationAndLengthFromRange(m_frame.selection().rootEditableElementOrTreeScopeRootNode(), range.get(), location, length))
-        return PlainTextOffsets(location, location + length);
-    return PlainTextOffsets();
+        return PlainTextRange();
+    Node* editable = m_frame.selection().rootEditableElementOrTreeScopeRootNode();
+    ASSERT(editable);
+    return PlainTextRange::create(*editable, *range.get());
 }
 
-bool InputMethodController::setSelectionOffsets(const PlainTextOffsets& selectionOffsets)
+bool InputMethodController::setSelectionOffsets(const PlainTextRange& selectionOffsets)
 {
     if (selectionOffsets.isNull())
         return false;
@@ -395,14 +375,14 @@
     if (!rootEditableElement)
         return false;
 
-    RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(rootEditableElement, selectionOffsets.start(), selectionOffsets.end() - selectionOffsets.start());
+    RefPtr<Range> range = selectionOffsets.createRange(*rootEditableElement);
     if (!range)
         return false;
 
     return m_frame.selection().setSelectedRange(range.get(), VP_DEFAULT_AFFINITY, true);
 }
 
-bool InputMethodController::setEditableSelectionOffsets(const PlainTextOffsets& selectionOffsets)
+bool InputMethodController::setEditableSelectionOffsets(const PlainTextRange& selectionOffsets)
 {
     if (!editor().canEdit())
         return false;
@@ -413,10 +393,10 @@
 {
     if (!editor().canEdit())
         return;
-    PlainTextOffsets selectionOffsets = getSelectionOffsets();
+    PlainTextRange selectionOffsets(getSelectionOffsets());
     if (selectionOffsets.isNull())
         return;
-    setSelectionOffsets(PlainTextOffsets(std::max(static_cast<int>(selectionOffsets.start()) - before, 0), selectionOffsets.end() + after));
+    setSelectionOffsets(PlainTextRange(std::max(static_cast<int>(selectionOffsets.start()) - before, 0), selectionOffsets.end() + after));
     TypingCommand::deleteSelection(*m_frame.document());
 }
 
diff --git a/Source/core/editing/InputMethodController.h b/Source/core/editing/InputMethodController.h
index b6bf105..7b49c4f 100644
--- a/Source/core/editing/InputMethodController.h
+++ b/Source/core/editing/InputMethodController.h
@@ -27,6 +27,7 @@
 #define InputMethodController_h
 
 #include "core/editing/CompositionUnderline.h"
+#include "core/editing/PlainTextRange.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
@@ -37,21 +38,6 @@
 class Range;
 class Text;
 
-// FIXME: We should move PlainTextOffsets to own file for using InputMethodController
-// and TextIterator and unify PlainTextRange defined in AXObject.h.
-class PlainTextOffsets {
-public:
-    PlainTextOffsets();
-    PlainTextOffsets(int start, int length);
-    size_t end() const { return m_end; }
-    size_t start() const { return m_start; }
-    bool isNull() const { return m_start == kNotFound; }
-    size_t length() const { ASSERT(!isNull()); return m_end - m_start; }
-private:
-    size_t m_start;
-    size_t m_end;
-};
-
 class InputMethodController {
     WTF_MAKE_NONCOPYABLE(InputMethodController);
 public:
@@ -91,9 +77,9 @@
 
     void clear();
 
-    PlainTextOffsets getSelectionOffsets() const;
+    PlainTextRange getSelectionOffsets() const;
     // Returns true if setting selection to specified offsets, otherwise false.
-    bool setEditableSelectionOffsets(const PlainTextOffsets&);
+    bool setEditableSelectionOffsets(const PlainTextRange&);
     void extendSelectionAndDelete(int before, int after);
 
 private:
@@ -104,14 +90,13 @@
         ~SelectionOffsetsScope();
     private:
         InputMethodController* m_inputMethodController;
-        PlainTextOffsets m_offsets;
+        const PlainTextRange m_offsets;
     };
     friend class SelectionOffsetsScope;
 
     Frame& m_frame;
     RefPtr<Text> m_compositionNode;
-    // FIXME: We should use PlainTextOffsets m_compositionRange instead of
-    // m_compositionStart/m_compositionEnd.
+    // We don't use PlainTextRange which is immutable, for composition range.
     unsigned m_compositionStart;
     unsigned m_compositionEnd;
     // startOffset and endOffset of CompositionUnderline are based on
@@ -126,7 +111,7 @@
     enum FinishCompositionMode { ConfirmComposition, CancelComposition };
     // Returns true if composition exists.
     bool finishComposition(const String&, FinishCompositionMode);
-    bool setSelectionOffsets(const PlainTextOffsets&);
+    bool setSelectionOffsets(const PlainTextRange&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/editing/InsertNodeBeforeCommand.cpp b/Source/core/editing/InsertNodeBeforeCommand.cpp
index d30ea73..862d541 100644
--- a/Source/core/editing/InsertNodeBeforeCommand.cpp
+++ b/Source/core/editing/InsertNodeBeforeCommand.cpp
@@ -43,7 +43,7 @@
     ASSERT(m_refChild);
     ASSERT(m_refChild->parentNode());
 
-    ASSERT(m_refChild->parentNode()->rendererIsEditable() || !m_refChild->parentNode()->confusingAndOftenMisusedAttached());
+    ASSERT(m_refChild->parentNode()->rendererIsEditable() || !m_refChild->parentNode()->inActiveDocument());
 }
 
 void InsertNodeBeforeCommand::doApply()
diff --git a/Source/core/editing/PlainTextRange.cpp b/Source/core/editing/PlainTextRange.cpp
new file mode 100644
index 0000000..82f3215
--- /dev/null
+++ b/Source/core/editing/PlainTextRange.cpp
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2005 Alexey Proskuryakov.
+ *
+ * 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/PlainTextRange.h"
+
+#include "core/dom/ContainerNode.h"
+#include "core/dom/Document.h"
+#include "core/dom/Range.h"
+#include "core/editing/TextIterator.h"
+#include "core/editing/VisiblePosition.h"
+
+namespace WebCore {
+
+PlainTextRange::PlainTextRange()
+    : m_start(kNotFound)
+    , m_end(kNotFound)
+{
+}
+
+PlainTextRange::PlainTextRange(int location)
+    : m_start(location)
+    , m_end(location)
+{
+    ASSERT(location >= 0);
+}
+
+PlainTextRange::PlainTextRange(int start, int end)
+    : m_start(start)
+    , m_end(end)
+{
+    ASSERT(start >= 0);
+    ASSERT(end >= 0);
+    ASSERT(start <= end);
+}
+
+PassRefPtr<Range> PlainTextRange::createRange(const ContainerNode& scope) const
+{
+    return createRangeFor(scope, ForGeneric);
+}
+
+PassRefPtr<Range> PlainTextRange::createRangeForSelection(const ContainerNode& scope) const
+{
+    return createRangeFor(scope, ForSelection);
+}
+
+PassRefPtr<Range> PlainTextRange::createRangeFor(const ContainerNode& scope, GetRangeFor getRangeFor) const
+{
+    ASSERT(isNotNull());
+
+    RefPtr<Range> resultRange = scope.document().createRange();
+
+    size_t docTextPosition = 0;
+    bool startRangeFound = false;
+
+    RefPtr<Range> textRunRange;
+
+    TextIterator it(rangeOfContents(const_cast<ContainerNode*>(&scope)).get(), getRangeFor == ForSelection ? TextIteratorEmitsCharactersBetweenAllVisiblePositions : TextIteratorDefaultBehavior);
+
+    // FIXME: the atEnd() check shouldn't be necessary, workaround for <http://bugs.webkit.org/show_bug.cgi?id=6289>.
+    if (!start() && !length() && it.atEnd()) {
+        textRunRange = it.range();
+
+        resultRange->setStart(textRunRange->startContainer(), 0, ASSERT_NO_EXCEPTION);
+        resultRange->setEnd(textRunRange->startContainer(), 0, ASSERT_NO_EXCEPTION);
+
+        return resultRange.release();
+    }
+
+    for (; !it.atEnd(); it.advance()) {
+        int len = it.length();
+        textRunRange = it.range();
+
+        bool foundStart = start() >= docTextPosition && start() <= docTextPosition + len;
+        bool foundEnd = end() >= docTextPosition && end() <= docTextPosition + len;
+
+        // Fix textRunRange->endPosition(), but only if foundStart || foundEnd, because it is only
+        // in those cases that textRunRange is used.
+        if (foundEnd) {
+            // FIXME: This is a workaround for the fact that the end of a run is often at the wrong
+            // position for emitted '\n's.
+            if (len == 1 && it.characterAt(0) == '\n') {
+                scope.document().updateLayoutIgnorePendingStylesheets();
+                it.advance();
+                if (!it.atEnd()) {
+                    RefPtr<Range> range = it.range();
+                    textRunRange->setEnd(range->startContainer(), range->startOffset(), ASSERT_NO_EXCEPTION);
+                } else {
+                    Position runStart = textRunRange->startPosition();
+                    Position runEnd = VisiblePosition(runStart).next().deepEquivalent();
+                    if (runEnd.isNotNull())
+                        textRunRange->setEnd(runEnd.containerNode(), runEnd.computeOffsetInContainerNode(), ASSERT_NO_EXCEPTION);
+                }
+            }
+        }
+
+        if (foundStart) {
+            startRangeFound = true;
+            if (textRunRange->startContainer()->isTextNode()) {
+                int offset = start() - docTextPosition;
+                resultRange->setStart(textRunRange->startContainer(), offset + textRunRange->startOffset(), IGNORE_EXCEPTION);
+            } else {
+                if (start() == docTextPosition)
+                    resultRange->setStart(textRunRange->startContainer(), textRunRange->startOffset(), IGNORE_EXCEPTION);
+                else
+                    resultRange->setStart(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
+            }
+        }
+
+        if (foundEnd) {
+            if (textRunRange->startContainer()->isTextNode()) {
+                int offset = end() - docTextPosition;
+                resultRange->setEnd(textRunRange->startContainer(), offset + textRunRange->startOffset(), IGNORE_EXCEPTION);
+            } else {
+                if (end() == docTextPosition)
+                    resultRange->setEnd(textRunRange->startContainer(), textRunRange->startOffset(), IGNORE_EXCEPTION);
+                else
+                    resultRange->setEnd(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
+            }
+            docTextPosition += len;
+            break;
+        }
+        docTextPosition += len;
+    }
+
+    if (!startRangeFound)
+        return 0;
+
+    if (length() && end() > docTextPosition) { // end() is out of bounds
+        resultRange->setEnd(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
+    }
+
+    return resultRange.release();
+}
+
+PlainTextRange PlainTextRange::create(const Node& scope, const Range& range)
+{
+    if (!range.startContainer())
+        return PlainTextRange();
+
+    // The critical assumption is that this only gets called with ranges that
+    // concentrate on a given area containing the selection root. This is done
+    // because of text fields and textareas. The DOM for those is not
+    // directly in the document DOM, so ensure that the range does not cross a
+    // boundary of one of those.
+    if (range.startContainer() != &scope && !range.startContainer()->isDescendantOf(&scope))
+        return PlainTextRange();
+    if (range.endContainer() != scope && !range.endContainer()->isDescendantOf(&scope))
+        return PlainTextRange();
+
+    RefPtr<Range> testRange = Range::create(scope.document(), const_cast<Node*>(&scope), 0, range.startContainer(), range.startOffset());
+    ASSERT(testRange->startContainer() == &scope);
+    size_t start = TextIterator::rangeLength(testRange.get());
+
+    testRange->setEnd(range.endContainer(), range.endOffset(), IGNORE_EXCEPTION);
+    ASSERT(testRange->startContainer() == &scope);
+    size_t end = TextIterator::rangeLength(testRange.get());
+
+    return PlainTextRange(start, end);
+}
+
+}
diff --git a/Source/core/editing/PlainTextRange.h b/Source/core/editing/PlainTextRange.h
new file mode 100644
index 0000000..faf200a
--- /dev/null
+++ b/Source/core/editing/PlainTextRange.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2006, 2007, 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.
+ */
+
+#ifndef PlainTextRange_h
+#define PlainTextRange_h
+
+#include "wtf/NotFound.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class ContainerNode;
+class Node;
+class Range;
+
+class PlainTextRange {
+public:
+    PlainTextRange();
+    PlainTextRange(const PlainTextRange&);
+    explicit PlainTextRange(int location);
+    PlainTextRange(int start, int end);
+
+    size_t end() const { ASSERT(!isNull()); return m_end; }
+    size_t start() const { ASSERT(!isNull()); return m_start; }
+    bool isNull() const { return m_start == kNotFound; }
+    bool isNotNull() const { return m_start != kNotFound; }
+    size_t length() const { ASSERT(!isNull()); return m_end - m_start; }
+
+    PassRefPtr<Range> createRange(const ContainerNode& scope) const;
+    PassRefPtr<Range> createRangeForSelection(const ContainerNode& scope) const;
+
+    static PlainTextRange create(const Node& scope, const Range&);
+
+private:
+    PlainTextRange& operator=(const PlainTextRange&)  WTF_DELETED_FUNCTION;
+
+    enum GetRangeFor { ForGeneric, ForSelection };
+    PassRefPtr<Range> createRangeFor(const ContainerNode& scope, GetRangeFor) const;
+
+    const size_t m_start;
+    const size_t m_end;
+};
+
+} // namespace WebCore
+
+#endif // PlainTextRange_h
diff --git a/Source/core/editing/RemoveNodeCommand.cpp b/Source/core/editing/RemoveNodeCommand.cpp
index 4fca7bd..cffc8c0 100644
--- a/Source/core/editing/RemoveNodeCommand.cpp
+++ b/Source/core/editing/RemoveNodeCommand.cpp
@@ -45,9 +45,9 @@
 {
     ContainerNode* parent = m_node->parentNode();
     if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable
-        && !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->confusingAndOftenMisusedAttached()))
+        && !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->inActiveDocument()))
         return;
-    ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->confusingAndOftenMisusedAttached());
+    ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->inActiveDocument());
 
     m_parent = parent;
     m_refChild = m_node->nextSibling();
diff --git a/Source/core/editing/ReplaceSelectionCommand.cpp b/Source/core/editing/ReplaceSelectionCommand.cpp
index aa05391..92e69b6 100644
--- a/Source/core/editing/ReplaceSelectionCommand.cpp
+++ b/Source/core/editing/ReplaceSelectionCommand.cpp
@@ -475,7 +475,7 @@
         if (!node->isStyledElement())
             continue;
 
-        Element* element = toElement(node.get());
+        Element* element = toElement(node);
 
         const StylePropertySet* inlineStyle = element->inlineStyle();
         RefPtr<EditingStyle> newInlineStyle = EditingStyle::create(inlineStyle);
@@ -487,7 +487,7 @@
                 if (newInlineStyle->conflictsWithImplicitStyleOfElement(htmlElement)) {
                     // e.g. <b style="font-weight: normal;"> is converted to <span style="font-weight: normal;">
                     node = replaceElementWithSpanPreservingChildrenAndAttributes(htmlElement);
-                    element = toElement(node.get());
+                    element = toElement(node);
                     insertedNodes.didReplaceNode(htmlElement, node.get());
                 } else if (newInlineStyle->extractConflictingImplicitStyleOfAttributes(htmlElement, EditingStyle::PreserveWritingDirection, 0, attributes,
                     EditingStyle::DoNotExtractMatchingStyle)) {
@@ -621,7 +621,7 @@
         if (!node->isHTMLElement())
             continue;
 
-        if (isProhibitedParagraphChild(toHTMLElement(node.get())->localName())) {
+        if (isProhibitedParagraphChild(toHTMLElement(node)->localName())) {
             if (HTMLElement* paragraphElement = toHTMLElement(enclosingNodeWithTag(positionInParentBeforeNode(node.get()), pTag)))
                 moveNodeOutOfAncestor(node, paragraphElement);
         }
@@ -1074,7 +1074,7 @@
     Node* blockStart = enclosingBlock(insertionPos.deprecatedNode());
     if ((isListElement(refNode.get()) || (isLegacyAppleStyleSpan(refNode.get()) && isListElement(refNode->firstChild())))
         && blockStart && blockStart->renderer()->isListItem())
-        refNode = insertAsListItems(toHTMLElement(refNode.get()), blockStart, insertionPos, insertedNodes);
+        refNode = insertAsListItems(toHTMLElement(refNode), blockStart, insertionPos, insertedNodes);
     else {
         insertNodeAt(refNode, insertionPos);
         insertedNodes.respondToNodeInsertion(refNode.get());
diff --git a/Source/core/editing/SpellChecker.cpp b/Source/core/editing/SpellChecker.cpp
index 6520f41..ea460e7 100644
--- a/Source/core/editing/SpellChecker.cpp
+++ b/Source/core/editing/SpellChecker.cpp
@@ -95,7 +95,7 @@
     editorClient().toggleContinuousSpellChecking();
     if (isContinuousSpellCheckingEnabled())
         return;
-    for (Frame* frame = m_frame.page()->mainFrame(); frame && frame->document(); frame = frame->tree()->traverseNext()) {
+    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)) {
             node->setAlreadySpellChecked(false);
         }
diff --git a/Source/core/editing/TextIterator.cpp b/Source/core/editing/TextIterator.cpp
index 138e8fe..6707368 100644
--- a/Source/core/editing/TextIterator.cpp
+++ b/Source/core/editing/TextIterator.cpp
@@ -318,7 +318,7 @@
     if (m_needsAnotherNewline) {
         // Emit the extra newline, and position it *inside* m_node, after m_node's
         // contents, in case it's a block, in the same way that we position the first
-        // newline.  The range for the emitted newline should start where the line
+        // newline. The range for the emitted newline should start where the line
         // break begins.
         // FIXME: It would be cleaner if we emitted two newlines during the last
         // iteration, instead of using m_needsAnotherNewline.
@@ -349,7 +349,7 @@
         // position, but not the content, of that element e.g. if the
         // node is a blockflow element, emit a newline that
         // precedes the element
-        if (m_node == m_endContainer && m_endOffset == 0) {
+        if (m_node == m_endContainer && !m_endOffset) {
             representNodeOffsetZero();
             m_node = 0;
             return;
@@ -362,17 +362,18 @@
         } else {
             // handle current node according to its type
             if (!m_handledNode) {
-                if (renderer->isText() && m_node->nodeType() == Node::TEXT_NODE) // FIXME: What about CDATA_SECTION_NODE?
+                if (renderer->isText() && m_node->nodeType() == Node::TEXT_NODE) { // FIXME: What about CDATA_SECTION_NODE?
                     m_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)))))
+                } 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_handledNode = handleReplacedElement();
-                else
+                } else {
                     m_handledNode = handleNonTextNode();
+                }
                 if (m_positionNode)
                     return;
             }
@@ -560,8 +561,9 @@
                 while (spaceRunStart > 0 && str[spaceRunStart - 1] == ' ')
                     --spaceRunStart;
                 emitText(m_node, renderer, spaceRunStart, spaceRunStart + 1);
-            } else
+            } else {
                 emitCharacter(' ', m_node, 0, runStart, runStart);
+            }
             return;
         }
         unsigned textBoxEnd = textBoxStart + m_textBox->len();
@@ -572,8 +574,9 @@
         if (renderer->containsReversedText()) {
             if (m_sortedTextBoxesPosition + 1 < m_sortedTextBoxes.size())
                 nextTextBox = m_sortedTextBoxes[m_sortedTextBoxesPosition + 1];
-        } else
+        } else {
             nextTextBox = m_textBox->nextTextBox();
+        }
         ASSERT(!nextTextBox || nextTextBox->renderer() == renderer);
 
         if (runStart < runEnd) {
@@ -751,24 +754,24 @@
     RenderObject* r = node->renderer();
     if (!r) {
         return (node->hasTagName(blockquoteTag)
-                || node->hasTagName(ddTag)
-                || node->hasTagName(divTag)
-                || node->hasTagName(dlTag)
-                || node->hasTagName(dtTag)
-                || node->hasTagName(h1Tag)
-                || node->hasTagName(h2Tag)
-                || node->hasTagName(h3Tag)
-                || node->hasTagName(h4Tag)
-                || node->hasTagName(h5Tag)
-                || node->hasTagName(h6Tag)
-                || node->hasTagName(hrTag)
-                || node->hasTagName(liTag)
-                || node->hasTagName(listingTag)
-                || node->hasTagName(olTag)
-                || node->hasTagName(pTag)
-                || node->hasTagName(preTag)
-                || node->hasTagName(trTag)
-                || node->hasTagName(ulTag));
+            || node->hasTagName(ddTag)
+            || node->hasTagName(divTag)
+            || node->hasTagName(dlTag)
+            || node->hasTagName(dtTag)
+            || node->hasTagName(h1Tag)
+            || node->hasTagName(h2Tag)
+            || node->hasTagName(h3Tag)
+            || node->hasTagName(h4Tag)
+            || node->hasTagName(h5Tag)
+            || node->hasTagName(h6Tag)
+            || node->hasTagName(hrTag)
+            || node->hasTagName(liTag)
+            || node->hasTagName(listingTag)
+            || node->hasTagName(olTag)
+            || node->hasTagName(pTag)
+            || node->hasTagName(preTag)
+            || node->hasTagName(trTag)
+            || node->hasTagName(ulTag));
     }
 
     // Need to make an exception for table cells, because they are blocks, but we
@@ -795,9 +798,10 @@
         return false;
     // Check if this is the very last renderer in the document.
     // If so, then we should not emit a newline.
-    while ((node = NodeTraversal::nextSkippingChildren(node)))
+    while ((node = NodeTraversal::nextSkippingChildren(node))) {
         if (node->renderer())
             return true;
+    }
     return false;
 }
 
@@ -809,7 +813,7 @@
 static bool shouldEmitExtraNewlineForNode(Node* node)
 {
     // When there is a significant collapsed bottom margin, emit an extra
-    // newline for a more realistic result.  We end up getting the right
+    // newline for a more realistic result. We end up getting the right
     // result even without margin collapsing. For example: <div><p>text</p></div>
     // will work right even if both the <div> and the <p> have bottom margins.
     RenderObject* r = node->renderer();
@@ -897,7 +901,7 @@
     // so don't second guess that now.
     // NOTE: Is this really correct when m_node is not a leftmost descendant? Probably
     // immaterial since we likely would have already emitted something by now.
-    if (m_startOffset == 0)
+    if (!m_startOffset)
         return false;
 
     // If this node is unrendered or invisible the VisiblePosition checks below won't have much meaning.
@@ -926,7 +930,7 @@
     // Emit a character to show the positioning of m_node.
 
     // When we haven't been emitting any characters, shouldRepresentNodeOffsetZero() can
-    // create VisiblePositions, which is expensive.  So, we perform the inexpensive checks
+    // create VisiblePositions, which is expensive. So, we perform the inexpensive checks
     // on m_node to see if it necessitates emitting a character first and will early return
     // before encountering shouldRepresentNodeOffsetZero()s worse case behavior.
     if (shouldEmitTabBeforeNode(m_node)) {
@@ -967,7 +971,7 @@
     // emitted character is positioned visually.
     Node* baseNode = m_node->lastChild() ? m_node->lastChild() : m_node;
     // FIXME: This shouldn't require the m_lastTextNode to be true, but we can't change that without making
-    // the logic in _web_attributedStringFromRange match.  We'll get that for free when we switch to use
+    // the logic in _web_attributedStringFromRange match. We'll get that for free when we switch to use
     // TextIterator in _web_attributedStringFromRange.
     // See <rdar://problem/5428427> for an example of how this mismatch will cause problems.
     if (m_lastTextNode && shouldEmitNewlineAfterNode(m_node)) {
@@ -982,9 +986,10 @@
             // remember whether to later add a newline for the current node
             ASSERT(!m_needsAnotherNewline);
             m_needsAnotherNewline = addNewline;
-        } else if (addNewline)
+        } else if (addNewline) {
             // insert a newline with a position following this block's contents.
             emitCharacter('\n', baseNode->parentNode(), baseNode, 1, 1);
+        }
     }
 
     // If nothing was emitted, see if we need to emit a space.
@@ -1128,7 +1133,7 @@
     setUpFullyClippedStack(m_fullyClippedStack, m_node);
     m_offset = endOffset;
     m_handledNode = false;
-    m_handledChildren = endOffset == 0;
+    m_handledChildren = !endOffset;
 
     m_startNode = startNode;
     m_startOffset = startOffset;
@@ -1165,7 +1170,7 @@
 
     while (m_node && !m_havePassedStartNode) {
         // Don't handle node if we start iterating at [node, 0].
-        if (!m_handledNode && !(m_node == m_endNode && m_endOffset == 0)) {
+        if (!m_handledNode && !(m_node == m_endNode && !m_endOffset)) {
             RenderObject* renderer = m_node->renderer();
             if (renderer && renderer->isText() && m_node->nodeType() == Node::TEXT_NODE) {
                 // FIXME: What about CDATA_SECTION_NODE?
@@ -1174,8 +1179,9 @@
             } else if (renderer && (renderer->isImage() || renderer->isWidget())) {
                 if (renderer->style()->visibility() == VISIBLE && m_offset > 0)
                     m_handledNode = handleReplacedElement();
-            } else
+            } else {
                 m_handledNode = handleNonTextNode();
+            }
             if (m_positionNode)
                 return;
         }
@@ -1187,9 +1193,9 @@
             // Exit empty containers as we pass over them or containers
             // where [container, 0] is where we started iterating.
             if (!m_handledNode
-                    && canHaveChildrenForEditing(m_node)
-                    && m_node->parentNode()
-                    && (!m_node->lastChild() || (m_node == m_endNode && !m_endOffset))) {
+                && canHaveChildrenForEditing(m_node)
+                && m_node->parentNode()
+                && (!m_node->lastChild() || (m_node == m_endNode && !m_endOffset))) {
                 exitNode();
                 if (m_positionNode) {
                     m_handledNode = true;
@@ -1297,7 +1303,7 @@
     unsigned index = m_node->nodeIndex();
     // We want replaced elements to behave like punctuation for boundary
     // finding, and to simply take up space for the selection preservation
-    // code in moveParagraphs, so we use a comma.  Unconditionally emit
+    // code in moveParagraphs, so we use a comma. Unconditionally emit
     // here because this iterator is only used for boundary finding.
     emitCharacter(',', m_node->parentNode(), index, index + 1);
     return true;
@@ -1306,7 +1312,7 @@
 bool SimplifiedBackwardsTextIterator::handleNonTextNode()
 {
     // We can use a linefeed in place of a tab because this simple iterator is only used to
-    // find boundaries, not actual content.  A linefeed breaks words, sentences, and paragraphs.
+    // find boundaries, not actual content. A linefeed breaks words, sentences, and paragraphs.
     if (shouldEmitNewlineForNode(m_node, m_emitsOriginalText) || shouldEmitNewlineAfterNode(m_node) || shouldEmitTabBeforeNode(m_node)) {
         unsigned index = m_node->nodeIndex();
         // The start of this emitted range is wrong. Ensuring correctness would require
@@ -1363,7 +1369,7 @@
     , m_atBreak(true)
     , m_textIterator(r, behavior)
 {
-    while (!atEnd() && m_textIterator.length() == 0)
+    while (!atEnd() && !m_textIterator.length())
         m_textIterator.advance();
 }
 
@@ -1372,7 +1378,7 @@
     RefPtr<Range> r = m_textIterator.range();
     if (!m_textIterator.atEnd()) {
         if (m_textIterator.length() <= 1) {
-            ASSERT(m_runOffset == 0);
+            ASSERT(!m_runOffset);
         } else {
             Node* n = r->startContainer();
             ASSERT(n == r->endContainer());
@@ -1387,7 +1393,7 @@
 void CharacterIterator::advance(int count)
 {
     if (count <= 0) {
-        ASSERT(count == 0);
+        ASSERT(!count);
         return;
     }
 
@@ -1408,9 +1414,9 @@
     // move to a subsequent m_textIterator run
     for (m_textIterator.advance(); !atEnd(); m_textIterator.advance()) {
         int runLength = m_textIterator.length();
-        if (runLength == 0)
+        if (!runLength) {
             m_atBreak = true;
-        else {
+        } else {
             // see whether this is m_textIterator to use
             if (count < runLength) {
                 m_runOffset = count;
@@ -1470,9 +1476,9 @@
 {
     RefPtr<Range> r = m_textIterator.range();
     if (!m_textIterator.atEnd()) {
-        if (m_textIterator.length() <= 1)
-            ASSERT(m_runOffset == 0);
-        else {
+        if (m_textIterator.length() <= 1) {
+            ASSERT(!m_runOffset);
+        } else {
             Node* n = r->startContainer();
             ASSERT(n == r->endContainer());
             int offset = r->endOffset() - m_runOffset;
@@ -1504,9 +1510,9 @@
 
     for (m_textIterator.advance(); !atEnd(); m_textIterator.advance()) {
         int runLength = m_textIterator.length();
-        if (runLength == 0)
+        if (!runLength) {
             m_atBreak = true;
-        else {
+        } else {
             if (count < runLength) {
                 m_runOffset = count;
                 m_offset += count;
@@ -1549,7 +1555,7 @@
     m_didLookAhead = false;
 
     // Go to next non-empty chunk.
-    while (!m_textIterator.atEnd() && m_textIterator.length() == 0)
+    while (!m_textIterator.atEnd() && !m_textIterator.length())
         m_textIterator.advance();
 
     m_range = m_textIterator.range();
@@ -1605,20 +1611,20 @@
 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;
+    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;
     }
 }
 
@@ -2230,122 +2236,6 @@
     return characterSubrange(entireRangeIterator, characterOffset, characterCount);
 }
 
-PassRefPtr<Range> TextIterator::rangeFromLocationAndLength(ContainerNode* scope, int rangeLocation, int rangeLength, bool forSelectionPreservation)
-{
-    RefPtr<Range> resultRange = scope->document().createRange();
-
-    int docTextPosition = 0;
-    int rangeEnd = rangeLocation + rangeLength;
-    bool startRangeFound = false;
-
-    RefPtr<Range> textRunRange;
-
-    TextIterator it(rangeOfContents(scope).get(), forSelectionPreservation ? TextIteratorEmitsCharactersBetweenAllVisiblePositions : TextIteratorDefaultBehavior);
-
-    // FIXME: the atEnd() check shouldn't be necessary, workaround for <http://bugs.webkit.org/show_bug.cgi?id=6289>.
-    if (rangeLocation == 0 && rangeLength == 0 && it.atEnd()) {
-        textRunRange = it.range();
-
-        resultRange->setStart(textRunRange->startContainer(), 0, ASSERT_NO_EXCEPTION);
-        resultRange->setEnd(textRunRange->startContainer(), 0, ASSERT_NO_EXCEPTION);
-
-        return resultRange.release();
-    }
-
-    for (; !it.atEnd(); it.advance()) {
-        int len = it.length();
-        textRunRange = it.range();
-
-        bool foundStart = rangeLocation >= docTextPosition && rangeLocation <= docTextPosition + len;
-        bool foundEnd = rangeEnd >= docTextPosition && rangeEnd <= docTextPosition + len;
-
-        // Fix textRunRange->endPosition(), but only if foundStart || foundEnd, because it is only
-        // in those cases that textRunRange is used.
-        if (foundEnd) {
-            // FIXME: This is a workaround for the fact that the end of a run is often at the wrong
-            // position for emitted '\n's.
-            if (len == 1 && it.characterAt(0) == '\n') {
-                scope->document().updateLayoutIgnorePendingStylesheets();
-                it.advance();
-                if (!it.atEnd()) {
-                    RefPtr<Range> range = it.range();
-                    textRunRange->setEnd(range->startContainer(), range->startOffset(), ASSERT_NO_EXCEPTION);
-                } else {
-                    Position runStart = textRunRange->startPosition();
-                    Position runEnd = VisiblePosition(runStart).next().deepEquivalent();
-                    if (runEnd.isNotNull())
-                        textRunRange->setEnd(runEnd.containerNode(), runEnd.computeOffsetInContainerNode(), ASSERT_NO_EXCEPTION);
-                }
-            }
-        }
-
-        if (foundStart) {
-            startRangeFound = true;
-            if (textRunRange->startContainer()->isTextNode()) {
-                int offset = rangeLocation - docTextPosition;
-                resultRange->setStart(textRunRange->startContainer(), offset + textRunRange->startOffset(), IGNORE_EXCEPTION);
-            } else {
-                if (rangeLocation == docTextPosition)
-                    resultRange->setStart(textRunRange->startContainer(), textRunRange->startOffset(), IGNORE_EXCEPTION);
-                else
-                    resultRange->setStart(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
-            }
-        }
-
-        if (foundEnd) {
-            if (textRunRange->startContainer()->isTextNode()) {
-                int offset = rangeEnd - docTextPosition;
-                resultRange->setEnd(textRunRange->startContainer(), offset + textRunRange->startOffset(), IGNORE_EXCEPTION);
-            } else {
-                if (rangeEnd == docTextPosition)
-                    resultRange->setEnd(textRunRange->startContainer(), textRunRange->startOffset(), IGNORE_EXCEPTION);
-                else
-                    resultRange->setEnd(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
-            }
-            docTextPosition += len;
-            break;
-        }
-        docTextPosition += len;
-    }
-
-    if (!startRangeFound)
-        return 0;
-
-    if (rangeLength != 0 && rangeEnd > docTextPosition) { // rangeEnd is out of bounds
-        resultRange->setEnd(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
-    }
-
-    return resultRange.release();
-}
-
-bool TextIterator::getLocationAndLengthFromRange(Node* scope, const Range* range, size_t& location, size_t& length)
-{
-    location = kNotFound;
-    length = 0;
-
-    if (!range->startContainer())
-        return false;
-
-    // The critical assumption is that this only gets called with ranges that
-    // concentrate on a given area containing the selection root. This is done
-    // because of text fields and textareas. The DOM for those is not
-    // directly in the document DOM, so ensure that the range does not cross a
-    // boundary of one of those.
-    if (range->startContainer() != scope && !range->startContainer()->isDescendantOf(scope))
-        return false;
-    if (range->endContainer() != scope && !range->endContainer()->isDescendantOf(scope))
-        return false;
-
-    RefPtr<Range> testRange = Range::create(scope->document(), scope, 0, range->startContainer(), range->startOffset());
-    ASSERT(testRange->startContainer() == scope);
-    location = TextIterator::rangeLength(testRange.get());
-
-    testRange->setEnd(range->endContainer(), range->endOffset(), IGNORE_EXCEPTION);
-    ASSERT(testRange->startContainer() == scope);
-    length = TextIterator::rangeLength(testRange.get()) - location;
-    return true;
-}
-
 // --------
 
 String plainText(const Range* r, TextIteratorBehavior defaultBehavior)
diff --git a/Source/core/editing/TextIterator.h b/Source/core/editing/TextIterator.h
index b8b1e35..2e2d2cc 100644
--- a/Source/core/editing/TextIterator.h
+++ b/Source/core/editing/TextIterator.h
@@ -116,8 +116,6 @@
     Node* node() const;
 
     static int rangeLength(const Range*, bool spacesForReplacedElements = false);
-    static PassRefPtr<Range> rangeFromLocationAndLength(ContainerNode* scope, int rangeLocation, int rangeLength, bool spacesForReplacedElements = false);
-    static bool getLocationAndLengthFromRange(Node* scope, const Range*, size_t& location, size_t& length);
     static PassRefPtr<Range> subrange(Range* entireRange, int characterOffset, int characterCount);
 
 private:
diff --git a/Source/core/editing/TypingCommand.cpp b/Source/core/editing/TypingCommand.cpp
index 596265b..042d0a8 100644
--- a/Source/core/editing/TypingCommand.cpp
+++ b/Source/core/editing/TypingCommand.cpp
@@ -484,10 +484,10 @@
 
     if (killRing)
         frame->editor().addToKillRing(selectionToDelete.toNormalizedRange().get(), false);
-    // Make undo select everything that has been deleted, unless an undo will undo more than just this deletion.
+    // On Mac, make undo select everything that has been deleted, unless an undo will undo more than just this deletion.
     // FIXME: This behaves like TextEdit except for the case where you open with text insertion and then delete
     // more text than you insert.  In that case all of the text that was around originally should be selected.
-    if (m_openedByBackwardDelete)
+    if (frame->editor().behavior().shouldUndoOfDeleteSelectText() && m_openedByBackwardDelete)
         setStartingSelection(selectionAfterUndo);
     CompositeEditCommand::deleteSelection(selectionToDelete, m_smartDelete);
     setSmartDelete(false);
@@ -577,8 +577,9 @@
 
     if (killRing)
         frame->editor().addToKillRing(selectionToDelete.toNormalizedRange().get(), false);
-    // make undo select what was deleted
-    setStartingSelection(selectionAfterUndo);
+    // Make undo select what was deleted on Mac alone
+    if (frame->editor().behavior().shouldUndoOfDeleteSelectText())
+        setStartingSelection(selectionAfterUndo);
     CompositeEditCommand::deleteSelection(selectionToDelete, m_smartDelete);
     setSmartDelete(false);
     typingAddedToOpenCommand(ForwardDeleteKey);
diff --git a/Source/core/editing/htmlediting.cpp b/Source/core/editing/htmlediting.cpp
index 26fa599..ce132c1 100644
--- a/Source/core/editing/htmlediting.cpp
+++ b/Source/core/editing/htmlediting.cpp
@@ -38,6 +38,7 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
 #include "core/editing/HTMLInterchange.h"
+#include "core/editing/PlainTextRange.h"
 #include "core/editing/TextIterator.h"
 #include "core/editing/VisiblePosition.h"
 #include "core/editing/VisibleSelection.h"
@@ -1060,7 +1061,9 @@
 
 VisiblePosition visiblePositionForIndex(int index, ContainerNode* scope)
 {
-    RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(scope, index, 0, true);
+    if (!scope)
+        return VisiblePosition();
+    RefPtr<Range> range = PlainTextRange(index).createRangeForSelection(*scope);
     // Check for an invalid index. Certain editing operations invalidate indices because
     // of problems with TextIteratorEmitsCharactersBetweenAllVisiblePositions.
     if (!range)
diff --git a/Source/core/editing/markup.cpp b/Source/core/editing/markup.cpp
index 5d233ea..1d7b8b4 100644
--- a/Source/core/editing/markup.cpp
+++ b/Source/core/editing/markup.cpp
@@ -32,6 +32,7 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSValue.h"
@@ -942,7 +943,7 @@
     return markup.toString();
 }
 
-PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, ExceptionState& es)
+PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& es)
 {
     Document& document = contextElement->hasTagName(templateTag) ? contextElement->document().ensureTemplateDocument() : contextElement->document();
     RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
@@ -954,7 +955,7 @@
 
     bool wasValid = fragment->parseXML(markup, contextElement, parserContentPolicy);
     if (!wasValid) {
-        es.throwUninformativeAndGenericDOMException(SyntaxError);
+        es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute(method, "Node", "The provided markup is invalid XML, and therefore cannot be inserted into an XML document."));
         return 0;
     }
     return fragment.release();
@@ -998,18 +999,13 @@
 PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& es)
 {
     ASSERT(element);
-    if (element->ieForbidsInsertHTML()) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-
-    if (element->hasLocalName(colTag) || element->hasLocalName(colgroupTag) || element->hasLocalName(framesetTag)
+    if (element->ieForbidsInsertHTML() || element->hasLocalName(colTag) || element->hasLocalName(colgroupTag) || element->hasLocalName(framesetTag)
         || element->hasLocalName(headTag) || element->hasLocalName(styleTag) || element->hasLocalName(titleTag)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range's container is '" + element->localName() + "', which is not supported."));
         return 0;
     }
 
-    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, es);
+    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", es);
     if (!fragment)
         return 0;
 
@@ -1021,7 +1017,7 @@
     for (RefPtr<Node> node = fragment->firstChild(); node; node = nextNode) {
         nextNode = node->nextSibling();
         if (isHTMLHtmlElement(node.get()) || node->hasTagName(headTag) || node->hasTagName(bodyTag)) {
-            HTMLElement* element = toHTMLElement(node.get());
+            HTMLElement* element = toHTMLElement(node);
             if (Node* firstChild = element->firstChild())
                 nextNode = firstChild;
             removeElementPreservingChildren(fragment, element);
@@ -1032,9 +1028,10 @@
 
 void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionState& es)
 {
+    ASSERT(container);
     RefPtr<ContainerNode> containerNode(container);
 
-    ChildListMutationScope mutation(containerNode.get());
+    ChildListMutationScope mutation(*containerNode);
 
     if (!fragment->firstChild()) {
         containerNode->removeChildren();
@@ -1057,9 +1054,10 @@
 
 void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& es)
 {
+    ASSERT(container);
     RefPtr<ContainerNode> containerNode(container);
 
-    ChildListMutationScope mutation(containerNode.get());
+    ChildListMutationScope mutation(*containerNode);
 
     if (containerNode->hasOneTextChild()) {
         toText(containerNode->firstChild())->setData(text);
diff --git a/Source/core/editing/markup.h b/Source/core/editing/markup.h
index b293441..00e17b3 100644
--- a/Source/core/editing/markup.h
+++ b/Source/core/editing/markup.h
@@ -51,7 +51,7 @@
 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, ExceptionState&);
+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&);
 
diff --git a/Source/core/events/BeforeUnloadEvent.h b/Source/core/events/BeforeUnloadEvent.h
index 52dbff2..57136f9 100644
--- a/Source/core/events/BeforeUnloadEvent.h
+++ b/Source/core/events/BeforeUnloadEvent.h
@@ -52,11 +52,7 @@
     String m_returnValue;
 };
 
-inline BeforeUnloadEvent* toBeforeUnloadEvent(Event* event)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isBeforeUnloadEvent());
-    return static_cast<BeforeUnloadEvent*>(event);
-}
+DEFINE_EVENT_TYPE_CASTS(BeforeUnloadEvent);
 
 } // namespace WebCore
 
diff --git a/Source/core/events/DocumentEventQueue.cpp b/Source/core/events/DOMWindowEventQueue.cpp
similarity index 78%
rename from Source/core/events/DocumentEventQueue.cpp
rename to Source/core/events/DOMWindowEventQueue.cpp
index bf0f13d..e18530c 100644
--- a/Source/core/events/DocumentEventQueue.cpp
+++ b/Source/core/events/DOMWindowEventQueue.cpp
@@ -25,7 +25,7 @@
  */
 
 #include "config.h"
-#include "core/events/DocumentEventQueue.h"
+#include "core/events/DOMWindowEventQueue.h"
 
 #include "core/dom/Document.h"
 #include "core/events/Event.h"
@@ -35,35 +35,35 @@
 
 namespace WebCore {
 
-class DocumentEventQueueTimer : public SuspendableTimer {
-    WTF_MAKE_NONCOPYABLE(DocumentEventQueueTimer);
+class DOMWindowEventQueueTimer : public SuspendableTimer {
+    WTF_MAKE_NONCOPYABLE(DOMWindowEventQueueTimer);
 public:
-    DocumentEventQueueTimer(DocumentEventQueue* eventQueue, ExecutionContext* context)
+    DOMWindowEventQueueTimer(DOMWindowEventQueue* eventQueue, ExecutionContext* context)
         : SuspendableTimer(context)
         , m_eventQueue(eventQueue) { }
 
 private:
     virtual void fired() { m_eventQueue->pendingEventTimerFired(); }
-    DocumentEventQueue* m_eventQueue;
+    DOMWindowEventQueue* m_eventQueue;
 };
 
-PassRefPtr<DocumentEventQueue> DocumentEventQueue::create(ExecutionContext* context)
+PassRefPtr<DOMWindowEventQueue> DOMWindowEventQueue::create(ExecutionContext* context)
 {
-    return adoptRef(new DocumentEventQueue(context));
+    return adoptRef(new DOMWindowEventQueue(context));
 }
 
-DocumentEventQueue::DocumentEventQueue(ExecutionContext* context)
-    : m_pendingEventTimer(adoptPtr(new DocumentEventQueueTimer(this, context)))
+DOMWindowEventQueue::DOMWindowEventQueue(ExecutionContext* context)
+    : m_pendingEventTimer(adoptPtr(new DOMWindowEventQueueTimer(this, context)))
     , m_isClosed(false)
 {
     m_pendingEventTimer->suspendIfNeeded();
 }
 
-DocumentEventQueue::~DocumentEventQueue()
+DOMWindowEventQueue::~DOMWindowEventQueue()
 {
 }
 
-bool DocumentEventQueue::enqueueEvent(PassRefPtr<Event> event)
+bool DOMWindowEventQueue::enqueueEvent(PassRefPtr<Event> event)
 {
     if (m_isClosed)
         return false;
@@ -78,7 +78,7 @@
     return true;
 }
 
-bool DocumentEventQueue::cancelEvent(Event* event)
+bool DOMWindowEventQueue::cancelEvent(Event* event)
 {
     ListHashSet<RefPtr<Event>, 16>::iterator it = m_queuedEvents.find(event);
     bool found = it != m_queuedEvents.end();
@@ -89,14 +89,14 @@
     return found;
 }
 
-void DocumentEventQueue::close()
+void DOMWindowEventQueue::close()
 {
     m_isClosed = true;
     m_pendingEventTimer->stop();
     m_queuedEvents.clear();
 }
 
-void DocumentEventQueue::pendingEventTimerFired()
+void DOMWindowEventQueue::pendingEventTimerFired()
 {
     ASSERT(!m_pendingEventTimer->isActive());
     ASSERT(!m_queuedEvents.isEmpty());
@@ -106,7 +106,7 @@
     bool wasAdded = m_queuedEvents.add(0).isNewEntry;
     ASSERT_UNUSED(wasAdded, wasAdded); // It should not have already been in the list.
 
-    RefPtr<DocumentEventQueue> protector(this);
+    RefPtr<DOMWindowEventQueue> protector(this);
 
     while (!m_queuedEvents.isEmpty()) {
         ListHashSet<RefPtr<Event>, 16>::iterator iter = m_queuedEvents.begin();
@@ -118,7 +118,7 @@
     }
 }
 
-void DocumentEventQueue::dispatchEvent(PassRefPtr<Event> event)
+void DOMWindowEventQueue::dispatchEvent(PassRefPtr<Event> event)
 {
     EventTarget* eventTarget = event->target();
     if (eventTarget->toDOMWindow())
diff --git a/Source/core/events/DocumentEventQueue.h b/Source/core/events/DOMWindowEventQueue.h
similarity index 80%
rename from Source/core/events/DocumentEventQueue.h
rename to Source/core/events/DOMWindowEventQueue.h
index 401f67d..f19e22b 100644
--- a/Source/core/events/DocumentEventQueue.h
+++ b/Source/core/events/DOMWindowEventQueue.h
@@ -24,8 +24,8 @@
  *
  */
 
-#ifndef DocumentEventQueue_h
-#define DocumentEventQueue_h
+#ifndef DOMWindowEventQueue_h
+#define DOMWindowEventQueue_h
 
 #include "core/events/EventQueue.h"
 #include "wtf/Forward.h"
@@ -37,14 +37,14 @@
 namespace WebCore {
 
 class Event;
-class DocumentEventQueueTimer;
+class DOMWindowEventQueueTimer;
 class Node;
 class ExecutionContext;
 
-class DocumentEventQueue : public RefCounted<DocumentEventQueue>, public EventQueue {
+class DOMWindowEventQueue : public RefCounted<DOMWindowEventQueue>, public EventQueue {
 public:
-    static PassRefPtr<DocumentEventQueue> create(ExecutionContext*);
-    virtual ~DocumentEventQueue();
+    static PassRefPtr<DOMWindowEventQueue> create(ExecutionContext*);
+    virtual ~DOMWindowEventQueue();
 
     // EventQueue
     virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE;
@@ -52,18 +52,18 @@
     virtual void close() OVERRIDE;
 
 private:
-    explicit DocumentEventQueue(ExecutionContext*);
+    explicit DOMWindowEventQueue(ExecutionContext*);
 
     void pendingEventTimerFired();
     void dispatchEvent(PassRefPtr<Event>);
 
-    OwnPtr<DocumentEventQueueTimer> m_pendingEventTimer;
+    OwnPtr<DOMWindowEventQueueTimer> m_pendingEventTimer;
     ListHashSet<RefPtr<Event>, 16> m_queuedEvents;
     bool m_isClosed;
 
-    friend class DocumentEventQueueTimer;
+    friend class DOMWindowEventQueueTimer;
 };
 
 }
 
-#endif // DocumentEventQueue_h
+#endif // DOMWindowEventQueue_h
diff --git a/Source/core/events/Event.h b/Source/core/events/Event.h
index 0717995..b28f7f1 100644
--- a/Source/core/events/Event.h
+++ b/Source/core/events/Event.h
@@ -209,6 +209,9 @@
     EventPath m_eventPath;
 };
 
+#define DEFINE_EVENT_TYPE_CASTS(typeName) \
+    DEFINE_TYPE_CASTS(typeName, Event, event, event->is##typeName(), event.is##typeName())
+
 } // namespace WebCore
 
 #endif // Event_h
diff --git a/Source/core/events/EventRetargeter.h b/Source/core/events/EventRetargeter.h
index 1bb6ce5..4edcded 100644
--- a/Source/core/events/EventRetargeter.h
+++ b/Source/core/events/EventRetargeter.h
@@ -20,19 +20,19 @@
 #ifndef EventRetargeter_h
 #define EventRetargeter_h
 
-#include "core/dom/ContainerNode.h"
-#include "core/events/EventContext.h"
-#include "core/dom/shadow/ShadowRoot.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 {
@@ -49,9 +49,6 @@
         StopAtBoundaryIfNeeded,
         DoesNotStopAtBoundary
     };
-    static void calculateEventPath(Node*, Event*);
-    static void calculateAdjustedEventPathForEachNode(EventPath&);
-
     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&);
diff --git a/Source/core/events/EventTarget.cpp b/Source/core/events/EventTarget.cpp
index cb149b9..0c93217 100644
--- a/Source/core/events/EventTarget.cpp
+++ b/Source/core/events/EventTarget.cpp
@@ -34,6 +34,7 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/DOMWrapperWorld.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/events/Event.h"
 #include "core/dom/ExceptionCode.h"
@@ -156,8 +157,16 @@
 
 bool EventTarget::dispatchEvent(PassRefPtr<Event> event, ExceptionState& es)
 {
-    if (!event || event->type().isEmpty() || event->isBeingDispatched()) {
-        es.throwUninformativeAndGenericDOMException(InvalidStateError);
+    if (!event) {
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("dispatchEvent", "EventTarget", "The event provided is null."));
+        return false;
+    }
+    if (event->type().isEmpty()) {
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("dispatchEvent", "EventTarget", "The event provided is uninitialized."));
+        return false;
+    }
+    if (event->isBeingDispatched()) {
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("dispatchEvent", "EventTarget", "The event is already being dispatched."));
         return false;
     }
 
diff --git a/Source/core/events/EventTarget.h b/Source/core/events/EventTarget.h
index 3c5965b..fa21925 100644
--- a/Source/core/events/EventTarget.h
+++ b/Source/core/events/EventTarget.h
@@ -38,185 +38,201 @@
 
 namespace WebCore {
 
-    class ApplicationCache;
-    class AudioContext;
-    class DOMWindow;
-    class DedicatedWorkerGlobalScope;
-    class Event;
-    class EventListener;
-    class EventSource;
-    class ExceptionState;
-    class FileReader;
-    class FileWriter;
-    class IDBDatabase;
-    class IDBRequest;
-    class IDBTransaction;
-    class MIDIAccess;
-    class MIDIInput;
-    class MIDIPort;
-    class MediaController;
-    class MediaStream;
-    class MessagePort;
-    class NamedFlow;
-    class Node;
-    class Notification;
-    class SVGElementInstance;
-    class ExecutionContext;
-    class ScriptProcessorNode;
-    class SharedWorker;
-    class SharedWorkerGlobalScope;
-    class TextTrack;
-    class TextTrackCue;
-    class WebSocket;
-    class Worker;
-    class XMLHttpRequest;
-    class XMLHttpRequestUpload;
+class ApplicationCache;
+class AudioContext;
+class DOMWindow;
+class DedicatedWorkerGlobalScope;
+class Event;
+class EventListener;
+class EventSource;
+class ExceptionState;
+class FileReader;
+class FileWriter;
+class IDBDatabase;
+class IDBRequest;
+class IDBTransaction;
+class MIDIAccess;
+class MIDIInput;
+class MIDIPort;
+class MediaController;
+class MediaStream;
+class MessagePort;
+class NamedFlow;
+class Node;
+class Notification;
+class SVGElementInstance;
+class ExecutionContext;
+class ScriptProcessorNode;
+class SharedWorker;
+class SharedWorkerGlobalScope;
+class TextTrack;
+class TextTrackCue;
+class WebSocket;
+class Worker;
+class XMLHttpRequest;
+class XMLHttpRequestUpload;
 
-    struct FiringEventIterator {
-        FiringEventIterator(const AtomicString& eventType, size_t& iterator, size_t& end)
-            : eventType(eventType)
-            , iterator(iterator)
-            , end(end)
-        {
-        }
-
-        const AtomicString& eventType;
-        size_t& iterator;
-        size_t& end;
-    };
-    typedef Vector<FiringEventIterator, 1> FiringEventIteratorVector;
-
-    struct EventTargetData {
-        WTF_MAKE_NONCOPYABLE(EventTargetData); WTF_MAKE_FAST_ALLOCATED;
-    public:
-        EventTargetData();
-        ~EventTargetData();
-
-        EventListenerMap eventListenerMap;
-        OwnPtr<FiringEventIteratorVector> firingEventIterators;
-    };
-
-    class EventTarget {
-    public:
-        void ref() { refEventTarget(); }
-        void deref() { derefEventTarget(); }
-
-        virtual const AtomicString& interfaceName() const = 0;
-        virtual ExecutionContext* executionContext() const = 0;
-
-        virtual Node* toNode();
-        virtual DOMWindow* toDOMWindow();
-        virtual MessagePort* toMessagePort();
-
-        virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
-        virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
-        virtual void removeAllEventListeners();
-        virtual bool dispatchEvent(PassRefPtr<Event>);
-        bool dispatchEvent(PassRefPtr<Event>, ExceptionState&); // DOM API
-        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 hasEventListeners() const;
-        bool hasEventListeners(const AtomicString& eventType) const;
-        bool hasCapturingEventListeners(const AtomicString& eventType);
-        const EventListenerVector& getEventListeners(const AtomicString& eventType);
-
-        bool fireEventListeners(Event*);
-        bool isFiringEventListeners();
-
-    protected:
-        virtual ~EventTarget();
-
-        // Subclasses should likely not override these themselves; instead, they should subclass EventTargetWithInlineData.
-        virtual EventTargetData* eventTargetData() = 0;
-        virtual EventTargetData& ensureEventTargetData() = 0;
-
-    private:
-        // Subclasses should likely not override these themselves; instead, they should use the REFCOUNTED_EVENT_TARGET() macro.
-        virtual void refEventTarget() = 0;
-        virtual void derefEventTarget() = 0;
-
-        DOMWindow* executingWindow();
-        void fireEventListeners(Event*, EventTargetData*, EventListenerVector&);
-        void countLegacyEvents(const AtomicString& legacyTypeName, EventListenerVector*, EventListenerVector*);
-
-        bool clearAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld);
-
-        friend class EventListenerIterator;
-    };
-
-    class EventTargetWithInlineData : public EventTarget {
-    protected:
-        virtual EventTargetData* eventTargetData() OVERRIDE FINAL { return &m_eventTargetData; }
-        virtual EventTargetData& ensureEventTargetData() OVERRIDE FINAL { return m_eventTargetData; }
-    private:
-        EventTargetData m_eventTargetData;
-    };
-
-    // 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); } \
-
-    #define DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(attribute) \
-        virtual EventListener* on##attribute(DOMWrapperWorld* isolatedWorld); \
-        virtual void setOn##attribute(PassRefPtr<EventListener>, DOMWrapperWorld* isolatedWorld); \
-
-    #define DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(type, attribute) \
-        EventListener* type::on##attribute(DOMWrapperWorld* isolatedWorld) { return getAttributeEventListener(EventTypeNames::attribute, isolatedWorld); } \
-        void type::setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); } \
-
-    #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); } \
-
-    #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); } \
-
-    #define DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(recipient, attribute) \
-        EventListener* on##attribute(DOMWrapperWorld* isolatedWorld); \
-        void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld);
-
-    #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) { if (recipient) recipient->setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); }
-
-    inline bool EventTarget::isFiringEventListeners()
+struct FiringEventIterator {
+    FiringEventIterator(const AtomicString& eventType, size_t& iterator, size_t& end)
+        : eventType(eventType)
+        , iterator(iterator)
+        , end(end)
     {
-        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.
-        if (const EventTargetData* d = const_cast<EventTarget*>(this)->eventTargetData())
-            return !d->eventListenerMap.isEmpty();
+    const AtomicString& eventType;
+    size_t& iterator;
+    size_t& end;
+};
+typedef Vector<FiringEventIterator, 1> FiringEventIteratorVector;
+
+struct EventTargetData {
+    WTF_MAKE_NONCOPYABLE(EventTargetData); WTF_MAKE_FAST_ALLOCATED;
+public:
+    EventTargetData();
+    ~EventTargetData();
+
+    EventListenerMap eventListenerMap;
+    OwnPtr<FiringEventIteratorVector> firingEventIterators;
+};
+
+class EventTarget {
+public:
+    void ref() { refEventTarget(); }
+    void deref() { derefEventTarget(); }
+
+    virtual const AtomicString& interfaceName() const = 0;
+    virtual ExecutionContext* executionContext() const = 0;
+
+    virtual Node* toNode();
+    virtual DOMWindow* toDOMWindow();
+    virtual MessagePort* toMessagePort();
+
+    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
+    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
+    virtual void removeAllEventListeners();
+    virtual bool dispatchEvent(PassRefPtr<Event>);
+    bool dispatchEvent(PassRefPtr<Event>, ExceptionState&); // DOM API
+    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 hasEventListeners() const;
+    bool hasEventListeners(const AtomicString& eventType) const;
+    bool hasCapturingEventListeners(const AtomicString& eventType);
+    const EventListenerVector& getEventListeners(const AtomicString& eventType);
+
+    bool fireEventListeners(Event*);
+    bool isFiringEventListeners();
+
+protected:
+    virtual ~EventTarget();
+
+    // Subclasses should likely not override these themselves; instead, they should subclass EventTargetWithInlineData.
+    virtual EventTargetData* eventTargetData() = 0;
+    virtual EventTargetData& ensureEventTargetData() = 0;
+
+private:
+    // Subclasses should likely not override these themselves; instead, they should use the REFCOUNTED_EVENT_TARGET() macro.
+    virtual void refEventTarget() = 0;
+    virtual void derefEventTarget() = 0;
+
+    DOMWindow* executingWindow();
+    void fireEventListeners(Event*, EventTargetData*, EventListenerVector&);
+    void countLegacyEvents(const AtomicString& legacyTypeName, EventListenerVector*, EventListenerVector*);
+
+    bool clearAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld);
+
+    friend class EventListenerIterator;
+};
+
+class EventTargetWithInlineData : public EventTarget {
+protected:
+    virtual EventTargetData* eventTargetData() OVERRIDE FINAL { return &m_eventTargetData; }
+    virtual EventTargetData& ensureEventTargetData() OVERRIDE FINAL { return m_eventTargetData; }
+private:
+    EventTargetData m_eventTargetData;
+};
+
+// 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); } \
+
+#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); } \
+
+#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); } \
+
+#define DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(attribute) \
+    static EventListener* on##attribute(EventTarget* eventTarget, DOMWrapperWorld* isolatedWorld) { \
+        if (Node* node = eventTarget->toNode()) \
+            return node->document().getWindowAttributeEventListener(EventTypeNames::attribute, isolatedWorld); \
+        ASSERT(eventTarget->toDOMWindow()); \
+        return eventTarget->getAttributeEventListener(EventTypeNames::attribute, isolatedWorld); \
+    } \
+    static void setOn##attribute(EventTarget* eventTarget, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { \
+        if (Node* node = eventTarget->toNode()) \
+            node->document().setWindowAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); \
+        else { \
+            ASSERT(eventTarget->toDOMWindow()); \
+            eventTarget->setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); \
+        } \
+    }
+
+#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); } \
+
+#define DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(recipient, attribute) \
+    EventListener* on##attribute(DOMWrapperWorld* isolatedWorld); \
+    void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld);
+
+#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) \
+    { \
+        if (recipient) \
+            recipient->setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); \
+    }
+
+inline bool EventTarget::isFiringEventListeners()
+{
+    EventTargetData* d = eventTargetData();
+    if (!d)
         return false;
-    }
+    return d->firingEventIterators && !d->firingEventIterators->isEmpty();
+}
 
-    inline bool EventTarget::hasEventListeners(const AtomicString& eventType) const
-    {
-        // FIXME: We should have const version of eventTargetData.
-        if (const EventTargetData* d = const_cast<EventTarget*>(this)->eventTargetData())
-            return d->eventListenerMap.contains(eventType);
+inline bool EventTarget::hasEventListeners() const
+{
+    // FIXME: We should have a const version of eventTargetData.
+    if (const EventTargetData* d = const_cast<EventTarget*>(this)->eventTargetData())
+        return !d->eventListenerMap.isEmpty();
+    return false;
+}
+
+inline bool EventTarget::hasEventListeners(const AtomicString& eventType) const
+{
+    // FIXME: We should have const version of eventTargetData.
+    if (const EventTargetData* d = const_cast<EventTarget*>(this)->eventTargetData())
+        return d->eventListenerMap.contains(eventType);
+    return false;
+}
+
+inline bool EventTarget::hasCapturingEventListeners(const AtomicString& eventType)
+{
+    EventTargetData* d = eventTargetData();
+    if (!d)
         return false;
-    }
-
-    inline bool EventTarget::hasCapturingEventListeners(const AtomicString& eventType)
-    {
-        EventTargetData* d = eventTargetData();
-        if (!d)
-            return false;
-        return d->eventListenerMap.containsCapturing(eventType);
-    }
+    return d->eventListenerMap.containsCapturing(eventType);
+}
 
 } // namespace WebCore
 
diff --git a/Source/core/events/FocusEvent.h b/Source/core/events/FocusEvent.h
index 380658f..fda7ef3 100644
--- a/Source/core/events/FocusEvent.h
+++ b/Source/core/events/FocusEvent.h
@@ -70,11 +70,7 @@
     RefPtr<EventTarget> m_relatedTarget;
 };
 
-inline FocusEvent* toFocusEvent(Event* event)
-{
-    ASSERT(event && event->isFocusEvent());
-    return static_cast<FocusEvent*>(event);
-}
+DEFINE_EVENT_TYPE_CASTS(FocusEvent);
 
 class FocusEventDispatchMediator : public EventDispatchMediator {
 public:
diff --git a/Source/core/events/GestureEvent.h b/Source/core/events/GestureEvent.h
index 03ca127..fe98200 100644
--- a/Source/core/events/GestureEvent.h
+++ b/Source/core/events/GestureEvent.h
@@ -71,11 +71,7 @@
     virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
 };
 
-inline GestureEvent* toGestureEvent(Event* event)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isGestureEvent());
-    return static_cast<GestureEvent*>(event);
-}
+DEFINE_EVENT_TYPE_CASTS(GestureEvent);
 
 } // namespace WebCore
 
diff --git a/Source/core/events/KeyboardEvent.h b/Source/core/events/KeyboardEvent.h
index f11901e..e4d1e9e 100644
--- a/Source/core/events/KeyboardEvent.h
+++ b/Source/core/events/KeyboardEvent.h
@@ -125,11 +125,7 @@
     virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
 };
 
-inline KeyboardEvent* toKeyboardEvent(Event* event)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isKeyboardEvent());
-    return static_cast<KeyboardEvent*>(event);
-}
+DEFINE_EVENT_TYPE_CASTS(KeyboardEvent);
 
 } // namespace WebCore
 
diff --git a/Source/core/events/MouseEvent.cpp b/Source/core/events/MouseEvent.cpp
index ad0f99c..1e6a697 100644
--- a/Source/core/events/MouseEvent.cpp
+++ b/Source/core/events/MouseEvent.cpp
@@ -24,6 +24,7 @@
 #include "core/events/MouseEvent.h"
 
 #include "core/dom/Clipboard.h"
+#include "core/dom/Element.h"
 #include "core/events/EventDispatcher.h"
 #include "core/events/EventRetargeter.h"
 #include "core/events/ThreadLocalEventNames.h"
diff --git a/Source/core/events/MouseEvent.h b/Source/core/events/MouseEvent.h
index 139cea8..710adf3 100644
--- a/Source/core/events/MouseEvent.h
+++ b/Source/core/events/MouseEvent.h
@@ -139,11 +139,7 @@
     MouseEventType m_mouseEventType;
 };
 
-inline MouseEvent* toMouseEvent(Event* event)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isMouseEvent());
-    return static_cast<MouseEvent*>(event);
-}
+DEFINE_EVENT_TYPE_CASTS(MouseEvent);
 
 } // namespace WebCore
 
diff --git a/Source/core/events/TextEvent.h b/Source/core/events/TextEvent.h
index 26cf89f..6c2f256 100644
--- a/Source/core/events/TextEvent.h
+++ b/Source/core/events/TextEvent.h
@@ -77,12 +77,13 @@
         bool m_shouldMatchStyle;
     };
 
-inline TextEvent* toTextEvent(Event* event)
+inline bool isTextEvent(const Event& event)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!event || (event->type() == EventTypeNames::textInput && event->hasInterface(EventNames::TextEvent)));
-    return static_cast<TextEvent*>(event);
+    return event.type() == EventTypeNames::textInput && event.hasInterface(EventNames::TextEvent);
 }
 
+DEFINE_TYPE_CASTS(TextEvent, Event, event, isTextEvent(*event), isTextEvent(event));
+
 } // namespace WebCore
 
 #endif // TextEvent_h
diff --git a/Source/core/events/TouchEvent.h b/Source/core/events/TouchEvent.h
index 11ad47f..25c6f61 100644
--- a/Source/core/events/TouchEvent.h
+++ b/Source/core/events/TouchEvent.h
@@ -93,11 +93,7 @@
     virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
 };
 
-inline TouchEvent* toTouchEvent(Event* event)
-{
-    ASSERT(event && event->isTouchEvent());
-    return static_cast<TouchEvent*>(event);
-}
+DEFINE_EVENT_TYPE_CASTS(TouchEvent);
 
 } // namespace WebCore
 
diff --git a/Source/core/events/WheelEvent.h b/Source/core/events/WheelEvent.h
index 27c8967..6c8ea02 100644
--- a/Source/core/events/WheelEvent.h
+++ b/Source/core/events/WheelEvent.h
@@ -112,11 +112,7 @@
     bool m_directionInvertedFromDevice;
 };
 
-inline WheelEvent* toWheelEvent(Event* event)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isWheelEvent());
-    return static_cast<WheelEvent*>(event);
-}
+DEFINE_EVENT_TYPE_CASTS(WheelEvent);
 
 class WheelEventDispatchMediator : public EventDispatchMediator {
 public:
diff --git a/Source/core/fetch/FontResource.cpp b/Source/core/fetch/FontResource.cpp
index 39bf1e4..7f227b9 100644
--- a/Source/core/fetch/FontResource.cpp
+++ b/Source/core/fetch/FontResource.cpp
@@ -30,10 +30,10 @@
 #include "core/fetch/ResourceClient.h"
 #include "core/fetch/ResourceClientWalker.h"
 #include "core/fetch/TextResourceDecoder.h"
-#include "core/platform/HistogramSupport.h"
-#include "platform/SharedBuffer.h"
 #include "core/platform/graphics/FontCustomPlatformData.h"
 #include "core/platform/graphics/FontPlatformData.h"
+#include "platform/SharedBuffer.h"
+#include "public/platform/Platform.h"
 #include "wtf/CurrentTime.h"
 
 #if ENABLE(SVG_FONTS)
@@ -174,7 +174,7 @@
 FontResource::FontResourceHistograms::~FontResourceHistograms()
 {
     if (m_styledTime > 0)
-        HistogramSupport::histogramEnumeration("WebFont.Resource.UsageType", StyledButNotUsed, UsageTypeMax);
+        WebKit::Platform::current()->histogramEnumeration("WebFont.Resource.UsageType", StyledButNotUsed, UsageTypeMax);
 }
 
 void FontResource::FontResourceHistograms::willUseFontData()
@@ -188,11 +188,11 @@
     if (m_styledTime < 0)
         return;
     if (!m_styledTime) {
-        HistogramSupport::histogramEnumeration("WebFont.Resource.UsageType", NotStyledButUsed, UsageTypeMax);
+        WebKit::Platform::current()->histogramEnumeration("WebFont.Resource.UsageType", NotStyledButUsed, UsageTypeMax);
     } else {
         int duration = static_cast<int>(currentTimeMS() - m_styledTime);
-        HistogramSupport::histogramCustomCounts("WebFont.Resource.StyleRecalcToDownloadLatency", duration, 0, 10000, 50);
-        HistogramSupport::histogramEnumeration("WebFont.Resource.UsageType", StyledAndUsed, UsageTypeMax);
+        WebKit::Platform::current()->histogramCustomCounts("WebFont.Resource.StyleRecalcToDownloadLatency", duration, 0, 10000, 50);
+        WebKit::Platform::current()->histogramEnumeration("WebFont.Resource.UsageType", StyledAndUsed, UsageTypeMax);
     }
     m_styledTime = -1;
 }
diff --git a/Source/core/fetch/FontResource.h b/Source/core/fetch/FontResource.h
index a910f8e..4666820 100644
--- a/Source/core/fetch/FontResource.h
+++ b/Source/core/fetch/FontResource.h
@@ -28,8 +28,8 @@
 
 #include "core/fetch/Resource.h"
 #include "core/fetch/ResourceClient.h"
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/FontWidthVariant.h"
+#include "platform/fonts/FontOrientation.h"
+#include "platform/fonts/FontWidthVariant.h"
 #include "wtf/OwnPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/fetch/ImageResource.cpp b/Source/core/fetch/ImageResource.cpp
index 9001189..4827b2e 100644
--- a/Source/core/fetch/ImageResource.cpp
+++ b/Source/core/fetch/ImageResource.cpp
@@ -24,6 +24,7 @@
 #include "config.h"
 #include "core/fetch/ImageResource.h"
 
+#include "RuntimeEnabledFeatures.h"
 #include "core/fetch/ImageResourceClient.h"
 #include "core/fetch/MemoryCache.h"
 #include "core/fetch/ResourceClient.h"
@@ -44,8 +45,10 @@
 
 ImageResource::ImageResource(const ResourceRequest& resourceRequest)
     : Resource(resourceRequest, Image)
+    , m_devicePixelRatioHeaderValue(1.0)
     , m_image(0)
     , m_loadingMultipartContent(false)
+    , m_hasDevicePixelRatioHeaderValue(false)
 {
     setStatus(Unknown);
     setCustomAcceptHeader();
@@ -377,6 +380,13 @@
         finishOnePart();
     else if (response.isMultipart())
         m_loadingMultipartContent = true;
+    if (RuntimeEnabledFeatures::clientHintsDprEnabled()) {
+        m_devicePixelRatioHeaderValue = response.httpHeaderField("DPR").toFloat(&m_hasDevicePixelRatioHeaderValue);
+        if (!m_hasDevicePixelRatioHeaderValue || m_devicePixelRatioHeaderValue <= 0.0) {
+            m_devicePixelRatioHeaderValue = 1.0;
+            m_hasDevicePixelRatioHeaderValue = false;
+        }
+    }
     Resource::responseReceived(response);
 }
 
@@ -450,4 +460,13 @@
     return image->currentFrameKnownToBeOpaque();
 }
 
+bool ImageResource::isAccessAllowed(SecurityOrigin* securityOrigin)
+{
+    if (!image()->currentFrameHasSingleSecurityOrigin())
+        return false;
+    if (passesAccessControlCheck(securityOrigin))
+        return true;
+    return !securityOrigin->taintsCanvas(response().url());
+}
+
 } // namespace WebCore
diff --git a/Source/core/fetch/ImageResource.h b/Source/core/fetch/ImageResource.h
index 968a760..2092d9f 100644
--- a/Source/core/fetch/ImageResource.h
+++ b/Source/core/fetch/ImageResource.h
@@ -39,6 +39,7 @@
 class Length;
 class MemoryCache;
 class RenderObject;
+class SecurityOrigin;
 
 class ImageResource : public Resource, public ImageObserver {
     friend class MemoryCache;
@@ -64,6 +65,9 @@
     bool usesImageContainerSize() const;
     bool imageHasRelativeWidth() const;
     bool imageHasRelativeHeight() const;
+    // The device pixel ratio we got from the server for this image, or 1.0.
+    float devicePixelRatioHeaderValue() const { return m_devicePixelRatioHeaderValue; }
+    bool hasDevicePixelRatioHeaderValue() const { return m_hasDevicePixelRatioHeaderValue; }
 
     enum SizeType {
         NormalSize, // Report the size of the image associated with a certain renderer
@@ -73,6 +77,8 @@
     LayoutSize imageSizeForRenderer(const RenderObject*, float multiplier, SizeType = NormalSize); // returns the size of the complete image.
     void computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio);
 
+    bool isAccessAllowed(SecurityOrigin*);
+
     virtual void didAddClient(ResourceClient*);
     virtual void didRemoveClient(ResourceClient*);
 
@@ -113,10 +119,12 @@
     typedef pair<IntSize, float> SizeAndZoom;
     typedef HashMap<const ImageResourceClient*, SizeAndZoom> ContainerSizeRequests;
     ContainerSizeRequests m_pendingContainerSizeRequests;
+    float m_devicePixelRatioHeaderValue;
 
     RefPtr<WebCore::Image> m_image;
     OwnPtr<SVGImageCache> m_svgImageCache;
     bool m_loadingMultipartContent;
+    bool m_hasDevicePixelRatioHeaderValue;
 };
 
 }
diff --git a/Source/core/fetch/MemoryCache.cpp b/Source/core/fetch/MemoryCache.cpp
index 51f868c..22ce954 100644
--- a/Source/core/fetch/MemoryCache.cpp
+++ b/Source/core/fetch/MemoryCache.cpp
@@ -75,9 +75,9 @@
     , m_minDeadCapacity(0)
     , m_maxDeadCapacity(cDefaultCacheCapacity)
     , m_maxDeferredPruneDeadCapacity(cDeferredPruneDeadCapacityFactor * cDefaultCacheCapacity)
+    , m_delayBeforeLiveDecodedPrune(cMinDelayBeforeLiveDecodedPrune)
     , m_liveSize(0)
     , m_deadSize(0)
-    , m_delayBeforeLiveDecodedPrune(cMinDelayBeforeLiveDecodedPrune)
 #ifdef MEMORY_CACHE_STATS
     , m_statsTimer(this, &MemoryCache::dumpStats)
 #endif
diff --git a/Source/core/fetch/Resource.cpp b/Source/core/fetch/Resource.cpp
index ae8542d..f3b012a 100644
--- a/Source/core/fetch/Resource.cpp
+++ b/Source/core/fetch/Resource.cpp
@@ -891,5 +891,40 @@
         resources[i]->finishPendingClients();
 }
 
+#if !LOG_DISABLED
+const char* ResourceTypeName(Resource::Type type)
+{
+    switch (type) {
+    case Resource::MainResource:
+        return "MainResource";
+    case Resource::Image:
+        return "Image";
+    case Resource::CSSStyleSheet:
+        return "CSSStyleSheet";
+    case Resource::Script:
+        return "Script";
+    case Resource::Font:
+        return "Font";
+    case Resource::Raw:
+        return "Raw";
+    case Resource::SVGDocument:
+        return "SVGDocument";
+    case Resource::XSLStyleSheet:
+        return "XSLStyleSheet";
+    case Resource::LinkPrefetch:
+        return "LinkPrefetch";
+    case Resource::LinkSubresource:
+        return "LinkSubresource";
+    case Resource::TextTrack:
+        return "TextTrack";
+    case Resource::Shader:
+        return "Shader";
+    case Resource::ImportResource:
+        return "ImportResource";
+    }
+    ASSERT_NOT_REACHED();
+    return "Unknown";
 }
+#endif // !LOG_DISABLED
 
+}
diff --git a/Source/core/fetch/Resource.h b/Source/core/fetch/Resource.h
index 70f594e..dfb7825 100644
--- a/Source/core/fetch/Resource.h
+++ b/Source/core/fetch/Resource.h
@@ -109,7 +109,8 @@
     ResourceRequest& resourceRequest() { return m_resourceRequest; }
     const KURL& url() const { return m_resourceRequest.url();}
     Type type() const { return static_cast<Type>(m_type); }
-    const ResourceLoaderOptions& options() const {  return m_options; }
+    const ResourceLoaderOptions& options() const { return m_options; }
+    void setOptions(const ResourceLoaderOptions& options) { m_options = options; }
 
     void didChangePriority(ResourceLoadPriority);
 
@@ -358,6 +359,11 @@
     HashSet<ResourcePtrBase*> m_handlesToRevalidate;
 };
 
+#if !LOG_DISABLED
+// Intended to be used in LOG statements.
+const char* ResourceTypeName(Resource::Type);
+#endif
+
 }
 
 #endif
diff --git a/Source/core/fetch/ResourceClient.h b/Source/core/fetch/ResourceClient.h
index ae7b7bb..937f787 100644
--- a/Source/core/fetch/ResourceClient.h
+++ b/Source/core/fetch/ResourceClient.h
@@ -44,7 +44,6 @@
 
     virtual ~ResourceClient() { }
     virtual void notifyFinished(Resource*) { }
-    virtual void deprecatedDidReceiveResource(Resource*) { }
 
     static ResourceClientType expectedType() { return BaseResourceType; }
     virtual ResourceClientType resourceClientType() const { return expectedType(); }
diff --git a/Source/core/fetch/ResourceFetcher.cpp b/Source/core/fetch/ResourceFetcher.cpp
index 1788add..4570574 100644
--- a/Source/core/fetch/ResourceFetcher.cpp
+++ b/Source/core/fetch/ResourceFetcher.cpp
@@ -143,7 +143,7 @@
     return ResourceLoadPriorityUnresolved;
 }
 
-static Resource* resourceFromDataURIRequest(const ResourceRequest& request)
+static Resource* resourceFromDataURIRequest(const ResourceRequest& request, const ResourceLoaderOptions& resourceOptions)
 {
     const KURL& url = request.url();
     ASSERT(url.protocolIsData());
@@ -156,6 +156,7 @@
     ResourceResponse response(url, mimetype, data->size(), charset, String());
 
     Resource* resource = createResource(Resource::Image, request, charset);
+    resource->setOptions(resourceOptions);
     resource->responseReceived(response);
     // FIXME: AppendData causes an unnecessary memcpy.
     if (data->size())
@@ -164,6 +165,56 @@
     return resource;
 }
 
+static void reportResourceTiming(ResourceTimingInfo* info, Resource* resource, double finishTime, Document* initiatorDocument, 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);
+    if (DOMWindow* initiatorWindow = initiatorDocument->domWindow()) {
+        if (Performance* performance = initiatorWindow->performance())
+            performance->addResourceTiming(*info, initiatorDocument);
+    }
+}
+
+static ResourceRequest::TargetType requestTargetType(const ResourceFetcher* fetcher, const ResourceRequest& request, Resource::Type type)
+{
+    switch (type) {
+    case Resource::MainResource:
+        if (fetcher->frame()->tree().parent())
+            return ResourceRequest::TargetIsSubframe;
+        return ResourceRequest::TargetIsMainFrame;
+    case Resource::XSLStyleSheet:
+        ASSERT(RuntimeEnabledFeatures::xsltEnabled());
+    case Resource::CSSStyleSheet:
+        return ResourceRequest::TargetIsStyleSheet;
+    case Resource::Script:
+        return ResourceRequest::TargetIsScript;
+    case Resource::Font:
+        return ResourceRequest::TargetIsFont;
+    case Resource::Image:
+        return ResourceRequest::TargetIsImage;
+    case Resource::Shader:
+    case Resource::Raw:
+    case Resource::ImportResource:
+        return ResourceRequest::TargetIsSubresource;
+    case Resource::LinkPrefetch:
+        return ResourceRequest::TargetIsPrefetch;
+    case Resource::LinkSubresource:
+        return ResourceRequest::TargetIsSubresource;
+    case Resource::TextTrack:
+        return ResourceRequest::TargetIsTextTrack;
+    case Resource::SVGDocument:
+        return ResourceRequest::TargetIsImage;
+    }
+    ASSERT_NOT_REACHED();
+    return ResourceRequest::TargetIsSubresource;
+}
+
 ResourceFetcher::ResourceFetcher(DocumentLoader* documentLoader)
     : m_document(0)
     , m_documentLoader(documentLoader)
@@ -247,10 +298,10 @@
     const KURL& url = request.resourceRequest().url();
     ASSERT(url.protocolIsData());
 
-    if (Resource* existing = memoryCache()->resourceForURL(url))
+    if (memoryCache()->resourceForURL(url))
         return;
 
-    if (Resource* resource = resourceFromDataURIRequest(request.resourceRequest()))
+    if (Resource* resource = resourceFromDataURIRequest(request.resourceRequest(), request.options()))
         memoryCache()->add(resource);
 }
 
@@ -360,13 +411,16 @@
     }
     if (treatment == TreatAsActiveContent) {
         if (Frame* f = frame()) {
-            if (!f->loader()->mixedContentChecker()->canRunInsecureContent(m_document->securityOrigin(), url))
+            if (!f->loader().mixedContentChecker()->canRunInsecureContent(m_document->securityOrigin(), url))
+                return false;
+            Frame* top = f->tree().top();
+            if (top != f && !top->loader().mixedContentChecker()->canRunInsecureContent(top->document()->securityOrigin(), url))
                 return false;
         }
     } else if (treatment == TreatAsPassiveContent) {
         if (Frame* f = frame()) {
-            Frame* top = f->tree()->top();
-            if (!top->loader()->mixedContentChecker()->canDisplayInsecureContent(top->document()->securityOrigin(), url))
+            Frame* top = f->tree().top();
+            if (!top->loader().mixedContentChecker()->canDisplayInsecureContent(top->document()->securityOrigin(), url))
                 return false;
         }
     } else {
@@ -385,7 +439,7 @@
     }
 
     // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
-    bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script()->shouldBypassMainWorldContentSecurityPolicy()) || (options.contentSecurityPolicyOption == DoNotCheckContentSecurityPolicy);
+    bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script().shouldBypassMainWorldContentSecurityPolicy()) || (options.contentSecurityPolicyOption == DoNotCheckContentSecurityPolicy);
 
     // Some types of resources can be loaded only from the same origin. Other
     // types of resources, like Images, Scripts, and CSS, can be loaded from
@@ -432,8 +486,8 @@
 
         if (frame()) {
             Settings* settings = frame()->settings();
-            if (!frame()->loader()->client()->allowScriptFromSource(!settings || settings->isScriptEnabled(), url)) {
-                frame()->loader()->client()->didNotAllowScript();
+            if (!frame()->loader().client()->allowScriptFromSource(!settings || settings->isScriptEnabled(), url)) {
+                frame()->loader().client()->didNotAllowScript();
                 return false;
             }
         }
@@ -460,7 +514,7 @@
     case Resource::LinkSubresource:
         break;
     case Resource::TextTrack:
-        // Cues aren't called out in the CPS spec yet, but they only work with a media element
+        // Cues aren't called out in the CSP spec yet, but they only work with a media element
         // so use the media policy.
         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowMediaFromSource(url))
             return false;
@@ -511,7 +565,7 @@
         return false;
     if (!m_documentLoader)
         return true;
-    return m_documentLoader == frame()->loader()->activeDocumentLoader();
+    return m_documentLoader == frame()->loader().activeDocumentLoader();
 }
 
 bool ResourceFetcher::resourceNeedsLoad(Resource* resource, const FetchRequest& request, RevalidationPolicy policy)
@@ -531,7 +585,7 @@
 
     KURL url = request.resourceRequest().url();
 
-    LOG(ResourceLoading, "ResourceFetcher::requestResource '%s', charset '%s', priority=%d, forPreload=%u", url.elidedString().latin1().data(), request.charset().latin1().data(), request.priority(), request.forPreload());
+    LOG(ResourceLoading, "ResourceFetcher::requestResource '%s', charset '%s', priority=%d, forPreload=%u, type=%s", url.elidedString().latin1().data(), request.charset().latin1().data(), request.priority(), request.forPreload(), ResourceTypeName(type));
 
     // If only the fragment identifiers differ, it is the same resource.
     url = MemoryCache::removeFragmentIdentifierIfNeeded(url);
@@ -543,7 +597,7 @@
         return 0;
 
     if (Frame* f = frame())
-        f->loader()->client()->dispatchWillRequestResource(&request);
+        f->loader().client()->dispatchWillRequestResource(&request);
 
     // See if we can use an existing resource from the cache.
     ResourcePtr<Resource> resource = memoryCache()->resourceForURL(url);
@@ -617,8 +671,15 @@
             return 0;
     }
 
-    if (!request.resourceRequest().url().protocolIsData())
+    if (!request.resourceRequest().url().protocolIsData()) {
+        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);
+        }
+
         m_validatedURLs.add(request.resourceRequest().url());
+    }
 
     ASSERT(resource->url() == url.string());
     m_documentResources.set(resource->url(), resource);
@@ -627,58 +688,14 @@
 
 void ResourceFetcher::determineTargetType(ResourceRequest& request, Resource::Type type)
 {
-    ResourceRequest::TargetType targetType;
-
-    switch (type) {
-    case Resource::MainResource:
-        if (frame()->tree()->parent())
-            targetType = ResourceRequest::TargetIsSubframe;
-        else
-            targetType = ResourceRequest::TargetIsMainFrame;
-        break;
-    case Resource::XSLStyleSheet:
-        ASSERT(RuntimeEnabledFeatures::xsltEnabled());
-    case Resource::CSSStyleSheet:
-        targetType = ResourceRequest::TargetIsStyleSheet;
-        break;
-    case Resource::Script:
-        targetType = ResourceRequest::TargetIsScript;
-        break;
-    case Resource::Font:
-        targetType = ResourceRequest::TargetIsFont;
-        break;
-    case Resource::Image:
-        targetType = ResourceRequest::TargetIsImage;
-        break;
-    case Resource::Shader:
-    case Resource::Raw:
-    case Resource::ImportResource:
-        targetType = ResourceRequest::TargetIsSubresource;
-        break;
-    case Resource::LinkPrefetch:
-        targetType = ResourceRequest::TargetIsPrefetch;
-        break;
-    case Resource::LinkSubresource:
-        targetType = ResourceRequest::TargetIsSubresource;
-        break;
-    case Resource::TextTrack:
-        targetType = ResourceRequest::TargetIsTextTrack;
-        break;
-    case Resource::SVGDocument:
-        targetType = ResourceRequest::TargetIsImage;
-        break;
-    default:
-        ASSERT_NOT_REACHED();
-        targetType = ResourceRequest::TargetIsSubresource;
-        break;
-    }
+    ResourceRequest::TargetType targetType = requestTargetType(this, request, type);
     request.setTargetType(targetType);
 }
 
 ResourceRequestCachePolicy ResourceFetcher::resourceRequestCachePolicy(const ResourceRequest& request, Resource::Type type)
 {
     if (type == Resource::MainResource) {
-        FrameLoadType frameLoadType = frame()->loader()->loadType();
+        FrameLoadType frameLoadType = frame()->loader().loadType();
         bool isReload = frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin;
         if (request.httpMethod() == "POST" && frameLoadType == FrameLoadTypeBackForward)
             return ReturnCacheDataDontLoad;
@@ -929,7 +946,7 @@
 
 bool ResourceFetcher::clientDefersImage(const KURL& url) const
 {
-    return frame() && !frame()->loader()->client()->allowImage(m_imagesEnabled, url);
+    return frame() && !frame()->loader().client()->allowImage(m_imagesEnabled, url);
 }
 
 bool ResourceFetcher::shouldDeferImageLoad(const KURL& url) const
@@ -962,24 +979,14 @@
     if (resource && resource->response().isHTTP() && ((!resource->errorOccurred() && !resource->wasCanceled()) || resource->response().httpStatusCode() == 304) && document()) {
         ResourceTimingInfoMap::iterator it = m_resourceTimingInfoMap.find(resource);
         if (it != m_resourceTimingInfoMap.end()) {
-            Document* initiatorDocument = document();
-            if (resource->type() == Resource::MainResource)
-                initiatorDocument = document()->parentDocument();
-            ASSERT(initiatorDocument);
             RefPtr<ResourceTimingInfo> info = it->value;
             m_resourceTimingInfoMap.remove(it);
-            info->setInitialRequest(resource->resourceRequest());
-            info->setFinalResponse(resource->response());
-            info->setLoadFinishTime(resource->loadFinishTime());
-            if (DOMWindow* initiatorWindow = initiatorDocument->domWindow()) {
-                if (Performance* performance = initiatorWindow->performance())
-                    performance->addResourceTiming(*info, initiatorDocument);
-            }
+            reportResourceTiming(info.get(), resource, resource->loadFinishTime(), document(), false);
         }
     }
 
     if (frame())
-        frame()->loader()->loadDone();
+        frame()->loader().loadDone();
     performPostLoadActions();
 
     if (!m_garbageCollectDocumentResourcesTimer.isActive())
@@ -1193,7 +1200,7 @@
     if (m_loaders)
         m_loaders->remove(loader);
     if (Frame* frame = this->frame())
-        return frame->loader()->checkLoadComplete(m_documentLoader);
+        return frame->loader().checkLoadComplete(m_documentLoader);
 }
 
 void ResourceFetcher::didInitializeResourceLoader(ResourceLoader* loader)
@@ -1212,7 +1219,7 @@
         return;
     m_loaders->remove(loader);
     if (Frame* frame = this->frame())
-        frame->loader()->checkLoadComplete(m_documentLoader);
+        frame->loader().checkLoadComplete(m_documentLoader);
 }
 
 void ResourceFetcher::willStartLoadingResource(ResourceRequest& request)
diff --git a/Source/core/fetch/ResourceLoader.cpp b/Source/core/fetch/ResourceLoader.cpp
index c210e74..2f06d18 100644
--- a/Source/core/fetch/ResourceLoader.cpp
+++ b/Source/core/fetch/ResourceLoader.cpp
@@ -44,6 +44,7 @@
 #include "public/platform/WebURLRequest.h"
 #include "public/platform/WebURLResponse.h"
 #include "wtf/Assertions.h"
+#include "wtf/CurrentTime.h"
 
 namespace WebCore {
 
@@ -431,7 +432,7 @@
     RefPtr<ResourceLoadInfo> resourceLoadInfo = responseOut.toResourceResponse().resourceLoadInfo();
     m_host->didReceiveData(m_resource, dataOut.data(), dataOut.size(), resourceLoadInfo ? resourceLoadInfo->encodedDataLength : -1, m_options);
     m_resource->setResourceBuffer(dataOut);
-    didFinishLoading(0, responseOut.responseTime());
+    didFinishLoading(0, monotonicallyIncreasingTime());
 }
 
 }
diff --git a/Source/core/fetch/TextTrackResource.cpp b/Source/core/fetch/TextTrackResource.cpp
index 5093d7e..e20d716 100644
--- a/Source/core/fetch/TextTrackResource.cpp
+++ b/Source/core/fetch/TextTrackResource.cpp
@@ -33,7 +33,7 @@
 namespace WebCore {
 
 TextTrackResource::TextTrackResource(const ResourceRequest& resourceRequest)
-    : Resource(resourceRequest, TextTrack)
+    : RawResource(resourceRequest, TextTrack)
 {
 }
 
@@ -41,13 +41,4 @@
 {
 }
 
-void TextTrackResource::appendData(const char* data, int length)
-{
-    Resource::appendData(data, length);
-    ResourceClientWalker<ResourceClient> walker(m_clients);
-    while (ResourceClient *client = walker.next())
-        client->deprecatedDidReceiveResource(this);
 }
-
-}
-
diff --git a/Source/core/fetch/TextTrackResource.h b/Source/core/fetch/TextTrackResource.h
index 3599f0b..48af088 100644
--- a/Source/core/fetch/TextTrackResource.h
+++ b/Source/core/fetch/TextTrackResource.h
@@ -26,16 +26,14 @@
 #ifndef TextTrackResource_h
 #define TextTrackResource_h
 
-#include "core/fetch/Resource.h"
+#include "core/fetch/RawResource.h"
 
 namespace WebCore {
 
-class TextTrackResource : public Resource {
+class TextTrackResource : public RawResource {
 public:
     TextTrackResource(const ResourceRequest&);
     virtual ~TextTrackResource();
-
-    virtual void appendData(const char*, int) OVERRIDE;
 };
 
 }
diff --git a/Source/core/frame/AbstractView.idl b/Source/core/frame/AbstractView.idl
deleted file mode 100644
index 01df15c..0000000
--- a/Source/core/frame/AbstractView.idl
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@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.
- */
-
-// FIXME: I believe this file is unused.  Window.idl could use it
-// but currently it just defines these interfaces itself.
-
-// Introduced in DOM Level 2:
-[
-
-] interface AbstractView {
-    readonly attribute Document document;
-    readonly attribute StyleMedia styleMedia;
-};
-
diff --git a/Source/core/frame/ConsoleBase.cpp b/Source/core/frame/ConsoleBase.cpp
index c367df8..1038da8 100644
--- a/Source/core/frame/ConsoleBase.cpp
+++ b/Source/core/frame/ConsoleBase.cpp
@@ -60,7 +60,7 @@
 
 void ConsoleBase::info(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
 {
-    log(state, arguments);
+    internalAddMessage(LogMessageType, InfoMessageLevel, state, arguments);
 }
 
 void ConsoleBase::log(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
@@ -204,7 +204,6 @@
 
     size_t stackSize = printTrace ? ScriptCallStack::maxCallStackSizeToCapture : 1;
     RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(stackSize));
-    const ScriptCallFrame& lastCaller = callStack->at(0);
 
     String message;
     bool gotStringMessage = arguments->getFirstArgumentAsString(message);
diff --git a/Source/core/frame/ConsoleTypes.h b/Source/core/frame/ConsoleTypes.h
index 6a1a4b3..d37949b 100644
--- a/Source/core/frame/ConsoleTypes.h
+++ b/Source/core/frame/ConsoleTypes.h
@@ -45,6 +45,7 @@
 enum MessageLevel {
     DebugMessageLevel = 4,
     LogMessageLevel = 1,
+    InfoMessageLevel = 5,
     WarningMessageLevel = 2,
     ErrorMessageLevel = 3
 };
diff --git a/Source/core/frame/ContentSecurityPolicy.cpp b/Source/core/frame/ContentSecurityPolicy.cpp
index 9d7e6a3..bc17809 100644
--- a/Source/core/frame/ContentSecurityPolicy.cpp
+++ b/Source/core/frame/ContentSecurityPolicy.cpp
@@ -34,14 +34,16 @@
 #include "core/dom/Document.h"
 #include "core/events/SecurityPolicyViolationEvent.h"
 #include "core/frame/ContentSecurityPolicyResponseHeaders.h"
+#include "core/frame/DOMWindow.h"
 #include "core/frame/Frame.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/inspector/ScriptCallStack.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/PingLoader.h"
 #include "core/page/UseCounter.h"
-#include "core/platform/ParsingUtilities.h"
 #include "platform/JSONValues.h"
+#include "platform/NotImplemented.h"
+#include "platform/ParsingUtilities.h"
 #include "platform/network/FormData.h"
 #include "platform/network/ResourceResponse.h"
 #include "weborigin/KURL.h"
@@ -49,11 +51,30 @@
 #include "weborigin/SchemeRegistry.h"
 #include "weborigin/SecurityOrigin.h"
 #include "wtf/HashSet.h"
+#include "wtf/SHA1.h"
+#include "wtf/StringHasher.h"
+#include "wtf/text/Base64.h"
+#include "wtf/text/StringBuilder.h"
 #include "wtf/text/TextPosition.h"
 #include "wtf/text/WTFString.h"
 
+namespace WTF {
+
+struct VectorIntHash {
+    static unsigned hash(const Vector<uint8_t>& v) { return StringHasher::computeHash(v.data(), v.size()); }
+    static bool equal(const Vector<uint8_t>& a, const Vector<uint8_t>& b) { return a == b; };
+    static const bool safeToCompareToEmptyOrDeleted = true;
+};
+template<> struct DefaultHash<Vector<uint8_t> > {
+    typedef VectorIntHash Hash;
+};
+
+} // namespace WTF
+
 namespace WebCore {
 
+typedef std::pair<unsigned, Vector<uint8_t> > SourceHashValue;
+
 // Normally WebKit uses "static" for internal linkage, but using "static" for
 // these functions causes a compile error because these functions are used as
 // template parameters.
@@ -69,7 +90,9 @@
     return isASCIISpace(c) || (c >= 0x21 && c <= 0x7e); // Whitespace + VCHAR
 }
 
-bool isNonceCharacter(UChar c)
+// Only checks for general Base64 encoded chars, not '=' chars since '=' is
+// positional and may only appear at the end of a Base64 encoded string.
+bool isBase64EncodedCharacter(UChar c)
 {
     return isASCIIAlphanumeric(c) || c == '+' || c == '/';
 }
@@ -275,6 +298,8 @@
     bool allowInline() const { return m_allowInline; }
     bool allowEval() const { return m_allowEval; }
     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; }
 
 private:
     bool parseSource(const UChar* begin, const UChar* end, String& scheme, String& host, int& port, String& path, bool& hostHasWildcard, bool& portHasWildcard);
@@ -283,12 +308,14 @@
     bool parsePort(const UChar* begin, const UChar* end, int& port, bool& portHasWildcard);
     bool parsePath(const UChar* begin, const UChar* end, String& path);
     bool parseNonce(const UChar* begin, const UChar* end, String& nonce);
+    bool parseHash(const UChar* begin, const UChar* end, Vector<uint8_t>& hash, ContentSecurityPolicy::HashAlgorithms&);
 
     void addSourceSelf();
     void addSourceStar();
     void addSourceUnsafeInline();
     void addSourceUnsafeEval();
     void addSourceNonce(const String& nonce);
+    void addSourceHash(const ContentSecurityPolicy::HashAlgorithms&, const Vector<uint8_t>& hash);
 
     ContentSecurityPolicy* m_policy;
     Vector<CSPSource> m_list;
@@ -297,6 +324,8 @@
     bool m_allowInline;
     bool m_allowEval;
     HashSet<String> m_nonces;
+    HashSet<SourceHashValue> m_hashes;
+    uint8_t m_hashAlgorithmsUsed;
 };
 
 CSPSourceList::CSPSourceList(ContentSecurityPolicy* policy, const String& directiveName)
@@ -305,6 +334,7 @@
     , m_allowStar(false)
     , m_allowInline(false)
     , m_allowEval(false)
+    , m_hashAlgorithmsUsed(0)
 {
 }
 
@@ -403,6 +433,16 @@
             addSourceNonce(nonce);
             return true;
         }
+
+        Vector<uint8_t> hash;
+        ContentSecurityPolicy::HashAlgorithms algorithm = ContentSecurityPolicy::HashAlgorithmsNone;
+        if (!parseHash(begin, end, hash, algorithm))
+            return false;
+
+        if (hash.size() > 0) {
+            addSourceHash(algorithm, hash);
+            return true;
+        }
     }
 
     const UChar* position = begin;
@@ -492,16 +532,54 @@
     const UChar* position = begin + noncePrefix.length();
     const UChar* nonceBegin = position;
 
-    skipWhile<UChar, isNonceCharacter>(position, end);
+    skipWhile<UChar, isBase64EncodedCharacter>(position, end);
     ASSERT(nonceBegin <= position);
 
-    if (((position + 1) != end  && *position != '\'') || !(position - nonceBegin))
+    if ((position + 1) != end  || *position != '\'' || !(position - nonceBegin))
         return false;
 
     nonce = String(nonceBegin, position - nonceBegin);
     return true;
 }
 
+// hash-source       = "'" hash-algorithm "-" hash-value "'"
+// hash-algorithm    = "sha1" / "sha256"
+// hash-value        = 1*( ALPHA / DIGIT / "+" / "/" / "=" )
+//
+bool CSPSourceList::parseHash(const UChar* begin, const UChar* end, Vector<uint8_t>& hash, ContentSecurityPolicy::HashAlgorithms& hashAlgorithm)
+{
+    DEFINE_STATIC_LOCAL(const String, sha1Prefix, ("'sha1-"));
+    DEFINE_STATIC_LOCAL(const String, sha256Prefix, ("'sha256-"));
+
+    String prefix;
+    if (equalIgnoringCase(sha1Prefix.characters8(), begin, sha1Prefix.length())) {
+        prefix = sha1Prefix;
+        hashAlgorithm = ContentSecurityPolicy::HashAlgorithmsSha1;
+    } else if (equalIgnoringCase(sha256Prefix.characters8(), begin, sha256Prefix.length())) {
+        notImplemented();
+    } else {
+        return true;
+    }
+
+    const UChar* position = begin + prefix.length();
+    const UChar* hashBegin = position;
+
+    skipWhile<UChar, isBase64EncodedCharacter>(position, end);
+    ASSERT(hashBegin <= position);
+
+    // Base64 encodings may end with exactly one or two '=' characters
+    skipExactly<UChar>(position, position + 1, '=');
+    skipExactly<UChar>(position, position + 1, '=');
+
+    if ((position + 1) != end  || *position != '\'' || !(position - hashBegin))
+        return false;
+
+    Vector<char> hashVector;
+    base64Decode(hashBegin, position - hashBegin, hashVector);
+    hash.append(reinterpret_cast<uint8_t*>(hashVector.data()), hashVector.size());
+    return true;
+}
+
 //                     ; <scheme> production from RFC 3986
 // scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
 //
@@ -644,6 +722,12 @@
     m_nonces.add(nonce);
 }
 
+void CSPSourceList::addSourceHash(const ContentSecurityPolicy::HashAlgorithms& algorithm, const Vector<uint8_t>& hash)
+{
+    m_hashes.add(SourceHashValue(algorithm, hash));
+    m_hashAlgorithmsUsed |= algorithm;
+}
+
 class CSPDirective {
 public:
     CSPDirective(const String& name, const String& value, ContentSecurityPolicy* policy)
@@ -760,6 +844,9 @@
     bool allowInline() const { return m_sourceList.allowInline(); }
     bool allowEval() const { return m_sourceList.allowEval(); }
     bool allowNonce(const String& nonce) const { return m_sourceList.allowNonce(nonce.stripWhiteSpace()); }
+    bool allowHash(const SourceHashValue& hashValue) const { return m_sourceList.allowHash(hashValue); }
+
+    uint8_t hashAlgorithmsUsed() const { return m_sourceList.hashAlgorithmsUsed(); }
 
 private:
     CSPSourceList m_sourceList;
@@ -794,6 +881,7 @@
     bool allowBaseURI(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
     bool allowScriptNonce(const String&) const;
     bool allowStyleNonce(const String&) const;
+    bool allowScriptHash(const SourceHashValue&) const;
 
     void gatherReportURIs(DOMStringList&) const;
     const String& evalDisabledErrorMessage() const { return m_evalDisabledErrorMessage; }
@@ -822,6 +910,7 @@
     bool checkEval(SourceListDirective*) const;
     bool checkInline(SourceListDirective*) const;
     bool checkNonce(SourceListDirective*, const String&) const;
+    bool checkHash(SourceListDirective*, const SourceHashValue&) const;
     bool checkSource(SourceListDirective*, const KURL&) const;
     bool checkMediaType(MediaListDirective*, const String& type, const String& typeAttribute) const;
 
@@ -891,21 +980,21 @@
 void CSPDirectiveList::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL) const
 {
     String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
-    m_policy->executionContext()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+    m_policy->client()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
     m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
 }
 
 void CSPDirectiveList::reportViolationWithLocation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const String& contextURL, const WTF::OrdinalNumber& contextLine) const
 {
     String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
-    m_policy->executionContext()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, contextURL, contextLine.oneBasedInt());
+    m_policy->client()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, contextURL, contextLine.oneBasedInt());
     m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
 }
 
 void CSPDirectiveList::reportViolationWithState(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, ScriptState* state) const
 {
     String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
-    m_policy->executionContext()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, state);
+    m_policy->client()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, state);
     m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
 }
 
@@ -924,6 +1013,11 @@
     return !directive || directive->allowNonce(nonce);
 }
 
+bool CSPDirectiveList::checkHash(SourceListDirective* directive, const SourceHashValue& hashValue) const
+{
+    return !directive || directive->allowHash(hashValue);
+}
+
 bool CSPDirectiveList::checkSource(SourceListDirective* directive, const KURL& url) const
 {
     return !directive || directive->allows(url);
@@ -1166,6 +1260,11 @@
     return checkNonce(operativeDirective(m_styleSrc.get()), nonce);
 }
 
+bool CSPDirectiveList::allowScriptHash(const SourceHashValue& hashValue) const
+{
+    return checkHash(operativeDirective(m_scriptSrc.get()), hashValue);
+}
+
 // policy            = directive-list
 // directive-list    = [ directive *( ";" [ directive ] ) ]
 //
@@ -1353,6 +1452,7 @@
         setCSPDirective<SourceListDirective>(name, value, m_defaultSrc);
     } else if (equalIgnoringCase(name, scriptSrc)) {
         setCSPDirective<SourceListDirective>(name, value, m_scriptSrc);
+        m_policy->usesScriptHashAlgorithms(m_scriptSrc->hashAlgorithmsUsed());
     } else if (equalIgnoringCase(name, objectSrc)) {
         setCSPDirective<SourceListDirective>(name, value, m_objectSrc);
     } else if (equalIgnoringCase(name, frameSrc)) {
@@ -1387,9 +1487,10 @@
     }
 }
 
-ContentSecurityPolicy::ContentSecurityPolicy(ExecutionContext* executionContext)
-    : m_executionContext(executionContext)
+ContentSecurityPolicy::ContentSecurityPolicy(ExecutionContextClient* client)
+    : m_client(client)
     , m_overrideInlineStyleAllowed(false)
+    , m_sourceHashAlgorithmsUsed(HashAlgorithmsNone)
 {
 }
 
@@ -1412,8 +1513,8 @@
         didReceiveHeader(headers.contentSecurityPolicyReportOnly(), ContentSecurityPolicy::Report);
 
     // FIXME: Remove this reporting (and the 'xWebKitCSP*' methods) after the next release branch.
-    if (m_executionContext->isDocument()) {
-        Document* document = toDocument(m_executionContext);
+    if (m_client->isDocument()) {
+        Document* document = static_cast<Document*>(m_client);
         if (!headers.xWebKitCSP().isEmpty())
             UseCounter::countDeprecation(*document, UseCounter::PrefixedContentSecurityPolicy);
         if (!headers.xWebKitCSPReportOnly().isEmpty())
@@ -1428,8 +1529,8 @@
 
 void ContentSecurityPolicy::addPolicyFromHeaderValue(const String& header, HeaderType type)
 {
-    if (m_executionContext->isDocument()) {
-        Document* document = toDocument(m_executionContext);
+    if (m_client->isDocument()) {
+        Document* document = static_cast<Document*>(m_client);
         UseCounter::count(*document, getUseCounterType(type));
     }
 
@@ -1452,7 +1553,7 @@
 
         // 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))
-            m_executionContext->disableEval(policy->evalDisabledErrorMessage());
+            m_client->disableEval(policy->evalDisabledErrorMessage());
 
         m_policies.append(policy.release());
 
@@ -1517,6 +1618,17 @@
     }
     return true;
 }
+
+template<bool (CSPDirectiveList::*allowed)(const SourceHashValue&) const>
+bool isAllowedByAllWithHash(const CSPDirectiveListVector& policies, const SourceHashValue& hashValue)
+{
+    for (size_t i = 0; i < policies.size(); ++i) {
+        if (!(policies[i].get()->*allowed)(hashValue))
+            return false;
+    }
+    return true;
+}
+
 template<bool (CSPDirectiveList::*allowFromURL)(const KURL&, ContentSecurityPolicy::ReportingStatus) const>
 bool isAllowedByAllWithURL(const CSPDirectiveListVector& policies, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus)
 {
@@ -1590,6 +1702,28 @@
     return isAllowedByAllWithNonce<&CSPDirectiveList::allowStyleNonce>(m_policies, nonce);
 }
 
+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) {
+        Vector<uint8_t, 20> digest;
+        SHA1 sourceSha1;
+        sourceSha1.addBytes(UTF8Encoding().normalizeAndEncode(source, WTF::EntitiesForUnencodables));
+        sourceSha1.computeHash(digest);
+
+        if (isAllowedByAllWithHash<&CSPDirectiveList::allowScriptHash>(m_policies, SourceHashValue(HashAlgorithmsSha1, Vector<uint8_t>(digest))))
+            return true;
+    }
+
+    return false;
+}
+
+void ContentSecurityPolicy::usesScriptHashAlgorithms(uint8_t algorithms)
+{
+    m_sourceHashAlgorithmsUsed |= algorithms;
+}
+
 bool ContentSecurityPolicy::allowObjectFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
     return isAllowedByAllWithURL<&CSPDirectiveList::allowObjectFromSource>(m_policies, url, reportingStatus);
@@ -1658,23 +1792,23 @@
 
 SecurityOrigin* ContentSecurityPolicy::securityOrigin() const
 {
-    return m_executionContext->securityOrigin();
+    return m_client->securityContext().securityOrigin();
 }
 
-const KURL& ContentSecurityPolicy::url() const
+const KURL ContentSecurityPolicy::url() const
 {
-    return m_executionContext->url();
+    return m_client->contextURL();
 }
 
 KURL ContentSecurityPolicy::completeURL(const String& url) const
 {
-    return m_executionContext->completeURL(url);
+    return m_client->contextCompleteURL(url);
 }
 
 void ContentSecurityPolicy::enforceSandboxFlags(SandboxFlags mask) const
 {
-    if (m_executionContext->isDocument())
-        toDocument(m_executionContext)->enforceSandboxFlags(mask);
+    if (m_client->isDocument())
+        static_cast<Document*>(m_client)->enforceSandboxFlags(mask);
 }
 
 static String stripURLForUseInReport(Document* document, const KURL& url)
@@ -1719,10 +1853,10 @@
 void ContentSecurityPolicy::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header)
 {
     // FIXME: Support sending reports from worker.
-    if (!m_executionContext->isDocument())
+    if (!m_client->isDocument())
         return;
 
-    Document* document = toDocument(m_executionContext);
+    Document* document = static_cast<Document*>(m_client);
     Frame* frame = document->frame();
     if (!frame)
         return;
@@ -1731,7 +1865,7 @@
     gatherSecurityPolicyViolationEventData(violationData, document, directiveText, effectiveDirective, blockedURL, header);
 
     if (experimentalFeaturesEnabled())
-        document->enqueueDocumentEvent(SecurityPolicyViolationEvent::create(EventTypeNames::securitypolicyviolation, violationData));
+        frame->domWindow()->enqueueDocumentEvent(SecurityPolicyViolationEvent::create(EventTypeNames::securitypolicyviolation, violationData));
 
     if (reportURIs.isEmpty())
         return;
@@ -1845,12 +1979,6 @@
     logToConsole(message);
 }
 
-void ContentSecurityPolicy::reportInvalidNonce(const String& nonce) const
-{
-    String message = "Ignoring invalid Content Security Policy script nonce: '" + nonce + "'.\n";
-    logToConsole(message);
-}
-
 void ContentSecurityPolicy::reportInvalidSourceExpression(const String& directiveName, const String& source) const
 {
     String message = "The source list for Content Security Policy directive '" + directiveName + "' contains an invalid source: '" + source + "'. It will be ignored.";
@@ -1866,12 +1994,12 @@
 
 void ContentSecurityPolicy::logToConsole(const String& message) const
 {
-    m_executionContext->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+    m_client->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
 }
 
 void ContentSecurityPolicy::reportBlockedScriptExecutionToInspector(const String& directiveText) const
 {
-    InspectorInstrumentation::scriptExecutionBlockedByCSP(m_executionContext, directiveText);
+    m_client->reportBlockedScriptExecutionToInspector(directiveText);
 }
 
 bool ContentSecurityPolicy::experimentalFeaturesEnabled() const
@@ -1884,7 +2012,7 @@
     if (context && context->isDocument()) {
         Document* document = toDocument(context);
         if (document->frame())
-            return document->frame()->script()->shouldBypassMainWorldContentSecurityPolicy();
+            return document->frame()->script().shouldBypassMainWorldContentSecurityPolicy();
     }
     return false;
 }
diff --git a/Source/core/frame/ContentSecurityPolicy.h b/Source/core/frame/ContentSecurityPolicy.h
index f571d46..0720123 100644
--- a/Source/core/frame/ContentSecurityPolicy.h
+++ b/Source/core/frame/ContentSecurityPolicy.h
@@ -46,7 +46,7 @@
 class DOMStringList;
 class JSONObject;
 class KURL;
-class ExecutionContext;
+class ExecutionContextClient;
 class SecurityOrigin;
 
 typedef int SandboxFlags;
@@ -55,9 +55,9 @@
 class ContentSecurityPolicy {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<ContentSecurityPolicy> create(ExecutionContext* executionContext)
+    static PassOwnPtr<ContentSecurityPolicy> create(ExecutionContextClient* client)
     {
-        return adoptPtr(new ContentSecurityPolicy(executionContext));
+        return adoptPtr(new ContentSecurityPolicy(client));
     }
     ~ContentSecurityPolicy();
 
@@ -73,6 +73,12 @@
         SuppressReport
     };
 
+    enum HashAlgorithms {
+        HashAlgorithmsNone   = 0,
+        HashAlgorithmsSha1   = 1 << 1,
+        HashAlgorithmsSha256 = 1 << 2
+    };
+
     void didReceiveHeaders(const ContentSecurityPolicyResponseHeaders&);
     void didReceiveHeader(const String&, HeaderType);
 
@@ -98,8 +104,13 @@
     bool allowConnectToSource(const KURL&, ReportingStatus = SendReport) const;
     bool allowFormAction(const KURL&, ReportingStatus = SendReport) const;
     bool allowBaseURI(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;
+
+    void usesScriptHashAlgorithms(uint8_t HashAlgorithms);
 
     ReflectedXSSDisposition reflectedXSSDisposition() const;
 
@@ -112,7 +123,6 @@
     void reportDuplicateDirective(const String&) const;
     void reportInvalidDirectiveValueCharacter(const String& directiveName, const String& value) const;
     void reportInvalidPathCharacter(const String& directiveName, const String& value, const char) const;
-    void reportInvalidNonce(const String&) const;
     void reportInvalidPluginTypes(const String&) const;
     void reportInvalidSandboxFlags(const String&) const;
     void reportInvalidSourceExpression(const String& directiveName, const String& source) const;
@@ -123,7 +133,7 @@
 
     void reportBlockedScriptExecutionToInspector(const String& directiveText) const;
 
-    const KURL& url() const;
+    const KURL url() const;
     KURL completeURL(const String&) const;
     SecurityOrigin* securityOrigin() const;
     void enforceSandboxFlags(SandboxFlags) const;
@@ -133,10 +143,10 @@
 
     static bool shouldBypassMainWorld(ExecutionContext*);
 
-    ExecutionContext* executionContext() { return m_executionContext; }
+    ExecutionContextClient* client() { return m_client; }
 
 private:
-    explicit ContentSecurityPolicy(ExecutionContext*);
+    explicit ContentSecurityPolicy(ExecutionContextClient*);
 
     void logToConsole(const String& message) const;
     void addPolicyFromHeaderValue(const String&, HeaderType);
@@ -144,11 +154,16 @@
     bool shouldSendViolationReport(const String&) const;
     void didSendViolationReport(const String&);
 
-    ExecutionContext* m_executionContext;
+    ExecutionContextClient* m_client;
     bool m_overrideInlineStyleAllowed;
     CSPDirectiveListVector m_policies;
 
     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;
 };
 
 }
diff --git a/Source/core/frame/DOMWindow.cpp b/Source/core/frame/DOMWindow.cpp
index 551d5fb..ef36024 100644
--- a/Source/core/frame/DOMWindow.cpp
+++ b/Source/core/frame/DOMWindow.cpp
@@ -29,6 +29,7 @@
 
 #include <algorithm>
 #include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "bindings/v8/ScriptCallStackFactory.h"
@@ -41,15 +42,20 @@
 #include "core/css/MediaQueryMatcher.h"
 #include "core/css/StyleMedia.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/dom/ContextFeatures.h"
+#include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExecutionContext.h"
 #include "core/dom/RequestAnimationFrameCallback.h"
 #include "core/editing/Editor.h"
+#include "core/events/DOMWindowEventQueue.h"
 #include "core/events/EventListener.h"
+#include "core/events/HashChangeEvent.h"
 #include "core/events/MessageEvent.h"
 #include "core/events/PageTransitionEvent.h"
+#include "core/events/PopStateEvent.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/frame/Console.h"
 #include "core/frame/DOMPoint.h"
@@ -65,6 +71,7 @@
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
 #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"
@@ -333,35 +340,59 @@
     ScriptWrappable::init(this);
 }
 
-void DOMWindow::setDocument(PassRefPtr<Document> document)
+void DOMWindow::clearDocument()
 {
-    ASSERT(!document || document->frame() == m_frame);
-    if (m_document) {
-        if (m_document->confusingAndOftenMisusedAttached()) {
-            // FIXME: We don't call willRemove here. Why is that OK?
-            // This detach() call is also mostly redundant. Most of the calls to
-            // this function come via DocumentLoader::createWriterFor, which
-            // always detaches the previous Document first. Only XSLTProcessor
-            // depends on this detach() call, so it seems like there's some room
-            // for cleanup.
-            m_document->detach();
-        }
-        m_document->setDOMWindow(0);
-    }
-
-    m_document = document;
-
     if (!m_document)
         return;
 
-    m_document->setDOMWindow(this);
+    if (m_document->confusingAndOftenMisusedAttached()) {
+        // FIXME: We don't call willRemove here. Why is that OK?
+        // This detach() call is also mostly redundant. Most of the calls to
+        // this function come via DocumentLoader::createWriterFor, which
+        // always detaches the previous Document first. Only XSLTProcessor
+        // depends on this detach() call, so it seems like there's some room
+        // for cleanup.
+        m_document->detach();
+        m_eventQueue->close();
+    }
+
+    m_eventQueue.clear();
+
+    m_document->clearDOMWindow();
+    m_document = 0;
+}
+
+PassRefPtr<Document> DOMWindow::createDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
+{
+    RefPtr<Document> document;
+    if (forceXHTML) {
+        // This is a hack for XSLTProcessor. See XSLTProcessor::createDocumentFromSource().
+        document = Document::create(init);
+    } else {
+        document = DOMImplementation::createDocument(mimeType, init, init.frame() ? init.frame()->inViewSourceMode() : false);
+        if (document->isPluginDocument() && document->isSandboxed(SandboxPlugins))
+            document = SinkDocument::create(init);
+    }
+
+    return document.release();
+}
+
+PassRefPtr<Document> DOMWindow::installNewDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
+{
+    ASSERT(init.frame() == m_frame);
+
+    clearDocument();
+
+    m_document = createDocument(mimeType, init, forceXHTML);
+    m_eventQueue = DOMWindowEventQueue::create(m_document.get());
+
     if (!m_document->confusingAndOftenMisusedAttached())
         m_document->attach();
 
     if (!m_frame)
-        return;
+        return m_document;
 
-    m_frame->script()->updateDocument();
+    m_frame->script().updateDocument();
     m_document->updateViewportDescription();
 
     if (m_frame->page() && m_frame->view()) {
@@ -379,6 +410,71 @@
         if (m_document->hasTouchEventHandlers())
             m_frame->page()->chrome().client().needTouchEvents(true);
     }
+
+    return m_document;
+}
+
+EventQueue* DOMWindow::eventQueue() const
+{
+    return m_eventQueue.get();
+}
+
+void DOMWindow::enqueueWindowEvent(PassRefPtr<Event> event)
+{
+    event->setTarget(this);
+    m_eventQueue->enqueueEvent(event);
+}
+
+void DOMWindow::enqueueDocumentEvent(PassRefPtr<Event> event)
+{
+    event->setTarget(m_document);
+    m_eventQueue->enqueueEvent(event);
+}
+
+void DOMWindow::dispatchWindowLoadEvent()
+{
+    ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
+    dispatchLoadEvent();
+}
+
+void DOMWindow::documentWasClosed()
+{
+    dispatchWindowLoadEvent();
+    enqueuePageshowEvent(PageshowEventNotPersisted);
+    enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
+}
+
+void DOMWindow::enqueuePageshowEvent(PageshowEventPersistence persisted)
+{
+    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
+    dispatchEvent(PageTransitionEvent::create(EventTypeNames::pageshow, persisted), m_document.get());
+}
+
+void DOMWindow::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
+{
+    enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
+}
+
+void DOMWindow::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
+{
+    if (!ContextFeatures::pushStateEnabled(document()))
+        return;
+
+    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
+    dispatchEvent(PopStateEvent::create(stateObject, history()));
+}
+
+void DOMWindow::statePopped(PassRefPtr<SerializedScriptValue> stateObject)
+{
+    if (!frame())
+        return;
+
+    // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
+    // defer firing of popstate until we're in the complete state.
+    if (document()->isLoadCompleted())
+        enqueuePopstateEvent(stateObject);
+    else
+        m_pendingStateObject = stateObject;
 }
 
 DOMWindow::~DOMWindow()
@@ -405,7 +501,7 @@
     removeAllEventListeners();
 
     ASSERT(!m_document->confusingAndOftenMisusedAttached());
-    setDocument(0);
+    clearDocument();
 }
 
 const AtomicString& DOMWindow::interfaceName() const
@@ -425,7 +521,7 @@
 
 PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
 {
-    return document() ? document()->mediaQueryMatcher()->matchMedia(media) : 0;
+    return document() ? document()->mediaQueryMatcher().matchMedia(media) : 0;
 }
 
 Page* DOMWindow::page()
@@ -541,6 +637,7 @@
 
 BarProp* DOMWindow::locationbar() const
 {
+    UseCounter::count(this, UseCounter::BarPropLocationbar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_locationbar)
@@ -550,6 +647,7 @@
 
 BarProp* DOMWindow::menubar() const
 {
+    UseCounter::count(this, UseCounter::BarPropMenubar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_menubar)
@@ -559,6 +657,7 @@
 
 BarProp* DOMWindow::personalbar() const
 {
+    UseCounter::count(this, UseCounter::BarPropPersonalbar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_personalbar)
@@ -568,6 +667,7 @@
 
 BarProp* DOMWindow::scrollbars() const
 {
+    UseCounter::count(this, UseCounter::BarPropScrollbars);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_scrollbars)
@@ -577,6 +677,7 @@
 
 BarProp* DOMWindow::statusbar() const
 {
+    UseCounter::count(this, UseCounter::BarPropStatusbar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_statusbar)
@@ -586,6 +687,7 @@
 
 BarProp* DOMWindow::toolbar() const
 {
+    UseCounter::count(this, UseCounter::BarPropToolbar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_toolbar)
@@ -788,7 +890,7 @@
     // Give the embedder a chance to intercept this postMessage because this
     // DOMWindow might be a proxy for another in browsers that support
     // postMessage calls across WebKit instances.
-    if (m_frame->loader()->client()->willCheckAndDispatchMessageEvent(timer->targetOrigin(), event.get()))
+    if (m_frame->loader().client()->willCheckAndDispatchMessageEvent(timer->targetOrigin(), event.get()))
         return;
 
     event->entangleMessagePorts(document());
@@ -800,8 +902,7 @@
     if (intendedTargetOrigin) {
         // Check target origin now since the target document may have changed since the timer was scheduled.
         if (!intendedTargetOrigin->isSameSchemeHostPort(document()->securityOrigin())) {
-            String message = "Unable to post message to " + intendedTargetOrigin->toString() +
-                             ". Recipient has origin " + document()->securityOrigin()->toString() + ".\n";
+            String message = ExceptionMessages::failedToExecute("postMessage", "DOMWindow", "The target origin provided ('" + intendedTargetOrigin->toString() + "') does not match the recipient window's origin ('" + document()->securityOrigin()->toString() + "').");
             pageConsole()->addMessage(SecurityMessageSource, ErrorMessageLevel, message, stackTrace);
             return;
         }
@@ -850,7 +951,7 @@
     if (!m_frame)
         return;
 
-    m_frame->eventHandler()->focusDocumentView();
+    m_frame->eventHandler().focusDocumentView();
 }
 
 void DOMWindow::blur()
@@ -882,10 +983,12 @@
     Settings* settings = m_frame->settings();
     bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
 
-    if (!(page->openedByDOM() || page->backForward().backForwardListCount() <= 1 || allowScriptsToCloseWindows))
+    if (!(page->openedByDOM() || page->backForward().backForwardListCount() <= 1 || allowScriptsToCloseWindows)) {
+        pageConsole()->addMessage(JSMessageSource, WarningMessageLevel, "Scripts may close only the windows that were opened by it.");
         return;
+    }
 
-    if (!m_frame->loader()->shouldClose())
+    if (!m_frame->loader().shouldClose())
         return;
 
     page->chrome().closeWindowSoon();
@@ -900,7 +1003,7 @@
     if (!page)
         return;
 
-    if (m_frame->loader()->activeDocumentLoader()->isLoading()) {
+    if (m_frame->loader().activeDocumentLoader()->isLoading()) {
         m_shouldPrintWhenFinishedLoading = true;
         return;
     }
@@ -912,7 +1015,7 @@
 {
     if (!m_frame)
         return;
-    m_frame->loader()->stopAllLoaders();
+    m_frame->loader().stopAllLoaders();
 }
 
 void DOMWindow::alert(const String& message)
@@ -1013,7 +1116,7 @@
         return 0;
 
     // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
-    if (Frame* parent = m_frame->tree()->parent())
+    if (Frame* parent = m_frame->tree().parent())
         parent->document()->updateLayoutIgnorePendingStylesheets();
 
     return view->mapFromLayoutToCSSUnits(static_cast<int>(view->visibleContentRect(ScrollableArea::IncludeScrollbars).height()));
@@ -1029,7 +1132,7 @@
         return 0;
 
     // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
-    if (Frame* parent = m_frame->tree()->parent())
+    if (Frame* parent = m_frame->tree().parent())
         parent->document()->updateLayoutIgnorePendingStylesheets();
 
     return view->mapFromLayoutToCSSUnits(static_cast<int>(view->visibleContentRect(ScrollableArea::IncludeScrollbars).width()));
@@ -1101,7 +1204,7 @@
     if (!isCurrentlyDisplayedInFrame())
         return 0;
 
-    return m_frame->tree()->scopedChildCount();
+    return m_frame->tree().scopedChildCount();
 }
 
 String DOMWindow::name() const
@@ -1109,7 +1212,7 @@
     if (!m_frame)
         return String();
 
-    return m_frame->tree()->name();
+    return m_frame->tree().name();
 }
 
 void DOMWindow::setName(const String& string)
@@ -1117,8 +1220,8 @@
     if (!m_frame)
         return;
 
-    m_frame->tree()->setName(string);
-    m_frame->loader()->client()->didChangeName(string);
+    m_frame->tree().setName(string);
+    m_frame->loader().client()->didChangeName(string);
 }
 
 void DOMWindow::setStatus(const String& string)
@@ -1164,7 +1267,7 @@
     if (!m_frame)
         return 0;
 
-    Frame* opener = m_frame->loader()->opener();
+    Frame* opener = m_frame->loader().opener();
     if (!opener)
         return 0;
 
@@ -1176,7 +1279,7 @@
     if (!m_frame)
         return 0;
 
-    Frame* parent = m_frame->tree()->parent();
+    Frame* parent = m_frame->tree().parent();
     if (parent)
         return parent->domWindow();
 
@@ -1192,7 +1295,7 @@
     if (!page)
         return 0;
 
-    return m_frame->tree()->top()->domWindow();
+    return m_frame->tree().top()->domWindow();
 }
 
 Document* DOMWindow::document() const
@@ -1433,7 +1536,7 @@
             didAddStorageEventListener(this);
     }
 
-    lifecycleNotifier()->notifyAddEventListener(this, eventType);
+    lifecycleNotifier().notifyAddEventListener(this, eventType);
 
     if (eventType == EventTypeNames::unload) {
         addUnloadEventListener(this);
@@ -1465,7 +1568,7 @@
             document->didRemoveTouchEventHandler(document);
     }
 
-    lifecycleNotifier()->notifyRemoveEventListener(this, eventType);
+    lifecycleNotifier().notifyRemoveEventListener(this, eventType);
 
     if (eventType == EventTypeNames::unload) {
         removeUnloadEventListener(this);
@@ -1482,10 +1585,10 @@
 void DOMWindow::dispatchLoadEvent()
 {
     RefPtr<Event> loadEvent(Event::create(EventTypeNames::load));
-    if (m_frame && m_frame->loader()->documentLoader() && !m_frame->loader()->documentLoader()->timing()->loadEventStart()) {
+    if (m_frame && m_frame->loader().documentLoader() && !m_frame->loader().documentLoader()->timing()->loadEventStart()) {
         // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
         // the event, so protect it to prevent writing the end time into freed memory.
-        RefPtr<DocumentLoader> documentLoader = m_frame->loader()->documentLoader();
+        RefPtr<DocumentLoader> documentLoader = m_frame->loader().documentLoader();
         DocumentLoadTiming* timing = documentLoader->timing();
         timing->markLoadEventStart();
         dispatchEvent(loadEvent, document());
@@ -1505,6 +1608,8 @@
 
 bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
 {
+    ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
+
     RefPtr<EventTarget> protect = this;
     RefPtr<Event> event = prpEvent;
 
@@ -1525,7 +1630,7 @@
 {
     EventTarget::removeAllEventListeners();
 
-    lifecycleNotifier()->notifyRemoveAllEventListeners(this);
+    lifecycleNotifier().notifyRemoveAllEventListeners(this);
 
     if (NewDeviceOrientationController* controller = NewDeviceOrientationController::from(document()))
         controller->stopUpdating();
@@ -1568,9 +1673,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->securityOrigin(),
         // FIXME: What if activeDocument()->frame() is 0?
-        completedURL, activeDocument->frame()->loader()->outgoingReferrer(),
+        completedURL, activeDocument->frame()->loader().outgoingReferrer(),
         locking != LockHistoryBasedOnGestureState);
 }
 
@@ -1683,7 +1788,7 @@
     if (!firstWindow->allowPopUp()) {
         // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
         // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
-        if (frameName.isEmpty() || !m_frame->tree()->find(frameName))
+        if (frameName.isEmpty() || !m_frame->tree().find(frameName))
             return 0;
     }
 
@@ -1691,9 +1796,9 @@
     // In those cases, we schedule a location change right now and return early.
     Frame* targetFrame = 0;
     if (frameName == "_top")
-        targetFrame = m_frame->tree()->top();
+        targetFrame = m_frame->tree().top();
     else if (frameName == "_parent") {
-        if (Frame* parent = m_frame->tree()->parent())
+        if (Frame* parent = m_frame->tree().parent())
             targetFrame = parent;
         else
             targetFrame = m_frame;
@@ -1712,10 +1817,10 @@
 
         // 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(
+        targetFrame->navigationScheduler().scheduleLocationChange(
             activeDocument->securityOrigin(),
             completedURL,
-            firstFrame->loader()->outgoingReferrer(),
+            firstFrame->loader().outgoingReferrer(),
             false);
         return targetFrame->domWindow();
     }
@@ -1755,19 +1860,19 @@
     if (!frame)
         return 0;
 
-    Frame* child = frame->tree()->scopedChild(index);
+    Frame* child = frame->tree().scopedChild(index);
     if (child)
         return child->domWindow();
 
     return 0;
 }
 
-DOMWindowLifecycleNotifier* DOMWindow::lifecycleNotifier()
+DOMWindowLifecycleNotifier& DOMWindow::lifecycleNotifier()
 {
-    return static_cast<DOMWindowLifecycleNotifier*>(LifecycleContext::lifecycleNotifier());
+    return static_cast<DOMWindowLifecycleNotifier&>(LifecycleContext::lifecycleNotifier());
 }
 
-PassOwnPtr<LifecycleNotifier> DOMWindow::createLifecycleNotifier()
+PassOwnPtr<LifecycleNotifier<DOMWindow> > DOMWindow::createLifecycleNotifier()
 {
     return DOMWindowLifecycleNotifier::create(this);
 }
diff --git a/Source/core/frame/DOMWindow.h b/Source/core/frame/DOMWindow.h
index c203a69..9632a7f 100644
--- a/Source/core/frame/DOMWindow.h
+++ b/Source/core/frame/DOMWindow.h
@@ -30,7 +30,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/events/EventTarget.h"
 #include "core/frame/FrameDestructionObserver.h"
-#include "core/platform/LifecycleContext.h"
+#include "platform/LifecycleContext.h"
 #include "platform/Supplementable.h"
 
 #include "wtf/Forward.h"
@@ -48,9 +48,12 @@
     class Database;
     class DatabaseCallback;
     class Document;
+    class DocumentInit;
+    class DOMWindowEventQueue;
     class DOMWindowLifecycleNotifier;
     class Element;
     class EventListener;
+    class EventQueue;
     class ExceptionState;
     class FloatRect;
     class Frame;
@@ -79,22 +82,21 @@
 
     typedef Vector<RefPtr<MessagePort>, 1> MessagePortArray;
 
+enum PageshowEventPersistence {
+    PageshowEventNotPersisted = 0,
+    PageshowEventPersisted = 1
+};
+
     enum SetLocationLocking { LockHistoryBasedOnGestureState, LockHistoryAndBackForwardList };
 
-    class DOMWindow : public RefCounted<DOMWindow>, public ScriptWrappable, public EventTargetWithInlineData, public FrameDestructionObserver, public Supplementable<DOMWindow>, public LifecycleContext {
+    class DOMWindow : 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);
         static PassRefPtr<DOMWindow> create(Frame* frame) { return adoptRef(new DOMWindow(frame)); }
         virtual ~DOMWindow();
 
-        // 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
-        // synchronously but kicks off the load in the window asynchronously. Web sites
-        // expect that modifications that they make to the window object synchronously
-        // won't be blown away when the network load commits. To make that happen, we
-        // "securely transition" the existing DOMWindow to the Document that results from
-        // the network load. See also SecurityContext::isSecureTransitionTo.
-        void setDocument(PassRefPtr<Document>);
+        PassRefPtr<Document> installNewDocument(const String& mimeType, const DocumentInit&, bool forceXHTML = false);
 
         virtual const AtomicString& interfaceName() const OVERRIDE;
         virtual ExecutionContext* executionContext() const OVERRIDE;
@@ -257,79 +259,11 @@
 
         void dispatchLoadEvent();
 
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(animationend);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(animationiteration);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(animationstart);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(beforeunload);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(blur);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(cancel);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(canplay);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(canplaythrough);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(close);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(contextmenu);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(cuechange);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(dblclick);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(drag);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(dragend);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(dragenter);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(dragleave);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(dragover);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(dragstart);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(drop);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(durationchange);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(emptied);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(ended);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(focus);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(hashchange);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(input);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(invalid);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(keydown);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(keypress);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(keyup);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(loadeddata);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(loadedmetadata);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(mousedown);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseenter);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseleave);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(mousemove);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseout);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseover);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseup);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(mousewheel);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(offline);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(online);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(pagehide);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(pageshow);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(pause);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(play);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(playing);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(popstate);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(ratechange);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(reset);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(resize);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(seeked);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(seeking);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(show);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(stalled);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(storage);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(suspend);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(timeupdate);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(transitionend);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(unload);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(volumechange);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(waiting);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
 
         DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationstart, webkitAnimationStart);
@@ -381,19 +315,29 @@
 
         bool isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString);
 
+        PassOwnPtr<LifecycleNotifier<DOMWindow> > createLifecycleNotifier();
+
+        EventQueue* eventQueue() const;
+        void enqueueWindowEvent(PassRefPtr<Event>);
+        void enqueueDocumentEvent(PassRefPtr<Event>);
+        void enqueuePageshowEvent(PageshowEventPersistence);
+        void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
+        void enqueuePopstateEvent(PassRefPtr<SerializedScriptValue>);
+        void dispatchWindowLoadEvent();
+        void documentWasClosed();
+        void statePopped(PassRefPtr<SerializedScriptValue>);
     protected:
-        DOMWindowLifecycleNotifier* lifecycleNotifier();
+        DOMWindowLifecycleNotifier& lifecycleNotifier();
 
     private:
         explicit DOMWindow(Frame*);
 
         Page* page();
 
-        virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
-
         virtual void frameDestroyed() OVERRIDE;
         virtual void willDetachPage() OVERRIDE;
 
+        void clearDocument();
         void resetDOMWindowProperties();
         void willDestroyDocumentInFrame();
 
@@ -426,6 +370,9 @@
         mutable RefPtr<Performance> m_performance;
 
         mutable RefPtr<DOMWindowCSS> m_css;
+
+        RefPtr<DOMWindowEventQueue> m_eventQueue;
+        RefPtr<SerializedScriptValue> m_pendingStateObject;
     };
 
     inline String DOMWindow::status() const
diff --git a/Source/core/frame/DOMWindowEventHandlers.h b/Source/core/frame/DOMWindowEventHandlers.h
new file mode 100644
index 0000000..bf89771
--- /dev/null
+++ b/Source/core/frame/DOMWindowEventHandlers.h
@@ -0,0 +1,53 @@
+/*
+ * 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 DOMWindowEventHandlers_h
+#define DOMWindowEventHandlers_h
+
+#include "core/events/EventTarget.h"
+
+namespace WebCore {
+
+namespace DOMWindowEventHandlers {
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeunload);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(hashchange);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(message);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(offline);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(online);
+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);
+}
+
+} // namespace
+
+#endif
diff --git a/Source/core/frame/DOMWindowLifecycleNotifier.cpp b/Source/core/frame/DOMWindowLifecycleNotifier.cpp
index 7132bf6..0ecb796 100644
--- a/Source/core/frame/DOMWindowLifecycleNotifier.cpp
+++ b/Source/core/frame/DOMWindowLifecycleNotifier.cpp
@@ -29,14 +29,14 @@
 
 namespace WebCore {
 
-DOMWindowLifecycleNotifier::DOMWindowLifecycleNotifier(LifecycleContext* context)
+DOMWindowLifecycleNotifier::DOMWindowLifecycleNotifier(DOMWindow* context)
     : LifecycleNotifier(context)
 {
 }
 
-void DOMWindowLifecycleNotifier::addObserver(LifecycleObserver* observer)
+void DOMWindowLifecycleNotifier::addObserver(DOMWindowLifecycleNotifier::Observer* observer)
 {
-    if (observer->observerType() == LifecycleObserver::DOMWindowLifecycleObserverType) {
+    if (observer->observerType() == Observer::DOMWindowLifecycleObserverType) {
         RELEASE_ASSERT(m_iterating != IteratingOverDOMWindowObservers);
         m_windowObservers.add(static_cast<DOMWindowLifecycleObserver*>(observer));
     }
@@ -44,9 +44,9 @@
     LifecycleNotifier::addObserver(observer);
 }
 
-void DOMWindowLifecycleNotifier::removeObserver(LifecycleObserver* observer)
+void DOMWindowLifecycleNotifier::removeObserver(DOMWindowLifecycleNotifier::Observer* observer)
 {
-    if (observer->observerType() == LifecycleObserver::DOMWindowLifecycleObserverType) {
+    if (observer->observerType() == Observer::DOMWindowLifecycleObserverType) {
         RELEASE_ASSERT(m_iterating != IteratingOverDOMWindowObservers);
         m_windowObservers.remove(static_cast<DOMWindowLifecycleObserver*>(observer));
     }
@@ -54,7 +54,7 @@
     LifecycleNotifier::removeObserver(observer);
 }
 
-PassOwnPtr<DOMWindowLifecycleNotifier> DOMWindowLifecycleNotifier::create(LifecycleContext* context)
+PassOwnPtr<DOMWindowLifecycleNotifier> DOMWindowLifecycleNotifier::create(DOMWindow* context)
 {
     return adoptPtr(new DOMWindowLifecycleNotifier(context));
 }
diff --git a/Source/core/frame/DOMWindowLifecycleNotifier.h b/Source/core/frame/DOMWindowLifecycleNotifier.h
index f439420..7db4859 100644
--- a/Source/core/frame/DOMWindowLifecycleNotifier.h
+++ b/Source/core/frame/DOMWindowLifecycleNotifier.h
@@ -27,7 +27,7 @@
 #define DOMWindowLifecycleNotifier_h
 
 #include "core/frame/DOMWindowLifecycleObserver.h"
-#include "core/platform/LifecycleNotifier.h"
+#include "platform/LifecycleNotifier.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/TemporaryChange.h"
 #include "wtf/text/WTFString.h"
@@ -36,19 +36,19 @@
 
 class DOMWindow;
 
-class DOMWindowLifecycleNotifier : public LifecycleNotifier {
+class DOMWindowLifecycleNotifier : public LifecycleNotifier<DOMWindow> {
 public:
-    static PassOwnPtr<DOMWindowLifecycleNotifier> create(LifecycleContext*);
+    static PassOwnPtr<DOMWindowLifecycleNotifier> create(DOMWindow*);
 
     void notifyAddEventListener(DOMWindow*, const AtomicString& eventType);
     void notifyRemoveEventListener(DOMWindow*, const AtomicString& eventType);
     void notifyRemoveAllEventListeners(DOMWindow*);
 
-    virtual void addObserver(LifecycleObserver*) OVERRIDE;
-    virtual void removeObserver(LifecycleObserver*) OVERRIDE;
+    virtual void addObserver(Observer*) OVERRIDE;
+    virtual void removeObserver(Observer*) OVERRIDE;
 
 private:
-    explicit DOMWindowLifecycleNotifier(LifecycleContext*);
+    explicit DOMWindowLifecycleNotifier(DOMWindow*);
 
     typedef HashSet<DOMWindowLifecycleObserver*> DOMWindowObserverSet;
     DOMWindowObserverSet m_windowObservers;
diff --git a/Source/core/frame/DOMWindowLifecycleObserver.cpp b/Source/core/frame/DOMWindowLifecycleObserver.cpp
index cb52bb2..ad17f84 100644
--- a/Source/core/frame/DOMWindowLifecycleObserver.cpp
+++ b/Source/core/frame/DOMWindowLifecycleObserver.cpp
@@ -31,6 +31,16 @@
 
 namespace WebCore {
 
+template<> void observerContext(DOMWindow* context, LifecycleObserver<DOMWindow>* observer)
+{
+    context->wasObservedBy(observer);
+}
+
+template<> void unobserverContext(DOMWindow* context, LifecycleObserver<DOMWindow>* observer)
+{
+    context->wasUnobservedBy(observer);
+}
+
 DOMWindowLifecycleObserver::DOMWindowLifecycleObserver(DOMWindow* window)
     : LifecycleObserver(window, DOMWindowLifecycleObserverType)
 {
diff --git a/Source/core/frame/DOMWindowLifecycleObserver.h b/Source/core/frame/DOMWindowLifecycleObserver.h
index 46b17d5..de49449 100644
--- a/Source/core/frame/DOMWindowLifecycleObserver.h
+++ b/Source/core/frame/DOMWindowLifecycleObserver.h
@@ -27,14 +27,17 @@
 #ifndef DOMWindowLifecycleObserver_h
 #define DOMWindowLifecycleObserver_h
 
-#include "core/platform/LifecycleObserver.h"
+#include "platform/LifecycleObserver.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
 class DOMWindow;
 
-class DOMWindowLifecycleObserver : public LifecycleObserver {
+template<> void observerContext(DOMWindow*, LifecycleObserver<DOMWindow>*);
+template<> void unobserverContext(DOMWindow*, LifecycleObserver<DOMWindow>*);
+
+class DOMWindowLifecycleObserver : public LifecycleObserver<DOMWindow> {
 public:
     explicit DOMWindowLifecycleObserver(DOMWindow*);
     virtual ~DOMWindowLifecycleObserver();
diff --git a/Source/core/frame/Frame.cpp b/Source/core/frame/Frame.cpp
index cb64fa9..1b7f0d1 100644
--- a/Source/core/frame/Frame.cpp
+++ b/Source/core/frame/Frame.cpp
@@ -86,7 +86,7 @@
 
 static inline float parentPageZoomFactor(Frame* frame)
 {
-    Frame* parent = frame->tree()->parent();
+    Frame* parent = frame->tree().parent();
     if (!parent)
         return 1;
     return parent->pageZoomFactor();
@@ -94,7 +94,7 @@
 
 static inline float parentTextZoomFactor(Frame* frame)
 {
-    Frame* parent = frame->tree()->parent();
+    Frame* parent = frame->tree().parent();
     if (!parent)
         return 1;
     return parent->textZoomFactor();
@@ -144,7 +144,7 @@
 Frame::~Frame()
 {
     setView(0);
-    loader()->clear(ClearScriptObjects | ClearWindowObject);
+    loader().clear(ClearScriptObjects | ClearWindowObject);
 
     // FIXME: We should not be doing all this work inside the destructor
 
@@ -200,7 +200,7 @@
     if (m_view)
         m_view->unscheduleRelayout();
 
-    eventHandler()->clear();
+    eventHandler().clear();
 
     m_view = view;
 
@@ -212,8 +212,8 @@
 void Frame::sendOrientationChangeEvent(int orientation)
 {
     m_orientation = orientation;
-    if (Document* doc = document())
-        doc->dispatchWindowEvent(Event::create(EventTypeNames::orientationchange));
+    if (DOMWindow* window = domWindow())
+        window->dispatchEvent(Event::create(EventTypeNames::orientationchange));
 }
 #endif // ENABLE(ORIENTATION_EVENTS)
 
@@ -241,7 +241,7 @@
     }
 
     // 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())
+    for (RefPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling())
         child->setPrinting(printing, FloatSize(), FloatSize(), 0, shouldAdjustViewSize);
 }
 
@@ -249,7 +249,7 @@
 {
     // Only top frame being printed should be fit to page size.
     // Subframes should be constrained by parents only.
-    return document()->printing() && (!tree()->parent() || !tree()->parent()->document()->printing());
+    return document()->printing() && (!tree().parent() || !tree().parent()->document()->printing());
 }
 
 FloatSize Frame::resizePageRectsKeepingRatio(const FloatSize& originalSize, const FloatSize& expectedSize)
@@ -310,7 +310,7 @@
         document()->dispatchVisibilityStateChangeEvent();
 
     Vector<RefPtr<Frame> > childFrames;
-    for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling())
+    for (Frame* child = tree().firstChild(); child; child = child->tree().nextSibling())
         childFrames.append(child);
 
     for (size_t i = 0; i < childFrames.size(); ++i)
@@ -322,8 +322,8 @@
     // We should never be detatching the page during a Layout.
     RELEASE_ASSERT(!m_view || !m_view->isInLayout());
 
-    if (Frame* parent = tree()->parent())
-        parent->loader()->checkLoadComplete();
+    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)
@@ -337,7 +337,7 @@
     if (page() && page()->scrollingCoordinator() && m_view)
         page()->scrollingCoordinator()->willDestroyScrollableArea(m_view.get());
 
-    script()->clearScriptObjects();
+    script().clearScriptObjects();
 }
 
 void Frame::detachFromPage()
@@ -379,7 +379,7 @@
 
 VisiblePosition Frame::visiblePositionForPoint(const IntPoint& framePoint)
 {
-    HitTestResult result = eventHandler()->hitTestResultAtPoint(framePoint);
+    HitTestResult result = eventHandler().hitTestResultAtPoint(framePoint);
     Node* node = result.innerNonSharedNode();
     if (!node)
         return VisiblePosition();
@@ -401,7 +401,7 @@
     HitTestResult result = HitTestResult(pt);
 
     if (contentRenderer())
-        result = eventHandler()->hitTestResultAtPoint(pt, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+        result = eventHandler().hitTestResultAtPoint(pt, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
     return result.innerNode() ? &result.innerNode()->document() : 0;
 }
 
@@ -530,7 +530,7 @@
 
     document->recalcStyle(Force);
 
-    for (RefPtr<Frame> child = tree()->firstChild(); child; child = child->tree()->nextSibling())
+    for (RefPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling())
         child->setPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor);
 
     if (FrameView* view = this->view()) {
@@ -541,7 +541,7 @@
 
 void Frame::deviceOrPageScaleFactorChanged()
 {
-    for (RefPtr<Frame> child = tree()->firstChild(); child; child = child->tree()->nextSibling())
+    for (RefPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling())
         child->deviceOrPageScaleFactorChanged();
 }
 
@@ -551,7 +551,7 @@
     ASSERT(m_page && m_page->mainFrame() == this);
 
     unsigned count = 0;
-    for (const Frame* frame = this; frame; frame = frame->tree()->traverseNext()) {
+    for (const Frame* frame = this; frame; frame = frame->tree().traverseNext()) {
         if (frame->document())
             count += WheelController::from(frame->document())->wheelEventHandlerCount();
     }
@@ -566,7 +566,7 @@
     if (m_page->subframeCount() >= Page::maxNumberOfFrames)
         return false;
     bool foundSelfReference = false;
-    for (const Frame* frame = this; frame; frame = frame->tree()->parent()) {
+    for (const Frame* frame = this; frame; frame = frame->tree().parent()) {
         if (equalIgnoringFragmentIdentifier(frame->document()->url(), url)) {
             if (foundSelfReference)
                 return false;
diff --git a/Source/core/frame/Frame.h b/Source/core/frame/Frame.h
index 7af46d2..0937f95 100644
--- a/Source/core/frame/Frame.h
+++ b/Source/core/frame/Frame.h
@@ -96,15 +96,15 @@
         FrameView* view() const;
 
         Editor& editor() const;
-        EventHandler* eventHandler() const;
-        FrameLoader* loader() const;
-        NavigationScheduler* navigationScheduler() const;
+        EventHandler& eventHandler() const;
+        FrameLoader& loader() const;
+        NavigationScheduler& navigationScheduler() const;
         FrameSelection& selection() const;
-        FrameTree* tree() const;
+        FrameTree& tree() const;
         AnimationController& animation() const;
         InputMethodController& inputMethodController() const;
-        FetchContext& fetchContext() const { return loader()->fetchContext(); }
-        ScriptController* script();
+        FetchContext& fetchContext() const { return loader().fetchContext(); }
+        ScriptController& script();
         SpellChecker& spellChecker() const;
 
         RenderView* contentRenderer() const; // Root of the render tree for the document contained in this frame.
@@ -183,7 +183,7 @@
         const OwnPtr<Editor> m_editor;
         const OwnPtr<SpellChecker> m_spellChecker;
         const OwnPtr<FrameSelection> m_selection;
-        OwnPtr<EventHandler> m_eventHandler;
+        const OwnPtr<EventHandler> m_eventHandler;
         OwnPtr<AnimationController> m_animationController;
         OwnPtr<InputMethodController> m_inputMethodController;
 
@@ -202,14 +202,14 @@
         m_loader.init();
     }
 
-    inline FrameLoader* Frame::loader() const
+    inline FrameLoader& Frame::loader() const
     {
-        return &m_loader;
+        return m_loader;
     }
 
-    inline NavigationScheduler* Frame::navigationScheduler() const
+    inline NavigationScheduler& Frame::navigationScheduler() const
     {
-        return &m_navigationScheduler;
+        return m_navigationScheduler;
     }
 
     inline FrameView* Frame::view() const
@@ -217,9 +217,9 @@
         return m_view.get();
     }
 
-    inline ScriptController* Frame::script()
+    inline ScriptController& Frame::script()
     {
-        return m_script.get();
+        return *m_script;
     }
 
     inline DOMWindow* Frame::domWindow() const
@@ -267,9 +267,9 @@
         m_inViewSourceMode = mode;
     }
 
-    inline FrameTree* Frame::tree() const
+    inline FrameTree& Frame::tree() const
     {
-        return &m_treeNode;
+        return m_treeNode;
     }
 
     inline Page* Frame::page() const
@@ -277,9 +277,10 @@
         return m_page;
     }
 
-    inline EventHandler* Frame::eventHandler() const
+    inline EventHandler& Frame::eventHandler() const
     {
-        return m_eventHandler.get();
+        ASSERT(m_eventHandler);
+        return *m_eventHandler;
     }
 
 } // namespace WebCore
diff --git a/Source/core/frame/FrameView.cpp b/Source/core/frame/FrameView.cpp
index b89cae5..a173a89 100644
--- a/Source/core/frame/FrameView.cpp
+++ b/Source/core/frame/FrameView.cpp
@@ -40,7 +40,7 @@
 #include "core/fetch/TextResourceDecoder.h"
 #include "core/html/HTMLFrameElement.h"
 #include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLPlugInImageElement.h"
+#include "core/html/HTMLPlugInElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
@@ -429,7 +429,7 @@
     if (newRect.width() != oldRect.width()) {
         Page* page = m_frame->page();
         if (isMainFrame() && page->settings().textAutosizingEnabled()) {
-            for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
+            for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
                 m_frame->document()->textAutosizer()->recalculateMultipliers();
         }
     }
@@ -772,16 +772,6 @@
     return renderView->compositor()->layerForScrollCorner();
 }
 
-#if USE(RUBBER_BANDING)
-GraphicsLayer* FrameView::layerForOverhangAreas() const
-{
-    RenderView* renderView = this->renderView();
-    if (!renderView)
-        return 0;
-    return renderView->compositor()->layerForOverhangAreas();
-}
-#endif // USE(RUBBER_BANDING)
-
 bool FrameView::hasCompositedContent() const
 {
     if (RenderView* renderView = this->renderView())
@@ -1176,10 +1166,8 @@
 
     // Tell the DOM element that it needs a widget update.
     Node* node = object->node();
-    if (node->hasTagName(objectTag) || node->hasTagName(embedTag)) {
-        HTMLPlugInImageElement* pluginElement = toHTMLPlugInImageElement(node);
-        pluginElement->setNeedsWidgetUpdate(true);
-    }
+    if (node->hasTagName(objectTag) || node->hasTagName(embedTag))
+        toHTMLPlugInElement(node)->setNeedsWidgetUpdate(true);
 
     m_widgetUpdateSet->add(object);
 }
@@ -1250,7 +1238,7 @@
 
 void FrameView::updateCanBlitOnScrollRecursively()
 {
-    for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
+    for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
         if (FrameView* view = frame->view())
             view->setCanBlitOnScroll(!view->useSlowRepaints());
     }
@@ -1346,7 +1334,7 @@
 
 IntPoint FrameView::lastKnownMousePosition() const
 {
-    return m_frame->eventHandler()->lastKnownMousePosition();
+    return m_frame->eventHandler().lastKnownMousePosition();
 }
 
 bool FrameView::shouldSetCursor() const
@@ -1591,10 +1579,6 @@
     if (newScrollPosition == scrollPosition())
         return;
 
-    Page* page = m_frame->page();
-    if (page && RuntimeEnabledFeatures::programmaticScrollNotificationsEnabled())
-        page->chrome().client().didProgrammaticallyScroll(m_frame.get(), newScrollPosition);
-
     ScrollView::setScrollPosition(newScrollPosition);
 }
 
@@ -1635,8 +1619,8 @@
 
 void FrameView::scrollPositionChanged()
 {
-    m_frame->eventHandler()->sendScrollEvent();
-    m_frame->eventHandler()->dispatchFakeMouseMoveEventSoon();
+    m_frame->eventHandler().sendScrollEvent();
+    m_frame->eventHandler().dispatchFakeMouseMoveEventSoon();
 
     if (RenderView* renderView = this->renderView()) {
         if (renderView->usesCompositing())
@@ -1852,7 +1836,7 @@
 bool FrameView::shouldUseLoadTimeDeferredRepaintDelay() const
 {
     // Don't defer after the initial load of the page has been completed.
-    if (m_frame->tree()->top()->document()->loadEventFinished())
+    if (m_frame->tree().top()->document()->loadEventFinished())
         return false;
     Document* document = m_frame->document();
     if (!document)
@@ -2025,16 +2009,20 @@
 
 void FrameView::serviceScriptedAnimations(double monotonicAnimationStartTime)
 {
-    for (RefPtr<Frame> frame = m_frame; frame; frame = frame->tree()->traverseNext()) {
+    for (RefPtr<Frame> frame = m_frame; frame; frame = frame->tree().traverseNext()) {
         frame->view()->serviceScrollAnimations();
         if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
             frame->animation().serviceAnimations();
-        if (RuntimeEnabledFeatures::webAnimationsEnabled())
+        if (RuntimeEnabledFeatures::webAnimationsEnabled()) {
             frame->document()->timeline()->serviceAnimations(monotonicAnimationStartTime);
+            frame->document()->transitionTimeline()->serviceAnimations(monotonicAnimationStartTime);
+            frame->document()->timeline()->dispatchEvents();
+            frame->document()->transitionTimeline()->dispatchEvents();
+        }
     }
 
     Vector<RefPtr<Document> > documents;
-    for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext())
+    for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext())
         documents.append(frame->document());
 
     for (size_t i = 0; i < documents.size(); ++i)
@@ -2080,7 +2068,7 @@
 
 void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
 {
-    for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
+    for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
         if (FrameView* view = frame->view()) {
             view->setTransparent(transparent);
             view->setBaseBackgroundColor(backgroundColor);
@@ -2175,12 +2163,13 @@
 
         // FIXME: This could turn into a real virtual dispatch if we defined
         // updateWidget(PluginCreationOption) on HTMLElement.
-        if (ownerElement->hasTagName(objectTag) || ownerElement->hasTagName(embedTag) || ownerElement->hasTagName(appletTag)) {
-            HTMLPlugInImageElement* pluginElement = toHTMLPlugInImageElement(ownerElement);
+        if (ownerElement->isPluginElement()) {
+            HTMLPlugInElement* pluginElement = toHTMLPlugInElement(ownerElement);
             if (pluginElement->needsWidgetUpdate())
                 pluginElement->updateWidget(CreateAnyWidgetType);
-        } else
+        } else {
             ASSERT_NOT_REACHED();
+        }
 
         // Caution: it's possible the object was destroyed again, since loading a
         // plugin may run any arbitrary JavaScript.
@@ -2247,11 +2236,11 @@
     if (m_nestedLayoutCount <= 1) {
         if (m_firstLayoutCallbackPending) {
             m_firstLayoutCallbackPending = false;
-            m_frame->loader()->didFirstLayout();
+            m_frame->loader().didFirstLayout();
         }
 
         // Ensure that we always send this eventually.
-        if (!m_frame->document()->parsing() && m_frame->loader()->stateMachine()->committedFirstRealDocumentLoad())
+        if (!m_frame->document()->parsing() && m_frame->loader().stateMachine()->committedFirstRealDocumentLoad())
             m_isVisuallyNonEmpty = true;
 
         // If the layout was done with pending sheets, we are not in fact visually non-empty yet.
@@ -2259,11 +2248,11 @@
             m_firstVisuallyNonEmptyLayoutCallbackPending = false;
             // FIXME: This callback is probably not needed, but is currently used
             // by android for setting the background color.
-            m_frame->loader()->client()->dispatchDidFirstVisuallyNonEmptyLayout();
+            m_frame->loader().client()->dispatchDidFirstVisuallyNonEmptyLayout();
         }
     }
 
-    m_frame->document()->fonts()->didLayout();
+    FontFaceSet::didLayout(m_frame->document());
 
     RenderView* renderView = this->renderView();
     if (renderView)
@@ -2305,7 +2294,7 @@
     if (!shouldSendResizeEvent)
         return;
 
-    m_frame->eventHandler()->sendResizeEvent();
+    m_frame->eventHandler().sendResizeEvent();
 
     if (isMainFrame())
         InspectorInstrumentation::didResizeMainFrame(m_frame->page());
@@ -2528,7 +2517,7 @@
     ScrollView::scrollTo(newOffset);
     if (offset != scrollOffset())
         scrollPositionChanged();
-    frame().loader()->client()->didChangeScrollOffset();
+    frame().loader().client()->didChangeScrollOffset();
 }
 
 void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
@@ -2643,7 +2632,7 @@
 
 bool FrameView::shouldSuspendScrollAnimations() const
 {
-    return m_frame->loader()->state() != FrameStateComplete;
+    return m_frame->loader().state() != FrameStateComplete;
 }
 
 void FrameView::scrollbarStyleChanged(int newStyle, bool forceUpdate)
@@ -2852,7 +2841,7 @@
     if (!parent())
         return 0;
 
-    if (Frame* parentFrame = m_frame->tree()->parent())
+    if (Frame* parentFrame = m_frame->tree().parent())
         return parentFrame->view();
 
     return 0;
@@ -3313,7 +3302,7 @@
     if (trackRepaints == m_isTrackingRepaints)
         return;
 
-    for (Frame* frame = m_frame->tree()->top(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = m_frame->tree().top(); frame; frame = frame->tree().traverseNext()) {
         if (RenderView* renderView = frame->contentRenderer())
             renderView->compositor()->setTracksRepaints(trackRepaints);
     }
@@ -3436,6 +3425,14 @@
     return 0;
 }
 
+void FrameView::setCursor(const Cursor& cursor)
+{
+    Page* page = frame().page();
+    if (!page)
+        return;
+    page->chrome().setCursor(cursor);
+}
+
 bool FrameView::isMainFrame() const
 {
     return m_frame->page() && m_frame->page()->mainFrame() == m_frame;
diff --git a/Source/core/frame/FrameView.h b/Source/core/frame/FrameView.h
index 841b71c..389d999 100644
--- a/Source/core/frame/FrameView.h
+++ b/Source/core/frame/FrameView.h
@@ -27,11 +27,11 @@
 
 #include "core/frame/AdjustViewSizeOrNot.h"
 #include "core/platform/ScrollView.h"
-#include "core/platform/graphics/Color.h"
 #include "core/rendering/Pagination.h"
 #include "core/rendering/PaintPhase.h"
 #include "core/rendering/PartialLayoutState.h"
 #include "platform/geometry/LayoutRect.h"
+#include "platform/graphics/Color.h"
 #include "wtf/Forward.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/text/WTFString.h"
@@ -277,6 +277,8 @@
     virtual IntPoint lastKnownMousePosition() const;
     bool shouldSetCursor() const;
 
+    void setCursor(const Cursor&);
+
     virtual bool scrollbarsCanBeActive() const OVERRIDE;
 
     // FIXME: Remove this method once plugin loading is decoupled from layout.
@@ -413,9 +415,6 @@
     virtual GraphicsLayer* layerForHorizontalScrollbar() const OVERRIDE;
     virtual GraphicsLayer* layerForVerticalScrollbar() const OVERRIDE;
     virtual GraphicsLayer* layerForScrollCorner() const OVERRIDE;
-#if USE(RUBBER_BANDING)
-    virtual GraphicsLayer* layerForOverhangAreas() const OVERRIDE;
-#endif
 
     void sendResizeEventIfNeeded();
 
diff --git a/Source/core/frame/History.cpp b/Source/core/frame/History.cpp
index 5edbb8d..2529ced 100644
--- a/Source/core/frame/History.cpp
+++ b/Source/core/frame/History.cpp
@@ -70,7 +70,7 @@
     if (!m_frame)
         return 0;
 
-    if (HistoryItem* historyItem = m_frame->loader()->history()->currentItem())
+    if (HistoryItem* historyItem = m_frame->loader().history()->currentItem())
         return historyItem->stateObject();
 
     return 0;
@@ -111,7 +111,7 @@
     if (!m_frame)
         return;
 
-    m_frame->navigationScheduler()->scheduleHistoryNavigation(distance);
+    m_frame->navigationScheduler().scheduleHistoryNavigation(distance);
 }
 
 void History::go(ExecutionContext* context, int distance)
@@ -127,7 +127,7 @@
     if (!activeDocument->canNavigate(m_frame))
         return;
 
-    m_frame->navigationScheduler()->scheduleHistoryNavigation(distance);
+    m_frame->navigationScheduler().scheduleHistoryNavigation(distance);
 }
 
 KURL History::urlForState(const String& urlString)
@@ -153,7 +153,7 @@
         es.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, sameDocumentNavigationSource, data, FrameLoader::DoNotUpdateBackForwardList);
 }
 
 } // namespace WebCore
diff --git a/Source/core/frame/ImageBitmap.cpp b/Source/core/frame/ImageBitmap.cpp
index ba0e18f..1d21602 100644
--- a/Source/core/frame/ImageBitmap.cpp
+++ b/Source/core/frame/ImageBitmap.cpp
@@ -39,9 +39,9 @@
 }
 
 ImageBitmap::ImageBitmap(HTMLImageElement* image, const IntRect& cropRect)
-    : m_cropRect(cropRect)
+    : m_imageElement(image)
     , m_bitmap(0)
-    , m_imageElement(image)
+    , m_cropRect(cropRect)
 {
     IntRect srcRect = intersection(cropRect, IntRect(0, 0, image->width(), image->height()));
     m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
@@ -56,8 +56,8 @@
 }
 
 ImageBitmap::ImageBitmap(HTMLVideoElement* video, const IntRect& cropRect)
-    : m_cropRect(cropRect)
-    , m_imageElement(0)
+    : m_imageElement(0)
+    , m_cropRect(cropRect)
     , m_bitmapOffset(IntPoint())
 {
     IntRect videoRect = IntRect(IntPoint(), video->player()->naturalSize());
@@ -76,8 +76,8 @@
 }
 
 ImageBitmap::ImageBitmap(HTMLCanvasElement* canvas, const IntRect& cropRect)
-    : m_cropRect(cropRect)
-    , m_imageElement(0)
+    : m_imageElement(0)
+    , m_cropRect(cropRect)
     , m_bitmapOffset(IntPoint())
 {
     CanvasRenderingContext* sourceContext = canvas->renderingContext();
@@ -92,8 +92,8 @@
 }
 
 ImageBitmap::ImageBitmap(ImageData* data, const IntRect& cropRect)
-    : m_cropRect(cropRect)
-    , m_imageElement(0)
+    : m_imageElement(0)
+    , m_cropRect(cropRect)
     , m_bitmapOffset(IntPoint())
 {
     IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), data->size()));
@@ -109,9 +109,9 @@
 }
 
 ImageBitmap::ImageBitmap(ImageBitmap* bitmap, const IntRect& cropRect)
-    : m_cropRect(cropRect)
+    : m_imageElement(bitmap->imageElement())
     , m_bitmap(0)
-    , m_imageElement(bitmap->imageElement())
+    , m_cropRect(cropRect)
     , m_bitmapOffset(IntPoint())
 {
     IntRect oldBitmapRect = bitmap->bitmapRect();
@@ -130,8 +130,8 @@
 }
 
 ImageBitmap::ImageBitmap(Image* image, const IntRect& cropRect)
-    : m_cropRect(cropRect)
-    , m_imageElement(0)
+    : m_imageElement(0)
+    , m_cropRect(cropRect)
 {
     IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), image->size()));
     m_bitmap = cropImage(image, cropRect);
diff --git a/Source/core/frame/Location.cpp b/Source/core/frame/Location.cpp
index 521b912..bb7e5e7 100644
--- a/Source/core/frame/Location.cpp
+++ b/Source/core/frame/Location.cpp
@@ -121,7 +121,7 @@
     RefPtr<DOMStringList> origins = DOMStringList::create();
     if (!m_frame)
         return origins.release();
-    for (Frame* frame = m_frame->tree()->parent(); frame; frame = frame->tree()->parent())
+    for (Frame* frame = m_frame->tree().parent(); frame; frame = frame->tree().parent())
         origins->append(frame->document()->securityOrigin()->toString());
     return origins.release();
 }
@@ -237,14 +237,14 @@
         return;
     if (protocolIsJavaScript(m_frame->document()->url()))
         return;
-    m_frame->navigationScheduler()->scheduleRefresh();
+    m_frame->navigationScheduler().scheduleRefresh();
 }
 
 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(String(), activeWindow->document());
     if (!frame)
         return;
     frame->domWindow()->setLocation(url, activeWindow, firstWindow);
diff --git a/Source/core/frame/Navigator.cpp b/Source/core/frame/Navigator.cpp
index 7d93cde..0d5d778 100644
--- a/Source/core/frame/Navigator.cpp
+++ b/Source/core/frame/Navigator.cpp
@@ -65,7 +65,7 @@
 // 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();
+    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")))
@@ -116,7 +116,7 @@
     if (!m_frame->page())
         return String();
 
-    return m_frame->loader()->userAgent(m_frame->document()->url());
+    return m_frame->loader().userAgent(m_frame->document()->url());
 }
 
 DOMPluginArray* Navigator::plugins() const
diff --git a/Source/core/frame/Window.idl b/Source/core/frame/Window.idl
index 980f71f..86dd8e0 100644
--- a/Source/core/frame/Window.idl
+++ b/Source/core/frame/Window.idl
@@ -24,6 +24,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+// HTML 5 draft spec:
+// http://www.w3.org/html/wg/drafts/html/master/browsers.html#window
 [
     CheckSecurity,
     CustomToV8,
@@ -42,7 +44,7 @@
     [Replaceable, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds] readonly attribute Navigator navigator;
     [Replaceable] readonly attribute Navigator clientInformation;
     [DoNotCheckSecurity, Unforgeable, Replaceable, PerWorldBindings, ActivityLogging=AccessForIsolatedWorlds, PutForwards=href] readonly attribute Location location;
-    [Custom, MeasureAs=WindowEvent, NotEnumerable, Replaceable] readonly attribute Event event;
+    [Custom, MeasureAs=WindowEvent, NotEnumerable] attribute Event event;
 
     Selection getSelection();
 
@@ -115,7 +117,7 @@
     [DoNotCheckSecurity, Unforgeable] readonly attribute Window window;
     [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute  Window frames;
 
-    [Replaceable, DoNotCheckSecurityOnGetter, CustomSetter] readonly attribute Window opener;
+    [DoNotCheckSecurityOnGetter, CustomSetter] attribute Window opener;
     [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute Window parent;
     [DoNotCheckSecurityOnGetter, Unforgeable] readonly attribute Window top;
 
@@ -172,26 +174,15 @@
     [RuntimeEnabled=CSSAnimationUnprefixed] attribute EventHandler onanimationend;
     [RuntimeEnabled=CSSAnimationUnprefixed] attribute EventHandler onanimationiteration;
     [RuntimeEnabled=CSSAnimationUnprefixed] attribute EventHandler onanimationstart;
-    attribute EventHandler onbeforeunload;
     [RuntimeEnabled=DeviceMotion] attribute EventHandler ondevicemotion;
     [RuntimeEnabled=DeviceOrientation] attribute EventHandler ondeviceorientation;
-    attribute EventHandler onhashchange;
-    attribute EventHandler onmessage;
-    attribute EventHandler onoffline;
-    attribute EventHandler ononline;
     [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
-    attribute EventHandler onpagehide;
-    attribute EventHandler onpageshow;
-    attribute EventHandler onpopstate;
-    attribute EventHandler onresize;
     attribute EventHandler onsearch;
-    attribute EventHandler onstorage;
     [RuntimeEnabled=Touch] attribute EventHandler ontouchcancel;
     [RuntimeEnabled=Touch] attribute EventHandler ontouchend;
     [RuntimeEnabled=Touch] attribute EventHandler ontouchmove;
     [RuntimeEnabled=Touch] attribute EventHandler ontouchstart;
     attribute EventHandler ontransitionend;
-    attribute EventHandler onunload;
     attribute EventHandler onwebkitanimationend;
     attribute EventHandler onwebkitanimationiteration;
     attribute EventHandler onwebkitanimationstart;
@@ -204,7 +195,6 @@
     // Additional constructors.
     attribute TransitionEventConstructor WebKitTransitionEvent;
     [RuntimeEnabled=CSSAnimationUnprefixed] attribute WebKitAnimationEventConstructor AnimationEvent;
-    [CustomConstructor] attribute HTMLImageElementConstructorConstructor Image; // Usable with new operator
     // Mozilla has a separate XMLDocument object for XML documents.
     // We just use Document for this.
     attribute DocumentConstructor XMLDocument;
@@ -249,4 +239,5 @@
 Window implements GlobalEventHandlers;
 Window implements ImageBitmapFactories;
 Window implements WindowBase64;
+Window implements WindowEventHandlers;
 Window implements WindowTimers;
diff --git a/Source/core/frame/WindowEventHandlers.idl b/Source/core/frame/WindowEventHandlers.idl
new file mode 100644
index 0000000..b7634ae
--- /dev/null
+++ b/Source/core/frame/WindowEventHandlers.idl
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+[
+    NoInterfaceObject,
+    ImplementedAs=DOMWindowEventHandlers
+] interface WindowEventHandlers {
+    //attribute EventHandler onafterprint;
+    //attribute EventHandler onbeforeprint;
+    attribute EventHandler onbeforeunload;
+    attribute EventHandler onhashchange;
+    attribute EventHandler onmessage;
+    attribute EventHandler onoffline;
+    attribute EventHandler ononline;
+    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
index 8b389a5..20af331 100644
--- a/Source/core/frame/animation/AnimationBase.cpp
+++ b/Source/core/frame/animation/AnimationBase.cpp
@@ -556,7 +556,7 @@
     // 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())
-        toRenderBoxModelObject(m_object)->suspendAnimations(m_pauseTime);
+        pauseAnimation(t);
 }
 
 double AnimationBase::beginAnimationUpdateTime() const
diff --git a/Source/core/frame/animation/AnimationController.cpp b/Source/core/frame/animation/AnimationController.cpp
index 604b5fc..152fa96 100644
--- a/Source/core/frame/animation/AnimationController.cpp
+++ b/Source/core/frame/animation/AnimationController.cpp
@@ -54,7 +54,7 @@
     , m_beginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet)
     , m_animationsWaitingForStyle()
     , m_animationsWaitingForStartTimeResponse()
-    , m_waitingForAsyncStartNotification(false)
+    , m_animationsWaitingForAsyncStartNotification()
 {
 }
 
@@ -306,13 +306,12 @@
 void AnimationControllerPrivate::endAnimationUpdate()
 {
     styleAvailable();
-    if (!m_waitingForAsyncStartNotification)
+    if (m_animationsWaitingForAsyncStartNotification.isEmpty())
         startTimeResponse(beginAnimationUpdateTime());
 }
 
 void AnimationControllerPrivate::receivedStartTimeResponse(double time)
 {
-    m_waitingForAsyncStartNotification = false;
     startTimeResponse(time);
 }
 
@@ -351,6 +350,7 @@
 {
     // Make sure this animation is not in the start time waiters
     m_animationsWaitingForStartTimeResponse.remove(animation);
+    m_animationsWaitingForAsyncStartNotification.remove(animation);
 
     m_animationsWaitingForStyle.add(animation);
 }
@@ -392,7 +392,7 @@
     //
 
     if (willGetResponse)
-        m_waitingForAsyncStartNotification = true;
+        m_animationsWaitingForAsyncStartNotification.add(animation);
 
     m_animationsWaitingForStartTimeResponse.add(animation);
 }
@@ -400,9 +400,7 @@
 void AnimationControllerPrivate::removeFromAnimationsWaitingForStartTimeResponse(AnimationBase* animationToRemove)
 {
     m_animationsWaitingForStartTimeResponse.remove(animationToRemove);
-
-    if (m_animationsWaitingForStartTimeResponse.isEmpty())
-        m_waitingForAsyncStartNotification = false;
+    m_animationsWaitingForAsyncStartNotification.remove(animationToRemove);
 }
 
 void AnimationControllerPrivate::startTimeResponse(double time)
@@ -415,7 +413,7 @@
         (*it)->onAnimationStartResponse(time);
 
     m_animationsWaitingForStartTimeResponse.clear();
-    m_waitingForAsyncStartNotification = false;
+    m_animationsWaitingForAsyncStartNotification.clear();
 }
 
 void AnimationControllerPrivate::animationWillBeRemoved(AnimationBase* animation)
diff --git a/Source/core/frame/animation/AnimationControllerPrivate.h b/Source/core/frame/animation/AnimationControllerPrivate.h
index b38c936..94a0ec3 100644
--- a/Source/core/frame/animation/AnimationControllerPrivate.h
+++ b/Source/core/frame/animation/AnimationControllerPrivate.h
@@ -132,7 +132,7 @@
     typedef HashSet<RefPtr<AnimationBase> > WaitingAnimationsSet;
     WaitingAnimationsSet m_animationsWaitingForStyle;
     WaitingAnimationsSet m_animationsWaitingForStartTimeResponse;
-    bool m_waitingForAsyncStartNotification;
+    WaitingAnimationsSet m_animationsWaitingForAsyncStartNotification;
 };
 
 } // namespace WebCore
diff --git a/Source/core/frame/animation/CSSPropertyAnimation.cpp b/Source/core/frame/animation/CSSPropertyAnimation.cpp
index 527ebe0..4479e65 100644
--- a/Source/core/frame/animation/CSSPropertyAnimation.cpp
+++ b/Source/core/frame/animation/CSSPropertyAnimation.cpp
@@ -42,6 +42,7 @@
 #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"
@@ -87,30 +88,6 @@
                    blendFunc(anim, from.height(), to.height(), progress));
 }
 
-static inline ShadowStyle blendFunc(const AnimationBase* anim, ShadowStyle from, ShadowStyle to, double progress)
-{
-    if (from == to)
-        return to;
-
-    double fromVal = from == Normal ? 1 : 0;
-    double toVal = to == Normal ? 1 : 0;
-    double result = blendFunc(anim, fromVal, toVal, progress);
-    return result > 0 ? Normal : Inset;
-}
-
-static inline PassOwnPtr<ShadowData> blendFunc(const AnimationBase* anim, const ShadowData* from, const ShadowData* to, double progress)
-{
-    ASSERT(from && to);
-    if (from->style() != to->style())
-        return to->clone();
-
-    return ShadowData::create(blend(from->location(), to->location(), progress),
-        blend(from->blur(), to->blur(), progress),
-        blend(from->spread(), to->spread(), progress),
-        blendFunc(anim, from->style(), to->style(), progress),
-        blend(from->color(), to->color(), progress));
-}
-
 static inline TransformOperations blendFunc(const AnimationBase* anim, const TransformOperations& from, const TransformOperations& to, double progress)
 {
     if (anim->isTransformFunctionListValid())
@@ -148,12 +125,6 @@
     return ShapeValue::createShapeValue(toShape->blend(fromShape, progress));
 }
 
-static inline PassRefPtr<FilterOperation> blendFunc(const AnimationBase* anim, FilterOperation* fromOp, FilterOperation* toOp, double progress, bool blendToPassthrough = false)
-{
-    ASSERT(toOp);
-    return toOp->blend(fromOp, progress, blendToPassthrough);
-}
-
 static inline FilterOperations blendFunc(const AnimationBase* anim, const FilterOperations& from, const FilterOperations& to, double progress)
 {
     FilterOperations result;
@@ -164,18 +135,13 @@
         size_t toSize = to.operations().size();
         size_t size = max(fromSize, toSize);
         for (size_t i = 0; i < size; i++) {
-            RefPtr<FilterOperation> fromOp = (i < fromSize) ? from.operations()[i].get() : 0;
-            RefPtr<FilterOperation> toOp = (i < toSize) ? to.operations()[i].get() : 0;
-            RefPtr<FilterOperation> blendedOp = toOp ? blendFunc(anim, fromOp.get(), toOp.get(), progress) : (fromOp ? blendFunc(anim, 0, fromOp.get(), progress, true) : 0);
+            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 {
-                RefPtr<FilterOperation> identityOp = PassthroughFilterOperation::create();
-                if (progress > 0.5)
-                    result.operations().append(toOp ? toOp : identityOp);
-                else
-                    result.operations().append(fromOp ? fromOp : identityOp);
-            }
+            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.
@@ -523,31 +489,9 @@
     }
 };
 
-static inline size_t shadowListLength(const ShadowData* shadow)
-{
-    size_t count;
-    for (count = 0; shadow; shadow = shadow->next())
-        ++count;
-    return count;
-}
-
-static inline const ShadowData* shadowForBlending(const ShadowData* srcShadow, const ShadowData* otherShadow)
-{
-    DEFINE_STATIC_LOCAL(OwnPtr<ShadowData>, defaultShadowData, (ShadowData::create(IntPoint(), 0, 0, Normal, Color::transparent)));
-    DEFINE_STATIC_LOCAL(OwnPtr<ShadowData>, defaultInsetShadowData, (ShadowData::create(IntPoint(), 0, 0, Inset, Color::transparent)));
-
-    if (srcShadow)
-        return srcShadow;
-
-    if (otherShadow->style() == Inset)
-        return defaultInsetShadowData.get();
-
-    return defaultShadowData.get();
-}
-
 class PropertyWrapperShadow : public AnimationPropertyWrapperBase {
 public:
-    PropertyWrapperShadow(CSSPropertyID prop, const ShadowData* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassOwnPtr<ShadowData>, bool))
+    PropertyWrapperShadow(CSSPropertyID prop, ShadowList* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ShadowList>))
         : AnimationPropertyWrapperBase(prop)
         , m_getter(getter)
         , m_setter(setter)
@@ -556,108 +500,22 @@
 
     virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
     {
-        const ShadowData* shadowA = (a->*m_getter)();
-        const ShadowData* shadowB = (b->*m_getter)();
-
-        while (true) {
-            // end of both lists
-            if (!shadowA && !shadowB)
-                return true;
-
-            // end of just one of the lists
-            if (!shadowA || !shadowB)
-                return false;
-
-            if (*shadowA != *shadowB)
-                return false;
-
-            shadowA = shadowA->next();
-            shadowB = shadowB->next();
-        }
-
-        return true;
+        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
     {
-        const ShadowData* shadowA = (a->*m_getter)();
-        const ShadowData* shadowB = (b->*m_getter)();
-
-        int fromLength = shadowListLength(shadowA);
-        int toLength = shadowListLength(shadowB);
-
-        if (fromLength == toLength || (fromLength <= 1 && toLength <= 1)) {
-            (dst->*m_setter)(blendSimpleOrMatchedShadowLists(anim, progress, shadowA, shadowB), false);
-            return;
-        }
-
-        (dst->*m_setter)(blendMismatchedShadowLists(anim, progress, shadowA, shadowB, fromLength, toLength), false);
+        (dst->*m_setter)(ShadowList::blend((a->*m_getter)(), (b->*m_getter)(), progress));
     }
 
-private:
-    PassOwnPtr<ShadowData> blendSimpleOrMatchedShadowLists(const AnimationBase* anim, double progress, const ShadowData* shadowA, const ShadowData* shadowB) const
-    {
-        OwnPtr<ShadowData> newShadowData;
-        ShadowData* lastShadow = 0;
-
-        while (shadowA || shadowB) {
-            const ShadowData* srcShadow = shadowForBlending(shadowA, shadowB);
-            const ShadowData* dstShadow = shadowForBlending(shadowB, shadowA);
-
-            OwnPtr<ShadowData> blendedShadow = blendFunc(anim, srcShadow, dstShadow, progress);
-            ShadowData* blendedShadowPtr = blendedShadow.get();
-
-            if (!lastShadow)
-                newShadowData = blendedShadow.release();
-            else
-                lastShadow->setNext(blendedShadow.release());
-
-            lastShadow = blendedShadowPtr;
-
-            shadowA = shadowA ? shadowA->next() : 0;
-            shadowB = shadowB ? shadowB->next() : 0;
-        }
-
-        return newShadowData.release();
-    }
-
-    PassOwnPtr<ShadowData> blendMismatchedShadowLists(const AnimationBase* anim, double progress, const ShadowData* shadowA, const ShadowData* shadowB, int fromLength, int toLength) const
-    {
-        // The shadows in ShadowData are stored in reverse order, so when animating mismatched lists,
-        // reverse them and match from the end.
-        Vector<const ShadowData*, 4> fromShadows(fromLength);
-        for (int i = fromLength - 1; i >= 0; --i) {
-            fromShadows[i] = shadowA;
-            shadowA = shadowA->next();
-        }
-
-        Vector<const ShadowData*, 4> toShadows(toLength);
-        for (int i = toLength - 1; i >= 0; --i) {
-            toShadows[i] = shadowB;
-            shadowB = shadowB->next();
-        }
-
-        OwnPtr<ShadowData> newShadowData;
-
-        int maxLength = max(fromLength, toLength);
-        for (int i = 0; i < maxLength; ++i) {
-            const ShadowData* fromShadow = i < fromLength ? fromShadows[i] : 0;
-            const ShadowData* toShadow = i < toLength ? toShadows[i] : 0;
-
-            const ShadowData* srcShadow = shadowForBlending(fromShadow, toShadow);
-            const ShadowData* dstShadow = shadowForBlending(toShadow, fromShadow);
-
-            OwnPtr<ShadowData> blendedShadow = blendFunc(anim, srcShadow, dstShadow, progress);
-            // Insert at the start of the list to preserve the order.
-            blendedShadow->setNext(newShadowData.release());
-            newShadowData = blendedShadow.release();
-        }
-
-        return newShadowData.release();
-    }
-
-    const ShadowData* (RenderStyle::*m_getter)() const;
-    void (RenderStyle::*m_setter)(PassOwnPtr<ShadowData>, bool);
+    ShadowList* (RenderStyle::*m_getter)() const;
+    void (RenderStyle::*m_setter)(PassRefPtr<ShadowList>);
 };
 
 class PropertyWrapperMaybeInvalidColor : public AnimationPropertyWrapperBase {
diff --git a/Source/core/frame/animation/ImplicitAnimation.cpp b/Source/core/frame/animation/ImplicitAnimation.cpp
index 87f29e0..bd9eb6b 100644
--- a/Source/core/frame/animation/ImplicitAnimation.cpp
+++ b/Source/core/frame/animation/ImplicitAnimation.cpp
@@ -257,14 +257,7 @@
     const FilterOperations* val = &m_fromStyle->filter();
     const FilterOperations* toVal = &m_toStyle->filter();
 
-    if (val->operations().isEmpty())
-        val = toVal;
-
-    if (val->operations().isEmpty())
-        return;
-
-    // An emtpy filter list matches anything.
-    if (val != toVal && !toVal->operations().isEmpty() && !val->operationsMatch(*toVal))
+    if (!val->canInterpolateWith(*toVal))
         return;
 
     // Filter lists match.
diff --git a/Source/core/frame/animation/KeyframeAnimation.cpp b/Source/core/frame/animation/KeyframeAnimation.cpp
index da94a58..8ef47df 100644
--- a/Source/core/frame/animation/KeyframeAnimation.cpp
+++ b/Source/core/frame/animation/KeyframeAnimation.cpp
@@ -421,11 +421,7 @@
         const KeyframeValue& currentKeyframe = m_keyframes[i];
         const FilterOperations* val = &currentKeyframe.style()->filter();
 
-        // An emtpy filter list matches anything.
-        if (val->operations().isEmpty())
-            continue;
-
-        if (!firstVal->operationsMatch(*val))
+        if (!firstVal->canInterpolateWith(*val))
             return;
     }
 
diff --git a/Source/core/generate_test_support_idls.target.darwin-arm.mk b/Source/core/generate_test_support_idls.target.darwin-arm.mk
index 3accd09..390a91c 100644
--- a/Source/core/generate_test_support_idls.target.darwin-arm.mk
+++ b/Source/core/generate_test_support_idls.target.darwin-arm.mk
@@ -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/WebKit/Source/core/page/make_settings.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(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" -- page/make_settings.pl page/Settings.in
+	$(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 ;
@@ -31,9 +31,9 @@
 $(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/core/page/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)
+$(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 page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+	$(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 ;
 
diff --git a/Source/core/generate_test_support_idls.target.darwin-mips.mk b/Source/core/generate_test_support_idls.target.darwin-mips.mk
index 3accd09..390a91c 100644
--- a/Source/core/generate_test_support_idls.target.darwin-mips.mk
+++ b/Source/core/generate_test_support_idls.target.darwin-mips.mk
@@ -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/WebKit/Source/core/page/make_settings.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(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" -- page/make_settings.pl page/Settings.in
+	$(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 ;
@@ -31,9 +31,9 @@
 $(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/core/page/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)
+$(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 page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+	$(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 ;
 
diff --git a/Source/core/generate_test_support_idls.target.darwin-x86.mk b/Source/core/generate_test_support_idls.target.darwin-x86.mk
index 3accd09..390a91c 100644
--- a/Source/core/generate_test_support_idls.target.darwin-x86.mk
+++ b/Source/core/generate_test_support_idls.target.darwin-x86.mk
@@ -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/WebKit/Source/core/page/make_settings.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(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" -- page/make_settings.pl page/Settings.in
+	$(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 ;
@@ -31,9 +31,9 @@
 $(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/core/page/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)
+$(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 page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+	$(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 ;
 
diff --git a/Source/core/generate_test_support_idls.target.linux-arm.mk b/Source/core/generate_test_support_idls.target.linux-arm.mk
index 3accd09..390a91c 100644
--- a/Source/core/generate_test_support_idls.target.linux-arm.mk
+++ b/Source/core/generate_test_support_idls.target.linux-arm.mk
@@ -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/WebKit/Source/core/page/make_settings.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(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" -- page/make_settings.pl page/Settings.in
+	$(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 ;
@@ -31,9 +31,9 @@
 $(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/core/page/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)
+$(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 page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+	$(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 ;
 
diff --git a/Source/core/generate_test_support_idls.target.linux-mips.mk b/Source/core/generate_test_support_idls.target.linux-mips.mk
index 3accd09..390a91c 100644
--- a/Source/core/generate_test_support_idls.target.linux-mips.mk
+++ b/Source/core/generate_test_support_idls.target.linux-mips.mk
@@ -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/WebKit/Source/core/page/make_settings.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(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" -- page/make_settings.pl page/Settings.in
+	$(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 ;
@@ -31,9 +31,9 @@
 $(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/core/page/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)
+$(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 page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+	$(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 ;
 
diff --git a/Source/core/generate_test_support_idls.target.linux-x86.mk b/Source/core/generate_test_support_idls.target.linux-x86.mk
index 3accd09..390a91c 100644
--- a/Source/core/generate_test_support_idls.target.linux-x86.mk
+++ b/Source/core/generate_test_support_idls.target.linux-x86.mk
@@ -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/WebKit/Source/core/page/make_settings.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(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" -- page/make_settings.pl page/Settings.in
+	$(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 ;
@@ -31,9 +31,9 @@
 $(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/core/page/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)
+$(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 page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+	$(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 ;
 
diff --git a/Source/core/html/HTMLAnchorElement.cpp b/Source/core/html/HTMLAnchorElement.cpp
index 7dcbbdc..7346398 100644
--- a/Source/core/html/HTMLAnchorElement.cpp
+++ b/Source/core/html/HTMLAnchorElement.cpp
@@ -43,7 +43,6 @@
 #include "core/page/ChromeClient.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/HistogramSupport.h"
 #include "core/rendering/RenderImage.h"
 #include "core/svg/graphics/SVGImage.h"
 #include "platform/PlatformMouseEvent.h"
@@ -433,21 +432,21 @@
 
     ResourceRequest request(completedURL);
     if (prefetchEventHandler()->hasIssuedPreconnect())
-        frame->loader()->client()->dispatchWillRequestAfterPreconnect(request);
+        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, frame->loader().outgoingReferrer());
             if (!referrer.isEmpty())
                 request.setHTTPReferrer(referrer);
         }
 
-        frame->loader()->client()->loadURLExternally(request, NavigationPolicyDownload, fastGetAttribute(downloadAttr));
+        frame->loader().client()->loadURLExternally(request, NavigationPolicyDownload, fastGetAttribute(downloadAttr));
     } else {
         FrameLoadRequest frameRequest(document().securityOrigin(), request, target());
         frameRequest.setTriggeringEvent(event);
         if (hasRel(RelationNoReferrer))
             frameRequest.setShouldSendReferrer(NeverSendReferrer);
-        frame->loader()->load(frameRequest);
+        frame->loader().load(frameRequest);
     }
 }
 
@@ -587,7 +586,7 @@
     if (m_mouseOverTimestamp == 0.0) {
         m_mouseOverTimestamp = event->timeStamp();
 
-        HistogramSupport::histogramEnumeration("MouseEventPrefetch.MouseOvers", 0, 2);
+        WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseOvers", 0, 2);
 
         prefetch(WebKit::WebPreconnectMotivationLinkMouseOver);
     }
@@ -597,7 +596,7 @@
 {
     if (m_mouseOverTimestamp > 0.0) {
         double mouseOverDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_mouseOverTimestamp);
-        HistogramSupport::histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_NoClick", mouseOverDuration * 1000, 0, 10000, 100);
+        WebKit::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_NoClick", mouseOverDuration * 1000, 0, 10000, 100);
 
         m_mouseOverTimestamp = 0.0;
     }
@@ -607,7 +606,7 @@
 {
     m_mouseDownTimestamp = event->timeStamp();
 
-    HistogramSupport::histogramEnumeration("MouseEventPrefetch.MouseDowns", 0, 2);
+    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseDowns", 0, 2);
 
     prefetch(WebKit::WebPreconnectMotivationLinkMouseDown);
 }
@@ -616,7 +615,7 @@
 {
     m_hadTapUnconfirmed = true;
 
-    HistogramSupport::histogramEnumeration("MouseEventPrefetch.TapUnconfirmeds", 0, 2);
+    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.TapUnconfirmeds", 0, 2);
 
     prefetch(WebKit::WebPreconnectMotivationLinkTapUnconfirmed);
 }
@@ -625,7 +624,7 @@
 {
     m_tapDownTimestamp = event->timeStamp();
 
-    HistogramSupport::histogramEnumeration("MouseEventPrefetch.TapDowns", 0, 2);
+    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.TapDowns", 0, 2);
 
     prefetch(WebKit::WebPreconnectMotivationLinkTapDown);
 }
@@ -636,27 +635,27 @@
     if (capturedMouseOver) {
         double mouseOverDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_mouseOverTimestamp);
 
-        HistogramSupport::histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_Click", mouseOverDuration * 1000, 0, 10000, 100);
+        WebKit::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_Click", mouseOverDuration * 1000, 0, 10000, 100);
     }
 
     bool capturedMouseDown = (m_mouseDownTimestamp > 0.0);
-    HistogramSupport::histogramEnumeration("MouseEventPrefetch.MouseDownFollowedByClick", capturedMouseDown, 2);
+    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseDownFollowedByClick", capturedMouseDown, 2);
 
     if (capturedMouseDown) {
         double mouseDownDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_mouseDownTimestamp);
 
-        HistogramSupport::histogramCustomCounts("MouseEventPrefetch.MouseDownDuration_Click", mouseDownDuration * 1000, 0, 10000, 100);
+        WebKit::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseDownDuration_Click", mouseDownDuration * 1000, 0, 10000, 100);
     }
 
     bool capturedTapDown = (m_tapDownTimestamp > 0.0);
     if (capturedTapDown) {
         double tapDownDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_tapDownTimestamp);
 
-        HistogramSupport::histogramCustomCounts("MouseEventPrefetch.TapDownDuration_Click", tapDownDuration * 1000, 0, 10000, 100);
+        WebKit::Platform::current()->histogramCustomCounts("MouseEventPrefetch.TapDownDuration_Click", tapDownDuration * 1000, 0, 10000, 100);
     }
 
     int flags = (m_hadTapUnconfirmed ? 2 : 0) | (capturedTapDown ? 1 : 0);
-    HistogramSupport::histogramEnumeration("MouseEventPrefetch.PreTapEventsFollowedByClick", flags, 4);
+    WebKit::Platform::current()->histogramEnumeration("MouseEventPrefetch.PreTapEventsFollowedByClick", flags, 4);
 }
 
 bool HTMLAnchorElement::PrefetchEventHandler::shouldPrefetch(const KURL& url)
diff --git a/Source/core/html/HTMLAppletElement.cpp b/Source/core/html/HTMLAppletElement.cpp
index 3664ca1..fb3dbac 100644
--- a/Source/core/html/HTMLAppletElement.cpp
+++ b/Source/core/html/HTMLAppletElement.cpp
@@ -40,7 +40,7 @@
 using namespace HTMLNames;
 
 HTMLAppletElement::HTMLAppletElement(const QualifiedName& tagName, Document& document, bool createdByParser)
-    : HTMLPlugInImageElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
+    : HTMLPlugInElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
 {
     ASSERT(hasTagName(appletTag));
     ScriptWrappable::init(this);
@@ -65,14 +65,14 @@
         return;
     }
 
-    HTMLPlugInImageElement::parseAttribute(name, value);
+    HTMLPlugInElement::parseAttribute(name, value);
 }
 
 bool HTMLAppletElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (!fastHasAttribute(codeAttr))
         return false;
-    return HTMLPlugInImageElement::rendererIsNeeded(style);
+    return HTMLPlugInElement::rendererIsNeeded(style);
 }
 
 RenderObject* HTMLAppletElement::createRenderer(RenderStyle* style)
@@ -87,7 +87,7 @@
 {
     if (!canEmbedJava())
         return 0;
-    return HTMLPlugInImageElement::renderWidgetForJSBindings();
+    return HTMLPlugInElement::renderWidgetForJSBindings();
 }
 
 RenderWidget* HTMLAppletElement::existingRenderWidget() const
@@ -168,15 +168,15 @@
     }
 
     RefPtr<Widget> widget;
-    if (frame->loader()->allowPlugins(AboutToInstantiatePlugin))
-        widget = frame->loader()->client()->createJavaAppletWidget(roundedIntSize(LayoutSize(contentWidth, contentHeight)), this, baseURL, paramNames, paramValues);
+    if (frame->loader().allowPlugins(AboutToInstantiatePlugin))
+        widget = frame->loader().client()->createJavaAppletWidget(roundedIntSize(LayoutSize(contentWidth, contentHeight)), this, baseURL, paramNames, paramValues);
 
     if (!widget) {
         if (!renderer->showsUnavailablePluginIndicator())
             renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginMissing);
         return;
     }
-    frame->loader()->setContainsPlugins();
+    frame->loader().setContainsPlugins();
     renderer->setWidget(widget);
 }
 
diff --git a/Source/core/html/HTMLAppletElement.h b/Source/core/html/HTMLAppletElement.h
index 0408a3b..c709b8f 100644
--- a/Source/core/html/HTMLAppletElement.h
+++ b/Source/core/html/HTMLAppletElement.h
@@ -23,11 +23,11 @@
 #ifndef HTMLAppletElement_h
 #define HTMLAppletElement_h
 
-#include "core/html/HTMLPlugInImageElement.h"
+#include "core/html/HTMLPlugInElement.h"
 
 namespace WebCore {
 
-class HTMLAppletElement FINAL : public HTMLPlugInImageElement {
+class HTMLAppletElement FINAL : public HTMLPlugInElement {
 public:
     static PassRefPtr<HTMLAppletElement> create(const QualifiedName&, Document&, bool createdByParser);
 
diff --git a/Source/core/html/HTMLAreaElement.h b/Source/core/html/HTMLAreaElement.h
index b5f2221..67c7a58 100644
--- a/Source/core/html/HTMLAreaElement.h
+++ b/Source/core/html/HTMLAreaElement.h
@@ -78,11 +78,7 @@
     return element->hasTagName(HTMLNames::areaTag);
 }
 
-inline HTMLAreaElement* toHTMLAreaElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLAreaElement(node));
-    return static_cast<HTMLAreaElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLAreaElement, hasTagName(HTMLNames::areaTag));
 
 } //namespace
 
diff --git a/Source/core/html/HTMLAttributeNames.in b/Source/core/html/HTMLAttributeNames.in
index e6d19eb..b80a4ad 100644
--- a/Source/core/html/HTMLAttributeNames.in
+++ b/Source/core/html/HTMLAttributeNames.in
@@ -215,6 +215,7 @@
 onloadeddata
 onloadedmetadata
 onloadstart
+onmessage
 onmousedown
 onmouseenter
 onmouseleave
diff --git a/Source/core/html/HTMLAudioElement.cpp b/Source/core/html/HTMLAudioElement.cpp
index c83650a..e30c85a 100644
--- a/Source/core/html/HTMLAudioElement.cpp
+++ b/Source/core/html/HTMLAudioElement.cpp
@@ -50,10 +50,8 @@
 {
     RefPtr<HTMLAudioElement> audio = adoptRef(new HTMLAudioElement(audioTag, document, false));
     audio->setPreload("auto");
-    if (!src.isNull()) {
+    if (!src.isNull())
         audio->setSrc(src);
-        audio->scheduleDelayedAction(HTMLMediaElement::LoadMediaResource);
-    }
     audio->suspendIfNeeded();
     return audio.release();
 }
diff --git a/Source/core/html/HTMLBodyElement.cpp b/Source/core/html/HTMLBodyElement.cpp
index 0633ec7..ad0cbb2 100644
--- a/Source/core/html/HTMLBodyElement.cpp
+++ b/Source/core/html/HTMLBodyElement.cpp
@@ -132,6 +132,8 @@
         document().setWindowAttributeEventListener(EventTypeNames::popstate, createAttributeEventListener(document().frame(), name, value));
     else if (name == onblurAttr)
         document().setWindowAttributeEventListener(EventTypeNames::blur, createAttributeEventListener(document().frame(), name, value));
+    else if (name == onerrorAttr)
+        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)
@@ -140,6 +142,8 @@
 #endif
     else if (name == onhashchangeAttr)
         document().setWindowAttributeEventListener(EventTypeNames::hashchange, createAttributeEventListener(document().frame(), name, value));
+    else if (name == onmessageAttr)
+        document().setWindowAttributeEventListener(EventTypeNames::message, createAttributeEventListener(document().frame(), name, value));
     else if (name == onresizeAttr)
         document().setWindowAttributeEventListener(EventTypeNames::resize, createAttributeEventListener(document().frame(), name, value));
     else if (name == onscrollAttr)
diff --git a/Source/core/html/HTMLBodyElement.h b/Source/core/html/HTMLBodyElement.h
index 769bd4f..14da8fb 100644
--- a/Source/core/html/HTMLBodyElement.h
+++ b/Source/core/html/HTMLBodyElement.h
@@ -36,23 +36,12 @@
     static PassRefPtr<HTMLBodyElement> create(const QualifiedName&, Document&);
     virtual ~HTMLBodyElement();
 
-    // Declared virtual in Element
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(blur);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll);
 
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeunload);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(hashchange);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(message);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(offline);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(online);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(popstate);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(storage);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(unload);
-
 #if ENABLE(ORIENTATION_EVENTS)
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange);
 #endif
diff --git a/Source/core/html/HTMLBodyElement.idl b/Source/core/html/HTMLBodyElement.idl
index 6ecf3d7..3ce7850 100644
--- a/Source/core/html/HTMLBodyElement.idl
+++ b/Source/core/html/HTMLBodyElement.idl
@@ -26,29 +26,14 @@
     [Reflect, TreatNullAs=NullString] attribute DOMString text;
     [Reflect, TreatNullAs=NullString] attribute DOMString vLink;
 
-    // Event handler attributes
-    [NotEnumerable] attribute EventHandler onbeforeunload;
-    [NotEnumerable] attribute EventHandler onhashchange;
-    [NotEnumerable] attribute EventHandler onmessage;
-    [NotEnumerable] attribute EventHandler onoffline;
-    [NotEnumerable] attribute EventHandler ononline;
-    [NotEnumerable] attribute EventHandler onpopstate;
-    [NotEnumerable] attribute EventHandler onresize;
-    [NotEnumerable] attribute EventHandler onstorage;
-    [NotEnumerable] attribute EventHandler onunload;
+    [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
 
-    [Conditional=ORIENTATION_EVENTS, NotEnumerable] attribute EventHandler onorientationchange;
-
-    // Overrides of Element attributes (with different implementation in bindings).
-    [NotEnumerable] attribute EventHandler onblur;
-    [NotEnumerable] attribute EventHandler onerror;
-    [NotEnumerable] attribute EventHandler onfocus;
-    [NotEnumerable] attribute EventHandler onload;
-
-    // Not implemented yet.
-    // attribute [NotEnumerable] EventHandler onafterprint;
-    // attribute [NotEnumerable] EventHandler onbeforeprint;
-    // attribute [NotEnumerable] EventHandler onredo;
-    // attribute [NotEnumerable] EventHandler onundo;
+    // Overrides of GlobalEventHandler attributes
+    attribute EventHandler onblur;
+    attribute EventHandler onerror;
+    attribute EventHandler onfocus;
+    attribute EventHandler onload;
+    attribute EventHandler onscroll;
 };
 
+HTMLBodyElement implements WindowEventHandlers;
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index 94f0dc4..e94c050 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -43,7 +43,6 @@
 #include "core/html/canvas/WebGLRenderingContext.h"
 #include "core/frame/Frame.h"
 #include "core/page/Settings.h"
-#include "core/platform/HistogramSupport.h"
 #include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/ImageBuffer.h"
@@ -61,22 +60,22 @@
 // Firefox limits width/height to 32767 pixels, but slows down dramatically before it
 // reaches that limit. We limit by area instead, giving us larger maximum dimensions,
 // in exchange for a smaller maximum canvas size.
-static const float MaxCanvasArea = 32768 * 8192; // Maximum canvas area in CSS pixels
+static const int MaxCanvasArea = 32768 * 8192; // Maximum canvas area in CSS pixels
 
 //In Skia, we will also limit width/height to 32767.
-static const float MaxSkiaDim = 32767.0F; // Maximum width/height in CSS pixels.
+static const int MaxSkiaDim = 32767; // Maximum width/height in CSS pixels.
 
 HTMLCanvasElement::HTMLCanvasElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_size(DefaultWidth, DefaultHeight)
     , m_rendererIsCanvas(false)
     , m_ignoreReset(false)
+    , m_accelerationDisabled(false)
+    , m_externallyAllocatedMemory(0)
     , m_deviceScaleFactor(1)
     , m_originClean(true)
     , m_hasCreatedImageBuffer(false)
     , m_didClearImageBuffer(false)
-    , m_accelerationDisabled(false)
-    , m_externallyAllocatedMemory(0)
 {
     ASSERT(hasTagName(canvasTag));
     ScriptWrappable::init(this);
@@ -112,7 +111,7 @@
 RenderObject* HTMLCanvasElement::createRenderer(RenderStyle* style)
 {
     Frame* frame = document().frame();
-    if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
+    if (frame && frame->script().canExecuteScripts(NotAboutToExecuteScript)) {
         m_rendererIsCanvas = true;
         return new RenderHTMLCanvas(this);
     }
@@ -169,7 +168,7 @@
         if (m_context && !m_context->is2d())
             return 0;
         if (!m_context) {
-            HistogramSupport::histogramEnumeration("Canvas.ContextType", Context2d, ContextTypeCount);
+            WebKit::Platform::current()->histogramEnumeration("Canvas.ContextType", Context2d, ContextTypeCount);
             m_context = CanvasRenderingContext2D::create(this, static_cast<Canvas2DContextAttributes*>(attrs), document().inQuirksMode());
             if (m_context)
                 scheduleLayerUpdate();
@@ -196,7 +195,7 @@
             if (m_context && !m_context->is3d())
                 return 0;
             if (!m_context) {
-                HistogramSupport::histogramEnumeration("Canvas.ContextType", contextType, ContextTypeCount);
+                WebKit::Platform::current()->histogramEnumeration("Canvas.ContextType", contextType, ContextTypeCount);
                 m_context = WebGLRenderingContext::create(this, static_cast<WebGLContextAttributes*>(attrs));
                 if (m_context)
                     scheduleLayerUpdate();
@@ -411,35 +410,11 @@
     return ctx->paintRenderingResultsToImageData();
 }
 
-FloatRect HTMLCanvasElement::convertLogicalToDevice(const FloatRect& logicalRect) const
-{
-    FloatRect deviceRect(logicalRect);
-    deviceRect.scale(m_deviceScaleFactor);
-
-    float x = floorf(deviceRect.x());
-    float y = floorf(deviceRect.y());
-    float w = ceilf(deviceRect.maxX() - x);
-    float h = ceilf(deviceRect.maxY() - y);
-    deviceRect.setX(x);
-    deviceRect.setY(y);
-    deviceRect.setWidth(w);
-    deviceRect.setHeight(h);
-
-    return deviceRect;
-}
-
-FloatSize HTMLCanvasElement::convertLogicalToDevice(const FloatSize& logicalSize) const
+IntSize HTMLCanvasElement::convertLogicalToDevice(const IntSize& logicalSize) const
 {
     float width = ceilf(logicalSize.width() * m_deviceScaleFactor);
     float height = ceilf(logicalSize.height() * m_deviceScaleFactor);
-    return FloatSize(width, height);
-}
-
-FloatSize HTMLCanvasElement::convertDeviceToLogical(const FloatSize& deviceSize) const
-{
-    float width = ceilf(deviceSize.width() / m_deviceScaleFactor);
-    float height = ceilf(deviceSize.height() / m_deviceScaleFactor);
-    return FloatSize(width, height);
+    return IntSize(width, height);
 }
 
 SecurityOrigin* HTMLCanvasElement::securityOrigin() const
@@ -481,24 +456,22 @@
     m_hasCreatedImageBuffer = true;
     m_didClearImageBuffer = true;
 
-    FloatSize logicalSize = size();
-    FloatSize deviceSize = convertLogicalToDevice(logicalSize);
-    if (!deviceSize.isExpressibleAsIntSize())
-        return;
-
+    IntSize deviceSize = convertLogicalToDevice(size());
     if (deviceSize.width() * deviceSize.height() > MaxCanvasArea)
         return;
 
     if (deviceSize.width() > MaxSkiaDim || deviceSize.height() > MaxSkiaDim)
         return;
 
-    IntSize bufferSize(deviceSize.width(), deviceSize.height());
-    if (!bufferSize.width() || !bufferSize.height())
+    if (!deviceSize.width() || !deviceSize.height())
         return;
 
-    RenderingMode renderingMode = shouldAccelerate(bufferSize) ? Accelerated : UnacceleratedNonPlatformBuffer;
+    RenderingMode renderingMode = shouldAccelerate(deviceSize) ? Accelerated : UnacceleratedNonPlatformBuffer;
+    int msaaSampleCount = 0;
+    if (renderingMode == Accelerated && document().settings()->antialiased2dCanvasEnabled())
+        msaaSampleCount = document().settings()->accelerated2dCanvasMSAASampleCount();
     OpacityMode opacityMode = !m_context || m_context->hasAlpha() ? NonOpaque : Opaque;
-    m_imageBuffer = ImageBuffer::create(size(), m_deviceScaleFactor, renderingMode, opacityMode);
+    m_imageBuffer = ImageBuffer::create(size(), m_deviceScaleFactor, renderingMode, opacityMode, msaaSampleCount);
     if (!m_imageBuffer)
         return;
     setExternallyAllocatedMemory(4 * width() * height());
@@ -577,9 +550,8 @@
 AffineTransform HTMLCanvasElement::baseTransform() const
 {
     ASSERT(m_hasCreatedImageBuffer);
-    FloatSize unscaledSize = size();
-    FloatSize deviceSize = convertLogicalToDevice(unscaledSize);
-    IntSize size(deviceSize.width(), deviceSize.height());
+    IntSize unscaledSize = size();
+    IntSize size = convertLogicalToDevice(unscaledSize);
     AffineTransform transform;
     if (size.width() && size.height())
         transform.scaleNonUniform(size.width() / unscaledSize.width(), size.height() / unscaledSize.height());
diff --git a/Source/core/html/HTMLCanvasElement.h b/Source/core/html/HTMLCanvasElement.h
index 05289b0..2691bcd 100644
--- a/Source/core/html/HTMLCanvasElement.h
+++ b/Source/core/html/HTMLCanvasElement.h
@@ -111,11 +111,6 @@
     void makePresentationCopy();
     void clearPresentationCopy();
 
-    FloatRect convertLogicalToDevice(const FloatRect&) const;
-    FloatSize convertLogicalToDevice(const FloatSize&) const;
-
-    FloatSize convertDeviceToLogical(const FloatSize&) const;
-
     SecurityOrigin* securityOrigin() const;
     void setOriginTainted() { m_originClean = false; }
     bool originClean() const { return m_originClean; }
@@ -147,6 +142,7 @@
     void clearImageBuffer();
 
     void setSurfaceSize(const IntSize&);
+    IntSize convertLogicalToDevice(const IntSize&) const;
 
     bool paintsIntoCanvasBuffer() const;
 
diff --git a/Source/core/html/HTMLDetailsElement.h b/Source/core/html/HTMLDetailsElement.h
index 55e635c..55cc956 100644
--- a/Source/core/html/HTMLDetailsElement.h
+++ b/Source/core/html/HTMLDetailsElement.h
@@ -54,11 +54,7 @@
     return element->hasTagName(HTMLNames::detailsTag);
 }
 
-inline HTMLDetailsElement* toHTMLDetailsElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLDetailsElement(node));
-    return static_cast<HTMLDetailsElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLDetailsElement, hasTagName(HTMLNames::detailsTag));
 
 } // namespace WebCore
 
diff --git a/Source/core/html/HTMLDimension.cpp b/Source/core/html/HTMLDimension.cpp
index 959b9fe..e15acbe 100644
--- a/Source/core/html/HTMLDimension.cpp
+++ b/Source/core/html/HTMLDimension.cpp
@@ -62,7 +62,6 @@
 
         if (position < endOfCurrentToken && characters[position] == '.') {
             ++position;
-            size_t fractionStart = position;
             Vector<CharacterType> fractionNumbers;
             while (position < endOfCurrentToken && (isASCIIDigit(characters[position]) || isASCIISpace(characters[position]))) {
                 if (isASCIIDigit(characters[position]))
diff --git a/Source/core/html/HTMLDocument.cpp b/Source/core/html/HTMLDocument.cpp
index c0d590a..39952ae 100644
--- a/Source/core/html/HTMLDocument.cpp
+++ b/Source/core/html/HTMLDocument.cpp
@@ -124,7 +124,7 @@
     if (!page->focusController().isActive() || !page->focusController().isFocused())
         return false;
     if (Frame* focusedFrame = page->focusController().focusedFrame()) {
-        if (focusedFrame->tree()->isDescendantOf(frame()))
+        if (focusedFrame->tree().isDescendantOf(frame()))
             return true;
     }
     return false;
@@ -214,22 +214,22 @@
 // not part of the DOM
 // --------------------------------------------------------------------------
 
-void HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name)
+void HTMLDocument::addItemToMap(HashCountedSet<AtomicString>& map, const AtomicString& name)
 {
     if (name.isEmpty())
         return;
-    map.add(name.impl());
+    map.add(name);
     if (Frame* f = frame())
-        f->script()->namedItemAdded(this, name);
+        f->script().namedItemAdded(this, name);
 }
 
-void HTMLDocument::removeItemFromMap(HashCountedSet<StringImpl*>& map, const AtomicString& name)
+void HTMLDocument::removeItemFromMap(HashCountedSet<AtomicString>& map, const AtomicString& name)
 {
     if (name.isEmpty())
         return;
-    map.remove(name.impl());
+    map.remove(name);
     if (Frame* f = frame())
-        f->script()->namedItemRemoved(this, name);
+        f->script().namedItemRemoved(this, name);
 }
 
 void HTMLDocument::addNamedItem(const AtomicString& name)
diff --git a/Source/core/html/HTMLDocument.h b/Source/core/html/HTMLDocument.h
index 144421f..bc3b9a7 100644
--- a/Source/core/html/HTMLDocument.h
+++ b/Source/core/html/HTMLDocument.h
@@ -68,11 +68,11 @@
 
     void addNamedItem(const AtomicString& name);
     void removeNamedItem(const AtomicString& name);
-    bool hasNamedItem(StringImpl* name);
+    bool hasNamedItem(const AtomicString& name);
 
     void addExtraNamedItem(const AtomicString& name);
     void removeExtraNamedItem(const AtomicString& name);
-    bool hasExtraNamedItem(StringImpl* name);
+    bool hasExtraNamedItem(const AtomicString& name);
 
     static bool isCaseSensitiveAttribute(const QualifiedName&);
 
@@ -87,22 +87,20 @@
     const AtomicString& bodyAttributeValue(const QualifiedName&) const;
     void setBodyAttribute(const QualifiedName&, const AtomicString&);
 
-    void addItemToMap(HashCountedSet<StringImpl*>&, const AtomicString&);
-    void removeItemFromMap(HashCountedSet<StringImpl*>&, const AtomicString&);
+    void addItemToMap(HashCountedSet<AtomicString>&, const AtomicString&);
+    void removeItemFromMap(HashCountedSet<AtomicString>&, const AtomicString&);
 
-    HashCountedSet<StringImpl*> m_namedItemCounts;
-    HashCountedSet<StringImpl*> m_extraNamedItemCounts;
+    HashCountedSet<AtomicString> m_namedItemCounts;
+    HashCountedSet<AtomicString> m_extraNamedItemCounts;
 };
 
-inline bool HTMLDocument::hasNamedItem(StringImpl* name)
+inline bool HTMLDocument::hasNamedItem(const AtomicString& name)
 {
-    ASSERT(name);
     return m_namedItemCounts.contains(name);
 }
 
-inline bool HTMLDocument::hasExtraNamedItem(StringImpl* name)
+inline bool HTMLDocument::hasExtraNamedItem(const AtomicString& name)
 {
-    ASSERT(name);
     return m_extraNamedItemCounts.contains(name);
 }
 
diff --git a/Source/core/html/HTMLElement.cpp b/Source/core/html/HTMLElement.cpp
index bdc58e0..c19dcfb 100644
--- a/Source/core/html/HTMLElement.cpp
+++ b/Source/core/html/HTMLElement.cpp
@@ -152,6 +152,11 @@
     return Element::isPresentationAttribute(name);
 }
 
+static inline bool isValidDirAttribute(const AtomicString& value)
+{
+    return equalIgnoringCase(value, "auto") || equalIgnoringCase(value, "ltr") || equalIgnoringCase(value, "rtl");
+}
+
 void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
 {
     if (name == alignAttr) {
@@ -182,7 +187,10 @@
         if (equalIgnoringCase(value, "auto"))
             addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(this));
         else {
-            addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, value);
+            if (isValidDirAttribute(value))
+                addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, value);
+            else
+                addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, "ltr");
             if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
                 addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, CSSValueEmbed);
         }
@@ -329,7 +337,7 @@
 
 void HTMLElement::setInnerHTML(const String& html, ExceptionState& es)
 {
-    if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, es)) {
+    if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", es)) {
         ContainerNode* container = this;
         if (hasLocalName(templateTag))
             container = toHTMLTemplateElement(this)->content();
@@ -362,7 +370,7 @@
     RefPtr<Node> prev = previousSibling();
     RefPtr<Node> next = nextSibling();
 
-    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, es);
+    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, "outerHTML", es);
     if (es.hadException())
         return;
 
@@ -575,7 +583,8 @@
     Element* contextElement = contextElementForInsertion(where, this, es);
     if (!contextElement)
         return;
-    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement, AllowScriptingContent, es);
+
+    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement, AllowScriptingContent, "insertAdjacentHTML", es);
     if (!fragment)
         return;
     insertAdjacent(where, fragment.get(), es);
@@ -771,11 +780,11 @@
 {
     if (hasLocalName(noscriptTag)) {
         Frame* frame = document().frame();
-        if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+        if (frame && frame->script().canExecuteScripts(NotAboutToExecuteScript))
             return false;
     } else if (hasLocalName(noembedTag)) {
         Frame* frame = document().frame();
-        if (frame && frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
+        if (frame && frame->loader().allowPlugins(NotAboutToInstantiatePlugin))
             return false;
     }
     return Element::rendererIsNeeded(style);
@@ -885,7 +894,7 @@
         // Skip elements with valid dir attribute
         if (node->isElementNode()) {
             AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
-            if (equalIgnoringCase(dirAttributeValue, "rtl") || equalIgnoringCase(dirAttributeValue, "ltr") || equalIgnoringCase(dirAttributeValue, "auto")) {
+            if (isValidDirAttribute(dirAttributeValue)) {
                 node = NodeTraversal::nextSkippingChildren(node, this);
                 continue;
             }
diff --git a/Source/core/html/HTMLEmbedElement.cpp b/Source/core/html/HTMLEmbedElement.cpp
index 5bdc27c..09b3b7b 100644
--- a/Source/core/html/HTMLEmbedElement.cpp
+++ b/Source/core/html/HTMLEmbedElement.cpp
@@ -39,7 +39,7 @@
 using namespace HTMLNames;
 
 inline HTMLEmbedElement::HTMLEmbedElement(const QualifiedName& tagName, Document& document, bool createdByParser)
-    : HTMLPlugInImageElement(tagName, document, createdByParser, ShouldPreferPlugInsForImages)
+    : HTMLPlugInElement(tagName, document, createdByParser, ShouldPreferPlugInsForImages)
 {
     ASSERT(hasTagName(embedTag));
     ScriptWrappable::init(this);
@@ -77,7 +77,7 @@
 {
     if (name == hiddenAttr)
         return true;
-    return HTMLPlugInImageElement::isPresentationAttribute(name);
+    return HTMLPlugInElement::isPresentationAttribute(name);
 }
 
 void HTMLEmbedElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
@@ -87,8 +87,9 @@
             addPropertyToPresentationAttributeStyle(style, CSSPropertyWidth, 0, CSSPrimitiveValue::CSS_PX);
             addPropertyToPresentationAttributeStyle(style, CSSPropertyHeight, 0, CSSPrimitiveValue::CSS_PX);
         }
-    } else
-        HTMLPlugInImageElement::collectStyleForPresentationAttribute(name, value, style);
+    } else {
+        HTMLPlugInElement::collectStyleForPresentationAttribute(name, value, style);
+    }
 }
 
 void HTMLEmbedElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -98,17 +99,18 @@
         size_t pos = m_serviceType.find(";");
         if (pos != kNotFound)
             m_serviceType = m_serviceType.left(pos);
-    } else if (name == codeAttr)
+    } else if (name == codeAttr) {
         m_url = stripLeadingAndTrailingHTMLSpaces(value);
-    else if (name == srcAttr) {
+    } else if (name == srcAttr) {
         m_url = stripLeadingAndTrailingHTMLSpaces(value);
         if (renderer() && isImageType()) {
             if (!m_imageLoader)
                 m_imageLoader = adoptPtr(new HTMLImageLoader(this));
             m_imageLoader->updateFromElementIgnoringPreviousError();
         }
-    } else
-        HTMLPlugInImageElement::parseAttribute(name, value);
+    } else {
+        HTMLPlugInElement::parseAttribute(name, value);
+    }
 }
 
 void HTMLEmbedElement::parametersForPlugin(Vector<String>& paramNames, Vector<String>& paramValues)
@@ -124,7 +126,7 @@
 }
 
 // FIXME: This should be unified with HTMLObjectElement::updateWidget and
-// moved down into HTMLPluginImageElement.cpp
+// moved down into HTMLPluginElement.cpp
 void HTMLEmbedElement::updateWidget(PluginCreationOption pluginCreationOption)
 {
     ASSERT(!renderEmbeddedObject()->showsUnavailablePluginIndicator());
@@ -174,7 +176,7 @@
 bool HTMLEmbedElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (isImageType())
-        return HTMLPlugInImageElement::rendererIsNeeded(style);
+        return HTMLPlugInElement::rendererIsNeeded(style);
 
     Frame* frame = document().frame();
     if (!frame)
@@ -190,12 +192,12 @@
             return false;
         }
     }
-    return HTMLPlugInImageElement::rendererIsNeeded(style);
+    return HTMLPlugInElement::rendererIsNeeded(style);
 }
 
 bool HTMLEmbedElement::isURLAttribute(const Attribute& attribute) const
 {
-    return attribute.name() == srcAttr || HTMLPlugInImageElement::isURLAttribute(attribute);
+    return attribute.name() == srcAttr || HTMLPlugInElement::isURLAttribute(attribute);
 }
 
 const AtomicString HTMLEmbedElement::imageSourceURL() const
@@ -205,7 +207,7 @@
 
 void HTMLEmbedElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
 {
-    HTMLPlugInImageElement::addSubresourceAttributeURLs(urls);
+    HTMLPlugInElement::addSubresourceAttributeURLs(urls);
 
     addSubresourceURL(urls, document().completeURL(getAttribute(srcAttr)));
 }
diff --git a/Source/core/html/HTMLEmbedElement.h b/Source/core/html/HTMLEmbedElement.h
index abe1e58..023344a 100644
--- a/Source/core/html/HTMLEmbedElement.h
+++ b/Source/core/html/HTMLEmbedElement.h
@@ -23,11 +23,11 @@
 #ifndef HTMLEmbedElement_h
 #define HTMLEmbedElement_h
 
-#include "core/html/HTMLPlugInImageElement.h"
+#include "core/html/HTMLPlugInElement.h"
 
 namespace WebCore {
 
-class HTMLEmbedElement FINAL : public HTMLPlugInImageElement {
+class HTMLEmbedElement FINAL : public HTMLPlugInElement {
 public:
     static PassRefPtr<HTMLEmbedElement> create(Document&);
     static PassRefPtr<HTMLEmbedElement> create(const QualifiedName&, Document&, bool createdByParser);
diff --git a/Source/core/html/HTMLFormControlElement.h b/Source/core/html/HTMLFormControlElement.h
index fc237b4..973bb5a 100644
--- a/Source/core/html/HTMLFormControlElement.h
+++ b/Source/core/html/HTMLFormControlElement.h
@@ -178,12 +178,13 @@
     bool m_hasAutofocused : 1;
 };
 
-inline HTMLFormControlElement* toHTMLFormControlElement(Node* node)
+inline bool isHTMLFormControlElement(const Node& node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isElementNode() && toElement(node)->isFormControlElement()));
-    return static_cast<HTMLFormControlElement*>(node);
+    return node.isElementNode() && toElement(node).isFormControlElement();
 }
 
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLFormControlElement);
+
 inline HTMLFormControlElement* toHTMLFormControlElement(FormAssociatedElement* control)
 {
     ASSERT_WITH_SECURITY_IMPLICATION(!control || control->isFormControlElement());
diff --git a/Source/core/html/HTMLFormControlElementWithState.cpp b/Source/core/html/HTMLFormControlElementWithState.cpp
index 905fd08..1508d79 100644
--- a/Source/core/html/HTMLFormControlElementWithState.cpp
+++ b/Source/core/html/HTMLFormControlElementWithState.cpp
@@ -77,7 +77,7 @@
 bool HTMLFormControlElementWithState::shouldSaveAndRestoreFormControlState() const
 {
     // We don't save/restore control state in a form with autocomplete=off.
-    return confusingAndOftenMisusedAttached() && shouldAutocomplete();
+    return inActiveDocument() && shouldAutocomplete();
 }
 
 FormControlState HTMLFormControlElementWithState::saveFormControlState() const
diff --git a/Source/core/html/HTMLFormElement.cpp b/Source/core/html/HTMLFormElement.cpp
index 8fe4eed..585ad3c 100644
--- a/Source/core/html/HTMLFormElement.cpp
+++ b/Source/core/html/HTMLFormElement.cpp
@@ -279,7 +279,7 @@
     StringPairVector controlNamesAndValues;
     getTextFieldValues(controlNamesAndValues);
     RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), NotSubmittedByJavaScript);
-    frame->loader()->client()->dispatchWillSendSubmitEvent(formState.release());
+    frame->loader().client()->dispatchWillSendSubmitEvent(formState.release());
 
     if (dispatchEvent(Event::createCancelableBubble(EventTypeNames::submit)))
         m_shouldSubmit = true;
@@ -395,13 +395,13 @@
     if (protocolIsJavaScript(submission->action())) {
         if (!document().contentSecurityPolicy()->allowFormAction(KURL(submission->action())))
             return;
-        document().frame()->script()->executeScriptIfJavaScriptURL(submission->action());
+        document().frame()->script().executeScriptIfJavaScriptURL(submission->action());
         return;
     }
-    submission->setReferrer(document().frame()->loader()->outgoingReferrer());
-    submission->setOrigin(document().frame()->loader()->outgoingOrigin());
+    submission->setReferrer(document().frame()->loader().outgoingReferrer());
+    submission->setOrigin(document().frame()->loader().outgoingOrigin());
 
-    document().frame()->navigationScheduler()->scheduleFormSubmission(submission);
+    document().frame()->navigationScheduler().scheduleFormSubmission(submission);
 }
 
 void HTMLFormElement::reset()
@@ -439,7 +439,7 @@
     StringPairVector controlNamesAndValues;
     getTextFieldValues(controlNamesAndValues);
     RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), SubmittedByJavaScript);
-    frame->loader()->client()->didRequestAutocomplete(formState.release());
+    frame->loader().client()->didRequestAutocomplete(formState.release());
 }
 
 void HTMLFormElement::finishRequestAutocomplete(AutocompleteResult result)
diff --git a/Source/core/html/HTMLFormElement.idl b/Source/core/html/HTMLFormElement.idl
index a5f89d4..f12b47a 100644
--- a/Source/core/html/HTMLFormElement.idl
+++ b/Source/core/html/HTMLFormElement.idl
@@ -39,6 +39,6 @@
     boolean checkValidity();
 
     [RuntimeEnabled=RequestAutocomplete] void requestAutocomplete();
-    [RuntimeEnabled=RequestAutocomplete, NotEnumerable] attribute EventHandler onautocomplete;
-    [RuntimeEnabled=RequestAutocomplete, NotEnumerable] attribute EventHandler onautocompleteerror;
+    [RuntimeEnabled=RequestAutocomplete] attribute EventHandler onautocomplete;
+    [RuntimeEnabled=RequestAutocomplete] attribute EventHandler onautocompleteerror;
 };
diff --git a/Source/core/html/HTMLFrameElementBase.cpp b/Source/core/html/HTMLFrameElementBase.cpp
index 5c3598b..2e7fcde 100644
--- a/Source/core/html/HTMLFrameElementBase.cpp
+++ b/Source/core/html/HTMLFrameElementBase.cpp
@@ -94,7 +94,7 @@
         return;
     if (!contentFrame() || scriptURL.isEmpty())
         return;
-    contentFrame()->script()->executeScriptIfJavaScriptURL(scriptURL);
+    contentFrame()->script().executeScriptIfJavaScriptURL(scriptURL);
 }
 
 void HTMLFrameElementBase::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/html/HTMLFrameElementBase.h b/Source/core/html/HTMLFrameElementBase.h
index 2fa32b9..9352e4e 100644
--- a/Source/core/html/HTMLFrameElementBase.h
+++ b/Source/core/html/HTMLFrameElementBase.h
@@ -77,12 +77,13 @@
     int m_marginHeight;
 };
 
-inline HTMLFrameElementBase* toHTMLFrameElementBase(Node* node)
+inline bool isHTMLFrameElementBase(const Node& node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isElementNode() && toElement(node)->isFrameElementBase()));
-    return static_cast<HTMLFrameElementBase*>(node);
+    return node.isElementNode() && toElement(node).isFrameElementBase();
 }
 
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLFrameElementBase);
+
 } // namespace WebCore
 
 #endif // HTMLFrameElementBase_h
diff --git a/Source/core/html/HTMLFrameOwnerElement.cpp b/Source/core/html/HTMLFrameOwnerElement.cpp
index 184af3a..d072867 100644
--- a/Source/core/html/HTMLFrameOwnerElement.cpp
+++ b/Source/core/html/HTMLFrameOwnerElement.cpp
@@ -82,7 +82,7 @@
     // see if this behavior is really needed as Gecko does not allow this.
     if (Frame* frame = contentFrame()) {
         RefPtr<Frame> protect(frame);
-        frame->loader()->frameDetached();
+        frame->loader().frameDetached();
         frame->disconnectOwnerElement();
     }
 }
@@ -127,7 +127,7 @@
 {
     RefPtr<Frame> parentFrame = document().frame();
     if (contentFrame()) {
-        contentFrame()->navigationScheduler()->scheduleLocationChange(document().securityOrigin(), url.string(), parentFrame->loader()->outgoingReferrer(), lockBackForwardList);
+        contentFrame()->navigationScheduler().scheduleLocationChange(document().securityOrigin(), url.string(), parentFrame->loader().outgoingReferrer(), lockBackForwardList);
         return true;
     }
 
@@ -139,11 +139,11 @@
     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, parentFrame->loader().outgoingReferrer());
+    RefPtr<Frame> childFrame = parentFrame->loader().client()->createFrame(url, frameName, referrer, this);
 
     if (!childFrame)  {
-        parentFrame->loader()->checkCompleted();
+        parentFrame->loader().checkCompleted();
         return false;
     }
 
@@ -153,7 +153,7 @@
     // actually completed below. (Note that we set m_isComplete to false even for synchronous
     // loads, so that checkCompleted() below won't bail early.)
     // FIXME: Can we remove this entirely? m_isComplete normally gets set to false when a load is committed.
-    childFrame->loader()->started();
+    childFrame->loader().started();
 
     RenderObject* renderObject = renderer();
     FrameView* view = childFrame->view();
@@ -169,8 +169,8 @@
     // FIXME: In this case the Frame will have finished loading before
     // it's being added to the child list. It would be a good idea to
     // create the child first, then invoke the loader separately.
-    if (childFrame->loader()->state() == FrameStateComplete && !childFrame->loader()->policyDocumentLoader())
-        childFrame->loader()->checkCompleted();
+    if (childFrame->loader().state() == FrameStateComplete && !childFrame->loader().policyDocumentLoader())
+        childFrame->loader().checkCompleted();
     return true;
 }
 
diff --git a/Source/core/html/HTMLFrameSetElement.cpp b/Source/core/html/HTMLFrameSetElement.cpp
index ff951d8..e699491 100644
--- a/Source/core/html/HTMLFrameSetElement.cpp
+++ b/Source/core/html/HTMLFrameSetElement.cpp
@@ -116,8 +116,14 @@
         document().setWindowAttributeEventListener(EventTypeNames::beforeunload, createAttributeEventListener(document().frame(), name, value));
     else if (name == onunloadAttr)
         document().setWindowAttributeEventListener(EventTypeNames::unload, createAttributeEventListener(document().frame(), name, value));
+    else if (name == onpagehideAttr)
+        document().setWindowAttributeEventListener(EventTypeNames::pagehide, createAttributeEventListener(document().frame(), name, value));
+    else if (name == onpageshowAttr)
+        document().setWindowAttributeEventListener(EventTypeNames::pageshow, createAttributeEventListener(document().frame(), name, value));
     else if (name == onblurAttr)
         document().setWindowAttributeEventListener(EventTypeNames::blur, createAttributeEventListener(document().frame(), name, value));
+    else if (name == onerrorAttr)
+        document().setWindowAttributeEventListener(EventTypeNames::error, createAttributeEventListener(document().frame(), name, value));
     else if (name == onfocusAttr)
         document().setWindowAttributeEventListener(EventTypeNames::focus, createAttributeEventListener(document().frame(), name, value));
     else if (name == onfocusinAttr)
@@ -130,6 +136,8 @@
 #endif
     else if (name == onhashchangeAttr)
         document().setWindowAttributeEventListener(EventTypeNames::hashchange, createAttributeEventListener(document().frame(), name, value));
+    else if (name == onmessageAttr)
+        document().setWindowAttributeEventListener(EventTypeNames::message, createAttributeEventListener(document().frame(), name, value));
     else if (name == onresizeAttr)
         document().setWindowAttributeEventListener(EventTypeNames::resize, createAttributeEventListener(document().frame(), name, value));
     else if (name == onscrollAttr)
@@ -200,7 +208,7 @@
 {
     if (insertionPoint->inDocument() && document().frame()) {
         // A document using <frameset> likely won't literally have a body, but as far as the client is concerned, the frameset is effectively the body.
-        document().frame()->loader()->client()->dispatchWillInsertBody();
+        document().frame()->loader().client()->dispatchWillInsertBody();
     }
     return HTMLElement::insertedInto(insertionPoint);
 }
diff --git a/Source/core/html/HTMLFrameSetElement.h b/Source/core/html/HTMLFrameSetElement.h
index 8ff251b..2815c1a 100644
--- a/Source/core/html/HTMLFrameSetElement.h
+++ b/Source/core/html/HTMLFrameSetElement.h
@@ -47,22 +47,12 @@
 
     DOMWindow* anonymousNamedGetter(const AtomicString&);
 
-    // Declared virtual in Element
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(blur);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll);
 
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeunload);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(hashchange);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(message);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(offline);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(online);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(popstate);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(storage);
-    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(unload);
 #if ENABLE(ORIENTATION_EVENTS)
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange);
 #endif
diff --git a/Source/core/html/HTMLFrameSetElement.idl b/Source/core/html/HTMLFrameSetElement.idl
index 8a09ca1..b1ec56f 100644
--- a/Source/core/html/HTMLFrameSetElement.idl
+++ b/Source/core/html/HTMLFrameSetElement.idl
@@ -23,29 +23,14 @@
     [Reflect, TreatNullAs=NullString] attribute DOMString cols;
     [Reflect, TreatNullAs=NullString] attribute DOMString rows;
 
-    // Event handler attributes
-    [NotEnumerable] attribute EventHandler onbeforeunload;
-    [NotEnumerable] attribute EventHandler onhashchange;
-    [NotEnumerable] attribute EventHandler onmessage;
-    [NotEnumerable] attribute EventHandler onoffline;
-    [NotEnumerable] attribute EventHandler ononline;
-    [NotEnumerable] attribute EventHandler onpopstate;
-    [NotEnumerable] attribute EventHandler onresize;
-    [NotEnumerable] attribute EventHandler onstorage;
-    [NotEnumerable] attribute EventHandler onunload;
+    [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
 
-    [Conditional=ORIENTATION_EVENTS, NotEnumerable] attribute EventHandler onorientationchange;
-
-    // Overrides of Element attributes (with different implementation in bindings).
-    [NotEnumerable] attribute EventHandler onblur;
-    [NotEnumerable] attribute EventHandler onerror;
-    [NotEnumerable] attribute EventHandler onfocus;
-    [NotEnumerable] attribute EventHandler onload;
-
-    // Not implemented yet.
-    // attribute [NotEnumerable] EventHandler onafterprint;
-    // attribute [NotEnumerable] EventHandler onbeforeprint;
-    // attribute [NotEnumerable] EventHandler onredo;
-    // attribute [NotEnumerable] EventHandler onundo;
+    // Overrides of GlobalEventHandler attributes
+    attribute EventHandler onblur;
+    attribute EventHandler onerror;
+    attribute EventHandler onfocus;
+    attribute EventHandler onload;
+    attribute EventHandler onscroll;
 };
 
+HTMLFrameSetElement implements WindowEventHandlers;
diff --git a/Source/core/html/HTMLHtmlElement.cpp b/Source/core/html/HTMLHtmlElement.cpp
index e949dfe..fe9f0ac 100644
--- a/Source/core/html/HTMLHtmlElement.cpp
+++ b/Source/core/html/HTMLHtmlElement.cpp
@@ -67,7 +67,7 @@
     if (!document().frame())
         return;
 
-    DocumentLoader* documentLoader = document().frame()->loader()->documentLoader();
+    DocumentLoader* documentLoader = document().frame()->loader().documentLoader();
     if (!documentLoader)
         return;
 
diff --git a/Source/core/html/HTMLHtmlElement.h b/Source/core/html/HTMLHtmlElement.h
index e66f061..196cd55 100644
--- a/Source/core/html/HTMLHtmlElement.h
+++ b/Source/core/html/HTMLHtmlElement.h
@@ -51,11 +51,7 @@
     return element->hasTagName(HTMLNames::htmlTag);
 }
 
-inline HTMLHtmlElement* toHTMLHtmlElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLHtmlElement(node));
-    return static_cast<HTMLHtmlElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLHtmlElement, hasTagName(HTMLNames::htmlTag));
 
 } // namespace
 
diff --git a/Source/core/html/HTMLImageElement.cpp b/Source/core/html/HTMLImageElement.cpp
index 5f6c411..6a96bc1 100644
--- a/Source/core/html/HTMLImageElement.cpp
+++ b/Source/core/html/HTMLImageElement.cpp
@@ -71,13 +71,13 @@
         m_form->removeImgElement(this);
 }
 
-PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document& document, const int* optionalWidth, const int* optionalHeight)
+PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document& document, int width, int height)
 {
     RefPtr<HTMLImageElement> image = adoptRef(new HTMLImageElement(imgTag, document));
-    if (optionalWidth)
-        image->setWidth(*optionalWidth);
-    if (optionalHeight)
-        image->setHeight(*optionalHeight);
+    if (width)
+        image->setWidth(width);
+    if (height)
+        image->setHeight(height);
     return image.release();
 }
 
diff --git a/Source/core/html/HTMLImageElement.h b/Source/core/html/HTMLImageElement.h
index 5ce887f..6ae7f62 100644
--- a/Source/core/html/HTMLImageElement.h
+++ b/Source/core/html/HTMLImageElement.h
@@ -26,7 +26,7 @@
 
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLImageLoader.h"
-#include "core/platform/graphics/GraphicsTypes.h"
+#include "platform/graphics/GraphicsTypes.h"
 
 namespace WebCore {
 
@@ -37,7 +37,7 @@
 public:
     static PassRefPtr<HTMLImageElement> create(Document&);
     static PassRefPtr<HTMLImageElement> create(const QualifiedName&, Document&, HTMLFormElement*);
-    static PassRefPtr<HTMLImageElement> createForJSConstructor(Document&, const int* optionalWidth, const int* optionalHeight);
+    static PassRefPtr<HTMLImageElement> createForJSConstructor(Document&, int width, int height);
 
     virtual ~HTMLImageElement();
 
diff --git a/Source/core/html/HTMLImageElement.idl b/Source/core/html/HTMLImageElement.idl
index a7c80e5..1812761 100644
--- a/Source/core/html/HTMLImageElement.idl
+++ b/Source/core/html/HTMLImageElement.idl
@@ -18,7 +18,10 @@
  * Boston, MA 02110-1301, USA.
  */
 
+// FIXME: NamedConstructor does not support optional without Default. Fortunately using Undefined makes
+// us use 0 which happens to be the default width and height anyway.
 [
+    NamedConstructor=Image([Default=Undefined] optional long width, [Default=Undefined] optional long height)
 ] interface HTMLImageElement : HTMLElement {
     [Reflect, TreatNullAs=NullString] attribute DOMString name;
     [Reflect, TreatNullAs=NullString] attribute DOMString align;
@@ -43,4 +46,3 @@
     readonly attribute long x;
     readonly attribute long y;
 };
-
diff --git a/Source/core/html/HTMLImageLoader.cpp b/Source/core/html/HTMLImageLoader.cpp
index a718ba1..9a50c5f 100644
--- a/Source/core/html/HTMLImageLoader.cpp
+++ b/Source/core/html/HTMLImageLoader.cpp
@@ -69,7 +69,7 @@
     bool loadError = cachedImage->errorOccurred() || cachedImage->response().httpStatusCode() >= 400;
 
     if (loadError && element->hasTagName(HTMLNames::objectTag))
-        toHTMLObjectElement(element.get())->renderFallbackContent();
+        toHTMLObjectElement(element)->renderFallbackContent();
 }
 
 }
diff --git a/Source/core/html/HTMLInputElement.cpp b/Source/core/html/HTMLInputElement.cpp
index 33a04f4..cab18d8 100644
--- a/Source/core/html/HTMLInputElement.cpp
+++ b/Source/core/html/HTMLInputElement.cpp
@@ -50,6 +50,8 @@
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/events/TouchEvent.h"
 #include "core/fileapi/FileList.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLDataListElement.h"
 #include "core/html/HTMLFormElement.h"
@@ -61,8 +63,7 @@
 #include "core/html/forms/InputType.h"
 #include "core/html/forms/SearchInputType.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/frame/Frame.h"
-#include "core/frame/FrameView.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/page/UseCounter.h"
 #include "core/platform/DateTimeChooser.h"
 #include "core/rendering/RenderTextControlSingleLine.h"
@@ -94,7 +95,7 @@
 // large. However, due to https://bugs.webkit.org/show_bug.cgi?id=14536 things
 // get rather sluggish when a text field has a larger number of characters than
 // this, even when just clicking in the text field.
-const unsigned HTMLInputElement::maximumLength = 524288;
+const int HTMLInputElement::maximumLength = 524288;
 const int defaultSize = 20;
 const int maxSavedResults = 256;
 
@@ -175,14 +176,9 @@
     return FileInputType::filesFromFormControlState(state);
 }
 
-HTMLElement* HTMLInputElement::innerTextElement() const
-{
-    return m_inputType->innerTextElement();
-}
-
 HTMLElement* HTMLInputElement::passwordGeneratorButtonElement() const
 {
-    return m_inputType->passwordGeneratorButtonElement();
+    return toHTMLElement(userAgentShadowRoot()->getElementById(ShadowElementNames::passwordGenerator()));
 }
 
 bool HTMLInputElement::shouldAutocomplete() const
@@ -418,10 +414,7 @@
     bool didRespectHeightAndWidth = m_inputType->shouldRespectHeightAndWidthAttributes();
 
     m_inputType->destroyShadowSubtree();
-
-    bool wasAttached = confusingAndOftenMisusedAttached();
-    if (wasAttached)
-        detach();
+    lazyReattachIfAttached();
 
     m_inputType = newType.release();
     if (hasAuthorShadowRoot())
@@ -468,11 +461,8 @@
             attributeChanged(alignAttr, align->value());
     }
 
-    if (wasAttached) {
-        lazyAttach();
-        if (document().focusedElement() == this)
-            document().updateFocusAppearanceSoon(true /* restore selection */);
-    }
+    if (document().focusedElement() == this)
+        document().updateFocusAppearanceSoon(true /* restore selection */);
 
     setChangedSinceLastFormControlChangeEvent(false);
 
diff --git a/Source/core/html/HTMLInputElement.h b/Source/core/html/HTMLInputElement.h
index 1db4f99..e34f871 100644
--- a/Source/core/html/HTMLInputElement.h
+++ b/Source/core/html/HTMLInputElement.h
@@ -119,7 +119,6 @@
     bool isSpeechEnabled() const;
 #endif
 
-    virtual HTMLElement* innerTextElement() const;
     HTMLElement* passwordGeneratorButtonElement() const;
 
     bool checked() const { return m_isChecked; }
@@ -251,7 +250,7 @@
     bool capture() const;
 #endif
 
-    static const unsigned maximumLength;
+    static const int maximumLength;
 
     unsigned height() const;
     unsigned width() const;
diff --git a/Source/core/html/HTMLInputElement.idl b/Source/core/html/HTMLInputElement.idl
index 20056c3..c1f1666 100644
--- a/Source/core/html/HTMLInputElement.idl
+++ b/Source/core/html/HTMLInputElement.idl
@@ -96,7 +96,7 @@
     [Reflect] attribute boolean incremental;
     [Conditional=INPUT_SPEECH, Reflect, RuntimeEnabled=SpeechInput] attribute boolean webkitSpeech;
     [Conditional=INPUT_SPEECH, Reflect, RuntimeEnabled=SpeechInput] attribute boolean webkitGrammar;
-    [Conditional=INPUT_SPEECH, NotEnumerable] attribute EventHandler onwebkitspeechchange;
+    [Conditional=INPUT_SPEECH] attribute EventHandler onwebkitspeechchange;
 
     // See http://www.w3.org/TR/html-media-capture/
     [Conditional=MEDIA_CAPTURE, Reflect] attribute boolean capture;
diff --git a/Source/core/html/HTMLLabelElement.h b/Source/core/html/HTMLLabelElement.h
index f199395..a71af43 100644
--- a/Source/core/html/HTMLLabelElement.h
+++ b/Source/core/html/HTMLLabelElement.h
@@ -66,11 +66,7 @@
     return element->hasTagName(HTMLNames::labelTag);
 }
 
-inline HTMLLabelElement* toHTMLLabelElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLLabelElement(node));
-    return static_cast<HTMLLabelElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLLabelElement, hasTagName(HTMLNames::labelTag));
 
 } //namespace
 
diff --git a/Source/core/html/HTMLLinkElement.cpp b/Source/core/html/HTMLLinkElement.cpp
index 3fa28a1..5e40e35 100644
--- a/Source/core/html/HTMLLinkElement.cpp
+++ b/Source/core/html/HTMLLinkElement.cpp
@@ -178,7 +178,7 @@
 Document* HTMLLinkElement::import() const
 {
     if (LinkImport* link = linkImport())
-        return linkImport()->importedDocument();
+        return link->importedDocument();
     return 0;
 }
 
@@ -572,7 +572,7 @@
         if (!document().contentSecurityPolicy()->allowImageFromSource(builder.url()))
             return;
         if (document().frame())
-            document().frame()->loader()->client()->dispatchDidChangeIcons(m_owner->relAttribute().iconType());
+            document().frame()->loader().client()->dispatchDidChangeIcons(m_owner->relAttribute().iconType());
     }
 
     if (!m_owner->loadLink(type, builder.url()))
diff --git a/Source/core/html/HTMLMediaElement.cpp b/Source/core/html/HTMLMediaElement.cpp
index e51a051..8d0674c 100644
--- a/Source/core/html/HTMLMediaElement.cpp
+++ b/Source/core/html/HTMLMediaElement.cpp
@@ -125,7 +125,7 @@
 #endif
 
 // URL protocol used to signal that the media source API is being used.
-static const char* mediaSourceBlobProtocol = "blob";
+static const char mediaSourceBlobProtocol[] = "blob";
 
 using namespace HTMLNames;
 using namespace std;
@@ -272,7 +272,7 @@
     , m_playing(false)
     , m_shouldDelayLoadEvent(false)
     , m_haveFiredLoadedData(false)
-    , m_inActiveDocument(true)
+    , m_active(true)
     , m_autoplaying(true)
     , m_muted(false)
     , m_paused(true)
@@ -486,7 +486,7 @@
 
     HTMLElement::insertedInto(insertionPoint);
     if (insertionPoint->inDocument()) {
-        m_inActiveDocument = true;
+        m_active = true;
 
         if (!getAttribute(srcAttr).isEmpty() && m_networkState == NETWORK_EMPTY)
             scheduleDelayedAction(LoadMediaResource);
@@ -500,7 +500,7 @@
 {
     LOG(Media, "HTMLMediaElement::removedFrom");
 
-    m_inActiveDocument = false;
+    m_active = false;
     if (insertionPoint->inDocument()) {
         configureMediaControls();
         if (m_networkState > NETWORK_EMPTY)
@@ -1224,7 +1224,7 @@
 {
     ASSERT(m_ignoreTrackDisplayUpdate);
     --m_ignoreTrackDisplayUpdate;
-    if (!m_ignoreTrackDisplayUpdate && m_inActiveDocument)
+    if (!m_ignoreTrackDisplayUpdate && m_active)
         updateActiveTextTrackCues(currentTime());
 }
 
@@ -1982,14 +1982,6 @@
     seek(time, es);
 }
 
-double HTMLMediaElement::initialTime() const
-{
-    if (m_fragmentStartTime != MediaPlayer::invalidTime())
-        return m_fragmentStartTime;
-
-    return 0;
-}
-
 double HTMLMediaElement::duration() const
 {
     if (!m_player || m_readyState < HAVE_METADATA)
@@ -2068,12 +2060,6 @@
     return fastHasAttribute(autoplayAttr);
 }
 
-void HTMLMediaElement::setAutoplay(bool b)
-{
-    LOG(Media, "HTMLMediaElement::setAutoplay(%s)", boolString(b));
-    setBooleanAttribute(autoplayAttr, b);
-}
-
 String HTMLMediaElement::preload() const
 {
     switch (m_preload) {
@@ -2277,7 +2263,7 @@
     Frame* frame = document().frame();
 
     // always show controls when scripting is disabled
-    if (frame && !frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+    if (frame && !frame->script().canExecuteScripts(NotAboutToExecuteScript))
         return true;
 
     // Always show controls when in full screen mode.
@@ -2876,6 +2862,7 @@
         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
@@ -2894,8 +2881,10 @@
             if (shouldLog)
                 LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'media' is %s", source->media().utf8().data());
 #endif
-            if (!screenEval.eval(media.get()))
+            if (!screenEval.eval(media.get())) {
+                UseCounter::count(document(), UseCounter::SourceElementNonMatchingMedia);
                 goto check_again;
+            }
         }
 
         type = source->type();
@@ -3422,7 +3411,7 @@
 {
     LOG(Media, "HTMLMediaElement::stop");
 
-    m_inActiveDocument = false;
+    m_active = false;
     userCancelledLoad();
 
     // Stop the playback without generating events
@@ -3459,8 +3448,13 @@
 {
     LOG(Media, "HTMLMediaElement::enterFullscreen");
 
+    bool processingUserGesture = UserGestureIndicator::processingUserGesture();
     if (document().settings() && document().settings()->fullScreenEnabled())
         FullscreenElementStack::from(&document())->requestFullScreenForElement(this, 0, FullscreenElementStack::ExemptIFrameAllowFullScreenRequirement);
+    // If gesture is consumed by FullscreenElementStack, remove all the behavior
+    // restrictions as other media operations may depend on the same gesture.
+    if (processingUserGesture && !UserGestureIndicator::processingUserGesture())
+        removeBehaviorsRestrictionsAfterFirstUserGesture();
 }
 
 void HTMLMediaElement::exitFullscreen()
diff --git a/Source/core/html/HTMLMediaElement.h b/Source/core/html/HTMLMediaElement.h
index e53f5f2..fc4c1f9 100644
--- a/Source/core/html/HTMLMediaElement.h
+++ b/Source/core/html/HTMLMediaElement.h
@@ -96,7 +96,7 @@
     };
     void scheduleDelayedAction(DelayedActionType);
 
-    bool inActiveDocument() const { return m_inActiveDocument; }
+    bool isActive() const { return m_active; }
 
 // DOM API
 // error state
@@ -123,7 +123,6 @@
 // playback state
     double currentTime() const;
     void setCurrentTime(double, ExceptionState&);
-    double initialTime() const;
     double duration() const;
     bool paused() const;
     double defaultPlaybackRate() const;
@@ -135,7 +134,6 @@
     PassRefPtr<TimeRanges> seekable() const;
     bool ended() const;
     bool autoplay() const;
-    void setAutoplay(bool b);
     bool loop() const;
     void setLoop(bool b);
     void play();
@@ -516,10 +514,11 @@
     typedef unsigned PendingActionFlags;
     PendingActionFlags m_pendingActionFlags;
 
+    // FIXME: MediaElement has way too many state bits.
     bool m_playing : 1;
     bool m_shouldDelayLoadEvent : 1;
     bool m_haveFiredLoadedData : 1;
-    bool m_inActiveDocument : 1;
+    bool m_active : 1;
     bool m_autoplaying : 1;
     bool m_muted : 1;
     bool m_paused : 1;
@@ -599,12 +598,13 @@
     return node && node->isElementNode() && toElement(node)->isMediaElement();
 }
 
-inline HTMLMediaElement* toHTMLMediaElement(Node* node)
+inline bool isHTMLMediaElement(const Node& node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLMediaElement(node));
-    return static_cast<HTMLMediaElement*>(node);
+    return node.isElementNode() && toElement(node).isMediaElement();
 }
 
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLMediaElement);
+
 } //namespace
 
 #endif
diff --git a/Source/core/html/HTMLMediaElement.idl b/Source/core/html/HTMLMediaElement.idl
index 0007ac7..60d9ba6 100644
--- a/Source/core/html/HTMLMediaElement.idl
+++ b/Source/core/html/HTMLMediaElement.idl
@@ -32,7 +32,7 @@
     readonly attribute MediaError error;
 
     // network state
-    [Reflect, TreatNullAs=NullString, URL] attribute DOMString src;
+    [Reflect, URL] attribute DOMString src;
     [URL] readonly attribute DOMString currentSrc;
 
     const unsigned short NETWORK_EMPTY = 0;
@@ -57,7 +57,6 @@
 
     // playback state
     [SetterRaisesException] attribute double currentTime;
-    readonly attribute double initialTime;
     readonly attribute double duration;
     readonly attribute boolean paused;
     attribute double defaultPlaybackRate;
@@ -71,7 +70,7 @@
     void pause();
 
     // media controller
-    [Reflect, TreatNullAs=NullString] attribute DOMString mediaGroup;
+    [Reflect] attribute DOMString mediaGroup;
     [CustomSetter] attribute MediaController controller;
 
     // controls
diff --git a/Source/core/html/HTMLMeterElement.h b/Source/core/html/HTMLMeterElement.h
index 2e1d6b6..cfdbaf4 100644
--- a/Source/core/html/HTMLMeterElement.h
+++ b/Source/core/html/HTMLMeterElement.h
@@ -86,11 +86,7 @@
     return node->hasTagName(HTMLNames::meterTag);
 }
 
-inline HTMLMeterElement* toHTMLMeterElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLMeterElement(node));
-    return static_cast<HTMLMeterElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLMeterElement, hasTagName(HTMLNames::meterTag));
 
 } // namespace
 
diff --git a/Source/core/html/HTMLObjectElement.cpp b/Source/core/html/HTMLObjectElement.cpp
index 7df63dd..b336370 100644
--- a/Source/core/html/HTMLObjectElement.cpp
+++ b/Source/core/html/HTMLObjectElement.cpp
@@ -49,7 +49,7 @@
 using namespace HTMLNames;
 
 inline HTMLObjectElement::HTMLObjectElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
-    : HTMLPlugInImageElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
+    : HTMLPlugInElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
     , m_docNamedItem(true)
     , m_useFallbackContent(false)
 {
@@ -77,7 +77,7 @@
 {
     if (name == borderAttr)
         return true;
-    return HTMLPlugInImageElement::isPresentationAttribute(name);
+    return HTMLPlugInElement::isPresentationAttribute(name);
 }
 
 void HTMLObjectElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
@@ -85,7 +85,7 @@
     if (name == borderAttr)
         applyBorderAttributeToStyle(value, style);
     else
-        HTMLPlugInImageElement::collectStyleForPresentationAttribute(name, value, style);
+        HTMLPlugInElement::collectStyleForPresentationAttribute(name, value, style);
 }
 
 void HTMLObjectElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -113,10 +113,11 @@
         m_classId = value;
         if (renderer())
             setNeedsWidgetUpdate(true);
-    } else if (name == onbeforeloadAttr)
+    } else if (name == onbeforeloadAttr) {
         setAttributeEventListener(EventTypeNames::beforeload, createAttributeEventListener(this, name, value));
-    else
-        HTMLPlugInImageElement::parseAttribute(name, value);
+    } else {
+        HTMLPlugInElement::parseAttribute(name, value);
+    }
 }
 
 static void mapDataParamToSrc(Vector<String>* paramNames, Vector<String>* paramValues)
@@ -249,7 +250,7 @@
 
 bool HTMLObjectElement::hasValidClassId()
 {
-    if (MIMETypeRegistry::isJavaAppletMIMEType(serviceType()) && classId().startsWith("java:", false))
+    if (MIMETypeRegistry::isJavaAppletMIMEType(m_serviceType) && classId().startsWith("java:", false))
         return true;
 
     if (shouldAllowQuickTimeClassIdQuirk())
@@ -261,7 +262,7 @@
 }
 
 // FIXME: This should be unified with HTMLEmbedElement::updateWidget and
-// moved down into HTMLPluginImageElement.cpp
+// moved down into HTMLPluginElement.cpp
 void HTMLObjectElement::updateWidget(PluginCreationOption pluginCreationOption)
 {
     ASSERT(!renderEmbeddedObject()->showsUnavailablePluginIndicator());
@@ -278,7 +279,7 @@
         return;
 
     String url = this->url();
-    String serviceType = this->serviceType();
+    String serviceType = m_serviceType;
 
     // FIXME: These should be joined into a PluginParameters class.
     Vector<String> paramNames;
@@ -314,23 +315,21 @@
 bool HTMLObjectElement::rendererIsNeeded(const RenderStyle& style)
 {
     // FIXME: This check should not be needed, detached documents never render!
-    Frame* frame = document().frame();
-    if (!frame)
+    if (!document().frame())
         return false;
-
-    return HTMLPlugInImageElement::rendererIsNeeded(style);
+    return HTMLPlugInElement::rendererIsNeeded(style);
 }
 
 Node::InsertionNotificationRequest HTMLObjectElement::insertedInto(ContainerNode* insertionPoint)
 {
-    HTMLPlugInImageElement::insertedInto(insertionPoint);
+    HTMLPlugInElement::insertedInto(insertionPoint);
     FormAssociatedElement::insertedInto(insertionPoint);
     return InsertionDone;
 }
 
 void HTMLObjectElement::removedFrom(ContainerNode* insertionPoint)
 {
-    HTMLPlugInImageElement::removedFrom(insertionPoint);
+    HTMLPlugInElement::removedFrom(insertionPoint);
     FormAssociatedElement::removedFrom(insertionPoint);
 }
 
@@ -341,12 +340,12 @@
         setNeedsWidgetUpdate(true);
         setNeedsStyleRecalc();
     }
-    HTMLPlugInImageElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
+    HTMLPlugInElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
 }
 
 bool HTMLObjectElement::isURLAttribute(const Attribute& attribute) const
 {
-    return attribute.name() == dataAttr || (attribute.name() == usemapAttr && attribute.value().string()[0] != '#') || HTMLPlugInImageElement::isURLAttribute(attribute);
+    return attribute.name() == dataAttr || (attribute.name() == usemapAttr && attribute.value().string()[0] != '#') || HTMLPlugInElement::isURLAttribute(attribute);
 }
 
 const AtomicString HTMLObjectElement::imageSourceURL() const
@@ -362,7 +361,7 @@
     if (document().inStyleRecalc())
         reattach();
     else
-        lazyReattach();
+        lazyReattachIfAttached();
 }
 
 void HTMLObjectElement::renderFallbackContent()
@@ -395,7 +394,7 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<StringImpl*>, tagList, ());
     if (tagList.isEmpty()) {
-        QualifiedName** tags = HTMLNames::getHTMLTags();
+        const QualifiedName* const* tags = HTMLNames::getHTMLTags();
         for (size_t i = 0; i < HTMLNames::HTMLTagsCount; i++) {
             if (*tags[i] == bgsoundTag
                 || *tags[i] == commandTag
@@ -470,7 +469,7 @@
 
 void HTMLObjectElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
 {
-    HTMLPlugInImageElement::addSubresourceAttributeURLs(urls);
+    HTMLPlugInElement::addSubresourceAttributeURLs(urls);
 
     addSubresourceURL(urls, document().completeURL(getAttribute(dataAttr)));
 
@@ -484,7 +483,7 @@
 void HTMLObjectElement::didMoveToNewDocument(Document& oldDocument)
 {
     FormAssociatedElement::didMoveToNewDocument(oldDocument);
-    HTMLPlugInImageElement::didMoveToNewDocument(oldDocument);
+    HTMLPlugInElement::didMoveToNewDocument(oldDocument);
 }
 
 bool HTMLObjectElement::appendFormData(FormDataList& encoding, bool)
diff --git a/Source/core/html/HTMLObjectElement.h b/Source/core/html/HTMLObjectElement.h
index 16fc462..1326c6e 100644
--- a/Source/core/html/HTMLObjectElement.h
+++ b/Source/core/html/HTMLObjectElement.h
@@ -24,13 +24,13 @@
 #define HTMLObjectElement_h
 
 #include "core/html/FormAssociatedElement.h"
-#include "core/html/HTMLPlugInImageElement.h"
+#include "core/html/HTMLPlugInElement.h"
 
 namespace WebCore {
 
 class HTMLFormElement;
 
-class HTMLObjectElement FINAL : public HTMLPlugInImageElement, public FormAssociatedElement {
+class HTMLObjectElement FINAL : public HTMLPlugInElement, public FormAssociatedElement {
 public:
     static PassRefPtr<HTMLObjectElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
     virtual ~HTMLObjectElement();
diff --git a/Source/core/html/HTMLOptGroupElement.h b/Source/core/html/HTMLOptGroupElement.h
index b759218..0cc4c1e 100644
--- a/Source/core/html/HTMLOptGroupElement.h
+++ b/Source/core/html/HTMLOptGroupElement.h
@@ -73,11 +73,7 @@
     return element->hasTagName(HTMLNames::optgroupTag);
 }
 
-inline HTMLOptGroupElement* toHTMLOptGroupElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLOptGroupElement(node));
-    return static_cast<HTMLOptGroupElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLOptGroupElement, hasTagName(HTMLNames::optgroupTag));
 
 } //namespace
 
diff --git a/Source/core/html/HTMLPlugInElement.cpp b/Source/core/html/HTMLPlugInElement.cpp
index e7550e9..f3ad962 100644
--- a/Source/core/html/HTMLPlugInElement.cpp
+++ b/Source/core/html/HTMLPlugInElement.cpp
@@ -28,12 +28,24 @@
 #include "bindings/v8/ScriptController.h"
 #include "bindings/v8/npruntime_impl.h"
 #include "core/dom/Document.h"
+#include "core/dom/PostAttachCallbacks.h"
 #include "core/events/Event.h"
-#include "core/page/EventHandler.h"
+#include "core/frame/ContentSecurityPolicy.h"
 #include "core/frame/Frame.h"
+#include "core/html/HTMLImageLoader.h"
+#include "core/html/PluginDocument.h"
+#include "core/loader/FrameLoaderClient.h"
+#include "core/page/EventHandler.h"
+#include "core/page/Page.h"
+#include "core/page/Settings.h"
+#include "core/platform/MIMETypeFromURL.h"
+#include "core/platform/MIMETypeRegistry.h"
+#include "core/plugins/PluginData.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/RenderEmbeddedObject.h"
+#include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderWidget.h"
+#include "platform/Logging.h"
 #include "platform/Widget.h"
 #include "wtf/UnusedParam.h"
 
@@ -42,13 +54,20 @@
 
 using namespace HTMLNames;
 
-HTMLPlugInElement::HTMLPlugInElement(const QualifiedName& tagName, Document& doc)
+HTMLPlugInElement::HTMLPlugInElement(const QualifiedName& tagName, Document& doc, bool createdByParser, PreferPlugInsForImagesOption preferPlugInsForImagesOption)
     : HTMLFrameOwnerElement(tagName, doc)
     , m_NPObject(0)
     , m_isCapturingMouseEvents(false)
     , m_inBeforeLoadEventHandler(false)
+    // m_needsWidgetUpdate(!createdByParser) allows HTMLObjectElement to delay
+    // widget updates until after all children are parsed. For HTMLEmbedElement
+    // this delay is unnecessary, but it is simpler to make both classes share
+    // the same codepath in this class.
+    , m_needsWidgetUpdate(!createdByParser)
+    , m_shouldPreferPlugInsForImages(preferPlugInsForImagesOption == ShouldPreferPlugInsForImages)
     , m_displayState(Playing)
 {
+    setHasCustomStyleCallbacks();
 }
 
 HTMLPlugInElement::~HTMLPlugInElement()
@@ -63,8 +82,7 @@
 
 bool HTMLPlugInElement::canProcessDrag() const
 {
-    const PluginView* plugin = pluginWidget() && pluginWidget()->isPluginView() ? toPluginView(pluginWidget()) : 0;
-    return plugin ? plugin->canProcessDrag() : false;
+    return pluginWidget() && pluginWidget()->isPluginView() && toPluginView(pluginWidget())->canProcessDrag();
 }
 
 bool HTMLPlugInElement::willRespondToMouseClickEvents()
@@ -72,11 +90,7 @@
     if (isDisabledFormControl())
         return false;
     RenderObject* r = renderer();
-    if (!r)
-        return false;
-    if (!r->isEmbeddedObject() && !r->isWidget())
-        return false;
-    return true;
+    return r && (r->isEmbeddedObject() || r->isWidget());
 }
 
 void HTMLPlugInElement::removeAllEventListeners()
@@ -88,13 +102,58 @@
     }
 }
 
+void HTMLPlugInElement::didMoveToNewDocument(Document& oldDocument)
+{
+    if (m_imageLoader)
+        m_imageLoader->elementDidMoveToNewDocument();
+    HTMLFrameOwnerElement::didMoveToNewDocument(oldDocument);
+}
+
+void HTMLPlugInElement::attach(const AttachContext& context)
+{
+    bool isImage = isImageType();
+
+    if (!isImage)
+        PostAttachCallbacks::queueCallback(HTMLPlugInElement::updateWidgetCallback, this);
+
+    HTMLFrameOwnerElement::attach(context);
+
+    if (isImage && renderer() && !useFallbackContent()) {
+        if (!m_imageLoader)
+            m_imageLoader = adoptPtr(new HTMLImageLoader(this));
+        m_imageLoader->updateFromElement();
+    }
+}
+
+void HTMLPlugInElement::updateWidgetCallback(Node* n)
+{
+    toHTMLPlugInElement(n)->updateWidgetIfNecessary();
+}
+
+void HTMLPlugInElement::updateWidgetIfNecessary()
+{
+    document().updateStyleIfNeeded();
+
+    if (!needsWidgetUpdate() || useFallbackContent() || isImageType())
+        return;
+    if (!renderEmbeddedObject() || renderEmbeddedObject()->showsUnavailablePluginIndicator())
+        return;
+
+    updateWidget(CreateOnlyNonNetscapePlugins);
+}
+
 void HTMLPlugInElement::detach(const AttachContext& context)
 {
+    // Update the widget the next time we attach (detaching destroys the plugin).
+    // FIXME: None of this "needsWidgetUpdate" related code looks right.
+    if (renderer() && !useFallbackContent())
+        setNeedsWidgetUpdate(true);
+
     resetInstance();
 
     if (m_isCapturingMouseEvents) {
         if (Frame* frame = document().frame())
-            frame->eventHandler()->setCapturingMouseEventsNode(0);
+            frame->eventHandler().setCapturingMouseEventsNode(0);
         m_isCapturingMouseEvents = false;
     }
 
@@ -106,6 +165,41 @@
     HTMLFrameOwnerElement::detach(context);
 }
 
+RenderObject* HTMLPlugInElement::createRenderer(RenderStyle* style)
+{
+    // Fallback content breaks the DOM->Renderer class relationship of this
+    // class and all superclasses because createObject won't necessarily
+    // return a RenderEmbeddedObject, RenderPart or even RenderWidget.
+    if (useFallbackContent())
+        return RenderObject::createObject(this, style);
+
+    if (isImageType()) {
+        RenderImage* image = new RenderImage(this);
+        image->setImageResource(RenderImageResource::create());
+        return image;
+    }
+
+    return new RenderEmbeddedObject(this);
+}
+
+void HTMLPlugInElement::willRecalcStyle(StyleRecalcChange)
+{
+    // FIXME: Why is this necessary? Manual re-attach is almost always wrong.
+    if (!useFallbackContent() && needsWidgetUpdate() && renderer() && !isImageType())
+        reattach();
+}
+
+void HTMLPlugInElement::finishParsingChildren()
+{
+    HTMLFrameOwnerElement::finishParsingChildren();
+    if (useFallbackContent())
+        return;
+
+    setNeedsWidgetUpdate(true);
+    if (inDocument())
+        setNeedsStyleRecalc();
+}
+
 void HTMLPlugInElement::resetInstance()
 {
     m_pluginWrapper.clear();
@@ -117,11 +211,12 @@
     if (!frame)
         return 0;
 
-    // If the host dynamically turns off JavaScript (or Java) we will still return
-    // the cached allocated Bindings::Instance.  Not supporting this edge-case is OK.
+    // If the host dynamically turns off JavaScript (or Java) we will still
+    // return the cached allocated Bindings::Instance. Not supporting this
+    // edge-case is OK.
     if (!m_pluginWrapper) {
         if (Widget* widget = pluginWidget())
-            m_pluginWrapper = frame->script()->createPluginWrapper(widget);
+            m_pluginWrapper = frame->script().createPluginWrapper(widget);
     }
     return m_pluginWrapper.get();
 }
@@ -142,16 +237,15 @@
 Widget* HTMLPlugInElement::pluginWidget() const
 {
     if (m_inBeforeLoadEventHandler) {
-        // The plug-in hasn't loaded yet, and it makes no sense to try to load if beforeload handler happened to touch the plug-in element.
-        // That would recursively call beforeload for the same element.
+        // The plug-in hasn't loaded yet, and it makes no sense to try to load
+        // if beforeload handler happened to touch the plug-in element. That
+        // would recursively call beforeload for the same element.
         return 0;
     }
 
-    RenderWidget* renderWidget = renderWidgetForJSBindings();
-    if (!renderWidget)
-        return 0;
-
-    return renderWidget->widget();
+    if (RenderWidget* renderWidget = renderWidgetForJSBindings())
+        return renderWidget->widget();
+    return 0;
 }
 
 bool HTMLPlugInElement::isPresentationAttribute(const QualifiedName& name) const
@@ -163,41 +257,44 @@
 
 void HTMLPlugInElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
 {
-    if (name == widthAttr)
+    if (name == widthAttr) {
         addHTMLLengthToStyle(style, CSSPropertyWidth, value);
-    else if (name == heightAttr)
+    } else if (name == heightAttr) {
         addHTMLLengthToStyle(style, CSSPropertyHeight, value);
-    else if (name == vspaceAttr) {
+    } else if (name == vspaceAttr) {
         addHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
         addHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
     } else if (name == hspaceAttr) {
         addHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
         addHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
-    } else if (name == alignAttr)
+    } else if (name == alignAttr) {
         applyAlignmentAttributeToStyle(value, style);
-    else
+    } else {
         HTMLFrameOwnerElement::collectStyleForPresentationAttribute(name, value, style);
+    }
 }
 
 void HTMLPlugInElement::defaultEventHandler(Event* event)
 {
-    // Firefox seems to use a fake event listener to dispatch events to plug-in (tested with mouse events only).
-    // This is observable via different order of events - in Firefox, event listeners specified in HTML attributes fires first, then an event
-    // gets dispatched to plug-in, and only then other event listeners fire. Hopefully, this difference does not matter in practice.
+    // Firefox seems to use a fake event listener to dispatch events to plug-in
+    // (tested with mouse events only). This is observable via different order
+    // of events - in Firefox, event listeners specified in HTML attributes
+    // fires first, then an event gets dispatched to plug-in, and only then
+    // other event listeners fire. Hopefully, this difference does not matter in
+    // practice.
 
-    // FIXME: Mouse down and scroll events are passed down to plug-in via custom code in EventHandler; these code paths should be united.
+    // FIXME: Mouse down and scroll events are passed down to plug-in via custom
+    // code in EventHandler; these code paths should be united.
 
     RenderObject* r = renderer();
-    if (r && r->isEmbeddedObject()) {
+    if (!r || !r->isWidget())
+        return;
+    if (r->isEmbeddedObject()) {
         if (toRenderEmbeddedObject(r)->showsUnavailablePluginIndicator())
             return;
-
         if (displayState() < Playing)
             return;
     }
-
-    if (!r || !r->isWidget())
-        return;
     RefPtr<Widget> widget = toRenderWidget(r)->widget();
     if (!widget)
         return;
@@ -217,12 +314,7 @@
 {
     if (!document().page())
         return false;
-
-    const PluginView* plugin = pluginWidget() && pluginWidget()->isPluginView() ? toPluginView(pluginWidget()) : 0;
-    if (plugin)
-        return plugin->supportsKeyboardFocus();
-
-    return false;
+    return pluginWidget() && pluginWidget()->isPluginView() && toPluginView(pluginWidget())->supportsKeyboardFocus();
 }
 
 bool HTMLPlugInElement::isPluginElement() const
@@ -244,8 +336,169 @@
 {
     ASSERT(document().frame());
     if (!m_NPObject)
-        m_NPObject = document().frame()->script()->createScriptObjectForPluginElement(this);
+        m_NPObject = document().frame()->script().createScriptObjectForPluginElement(this);
     return m_NPObject;
 }
 
+bool HTMLPlugInElement::isImageType()
+{
+    if (m_serviceType.isEmpty() && protocolIs(m_url, "data"))
+        m_serviceType = mimeTypeFromDataURL(m_url);
+
+    if (Frame* frame = document().frame()) {
+        KURL completedURL = document().completeURL(m_url);
+        return frame->loader().client()->objectContentType(completedURL, m_serviceType, shouldPreferPlugInsForImages()) == ObjectContentImage;
+    }
+
+    return Image::supportsType(m_serviceType);
+}
+
+const String HTMLPlugInElement::loadedMimeType() const
+{
+    String mimeType = m_serviceType;
+    if (mimeType.isEmpty())
+        mimeType = mimeTypeFromURL(m_loadedUrl);
+    return mimeType;
+}
+
+RenderEmbeddedObject* HTMLPlugInElement::renderEmbeddedObject() const
+{
+    // HTMLObjectElement and HTMLEmbedElement may return arbitrary renderers
+    // when using fallback content.
+    if (!renderer() || !renderer()->isEmbeddedObject())
+        return 0;
+    return toRenderEmbeddedObject(renderer());
+}
+
+// We don't use m_url, as it may not be the final URL that the object loads,
+// depending on <param> values.
+bool HTMLPlugInElement::allowedToLoadFrameURL(const String& url)
+{
+    KURL completeURL = document().completeURL(url);
+    if (contentFrame() && protocolIsJavaScript(completeURL)
+        && !document().securityOrigin()->canAccess(contentDocument()->securityOrigin()))
+        return false;
+    return document().frame()->isURLAllowed(completeURL);
+}
+
+// We don't use m_url, or m_serviceType as they may not be the final values
+// that <object> uses depending on <param> values.
+bool HTMLPlugInElement::wouldLoadAsNetscapePlugin(const String& url, const String& serviceType)
+{
+    ASSERT(document().frame());
+    KURL completedURL;
+    if (!url.isEmpty())
+        completedURL = document().completeURL(url);
+    return document().frame()->loader().client()->objectContentType(completedURL, serviceType, shouldPreferPlugInsForImages()) == ObjectContentNetscapePlugin;
+}
+
+bool HTMLPlugInElement::requestObject(const String& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues)
+{
+    if (url.isEmpty() && mimeType.isEmpty())
+        return false;
+
+    // FIXME: None of this code should use renderers!
+    RenderEmbeddedObject* renderer = renderEmbeddedObject();
+    ASSERT(renderer);
+    if (!renderer)
+        return false;
+
+    KURL completedURL = document().completeURL(url);
+
+    bool useFallback;
+    if (shouldUsePlugin(completedURL, mimeType, renderer->hasFallbackContent(), useFallback))
+        return loadPlugin(completedURL, mimeType, paramNames, paramValues, useFallback);
+
+    // If the plug-in element already contains a subframe,
+    // loadOrRedirectSubframe will re-use it. Otherwise, it will create a new
+    // frame and set it as the RenderPart's widget, causing what was previously
+    // in the widget to be torn down.
+    return loadOrRedirectSubframe(completedURL, getNameAttribute(), true);
+}
+
+bool HTMLPlugInElement::loadPlugin(const KURL& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback)
+{
+    Frame* frame = document().frame();
+
+    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)
+        return false;
+
+    LOG(Plugins, "%p Plug-in URL: %s", this, m_url.utf8().data());
+    LOG(Plugins, "   Loaded URL: %s", url.string().utf8().data());
+    m_loadedUrl = url;
+
+    IntSize contentSize = roundedIntSize(LayoutSize(renderer->contentWidth(), renderer->contentHeight()));
+    bool loadManually = document().isPluginDocument() && !frame->loader().containsPlugins() && toPluginDocument(document()).shouldLoadPluginManually();
+    RefPtr<Widget> widget = frame->loader().client()->createPlugin(contentSize, this, url, paramNames, paramValues, mimeType, loadManually);
+
+    if (!widget) {
+        if (!renderer->showsUnavailablePluginIndicator())
+            renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginMissing);
+        return false;
+    }
+
+    renderer->setWidget(widget);
+    frame->loader().setContainsPlugins();
+    setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+    return true;
+}
+
+bool HTMLPlugInElement::shouldUsePlugin(const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback)
+{
+    // Allow other plug-ins to win over QuickTime because if the user has
+    // installed a plug-in that can handle TIFF (which QuickTime can also
+    // handle) they probably intended to override QT.
+    if (document().frame()->page() && (mimeType == "image/tiff" || mimeType == "image/tif" || mimeType == "image/x-tiff")) {
+        const PluginData* pluginData = document().frame()->page()->pluginData();
+        String pluginName = pluginData ? pluginData->pluginNameForMimeType(mimeType) : String();
+        if (!pluginName.isEmpty() && !pluginName.contains("QuickTime", false))
+            return true;
+    }
+
+    ObjectContentType objectType = document().frame()->loader().client()->objectContentType(url, mimeType, shouldPreferPlugInsForImages());
+    // If an object's content can't be handled and it has no fallback, let
+    // it be handled as a plugin to show the broken plugin icon.
+    useFallback = objectType == ObjectContentNone && hasFallback;
+    return objectType == ObjectContentNone || objectType == ObjectContentNetscapePlugin || objectType == ObjectContentOtherPlugin;
+
+}
+
+bool HTMLPlugInElement::pluginIsLoadable(const KURL& url, const String& mimeType)
+{
+    Frame* frame = document().frame();
+    Settings* settings = frame->settings();
+    if (!settings)
+        return false;
+
+    if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType) && !settings->isJavaEnabled())
+        return false;
+
+    if (document().isSandboxed(SandboxPlugins))
+        return false;
+
+    if (!document().securityOrigin()->canDisplay(url)) {
+        FrameLoader::reportLocalLoadFailed(frame, url.string());
+        return false;
+    }
+
+    String declaredMimeType = document().isPluginDocument() && document().ownerElement() ?
+        document().ownerElement()->fastGetAttribute(HTMLNames::typeAttr) :
+        fastGetAttribute(HTMLNames::typeAttr);
+    if (!document().contentSecurityPolicy()->allowObjectFromSource(url)
+        || !document().contentSecurityPolicy()->allowPluginType(mimeType, declaredMimeType, url)) {
+        renderEmbeddedObject()->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy);
+        return false;
+    }
+
+    return frame->loader().mixedContentChecker()->canRunInsecureContent(document().securityOrigin(), url);
+}
+
 }
diff --git a/Source/core/html/HTMLPlugInElement.h b/Source/core/html/HTMLPlugInElement.h
index df95283..1863145 100644
--- a/Source/core/html/HTMLPlugInElement.h
+++ b/Source/core/html/HTMLPlugInElement.h
@@ -30,19 +30,90 @@
 
 namespace WebCore {
 
+class HTMLImageLoader;
 class RenderEmbeddedObject;
 class RenderWidget;
 class Widget;
 
+enum PreferPlugInsForImagesOption {
+    ShouldPreferPlugInsForImages,
+    ShouldNotPreferPlugInsForImages
+};
+
+enum PluginCreationOption {
+    CreateAnyWidgetType,
+    CreateOnlyNonNetscapePlugins,
+};
+
 class HTMLPlugInElement : public HTMLFrameOwnerElement {
 public:
     virtual ~HTMLPlugInElement();
 
     void resetInstance();
-
     SharedPersistent<v8::Object>* pluginWrapper();
-
     Widget* pluginWidget() const;
+    NPObject* getNPObject();
+    bool canProcessDrag() const;
+    const String& url() const { return m_url; }
+
+    // Public for FrameView::addWidgetToUpdate()
+    bool needsWidgetUpdate() const { return m_needsWidgetUpdate; }
+    void setNeedsWidgetUpdate(bool needsWidgetUpdate) { m_needsWidgetUpdate = needsWidgetUpdate; }
+    virtual void updateWidget(PluginCreationOption) = 0;
+
+protected:
+    HTMLPlugInElement(const QualifiedName& tagName, Document&, bool createdByParser, PreferPlugInsForImagesOption);
+
+    // Node functions:
+    virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
+    virtual bool dispatchBeforeLoadEvent(const String& sourceURL) OVERRIDE;
+
+    // Element functions:
+    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
+    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
+
+    virtual bool useFallbackContent() const { return false; }
+    // Create or update the RenderWidget and return it, triggering layout if
+    // necessary.
+    virtual RenderWidget* renderWidgetForJSBindings() const;
+
+    bool isImageType();
+    bool shouldPreferPlugInsForImages() const { return m_shouldPreferPlugInsForImages; }
+    RenderEmbeddedObject* renderEmbeddedObject() const;
+    bool allowedToLoadFrameURL(const String& url);
+    bool wouldLoadAsNetscapePlugin(const String& url, const String& serviceType);
+    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);
+
+    String m_serviceType;
+    String m_url;
+    KURL m_loadedUrl;
+    OwnPtr<HTMLImageLoader> m_imageLoader;
+
+private:
+    // EventTarget functions:
+    virtual void removeAllEventListeners() OVERRIDE FINAL;
+
+    // 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;
+
+    // Element functions:
+    virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
+    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;
+
+    // Return any existing RenderWidget without triggering relayout, or 0 if it
+    // doesn't yet exist.
+    virtual RenderWidget* existingRenderWidget() const = 0;
 
     enum DisplayState {
         Restarting,
@@ -50,55 +121,19 @@
         Playing
     };
     DisplayState displayState() const { return m_displayState; }
-    virtual void setDisplayState(DisplayState state) { m_displayState = state; }
-
-    NPObject* getNPObject();
-
-    bool isCapturingMouseEvents() const { return m_isCapturingMouseEvents; }
-    void setIsCapturingMouseEvents(bool capturing) { m_isCapturingMouseEvents = capturing; }
-
-    bool canContainRangeEndPoint() const { return false; }
-
-    bool canProcessDrag() const;
-
-    virtual bool willRespondToMouseClickEvents() OVERRIDE;
-
-    virtual bool isPlugInImageElement() const { return false; }
-
-    virtual void removeAllEventListeners() OVERRIDE FINAL;
-
-protected:
-    HTMLPlugInElement(const QualifiedName& tagName, Document&);
-
-    virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
-    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
-
-    virtual bool useFallbackContent() const { return false; }
-
-    virtual bool dispatchBeforeLoadEvent(const String& sourceURL) OVERRIDE;
-
-    // Create or update the RenderWidget and return it, triggering layout if necessary.
-    virtual RenderWidget* renderWidgetForJSBindings() const;
-
-private:
-    virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
-
-    virtual void defaultEventHandler(Event*);
-
-    // Return any existing RenderWidget without triggering relayout, or 0 if it doesn't yet exist.
-    virtual RenderWidget* existingRenderWidget() const = 0;
-
-    virtual bool supportsFocus() const OVERRIDE { return true; };
-    virtual bool rendererIsFocusable() const OVERRIDE;
-
-    virtual bool isKeyboardFocusable() const OVERRIDE;
-    virtual bool isPluginElement() const;
+    void setDisplayState(DisplayState state) { m_displayState = state; }
+    const String loadedMimeType() const;
+    static void updateWidgetCallback(Node*);
+    void updateWidgetIfNecessary();
+    bool loadPlugin(const KURL&, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback);
+    bool pluginIsLoadable(const KURL&, const String& mimeType);
 
     mutable RefPtr<SharedPersistent<v8::Object> > m_pluginWrapper;
     NPObject* m_NPObject;
     bool m_isCapturingMouseEvents;
     bool m_inBeforeLoadEventHandler;
+    bool m_needsWidgetUpdate;
+    bool m_shouldPreferPlugInsForImages;
     DisplayState m_displayState;
 };
 
diff --git a/Source/core/html/HTMLPlugInImageElement.cpp b/Source/core/html/HTMLPlugInImageElement.cpp
deleted file mode 100644
index a7b5bbd..0000000
--- a/Source/core/html/HTMLPlugInImageElement.cpp
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * Copyright (C) 2008, 2011, 2012 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/html/HTMLPlugInImageElement.h"
-
-#include "core/dom/PostAttachCallbacks.h"
-#include "core/html/HTMLImageLoader.h"
-#include "core/html/PluginDocument.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/frame/ContentSecurityPolicy.h"
-#include "core/frame/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "platform/Logging.h"
-#include "core/platform/MIMETypeFromURL.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/graphics/Image.h"
-#include "core/plugins/PluginData.h"
-#include "core/rendering/RenderEmbeddedObject.h"
-#include "core/rendering/RenderImage.h"
-#include "platform/UserGestureIndicator.h"
-#include "weborigin/SecurityOrigin.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-typedef Vector<RefPtr<HTMLPlugInImageElement> > HTMLPlugInImageElementList;
-
-static const int sizingTinyDimensionThreshold = 40;
-static const int sizingSmallWidthThreshold = 250;
-static const int sizingMediumWidthThreshold = 450;
-static const int sizingMediumHeightThreshold = 300;
-static const float sizingFullPageAreaRatioThreshold = 0.96;
-static const float autostartSoonAfterUserGestureThreshold = 5.0;
-
-HTMLPlugInImageElement::HTMLPlugInImageElement(const QualifiedName& tagName, Document& document, bool createdByParser, PreferPlugInsForImagesOption preferPlugInsForImagesOption)
-    : HTMLPlugInElement(tagName, document)
-    // m_needsWidgetUpdate(!createdByParser) allows HTMLObjectElement to delay
-    // widget updates until after all children are parsed.  For HTMLEmbedElement
-    // this delay is unnecessary, but it is simpler to make both classes share
-    // the same codepath in this class.
-    , m_needsWidgetUpdate(!createdByParser)
-    , m_shouldPreferPlugInsForImages(preferPlugInsForImagesOption == ShouldPreferPlugInsForImages)
-    , m_createdDuringUserGesture(UserGestureIndicator::processingUserGesture())
-{
-    setHasCustomStyleCallbacks();
-}
-
-HTMLPlugInImageElement::~HTMLPlugInImageElement()
-{
-}
-
-void HTMLPlugInImageElement::setDisplayState(DisplayState state)
-{
-    HTMLPlugInElement::setDisplayState(state);
-}
-
-RenderEmbeddedObject* HTMLPlugInImageElement::renderEmbeddedObject() const
-{
-    // HTMLObjectElement and HTMLEmbedElement may return arbitrary renderers
-    // when using fallback content.
-    if (!renderer() || !renderer()->isEmbeddedObject())
-        return 0;
-    return toRenderEmbeddedObject(renderer());
-}
-
-bool HTMLPlugInImageElement::isImageType()
-{
-    if (m_serviceType.isEmpty() && protocolIs(m_url, "data"))
-        m_serviceType = mimeTypeFromDataURL(m_url);
-
-    if (Frame* frame = document().frame()) {
-        KURL completedURL = document().completeURL(m_url);
-        return frame->loader()->client()->objectContentType(completedURL, m_serviceType, shouldPreferPlugInsForImages()) == ObjectContentImage;
-    }
-
-    return Image::supportsType(m_serviceType);
-}
-
-// We don't use m_url, as it may not be the final URL that the object loads,
-// depending on <param> values.
-bool HTMLPlugInImageElement::allowedToLoadFrameURL(const String& url)
-{
-    KURL completeURL = document().completeURL(url);
-
-    if (contentFrame() && protocolIsJavaScript(completeURL)
-        && !document().securityOrigin()->canAccess(contentDocument()->securityOrigin()))
-        return false;
-
-    return document().frame()->isURLAllowed(completeURL);
-}
-
-// We don't use m_url, or m_serviceType as they may not be the final values
-// that <object> uses depending on <param> values.
-bool HTMLPlugInImageElement::wouldLoadAsNetscapePlugin(const String& url, const String& serviceType)
-{
-    ASSERT(document().frame());
-    KURL completedURL;
-    if (!url.isEmpty())
-        completedURL = document().completeURL(url);
-
-    FrameLoader* frameLoader = document().frame()->loader();
-    ASSERT(frameLoader);
-    if (frameLoader->client()->objectContentType(completedURL, serviceType, shouldPreferPlugInsForImages()) == ObjectContentNetscapePlugin)
-        return true;
-    return false;
-}
-
-RenderObject* HTMLPlugInImageElement::createRenderer(RenderStyle* style)
-{
-    // Fallback content breaks the DOM->Renderer class relationship of this
-    // class and all superclasses because createObject won't necessarily
-    // return a RenderEmbeddedObject, RenderPart or even RenderWidget.
-    if (useFallbackContent())
-        return RenderObject::createObject(this, style);
-
-    if (isImageType()) {
-        RenderImage* image = new RenderImage(this);
-        image->setImageResource(RenderImageResource::create());
-        return image;
-    }
-
-    return new RenderEmbeddedObject(this);
-}
-
-void HTMLPlugInImageElement::willRecalcStyle(StyleRecalcChange)
-{
-    // FIXME: Why is this necessary?  Manual re-attach is almost always wrong.
-    if (!useFallbackContent() && needsWidgetUpdate() && renderer() && !isImageType())
-        reattach();
-}
-
-void HTMLPlugInImageElement::attach(const AttachContext& context)
-{
-    bool isImage = isImageType();
-
-    if (!isImage)
-        PostAttachCallbacks::queueCallback(HTMLPlugInImageElement::updateWidgetCallback, this);
-
-    HTMLPlugInElement::attach(context);
-
-    if (isImage && renderer() && !useFallbackContent()) {
-        if (!m_imageLoader)
-            m_imageLoader = adoptPtr(new HTMLImageLoader(this));
-        m_imageLoader->updateFromElement();
-    }
-}
-
-void HTMLPlugInImageElement::detach(const AttachContext& context)
-{
-    // FIXME: Because of the insanity that is HTMLPlugInImageElement::recalcStyle,
-    // we can end up detaching during an attach() call, before we even have a
-    // renderer.  In that case, don't mark the widget for update.
-    if (confusingAndOftenMisusedAttached() && renderer() && !useFallbackContent())
-        // Update the widget the next time we attach (detaching destroys the plugin).
-        setNeedsWidgetUpdate(true);
-    HTMLPlugInElement::detach(context);
-}
-
-void HTMLPlugInImageElement::updateWidgetIfNecessary()
-{
-    document().updateStyleIfNeeded();
-
-    if (!needsWidgetUpdate() || useFallbackContent() || isImageType())
-        return;
-
-    if (!renderEmbeddedObject() || renderEmbeddedObject()->showsUnavailablePluginIndicator())
-        return;
-
-    updateWidget(CreateOnlyNonNetscapePlugins);
-}
-
-void HTMLPlugInImageElement::finishParsingChildren()
-{
-    HTMLPlugInElement::finishParsingChildren();
-    if (useFallbackContent())
-        return;
-
-    setNeedsWidgetUpdate(true);
-    if (inDocument())
-        setNeedsStyleRecalc();
-}
-
-void HTMLPlugInImageElement::didMoveToNewDocument(Document& oldDocument)
-{
-    if (m_imageLoader)
-        m_imageLoader->elementDidMoveToNewDocument();
-    HTMLPlugInElement::didMoveToNewDocument(oldDocument);
-}
-
-void HTMLPlugInImageElement::updateWidgetCallback(Node* n)
-{
-    toHTMLPlugInImageElement(n)->updateWidgetIfNecessary();
-}
-
-bool HTMLPlugInImageElement::requestObject(const String& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues)
-{
-    if (url.isEmpty() && mimeType.isEmpty())
-        return false;
-
-    // FIXME: None of this code should use renderers!
-    RenderEmbeddedObject* renderer = renderEmbeddedObject();
-    ASSERT(renderer);
-    if (!renderer)
-        return false;
-
-    KURL completedURL = document().completeURL(url);
-
-    bool useFallback;
-    if (shouldUsePlugin(completedURL, mimeType, renderer->hasFallbackContent(), useFallback)) {
-        bool success = loadPlugin(completedURL, mimeType, paramNames, paramValues, useFallback);
-        return success;
-    }
-
-    // If the plug-in element already contains a subframe, loadOrRedirectSubframe will re-use it. Otherwise,
-    // it will create a new frame and set it as the RenderPart's widget, causing what was previously
-    // in the widget to be torn down.
-    return loadOrRedirectSubframe(completedURL, getNameAttribute(), true);
-}
-
-bool HTMLPlugInImageElement::loadPlugin(const KURL& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback)
-{
-    Frame* frame = document().frame();
-
-    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)
-        return false;
-
-    LOG(Plugins, "%p Plug-in URL: %s", this, m_url.utf8().data());
-    LOG(Plugins, "   Loaded URL: %s", url.string().utf8().data());
-    m_loadedUrl = url;
-
-    IntSize contentSize = roundedIntSize(LayoutSize(renderer->contentWidth(), renderer->contentHeight()));
-    bool loadManually = document().isPluginDocument() && !frame->loader()->containsPlugins() && toPluginDocument(document()).shouldLoadPluginManually();
-    RefPtr<Widget> widget = frame->loader()->client()->createPlugin(contentSize, this, url, paramNames, paramValues, mimeType, loadManually);
-
-    if (!widget) {
-        if (!renderer->showsUnavailablePluginIndicator())
-            renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginMissing);
-        return false;
-    }
-
-    renderer->setWidget(widget);
-    frame->loader()->setContainsPlugins();
-    setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
-    return true;
-}
-
-bool HTMLPlugInImageElement::shouldUsePlugin(const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback)
-{
-    // Allow other plug-ins to win over QuickTime because if the user has installed a plug-in that
-    // can handle TIFF (which QuickTime can also handle) they probably intended to override QT.
-    if (document().frame()->page() && (mimeType == "image/tiff" || mimeType == "image/tif" || mimeType == "image/x-tiff")) {
-        const PluginData* pluginData = document().frame()->page()->pluginData();
-        String pluginName = pluginData ? pluginData->pluginNameForMimeType(mimeType) : String();
-        if (!pluginName.isEmpty() && !pluginName.contains("QuickTime", false))
-            return true;
-    }
-
-    ObjectContentType objectType = document().frame()->loader()->client()->objectContentType(url, mimeType, shouldPreferPlugInsForImages());
-    // If an object's content can't be handled and it has no fallback, let
-    // it be handled as a plugin to show the broken plugin icon.
-    useFallback = objectType == ObjectContentNone && hasFallback;
-    return objectType == ObjectContentNone || objectType == ObjectContentNetscapePlugin || objectType == ObjectContentOtherPlugin;
-
-}
-
-bool HTMLPlugInImageElement::pluginIsLoadable(const KURL& url, const String& mimeType)
-{
-    Frame* frame = document().frame();
-    Settings* settings = frame->settings();
-    if (!settings)
-        return false;
-
-    if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType)) {
-        if (!settings->isJavaEnabled())
-            return false;
-    }
-
-    if (document().isSandboxed(SandboxPlugins))
-        return false;
-
-    if (!document().securityOrigin()->canDisplay(url)) {
-        FrameLoader::reportLocalLoadFailed(frame, url.string());
-        return false;
-    }
-
-    String declaredMimeType = document().isPluginDocument() && document().ownerElement() ?
-        document().ownerElement()->fastGetAttribute(HTMLNames::typeAttr) :
-        fastGetAttribute(HTMLNames::typeAttr);
-    if (!document().contentSecurityPolicy()->allowObjectFromSource(url)
-        || !document().contentSecurityPolicy()->allowPluginType(mimeType, declaredMimeType, url)) {
-        renderEmbeddedObject()->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy);
-        return false;
-    }
-
-    if (frame->loader() && !frame->loader()->mixedContentChecker()->canRunInsecureContent(document().securityOrigin(), url))
-        return false;
-    return true;
-}
-
-} // namespace WebCore
diff --git a/Source/core/html/HTMLPlugInImageElement.h b/Source/core/html/HTMLPlugInImageElement.h
deleted file mode 100644
index 7f161fd..0000000
--- a/Source/core/html/HTMLPlugInImageElement.h
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (C) 2008, 2009, 2011, 2012 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 HTMLPlugInImageElement_h
-#define HTMLPlugInImageElement_h
-
-#include "core/html/HTMLPlugInElement.h"
-
-#include "core/platform/MIMETypeFromURL.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-class HTMLImageLoader;
-class FrameLoader;
-class Image;
-class MouseEvent;
-class Widget;
-
-enum PluginCreationOption {
-    CreateAnyWidgetType,
-    CreateOnlyNonNetscapePlugins,
-};
-
-enum PreferPlugInsForImagesOption {
-    ShouldPreferPlugInsForImages,
-    ShouldNotPreferPlugInsForImages
-};
-
-// Base class for HTMLObjectElement and HTMLEmbedElement
-class HTMLPlugInImageElement : public HTMLPlugInElement {
-public:
-    virtual ~HTMLPlugInImageElement();
-
-    RenderEmbeddedObject* renderEmbeddedObject() const;
-
-    virtual void setDisplayState(DisplayState) OVERRIDE;
-
-    virtual void updateWidget(PluginCreationOption) = 0;
-
-    const String& serviceType() const { return m_serviceType; }
-    const String& url() const { return m_url; }
-    const KURL& loadedUrl() const { return m_loadedUrl; }
-
-    const String loadedMimeType() const
-    {
-        String mimeType = serviceType();
-        if (mimeType.isEmpty())
-            mimeType = mimeTypeFromURL(m_loadedUrl);
-        return mimeType;
-    }
-
-    bool shouldPreferPlugInsForImages() const { return m_shouldPreferPlugInsForImages; }
-
-    // Public for FrameView::addWidgetToUpdate()
-    bool needsWidgetUpdate() const { return m_needsWidgetUpdate; }
-    void setNeedsWidgetUpdate(bool needsWidgetUpdate) { m_needsWidgetUpdate = needsWidgetUpdate; }
-
-protected:
-    HTMLPlugInImageElement(const QualifiedName& tagName, Document&, bool createdByParser, PreferPlugInsForImagesOption);
-
-    bool isImageType();
-
-    OwnPtr<HTMLImageLoader> m_imageLoader;
-    String m_serviceType;
-    String m_url;
-    KURL m_loadedUrl;
-
-    static void updateWidgetCallback(Node*);
-    virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-
-    bool allowedToLoadFrameURL(const String& url);
-    bool wouldLoadAsNetscapePlugin(const String& url, const String& serviceType);
-
-    virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
-
-    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);
-
-private:
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE FINAL;
-
-    virtual void finishParsingChildren();
-
-    void updateWidgetIfNecessary();
-
-    void swapRendererTimerFired(Timer<HTMLPlugInImageElement>*);
-
-    void restartSimilarPlugIns();
-
-    bool loadPlugin(const KURL&, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback);
-    bool pluginIsLoadable(const KURL&, const String& mimeType);
-
-    virtual bool isPlugInImageElement() const OVERRIDE { return true; }
-
-    bool m_needsWidgetUpdate;
-    bool m_shouldPreferPlugInsForImages;
-    bool m_createdDuringUserGesture;
-};
-
-inline HTMLPlugInImageElement* toHTMLPlugInImageElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isPluginElement());
-    HTMLPlugInElement* plugInElement = static_cast<HTMLPlugInElement*>(node);
-    ASSERT_WITH_SECURITY_IMPLICATION(plugInElement->isPlugInImageElement());
-    return static_cast<HTMLPlugInImageElement*>(plugInElement);
-}
-
-inline const HTMLPlugInImageElement* toHTMLPlugInImageElement(const Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isPluginElement());
-    const HTMLPlugInElement* plugInElement = static_cast<const HTMLPlugInElement*>(node);
-    ASSERT_WITH_SECURITY_IMPLICATION(plugInElement->isPlugInImageElement());
-    return static_cast<const HTMLPlugInImageElement*>(plugInElement);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toHTMLPlugInImageElement(const HTMLPlugInImageElement*);
-
-} // namespace WebCore
-
-#endif // HTMLPlugInImageElement_h
diff --git a/Source/core/html/HTMLProgressElement.h b/Source/core/html/HTMLProgressElement.h
index e9f624e..abb82aa 100644
--- a/Source/core/html/HTMLProgressElement.h
+++ b/Source/core/html/HTMLProgressElement.h
@@ -74,11 +74,7 @@
     return node->hasTagName(HTMLNames::progressTag);
 }
 
-inline HTMLProgressElement* toHTMLProgressElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLProgressElement(node));
-    return static_cast<HTMLProgressElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLProgressElement, hasTagName(HTMLNames::progressTag));
 
 } // namespace
 
diff --git a/Source/core/html/HTMLSelectElement.cpp b/Source/core/html/HTMLSelectElement.cpp
index 6842f31..327da68 100644
--- a/Source/core/html/HTMLSelectElement.cpp
+++ b/Source/core/html/HTMLSelectElement.cpp
@@ -304,8 +304,8 @@
 
         m_size = size;
         setNeedsValidityCheck();
-        if (m_size != oldSize && confusingAndOftenMisusedAttached()) {
-            lazyReattach();
+        if (m_size != oldSize && inActiveDocument()) {
+            lazyReattachIfAttached();
             setRecalcListItems();
         }
     } else if (name == multipleAttr)
@@ -447,7 +447,7 @@
         do {
             RefPtr<Element> option = document().createElement(optionTag, false);
             ASSERT(option);
-            add(toHTMLElement(option.get()), 0, es);
+            add(toHTMLElement(option), 0, es);
             if (es.hadException())
                 break;
         } while (++diff);
@@ -707,6 +707,9 @@
 
 void HTMLSelectElement::setRecalcListItems()
 {
+    // FIXME: This function does a bunch of confusing things depending on if it
+    // is in the document or not.
+
     m_shouldRecalcListItems = true;
     // Manual selection anchor is reset when manipulating the select programmatically.
     m_activeSelectionAnchorIndex = -1;
@@ -1298,7 +1301,7 @@
 #endif
             }
             if (Frame* frame = document().frame())
-                frame->eventHandler()->setMouseDownMayStartAutoscroll();
+                frame->eventHandler().setMouseDownMayStartAutoscroll();
 
             event->setDefaultHandled();
         }
diff --git a/Source/core/html/HTMLSourceElement.idl b/Source/core/html/HTMLSourceElement.idl
index e64d1da..52203bc 100644
--- a/Source/core/html/HTMLSourceElement.idl
+++ b/Source/core/html/HTMLSourceElement.idl
@@ -26,7 +26,7 @@
 [
     RuntimeEnabled=Media
 ] interface HTMLSourceElement : HTMLElement {
-[Reflect, TreatNullAs=NullString, URL] attribute DOMString src;
+    [Reflect, URL] attribute DOMString src;
     attribute DOMString type;
     attribute DOMString media;
 };
diff --git a/Source/core/html/HTMLTableCellElement.h b/Source/core/html/HTMLTableCellElement.h
index 413ccd9..78305a1 100644
--- a/Source/core/html/HTMLTableCellElement.h
+++ b/Source/core/html/HTMLTableCellElement.h
@@ -63,20 +63,12 @@
     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
 };
 
-inline HTMLTableCellElement* toHTMLTableCellElement(Node* node)
+inline bool isHTMLTableCellElement(const Node& node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::tdTag) || node->hasTagName(HTMLNames::thTag));
-    return static_cast<HTMLTableCellElement*>(node);
+    return node.hasTagName(HTMLNames::tdTag) || node.hasTagName(HTMLNames::thTag);
 }
 
-inline const HTMLTableCellElement* toHTMLTableCellElement(const Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::tdTag) || node->hasTagName(HTMLNames::thTag));
-    return static_cast<const HTMLTableCellElement*>(node);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toHTMLTableCellElement(const HTMLTableCellElement*);
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLTableCellElement);
 
 } // namespace
 
diff --git a/Source/core/html/HTMLTableColElement.h b/Source/core/html/HTMLTableColElement.h
index 635c661..4fb107c 100644
--- a/Source/core/html/HTMLTableColElement.h
+++ b/Source/core/html/HTMLTableColElement.h
@@ -50,12 +50,13 @@
     int m_span;
 };
 
-inline HTMLTableColElement* toHTMLTableColElement(Node* node)
+inline bool isHTMLTableColElement(const Node& node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::colTag) || node->hasTagName(HTMLNames::colgroupTag));
-    return static_cast<HTMLTableColElement*>(node);
+    return node.hasTagName(HTMLNames::colTag) || node.hasTagName(HTMLNames::colgroupTag);
 }
 
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLTableColElement);
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/html/HTMLTableElement.h b/Source/core/html/HTMLTableElement.h
index 4ec1674..c1b4918 100644
--- a/Source/core/html/HTMLTableElement.h
+++ b/Source/core/html/HTMLTableElement.h
@@ -111,11 +111,7 @@
     return element->hasTagName(HTMLNames::tableTag);
 }
 
-inline HTMLTableElement* toHTMLTableElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTableElement(node));
-    return static_cast<HTMLTableElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTableElement, hasTagName(HTMLNames::tableTag));
 
 } //namespace
 
diff --git a/Source/core/html/HTMLTableRowElement.h b/Source/core/html/HTMLTableRowElement.h
index 0c1bff8..9483642 100644
--- a/Source/core/html/HTMLTableRowElement.h
+++ b/Source/core/html/HTMLTableRowElement.h
@@ -58,11 +58,7 @@
     return node->hasTagName(HTMLNames::trTag);
 }
 
-inline HTMLTableRowElement* toHTMLTableRowElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTableRowElement(node));
-    return static_cast<HTMLTableRowElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTableRowElement, hasTagName(HTMLNames::trTag));
 
 } // namespace
 
diff --git a/Source/core/html/HTMLTableSectionElement.h b/Source/core/html/HTMLTableSectionElement.h
index f2d271b..e309697 100644
--- a/Source/core/html/HTMLTableSectionElement.h
+++ b/Source/core/html/HTMLTableSectionElement.h
@@ -61,12 +61,13 @@
     virtual const StylePropertySet* additionalPresentationAttributeStyle() OVERRIDE;
 };
 
-inline HTMLTableSectionElement* toHTMLTableSectionElement(Node* node)
+inline bool isHTMLTableSectionElement(const Node& node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::tbodyTag) || node->hasTagName(HTMLNames::tfootTag) || node->hasTagName(HTMLNames::theadTag));
-    return static_cast<HTMLTableSectionElement*>(node);
+    return node.hasTagName(HTMLNames::tbodyTag) || node.hasTagName(HTMLNames::tfootTag) || node.hasTagName(HTMLNames::theadTag);
 }
 
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLTableSectionElement);
+
 } //namespace
 
 #endif
diff --git a/Source/core/html/HTMLTemplateElement.cpp b/Source/core/html/HTMLTemplateElement.cpp
index 46e26e8..f2793ec 100644
--- a/Source/core/html/HTMLTemplateElement.cpp
+++ b/Source/core/html/HTMLTemplateElement.cpp
@@ -80,7 +80,7 @@
     HTMLElement::didMoveToNewDocument(oldDocument);
     if (!m_content)
         return;
-    document().ensureTemplateDocument().adoptIfNeeded(m_content.get());
+    document().ensureTemplateDocument().adoptIfNeeded(*m_content);
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLTextAreaElement.cpp b/Source/core/html/HTMLTextAreaElement.cpp
index d9d52ff..51cd2be 100644
--- a/Source/core/html/HTMLTextAreaElement.cpp
+++ b/Source/core/html/HTMLTextAreaElement.cpp
@@ -319,13 +319,6 @@
     return proposedValue.left(maxLength);
 }
 
-HTMLElement* HTMLTextAreaElement::innerTextElement() const
-{
-    Node* node = userAgentShadowRoot()->firstChild();
-    ASSERT(!node || node->hasTagName(divTag));
-    return toHTMLElement(node);
-}
-
 void HTMLTextAreaElement::rendererWillBeDestroyed()
 {
     updateValue();
diff --git a/Source/core/html/HTMLTextAreaElement.h b/Source/core/html/HTMLTextAreaElement.h
index ecbdf1e..1b8dd6b 100644
--- a/Source/core/html/HTMLTextAreaElement.h
+++ b/Source/core/html/HTMLTextAreaElement.h
@@ -54,8 +54,6 @@
     virtual bool tooLong() const OVERRIDE;
     bool isValidValue(const String&) const;
 
-    virtual HTMLElement* innerTextElement() const;
-
     void rendererWillBeDestroyed();
 
     void setCols(int);
@@ -139,11 +137,7 @@
     return element->hasTagName(HTMLNames::textareaTag);
 }
 
-inline HTMLTextAreaElement* toHTMLTextAreaElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTextAreaElement(node));
-    return static_cast<HTMLTextAreaElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTextAreaElement, hasTagName(HTMLNames::textareaTag));
 
 } //namespace
 
diff --git a/Source/core/html/HTMLTextFormControlElement.cpp b/Source/core/html/HTMLTextFormControlElement.cpp
index e8d07be..24859e6 100644
--- a/Source/core/html/HTMLTextFormControlElement.cpp
+++ b/Source/core/html/HTMLTextFormControlElement.cpp
@@ -651,4 +651,9 @@
     return "ltr";
 }
 
+HTMLElement* HTMLTextFormControlElement::innerTextElement() const
+{
+    return toHTMLElement(userAgentShadowRoot()->getElementById(ShadowElementNames::innerEditor()));
+}
+
 } // namespace Webcore
diff --git a/Source/core/html/HTMLTextFormControlElement.h b/Source/core/html/HTMLTextFormControlElement.h
index 66562b6..2c7a9bf 100644
--- a/Source/core/html/HTMLTextFormControlElement.h
+++ b/Source/core/html/HTMLTextFormControlElement.h
@@ -77,7 +77,7 @@
     virtual int maxLength() const = 0;
     virtual String value() const = 0;
 
-    virtual HTMLElement* innerTextElement() const = 0;
+    HTMLElement* innerTextElement() const;
 
     void selectionChanged(bool userTriggered);
     bool lastChangeWasUserEdit() const;
@@ -142,12 +142,13 @@
     return node->isElementNode() && toElement(node)->isTextFormControl();
 }
 
-inline HTMLTextFormControlElement* toHTMLTextFormControlElement(Node* node)
+inline bool isHTMLTextFormControlElement(const Node& node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTextFormControlElement(node));
-    return static_cast<HTMLTextFormControlElement*>(node);
+    return node.isElementNode() && toElement(node).isTextFormControl();
 }
 
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLTextFormControlElement);
+
 HTMLTextFormControlElement* enclosingTextFormControl(const Position&);
 
 } // namespace
diff --git a/Source/core/html/HTMLTitleElement.h b/Source/core/html/HTMLTitleElement.h
index 580a291..5eab749 100644
--- a/Source/core/html/HTMLTitleElement.h
+++ b/Source/core/html/HTMLTitleElement.h
@@ -51,11 +51,7 @@
     return element->hasTagName(HTMLNames::titleTag);
 }
 
-inline HTMLTitleElement* toHTMLTitleElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTitleElement(node));
-    return static_cast<HTMLTitleElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTitleElement, hasTagName(HTMLNames::titleTag));
 
 } //namespace
 
diff --git a/Source/core/html/HTMLTrackElement.cpp b/Source/core/html/HTMLTrackElement.cpp
index 02c8751..4214e36 100644
--- a/Source/core/html/HTMLTrackElement.cpp
+++ b/Source/core/html/HTMLTrackElement.cpp
@@ -116,16 +116,6 @@
     HTMLElement::parseAttribute(name, value);
 }
 
-KURL HTMLTrackElement::src() const
-{
-    return document().completeURL(getAttribute(srcAttr));
-}
-
-void HTMLTrackElement::setSrc(const String& url)
-{
-    setAttribute(srcAttr, url);
-}
-
 String HTMLTrackElement::kind()
 {
     return track()->kind();
diff --git a/Source/core/html/HTMLTrackElement.h b/Source/core/html/HTMLTrackElement.h
index 3efb317..f6676bd 100644
--- a/Source/core/html/HTMLTrackElement.h
+++ b/Source/core/html/HTMLTrackElement.h
@@ -38,9 +38,6 @@
 public:
     static PassRefPtr<HTMLTrackElement> create(const QualifiedName&, Document&);
 
-    KURL src() const;
-    void setSrc(const String&);
-
     String kind();
     void setKind(const String&);
 
diff --git a/Source/core/html/HTMLTrackElement.idl b/Source/core/html/HTMLTrackElement.idl
index 6a0b1c7..d15c8c4 100644
--- a/Source/core/html/HTMLTrackElement.idl
+++ b/Source/core/html/HTMLTrackElement.idl
@@ -27,7 +27,7 @@
     RuntimeEnabled=VideoTrack
 ] interface HTMLTrackElement : HTMLElement {
     attribute DOMString kind;
-    [Reflect, TreatNullAs=NullString, URL] attribute DOMString src;
+    [Reflect, URL] attribute DOMString src;
     attribute DOMString srclang;
     attribute DOMString label;
     [Reflect] attribute boolean default;
diff --git a/Source/core/html/HTMLVideoElement.cpp b/Source/core/html/HTMLVideoElement.cpp
index 5bea976..0c1c5b3 100644
--- a/Source/core/html/HTMLVideoElement.cpp
+++ b/Source/core/html/HTMLVideoElement.cpp
@@ -143,20 +143,6 @@
     return player()->naturalSize().height();
 }
 
-unsigned HTMLVideoElement::width() const
-{
-    bool ok;
-    unsigned w = getAttribute(widthAttr).string().toUInt(&ok);
-    return ok ? w : 0;
-}
-
-unsigned HTMLVideoElement::height() const
-{
-    bool ok;
-    unsigned h = getAttribute(heightAttr).string().toUInt(&ok);
-    return ok ? h : 0;
-}
-
 bool HTMLVideoElement::isURLAttribute(const Attribute& attribute) const
 {
     return attribute.name() == posterAttr || HTMLMediaElement::isURLAttribute(attribute);
diff --git a/Source/core/html/HTMLVideoElement.h b/Source/core/html/HTMLVideoElement.h
index f839152..64da978 100644
--- a/Source/core/html/HTMLVideoElement.h
+++ b/Source/core/html/HTMLVideoElement.h
@@ -38,9 +38,6 @@
     static PassRefPtr<HTMLVideoElement> create(Document& document) { return create(HTMLNames::videoTag, document, false); }
     static PassRefPtr<HTMLVideoElement> create(const QualifiedName&, Document&, bool);
 
-    unsigned width() const;
-    unsigned height() const;
-
     unsigned videoWidth() const;
     unsigned videoHeight() const;
 
@@ -100,11 +97,7 @@
     return element->hasTagName(HTMLNames::videoTag);
 }
 
-inline HTMLVideoElement* toHTMLVideoElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLVideoElement(node));
-    return static_cast<HTMLVideoElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLVideoElement, hasTagName(HTMLNames::videoTag));
 
 } //namespace
 
diff --git a/Source/core/html/HTMLVideoElement.idl b/Source/core/html/HTMLVideoElement.idl
index de0ba9c..3032eae 100644
--- a/Source/core/html/HTMLVideoElement.idl
+++ b/Source/core/html/HTMLVideoElement.idl
@@ -30,7 +30,7 @@
     [Reflect] attribute unsigned long height;
     readonly attribute unsigned long videoWidth;
     readonly attribute unsigned long videoHeight;
-    [Reflect, TreatNullAs=NullString, URL] attribute DOMString poster;
+    [Reflect, URL] attribute DOMString poster;
 
     [MeasureAs=PrefixedVideoSupportsFullscreen] readonly attribute boolean webkitSupportsFullscreen;
     [MeasureAs=PrefixedVideoDisplayingFullscreen] readonly attribute boolean webkitDisplayingFullscreen;
diff --git a/Source/core/html/ImageDocument.cpp b/Source/core/html/ImageDocument.cpp
index 326fdd2..31c91ee 100644
--- a/Source/core/html/ImageDocument.cpp
+++ b/Source/core/html/ImageDocument.cpp
@@ -127,7 +127,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->areImagesEnabled(), document()->url()))
         return 0;
 
     document()->cachedImage()->appendData(data, length);
@@ -140,7 +140,7 @@
     if (!isStopped() && document()->imageElement()) {
         ImageResource* cachedImage = document()->cachedImage();
         cachedImage->finish();
-        cachedImage->setResponse(document()->frame()->loader()->documentLoader()->response());
+        cachedImage->setResponse(document()->frame()->loader().documentLoader()->response());
 
         // Report the natural image size in the page title, regardless of zoom level.
         // At a zoom level of 1 the image is guaranteed to have an integer size.
@@ -184,8 +184,8 @@
     appendChild(rootElement);
     rootElement->insertedByParser();
 
-    if (frame() && frame()->loader())
-        frame()->loader()->dispatchDocumentElementAvailable();
+    if (frame())
+        frame()->loader().dispatchDocumentElementAvailable();
 
     RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(*this);
     RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(*this);
diff --git a/Source/core/html/LabelableElement.cpp b/Source/core/html/LabelableElement.cpp
index 02e8a98..ad30251 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().addCacheWithAtomicName<LabelsNodeList>(this, LabelsNodeListType, starAtom);
 }
 
 } // namespace Webcore
diff --git a/Source/core/html/MediaDocument.cpp b/Source/core/html/MediaDocument.cpp
index 8468527..14d8d99 100644
--- a/Source/core/html/MediaDocument.cpp
+++ b/Source/core/html/MediaDocument.cpp
@@ -78,7 +78,7 @@
     document()->appendChild(rootElement);
 
     if (document()->frame())
-        document()->frame()->loader()->dispatchDocumentElementAvailable();
+        document()->frame()->loader().dispatchDocumentElementAvailable();
 
     RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(*document());
     RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(*document());
diff --git a/Source/core/html/MediaError.idl b/Source/core/html/MediaError.idl
index 0b6d3a0..4cf13ed 100644
--- a/Source/core/html/MediaError.idl
+++ b/Source/core/html/MediaError.idl
@@ -26,10 +26,10 @@
 [
     RuntimeEnabled=Media
 ] interface MediaError {
-      const unsigned short MEDIA_ERR_ABORTED = 1;
-      const unsigned short MEDIA_ERR_NETWORK = 2;
-      const unsigned short MEDIA_ERR_DECODE = 3;
-      const unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
-      const unsigned short MEDIA_ERR_ENCRYPTED = 5;
-      readonly attribute unsigned short code;
+    const unsigned short MEDIA_ERR_ABORTED = 1;
+    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;
+    readonly attribute unsigned short code;
 };
diff --git a/Source/core/html/PluginDocument.cpp b/Source/core/html/PluginDocument.cpp
index 04511b5..e36e8d8 100644
--- a/Source/core/html/PluginDocument.cpp
+++ b/Source/core/html/PluginDocument.cpp
@@ -81,13 +81,13 @@
         return;
 
     // FIXME: Why does this check settings?
-    if (!frame->settings() || !frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
+    if (!frame->settings() || !frame->loader().allowPlugins(NotAboutToInstantiatePlugin))
         return;
 
     RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(*document());
     rootElement->insertedByParser();
     document()->appendChild(rootElement);
-    frame->loader()->dispatchDocumentElementAvailable();
+    frame->loader().dispatchDocumentElementAvailable();
 
     RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(*document());
     body->setAttribute(marginwidthAttr, "0");
@@ -191,7 +191,7 @@
     if (!shouldLoadPluginManually())
         return;
 
-    DocumentLoader* documentLoader = frame()->loader()->activeDocumentLoader();
+    DocumentLoader* documentLoader = frame()->loader().activeDocumentLoader();
     documentLoader->cancelMainResourceLoad(ResourceError::cancelledError(documentLoader->request().url()));
     setShouldLoadPluginManually(false);
 }
diff --git a/Source/core/html/canvas/ANGLEInstancedArrays.h b/Source/core/html/canvas/ANGLEInstancedArrays.h
index b7e11a5..0b9f531 100644
--- a/Source/core/html/canvas/ANGLEInstancedArrays.h
+++ b/Source/core/html/canvas/ANGLEInstancedArrays.h
@@ -32,7 +32,7 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLExtension.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index 930e52d..065f8ea 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -56,13 +56,13 @@
 #include "core/html/canvas/CanvasStyle.h"
 #include "core/html/canvas/DOMPath.h"
 #include "core/frame/ImageBitmap.h"
-#include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderTheme.h"
 #include "platform/geometry/FloatQuad.h"
+#include "platform/graphics/DrawLooper.h"
 #include "platform/graphics/TextRun.h"
 #include "platform/transforms/AffineTransform.h"
 #include "weborigin/SecurityOrigin.h"
@@ -77,17 +77,8 @@
 namespace WebCore {
 
 static const int defaultFontSize = 10;
-static const char* const defaultFontFamily = "sans-serif";
-static const char* const defaultFont = "10px sans-serif";
-
-static bool isOriginClean(ImageResource* cachedImage, SecurityOrigin* securityOrigin)
-{
-    if (!cachedImage->image()->currentFrameHasSingleSecurityOrigin())
-        return false;
-    if (cachedImage->passesAccessControlCheck(securityOrigin))
-        return true;
-    return !securityOrigin->taintsCanvas(cachedImage->response().url());
-}
+static const char defaultFontFamily[] = "sans-serif";
+static const char defaultFont[] = "10px sans-serif";
 
 CanvasRenderingContext2D::CanvasRenderingContext2D(HTMLCanvasElement* canvas, const Canvas2DContextAttributes* attrs, bool usesCSSCompatibilityParseMode)
     : CanvasRenderingContext(canvas)
@@ -1757,7 +1748,7 @@
     if (!image->renderer() && imageForRendering->usesContainerSize())
         imageForRendering->setContainerSize(imageForRendering->size());
 
-    bool originClean = isOriginClean(cachedImage, canvas()->securityOrigin());
+    bool originClean = cachedImage->isAccessAllowed(canvas()->securityOrigin());
     return CanvasPattern::create(imageForRendering, repeatX, repeatY, originClean);
 }
 
@@ -2055,7 +2046,8 @@
 
     if (!parsedStyle) {
         parsedStyle = MutableStylePropertySet::create();
-        CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, newFont, true, strictToCSSParserMode(!m_usesCSSCompatibilityParseMode), 0);
+        CSSParserMode mode = m_usesCSSCompatibilityParseMode ? HTMLQuirksMode : HTMLStandardMode;
+        CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, newFont, true, mode, 0);
         m_fetchedFonts.add(newFont, parsedStyle);
     }
     if (parsedStyle->isEmpty())
@@ -2169,6 +2161,7 @@
 {
     FontCachePurgePreventer fontCachePurgePreventer;
     RefPtr<TextMetrics> metrics = TextMetrics::create();
+    canvas()->document().updateStyleIfNeeded();
     metrics->setWidth(accessFont().width(TextRun(text)));
     return metrics.release();
 }
@@ -2185,6 +2178,11 @@
 
 void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, float y, bool fill, float maxWidth, bool useMaxWidth)
 {
+    // accessFont needs the style to be up to date, but updating style can cause script to run,
+    // (e.g. due to autofocus) which can free the GraphicsContext, so update style before grabbing
+    // the GraphicsContext.
+    canvas()->document().updateStyleIfNeeded();
+
     GraphicsContext* c = drawingContext();
     if (!c)
         return;
@@ -2305,8 +2303,8 @@
 
 const Font& CanvasRenderingContext2D::accessFont()
 {
-    canvas()->document().updateStyleIfNeeded();
-
+    // This needs style to be up to date, but can't assert so because drawTextInternal
+    // can invalidate style before this is called (e.g. drawingContext invalidates style).
     if (!state().m_realizedFont)
         setFont(state().m_unparsedFont);
     return state().m_font;
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.h b/Source/core/html/canvas/CanvasRenderingContext2D.h
index 0897424..31f474e 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.h
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.h
@@ -29,13 +29,13 @@
 #include "core/html/canvas/Canvas2DContextAttributes.h"
 #include "core/html/canvas/CanvasPathMethods.h"
 #include "core/html/canvas/CanvasRenderingContext.h"
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/platform/graphics/Path.h"
 #include "core/svg/SVGMatrix.h"
 #include "platform/geometry/FloatSize.h"
+#include "platform/graphics/Color.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "platform/transforms/AffineTransform.h"
 #include "wtf/HashMap.h"
 #include "wtf/Vector.h"
diff --git a/Source/core/html/canvas/CanvasStyle.h b/Source/core/html/canvas/CanvasStyle.h
index 0dbaf1b..526ab71 100644
--- a/Source/core/html/canvas/CanvasStyle.h
+++ b/Source/core/html/canvas/CanvasStyle.h
@@ -27,7 +27,7 @@
 #ifndef CanvasStyle_h
 #define CanvasStyle_h
 
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/Assertions.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/html/canvas/OESVertexArrayObject.h b/Source/core/html/canvas/OESVertexArrayObject.h
index 1ac1725..2fd0735 100644
--- a/Source/core/html/canvas/OESVertexArrayObject.h
+++ b/Source/core/html/canvas/OESVertexArrayObject.h
@@ -28,7 +28,7 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLExtension.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/html/canvas/WebGLContextGroup.h b/Source/core/html/canvas/WebGLContextGroup.h
index 3bd0056..b1fece9 100644
--- a/Source/core/html/canvas/WebGLContextGroup.h
+++ b/Source/core/html/canvas/WebGLContextGroup.h
@@ -40,10 +40,10 @@
 
 typedef int ExceptionCode;
 
-class WebGLContextGroup : public RefCounted<WebGLContextGroup> {
+class WebGLContextGroup FINAL : public RefCounted<WebGLContextGroup> {
 public:
     static PassRefPtr<WebGLContextGroup> create();
-    virtual ~WebGLContextGroup();
+    ~WebGLContextGroup();
 
     void addContext(WebGLRenderingContext*);
     void removeContext(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/WebGLGetInfo.cpp b/Source/core/html/canvas/WebGLGetInfo.cpp
index e8e71de..0c7b053 100644
--- a/Source/core/html/canvas/WebGLGetInfo.cpp
+++ b/Source/core/html/canvas/WebGLGetInfo.cpp
@@ -209,10 +209,6 @@
 {
 }
 
-WebGLGetInfo::~WebGLGetInfo()
-{
-}
-
 WebGLGetInfo::Type WebGLGetInfo::getType() const
 {
     return m_type;
diff --git a/Source/core/html/canvas/WebGLGetInfo.h b/Source/core/html/canvas/WebGLGetInfo.h
index 552cf47..d72e7f9 100644
--- a/Source/core/html/canvas/WebGLGetInfo.h
+++ b/Source/core/html/canvas/WebGLGetInfo.h
@@ -48,7 +48,7 @@
 // similar variants. For reference counted types, increments and
 // decrements the reference count of the target object.
 
-class WebGLGetInfo {
+class WebGLGetInfo FINAL {
 public:
     enum Type {
         kTypeBool,
@@ -92,8 +92,6 @@
     explicit WebGLGetInfo(PassRefPtr<Uint32Array> value);
     explicit WebGLGetInfo(PassRefPtr<WebGLVertexArrayObjectOES> value);
 
-    virtual ~WebGLGetInfo();
-
     Type getType() const;
 
     bool getBool() const;
diff --git a/Source/core/html/canvas/WebGLRenderingContext.cpp b/Source/core/html/canvas/WebGLRenderingContext.cpp
index 7fa3d83..5505630 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -87,7 +87,7 @@
 
 const double secondsBetweenRestoreAttempts = 1.0;
 const int maxGLErrorsAllowedToConsole = 256;
-const int maxGLActiveContexts = 16;
+const unsigned maxGLActiveContexts = 16;
 
 Vector<WebGLRenderingContext*>& WebGLRenderingContext::activeContexts()
 {
@@ -524,7 +524,7 @@
 
     // The FrameLoaderClient might block creation of a new WebGL context despite the page settings; in
     // particular, if WebGL contexts were lost one or more times via the GL_ARB_robustness extension.
-    if (!frame->loader()->client()->allowWebGL(settings && settings->webGLEnabled())) {
+    if (!frame->loader().client()->allowWebGL(settings && settings->webGLEnabled())) {
         canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Web page was not allowed to create a WebGL context."));
         return nullptr;
     }
@@ -601,8 +601,8 @@
     }
 
     // Register extensions.
-    static const char* webkitPrefix[] = { "WEBKIT_", 0, };
-    static const char* bothPrefixes[] = { "", "WEBKIT_", 0, };
+    static const char* const webkitPrefix[] = { "WEBKIT_", 0, };
+    static const char* const bothPrefixes[] = { "", "WEBKIT_", 0, };
 
     registerExtension<ANGLEInstancedArrays>(m_angleInstancedArrays);
     registerExtension<EXTTextureFilterAnisotropic>(m_extTextureFilterAnisotropic, PrefixedExtension, webkitPrefix);
@@ -1703,7 +1703,7 @@
         m_framebufferBinding->removeAttachmentFromBoundFramebuffer(texture);
 
     // If the deleted was bound to the the current maximum index, trace backwards to find the new max texture index
-    if (m_onePlusMaxNonDefaultTextureUnit == maxBoundTextureIndex + 1) {
+    if (m_onePlusMaxNonDefaultTextureUnit == static_cast<unsigned long>(maxBoundTextureIndex + 1)) {
         findNewMaxNonDefaultTextureUnit();
     }
 }
@@ -2157,9 +2157,9 @@
 
 bool WebGLRenderingContext::ExtensionTracker::matchesNameWithPrefixes(const String& name) const
 {
-    static const char* unprefixed[] = { "", 0, };
+    static const char* const unprefixed[] = { "", 0, };
 
-    const char** prefixes = m_prefixes ? m_prefixes : unprefixed;
+    const char* const* prefixes = m_prefixes ? m_prefixes : unprefixed;
     for (; *prefixes; ++prefixes) {
         String prefixedName = String(*prefixes) + extensionName();
         if (equalIgnoringCase(prefixedName, name)) {
@@ -3461,10 +3461,20 @@
     // 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) {
-        ImageBuffer* buffer = canvas->buffer();
-        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;
+        if (!canvas->is3D()) {
+            ImageBuffer* buffer = canvas->buffer();
+            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 = static_cast<WebGLRenderingContext*>(canvas->renderingContext());
+            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;
+            }
         }
     }
 
@@ -4157,7 +4167,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->extensions()->getGraphicsResetStatusARB());
     }
 
     // Make absolutely sure we do not refer to an already-deleted texture or framebuffer.
@@ -5389,7 +5399,7 @@
 
     Settings* settings = frame->settings();
 
-    if (!frame->loader()->client()->allowWebGL(settings && settings->webGLEnabled()))
+    if (!frame->loader().client()->allowWebGL(settings && settings->webGLEnabled()))
         return;
 
     // Reset the context attributes back to the requested attributes and re-apply restrictions
diff --git a/Source/core/html/canvas/WebGLRenderingContext.h b/Source/core/html/canvas/WebGLRenderingContext.h
index 137eafb..9f4cb3d 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.h
+++ b/Source/core/html/canvas/WebGLRenderingContext.h
@@ -543,7 +543,7 @@
 
     class ExtensionTracker {
     public:
-        ExtensionTracker(ExtensionFlags flags, const char** prefixes)
+        ExtensionTracker(ExtensionFlags flags, const char* const* prefixes)
             : m_privileged(flags & PrivilegedExtension)
             , m_draft(flags & DraftExtension)
             , m_prefixed(flags & PrefixedExtension)
@@ -581,13 +581,13 @@
         bool m_privileged;
         bool m_draft;
         bool m_prefixed;
-        const char** m_prefixes;
+        const char* const* m_prefixes;
     };
 
     template <typename T>
     class TypedExtensionTracker : public ExtensionTracker {
     public:
-        TypedExtensionTracker(RefPtr<T>& extensionField, ExtensionFlags flags, const char** prefixes)
+        TypedExtensionTracker(RefPtr<T>& extensionField, ExtensionFlags flags, const char* const* prefixes)
             : ExtensionTracker(flags, prefixes)
             , m_extensionField(extensionField)
         {
@@ -635,7 +635,7 @@
     Vector<ExtensionTracker*> m_extensions;
 
     template <typename T>
-    void registerExtension(RefPtr<T>& extensionPtr, ExtensionFlags flags = ApprovedExtension, const char** prefixes = 0)
+    void registerExtension(RefPtr<T>& extensionPtr, ExtensionFlags flags = ApprovedExtension, const char* const* prefixes = 0)
     {
         m_extensions.append(new TypedExtensionTracker<T>(extensionPtr, flags, prefixes));
     }
diff --git a/Source/core/html/canvas/WebGLUniformLocation.h b/Source/core/html/canvas/WebGLUniformLocation.h
index 2a41d00..34e0480 100644
--- a/Source/core/html/canvas/WebGLUniformLocation.h
+++ b/Source/core/html/canvas/WebGLUniformLocation.h
@@ -34,10 +34,8 @@
 
 namespace WebCore {
 
-class WebGLUniformLocation : public RefCounted<WebGLUniformLocation>, public ScriptWrappable {
+class WebGLUniformLocation FINAL : public RefCounted<WebGLUniformLocation>, public ScriptWrappable {
 public:
-    virtual ~WebGLUniformLocation() { }
-
     static PassRefPtr<WebGLUniformLocation> create(WebGLProgram*, GC3Dint location);
 
     WebGLProgram* program() const;
diff --git a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
index 3d590c7..e595534 100644
--- a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
+++ b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
@@ -313,6 +313,7 @@
     RefPtr<RenderStyle> style = RenderStyle::clone(originalStyle.get());
     style->setDirection(contentDirection);
     style->setDisplay(newDisplay);
+    style->setUnique();
     return style.release();
 }
 
diff --git a/Source/core/html/forms/ColorInputType.cpp b/Source/core/html/forms/ColorInputType.cpp
index 0f3bae9..5485568 100644
--- a/Source/core/html/forms/ColorInputType.cpp
+++ b/Source/core/html/forms/ColorInputType.cpp
@@ -43,9 +43,9 @@
 #include "core/html/HTMLOptionElement.h"
 #include "core/html/forms/InputTypeNames.h"
 #include "core/page/Chrome.h"
-#include "core/platform/graphics/Color.h"
 #include "core/rendering/RenderView.h"
 #include "platform/UserGestureIndicator.h"
+#include "platform/graphics/Color.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/text/WTFString.h"
 
@@ -79,7 +79,7 @@
 
 void ColorInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeColor);
+    countUsageIfVisible(UseCounter::InputTypeColor);
 }
 
 bool ColorInputType::isColorControl() const
diff --git a/Source/core/html/forms/DateInputType.cpp b/Source/core/html/forms/DateInputType.cpp
index 921cd4d..b37f0d8 100644
--- a/Source/core/html/forms/DateInputType.cpp
+++ b/Source/core/html/forms/DateInputType.cpp
@@ -60,7 +60,7 @@
 
 void DateInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeDate);
+    countUsageIfVisible(UseCounter::InputTypeDate);
 }
 
 const AtomicString& DateInputType::formControlType() const
diff --git a/Source/core/html/forms/DateTimeLocalInputType.cpp b/Source/core/html/forms/DateTimeLocalInputType.cpp
index 995968c..1f3317d 100644
--- a/Source/core/html/forms/DateTimeLocalInputType.cpp
+++ b/Source/core/html/forms/DateTimeLocalInputType.cpp
@@ -57,7 +57,7 @@
 
 void DateTimeLocalInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeDateTimeLocal);
+    countUsageIfVisible(UseCounter::InputTypeDateTimeLocal);
 }
 
 const AtomicString& DateTimeLocalInputType::formControlType() const
diff --git a/Source/core/html/forms/EmailInputType.cpp b/Source/core/html/forms/EmailInputType.cpp
index 7c31462..7259900 100644
--- a/Source/core/html/forms/EmailInputType.cpp
+++ b/Source/core/html/forms/EmailInputType.cpp
@@ -140,7 +140,15 @@
 
 void EmailInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeEmail);
+    countUsageIfVisible(UseCounter::InputTypeEmail);
+    bool hasMaxLength = element().fastHasAttribute(HTMLNames::maxlengthAttr);
+    if (hasMaxLength)
+        countUsageIfVisible(UseCounter::InputTypeEmailMaxLength);
+    if (element().multiple()) {
+        countUsageIfVisible(UseCounter::InputTypeEmailMultiple);
+        if (hasMaxLength)
+            countUsageIfVisible(UseCounter::InputTypeEmailMultipleMaxLength);
+    }
 }
 
 const AtomicString& EmailInputType::formControlType() const
diff --git a/Source/core/html/forms/InputType.cpp b/Source/core/html/forms/InputType.cpp
index b09845d..ff98bc8 100644
--- a/Source/core/html/forms/InputType.cpp
+++ b/Source/core/html/forms/InputType.cpp
@@ -992,7 +992,7 @@
     }
 }
 
-void InputType::observeFeatureIfVisible(UseCounter::Feature feature) const
+void InputType::countUsageIfVisible(UseCounter::Feature feature) const
 {
     if (RenderStyle* style = element().renderStyle()) {
         if (style->visibility() != HIDDEN)
diff --git a/Source/core/html/forms/InputType.h b/Source/core/html/forms/InputType.h
index 57218ca..d0a6a4c 100644
--- a/Source/core/html/forms/InputType.h
+++ b/Source/core/html/forms/InputType.h
@@ -170,9 +170,6 @@
     virtual void createShadowSubtree();
     virtual void destroyShadowSubtree();
 
-    virtual HTMLElement* innerTextElement() const { return 0; }
-    virtual HTMLElement* passwordGeneratorButtonElement() const { return 0; }
-
     // Miscellaneous functions
 
     virtual bool rendererIsNeeded();
@@ -244,7 +241,7 @@
     Chrome* chrome() const;
     Locale& locale() const;
     Decimal parseToNumberOrNaN(const String&) const;
-    void observeFeatureIfVisible(UseCounter::Feature) const;
+    void countUsageIfVisible(UseCounter::Feature) const;
 
 private:
     // Helper for stepUp()/stepDown(). Adds step value * count to the current value.
diff --git a/Source/core/html/forms/MonthInputType.cpp b/Source/core/html/forms/MonthInputType.cpp
index 5c568d3..1652dff 100644
--- a/Source/core/html/forms/MonthInputType.cpp
+++ b/Source/core/html/forms/MonthInputType.cpp
@@ -58,7 +58,7 @@
 
 void MonthInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeMonth);
+    countUsageIfVisible(UseCounter::InputTypeMonth);
 }
 
 const AtomicString& MonthInputType::formControlType() const
diff --git a/Source/core/html/forms/NumberInputType.cpp b/Source/core/html/forms/NumberInputType.cpp
index 26e5e40..a91d21a 100644
--- a/Source/core/html/forms/NumberInputType.cpp
+++ b/Source/core/html/forms/NumberInputType.cpp
@@ -101,7 +101,7 @@
 
 void NumberInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeNumber);
+    countUsageIfVisible(UseCounter::InputTypeNumber);
 }
 
 const AtomicString& NumberInputType::formControlType() const
diff --git a/Source/core/html/forms/PasswordInputType.cpp b/Source/core/html/forms/PasswordInputType.cpp
index ddab745..d18b8ca 100644
--- a/Source/core/html/forms/PasswordInputType.cpp
+++ b/Source/core/html/forms/PasswordInputType.cpp
@@ -52,11 +52,6 @@
     return adoptRef(new PasswordInputType(element));
 }
 
-HTMLElement* PasswordInputType::passwordGeneratorButtonElement() const
-{
-    return m_generatorButton.get();
-}
-
 bool PasswordInputType::isPasswordGenerationEnabled() const
 {
     if (isPasswordGenerationDecorationEnabled())
@@ -83,24 +78,10 @@
     BaseTextInputType::createShadowSubtree();
     if (!isPasswordGenerationEnabled())
         return;
-    ShadowRoot* root = element().userAgentShadowRoot();
-    RefPtr<HTMLDivElement> wrapper = HTMLDivElement::create(element().document());
-    wrapper->setInlineStyleProperty(CSSPropertyDisplay, CSSValueFlex);
-    wrapper->setInlineStyleProperty(CSSPropertyAlignItems, CSSValueCenter);
-    ASSERT(root->childNodeCount() == 1);
-    root->firstElementChild()->setInlineStyleProperty(CSSPropertyFlexGrow, 1.0, CSSPrimitiveValue::CSS_NUMBER);
-    wrapper->appendChild(root->firstElementChild());
-    m_generatorButton = PasswordGeneratorButtonElement::create(element().document());
+    RefPtr<PasswordGeneratorButtonElement> generatorButton = PasswordGeneratorButtonElement::create(element().document());
     if (!isPasswordGenerationDecorationEnabled())
-        m_generatorButton->setInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
-    wrapper->appendChild(m_generatorButton.get());
-    element().userAgentShadowRoot()->appendChild(wrapper);
-}
-
-void PasswordInputType::destroyShadowSubtree()
-{
-    BaseTextInputType::destroyShadowSubtree();
-    m_generatorButton = 0;
+        generatorButton->setInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
+    containerElement()->appendChild(generatorButton.release());
 }
 
 const AtomicString& PasswordInputType::formControlType() const
diff --git a/Source/core/html/forms/PasswordInputType.h b/Source/core/html/forms/PasswordInputType.h
index fa28371..9fd227a 100644
--- a/Source/core/html/forms/PasswordInputType.h
+++ b/Source/core/html/forms/PasswordInputType.h
@@ -42,10 +42,8 @@
 
 private:
     PasswordInputType(HTMLInputElement& element) : BaseTextInputType(element) { }
-    virtual HTMLElement* passwordGeneratorButtonElement() const OVERRIDE;
     virtual bool needsContainer() const OVERRIDE;
     virtual void createShadowSubtree() OVERRIDE;
-    virtual void destroyShadowSubtree() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual bool shouldSaveAndRestoreFormControlState() const OVERRIDE;
     virtual FormControlState saveFormControlState() const OVERRIDE;
@@ -61,8 +59,6 @@
     bool isPasswordGenerationEnabled() const;
     // For testing.
     bool isPasswordGenerationDecorationEnabled() const;
-
-    RefPtr<PasswordGeneratorButtonElement> m_generatorButton;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/forms/RangeInputType.cpp b/Source/core/html/forms/RangeInputType.cpp
index 58c2512..8827e4b 100644
--- a/Source/core/html/forms/RangeInputType.cpp
+++ b/Source/core/html/forms/RangeInputType.cpp
@@ -87,7 +87,7 @@
 
 void RangeInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeRange);
+    countUsageIfVisible(UseCounter::InputTypeRange);
 }
 
 bool RangeInputType::isRangeControl() const
diff --git a/Source/core/html/forms/SearchInputType.cpp b/Source/core/html/forms/SearchInputType.cpp
index 081a532..7bd4126 100644
--- a/Source/core/html/forms/SearchInputType.cpp
+++ b/Source/core/html/forms/SearchInputType.cpp
@@ -59,7 +59,7 @@
 
 void SearchInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeSearch);
+    countUsageIfVisible(UseCounter::InputTypeSearch);
 }
 
 RenderObject* SearchInputType::createRenderer(RenderStyle*) const
diff --git a/Source/core/html/forms/TelephoneInputType.cpp b/Source/core/html/forms/TelephoneInputType.cpp
index 174288f..44bb48a 100644
--- a/Source/core/html/forms/TelephoneInputType.cpp
+++ b/Source/core/html/forms/TelephoneInputType.cpp
@@ -43,7 +43,7 @@
 
 void TelephoneInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeTel);
+    countUsageIfVisible(UseCounter::InputTypeTel);
 }
 
 const AtomicString& TelephoneInputType::formControlType() const
diff --git a/Source/core/html/forms/TextFieldInputType.cpp b/Source/core/html/forms/TextFieldInputType.cpp
index f2f897b..5e71ae5 100644
--- a/Source/core/html/forms/TextFieldInputType.cpp
+++ b/Source/core/html/forms/TextFieldInputType.cpp
@@ -184,7 +184,7 @@
     if (element().renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(EventNames::WheelEvent) || event->type() == EventTypeNames::blur || event->type() == EventTypeNames::focus)) {
         RenderTextControlSingleLine* renderTextControl = toRenderTextControlSingleLine(element().renderer());
         if (event->type() == EventTypeNames::blur) {
-            if (RenderBox* innerTextRenderer = innerTextElement()->renderBox()) {
+            if (RenderBox* innerTextRenderer = element().innerTextElement()->renderBox()) {
                 // FIXME: This class has no need to know about RenderLayer!
                 if (RenderLayer* innerLayer = innerTextRenderer->layer()) {
                     RenderLayerScrollableArea* innerScrollableArea = innerLayer->scrollableArea();
@@ -248,9 +248,9 @@
     bool shouldHaveSpinButton = this->shouldHaveSpinButton();
     bool createsContainer = shouldHaveSpinButton || needsContainer();
 
-    m_innerText = TextControlInnerTextElement::create(document);
+    RefPtr<TextControlInnerTextElement> innerEditor = TextControlInnerTextElement::create(document);
     if (!createsContainer) {
-        shadowRoot->appendChild(m_innerText);
+        shadowRoot->appendChild(innerEditor.release());
         return;
     }
 
@@ -259,7 +259,7 @@
     shadowRoot->appendChild(container);
 
     RefPtr<EditingViewPortElement> editingViewPort = EditingViewPortElement::create(document);
-    editingViewPort->appendChild(m_innerText);
+    editingViewPort->appendChild(innerEditor.release());
     container->appendChild(editingViewPort.release());
 
 #if ENABLE(INPUT_SPEECH)
@@ -276,16 +276,9 @@
     return element().userAgentShadowRoot()->getElementById(ShadowElementNames::textFieldContainer());
 }
 
-HTMLElement* TextFieldInputType::innerTextElement() const
-{
-    ASSERT(m_innerText);
-    return m_innerText.get();
-}
-
 void TextFieldInputType::destroyShadowSubtree()
 {
     InputType::destroyShadowSubtree();
-    m_innerText.clear();
     if (SpinButtonElement* spinButton = spinButtonElement())
         spinButton->removeSpinButtonOwner();
 }
@@ -405,7 +398,7 @@
         placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
         placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
         Element* container = containerElement();
-        Node* previous = container ? container : innerTextElement();
+        Node* previous = container ? container : element().innerTextElement();
         previous->parentNode()->insertBefore(placeholder, previous->nextSibling());
         ASSERT_WITH_SECURITY_IMPLICATION(placeholder->parentNode() == previous->parentNode());
     }
diff --git a/Source/core/html/forms/TextFieldInputType.h b/Source/core/html/forms/TextFieldInputType.h
index c081778..f260eba 100644
--- a/Source/core/html/forms/TextFieldInputType.h
+++ b/Source/core/html/forms/TextFieldInputType.h
@@ -48,8 +48,6 @@
     virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
     void handleKeydownEventForSpinButton(KeyboardEvent*);
 
-    virtual HTMLElement* innerTextElement() const OVERRIDE;
-
 protected:
     virtual bool needsContainer() const;
     virtual bool shouldHaveSpinButton() const;
@@ -96,8 +94,6 @@
     virtual void spinButtonStepUp() OVERRIDE;
 
     SpinButtonElement* spinButtonElement() const;
-
-    RefPtr<HTMLElement> m_innerText;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/forms/TextInputType.cpp b/Source/core/html/forms/TextInputType.cpp
index e15324a..36c69cd 100644
--- a/Source/core/html/forms/TextInputType.cpp
+++ b/Source/core/html/forms/TextInputType.cpp
@@ -48,9 +48,9 @@
 {
     const AtomicString& type = element().fastGetAttribute(typeAttr);
     if (equalIgnoringCase(type, InputTypeNames::datetime()))
-        observeFeatureIfVisible(UseCounter::InputTypeDateTimeFallback);
+        countUsageIfVisible(UseCounter::InputTypeDateTimeFallback);
     else if (equalIgnoringCase(type, InputTypeNames::week()))
-        observeFeatureIfVisible(UseCounter::InputTypeWeekFallback);
+        countUsageIfVisible(UseCounter::InputTypeWeekFallback);
 }
 
 const AtomicString& TextInputType::formControlType() const
diff --git a/Source/core/html/forms/TimeInputType.cpp b/Source/core/html/forms/TimeInputType.cpp
index 7e68ac4..83a3fba 100644
--- a/Source/core/html/forms/TimeInputType.cpp
+++ b/Source/core/html/forms/TimeInputType.cpp
@@ -63,7 +63,7 @@
 
 void TimeInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeTime);
+    countUsageIfVisible(UseCounter::InputTypeTime);
 }
 
 const AtomicString& TimeInputType::formControlType() const
diff --git a/Source/core/html/forms/URLInputType.cpp b/Source/core/html/forms/URLInputType.cpp
index f662e1a..404906a 100644
--- a/Source/core/html/forms/URLInputType.cpp
+++ b/Source/core/html/forms/URLInputType.cpp
@@ -45,7 +45,7 @@
 
 void URLInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeURL);
+    countUsageIfVisible(UseCounter::InputTypeURL);
 }
 
 const AtomicString& URLInputType::formControlType() const
diff --git a/Source/core/html/forms/WeekInputType.cpp b/Source/core/html/forms/WeekInputType.cpp
index 248b227..84d8542 100644
--- a/Source/core/html/forms/WeekInputType.cpp
+++ b/Source/core/html/forms/WeekInputType.cpp
@@ -55,7 +55,7 @@
 
 void WeekInputType::countUsage()
 {
-    observeFeatureIfVisible(UseCounter::InputTypeWeek);
+    countUsageIfVisible(UseCounter::InputTypeWeek);
 }
 
 const AtomicString& WeekInputType::formControlType() const
diff --git a/Source/core/html/parser/HTMLConstructionSite.cpp b/Source/core/html/parser/HTMLConstructionSite.cpp
index 2674bf7..46c6faf 100644
--- a/Source/core/html/parser/HTMLConstructionSite.cpp
+++ b/Source/core/html/parser/HTMLConstructionSite.cpp
@@ -99,7 +99,7 @@
         task.parent = toHTMLTemplateElement(task.parent.get())->content();
 
     if (ContainerNode* parent = task.child->parentNode())
-        parent->parserRemoveChild(task.child.get());
+        parent->parserRemoveChild(*task.child);
 
     if (task.nextChild)
         task.parent->parserInsertBefore(task.child.get(), task.nextChild.get());
@@ -124,7 +124,7 @@
     ASSERT(task.operation == HTMLConstructionSiteTask::Reparent);
 
     if (ContainerNode* parent = task.child->parentNode())
-        parent->parserRemoveChild(task.child.get());
+        parent->parserRemoveChild(*task.child);
 
     task.parent->parserAppendChild(task.child);
 }
@@ -298,7 +298,7 @@
 {
     ASSERT(m_document);
     if (m_document->frame() && !m_isParsingFragment)
-        m_document->frame()->loader()->dispatchDocumentElementAvailable();
+        m_document->frame()->loader().dispatchDocumentElementAvailable();
 }
 
 void HTMLConstructionSite::insertHTMLHtmlStartTagBeforeHTML(AtomicHTMLToken* token)
@@ -516,7 +516,7 @@
     attachLater(currentNode(), body);
     m_openElements.pushHTMLBodyElement(HTMLStackItem::create(body.release(), token));
     if (Frame* frame = m_document->frame())
-        frame->loader()->client()->dispatchWillInsertBody();
+        frame->loader().client()->dispatchWillInsertBody();
 }
 
 void HTMLConstructionSite::insertHTMLFormElement(AtomicHTMLToken* token, bool isDemoted)
@@ -640,7 +640,7 @@
 
         ASSERT(breakIndex > currentPosition);
         ASSERT(breakIndex - currentPosition == substring.length());
-        ASSERT(toText(task.child.get())->length() == substring.length());
+        ASSERT(toText(task.child)->length() == substring.length());
         currentPosition = breakIndex;
     }
 }
diff --git a/Source/core/html/parser/HTMLDocumentParser.cpp b/Source/core/html/parser/HTMLDocumentParser.cpp
index 072db68..e0dfa89 100644
--- a/Source/core/html/parser/HTMLDocumentParser.cpp
+++ b/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -288,7 +288,7 @@
     //        parser to stop parsing cleanly.  The problem is we're not
     //        perpared to do that at every point where we run JavaScript.
     if (!isParsingFragment()
-        && document()->frame() && document()->frame()->navigationScheduler()->locationChangePending())
+        && document()->frame() && document()->frame()->navigationScheduler().locationChangePending())
         return false;
 
     if (mode == AllowYield)
@@ -411,7 +411,7 @@
         ASSERT(!isWaitingForScripts());
 
         if (!isParsingFragment()
-            && document()->frame() && document()->frame()->navigationScheduler()->locationChangePending()) {
+            && document()->frame() && document()->frame()->navigationScheduler().locationChangePending()) {
 
             // To match main-thread parser behavior (which never checks locationChangePending on the EOF path)
             // we peek to see if this chunk has an EOF and process it anyway.
diff --git a/Source/core/html/parser/HTMLIdentifier.cpp b/Source/core/html/parser/HTMLIdentifier.cpp
index d12ea6a..5a77dd0 100644
--- a/Source/core/html/parser/HTMLIdentifier.cpp
+++ b/Source/core/html/parser/HTMLIdentifier.cpp
@@ -91,7 +91,7 @@
     return m_string.impl();
 }
 
-void HTMLIdentifier::addNames(QualifiedName** names, unsigned namesCount, unsigned indexOffset)
+void HTMLIdentifier::addNames(const QualifiedName* const* names, unsigned namesCount, unsigned indexOffset)
 {
     IdentifierTable& table = identifierTable();
     for (unsigned i = 0; i < namesCount; ++i) {
diff --git a/Source/core/html/parser/HTMLIdentifier.h b/Source/core/html/parser/HTMLIdentifier.h
index 1aec5f7..54e1a3a 100644
--- a/Source/core/html/parser/HTMLIdentifier.h
+++ b/Source/core/html/parser/HTMLIdentifier.h
@@ -72,7 +72,7 @@
 private:
     static unsigned maxNameLength;
     static StringImpl* findIfKnown(const UChar* characters, unsigned length);
-    static void addNames(QualifiedName** names, unsigned namesCount, unsigned indexOffset);
+    static void addNames(const QualifiedName* const* names, unsigned namesCount, unsigned indexOffset);
 
     String m_string;
 };
diff --git a/Source/core/html/parser/HTMLParserOptions.cpp b/Source/core/html/parser/HTMLParserOptions.cpp
index 7de381b..b101eac 100644
--- a/Source/core/html/parser/HTMLParserOptions.cpp
+++ b/Source/core/html/parser/HTMLParserOptions.cpp
@@ -37,8 +37,8 @@
 HTMLParserOptions::HTMLParserOptions(Document* document)
 {
     Frame* frame = document ? document->frame() : 0;
-    scriptEnabled = frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript);
-    pluginsEnabled = frame && frame->loader()->allowPlugins(NotAboutToInstantiatePlugin);
+    scriptEnabled = frame && frame->script().canExecuteScripts(NotAboutToExecuteScript);
+    pluginsEnabled = frame && frame->loader().allowPlugins(NotAboutToInstantiatePlugin);
 
     Settings* settings = document ? document->settings() : 0;
     // We force the main-thread parser for about:blank, javascript: and data: urls for compatibility
diff --git a/Source/core/html/parser/HTMLResourcePreloader.cpp b/Source/core/html/parser/HTMLResourcePreloader.cpp
index 1d5317c..95f3f14 100644
--- a/Source/core/html/parser/HTMLResourcePreloader.cpp
+++ b/Source/core/html/parser/HTMLResourcePreloader.cpp
@@ -32,8 +32,8 @@
 #include "core/html/HTMLImport.h"
 #include "core/css/MediaList.h"
 #include "core/css/MediaQueryEvaluator.h"
-#include "core/platform/HistogramSupport.h"
 #include "core/rendering/RenderObject.h"
+#include "public/platform/Platform.h"
 
 namespace WebCore {
 
@@ -93,7 +93,7 @@
         return;
 
     FetchRequest request = preload->resourceRequest(m_document);
-    HistogramSupport::histogramCustomCounts("WebCore.PreloadDelayMs", static_cast<int>(1000 * (monotonicallyIncreasingTime() - preload->discoveryTime())), 0, 2000, 20);
+    WebKit::Platform::current()->histogramCustomCounts("WebCore.PreloadDelayMs", static_cast<int>(1000 * (monotonicallyIncreasingTime() - preload->discoveryTime())), 0, 2000, 20);
     loadingDocument->fetcher()->preload(preload->resourceType(), request, preload->charset());
 }
 
diff --git a/Source/core/html/parser/HTMLResourcePreloader.h b/Source/core/html/parser/HTMLResourcePreloader.h
index 75c620d..a72880f 100644
--- a/Source/core/html/parser/HTMLResourcePreloader.h
+++ b/Source/core/html/parser/HTMLResourcePreloader.h
@@ -89,18 +89,14 @@
 public:
     explicit HTMLResourcePreloader(Document* document)
         : m_document(document)
-        , m_weakFactory(this)
     {
     }
 
     void takeAndPreload(PreloadRequestStream&);
     void preload(PassOwnPtr<PreloadRequest>);
 
-    WeakPtr<HTMLResourcePreloader> createWeakPtr() { return m_weakFactory.createWeakPtr(); }
-
 private:
     Document* m_document;
-    WeakPtrFactory<HTMLResourcePreloader> m_weakFactory;
 };
 
 }
diff --git a/Source/core/html/parser/HTMLSrcsetParser.cpp b/Source/core/html/parser/HTMLSrcsetParser.cpp
index 815b556..7002dff 100644
--- a/Source/core/html/parser/HTMLSrcsetParser.cpp
+++ b/Source/core/html/parser/HTMLSrcsetParser.cpp
@@ -32,7 +32,7 @@
 #include "core/html/parser/HTMLSrcsetParser.h"
 
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/platform/ParsingUtilities.h"
+#include "platform/ParsingUtilities.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLTreeBuilder.cpp b/Source/core/html/parser/HTMLTreeBuilder.cpp
index 84100a8..4caa70c 100644
--- a/Source/core/html/parser/HTMLTreeBuilder.cpp
+++ b/Source/core/html/parser/HTMLTreeBuilder.cpp
@@ -546,7 +546,7 @@
 
 typedef HashMap<AtomicString, QualifiedName> PrefixedNameToQualifiedNameMap;
 
-static void mapLoweredLocalNameToName(PrefixedNameToQualifiedNameMap* map, QualifiedName** names, size_t length)
+static void mapLoweredLocalNameToName(PrefixedNameToQualifiedNameMap* map, const QualifiedName* const* names, size_t length)
 {
     for (size_t i = 0; i < length; ++i) {
         const QualifiedName& name = *names[i];
@@ -562,7 +562,7 @@
     static PrefixedNameToQualifiedNameMap* caseMap = 0;
     if (!caseMap) {
         caseMap = new PrefixedNameToQualifiedNameMap;
-        QualifiedName** svgTags = SVGNames::getSVGTags();
+        const QualifiedName* const* svgTags = SVGNames::getSVGTags();
         mapLoweredLocalNameToName(caseMap, svgTags, SVGNames::SVGTagsCount);
     }
 
@@ -572,13 +572,13 @@
     token->setName(casedName.localName());
 }
 
-template<QualifiedName** getAttrs(), unsigned length>
+template<const QualifiedName* const* getAttrs(), unsigned length>
 static void adjustAttributes(AtomicHTMLToken* token)
 {
     static PrefixedNameToQualifiedNameMap* caseMap = 0;
     if (!caseMap) {
         caseMap = new PrefixedNameToQualifiedNameMap;
-        QualifiedName** attrs = getAttrs();
+        const QualifiedName* const* attrs = getAttrs();
         mapLoweredLocalNameToName(caseMap, attrs, length);
     }
 
@@ -600,10 +600,10 @@
     adjustAttributes<MathMLNames::getMathMLAttrs, MathMLNames::MathMLAttrsCount>(token);
 }
 
-static void addNamesWithPrefix(PrefixedNameToQualifiedNameMap* map, const AtomicString& prefix, QualifiedName** names, size_t length)
+static void addNamesWithPrefix(PrefixedNameToQualifiedNameMap* map, const AtomicString& prefix, const QualifiedName* const* names, size_t length)
 {
     for (size_t i = 0; i < length; ++i) {
-        QualifiedName* name = names[i];
+        const QualifiedName* name = names[i];
         const AtomicString& localName = name->localName();
         AtomicString prefixColonLocalName = prefix + ':' + localName;
         QualifiedName nameWithPrefix(prefix, localName, name->namespaceURI());
@@ -617,7 +617,7 @@
     if (!map) {
         map = new PrefixedNameToQualifiedNameMap;
 
-        QualifiedName** attrs = XLinkNames::getXLinkAttrs();
+        const QualifiedName* const* attrs = XLinkNames::getXLinkAttrs();
         addNamesWithPrefix(map, xlinkAtom, attrs, XLinkNames::XLinkAttrsCount);
 
         attrs = XMLNames::getXMLAttrs();
diff --git a/Source/core/html/parser/XSSAuditor.cpp b/Source/core/html/parser/XSSAuditor.cpp
index 5b6da26..972c0e7 100644
--- a/Source/core/html/parser/XSSAuditor.cpp
+++ b/Source/core/html/parser/XSSAuditor.cpp
@@ -264,7 +264,7 @@
         m_decodedURL = String();
 
     String httpBodyAsString;
-    if (DocumentLoader* documentLoader = document->frame()->loader()->documentLoader()) {
+    if (DocumentLoader* documentLoader = document->frame()->loader().documentLoader()) {
         DEFINE_STATIC_LOCAL(String, XSSProtectionHeader, ("X-XSS-Protection"));
         String headerValue = documentLoader->response().httpHeaderField(XSSProtectionHeader);
         String errorDetails;
@@ -474,11 +474,10 @@
     ASSERT(request.token.type() == HTMLToken::StartTag);
     ASSERT(hasName(request.token, iframeTag) || hasName(request.token, frameTag));
 
-    bool didBlockScript = false;
-    if (isContainedInRequest(decodedSnippetForName(request))) {
+    bool didBlockScript = eraseAttributeIfInjected(request, srcdocAttr, String(), ScriptLikeAttribute);
+    if (isContainedInRequest(decodedSnippetForName(request)))
         didBlockScript |= eraseAttributeIfInjected(request, srcAttr, String(), SrcLikeAttribute);
-        didBlockScript |= eraseAttributeIfInjected(request, srcdocAttr, String(), ScriptLikeAttribute);
-    }
+
     return didBlockScript;
 }
 
diff --git a/Source/core/html/parser/XSSAuditorDelegate.cpp b/Source/core/html/parser/XSSAuditorDelegate.cpp
index 89262f0..b676bc9 100644
--- a/Source/core/html/parser/XSSAuditorDelegate.cpp
+++ b/Source/core/html/parser/XSSAuditorDelegate.cpp
@@ -77,10 +77,10 @@
 {
     ASSERT(isMainThread());
 
-    FrameLoader* frameLoader = m_document->frame()->loader();
+    FrameLoader& frameLoader = m_document->frame()->loader();
     String httpBody;
-    if (frameLoader->documentLoader()) {
-        if (FormData* formData = frameLoader->documentLoader()->originalRequest().httpBody())
+    if (frameLoader.documentLoader()) {
+        if (FormData* formData = frameLoader.documentLoader()->originalRequest().httpBody())
             httpBody = formData->flattenToString();
     }
 
@@ -102,21 +102,21 @@
 
     // stopAllLoaders can detach the Frame, so protect it.
     RefPtr<Frame> protect(m_document->frame());
-    FrameLoader* frameLoader = m_document->frame()->loader();
+    FrameLoader& frameLoader = m_document->frame()->loader();
     if (xssInfo.m_didBlockEntirePage)
-        frameLoader->stopAllLoaders();
+        frameLoader.stopAllLoaders();
 
     if (!m_didSendNotifications) {
         m_didSendNotifications = true;
 
-        frameLoader->client()->didDetectXSS(m_document->url(), xssInfo.m_didBlockEntirePage);
+        frameLoader.client()->didDetectXSS(m_document->url(), xssInfo.m_didBlockEntirePage);
 
         if (!m_reportURL.isEmpty())
             PingLoader::sendViolationReport(m_document->frame(), m_reportURL, generateViolationReport(xssInfo), PingLoader::XSSAuditorViolationReport);
     }
 
     if (xssInfo.m_didBlockEntirePage)
-        m_document->frame()->navigationScheduler()->scheduleLocationChange(m_document->securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
+        m_document->frame()->navigationScheduler().scheduleLocationChange(m_document->securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/shadow/ClearButtonElement.cpp b/Source/core/html/shadow/ClearButtonElement.cpp
index dce827a..96b3760 100644
--- a/Source/core/html/shadow/ClearButtonElement.cpp
+++ b/Source/core/html/shadow/ClearButtonElement.cpp
@@ -55,7 +55,7 @@
 {
     if (m_capturing) {
         if (Frame* frame = document().frame())
-            frame->eventHandler()->setCapturingMouseEventsNode(0);
+            frame->eventHandler().setCapturingMouseEventsNode(0);
     }
     HTMLDivElement::detach(context);
 }
@@ -66,7 +66,7 @@
         return;
 
     if (Frame* frame = document().frame()) {
-        frame->eventHandler()->setCapturingMouseEventsNode(0);
+        frame->eventHandler().setCapturingMouseEventsNode(0);
         m_capturing = false;
     }
 }
@@ -88,7 +88,7 @@
     if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (renderer() && renderer()->visibleToHitTesting()) {
             if (Frame* frame = document().frame()) {
-                frame->eventHandler()->setCapturingMouseEventsNode(this);
+                frame->eventHandler().setCapturingMouseEventsNode(this);
                 m_capturing = true;
             }
         }
@@ -98,7 +98,7 @@
     if (event->type() == EventTypeNames::mouseup && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (m_capturing) {
             if (Frame* frame = document().frame()) {
-                frame->eventHandler()->setCapturingMouseEventsNode(0);
+                frame->eventHandler().setCapturingMouseEventsNode(0);
                 m_capturing = false;
             }
             if (hovered()) {
diff --git a/Source/core/html/shadow/DateTimeEditElement.cpp b/Source/core/html/shadow/DateTimeEditElement.cpp
index 197da71..909402c 100644
--- a/Source/core/html/shadow/DateTimeEditElement.cpp
+++ b/Source/core/html/shadow/DateTimeEditElement.cpp
@@ -512,6 +512,7 @@
         }
     }
     style->setWidth(Length(ceilf(width), Fixed));
+    style->setUnique();
     return style.release();
 }
 
diff --git a/Source/core/html/shadow/HTMLContentElement.h b/Source/core/html/shadow/HTMLContentElement.h
index df52237..3b721b6 100644
--- a/Source/core/html/shadow/HTMLContentElement.h
+++ b/Source/core/html/shadow/HTMLContentElement.h
@@ -101,11 +101,7 @@
     return element->hasTagName(HTMLNames::contentTag);
 }
 
-inline HTMLContentElement* toHTMLContentElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLContentElement(node));
-    return static_cast<HTMLContentElement*>(node);
-}
+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 b9943bd..c528127 100644
--- a/Source/core/html/shadow/HTMLShadowElement.h
+++ b/Source/core/html/shadow/HTMLShadowElement.h
@@ -55,17 +55,7 @@
     return node->hasTagName(HTMLNames::shadowTag);
 }
 
-inline HTMLShadowElement* toHTMLShadowElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLShadowElement(node));
-    return static_cast<HTMLShadowElement*>(node);
-}
-
-inline const HTMLShadowElement* toHTMLShadowElement(const Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLShadowElement(node));
-    return static_cast<const HTMLShadowElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLShadowElement, hasTagName(HTMLNames::shadowTag));
 
 inline bool isActiveShadowInsertionPoint(const Node* node)
 {
diff --git a/Source/core/html/shadow/HTMLShadowElement.idl b/Source/core/html/shadow/HTMLShadowElement.idl
index 3b6351b..faceace 100644
--- a/Source/core/html/shadow/HTMLShadowElement.idl
+++ b/Source/core/html/shadow/HTMLShadowElement.idl
@@ -31,4 +31,5 @@
 interface HTMLShadowElement : HTMLElement {
     attribute boolean resetStyleInheritance;
     [DeprecateAs=HTMLShadowElementOlderShadowRoot] readonly attribute ShadowRoot olderShadowRoot;
+    [RuntimeEnabled=ShadowDOM] NodeList getDistributedNodes();
 };
diff --git a/Source/core/html/shadow/MediaControlElements.cpp b/Source/core/html/shadow/MediaControlElements.cpp
index 308c4dd..5c24e2c 100644
--- a/Source/core/html/shadow/MediaControlElements.cpp
+++ b/Source/core/html/shadow/MediaControlElements.cpp
@@ -56,7 +56,8 @@
 static const AtomicString& getMediaControlCurrentTimeDisplayElementShadowPseudoId();
 static const AtomicString& getMediaControlTimeRemainingDisplayElementShadowPseudoId();
 
-static const char* textTracksOffAttrValue = "-1"; // This must match HTMLMediaElement::textTracksOffIndex()
+static const double fadeInDuration = 0.1;
+static const double fadeOutDuration = 0.3;
 
 MediaControlPanelElement::MediaControlPanelElement(Document& document)
     : MediaControlDivElement(document, MediaControlsPanel)
@@ -97,7 +98,7 @@
 
     m_lastDragEventLocation = eventLocation;
 
-    frame->eventHandler()->setCapturingMouseEventsNode(this);
+    frame->eventHandler().setCapturingMouseEventsNode(this);
 
     m_isBeingDragged = true;
 }
@@ -124,7 +125,7 @@
     if (!frame)
         return;
 
-    frame->eventHandler()->setCapturingMouseEventsNode(0);
+    frame->eventHandler().setCapturingMouseEventsNode(0);
 }
 
 void MediaControlPanelElement::startTimer()
@@ -134,8 +135,8 @@
     // The timer is required to set the property display:'none' on the panel,
     // such that captions are correctly displayed at the bottom of the video
     // at the end of the fadeout transition.
-    double duration = RenderTheme::theme().mediaControlsFadeOutDuration();
-    m_transitionTimer.startOneShot(duration);
+    // FIXME: Racing a transition with a setTimeout like this is wrong.
+    m_transitionTimer.startOneShot(fadeOutDuration);
 }
 
 void MediaControlPanelElement::stopTimer()
@@ -185,10 +186,8 @@
     if (m_opaque)
         return;
 
-    double duration = RenderTheme::theme().mediaControlsFadeInDuration();
-
     setInlineStyleProperty(CSSPropertyTransitionProperty, CSSPropertyOpacity);
-    setInlineStyleProperty(CSSPropertyTransitionDuration, duration, CSSPrimitiveValue::CSS_S);
+    setInlineStyleProperty(CSSPropertyTransitionDuration, fadeInDuration, CSSPrimitiveValue::CSS_S);
     setInlineStyleProperty(CSSPropertyOpacity, 1.0, CSSPrimitiveValue::CSS_NUMBER);
 
     m_opaque = true;
@@ -202,10 +201,8 @@
     if (!m_opaque)
         return;
 
-    double duration = RenderTheme::theme().mediaControlsFadeOutDuration();
-
     setInlineStyleProperty(CSSPropertyTransitionProperty, CSSPropertyOpacity);
-    setInlineStyleProperty(CSSPropertyTransitionDuration, duration, CSSPrimitiveValue::CSS_S);
+    setInlineStyleProperty(CSSPropertyTransitionDuration, fadeOutDuration, CSSPrimitiveValue::CSS_S);
     setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
 
     m_opaque = false;
@@ -476,7 +473,7 @@
     RefPtr<MediaControlTimelineElement> timeline = adoptRef(new MediaControlTimelineElement(document, controls));
     timeline->ensureUserAgentShadowRoot();
     timeline->setType("range");
-    timeline->setAttribute(precisionAttr, "float");
+    timeline->setAttribute(stepAttr, "any");
     return timeline.release();
 }
 
@@ -543,7 +540,7 @@
     RefPtr<MediaControlPanelVolumeSliderElement> slider = adoptRef(new MediaControlPanelVolumeSliderElement(document));
     slider->ensureUserAgentShadowRoot();
     slider->setType("range");
-    slider->setAttribute(precisionAttr, "float");
+    slider->setAttribute(stepAttr, "any");
     slider->setAttribute(maxAttr, "1");
     return slider.release();
 }
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
index 7cbba45..a71d2a3 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
@@ -35,6 +35,7 @@
 #include "core/dom/NodeRenderStyle.h"
 #include "core/fetch/ImageResource.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"
@@ -45,8 +46,6 @@
 
 using namespace HTMLNames;
 
-// FIXME: This class is only used in Chromium and has no layout tests.
-
 PasswordGeneratorButtonElement::PasswordGeneratorButtonElement(Document& document)
     : HTMLDivElement(HTMLNames::divTag, document)
     , m_isInHoverState(false)
@@ -54,6 +53,13 @@
     setHasCustomStyleCallbacks();
 }
 
+PassRefPtr<PasswordGeneratorButtonElement> PasswordGeneratorButtonElement::create(Document& document)
+{
+    RefPtr<PasswordGeneratorButtonElement> element = adoptRef(new PasswordGeneratorButtonElement(document));
+    element->setAttribute(idAttr, ShadowElementNames::passwordGenerator());
+    return element.release();
+}
+
 inline HTMLInputElement* PasswordGeneratorButtonElement::hostInput()
 {
     // PasswordGeneratorButtonElement is created only by C++ code, and it is always
@@ -79,6 +85,7 @@
     ASSERT(inputStyle);
     style->setWidth(Length(inputStyle->fontSize(), Fixed));
     style->setHeight(Length(inputStyle->fontSize(), Fixed));
+    style->setUnique();
     updateImage();
     return style.release();
 }
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.h b/Source/core/html/shadow/PasswordGeneratorButtonElement.h
index e0853ea..0d220f9 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.h
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.h
@@ -42,10 +42,7 @@
 
 class PasswordGeneratorButtonElement FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<PasswordGeneratorButtonElement> create(Document& document)
-    {
-        return adoptRef(new PasswordGeneratorButtonElement(document));
-    }
+    static PassRefPtr<PasswordGeneratorButtonElement> create(Document&);
 
     void decorate(HTMLInputElement*);
 
diff --git a/Source/core/html/shadow/ShadowElementNames.cpp b/Source/core/html/shadow/ShadowElementNames.cpp
index 0767b85..abe60e1 100644
--- a/Source/core/html/shadow/ShadowElementNames.cpp
+++ b/Source/core/html/shadow/ShadowElementNames.cpp
@@ -59,6 +59,18 @@
     return name;
 }
 
+const AtomicString& innerEditor()
+{
+    DEFINE_STATIC_LOCAL(AtomicString, name, ("inner-editor", AtomicString::ConstructFromLiteral));
+    return name;
+}
+
+const AtomicString& passwordGenerator()
+{
+    DEFINE_STATIC_LOCAL(AtomicString, name, ("password-generator", AtomicString::ConstructFromLiteral));
+    return name;
+}
+
 const AtomicString& pickerIndicator()
 {
     DEFINE_STATIC_LOCAL(AtomicString, name, ("picker", AtomicString::ConstructFromLiteral));
diff --git a/Source/core/html/shadow/ShadowElementNames.h b/Source/core/html/shadow/ShadowElementNames.h
index a3cc5d2..46788a1 100644
--- a/Source/core/html/shadow/ShadowElementNames.h
+++ b/Source/core/html/shadow/ShadowElementNames.h
@@ -41,6 +41,8 @@
 const AtomicString& spinButton();
 const AtomicString& clearButton();
 const AtomicString& editingViewPort();
+const AtomicString& innerEditor();
+const AtomicString& passwordGenerator();
 const AtomicString& pickerIndicator();
 const AtomicString& placeholder();
 const AtomicString& searchDecoration();
diff --git a/Source/core/html/shadow/SliderThumbElement.cpp b/Source/core/html/shadow/SliderThumbElement.cpp
index cfc5578..bead464 100644
--- a/Source/core/html/shadow/SliderThumbElement.cpp
+++ b/Source/core/html/shadow/SliderThumbElement.cpp
@@ -287,16 +287,14 @@
     StepRange stepRange(input->createStepRange(RejectAny));
     Decimal value = stepRange.clampValue(stepRange.valueFromProportion(fraction));
 
-    const LayoutUnit snappingThreshold = RenderTheme::theme().sliderTickSnappingThreshold();
-    if (snappingThreshold > 0) {
-        Decimal closest = input->findClosestTickMarkValue(value);
-        if (closest.isFinite()) {
-            double closestFraction = stepRange.proportionFromValue(closest).toDouble();
-            double closestRatio = isVertical || !isLeftToRightDirection ? 1.0 - closestFraction : closestFraction;
-            LayoutUnit closestPosition = trackSize * closestRatio;
-            if ((closestPosition - position).abs() <= snappingThreshold)
-                value = closest;
-        }
+    Decimal closest = input->findClosestTickMarkValue(value);
+    if (closest.isFinite()) {
+        double closestFraction = stepRange.proportionFromValue(closest).toDouble();
+        double closestRatio = isVertical || !isLeftToRightDirection ? 1.0 - closestFraction : closestFraction;
+        LayoutUnit closestPosition = trackSize * closestRatio;
+        const LayoutUnit snappingThreshold = 5;
+        if ((closestPosition - position).abs() <= snappingThreshold)
+            value = closest;
     }
 
     String valueString = serializeForNumberType(value);
@@ -313,7 +311,7 @@
 void SliderThumbElement::startDragging()
 {
     if (Frame* frame = document().frame()) {
-        frame->eventHandler()->setCapturingMouseEventsNode(this);
+        frame->eventHandler().setCapturingMouseEventsNode(this);
         m_inDragMode = true;
     }
 }
@@ -324,7 +322,7 @@
         return;
 
     if (Frame* frame = document().frame())
-        frame->eventHandler()->setCapturingMouseEventsNode(0);
+        frame->eventHandler().setCapturingMouseEventsNode(0);
     m_inDragMode = false;
     if (renderer())
         renderer()->setNeedsLayout();
@@ -390,7 +388,7 @@
 {
     if (m_inDragMode) {
         if (Frame* frame = document().frame())
-            frame->eventHandler()->setCapturingMouseEventsNode(0);
+            frame->eventHandler().setCapturingMouseEventsNode(0);
     }
     HTMLDivElement::detach(context);
 }
diff --git a/Source/core/html/shadow/SpinButtonElement.cpp b/Source/core/html/shadow/SpinButtonElement.cpp
index 0b30118..c088512 100644
--- a/Source/core/html/shadow/SpinButtonElement.cpp
+++ b/Source/core/html/shadow/SpinButtonElement.cpp
@@ -117,7 +117,7 @@
         if (box->pixelSnappedBorderBoxRect().contains(local)) {
             if (!m_capturing) {
                 if (Frame* frame = document().frame()) {
-                    frame->eventHandler()->setCapturingMouseEventsNode(this);
+                    frame->eventHandler().setCapturingMouseEventsNode(this);
                     m_capturing = true;
                     if (Page* page = document().page())
                         page->chrome().registerPopupOpeningObserver(this);
@@ -193,7 +193,7 @@
     stopRepeatingTimer();
     if (m_capturing) {
         if (Frame* frame = document().frame()) {
-            frame->eventHandler()->setCapturingMouseEventsNode(0);
+            frame->eventHandler().setCapturingMouseEventsNode(0);
             m_capturing = false;
             if (Page* page = document().page())
                 page->chrome().unregisterPopupOpeningObserver(this);
diff --git a/Source/core/html/shadow/TextControlInnerElements.cpp b/Source/core/html/shadow/TextControlInnerElements.cpp
index ab08a53..93a28d6 100644
--- a/Source/core/html/shadow/TextControlInnerElements.cpp
+++ b/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -97,6 +97,7 @@
     // We don't want the shadow dom to be editable, so we set this block to
     // read-only in case the input itself is editable.
     style->setUserModify(READ_ONLY);
+    style->setUnique();
 
     return style.release();
 }
@@ -111,7 +112,9 @@
 
 PassRefPtr<TextControlInnerTextElement> TextControlInnerTextElement::create(Document& document)
 {
-    return adoptRef(new TextControlInnerTextElement(document));
+    RefPtr<TextControlInnerTextElement> element = adoptRef(new TextControlInnerTextElement(document));
+    element->setAttribute(idAttr, ShadowElementNames::innerEditor());
+    return element.release();
 }
 
 void TextControlInnerTextElement::defaultEventHandler(Event* event)
@@ -215,7 +218,7 @@
 {
     if (m_capturing) {
         if (Frame* frame = document().frame())
-            frame->eventHandler()->setCapturingMouseEventsNode(0);
+            frame->eventHandler().setCapturingMouseEventsNode(0);
     }
     HTMLDivElement::detach(context);
 }
@@ -234,7 +237,7 @@
     if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (renderer() && renderer()->visibleToHitTesting()) {
             if (Frame* frame = document().frame()) {
-                frame->eventHandler()->setCapturingMouseEventsNode(this);
+                frame->eventHandler().setCapturingMouseEventsNode(this);
                 m_capturing = true;
             }
         }
@@ -245,7 +248,7 @@
     if (event->type() == EventTypeNames::mouseup && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (m_capturing) {
             if (Frame* frame = document().frame()) {
-                frame->eventHandler()->setCapturingMouseEventsNode(0);
+                frame->eventHandler().setCapturingMouseEventsNode(0);
                 m_capturing = false;
             }
             if (hovered()) {
@@ -323,7 +326,7 @@
     if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (renderer() && renderer()->visibleToHitTesting()) {
             if (Frame* frame = document().frame()) {
-                frame->eventHandler()->setCapturingMouseEventsNode(this);
+                frame->eventHandler().setCapturingMouseEventsNode(this);
                 m_capturing = true;
             }
         }
@@ -336,7 +339,7 @@
     if (event->type() == EventTypeNames::mouseup && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (m_capturing && renderer() && renderer()->visibleToHitTesting()) {
             if (Frame* frame = document().frame()) {
-                frame->eventHandler()->setCapturingMouseEventsNode(0);
+                frame->eventHandler().setCapturingMouseEventsNode(0);
                 m_capturing = false;
             }
         }
@@ -435,7 +438,7 @@
 {
     if (m_capturing) {
         if (Frame* frame = document().frame())
-            frame->eventHandler()->setCapturingMouseEventsNode(0);
+            frame->eventHandler().setCapturingMouseEventsNode(0);
     }
 
     if (m_listenerId) {
diff --git a/Source/core/html/track/TextTrack.cpp b/Source/core/html/track/TextTrack.cpp
index 5e55511..bf17e6c 100644
--- a/Source/core/html/track/TextTrack.cpp
+++ b/Source/core/html/track/TextTrack.cpp
@@ -96,9 +96,9 @@
 
 TextTrack::TextTrack(Document& document, TextTrackClient* client, const AtomicString& kind, const AtomicString& label, const AtomicString& language, TextTrackType type)
     : TrackBase(TrackBase::TextTrack)
-    , m_document(&document)
     , m_cues(0)
     , m_regions(0)
+    , m_document(&document)
     , m_mediaElement(0)
     , m_label(label)
     , m_language(language)
diff --git a/Source/core/html/track/TextTrackCue.cpp b/Source/core/html/track/TextTrackCue.cpp
index 5a77269..3621d02 100644
--- a/Source/core/html/track/TextTrackCue.cpp
+++ b/Source/core/html/track/TextTrackCue.cpp
@@ -53,7 +53,6 @@
 
 static const int invalidCueIndex = -1;
 static const int undefinedPosition = -1;
-static const int autoSize = 0;
 
 static const CSSValueID displayWritingModeMap[] = {
     CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr
@@ -278,7 +277,7 @@
 {
     // NaN, Infinity and -Infinity values should trigger a TypeError.
     if (std::isinf(value) || std::isnan(value)) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return;
     }
 
@@ -295,7 +294,7 @@
 {
     // NaN, Infinity and -Infinity values should trigger a TypeError.
     if (std::isinf(value) || std::isnan(value)) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return;
     }
 
@@ -518,7 +517,7 @@
             clonedNode = node->cloneNode(false);
         parent->appendChild(clonedNode);
         if (node->isContainerNode())
-            copyWebVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode.get()));
+            copyWebVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode));
     }
 }
 
diff --git a/Source/core/html/track/TextTrackCue.h b/Source/core/html/track/TextTrackCue.h
index 6eb5b49..7fd5b9d 100644
--- a/Source/core/html/track/TextTrackCue.h
+++ b/Source/core/html/track/TextTrackCue.h
@@ -35,6 +35,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/events/EventTarget.h"
 #include "core/html/HTMLDivElement.h"
+#include "core/page/UseCounter.h"
 #include "wtf/RefCounted.h"
 
 namespace WebCore {
@@ -75,6 +76,7 @@
 public:
     static PassRefPtr<TextTrackCue> create(Document& document, double start, double end, const String& content)
     {
+        UseCounter::count(document, UseCounter::TextTrackCueConstructor);
         return adoptRef(new TextTrackCue(document, start, end, content));
     }
 
diff --git a/Source/core/html/track/TextTrackRegion.cpp b/Source/core/html/track/TextTrackRegion.cpp
index 49f6abb..8cb26a9 100644
--- a/Source/core/html/track/TextTrackRegion.cpp
+++ b/Source/core/html/track/TextTrackRegion.cpp
@@ -97,7 +97,7 @@
 void TextTrackRegion::setWidth(double value, ExceptionState& es)
 {
     if (std::isinf(value) || std::isnan(value)) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return;
     }
 
@@ -122,7 +122,7 @@
 void TextTrackRegion::setRegionAnchorX(double value, ExceptionState& es)
 {
     if (std::isinf(value) || std::isnan(value)) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return;
     }
 
@@ -137,7 +137,7 @@
 void TextTrackRegion::setRegionAnchorY(double value, ExceptionState& es)
 {
     if (std::isinf(value) || std::isnan(value)) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return;
     }
 
@@ -152,7 +152,7 @@
 void TextTrackRegion::setViewportAnchorX(double value, ExceptionState& es)
 {
     if (std::isinf(value) || std::isnan(value)) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return;
     }
 
@@ -167,7 +167,7 @@
 void TextTrackRegion::setViewportAnchorY(double value, ExceptionState& es)
 {
     if (std::isinf(value) || std::isnan(value)) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return;
     }
 
@@ -365,7 +365,6 @@
     ASSERT(m_cueContainer->contains(box));
 
     double boxHeight = box->getBoundingClientRect()->bottom() - box->getBoundingClientRect()->top();
-    float regionBottom = m_regionDisplayTree->getBoundingClientRect()->bottom();
 
     m_cueContainer->classList()->remove(textTrackCueContainerScrollingClass(), ASSERT_NO_EXCEPTION);
 
diff --git a/Source/core/html/track/WebVTTParser.h b/Source/core/html/track/WebVTTParser.h
index 796274c..60e098e 100644
--- a/Source/core/html/track/WebVTTParser.h
+++ b/Source/core/html/track/WebVTTParser.h
@@ -55,10 +55,8 @@
     virtual void fileFailedToParse() = 0;
 };
 
-class WebVTTParser {
+class WebVTTParser FINAL {
 public:
-    virtual ~WebVTTParser() { }
-
     enum ParseState {
         Initial,
         Header,
diff --git a/Source/core/injected_canvas_script_source.target.darwin-arm.mk b/Source/core/injected_canvas_script_source.target.darwin-arm.mk
index 5f7b331..31e0c51 100644
--- a/Source/core/injected_canvas_script_source.target.darwin-arm.mk
+++ b/Source/core/injected_canvas_script_source.target.darwin-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.darwin-mips.mk b/Source/core/injected_canvas_script_source.target.darwin-mips.mk
index 5f7b331..31e0c51 100644
--- a/Source/core/injected_canvas_script_source.target.darwin-mips.mk
+++ b/Source/core/injected_canvas_script_source.target.darwin-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.darwin-x86.mk b/Source/core/injected_canvas_script_source.target.darwin-x86.mk
index 5f7b331..31e0c51 100644
--- a/Source/core/injected_canvas_script_source.target.darwin-x86.mk
+++ b/Source/core/injected_canvas_script_source.target.darwin-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.linux-arm.mk b/Source/core/injected_canvas_script_source.target.linux-arm.mk
index 5f7b331..31e0c51 100644
--- a/Source/core/injected_canvas_script_source.target.linux-arm.mk
+++ b/Source/core/injected_canvas_script_source.target.linux-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.linux-mips.mk b/Source/core/injected_canvas_script_source.target.linux-mips.mk
index 5f7b331..31e0c51 100644
--- a/Source/core/injected_canvas_script_source.target.linux-mips.mk
+++ b/Source/core/injected_canvas_script_source.target.linux-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.linux-x86.mk b/Source/core/injected_canvas_script_source.target.linux-x86.mk
index 5f7b331..31e0c51 100644
--- a/Source/core/injected_canvas_script_source.target.linux-x86.mk
+++ b/Source/core/injected_canvas_script_source.target.linux-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.darwin-arm.mk b/Source/core/injected_script_source.target.darwin-arm.mk
index 3643178..0dbb44e 100644
--- a/Source/core/injected_script_source.target.darwin-arm.mk
+++ b/Source/core/injected_script_source.target.darwin-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.darwin-mips.mk b/Source/core/injected_script_source.target.darwin-mips.mk
index 3643178..0dbb44e 100644
--- a/Source/core/injected_script_source.target.darwin-mips.mk
+++ b/Source/core/injected_script_source.target.darwin-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.darwin-x86.mk b/Source/core/injected_script_source.target.darwin-x86.mk
index 3643178..0dbb44e 100644
--- a/Source/core/injected_script_source.target.darwin-x86.mk
+++ b/Source/core/injected_script_source.target.darwin-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.linux-arm.mk b/Source/core/injected_script_source.target.linux-arm.mk
index 3643178..0dbb44e 100644
--- a/Source/core/injected_script_source.target.linux-arm.mk
+++ b/Source/core/injected_script_source.target.linux-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.linux-mips.mk b/Source/core/injected_script_source.target.linux-mips.mk
index 3643178..0dbb44e 100644
--- a/Source/core/injected_script_source.target.linux-mips.mk
+++ b/Source/core/injected_script_source.target.linux-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.linux-x86.mk b/Source/core/injected_script_source.target.linux-x86.mk
index 3643178..0dbb44e 100644
--- a/Source/core/injected_script_source.target.linux-x86.mk
+++ b/Source/core/injected_script_source.target.linux-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/inspector/CodeGeneratorInspector.py b/Source/core/inspector/CodeGeneratorInspector.py
index 20122e6..163ce99 100755
--- a/Source/core/inspector/CodeGeneratorInspector.py
+++ b/Source/core/inspector/CodeGeneratorInspector.py
@@ -1281,8 +1281,8 @@
                                     for prop_data in resolve_data.main_properties + resolve_data.optional_properties:
                                         prop_name = prop_data.p["name"]
                                         prop_field_name = Capitalizer.lower_camel_case_to_upper(prop_name)
-                                        writer.newline("    static const char* %s;\n" % (prop_field_name))
-                                        cpp_writer.newline("const char* %s%s::%s = \"%s\";\n" % (helper.full_name_prefix_for_impl, class_name, prop_field_name, prop_name))
+                                        writer.newline("    static const char %s[];\n" % (prop_field_name))
+                                        cpp_writer.newline("const char %s%s::%s[] = \"%s\";\n" % (helper.full_name_prefix_for_impl, class_name, prop_field_name, prop_name))
 
 
                                 writer.newline("};\n\n")
@@ -1773,6 +1773,8 @@
     backend_method_declaration_list = []
     backend_method_implementation_list = []
     backend_method_name_declaration_list = []
+    backend_method_name_declaration_index_list = []
+    backend_method_name_declaration_current_index = 0
     method_handler_list = []
     frontend_method_list = []
 
@@ -1796,6 +1798,7 @@
             Generator.backend_method_declaration_list,
             Generator.backend_method_implementation_list,
             Generator.backend_method_name_declaration_list,
+            Generator.backend_method_name_declaration_index_list,
             Generator.backend_agent_interface_list,
             Generator.frontend_class_field_lines,
             Generator.frontend_constructor_init_list,
@@ -1921,9 +1924,11 @@
 
         if "parameters" in json_command:
             json_params = json_command["parameters"]
-            method_in_code += Templates.param_container_access_code
             request_message_param = " requestMessageObject"
 
+            if json_params:
+                method_in_code += Templates.param_container_access_code
+
             for json_parameter in json_params:
                 json_param_name = json_parameter["name"]
                 param_raw_type = resolve_param_raw_type(json_parameter, domain_name)
@@ -2063,7 +2068,10 @@
             responseCook=normal_response_cook_text,
             errorCook=error_response_cook_text,
             commandNameIndex=cmd_enum_name))
-        Generator.backend_method_name_declaration_list.append("    \"%s.%s\"," % (domain_name, json_command_name))
+        declaration_command_name = "%s.%s\\0" % (domain_name, json_command_name)
+        Generator.backend_method_name_declaration_list.append("    \"%s\"" % declaration_command_name)
+        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")
 
@@ -2307,6 +2315,7 @@
     setters="\n".join(Generator.backend_setters_list),
     fieldDeclarations="\n".join(Generator.backend_field_list),
     methodNameDeclarations="\n".join(Generator.backend_method_name_declaration_list),
+    methodNameDeclarationsIndex="\n".join(Generator.backend_method_name_declaration_index_list),
     methods="\n".join(Generator.backend_method_implementation_list),
     methodDeclarations="\n".join(Generator.backend_method_declaration_list),
     messageHandlers="\n".join(Generator.method_handler_list)))
diff --git a/Source/core/inspector/CodeGeneratorInspectorStrings.py b/Source/core/inspector/CodeGeneratorInspectorStrings.py
index e0f5262..bc3bb73 100644
--- a/Source/core/inspector/CodeGeneratorInspectorStrings.py
+++ b/Source/core/inspector/CodeGeneratorInspectorStrings.py
@@ -60,7 +60,7 @@
 
 $errorCook${responseCook}
     }
-    sendResponse(callId, result, commandNames[$commandNameIndex], protocolErrors, error, resultErrorData);
+    sendResponse(callId, result, commandName($commandNameIndex), protocolErrors, error, resultErrorData);
 }
 """)
 
@@ -196,7 +196,11 @@
         kMethodNamesEnumSize
     };
 
-    static const char* commandNames[];
+    static const char* commandName(MethodNames);
+
+private:
+    static const char commandNames[];
+    static const size_t commandNamesIndex[];
 };
 
 } // namespace WebCore
@@ -220,10 +224,18 @@
 
 namespace WebCore {
 
-const char* InspectorBackendDispatcher::commandNames[] = {
+const char InspectorBackendDispatcher::commandNames[] = {
 $methodNameDeclarations
 };
 
+const size_t InspectorBackendDispatcher::commandNamesIndex[] = {
+$methodNameDeclarationsIndex
+};
+
+const char* InspectorBackendDispatcher::commandName(MethodNames index) {
+    COMPILE_ASSERT(static_cast<int>(kMethodNamesEnumSize) == WTF_ARRAY_LENGTH(commandNamesIndex), command_name_array_problem);
+    return commandNames + commandNamesIndex[index];
+}
 
 class InspectorBackendDispatcherImpl : public InspectorBackendDispatcher {
 public:
@@ -281,9 +293,8 @@
         static CallHandler handlers[] = {
 $messageHandlers
         };
-        size_t length = WTF_ARRAY_LENGTH(commandNames);
-        for (size_t i = 0; i < length; ++i)
-            dispatchMap.add(commandNames[i], handlers[i]);
+        for (size_t i = 0; i < kMethodNamesEnumSize; ++i)
+            dispatchMap.add(commandName(static_cast<MethodNames>(i)), handlers[i]);
     }
 
     RefPtr<JSONValue> parsedMessage = parseJSON(message);
@@ -503,8 +514,6 @@
     m_alreadySent = true;
 }
 
-COMPILE_ASSERT(static_cast<int>(InspectorBackendDispatcher::kMethodNamesEnumSize) == WTF_ARRAY_LENGTH(InspectorBackendDispatcher::commandNames), command_name_array_problem);
-
 } // namespace WebCore
 
 """)
diff --git a/Source/core/inspector/ConsoleMessage.cpp b/Source/core/inspector/ConsoleMessage.cpp
index 6e3d905..e99aee8 100644
--- a/Source/core/inspector/ConsoleMessage.cpp
+++ b/Source/core/inspector/ConsoleMessage.cpp
@@ -184,6 +184,7 @@
     case LogMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Log;
     case WarningMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Warning;
     case ErrorMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Error;
+    case InfoMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Info;
     }
     return TypeBuilder::Console::ConsoleMessage::Level::Log;
 }
diff --git a/Source/core/inspector/DOMPatchSupport.cpp b/Source/core/inspector/DOMPatchSupport.cpp
index 3f62a6f..7dc4de3 100644
--- a/Source/core/inspector/DOMPatchSupport.cpp
+++ b/Source/core/inspector/DOMPatchSupport.cpp
@@ -82,8 +82,6 @@
 {
 }
 
-DOMPatchSupport::~DOMPatchSupport() { }
-
 void DOMPatchSupport::patchDocument(const String& markup)
 {
     RefPtr<Document> newDocument;
diff --git a/Source/core/inspector/DOMPatchSupport.h b/Source/core/inspector/DOMPatchSupport.h
index 4462fb5..3aa7751 100644
--- a/Source/core/inspector/DOMPatchSupport.h
+++ b/Source/core/inspector/DOMPatchSupport.h
@@ -45,13 +45,12 @@
 class ExceptionState;
 class Node;
 
-class DOMPatchSupport {
+class DOMPatchSupport FINAL {
     WTF_MAKE_NONCOPYABLE(DOMPatchSupport);
 public:
     static void patchDocument(Document&, const String& markup);
 
     DOMPatchSupport(DOMEditor*, Document&);
-    virtual ~DOMPatchSupport();
 
     void patchDocument(const String& markup);
     Node* patchNode(Node*, const String& markup, ExceptionState&);
diff --git a/Source/core/inspector/InjectedScriptSource.js b/Source/core/inspector/InjectedScriptSource.js
index 1a1791f..9dcecf2 100644
--- a/Source/core/inspector/InjectedScriptSource.js
+++ b/Source/core/inspector/InjectedScriptSource.js
@@ -408,9 +408,10 @@
         var nameProcessed = { __proto__: null };
 
         /**
+         * @param {Object} o
          * @param {Array.<string>} names
          */
-        function process(names)
+        function process(o, names)
         {
             for (var i = 0; i < names.length; ++i) {
                 var name = names[i];
@@ -454,8 +455,8 @@
 
         for (var o = object; this._isDefined(o); o = o.__proto__) {
             // First call Object.keys() to enforce ordering of the property descriptors.
-            process(Object.keys(/** @type {!Object} */ (o)));
-            process(Object.getOwnPropertyNames(/** @type {!Object} */ (o)));
+            process(o, Object.keys(/** @type {!Object} */ (o)));
+            process(o, Object.getOwnPropertyNames(/** @type {!Object} */ (o)));
 
             if (ownProperties) {
                 if (object.__proto__ && !accessorPropertiesOnly)
@@ -611,7 +612,7 @@
 
     /**
      * @param {Object} callFrame
-     * @return {Array.<InjectedScript.CallFrameProxy>|boolean}
+     * @return {!Array.<InjectedScript.CallFrameProxy>|boolean}
      */
     wrapCallFrames: function(callFrame)
     {
@@ -994,6 +995,10 @@
                 var descriptor = descriptors[i];
                 if (!descriptor)
                     continue;
+                if (descriptor.wasThrown) {
+                    preview.lossless = false;
+                    continue;
+                }
                 if (!descriptor.enumerable && !descriptor.isOwn)
                     continue;
 
@@ -1093,7 +1098,7 @@
 /**
  * @constructor
  * @param {number} ordinal
- * @param {Object} callFrame
+ * @param {!Object} callFrame
  */
 InjectedScript.CallFrameProxy = function(ordinal, callFrame)
 {
@@ -1178,7 +1183,20 @@
      */
     function customToStringMethod(name)
     {
-        return function () { return "function " + name + "() { [Command Line API] }"; };
+        return function()
+        {
+            var funcArgsSyntax = "";
+            try {
+                var funcSyntax = "" + commandLineAPIImpl[name];
+                funcSyntax = funcSyntax.replace(/\n/g, " ");
+                funcSyntax = funcSyntax.replace(/^function[^\(]*\(([^\)]*)\).*$/, "$1");
+                funcSyntax = funcSyntax.replace(/\s*,\s*/g, ", ");
+                funcSyntax = funcSyntax.replace(/\bopt_(\w+)\b/g, "[$1]");
+                funcArgsSyntax = funcSyntax.trim();
+            } catch (e) {
+            }
+            return "function " + name + "(" + funcArgsSyntax + ") { [Command Line API] }";
+        };
     }
 
     for (var i = 0; i < CommandLineAPI.members_.length; ++i) {
@@ -1202,6 +1220,7 @@
 }
 
 // NOTE: Please keep the list of API methods below snchronized to that in WebInspector.RuntimeModel!
+// NOTE: Argument names of these methods will be printed in the console, so use pretty names!
 /**
  * @type {Array.<string>}
  * @const
@@ -1222,24 +1241,24 @@
 CommandLineAPIImpl.prototype = {
     /**
      * @param {string} selector
-     * @param {Node=} start
+     * @param {Node=} opt_startNode
      */
-    $: function (selector, start)
+    $: function (selector, opt_startNode)
     {
-        if (this._canQuerySelectorOnNode(start))
-            return start.querySelector(selector);
+        if (this._canQuerySelectorOnNode(opt_startNode))
+            return opt_startNode.querySelector(selector);
 
         return inspectedWindow.document.querySelector(selector);
     },
 
     /**
      * @param {string} selector
-     * @param {Node=} start
+     * @param {Node=} opt_startNode
      */
-    $$: function (selector, start)
+    $$: function (selector, opt_startNode)
     {
-        if (this._canQuerySelectorOnNode(start))
-            return start.querySelectorAll(selector);
+        if (this._canQuerySelectorOnNode(opt_startNode))
+            return opt_startNode.querySelectorAll(selector);
         return inspectedWindow.document.querySelectorAll(selector);
     },
 
@@ -1254,12 +1273,12 @@
 
     /**
      * @param {string} xpath
-     * @param {Node=} context
+     * @param {Node=} opt_startNode
      */
-    $x: function(xpath, context)
+    $x: function(xpath, opt_startNode)
     {
-        var doc = (context && context.ownerDocument) || inspectedWindow.document;
-        var result = doc.evaluate(xpath, context || doc, null, XPathResult.ANY_TYPE, null);
+        var doc = (opt_startNode && opt_startNode.ownerDocument) || inspectedWindow.document;
+        var result = doc.evaluate(xpath, opt_startNode || doc, null, XPathResult.ANY_TYPE, null);
         switch (result.resultType) {
         case XPathResult.NUMBER_TYPE:
             return result.numberValue;
@@ -1276,12 +1295,12 @@
         }
     },
 
-    dir: function()
+    dir: function(var_args)
     {
         return inspectedWindow.console.dir.apply(inspectedWindow.console, arguments)
     },
 
-    dirxml: function()
+    dirxml: function(var_args)
     {
         return inspectedWindow.console.dirxml.apply(inspectedWindow.console, arguments)
     },
@@ -1299,25 +1318,25 @@
         return result;
     },
 
-    profile: function()
+    profile: function(opt_title)
     {
         return inspectedWindow.console.profile.apply(inspectedWindow.console, arguments)
     },
 
-    profileEnd: function()
+    profileEnd: function(opt_title)
     {
         return inspectedWindow.console.profileEnd.apply(inspectedWindow.console, arguments)
     },
 
     /**
      * @param {Object} object
-     * @param {Array.<string>|string=} types
+     * @param {Array.<string>|string=} opt_types
      */
-    monitorEvents: function(object, types)
+    monitorEvents: function(object, opt_types)
     {
         if (!object || !object.addEventListener || !object.removeEventListener)
             return;
-        types = this._normalizeEventTypes(types);
+        var types = this._normalizeEventTypes(opt_types);
         for (var i = 0; i < types.length; ++i) {
             object.removeEventListener(types[i], this._logEvent, false);
             object.addEventListener(types[i], this._logEvent, false);
@@ -1326,13 +1345,13 @@
 
     /**
      * @param {Object} object
-     * @param {Array.<string>|string=} types
+     * @param {Array.<string>|string=} opt_types
      */
-    unmonitorEvents: function(object, types)
+    unmonitorEvents: function(object, opt_types)
     {
         if (!object || !object.addEventListener || !object.removeEventListener)
             return;
-        types = this._normalizeEventTypes(types);
+        var types = this._normalizeEventTypes(opt_types);
         for (var i = 0; i < types.length; ++i)
             object.removeEventListener(types[i], this._logEvent, false);
     },
@@ -1363,10 +1382,26 @@
 
     /**
      * @param {Node} node
+     * @return {{type: string, listener: function(), useCapture: boolean, remove: function()}|undefined}
      */
     getEventListeners: function(node)
     {
-        return InjectedScriptHost.getEventListeners(node);
+        var result = InjectedScriptHost.getEventListeners(node);
+        if (!result)
+            return result;
+        /** @this {{type: string, listener: function(), useCapture: boolean}} */
+        var removeFunc = function()
+        {
+            node.removeEventListener(this.type, this.listener, this.useCapture);
+        }
+        for (var type in result) {
+            var listeners = result[type];
+            for (var i = 0, listener; listener = listeners[i]; ++i) {
+                listener["type"] = type;
+                listener["remove"] = removeFunc;
+            }
+        }
+        return result;
     },
 
     debug: function(fn)
@@ -1388,7 +1423,7 @@
         InjectedScriptHost.unmonitorFunction(fn);
     },
 
-    table: function()
+    table: function(data, opt_columns)
     {
         inspectedWindow.console.table.apply(inspectedWindow.console, arguments);
     },
diff --git a/Source/core/inspector/InspectorAgent.cpp b/Source/core/inspector/InspectorAgent.cpp
index ff1aaca..daf14ef 100644
--- a/Source/core/inspector/InspectorAgent.cpp
+++ b/Source/core/inspector/InspectorAgent.cpp
@@ -86,7 +86,7 @@
     scriptSource.append("(");
     scriptSource.appendNumber(injectedScriptId);
     scriptSource.append(")");
-    frame->script()->executeScriptInMainWorld(scriptSource.toString());
+    frame->script().executeScriptInMainWorld(scriptSource.toString());
 }
 
 void InspectorAgent::setFrontend(InspectorFrontend* inspectorFrontend)
diff --git a/Source/core/inspector/InspectorApplicationCacheAgent.cpp b/Source/core/inspector/InspectorApplicationCacheAgent.cpp
index 968b913..600ecd9 100644
--- a/Source/core/inspector/InspectorApplicationCacheAgent.cpp
+++ b/Source/core/inspector/InspectorApplicationCacheAgent.cpp
@@ -80,7 +80,7 @@
 
 void InspectorApplicationCacheAgent::updateApplicationCacheStatus(Frame* frame)
 {
-    DocumentLoader* documentLoader = frame->loader()->documentLoader();
+    DocumentLoader* documentLoader = frame->loader().documentLoader();
     if (!documentLoader)
         return;
 
@@ -102,8 +102,8 @@
     result = TypeBuilder::Array<TypeBuilder::ApplicationCache::FrameWithManifest>::create();
 
     Frame* mainFrame = m_pageAgent->mainFrame();
-    for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext(mainFrame)) {
-        DocumentLoader* documentLoader = frame->loader()->documentLoader();
+    for (Frame* frame = mainFrame; frame; frame = frame->tree().traverseNext(mainFrame)) {
+        DocumentLoader* documentLoader = frame->loader().documentLoader();
         if (!documentLoader)
             continue;
 
diff --git a/Source/core/inspector/InspectorCSSAgent.cpp b/Source/core/inspector/InspectorCSSAgent.cpp
index 75a4b93..c8eb513 100644
--- a/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/Source/core/inspector/InspectorCSSAgent.cpp
@@ -878,15 +878,19 @@
         return;
     }
 
-    // Re-read stylesheets, we know for sure we have content for all of them.
     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);
+
     if (callback)
         callback->sendSuccess();
-
-    m_instrumentingAgents->setInspectorCSSAgent(this);
 }
 
 void InspectorCSSAgent::disable(ErrorString*)
@@ -1072,14 +1076,15 @@
 
     // Matched rules.
     StyleResolver* styleResolver = element->ownerDocument()->styleResolver();
-    RefPtr<CSSRuleList> matchedRules = styleResolver->pseudoStyleRulesForElement(element, elementPseudoId, StyleResolver::AllCSSRules);
+    // FIXME:
+    RefPtr<CSSRuleList> matchedRules = styleResolver->pseudoStyleRulesForElement(element, elementPseudoId, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
     matchedCSSRules = buildArrayForMatchedRuleList(matchedRules.get(), styleResolver, 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->pseudoStyleRulesForElement(element, pseudoId, StyleResolver::AllCSSRules);
+            RefPtr<CSSRuleList> matchedRules = styleResolver->pseudoStyleRulesForElement(element, pseudoId, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
             if (matchedRules && matchedRules->length()) {
                 RefPtr<TypeBuilder::CSS::PseudoIdMatches> matches = TypeBuilder::CSS::PseudoIdMatches::create()
                     .setPseudoId(static_cast<int>(pseudoId))
@@ -1097,7 +1102,7 @@
         Element* parentElement = element->parentElement();
         while (parentElement) {
             StyleResolver* parentStyleResolver = parentElement->ownerDocument()->styleResolver();
-            RefPtr<CSSRuleList> parentMatchedRules = parentStyleResolver->styleRulesForElement(parentElement, StyleResolver::AllCSSRules);
+            RefPtr<CSSRuleList> parentMatchedRules = parentStyleResolver->styleRulesForElement(parentElement, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
             RefPtr<TypeBuilder::CSS::InheritedStyleEntry> entry = TypeBuilder::CSS::InheritedStyleEntry::create()
                 .setMatchedCSSRules(buildArrayForMatchedRuleList(parentMatchedRules.get(), styleResolver, parentElement));
             if (parentElement->style() && parentElement->style()->length()) {
@@ -1151,6 +1156,8 @@
         it.advance(run.length(), &glyphBuffer);
         for (int i = 0; i < glyphBuffer.size(); ++i) {
             String familyName = glyphBuffer.fontDataAt(i)->platformData().fontFamilyName();
+            if (familyName.isNull())
+                familyName = "";
             int value = fontStats->contains(familyName) ? fontStats->get(familyName) : 0;
             fontStats->set(familyName, value + 1);
         }
diff --git a/Source/core/inspector/InspectorCanvasAgent.cpp b/Source/core/inspector/InspectorCanvasAgent.cpp
index 4d630d3..e63481c 100644
--- a/Source/core/inspector/InspectorCanvasAgent.cpp
+++ b/Source/core/inspector/InspectorCanvasAgent.cpp
@@ -325,7 +325,7 @@
                 String frameId = m_pageAgent->frameId(frame);
                 m_frontend->traceLogsRemoved(&frameId, 0);
             }
-            frame = frame->tree()->traverseNext();
+            frame = frame->tree().traverseNext();
         }
     }
 }
diff --git a/Source/core/inspector/InspectorClient.cpp b/Source/core/inspector/InspectorClient.cpp
index 58a2cdb..bc0bcd7 100644
--- a/Source/core/inspector/InspectorClient.cpp
+++ b/Source/core/inspector/InspectorClient.cpp
@@ -47,10 +47,7 @@
     if (!frame)
         return false;
 
-    ScriptController* scriptController = frame->script();
-    if (!scriptController)
-        return false;
-    scriptController->executeScriptInMainWorld("InspectorFrontendAPI.dispatchMessageAsync(" + message + ");", ScriptController::ExecuteScriptWhenScriptsDisabled);
+    frame->script().executeScriptInMainWorld("InspectorFrontendAPI.dispatchMessageAsync(" + message + ");", ScriptController::ExecuteScriptWhenScriptsDisabled);
     return true;
 }
 
diff --git a/Source/core/inspector/InspectorClient.h b/Source/core/inspector/InspectorClient.h
index 6fd9c61..98c46e6 100644
--- a/Source/core/inspector/InspectorClient.h
+++ b/Source/core/inspector/InspectorClient.h
@@ -46,10 +46,14 @@
     virtual void clearBrowserCache() { }
     virtual void clearBrowserCookies() { }
 
+    // FIXME: remove once new API lands on both sides.
     typedef void (*TraceEventCallback)(char phase, const unsigned char*, const char* name, unsigned long long id,
         int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
         unsigned char flags);
-    virtual void setTraceEventCallback(TraceEventCallback) { }
+    typedef void (*TraceEventWithTimestampCallback)(char phase, const unsigned char*, const char* name, unsigned long long id,
+        int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
+        unsigned char flags, double timestamp);
+    virtual void setTraceEventCallback(TraceEventWithTimestampCallback) { }
 
     virtual void overrideDeviceMetrics(int /*width*/, int /*height*/, float /*deviceScaleFactor*/, bool /*fitWindow*/) { }
 
diff --git a/Source/core/inspector/InspectorController.cpp b/Source/core/inspector/InspectorController.cpp
index b72828e..9361152 100644
--- a/Source/core/inspector/InspectorController.cpp
+++ b/Source/core/inspector/InspectorController.cpp
@@ -91,7 +91,7 @@
     InspectorDOMAgent* domAgent = domAgentPtr.get();
     m_agents.append(domAgentPtr.release());
 
-    OwnPtr<InspectorResourceAgent> resourceAgentPtr(InspectorResourceAgent::create(m_instrumentingAgents.get(), pageAgent, inspectorClient, m_state.get(), m_overlay.get()));
+    OwnPtr<InspectorResourceAgent> resourceAgentPtr(InspectorResourceAgent::create(m_instrumentingAgents.get(), pageAgent, inspectorClient, m_state.get()));
     InspectorResourceAgent* resourceAgent = resourceAgentPtr.get();
     m_agents.append(resourceAgentPtr.release());
 
diff --git a/Source/core/inspector/InspectorDOMAgent.cpp b/Source/core/inspector/InspectorDOMAgent.cpp
index 9ce7afa..74afd22 100644
--- a/Source/core/inspector/InspectorDOMAgent.cpp
+++ b/Source/core/inspector/InspectorDOMAgent.cpp
@@ -286,7 +286,7 @@
 Vector<Document*> InspectorDOMAgent::documents()
 {
     Vector<Document*> result;
-    for (Frame* frame = m_document->frame(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = m_document->frame(); frame; frame = frame->tree().traverseNext()) {
         Document* document = frame->document();
         if (!document)
             continue;
diff --git a/Source/core/inspector/InspectorDOMDebuggerAgent.cpp b/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
index d8c4870..b3f7b14 100644
--- a/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
@@ -49,8 +49,8 @@
     DOMBreakpointTypesCount
 };
 
-static const char* const listenerEventCategoryType = "listener:";
-static const char* const instrumentationEventCategoryType = "instrumentation:";
+static const char listenerEventCategoryType[] = "listener:";
+static const char instrumentationEventCategoryType[] = "instrumentation:";
 
 const uint32_t inheritableDOMBreakpointTypesMask = (1 << SubtreeModified);
 const int domBreakpointDerivedTypeShift = 16;
@@ -59,15 +59,15 @@
 
 namespace WebCore {
 
-static const char* const requestAnimationFrameEventName = "requestAnimationFrame";
-static const char* const cancelAnimationFrameEventName = "cancelAnimationFrame";
-static const char* const animationFrameFiredEventName = "animationFrameFired";
-static const char* const setTimerEventName = "setTimer";
-static const char* const clearTimerEventName = "clearTimer";
-static const char* const timerFiredEventName = "timerFired";
-static const char* const webglErrorFiredEventName = "webglErrorFired";
-static const char* const webglWarningFiredEventName = "webglWarningFired";
-static const char* const webglErrorNameProperty = "webglErrorName";
+static const char requestAnimationFrameEventName[] = "requestAnimationFrame";
+static const char cancelAnimationFrameEventName[] = "cancelAnimationFrame";
+static const char animationFrameFiredEventName[] = "animationFrameFired";
+static const char setTimerEventName[] = "setTimer";
+static const char clearTimerEventName[] = "clearTimer";
+static const char timerFiredEventName[] = "timerFired";
+static const char webglErrorFiredEventName[] = "webglErrorFired";
+static const char webglWarningFiredEventName[] = "webglWarningFired";
+static const char webglErrorNameProperty[] = "webglErrorName";
 
 namespace DOMDebuggerAgentState {
 static const char eventListenerBreakpoints[] = "eventListenerBreakpoints";
diff --git a/Source/core/inspector/InspectorDebuggerAgent.cpp b/Source/core/inspector/InspectorDebuggerAgent.cpp
index 693985c..539bf17 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -75,7 +75,7 @@
 
 static const int numberOfStepsBeforeStepOut = 10;
 
-const char* InspectorDebuggerAgent::backtraceObjectGroup = "backtrace";
+const char InspectorDebuggerAgent::backtraceObjectGroup[] = "backtrace";
 
 static String breakpointIdSuffix(InspectorDebuggerAgent::BreakpointSource source)
 {
diff --git a/Source/core/inspector/InspectorDebuggerAgent.h b/Source/core/inspector/InspectorDebuggerAgent.h
index 7e56ce6..a8498a2 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.h
+++ b/Source/core/inspector/InspectorDebuggerAgent.h
@@ -68,7 +68,7 @@
         MonitorCommandBreakpointSource
     };
 
-    static const char* backtraceObjectGroup;
+    static const char backtraceObjectGroup[];
 
     virtual ~InspectorDebuggerAgent();
 
diff --git a/Source/core/inspector/InspectorFileSystemAgent.cpp b/Source/core/inspector/InspectorFileSystemAgent.cpp
index bd76696..f8bf1ae 100644
--- a/Source/core/inspector/InspectorFileSystemAgent.cpp
+++ b/Source/core/inspector/InspectorFileSystemAgent.cpp
@@ -702,7 +702,7 @@
 
 ExecutionContext* InspectorFileSystemAgent::assertExecutionContextForOrigin(ErrorString* error, SecurityOrigin* origin)
 {
-    for (Frame* frame = m_pageAgent->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = m_pageAgent->mainFrame(); frame; frame = frame->tree().traverseNext()) {
         if (frame->document() && frame->document()->securityOrigin()->isSameSchemeHostPort(origin))
             return frame->document();
     }
diff --git a/Source/core/inspector/InspectorHistory.cpp b/Source/core/inspector/InspectorHistory.cpp
index 9282e0f..1c814e5 100644
--- a/Source/core/inspector/InspectorHistory.cpp
+++ b/Source/core/inspector/InspectorHistory.cpp
@@ -83,8 +83,6 @@
 
 InspectorHistory::InspectorHistory() : m_afterLastActionIndex(0) { }
 
-InspectorHistory::~InspectorHistory() { }
-
 bool InspectorHistory::perform(PassOwnPtr<Action> action, ExceptionState& es)
 {
     if (!action->perform(es))
diff --git a/Source/core/inspector/InspectorHistory.h b/Source/core/inspector/InspectorHistory.h
index 8fb4a6d..049684e 100644
--- a/Source/core/inspector/InspectorHistory.h
+++ b/Source/core/inspector/InspectorHistory.h
@@ -39,7 +39,7 @@
 
 class ExceptionState;
 
-class InspectorHistory {
+class InspectorHistory FINAL {
     WTF_MAKE_NONCOPYABLE(InspectorHistory); WTF_MAKE_FAST_ALLOCATED;
 public:
     class Action {
@@ -63,7 +63,6 @@
     };
 
     InspectorHistory();
-    virtual ~InspectorHistory();
 
     bool perform(PassOwnPtr<Action>, ExceptionState&);
     void markUndoableState();
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.cpp b/Source/core/inspector/InspectorIndexedDBAgent.cpp
index 7689a75..3975d15 100644
--- a/Source/core/inspector/InspectorIndexedDBAgent.cpp
+++ b/Source/core/inspector/InspectorIndexedDBAgent.cpp
@@ -619,7 +619,7 @@
 
     // 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();
+    v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
 
@@ -644,7 +644,7 @@
 
     // 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();
+    v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
 
@@ -672,7 +672,7 @@
 
     // 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();
+    v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
 
@@ -776,7 +776,7 @@
 
     // 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();
+    v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
 
diff --git a/Source/core/inspector/InspectorInputAgent.cpp b/Source/core/inspector/InspectorInputAgent.cpp
index ab23f6e..01ae10d 100644
--- a/Source/core/inspector/InspectorInputAgent.cpp
+++ b/Source/core/inspector/InspectorInputAgent.cpp
@@ -269,8 +269,7 @@
         event.append(point);
     }
 
-    EventHandler* handler = m_page->mainFrame()->eventHandler();
-    handler->handleTouchEvent(event);
+    m_page->mainFrame()->eventHandler().handleTouchEvent(event);
 }
 
 void InspectorInputAgent::dispatchGestureEvent(ErrorString*, const String& type, int x, int y, const double* timestamp, const int* deltaX, const int* deltaY, const double* scale)
diff --git a/Source/core/inspector/InspectorInstrumentation.cpp b/Source/core/inspector/InspectorInstrumentation.cpp
index 49729a2..bb8f6b3 100644
--- a/Source/core/inspector/InspectorInstrumentation.cpp
+++ b/Source/core/inspector/InspectorInstrumentation.cpp
@@ -249,7 +249,6 @@
 const char Layer[] = "Layer";
 const char BeginFrame[] = "BeginFrame";
 const char UpdateLayer[] = "UpdateLayer";
-const char DrawLazyPixelRef[] = "DrawLazyPixelRef";
 };
 
 namespace InstrumentationEventArguments {
diff --git a/Source/core/inspector/InspectorInstrumentation.idl b/Source/core/inspector/InspectorInstrumentation.idl
index e743c1e..c208861 100644
--- a/Source/core/inspector/InspectorInstrumentation.idl
+++ b/Source/core/inspector/InspectorInstrumentation.idl
@@ -200,7 +200,7 @@
     void willAutosizeText([Keep] RenderObject* root);
 
     [Timeline, Inline=FastReturn]
-    void didAutosizeText(RenderObject* root);
+    void didAutosizeText([Keep] RenderObject* root);
 
     [Page, Inline=FastReturn]
     void didScroll(Page*);
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.cpp b/Source/core/inspector/InspectorLayerTreeAgent.cpp
index b91d04a..2983869 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.cpp
+++ b/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -52,10 +52,6 @@
 
 namespace WebCore {
 
-namespace LayerTreeAgentState {
-static const char layerTreeAgentEnabled[] = "layerTreeAgentEnabled";
-};
-
 inline String idForLayer(GraphicsLayer* graphicsLayer)
 {
     return String::number(graphicsLayer->platformLayer()->id());
@@ -112,6 +108,8 @@
     , m_frontend(0)
     , m_page(page)
     , m_domAgent(domAgent)
+    , m_notificationTimer(this, &InspectorLayerTreeAgent::notificationTimerFired)
+    , m_notifyAfterNextLayersUpdate(false)
 {
 }
 
@@ -132,27 +130,45 @@
 
 void InspectorLayerTreeAgent::restore()
 {
-    if (m_state->getBoolean(LayerTreeAgentState::layerTreeAgentEnabled))
-        enable(0);
+    // We do not re-enable layer agent automatically after navigation. This is because
+    // it depends on DOMAgent and node ids in particular, so we let front-end request document
+    // and re-enable the agent manually after this.
 }
 
 void InspectorLayerTreeAgent::enable(ErrorString*)
 {
-    m_state->setBoolean(LayerTreeAgentState::layerTreeAgentEnabled, true);
     m_instrumentingAgents->setInspectorLayerTreeAgent(this);
+    layerTreeDidChange();
 }
 
 void InspectorLayerTreeAgent::disable(ErrorString*)
 {
-    if (!m_state->getBoolean(LayerTreeAgentState::layerTreeAgentEnabled))
-        return;
-    m_state->setBoolean(LayerTreeAgentState::layerTreeAgentEnabled, false);
     m_instrumentingAgents->setInspectorLayerTreeAgent(0);
+    m_notificationTimer.stop();
 }
 
 void InspectorLayerTreeAgent::layerTreeDidChange()
 {
-    m_frontend->layerTreeDidChange();
+    if (m_notificationTimer.isActive())
+        return;
+    if (m_notifyAfterNextLayersUpdate) {
+        m_notifyAfterNextLayersUpdate = false;
+        m_frontend->layerTreeDidChange(buildLayerTree());
+        return;
+    }
+    const double layerTreeUpdateDelayInSeconds = 0.1;
+    m_notificationTimer.startOneShot(layerTreeUpdateDelayInSeconds);
+}
+
+void InspectorLayerTreeAgent::notificationTimerFired(Timer<InspectorLayerTreeAgent>*)
+{
+    RenderLayerCompositor* compositor = renderLayerCompositor();
+    if (compositor && compositor->compositingLayersNeedRebuild()) {
+        // Bad time for building layer tree -- let's do it as soon as it gets rebuild.
+        m_notifyAfterNextLayersUpdate = true;
+        return;
+    }
+    m_frontend->layerTreeDidChange(buildLayerTree());
 }
 
 void InspectorLayerTreeAgent::didPaint(RenderObject* renderer, GraphicsContext*, const LayoutRect& rect)
@@ -171,64 +187,46 @@
     m_frontend->layerPainted(idForLayer(graphicsLayer), domRect.release());
 }
 
-void InspectorLayerTreeAgent::getLayers(ErrorString* errorString, const int* nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
+PassRefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> > InspectorLayerTreeAgent::buildLayerTree()
 {
-    LayerIdToNodeIdMap layerIdToNodeIdMap;
-    layers = TypeBuilder::Array<TypeBuilder::LayerTree::Layer>::create();
-
     RenderLayerCompositor* compositor = renderLayerCompositor();
-    if (!compositor || !compositor->inCompositingMode()) {
-        *errorString = "Not in the compositing mode";
-        return;
-    }
-    if (!nodeId) {
-        buildLayerIdToNodeIdMap(errorString, compositor->rootRenderLayer(), layerIdToNodeIdMap);
-        gatherGraphicsLayers(compositor->rootGraphicsLayer(), layerIdToNodeIdMap, layers);
-        return;
-    }
-    Node* node = m_instrumentingAgents->inspectorDOMAgent()->nodeForId(*nodeId);
-    if (!node) {
-        *errorString = "Provided node id doesn't match any known node";
-        return;
-    }
-    RenderObject* renderer = node->renderer();
-    if (!renderer) {
-        *errorString = "Node for provided node id doesn't have a renderer";
-        return;
-    }
-    RenderLayer* enclosingLayer = renderer->enclosingLayer();
-    GraphicsLayer* enclosingGraphicsLayer = enclosingLayer->enclosingCompositingLayer()->compositedLayerMapping()->childForSuperlayers();
-    buildLayerIdToNodeIdMap(errorString, enclosingLayer, layerIdToNodeIdMap);
-    gatherGraphicsLayers(enclosingGraphicsLayer, layerIdToNodeIdMap, layers);
+    if (!compositor || !compositor->inCompositingMode())
+        return 0;
+    // Caller is responsible for only calling this when layer tree is up to date (preferrably just in the end of RenderLayerCompositor::updateCompositingLayers()
+    ASSERT(!compositor->compositingLayersNeedRebuild());
+    LayerIdToNodeIdMap layerIdToNodeIdMap;
+    RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> > layers = TypeBuilder::Array<TypeBuilder::LayerTree::Layer>::create();
+    buildLayerIdToNodeIdMap(compositor->rootRenderLayer(), layerIdToNodeIdMap);
+    gatherGraphicsLayers(compositor->rootGraphicsLayer(), layerIdToNodeIdMap, layers);
+    return layers.release();
 }
 
-void InspectorLayerTreeAgent::buildLayerIdToNodeIdMap(ErrorString* errorString, RenderLayer* root, LayerIdToNodeIdMap& layerIdToNodeIdMap)
+void InspectorLayerTreeAgent::buildLayerIdToNodeIdMap(RenderLayer* root, LayerIdToNodeIdMap& layerIdToNodeIdMap)
 {
     if (root->compositedLayerMapping()) {
         if (Node* node = root->renderer()->generatingNode()) {
             GraphicsLayer* graphicsLayer = root->compositedLayerMapping()->childForSuperlayers();
-            layerIdToNodeIdMap.set(graphicsLayer->platformLayer()->id(), idForNode(errorString, node));
+            layerIdToNodeIdMap.set(graphicsLayer->platformLayer()->id(), idForNode(node));
         }
     }
     for (RenderLayer* child = root->firstChild(); child; child = child->nextSibling())
-        buildLayerIdToNodeIdMap(errorString, child, layerIdToNodeIdMap);
+        buildLayerIdToNodeIdMap(child, layerIdToNodeIdMap);
     if (!root->renderer()->isRenderIFrame())
         return;
     FrameView* childFrameView = toFrameView(toRenderWidget(root->renderer())->widget());
     if (RenderView* childRenderView = childFrameView->renderView()) {
         if (RenderLayerCompositor* childCompositor = childRenderView->compositor())
-            buildLayerIdToNodeIdMap(errorString, childCompositor->rootRenderLayer(), layerIdToNodeIdMap);
+            buildLayerIdToNodeIdMap(childCompositor->rootRenderLayer(), layerIdToNodeIdMap);
     }
 }
 
-int InspectorLayerTreeAgent::idForNode(ErrorString* errorString, Node* node)
+int InspectorLayerTreeAgent::idForNode(Node* node)
 {
-    InspectorDOMAgent* domAgent = m_instrumentingAgents->inspectorDOMAgent();
-
-    int nodeId = domAgent->boundNodeId(node);
-    if (!nodeId)
-        nodeId = domAgent->pushNodeToFrontend(errorString, domAgent->boundNodeId(&node->document()), node);
-
+    int nodeId = m_domAgent->boundNodeId(node);
+    if (!nodeId) {
+        ErrorString ignoredError;
+        nodeId = m_domAgent->pushNodeToFrontend(&ignoredError, m_domAgent->boundNodeId(&node->document()), node);
+    }
     return nodeId;
 }
 
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.h b/Source/core/inspector/InspectorLayerTreeAgent.h
index 0640922..6e0b519 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.h
+++ b/Source/core/inspector/InspectorLayerTreeAgent.h
@@ -35,6 +35,7 @@
 #include "InspectorTypeBuilder.h"
 #include "core/inspector/InspectorBaseAgent.h"
 #include "core/rendering/RenderLayer.h"
+#include "platform/Timer.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/text/WTFString.h"
@@ -67,7 +68,6 @@
     // Called from the front-end.
     virtual void enable(ErrorString*);
     virtual void disable(ErrorString*);
-    virtual void getLayers(ErrorString*, const int* nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
     virtual void compositingReasons(ErrorString*, const String& layerId, RefPtr<TypeBuilder::Array<String> >&);
 
 private:
@@ -77,13 +77,16 @@
 
     RenderLayerCompositor* renderLayerCompositor();
     GraphicsLayer* layerById(ErrorString*, const String& layerId);
-    int idForNode(ErrorString*, Node*);
-
-    void buildLayerIdToNodeIdMap(ErrorString*, RenderLayer*, LayerIdToNodeIdMap&);
+    void notificationTimerFired(Timer<InspectorLayerTreeAgent>*);
+    PassRefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> > buildLayerTree();
+    void buildLayerIdToNodeIdMap(RenderLayer*, LayerIdToNodeIdMap&);
+    int idForNode(Node*);
 
     InspectorFrontend::LayerTree* m_frontend;
     Page* m_page;
     InspectorDOMAgent* m_domAgent;
+    Timer<InspectorLayerTreeAgent> m_notificationTimer;
+    bool m_notifyAfterNextLayersUpdate;
 
     HashMap<const RenderLayer*, String> m_documentLayerToIdMap;
 };
diff --git a/Source/core/inspector/InspectorOverlay.cpp b/Source/core/inspector/InspectorOverlay.cpp
index a9cc5b8..5724c18 100644
--- a/Source/core/inspector/InspectorOverlay.cpp
+++ b/Source/core/inspector/InspectorOverlay.cpp
@@ -248,12 +248,10 @@
     : m_page(page)
     , m_client(client)
     , m_inspectModeEnabled(false)
+    , m_overlayHost(InspectorOverlayHost::create())
     , m_drawViewSize(false)
     , m_drawViewSizeWithGrid(false)
     , m_timer(this, &InspectorOverlay::onTimer)
-    , m_overlayHost(InspectorOverlayHost::create())
-    , m_overrides(0)
-    , m_overridesTopOffset(0)
 {
 }
 
@@ -281,7 +279,7 @@
     if (isEmpty())
         return false;
 
-    return overlayPage()->mainFrame()->eventHandler()->handleGestureEvent(event);
+    return overlayPage()->mainFrame()->eventHandler().handleGestureEvent(event);
 }
 
 bool InspectorOverlay::handleMouseEvent(const PlatformMouseEvent& event)
@@ -289,17 +287,17 @@
     if (isEmpty())
         return false;
 
-    EventHandler* eventHandler = overlayPage()->mainFrame()->eventHandler();
+    EventHandler& eventHandler = overlayPage()->mainFrame()->eventHandler();
     bool result;
     switch (event.type()) {
     case PlatformEvent::MouseMoved:
-        result = eventHandler->handleMouseMoveEvent(event);
+        result = eventHandler.handleMouseMoveEvent(event);
         break;
     case PlatformEvent::MousePressed:
-        result = eventHandler->handleMousePressEvent(event);
+        result = eventHandler.handleMousePressEvent(event);
         break;
     case PlatformEvent::MouseReleased:
-        result = eventHandler->handleMouseReleaseEvent(event);
+        result = eventHandler.handleMouseReleaseEvent(event);
         break;
     default:
         return false;
@@ -314,7 +312,7 @@
     if (isEmpty())
         return false;
 
-    return overlayPage()->mainFrame()->eventHandler()->handleTouchEvent(event);
+    return overlayPage()->mainFrame()->eventHandler().handleTouchEvent(event);
 }
 
 void InspectorOverlay::drawOutline(GraphicsContext* context, const LayoutRect& rect, const Color& color)
@@ -353,25 +351,6 @@
     update();
 }
 
-void InspectorOverlay::setOverride(OverrideType type, bool enabled)
-{
-    bool currentEnabled = m_overrides & type;
-    if (currentEnabled == enabled)
-        return;
-    if (enabled)
-        m_overrides |= type;
-    else
-        m_overrides &= ~type;
-    update();
-}
-
-void InspectorOverlay::setOverridesTopOffset(int offset)
-{
-    m_overridesTopOffset = offset;
-    if (m_overrides)
-        update();
-}
-
 void InspectorOverlay::hideHighlight()
 {
     m_highlightNode.clear();
@@ -410,7 +389,7 @@
 
 bool InspectorOverlay::isEmpty()
 {
-    bool hasAlwaysVisibleElements = m_highlightNode || m_eventTargetNode || m_highlightQuad || m_overrides || !m_size.isEmpty() || m_drawViewSize;
+    bool hasAlwaysVisibleElements = m_highlightNode || m_eventTargetNode || m_highlightQuad || !m_size.isEmpty() || m_drawViewSize;
     bool hasInvisibleInInspectModeElements = !m_pausedInDebuggerMessage.isNull();
     return !(hasAlwaysVisibleElements || (hasInvisibleInInspectModeElements && !m_inspectModeEnabled));
 }
@@ -443,7 +422,6 @@
     if (!m_inspectModeEnabled)
         drawPausedInDebuggerMessage();
     drawViewSize();
-    drawOverridesMessage();
 
     // Position DOM elements.
     overlayPage()->mainFrame()->document()->recalcStyle(Force);
@@ -464,8 +442,6 @@
     m_size = IntSize();
     m_drawViewSize = false;
     m_drawViewSizeWithGrid = false;
-    m_overrides = 0;
-    m_overridesTopOffset = 0;
     update();
 }
 
@@ -600,16 +576,6 @@
         evaluateInOverlay("drawViewSize", m_drawViewSizeWithGrid ? "true" : "false");
 }
 
-void InspectorOverlay::drawOverridesMessage()
-{
-    RefPtr<JSONObject> data = JSONObject::create();
-    if (m_drawViewSize || m_highlightNode || m_highlightQuad)
-        data->setBoolean("hidden", true);
-    data->setNumber("overrides", m_overrides);
-    data->setNumber("topOffset", m_overridesTopOffset);
-    evaluateInOverlay("drawOverridesMessage", data.release());
-}
-
 Page* InspectorOverlay::overlayPage()
 {
     if (m_overlayPage)
@@ -643,16 +609,16 @@
     RefPtr<Frame> frame = Frame::create(m_overlayPage.get(), 0, dummyFrameLoaderClient);
     frame->setView(FrameView::create(frame.get()));
     frame->init();
-    FrameLoader* loader = frame->loader();
+    FrameLoader& loader = frame->loader();
     frame->view()->setCanHaveScrollbars(false);
     frame->view()->setTransparent(true);
-    ASSERT(loader->activeDocumentLoader());
-    DocumentWriter* writer = loader->activeDocumentLoader()->beginWriting("text/html", "UTF-8");
+    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);
+    loader.activeDocumentLoader()->endWriting(writer);
     v8::Isolate* isolate = toIsolate(frame.get());
     v8::HandleScope handleScope(isolate);
-    v8::Handle<v8::Context> frameContext = frame->script()->currentWorldContext();
+    v8::Handle<v8::Context> frameContext = frame->script().currentWorldContext();
     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();
@@ -687,7 +653,7 @@
     RefPtr<JSONArray> command = JSONArray::create();
     command->pushString(method);
     command->pushString(argument);
-    overlayPage()->mainFrame()->script()->executeScriptInMainWorld("dispatch(" + command->toJSONString() + ")", ScriptController::ExecuteScriptWhenScriptsDisabled);
+    overlayPage()->mainFrame()->script().executeScriptInMainWorld("dispatch(" + command->toJSONString() + ")", ScriptController::ExecuteScriptWhenScriptsDisabled);
 }
 
 void InspectorOverlay::evaluateInOverlay(const String& method, PassRefPtr<JSONValue> argument)
@@ -695,7 +661,7 @@
     RefPtr<JSONArray> command = JSONArray::create();
     command->pushString(method);
     command->pushValue(argument);
-    overlayPage()->mainFrame()->script()->executeScriptInMainWorld("dispatch(" + command->toJSONString() + ")", ScriptController::ExecuteScriptWhenScriptsDisabled);
+    overlayPage()->mainFrame()->script().executeScriptInMainWorld("dispatch(" + command->toJSONString() + ")", ScriptController::ExecuteScriptWhenScriptsDisabled);
 }
 
 void InspectorOverlay::onTimer(Timer<InspectorOverlay>*)
diff --git a/Source/core/inspector/InspectorOverlay.h b/Source/core/inspector/InspectorOverlay.h
index 303472e..151f920 100644
--- a/Source/core/inspector/InspectorOverlay.h
+++ b/Source/core/inspector/InspectorOverlay.h
@@ -29,10 +29,10 @@
 #ifndef InspectorOverlay_h
 #define InspectorOverlay_h
 
-#include "core/platform/graphics/Color.h"
 #include "platform/Timer.h"
 #include "platform/geometry/FloatQuad.h"
 #include "platform/geometry/LayoutRect.h"
+#include "platform/graphics/Color.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefPtr.h"
@@ -106,15 +106,6 @@
 class InspectorOverlay {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    // This must be kept in sync with the overrideEntries array in InspectorOverlayPage.html.
-    enum OverrideType {
-        UserAgentOverride = 1,
-        DeviceMetricsOverride = 1 << 1,
-        GeolocationOverride = 1 << 2,
-        DeviceOrientationOverride = 1 << 3,
-        TouchOverride = 1 << 4,
-        CSSMediaOverride = 1 << 5
-    };
     static PassOwnPtr<InspectorOverlay> create(Page* page, InspectorClient* client)
     {
         return adoptPtr(new InspectorOverlay(page, client));
@@ -134,8 +125,6 @@
 
     void setPausedInDebuggerMessage(const String*);
     void setInspectModeEnabled(bool);
-    void setOverride(OverrideType, bool);
-    void setOverridesTopOffset(int);
 
     void hideHighlight();
     void highlightNode(Node*, Node* eventTarget, const HighlightConfig&);
@@ -161,7 +150,6 @@
     void drawQuadHighlight();
     void drawPausedInDebuggerMessage();
     void drawViewSize();
-    void drawOverridesMessage();
 
     Page* overlayPage();
     void reset(const IntSize& viewportSize, const IntSize& frameViewFullSize, int scrollX, int scrollY);
@@ -185,8 +173,6 @@
     bool m_drawViewSize;
     bool m_drawViewSizeWithGrid;
     Timer<InspectorOverlay> m_timer;
-    unsigned m_overrides;
-    int m_overridesTopOffset;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorOverlayPage.html b/Source/core/inspector/InspectorOverlayPage.html
index adadeea..938840f 100644
--- a/Source/core/inspector/InspectorOverlayPage.html
+++ b/Source/core/inspector/InspectorOverlayPage.html
@@ -166,31 +166,6 @@
     position: absolute;
     background-color: darkgray;
 }
-
-#overrides-container {
-    display: inline-block;
-    padding: 0 0 10px 10px;
-    position: absolute;
-    top: 0;
-    right: 0;
-}
-
-#overrides-message > div:not(:first-child) {
-    text-indent: 8px;
-}
-
-#overrides-message {
-    display: inline-block;
-    font-size: 14px;
-    padding: 4px 6px;
-    color: red;
-    background-color: rgba(17, 17, 17, 0.843); /* Same as DebugColors::HUDBackgroundColor() */
-}
-
-#overrides-container:hover #overrides-message,
-#overrides-container.hidden #overrides-message {
-    visibility: hidden;
-}
 </style>
 <script>
 const lightGridColor = "rgba(0,0,0,0.2)";
@@ -198,13 +173,6 @@
 const transparentColor = "rgba(0, 0, 0, 0)";
 const gridBackgroundColor = "rgba(255, 255, 255, 0.8)";
 
-// The order must correspond to that in InspectorOverlay::OverrideType.
-const overrideEntries = ["User-Agent", "Device Metrics", "Geolocation", "Device Orientation", "Touch", "Media"];
-const overrideTouchBit = 1 << 4;
-
-var overridesContainer;
-var overridesMessageElement;
-
 function drawPausedInDebuggerMessage(message)
 {
     document.querySelector(".controls-line").style.visibility = "visible";
@@ -444,41 +412,6 @@
         _drawGrid();
 }
 
-function drawOverridesMessage(data)
-{
-    overridesContainer.style.top = data.topOffset + "px";
-    overridesMessageElement.textContent = "";
-
-    var overrides = data.overrides;
-    if (!overrides)
-        document.body.classList.remove("touch");
-    if (!overrides || data.hidden) {
-        overridesContainer.classList.add("hidden");
-        return;
-    }
-
-    var header = document.createElement("div");
-    header.id = "overrides-header";
-    header.textContent = "Overrides:";
-    overridesMessageElement.appendChild(header);
-
-    var maskBit = 1;
-    for (var i = 0; i < overrideEntries.length; ++i, maskBit <<= 1) {
-        if (!(overrides & maskBit))
-            continue;
-        var item = document.createElement("div");
-        item.textContent = overrideEntries[i];
-        overridesMessageElement.appendChild(item);
-    }
-
-    overridesContainer.classList.remove("hidden");
-    var hasTouch = overrides & overrideTouchBit;
-    if (hasTouch)
-        document.body.classList.add("touch");
-    else
-        document.body.classList.remove("touch");
-}
-
 function reset(resetData)
 {
     window.viewportSize = resetData.viewportSize;
@@ -758,31 +691,10 @@
     InspectorOverlayHost.stepOver();
 }
 
-function onMouseMotion(isOverElement)
-{
-    if (!overridesMessageElement.textContent.length)
-        return;
-    if (isOverElement)
-        overridesContainer.classList.add("hidden");
-    else
-        overridesContainer.classList.remove("hidden");
-}
-
-function onFocus()
-{
-    if (overridesMessageElement.textContent.length)
-        overridesContainer.classList.remove("hidden");
-}
-
 function onLoaded()
 {
-    overridesContainer = document.getElementById("overrides-container");
-    overridesMessageElement = document.getElementById("overrides-message");
     document.getElementById("resume-button").addEventListener("click", onResumeClick);
     document.getElementById("step-over-button").addEventListener("click", onStepOverClick);
-    overridesContainer.addEventListener("mousemove", onMouseMotion.bind(this, true));
-    overridesContainer.addEventListener("mouseout", onMouseMotion.bind(this, false));
-    window.addEventListener("focus", onFocus);
 }
 
 window.addEventListener("DOMContentLoaded", onLoaded);
@@ -803,8 +715,5 @@
 </div>
 <div id="right-gutter"></div>
 <div id="bottom-gutter"></div>
-<div id="overrides-container">
-  <div id="overrides-message"></div>
-</div>
 <div id="log"></div>
 </html>
diff --git a/Source/core/inspector/InspectorPageAgent.cpp b/Source/core/inspector/InspectorPageAgent.cpp
index bf22e05..1cab78e 100644
--- a/Source/core/inspector/InspectorPageAgent.cpp
+++ b/Source/core/inspector/InspectorPageAgent.cpp
@@ -444,7 +444,7 @@
 {
     m_pendingScriptToEvaluateOnLoadOnce = optionalScriptToEvaluateOnLoad ? *optionalScriptToEvaluateOnLoad : "";
     m_pendingScriptPreprocessor = optionalScriptPreprocessor ? *optionalScriptPreprocessor : "";
-    m_page->mainFrame()->loader()->reload(optionalIgnoreCache && *optionalIgnoreCache ? EndToEndReload : NormalReload);
+    m_page->mainFrame()->loader().reload(optionalIgnoreCache && *optionalIgnoreCache ? EndToEndReload : NormalReload);
 }
 
 void InspectorPageAgent::navigate(ErrorString*, const String& url)
@@ -452,7 +452,7 @@
     UserGestureIndicator indicator(DefinitelyProcessingNewUserGesture);
     Frame* frame = m_page->mainFrame();
     FrameLoadRequest request(frame->document()->securityOrigin(), ResourceRequest(frame->document()->completeURL(url)));
-    frame->loader()->load(request);
+    frame->loader().load(request);
 }
 
 void InspectorPageAgent::getNavigationHistory(ErrorString*, int*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::NavigationEntry> >&)
@@ -523,7 +523,7 @@
 {
     Vector<KURL> result;
 
-    result.append(urlWithoutFragment(frame->loader()->documentLoader()->url()));
+    result.append(urlWithoutFragment(frame->loader().documentLoader()->url()));
 
     Vector<Resource*> allResources = cachedResourcesForFrame(frame);
     for (Vector<Resource*>::const_iterator it = allResources.begin(); it != allResources.end(); ++it)
@@ -536,7 +536,7 @@
 {
     ListHashSet<Cookie> rawCookiesList;
 
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext(mainFrame())) {
+    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext(mainFrame())) {
         Document* document = frame->document();
         Vector<KURL> allURLs = allResourcesURLsForFrame(frame);
         for (Vector<KURL>::const_iterator it = allURLs.begin(); it != allURLs.end(); ++it) {
@@ -558,7 +558,7 @@
 void InspectorPageAgent::deleteCookie(ErrorString*, const String& cookieName, const String& url)
 {
     KURL parsedURL(ParsedURLString, url);
-    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext(m_page->mainFrame()))
+    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext(m_page->mainFrame()))
         WebCore::deleteCookie(frame->document(), parsedURL, cookieName);
 }
 
@@ -598,7 +598,7 @@
     Frame* frame = frameForId(frameId);
     KURL kurl(ParsedURLString, url);
 
-    FrameLoader* frameLoader = frame ? frame->loader() : 0;
+    FrameLoader* frameLoader = frame ? &frame->loader() : 0;
     DocumentLoader* loader = frameLoader ? frameLoader->documentLoader() : 0;
     if (!loader)
         return;
@@ -615,39 +615,6 @@
     results = ContentSearchUtils::searchInTextByLines(content, query, caseSensitive, isRegex);
 }
 
-static PassRefPtr<TypeBuilder::Page::SearchResult> buildObjectForSearchResult(const String& frameId, const String& url, int matchesCount)
-{
-    return TypeBuilder::Page::SearchResult::create()
-        .setUrl(url)
-        .setFrameId(frameId)
-        .setMatchesCount(matchesCount)
-        .release();
-}
-
-void InspectorPageAgent::searchInResources(ErrorString*, const String& text, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchResult> >& results)
-{
-    RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchResult> > searchResults = TypeBuilder::Array<TypeBuilder::Page::SearchResult>::create();
-
-    bool isRegex = optionalIsRegex ? *optionalIsRegex : false;
-    bool caseSensitive = optionalCaseSensitive ? *optionalCaseSensitive : false;
-    OwnPtr<RegularExpression> regex = ContentSearchUtils::createSearchRegex(text, caseSensitive, isRegex);
-
-    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext(m_page->mainFrame())) {
-        String content;
-        Vector<Resource*> allResources = cachedResourcesForFrame(frame);
-        for (Vector<Resource*>::const_iterator it = allResources.begin(); it != allResources.end(); ++it) {
-            Resource* cachedResource = *it;
-            if (textContentForResource(cachedResource, &content)) {
-                int matchesCount = ContentSearchUtils::countRegularExpressionMatches(regex.get(), content);
-                if (matchesCount)
-                    searchResults->addItem(buildObjectForSearchResult(frameId(frame), urlWithoutFragment(cachedResource->url()).string(), matchesCount));
-            }
-        }
-    }
-
-    results = searchResults;
-}
-
 void InspectorPageAgent::setDocumentContent(ErrorString* errorString, const String& frameId, const String& html)
 {
     Frame* frame = assertFrame(errorString, frameId);
@@ -728,8 +695,6 @@
     bool viewMetricsOverride = m_state->getLong(PageAgentState::pageAgentScreenWidthOverride);
     m_state->setBoolean(PageAgentState::pageAgentShowFPSCounter, show);
     m_client->setShowFPSCounter(show && !viewMetricsOverride);
-
-    updateOverridesTopOffset();
 }
 
 void InspectorPageAgent::setContinuousPaintingEnabled(ErrorString*, bool enabled)
@@ -737,8 +702,6 @@
     bool viewMetricsOverride = m_state->getLong(PageAgentState::pageAgentScreenWidthOverride);
     m_state->setBoolean(PageAgentState::pageAgentContinuousPaintingEnabled, enabled);
     m_client->setContinuousPaintingEnabled(enabled && !viewMetricsOverride);
-
-    updateOverridesTopOffset();
 }
 
 void InspectorPageAgent::setShowScrollBottleneckRects(ErrorString*, bool show)
@@ -753,7 +716,7 @@
     bool disabledInSettings = false;
     Frame* frame = mainFrame();
     if (frame) {
-        disabledByScriptController = !frame->script()->canExecuteScripts(NotAboutToExecuteScript);
+        disabledByScriptController = !frame->script().canExecuteScripts(NotAboutToExecuteScript);
         if (frame->settings())
             disabledInSettings = !frame->settings()->isScriptEnabled();
     }
@@ -800,11 +763,11 @@
         for (JSONObject::const_iterator it = scripts->begin(); it != end; ++it) {
             String scriptText;
             if (it->value->asString(&scriptText))
-                frame->script()->executeScriptInMainWorld(scriptText);
+                frame->script().executeScriptInMainWorld(scriptText);
         }
     }
     if (!m_scriptToEvaluateOnLoadOnce.isEmpty())
-        frame->script()->executeScriptInMainWorld(m_scriptToEvaluateOnLoadOnce);
+        frame->script().executeScriptInMainWorld(m_scriptToEvaluateOnLoadOnce);
 }
 
 void InspectorPageAgent::domContentLoadedEventFired(Frame* frame)
@@ -897,7 +860,7 @@
 
 Frame* InspectorPageAgent::findFrameWithSecurityOrigin(const String& originRawString)
 {
-    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
         RefPtr<SecurityOrigin> documentOrigin = frame->document()->securityOrigin();
         if (documentOrigin->toRawString() == originRawString)
             return frame;
@@ -936,8 +899,7 @@
 // static
 DocumentLoader* InspectorPageAgent::assertDocumentLoader(ErrorString* errorString, Frame* frame)
 {
-    FrameLoader* frameLoader = frame->loader();
-    DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
+    DocumentLoader* documentLoader = frame->loader().documentLoader();
     if (!documentLoader)
         *errorString = "No documentLoader for given frame found";
     return documentLoader;
@@ -1034,12 +996,12 @@
 {
     RefPtr<TypeBuilder::Page::Frame> frameObject = TypeBuilder::Page::Frame::create()
         .setId(frameId(frame))
-        .setLoaderId(loaderId(frame->loader()->documentLoader()))
+        .setLoaderId(loaderId(frame->loader().documentLoader()))
         .setUrl(urlWithoutFragment(frame->document()->url()).string())
-        .setMimeType(frame->loader()->documentLoader()->responseMIMEType())
+        .setMimeType(frame->loader().documentLoader()->responseMIMEType())
         .setSecurityOrigin(frame->document()->securityOrigin()->toRawString());
-    if (frame->tree()->parent())
-        frameObject->setParentId(frameId(frame->tree()->parent()));
+    if (frame->tree().parent())
+        frameObject->setParentId(frameId(frame->tree().parent()));
     if (frame->ownerElement()) {
         String name = frame->ownerElement()->getNameAttribute();
         if (name.isEmpty())
@@ -1074,7 +1036,7 @@
     }
 
     RefPtr<TypeBuilder::Array<TypeBuilder::Page::FrameResourceTree> > childrenArray;
-    for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
+    for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
         if (!childrenArray) {
             childrenArray = TypeBuilder::Array<TypeBuilder::Page::FrameResourceTree>::create();
             result->setChildFrames(childrenArray);
@@ -1101,13 +1063,11 @@
     if (document)
         document->styleResolverChanged(RecalcStyleImmediately);
     InspectorInstrumentation::mediaQueryResultChanged(document);
-    m_overlay->setOverride(InspectorOverlay::DeviceMetricsOverride, width && height);
 
     // FIXME: allow metrics override, fps counter and continuous painting at the same time: crbug.com/299837.
     bool override = width && height;
     m_client->setShowFPSCounter(m_state->getBoolean(PageAgentState::pageAgentShowFPSCounter) && !override);
     m_client->setContinuousPaintingEnabled(m_state->getBoolean(PageAgentState::pageAgentContinuousPaintingEnabled) && !override);
-    updateOverridesTopOffset();
 }
 
 void InspectorPageAgent::updateTouchEventEmulationInPage(bool enabled)
@@ -1115,22 +1075,6 @@
     m_state->setBoolean(PageAgentState::touchEventEmulationEnabled, enabled);
     if (mainFrame() && mainFrame()->settings())
         mainFrame()->settings()->setTouchEventEmulationEnabled(enabled);
-    m_overlay->setOverride(InspectorOverlay::TouchOverride, enabled);
-}
-
-void InspectorPageAgent::updateOverridesTopOffset()
-{
-    static const int continousPaintingGraphHeight = 92;
-    static const int fpsGraphHeight = 73;
-    int topOffset = 0;
-    if (m_state->getBoolean(PageAgentState::pageAgentContinuousPaintingEnabled))
-        topOffset = continousPaintingGraphHeight;
-    else if (m_state->getBoolean(PageAgentState::pageAgentShowFPSCounter))
-        topOffset = fpsGraphHeight;
-    // FIXME: allow metrics override, fps counter and continuous painting at the same time: crbug.com/299837.
-    bool setOffset = false;
-    if (setOffset)
-        m_overlay->setOverridesTopOffset(topOffset);
 }
 
 void InspectorPageAgent::setGeolocationOverride(ErrorString* error, const double* latitude, const double* longitude, const double* accuracy)
@@ -1152,7 +1096,6 @@
         m_geolocationPosition.clear();
 
     controller->positionChanged(0); // Kick location update.
-    m_overlay->setOverride(InspectorOverlay::GeolocationOverride, true);
 }
 
 void InspectorPageAgent::clearGeolocationOverride(ErrorString*)
@@ -1165,7 +1108,6 @@
     GeolocationController* controller = GeolocationController::from(m_page);
     if (controller && m_platformGeolocationPosition.get())
         controller->positionChanged(m_platformGeolocationPosition.get());
-    m_overlay->setOverride(InspectorOverlay::GeolocationOverride, false);
 }
 
 GeolocationPosition* InspectorPageAgent::overrideGeolocationPosition(GeolocationPosition* position)
@@ -1191,13 +1133,11 @@
 
     m_deviceOrientation = DeviceOrientationData::create(true, alpha, true, beta, true, gamma);
     controller->didChangeDeviceOrientation(m_deviceOrientation.get());
-    m_overlay->setOverride(InspectorOverlay::DeviceOrientationOverride, true);
 }
 
 void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString*)
 {
     m_deviceOrientation.clear();
-    m_overlay->setOverride(InspectorOverlay::DeviceOrientationOverride, false);
 }
 
 DeviceOrientationData* InspectorPageAgent::overrideDeviceOrientation(DeviceOrientationData* deviceOrientation)
@@ -1235,7 +1175,6 @@
         document->styleResolverChanged(RecalcStyleImmediately);
         document->updateLayout();
     }
-    m_overlay->setOverride(InspectorOverlay::CSSMediaOverride, !media.isEmpty());
 }
 
 void InspectorPageAgent::applyEmulatedMedia(String* media)
diff --git a/Source/core/inspector/InspectorPageAgent.h b/Source/core/inspector/InspectorPageAgent.h
index ff2a9bb..b2e3834 100644
--- a/Source/core/inspector/InspectorPageAgent.h
+++ b/Source/core/inspector/InspectorPageAgent.h
@@ -99,7 +99,6 @@
     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 searchInResources(ErrorString*, const String&, const bool* caseSensitive, const bool* isRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchResult> >&);
     virtual void setDocumentContent(ErrorString*, const String& frameId, const String& html);
     virtual void setDeviceMetricsOverride(ErrorString*, int width, int height, double deviceScaleFactor, bool fitWindow, const bool* optionalTextAutosizing);
     virtual void setShowPaintRects(ErrorString*, bool show);
@@ -187,7 +186,6 @@
     bool deviceMetricsChanged(int width, int height, double fontScaleFactor, bool fitWindow, bool textAutosizing);
     void updateViewMetrics(int width, int height, double deviceScaleFactor, bool fitWindow, bool textAutosizing);
     void updateTouchEventEmulationInPage(bool);
-    void updateOverridesTopOffset();
 
     static bool dataContent(const char* data, unsigned size, const String& textEncodingName, bool withBase64Encode, String* result);
 
diff --git a/Source/core/inspector/InspectorProfilerAgent.cpp b/Source/core/inspector/InspectorProfilerAgent.cpp
index f9ec494..13e01ae 100644
--- a/Source/core/inspector/InspectorProfilerAgent.cpp
+++ b/Source/core/inspector/InspectorProfilerAgent.cpp
@@ -52,7 +52,7 @@
 static const char profilerEnabled[] = "profilerEnabled";
 }
 
-static const char* const CPUProfileType = "CPU";
+static const char CPUProfileType[] = "CPU";
 
 PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
 {
diff --git a/Source/core/inspector/InspectorResourceAgent.cpp b/Source/core/inspector/InspectorResourceAgent.cpp
index 3ad579a..8cdc733 100644
--- a/Source/core/inspector/InspectorResourceAgent.cpp
+++ b/Source/core/inspector/InspectorResourceAgent.cpp
@@ -611,7 +611,6 @@
 void InspectorResourceAgent::setUserAgentOverride(ErrorString*, const String& userAgent)
 {
     m_state->setString(ResourceAgentState::userAgentOverride, userAgent);
-    m_overlay->setOverride(InspectorOverlay::UserAgentOverride, !userAgent.isEmpty());
 }
 
 void InspectorResourceAgent::setExtraHTTPHeaders(ErrorString*, const RefPtr<JSONObject>& headers)
@@ -787,11 +786,10 @@
     return false;
 }
 
-InspectorResourceAgent::InspectorResourceAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state, InspectorOverlay* overlay)
+InspectorResourceAgent::InspectorResourceAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state)
     : InspectorBaseAgent<InspectorResourceAgent>("Network", instrumentingAgents, state)
     , m_pageAgent(pageAgent)
     , m_client(client)
-    , m_overlay(overlay)
     , m_frontend(0)
     , m_resourcesData(adoptPtr(new NetworkResourcesData()))
     , m_isRecalculatingStyle(false)
diff --git a/Source/core/inspector/InspectorResourceAgent.h b/Source/core/inspector/InspectorResourceAgent.h
index 5d5e15c..eb079fc 100644
--- a/Source/core/inspector/InspectorResourceAgent.h
+++ b/Source/core/inspector/InspectorResourceAgent.h
@@ -53,7 +53,6 @@
 class HTTPHeaderMap;
 class InspectorClient;
 class InspectorFrontend;
-class InspectorOverlay;
 class InspectorPageAgent;
 class InstrumentingAgents;
 class JSONObject;
@@ -75,9 +74,9 @@
 
 class InspectorResourceAgent : public InspectorBaseAgent<InspectorResourceAgent>, public InspectorBackendDispatcher::NetworkCommandHandler {
 public:
-    static PassOwnPtr<InspectorResourceAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state, InspectorOverlay* overlay)
+    static PassOwnPtr<InspectorResourceAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state)
     {
-        return adoptPtr(new InspectorResourceAgent(instrumentingAgents, pageAgent, client, state, overlay));
+        return adoptPtr(new InspectorResourceAgent(instrumentingAgents, pageAgent, client, state));
     }
 
     virtual void setFrontend(InspectorFrontend*);
@@ -152,13 +151,12 @@
     bool fetchResourceContent(Frame*, const KURL&, String* content, bool* base64Encoded);
 
 private:
-    InspectorResourceAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorClient*, InspectorCompositeState*, InspectorOverlay*);
+    InspectorResourceAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorClient*, InspectorCompositeState*);
 
     void enable();
 
     InspectorPageAgent* m_pageAgent;
     InspectorClient* m_client;
-    InspectorOverlay* m_overlay;
     InspectorFrontend::Network* m_frontend;
     String m_userAgentOverride;
     OwnPtr<NetworkResourcesData> m_resourcesData;
diff --git a/Source/core/inspector/InspectorState.h b/Source/core/inspector/InspectorState.h
index 65dcc0f..d9faea7 100644
--- a/Source/core/inspector/InspectorState.h
+++ b/Source/core/inspector/InspectorState.h
@@ -46,11 +46,10 @@
     virtual void inspectorStateUpdated() = 0;
 };
 
-class InspectorState {
+class InspectorState FINAL {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     InspectorState(InspectorStateUpdateListener*, PassRefPtr<JSONObject>);
-    virtual ~InspectorState() {}
 
     void loadFromCookie(const String& inspectorStateCookie);
 
diff --git a/Source/core/inspector/InspectorStyleSheet.cpp b/Source/core/inspector/InspectorStyleSheet.cpp
index 4d8546d..d1b88da 100644
--- a/Source/core/inspector/InspectorStyleSheet.cpp
+++ b/Source/core/inspector/InspectorStyleSheet.cpp
@@ -508,10 +508,6 @@
     ASSERT(m_style);
 }
 
-InspectorStyle::~InspectorStyle()
-{
-}
-
 PassRefPtr<TypeBuilder::CSS::CSSStyle> InspectorStyle::buildObjectForStyle() const
 {
     RefPtr<TypeBuilder::CSS::CSSStyle> result = styleWithProperties();
diff --git a/Source/core/inspector/InspectorStyleSheet.h b/Source/core/inspector/InspectorStyleSheet.h
index 96d4001..d5100f3 100644
--- a/Source/core/inspector/InspectorStyleSheet.h
+++ b/Source/core/inspector/InspectorStyleSheet.h
@@ -129,10 +129,9 @@
     String rawText;
 };
 
-class InspectorStyle : public RefCounted<InspectorStyle> {
+class InspectorStyle FINAL : public RefCounted<InspectorStyle> {
 public:
     static PassRefPtr<InspectorStyle> create(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheet* parentStyleSheet);
-    virtual ~InspectorStyle();
 
     CSSStyleDeclaration* cssStyle() const { return m_style.get(); }
     PassRefPtr<TypeBuilder::CSS::CSSStyle> buildObjectForStyle() const;
diff --git a/Source/core/inspector/InspectorTimelineAgent.cpp b/Source/core/inspector/InspectorTimelineAgent.cpp
index d794294..41db918 100644
--- a/Source/core/inspector/InspectorTimelineAgent.cpp
+++ b/Source/core/inspector/InspectorTimelineAgent.cpp
@@ -49,7 +49,6 @@
 #include "core/inspector/TimelineTraceEventProcessor.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/page/PageConsole.h"
-#include "core/platform/MemoryUsageSupport.h"
 #include "core/platform/graphics/chromium/DeferredImageDecoder.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderView.h"
@@ -401,8 +400,13 @@
     pushCurrentRecord(TimelineRecordFactory::createNodeData(nodeId(renderer)), TimelineRecordType::AutosizeText, false, renderer->frame());
 }
 
-void InspectorTimelineAgent::didAutosizeText()
+void InspectorTimelineAgent::didAutosizeText(RenderObject* renderer)
 {
+    if (renderer->needsLayout()) {
+        TimelineRecordEntry& entry = m_recordStack.last();
+        ASSERT(entry.type == TimelineRecordType::AutosizeText);
+        entry.data->setBoolean("needsRelayout", true);
+    }
     didCompleteCurrentRecord(TimelineRecordType::AutosizeText);
 }
 
diff --git a/Source/core/inspector/InspectorTimelineAgent.h b/Source/core/inspector/InspectorTimelineAgent.h
index 81b51be..419ed08 100644
--- a/Source/core/inspector/InspectorTimelineAgent.h
+++ b/Source/core/inspector/InspectorTimelineAgent.h
@@ -146,7 +146,7 @@
     void didLayout(RenderObject*);
 
     void willAutosizeText(RenderObject*);
-    void didAutosizeText();
+    void didAutosizeText(RenderObject*);
 
     void didScheduleStyleRecalculation(Document*);
     bool willRecalculateStyle(Document*);
diff --git a/Source/core/inspector/PageRuntimeAgent.cpp b/Source/core/inspector/PageRuntimeAgent.cpp
index aa8bac6..dd62995 100644
--- a/Source/core/inspector/PageRuntimeAgent.cpp
+++ b/Source/core/inspector/PageRuntimeAgent.cpp
@@ -161,14 +161,14 @@
 void PageRuntimeAgent::reportExecutionContextCreation()
 {
     Vector<std::pair<ScriptState*, SecurityOrigin*> > isolatedContexts;
-    for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
-        if (!frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+    for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+        if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
             continue;
         String frameId = m_pageAgent->frameId(frame);
 
         ScriptState* scriptState = mainWorldScriptState(frame);
         notifyContextCreated(frameId, scriptState, 0, true);
-        frame->script()->collectIsolatedContexts(isolatedContexts);
+        frame->script().collectIsolatedContexts(isolatedContexts);
         if (isolatedContexts.isEmpty())
             continue;
         for (size_t i = 0; i< isolatedContexts.size(); i++)
diff --git a/Source/core/inspector/ScriptProfile.h b/Source/core/inspector/ScriptProfile.h
index ba14b98..0a99d89 100644
--- a/Source/core/inspector/ScriptProfile.h
+++ b/Source/core/inspector/ScriptProfile.h
@@ -41,13 +41,13 @@
 
 namespace WebCore {
 
-class ScriptProfile : public RefCounted<ScriptProfile> {
+class ScriptProfile FINAL : public RefCounted<ScriptProfile> {
 public:
     static PassRefPtr<ScriptProfile> create(const v8::CpuProfile* profile, double idleTime)
     {
         return adoptRef(new ScriptProfile(profile, idleTime));
     }
-    virtual ~ScriptProfile();
+    ~ScriptProfile();
 
     String title() const;
     unsigned int uid() const;
diff --git a/Source/core/inspector/TimelineTraceEventProcessor.cpp b/Source/core/inspector/TimelineTraceEventProcessor.cpp
index f57f09c..4554d1e 100644
--- a/Source/core/inspector/TimelineTraceEventProcessor.cpp
+++ b/Source/core/inspector/TimelineTraceEventProcessor.cpp
@@ -83,7 +83,7 @@
 
     static void dispatchEventOnAnyThread(char phase, const unsigned char*, const char* name, unsigned long long id,
         int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
-        unsigned char flags)
+        unsigned char flags, double timestamp)
     {
         TraceEventDispatcher* self = instance();
         Vector<RefPtr<TimelineTraceEventProcessor> > processors;
@@ -92,7 +92,7 @@
             processors = self->m_processors;
         }
         for (int i = 0, size = processors.size(); i < size; ++i)
-            processors[i]->processEventOnAnyThread(phase, name, id, numArgs, argNames, argTypes, argValues, flags);
+            processors[i]->processEventOnAnyThread(timestamp, phase, name, id, numArgs, argNames, argTypes, argValues, flags);
     }
 
     Mutex m_mutex;
@@ -154,11 +154,11 @@
     , m_inspectorClient(client)
     , m_pageId(reinterpret_cast<unsigned long long>(m_timelineAgent.get()->page()))
     , m_layerTreeId(m_timelineAgent.get()->layerTreeId())
+    , m_lastEventProcessingTime(0)
+    , m_processEventsTaskInFlight(false)
     , m_layerId(0)
     , m_paintSetupStart(0)
     , m_paintSetupEnd(0)
-    , m_lastEventProcessingTime(0)
-    , m_processEventsTaskInFlight(false)
 {
     registerHandler(InstrumentationEvents::BeginFrame, TRACE_EVENT_PHASE_INSTANT, &TimelineTraceEventProcessor::onBeginFrame);
     registerHandler(InstrumentationEvents::UpdateLayer, TRACE_EVENT_PHASE_BEGIN, &TimelineTraceEventProcessor::onUpdateLayerBegin);
@@ -215,7 +215,7 @@
     return *reinterpret_cast<const WebCore::TraceEvent::TraceValueUnion*>(m_argumentValues + index);
 }
 
-void TimelineTraceEventProcessor::processEventOnAnyThread(char phase, const char* name, unsigned long long id,
+void TimelineTraceEventProcessor::processEventOnAnyThread(double timestamp, char phase, const char* name, unsigned long long id,
     int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
     unsigned char)
 {
@@ -223,7 +223,6 @@
     if (it == m_handlersByType.end())
         return;
 
-    double timestamp = WTF::monotonicallyIncreasingTime();
     TraceEvent event(timestamp, phase, name, id, currentThread(), numArgs, argNames, argTypes, argValues);
 
     if (!isMainThread()) {
@@ -250,7 +249,7 @@
 void TimelineTraceEventProcessor::onUpdateLayerBegin(const TraceEvent& event)
 {
     unsigned long long layerTreeId = event.asUInt(InstrumentationEventArguments::LayerTreeId);
-    if (layerTreeId != m_layerTreeId)
+    if (layerTreeId != static_cast<unsigned long long>(m_layerTreeId))
         return;
     m_layerId = event.asUInt(InstrumentationEventArguments::LayerId);
     // We don't know the node yet. For content layers, the node will be updated
diff --git a/Source/core/inspector/TimelineTraceEventProcessor.h b/Source/core/inspector/TimelineTraceEventProcessor.h
index d9a470f..8b4d99d 100644
--- a/Source/core/inspector/TimelineTraceEventProcessor.h
+++ b/Source/core/inspector/TimelineTraceEventProcessor.h
@@ -85,7 +85,7 @@
     ~TimelineTraceEventProcessor();
 
     void shutdown();
-    void processEventOnAnyThread(char, const char* name, unsigned long long id,
+    void processEventOnAnyThread(double timestamp, char, const char* name, unsigned long long id,
         int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
         unsigned char flags);
 
diff --git a/Source/core/inspector/WorkerDebuggerAgent.cpp b/Source/core/inspector/WorkerDebuggerAgent.cpp
index 0af72ef..271c306 100644
--- a/Source/core/inspector/WorkerDebuggerAgent.cpp
+++ b/Source/core/inspector/WorkerDebuggerAgent.cpp
@@ -76,7 +76,7 @@
 
 } // namespace
 
-const char* WorkerDebuggerAgent::debuggerTaskMode = "debugger";
+const char WorkerDebuggerAgent::debuggerTaskMode[] = "debugger";
 
 PassOwnPtr<WorkerDebuggerAgent> WorkerDebuggerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, WorkerScriptDebugServer* scriptDebugServer, WorkerGlobalScope* inspectedWorkerGlobalScope, InjectedScriptManager* injectedScriptManager)
 {
diff --git a/Source/core/inspector/WorkerDebuggerAgent.h b/Source/core/inspector/WorkerDebuggerAgent.h
index 3974ade..dee9dbf 100644
--- a/Source/core/inspector/WorkerDebuggerAgent.h
+++ b/Source/core/inspector/WorkerDebuggerAgent.h
@@ -46,7 +46,7 @@
     static PassOwnPtr<WorkerDebuggerAgent> create(InstrumentingAgents*, InspectorCompositeState*, WorkerScriptDebugServer*, WorkerGlobalScope*, InjectedScriptManager*);
     virtual ~WorkerDebuggerAgent();
 
-    static const char* debuggerTaskMode;
+    static const char debuggerTaskMode[];
     static void interruptAndDispatchInspectorCommands(WorkerThread*);
 
 private:
diff --git a/Source/core/inspector_overlay_page.target.darwin-arm.mk b/Source/core/inspector_overlay_page.target.darwin-arm.mk
index d871016..32c8f37 100644
--- a/Source/core/inspector_overlay_page.target.darwin-arm.mk
+++ b/Source/core/inspector_overlay_page.target.darwin-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.darwin-mips.mk b/Source/core/inspector_overlay_page.target.darwin-mips.mk
index d871016..32c8f37 100644
--- a/Source/core/inspector_overlay_page.target.darwin-mips.mk
+++ b/Source/core/inspector_overlay_page.target.darwin-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.darwin-x86.mk b/Source/core/inspector_overlay_page.target.darwin-x86.mk
index d871016..32c8f37 100644
--- a/Source/core/inspector_overlay_page.target.darwin-x86.mk
+++ b/Source/core/inspector_overlay_page.target.darwin-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.linux-arm.mk b/Source/core/inspector_overlay_page.target.linux-arm.mk
index d871016..32c8f37 100644
--- a/Source/core/inspector_overlay_page.target.linux-arm.mk
+++ b/Source/core/inspector_overlay_page.target.linux-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.linux-mips.mk b/Source/core/inspector_overlay_page.target.linux-mips.mk
index d871016..32c8f37 100644
--- a/Source/core/inspector_overlay_page.target.linux-mips.mk
+++ b/Source/core/inspector_overlay_page.target.linux-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.linux-x86.mk b/Source/core/inspector_overlay_page.target.linux-x86.mk
index d871016..32c8f37 100644
--- a/Source/core/inspector_overlay_page.target.linux-x86.mk
+++ b/Source/core/inspector_overlay_page.target.linux-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/xxd.py $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl ../build/scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/loader/CookieJar.cpp b/Source/core/loader/CookieJar.cpp
index 79d6b54..df33648 100644
--- a/Source/core/loader/CookieJar.cpp
+++ b/Source/core/loader/CookieJar.cpp
@@ -47,7 +47,7 @@
 {
     if (!document || !document->frame())
         return 0;
-    WebKit::WebCookieJar* cookieJar = document->frame()->loader()->client()->cookieJar();
+    WebKit::WebCookieJar* cookieJar = document->frame()->loader().client()->cookieJar();
     // FIXME: DRT depends on being able to get a cookie jar from Platform rather than
     // FrameLoaderClient. Delete this when DRT is deleted.
     if (!cookieJar)
diff --git a/Source/core/loader/DocumentLoader.cpp b/Source/core/loader/DocumentLoader.cpp
index da758d7..027bb01 100644
--- a/Source/core/loader/DocumentLoader.cpp
+++ b/Source/core/loader/DocumentLoader.cpp
@@ -31,7 +31,6 @@
 #include "core/loader/DocumentLoader.h"
 
 #include "FetchInitiatorTypeNames.h"
-#include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentParser.h"
 #include "core/events/Event.h"
@@ -45,7 +44,6 @@
 #include "core/loader/DocumentWriter.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/SinkDocument.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
 #include "core/loader/archive/ArchiveResourceCollection.h"
@@ -96,7 +94,7 @@
 {
     if (!m_frame)
         return 0;
-    return m_frame->loader();
+    return &m_frame->loader();
 }
 
 ResourceLoader* DocumentLoader::mainResourceLoader() const
@@ -128,7 +126,7 @@
 
 Document* DocumentLoader::document() const
 {
-    if (m_frame && m_frame->loader()->documentLoader() == this)
+    if (m_frame && m_frame->loader().documentLoader() == this)
         return m_frame->document();
     return 0;
 }
@@ -226,7 +224,7 @@
         Document* doc = m_frame->document();
 
         if (loading || doc->parsing())
-            m_frame->loader()->stopLoading();
+            m_frame->loader().stopLoading();
     }
 
     clearArchiveResources();
@@ -440,9 +438,9 @@
     if (newRequest.cachePolicy() == UseProtocolCachePolicy && isRedirectAfterPost(newRequest, redirectResponse))
         newRequest.setCachePolicy(ReloadIgnoringCacheData);
 
-    Frame* parent = m_frame->tree()->parent();
+    Frame* parent = m_frame->tree().parent();
     if (parent) {
-        if (!parent->loader()->mixedContentChecker()->canRunInsecureContent(parent->document()->securityOrigin(), newRequest.url())) {
+        if (!parent->loader().mixedContentChecker()->canRunInsecureContent(parent->document()->securityOrigin(), newRequest.url())) {
             cancelMainResourceLoad(ResourceError::cancelledError(newRequest.url()));
             return;
         }
@@ -568,7 +566,6 @@
         return;
 
     String encoding = overrideEncoding().isNull() ? response().textEncodingName().impl() : overrideEncoding();
-    bool userChosen = !overrideEncoding().isNull();
     m_writer = createWriterFor(m_frame, 0, requestURL(), mimeType, encoding, false, false);
     m_writer->setDocumentWasLoadedAsPartOfNavigation();
     // This should be set before receivedFirstData().
@@ -721,14 +718,14 @@
 
 void DocumentLoader::prepareSubframeArchiveLoadIfNeeded()
 {
-    if (!m_frame->tree()->parent())
+    if (!m_frame->tree().parent())
         return;
 
-    ArchiveResourceCollection* parentCollection = m_frame->tree()->parent()->loader()->documentLoader()->m_archiveResourceCollection.get();
+    ArchiveResourceCollection* parentCollection = m_frame->tree().parent()->loader().documentLoader()->m_archiveResourceCollection.get();
     if (!parentCollection)
         return;
 
-    m_archive = parentCollection->popSubframeArchive(m_frame->tree()->uniqueName(), m_request.url());
+    m_archive = parentCollection->popSubframeArchive(m_frame->tree().uniqueName(), m_request.url());
 
     if (!m_archive)
         return;
@@ -894,15 +891,21 @@
 {
     // Create a new document before clearing the frame, because it may need to
     // inherit an aliased security context.
-    RefPtr<Document> document = DOMImplementation::createDocument(mimeType, frame, url, frame->inViewSourceMode());
-    if (document->isPluginDocument() && document->isSandboxed(SandboxPlugins))
-        document = SinkDocument::create(DocumentInit(url, frame));
-    bool shouldReuseDefaultView = frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument() && frame->document()->isSecureTransitionTo(url);
+    DocumentInit init(url, frame);
+
+    // 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
+    // synchronously but kicks off the load in the window asynchronously. Web sites
+    // expect that modifications that they make to the window object synchronously
+    // won't be blown away when the network load commits. To make that happen, we
+    // "securely transition" the existing DOMWindow to the Document that results from
+    // 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(options);
 
     if (frame->document())
         frame->document()->prepareForDestruction();
@@ -910,15 +913,14 @@
     if (!shouldReuseDefaultView)
         frame->setDOMWindow(DOMWindow::create(frame));
 
-    frame->loader()->setOutgoingReferrer(url);
-    frame->domWindow()->setDocument(document);
-
+    frame->loader().setOutgoingReferrer(url);
+    RefPtr<Document> document = frame->domWindow()->installNewDocument(mimeType, init);
     if (ownerDocument) {
         document->setCookieURL(ownerDocument->cookieURL());
         document->setSecurityOrigin(ownerDocument->securityOrigin());
     }
 
-    frame->loader()->didBeginDocument(dispatch);
+    frame->loader().didBeginDocument(dispatch);
 
     return DocumentWriter::create(document.get(), mimeType, encoding, userChosen);
 }
@@ -935,7 +937,7 @@
 // This is the <iframe src="javascript:'html'"> case.
 void DocumentLoader::replaceDocument(const String& source, Document* ownerDocument)
 {
-    m_frame->loader()->stopAllLoaders();
+    m_frame->loader().stopAllLoaders();
     m_writer = createWriterFor(m_frame, ownerDocument, m_frame->document()->url(), mimeType(), m_writer ? m_writer->encoding() : "",  m_writer ? m_writer->encodingWasChosenByUser() : false, true);
     if (!source.isNull())
         m_writer->appendReplacingData(source);
diff --git a/Source/core/loader/DocumentThreadableLoader.cpp b/Source/core/loader/DocumentThreadableLoader.cpp
index 6dc1486..97bf370 100644
--- a/Source/core/loader/DocumentThreadableLoader.cpp
+++ b/Source/core/loader/DocumentThreadableLoader.cpp
@@ -209,7 +209,7 @@
     // original request was not same-origin.
     if (m_options.crossOriginRequestPolicy == UseAccessControl) {
 
-        InspectorInstrumentation::didReceiveCORSRedirectResponse(m_document->frame(), resource->identifier(), m_document->frame()->loader()->documentLoader(), redirectResponse, 0);
+        InspectorInstrumentation::didReceiveCORSRedirectResponse(m_document->frame(), resource->identifier(), m_document->frame()->loader().documentLoader(), redirectResponse, 0);
 
         bool allowRedirect = false;
         String accessControlErrorDescription;
@@ -286,7 +286,7 @@
 
     String accessControlErrorDescription;
     if (m_actualRequest) {
-        DocumentLoader* loader = m_document->frame()->loader()->documentLoader();
+        DocumentLoader* loader = m_document->frame()->loader().documentLoader();
         InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_document->frame(), identifier, response);
         InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, loader, response, m_resource ? m_resource->loader() : 0);
 
@@ -356,7 +356,7 @@
 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
 {
     if (m_actualRequest) {
-        InspectorInstrumentation::didFinishLoading(m_document->frame(), identifier, m_document->frame()->loader()->documentLoader(), finishTime);
+        InspectorInstrumentation::didFinishLoading(m_document->frame(), identifier, m_document->frame()->loader().documentLoader(), finishTime);
         ASSERT(!m_sameOriginRequest);
         ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
         preflightSuccess();
@@ -367,7 +367,7 @@
 void DocumentThreadableLoader::didFail(unsigned long identifier, const ResourceError& error)
 {
     if (m_actualRequest)
-        InspectorInstrumentation::didFailLoading(m_document->frame(), identifier, m_document->frame()->loader()->documentLoader(), error);
+        InspectorInstrumentation::didFailLoading(m_document->frame(), identifier, m_document->frame()->loader().documentLoader(), error);
 
     m_client->didFail(error);
 }
@@ -401,7 +401,7 @@
 {
     ResourceError error(errorDomainWebKitInternal, 0, url, errorDescription);
     if (m_actualRequest)
-        InspectorInstrumentation::didFailLoading(m_document->frame(), identifier, m_document->frame()->loader()->documentLoader(), error);
+        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);
 }
diff --git a/Source/core/loader/FrameFetchContext.cpp b/Source/core/loader/FrameFetchContext.cpp
index 68bf77d..885d1e8 100644
--- a/Source/core/loader/FrameFetchContext.cpp
+++ b/Source/core/loader/FrameFetchContext.cpp
@@ -57,14 +57,14 @@
 {
     bool isMainResource = type == Resource::MainResource;
 
-    FrameLoader* frameLoader = m_frame->loader();
+    FrameLoader& frameLoader = m_frame->loader();
 
     if (!isMainResource) {
         String outgoingReferrer;
         String outgoingOrigin;
         if (request.httpReferrer().isNull()) {
-            outgoingReferrer = frameLoader->outgoingReferrer();
-            outgoingOrigin = frameLoader->outgoingOrigin();
+            outgoingReferrer = frameLoader.outgoingReferrer();
+            outgoingOrigin = frameLoader.outgoingOrigin();
         } else {
             outgoingReferrer = request.httpReferrer();
             outgoingOrigin = SecurityOrigin::createFromString(outgoingReferrer)->toString();
@@ -79,15 +79,15 @@
         FrameLoader::addHTTPOriginIfNeeded(request, outgoingOrigin);
     }
 
-    frameLoader->addExtraFieldsToRequest(request);
+    frameLoader.addExtraFieldsToRequest(request);
 }
 
 CachePolicy FrameFetchContext::cachePolicy(Resource::Type type) const
 {
     if (type != Resource::MainResource)
-        return m_frame->loader()->subresourceCachePolicy();
+        return m_frame->loader().subresourceCachePolicy();
 
-    if (m_frame->loader()->loadType() == FrameLoadTypeReloadFromOrigin || m_frame->loader()->loadType() == FrameLoadTypeReload)
+    if (m_frame->loader().loadType() == FrameLoadTypeReloadFromOrigin || m_frame->loader().loadType() == FrameLoadTypeReload)
         return CachePolicyReload;
     return CachePolicyVerify;
 
@@ -99,24 +99,24 @@
 // cannot see imported documents.
 inline DocumentLoader* FrameFetchContext::ensureLoader(DocumentLoader* loader)
 {
-    return loader ? loader : m_frame->loader()->activeDocumentLoader();
+    return loader ? loader : m_frame->loader().activeDocumentLoader();
 }
 
 void FrameFetchContext::dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority loadPriority)
 {
-    m_frame->loader()->client()->dispatchDidChangeResourcePriority(identifier, loadPriority);
+    m_frame->loader().client()->dispatchDidChangeResourcePriority(identifier, loadPriority);
 }
 
 void FrameFetchContext::dispatchWillSendRequest(DocumentLoader* loader, unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& initiatorInfo)
 {
-    m_frame->loader()->applyUserAgent(request);
-    m_frame->loader()->client()->dispatchWillSendRequest(loader, identifier, request, redirectResponse);
+    m_frame->loader().applyUserAgent(request);
+    m_frame->loader().client()->dispatchWillSendRequest(loader, identifier, request, redirectResponse);
     InspectorInstrumentation::willSendRequest(m_frame, identifier, ensureLoader(loader), request, redirectResponse, initiatorInfo);
 }
 
 void FrameFetchContext::dispatchDidLoadResourceFromMemoryCache(const ResourceRequest& request, const ResourceResponse& response)
 {
-    m_frame->loader()->client()->dispatchDidLoadResourceFromMemoryCache(request, response);
+    m_frame->loader().client()->dispatchDidLoadResourceFromMemoryCache(request, response);
 }
 
 void FrameFetchContext::dispatchDidReceiveResponse(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, ResourceLoader* resourceLoader)
@@ -124,7 +124,7 @@
     if (Page* page = m_frame->page())
         page->progress().incrementProgress(identifier, r);
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_frame, identifier, r);
-    m_frame->loader()->client()->dispatchDidReceiveResponse(loader, identifier, r);
+    m_frame->loader().client()->dispatchDidReceiveResponse(loader, identifier, r);
     InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, ensureLoader(loader), r, resourceLoader);
 }
 
@@ -139,7 +139,7 @@
 {
     if (Page* page = m_frame->page())
         page->progress().completeProgress(identifier);
-    m_frame->loader()->client()->dispatchDidFinishLoading(loader, identifier);
+    m_frame->loader().client()->dispatchDidFinishLoading(loader, identifier);
 
     InspectorInstrumentation::didFinishLoading(m_frame, identifier, ensureLoader(loader), finishTime);
 }
diff --git a/Source/core/loader/FrameLoader.cpp b/Source/core/loader/FrameLoader.cpp
index ae5d510..4b3db84 100644
--- a/Source/core/loader/FrameLoader.cpp
+++ b/Source/core/loader/FrameLoader.cpp
@@ -155,10 +155,10 @@
     , m_client(client)
     , m_history(frame)
     , m_icon(adoptPtr(new IconController(frame)))
-    , m_fetchContext(FrameFetchContext::create(frame))
     , m_mixedContentChecker(frame)
     , m_state(FrameStateProvisional)
     , m_loadType(FrameLoadTypeStandard)
+    , m_fetchContext(FrameFetchContext::create(frame))
     , m_inStopAllLoaders(false)
     , m_isComplete(false)
     , m_containsPlugins(false)
@@ -179,7 +179,7 @@
 
     HashSet<Frame*>::iterator end = m_openedFrames.end();
     for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
-        (*it)->loader()->m_opener = 0;
+        (*it)->loader().m_opener = 0;
 
     m_client->frameLoaderDestroyed();
 }
@@ -206,7 +206,7 @@
     history()->setDefersLoading(defers);
 
     if (!defers) {
-        m_frame->navigationScheduler()->startTimer();
+        m_frame->navigationScheduler().startTimer();
         startCheckCompleteTimer();
     }
 }
@@ -230,7 +230,7 @@
     }
 
     // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
-    m_frame->navigationScheduler()->cancel();
+    m_frame->navigationScheduler().cancel();
 }
 
 bool FrameLoader::closeURL()
@@ -258,7 +258,7 @@
     // from a subsequent window.document.open / window.document.write call.
     // Canceling redirection here works for all cases because document.open
     // implicitly precedes document.write.
-    m_frame->navigationScheduler()->cancel();
+    m_frame->navigationScheduler().cancel();
 }
 
 void FrameLoader::clear(ClearOptions options)
@@ -275,11 +275,11 @@
     if (options & ClearWindowProperties) {
         InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame->domWindow());
         m_frame->domWindow()->reset();
-        m_frame->script()->clearWindowShell();
+        m_frame->script().clearWindowShell();
     }
 
     m_frame->selection().prepareForDestruction();
-    m_frame->eventHandler()->clear();
+    m_frame->eventHandler().clear();
     if (m_frame->view())
         m_frame->view()->clear();
 
@@ -292,11 +292,11 @@
     m_containsPlugins = false;
 
     if (options & ClearScriptObjects)
-        m_frame->script()->clearScriptObjects();
+        m_frame->script().clearScriptObjects();
 
-    m_frame->script()->enableEval();
+    m_frame->script().enableEval();
 
-    m_frame->navigationScheduler()->clear();
+    m_frame->navigationScheduler().clear();
 
     m_checkTimer.stop();
     m_shouldCallCheckCompleted = false;
@@ -329,7 +329,7 @@
     m_frame->document()->setReadyState(Document::Loading);
 
     if (history()->currentItem() && m_loadType == FrameLoadTypeBackForward)
-        m_frame->document()->statePopped(history()->currentItem()->stateObject());
+        m_frame->domWindow()->statePopped(history()->currentItem()->stateObject());
 
     if (dispatch)
         dispatchDidClearWindowObjectsInAllWorlds();
@@ -390,8 +390,8 @@
 
 bool FrameLoader::allChildrenAreComplete() const
 {
-    for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
-        if (!child->loader()->m_isComplete)
+    for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
+        if (!child->loader().m_isComplete)
             return false;
     }
     return true;
@@ -399,7 +399,7 @@
 
 bool FrameLoader::allAncestorsAreComplete() const
 {
-    for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
+    for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree().parent()) {
         if (!ancestor->document()->loadEventFinished())
             return false;
     }
@@ -440,7 +440,7 @@
     if (m_frame->document()->loadEventStillNeeded())
         m_frame->document()->implicitClose();
 
-    m_frame->navigationScheduler()->startTimer();
+    m_frame->navigationScheduler().startTimer();
 
     completed();
     if (m_frame->page())
@@ -483,12 +483,12 @@
     // for why we walk the parent chain for srcdoc documents.
     Frame* frame = m_frame;
     while (frame->document()->isSrcdocDocument()) {
-        frame = frame->tree()->parent();
+        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;
+    return frame->loader().m_outgoingReferrer;
 }
 
 String FrameLoader::outgoingOrigin() const
@@ -507,9 +507,9 @@
         m_client->didDisownOpener();
 
     if (m_opener)
-        m_opener->loader()->m_openedFrames.remove(m_frame);
+        m_opener->loader().m_openedFrames.remove(m_frame);
     if (opener)
-        opener->loader()->m_openedFrames.add(m_frame);
+        opener->loader().m_openedFrames.add(m_frame);
     m_opener = opener;
 
     if (m_frame->document())
@@ -578,8 +578,8 @@
     // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
     bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
     if (hashChange) {
-        m_frame->eventHandler()->stopAutoscrollTimer();
-        m_frame->document()->enqueueHashchangeEvent(oldURL, url);
+        m_frame->eventHandler().stopAutoscrollTimer();
+        m_frame->domWindow()->enqueueHashchangeEvent(oldURL, url);
     }
     m_documentLoader->setIsClientRedirect((m_startingClientRedirect && !isNewNavigation) || !UserGestureIndicator::processingUserGesture());
     m_documentLoader->setReplacesCurrentHistoryItem(!isNewNavigation);
@@ -597,18 +597,18 @@
     m_isComplete = false;
     checkCompleted();
 
-    m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
+    m_frame->domWindow()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
 }
 
 void FrameLoader::completed()
 {
     RefPtr<Frame> protect(m_frame);
 
-    for (Frame* descendant = m_frame->tree()->traverseNext(m_frame); descendant; descendant = descendant->tree()->traverseNext(m_frame))
-        descendant->navigationScheduler()->startTimer();
+    for (Frame* descendant = m_frame->tree().traverseNext(m_frame); descendant; descendant = descendant->tree().traverseNext(m_frame))
+        descendant->navigationScheduler().startTimer();
 
-    if (Frame* parent = m_frame->tree()->parent())
-        parent->loader()->checkCompleted();
+    if (Frame* parent = m_frame->tree().parent())
+        parent->loader().checkCompleted();
 
     if (m_frame->view())
         m_frame->view()->maintainScrollPositionAtAnchor(0);
@@ -616,8 +616,8 @@
 
 void FrameLoader::started()
 {
-    for (Frame* frame = m_frame; frame; frame = frame->tree()->parent())
-        frame->loader()->m_isComplete = false;
+    for (Frame* frame = m_frame; frame; frame = frame->tree().parent())
+        frame->loader().m_isComplete = false;
 }
 
 void FrameLoader::prepareForHistoryNavigation()
@@ -656,16 +656,16 @@
     // If this is a child frame and the form submission was triggered by a script, lock the back/forward list
     // to match IE and Opera.
     // See https://bugs.webkit.org/show_bug.cgi?id=32383 for the original motivation for this.
-    if (!m_frame->tree()->parent() || UserGestureIndicator::processingUserGesture())
+    if (!m_frame->tree().parent() || UserGestureIndicator::processingUserGesture())
         return false;
     return request.formState() && request.formState()->formSubmissionTrigger() == SubmittedByJavaScript;
 }
 
 FrameLoadType FrameLoader::determineFrameLoadType(const FrameLoadRequest& request)
 {
-    if (m_frame->tree()->parent() && !m_stateMachine.startedFirstRealLoad())
+    if (m_frame->tree().parent() && !m_stateMachine.startedFirstRealLoad())
         return FrameLoadTypeInitialInChildFrame;
-    if (!m_frame->tree()->parent() && !history()->currentItem())
+    if (!m_frame->tree().parent() && !history()->currentItem())
         return FrameLoadTypeStandard;
     if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
         return FrameLoadTypeReload;
@@ -685,7 +685,7 @@
         return true;
 
     KURL url = request.resourceRequest().url();
-    if (m_frame->script()->executeScriptIfJavaScriptURL(url))
+    if (m_frame->script().executeScriptIfJavaScriptURL(url))
         return false;
 
     if (!request.requester()->canDisplay(url)) {
@@ -733,7 +733,7 @@
     RefPtr<Frame> targetFrame = findFrameForNavigation(request.frameName(), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
     if (targetFrame && targetFrame != m_frame) {
         request.setFrameName("_self");
-        targetFrame->loader()->load(request);
+        targetFrame->loader().load(request);
         if (Page* page = targetFrame->page())
             page->chrome().focus();
         return;
@@ -818,8 +818,8 @@
 
     m_inStopAllLoaders = true;
 
-    for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
-        child->loader()->stopAllLoaders();
+    for (RefPtr<Frame> child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
+        child->loader().stopAllLoaders();
     if (m_provisionalDocumentLoader)
         m_provisionalDocumentLoader->stopLoading();
     if (m_documentLoader)
@@ -910,7 +910,7 @@
     history()->updateForCommit();
     m_client->transitionToCommittedForNewPage();
 
-    m_frame->navigationScheduler()->cancel();
+    m_frame->navigationScheduler().cancel();
     m_frame->editor().clearLastEditCommand();
 
     // If we are still in the process of initializing an empty document then
@@ -929,8 +929,8 @@
     // 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();
+    for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
+        child->loader().closeOldDataSources();
 
     if (m_documentLoader)
         m_client->dispatchWillClose();
@@ -945,15 +945,15 @@
 bool FrameLoader::subframeIsLoading() const
 {
     // It's most likely that the last added frame is the last to load so we walk backwards.
-    for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling()) {
-        FrameLoader* childLoader = child->loader();
-        DocumentLoader* documentLoader = childLoader->documentLoader();
+    for (Frame* child = m_frame->tree().lastChild(); child; child = child->tree().previousSibling()) {
+        const FrameLoader& childLoader = child->loader();
+        DocumentLoader* documentLoader = childLoader.documentLoader();
         if (documentLoader && documentLoader->isLoadingInAPISense())
             return true;
-        documentLoader = childLoader->provisionalDocumentLoader();
+        documentLoader = childLoader.provisionalDocumentLoader();
         if (documentLoader && documentLoader->isLoadingInAPISense())
             return true;
-        documentLoader = childLoader->policyDocumentLoader();
+        documentLoader = childLoader.policyDocumentLoader();
         if (documentLoader)
             return true;
     }
@@ -973,8 +973,8 @@
     if (m_loadType == FrameLoadTypeReloadFromOrigin)
         return CachePolicyReload;
 
-    if (Frame* parentFrame = m_frame->tree()->parent()) {
-        CachePolicy parentCachePolicy = parentFrame->loader()->subresourceCachePolicy();
+    if (Frame* parentFrame = m_frame->tree().parent()) {
+        CachePolicy parentCachePolicy = parentFrame->loader().subresourceCachePolicy();
         if (parentCachePolicy != CachePolicyVerify)
             return parentCachePolicy;
     }
@@ -1049,17 +1049,17 @@
 {
     typedef Vector<RefPtr<Frame> > FrameVector;
     FrameVector childrenToDetach;
-    childrenToDetach.reserveCapacity(m_frame->tree()->childCount());
-    for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling())
+    childrenToDetach.reserveCapacity(m_frame->tree().childCount());
+    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++)
-        (*it)->loader()->detachFromParent();
+        (*it)->loader().detachFromParent();
 }
 
 void FrameLoader::closeAndRemoveChild(Frame* child)
 {
-    child->tree()->detachFromParent();
+    child->tree().detachFromParent();
 
     child->setView(0);
     if (child->ownerElement() && child->page())
@@ -1067,7 +1067,7 @@
     child->willDetachPage();
     child->detachFromPage();
 
-    m_frame->tree()->removeChild(child);
+    m_frame->tree().removeChild(child);
 }
 
 // Called every time a resource is completely loaded or an error is received.
@@ -1079,11 +1079,11 @@
     // is currently needed in order to null out the previous history item for all frames.
     if (Page* page = m_frame->page()) {
         Vector<RefPtr<Frame>, 10> frames;
-        for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
+        for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
             frames.append(frame);
         // To process children before their parents, iterate the vector backwards.
         for (size_t i = frames.size(); i; --i)
-            frames[i - 1]->loader()->checkLoadCompleteForThisFrame();
+            frames[i - 1]->loader().checkLoadCompleteForThisFrame();
     }
 }
 
@@ -1100,7 +1100,7 @@
         return m_frame->document()->fetcher()->requestCount();
 
     int count = 0;
-    for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
+    for (Frame* frame = m_frame; frame; frame = frame->tree().traverseNext(m_frame))
         count += frame->document()->fetcher()->requestCount();
     return count;
 }
@@ -1141,9 +1141,9 @@
 
     m_progressTracker.clear();
 
-    if (Frame* parent = m_frame->tree()->parent()) {
-        parent->loader()->closeAndRemoveChild(m_frame);
-        parent->loader()->scheduleCheckCompleted();
+    if (Frame* parent = m_frame->tree().parent()) {
+        parent->loader().closeAndRemoveChild(m_frame);
+        parent->loader().scheduleCheckCompleted();
     } else {
         m_frame->setView(0);
         m_frame->willDetachPage();
@@ -1296,7 +1296,7 @@
     // Store all references to each subframe in advance since beforeunload's event handler may modify frame
     Vector<RefPtr<Frame> > targetFrames;
     targetFrames.append(m_frame);
-    for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame))
+    for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().traverseNext(m_frame))
         targetFrames.append(child);
 
     bool shouldClose = false;
@@ -1304,10 +1304,11 @@
         NavigationDisablerForBeforeUnload navigationDisabler;
         size_t i;
 
+        bool didAllowNavigation = false;
         for (i = 0; i < targetFrames.size(); i++) {
-            if (!targetFrames[i]->tree()->isDescendantOf(m_frame))
+            if (!targetFrames[i]->tree().isDescendantOf(m_frame))
                 continue;
-            if (!targetFrames[i]->document()->dispatchBeforeUnloadEvent(page->chrome(), m_frame->document()))
+            if (!targetFrames[i]->document()->dispatchBeforeUnloadEvent(page->chrome(), didAllowNavigation))
                 break;
         }
 
@@ -1348,8 +1349,8 @@
     m_policyDocumentLoader->setReplacesCurrentHistoryItem(replacesCurrentHistoryItem);
     m_policyDocumentLoader->setIsClientRedirect(m_startingClientRedirect);
 
-    if (Frame* parent = m_frame->tree()->parent())
-        m_policyDocumentLoader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
+    if (Frame* parent = m_frame->tree().parent())
+        m_policyDocumentLoader->setOverrideEncoding(parent->loader().documentLoader()->overrideEncoding());
     else if (!overrideEncoding.isEmpty())
         m_policyDocumentLoader->setOverrideEncoding(overrideEncoding);
     else if (m_documentLoader)
@@ -1373,7 +1374,7 @@
 
     if (isLoadingMainFrame())
         m_frame->page()->inspectorController().resume();
-    m_frame->navigationScheduler()->cancel();
+    m_frame->navigationScheduler().cancel();
 
     m_provisionalDocumentLoader = m_policyDocumentLoader.release();
     m_loadType = type;
@@ -1425,18 +1426,18 @@
     }
 
     if (frameName != "_blank")
-        mainFrame->tree()->setName(frameName);
+        mainFrame->tree().setName(frameName);
 
     mainFrame->page()->setOpenedByDOM();
     mainFrame->page()->chrome().show(navigationPolicy);
     if (!m_suppressOpenerInNewFrame) {
-        mainFrame->loader()->setOpener(frame.get());
+        mainFrame->loader().setOpener(frame.get());
         mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
     }
 
     // FIXME: We can't just send our NavigationAction to the new FrameLoader's loadWithNavigationAction(), we need to
     // create a new one with a default NavigationType and no triggering event. We should figure out why.
-    mainFrame->loader()->loadWithNavigationAction(action.resourceRequest(), NavigationAction(action.resourceRequest()), FrameLoadTypeStandard, formState, SubstituteData());
+    mainFrame->loader().loadWithNavigationAction(action.resourceRequest(), NavigationAction(action.resourceRequest()), FrameLoadTypeStandard, formState, SubstituteData());
 }
 
 void FrameLoader::applyUserAgent(ResourceRequest& request)
@@ -1450,7 +1451,7 @@
 {
     UseCounter::count(m_frame->domWindow(), UseCounter::XFrameOptions);
 
-    Frame* topFrame = m_frame->tree()->top();
+    Frame* topFrame = m_frame->tree().top();
     if (m_frame == topFrame)
         return false;
 
@@ -1462,7 +1463,7 @@
         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()) {
+        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);
                 return true;
@@ -1508,7 +1509,7 @@
 Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* activeDocument)
 {
     ASSERT(activeDocument);
-    Frame* frame = m_frame->tree()->find(name);
+    Frame* frame = m_frame->tree().find(name);
 
     // From http://www.whatwg.org/specs/web-apps/current-work/#seamlessLinks:
     //
@@ -1520,7 +1521,7 @@
     // 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()) {
+        for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree().parent()) {
             if (!ancestor->document()->shouldDisplaySeamlesslyWithParent()) {
                 frame = ancestor;
                 break;
@@ -1574,7 +1575,7 @@
 
 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
 {
-    if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+    if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript))
         return;
 
     Vector<RefPtr<DOMWrapperWorld> > worlds;
@@ -1585,7 +1586,7 @@
 
 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
 {
-    if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script()->existingWindowShell(world))
+    if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script().existingWindowShell(world))
         return;
 
     m_client->dispatchDidClearWindowObjectInWorld(world);
@@ -1599,7 +1600,7 @@
 SandboxFlags FrameLoader::effectiveSandboxFlags() const
 {
     SandboxFlags flags = m_forcedSandboxFlags;
-    if (Frame* parentFrame = m_frame->tree()->parent())
+    if (Frame* parentFrame = m_frame->tree().parent())
         flags |= parentFrame->document()->sandboxFlags();
     if (HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement())
         flags |= ownerElement->sandboxFlags();
diff --git a/Source/core/loader/HistoryController.cpp b/Source/core/loader/HistoryController.cpp
index a506ffd..51edac6 100644
--- a/Source/core/loader/HistoryController.cpp
+++ b/Source/core/loader/HistoryController.cpp
@@ -80,7 +80,7 @@
 */
 void HistoryController::restoreScrollPositionAndViewState()
 {
-    if (!m_currentItem || !m_frame->loader()->stateMachine()->committedFirstRealDocumentLoad())
+    if (!m_currentItem || !m_frame->loader().stateMachine()->committedFirstRealDocumentLoad())
         return;
 
     if (FrameView* view = m_frame->view()) {
@@ -113,7 +113,7 @@
     ASSERT(document);
 
     if (m_currentItem->isCurrentDocument(document) && document->isActive()) {
-        LOG(Loading, "WebCoreLoading %s: saving form state to %p", m_frame->tree()->uniqueName().string().utf8().data(), m_currentItem.get());
+        LOG(Loading, "WebCoreLoading %s: saving form state to %p", m_frame->tree().uniqueName().string().utf8().data(), m_currentItem.get());
         m_currentItem->setDocumentState(document->formElementsState());
     }
 
@@ -129,7 +129,7 @@
 
 void HistoryController::restoreDocumentState()
 {
-    if (m_currentItem && m_frame->loader()->loadType() == FrameLoadTypeBackForward)
+    if (m_currentItem && m_frame->loader().loadType() == FrameLoadTypeBackForward)
         m_frame->document()->setStateForNewFormElements(m_currentItem->documentState());
 }
 
@@ -145,7 +145,7 @@
 // This includes recursion to handle loading into framesets properly
 void HistoryController::goToItem(HistoryItem* targetItem)
 {
-    ASSERT(!m_frame->tree()->parent());
+    ASSERT(!m_frame->tree().parent());
 
     // shouldGoToHistoryItem is a private delegate method. This is needed to fix:
     // <rdar://problem/3951283> can view pages from the back/forward cache that should be disallowed by Parental Controls
@@ -181,8 +181,8 @@
 
 void HistoryController::clearProvisionalItemsInAllFrames()
 {
-    for (RefPtr<Frame> frame = m_frame->page()->mainFrame(); frame; frame = frame->tree()->traverseNext())
-        frame->loader()->history()->m_provisionalItem = 0;
+    for (RefPtr<Frame> frame = m_frame->page()->mainFrame(); frame; frame = frame->tree().traverseNext())
+        frame->loader().history()->m_provisionalItem = 0;
 }
 
 // There are 2 things you might think of as "history", all of which are handled by these functions.
@@ -192,25 +192,25 @@
 //
 void HistoryController::updateForStandardLoad()
 {
-    LOG(History, "WebCoreHistory: Updating History for Standard Load in frame %s", m_frame->loader()->documentLoader()->url().string().ascii().data());
+    LOG(History, "WebCoreHistory: Updating History for Standard Load in frame %s", m_frame->loader().documentLoader()->url().string().ascii().data());
     createNewBackForwardItem(true);
 }
 
 void HistoryController::updateForInitialLoadInChildFrame()
 {
-    Frame* parentFrame = m_frame->tree()->parent();
-    if (parentFrame && parentFrame->loader()->history()->m_currentItem)
-        parentFrame->loader()->history()->m_currentItem->setChildItem(createItem());
+    Frame* parentFrame = m_frame->tree().parent();
+    if (parentFrame && parentFrame->loader().history()->m_currentItem)
+        parentFrame->loader().history()->m_currentItem->setChildItem(createItem());
 }
 
 void HistoryController::updateForCommit()
 {
-    FrameLoader* frameLoader = m_frame->loader();
+    FrameLoader& frameLoader = m_frame->loader();
 #if !LOG_DISABLED
     if (m_frame->document())
         LOG(History, "WebCoreHistory: Updating History for commit in frame %s", m_frame->document()->title().utf8().data());
 #endif
-    FrameLoadType type = frameLoader->loadType();
+    FrameLoadType type = frameLoader.loadType();
     if (isBackForwardLoadType(type)) {
         // Once committed, we want to use current item for saving DocState, and
         // the provisional item for restoring state.
@@ -226,7 +226,7 @@
         // committed) and its children (which will be replaced).
         Page* page = m_frame->page();
         ASSERT(page);
-        page->mainFrame()->loader()->history()->recursiveUpdateForCommit();
+        page->mainFrame()->loader().history()->recursiveUpdateForCommit();
     } else if (type != FrameLoadTypeRedirectWithLockedBackForwardList) {
         m_provisionalItem = 0;
     }
@@ -263,8 +263,8 @@
     }
 
     // Iterate over the rest of the tree
-    for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
-        child->loader()->history()->recursiveUpdateForCommit();
+    for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
+        child->loader().history()->recursiveUpdateForCommit();
 }
 
 void HistoryController::updateForSameDocumentNavigation()
@@ -276,7 +276,7 @@
     if (!page)
         return;
 
-    page->mainFrame()->loader()->history()->recursiveUpdateForSameDocumentNavigation();
+    page->mainFrame()->loader().history()->recursiveUpdateForSameDocumentNavigation();
 
     if (m_currentItem)
         m_currentItem->setURL(m_frame->document()->url());
@@ -300,8 +300,8 @@
     m_provisionalItem = 0;
 
     // Iterate over the rest of the tree.
-    for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
-        child->loader()->history()->recursiveUpdateForSameDocumentNavigation();
+    for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
+        child->loader().history()->recursiveUpdateForSameDocumentNavigation();
 }
 
 void HistoryController::setCurrentItem(HistoryItem* item)
@@ -326,7 +326,7 @@
 
 void HistoryController::initializeItem(HistoryItem* item)
 {
-    DocumentLoader* documentLoader = m_frame->loader()->documentLoader();
+    DocumentLoader* documentLoader = m_frame->loader().documentLoader();
     ASSERT(documentLoader);
 
     KURL unreachableURL = documentLoader->unreachableURL();
@@ -352,11 +352,11 @@
     if (originalURL.isEmpty())
         originalURL = blankURL();
 
-    Frame* parentFrame = m_frame->tree()->parent();
-    String parent = parentFrame ? parentFrame->tree()->uniqueName() : "";
+    Frame* parentFrame = m_frame->tree().parent();
+    String parent = parentFrame ? parentFrame->tree().uniqueName() : "";
 
     item->setURL(url);
-    item->setTarget(m_frame->tree()->uniqueName());
+    item->setTarget(m_frame->tree().uniqueName());
     item->setOriginalURLString(originalURL.string());
 
     // Save form state if this is a POST
@@ -390,13 +390,13 @@
             bfItem->setDocumentSequenceNumber(m_previousItem->documentSequenceNumber());
         }
 
-        for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
+        for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
             // If the child is a frame corresponding to an <object> element that never loaded,
             // we don't want to create a history item, because that causes fallback content
             // to be ignored on reload.
-            FrameLoader* childLoader = child->loader();
-            if (childLoader->stateMachine()->startedFirstRealLoad() || !child->ownerElement()->isObjectElement())
-                bfItem->addChildItem(childLoader->history()->createItemTree(targetFrame, clipAtTarget));
+            FrameLoader& childLoader = child->loader();
+            if (childLoader.stateMachine()->startedFirstRealLoad() || !child->ownerElement()->isObjectElement())
+                bfItem->addChildItem(childLoader.history()->createItemTree(targetFrame, clipAtTarget));
         }
     }
     return bfItem;
@@ -422,9 +422,9 @@
             String childFrameName = childItems[i]->target();
             HistoryItem* fromChildItem = fromItem->childItemWithTarget(childFrameName);
             ASSERT(fromChildItem);
-            Frame* childFrame = m_frame->tree()->child(childFrameName);
+            Frame* childFrame = m_frame->tree().child(childFrameName);
             ASSERT(childFrame);
-            childFrame->loader()->history()->recursiveSetProvisionalItem(childItems[i].get(), fromChildItem);
+            childFrame->loader().history()->recursiveSetProvisionalItem(childItems[i].get(), fromChildItem);
         }
     }
 }
@@ -444,12 +444,12 @@
             String childFrameName = childItems[i]->target();
             HistoryItem* fromChildItem = fromItem->childItemWithTarget(childFrameName);
             ASSERT(fromChildItem);
-            Frame* childFrame = m_frame->tree()->child(childFrameName);
+            Frame* childFrame = m_frame->tree().child(childFrameName);
             ASSERT(childFrame);
-            childFrame->loader()->history()->recursiveGoToItem(childItems[i].get(), fromChildItem);
+            childFrame->loader().history()->recursiveGoToItem(childItems[i].get(), fromChildItem);
         }
     } else {
-        m_frame->loader()->loadHistoryItem(item);
+        m_frame->loader().loadHistoryItem(item);
     }
 }
 
@@ -473,16 +473,16 @@
 // Helper method that determines whether the current frame tree matches given history item's.
 bool HistoryController::currentFramesMatchItem(HistoryItem* item) const
 {
-    if ((!m_frame->tree()->uniqueName().isEmpty() || !item->target().isEmpty()) && m_frame->tree()->uniqueName() != item->target())
+    if ((!m_frame->tree().uniqueName().isEmpty() || !item->target().isEmpty()) && m_frame->tree().uniqueName() != item->target())
         return false;
 
     const HistoryItemVector& childItems = item->children();
-    if (childItems.size() != m_frame->tree()->childCount())
+    if (childItems.size() != m_frame->tree().childCount())
         return false;
 
     unsigned size = childItems.size();
     for (unsigned i = 0; i < size; ++i) {
-        if (!m_frame->tree()->child(childItems[i]->target()))
+        if (!m_frame->tree().child(childItems[i]->target()))
             return false;
     }
 
@@ -500,14 +500,14 @@
     if (!page)
         return;
 
-    if (!m_frame->loader()->documentLoader()->isURLValidForNewHistoryEntry())
+    if (!m_frame->loader().documentLoader()->isURLValidForNewHistoryEntry())
         return;
 
     Frame* mainFrame = page->mainFrame();
     ASSERT(mainFrame);
 
-    RefPtr<HistoryItem> topItem = mainFrame->loader()->history()->createItemTree(m_frame, doClip);
-    LOG(BackForward, "WebCoreBackForward - Adding backforward item %p for frame %s", topItem.get(), m_frame->loader()->documentLoader()->url().string().ascii().data());
+    RefPtr<HistoryItem> topItem = mainFrame->loader().history()->createItemTree(m_frame, doClip);
+    LOG(BackForward, "WebCoreBackForward - Adding backforward item %p for frame %s", topItem.get(), m_frame->loader().documentLoader()->url().string().ascii().data());
 }
 
 void HistoryController::updateWithoutCreatingNewBackForwardItem()
@@ -515,7 +515,7 @@
     if (!m_currentItem)
         return;
 
-    DocumentLoader* documentLoader = m_frame->loader()->documentLoader();
+    DocumentLoader* documentLoader = m_frame->loader().documentLoader();
 
     if (!documentLoader->unreachableURL().isEmpty())
         return;
@@ -538,7 +538,7 @@
     ASSERT(page);
 
     // Get a HistoryItem tree for the current frame tree.
-    RefPtr<HistoryItem> topItem = page->mainFrame()->loader()->history()->createItemTree(m_frame, false);
+    RefPtr<HistoryItem> topItem = page->mainFrame()->loader().history()->createItemTree(m_frame, false);
 
     // Override data in the current item (created by createItemTree) to reflect
     // the pushState() arguments.
diff --git a/Source/core/loader/IconController.cpp b/Source/core/loader/IconController.cpp
index ed5189e..9061432 100644
--- a/Source/core/loader/IconController.cpp
+++ b/Source/core/loader/IconController.cpp
@@ -72,7 +72,7 @@
 IconURLs IconController::urlsForTypes(int iconTypesMask)
 {
     IconURLs iconURLs;
-    if (m_frame->tree() && m_frame->tree()->parent())
+    if (m_frame->tree().parent())
         return iconURLs;
 
     if (iconTypesMask & Favicon && !appendToIconURLs(Favicon, &iconURLs))
diff --git a/Source/core/loader/LinkLoader.cpp b/Source/core/loader/LinkLoader.cpp
index 359f0b3..41881d5 100644
--- a/Source/core/loader/LinkLoader.cpp
+++ b/Source/core/loader/LinkLoader.cpp
@@ -37,9 +37,8 @@
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/html/LinkRelAttribute.h"
-#include "core/loader/Prerenderer.h"
+#include "core/loader/PrerenderHandle.h"
 #include "core/page/Settings.h"
-#include "core/platform/Prerender.h"
 #include "platform/network/DNS.h"
 
 namespace WebCore {
@@ -55,8 +54,6 @@
 {
     if (m_cachedLinkResource)
         m_cachedLinkResource->removeClient(this);
-    if (m_prerender)
-        m_prerender->removeClient();
 }
 
 void LinkLoader::linkLoadTimerFired(Timer<LinkLoader>* timer)
@@ -130,16 +127,14 @@
 
     if (relAttribute.isLinkPrerender()) {
         if (!m_prerender) {
-            m_prerender = Prerenderer::from(&document)->render(this, href);
+            m_prerender = PrerenderHandle::create(document, this, href);
         } else if (m_prerender->url() != href) {
             m_prerender->cancel();
-            m_prerender->removeClient();
-            m_prerender = Prerenderer::from(&document)->render(this, href);
+            m_prerender = PrerenderHandle::create(document, this, href);
         }
     } else if (m_prerender) {
         m_prerender->cancel();
-        m_prerender->removeClient();
-        m_prerender = 0;
+        m_prerender.clear();
     }
     return true;
 }
@@ -150,7 +145,6 @@
     // atomic (dns prefetch).
     if (m_prerender) {
         m_prerender->cancel();
-        m_prerender->removeClient();
         m_prerender.clear();
     }
 }
diff --git a/Source/core/loader/LinkLoader.h b/Source/core/loader/LinkLoader.h
index 7b6c19a..56e940a 100644
--- a/Source/core/loader/LinkLoader.h
+++ b/Source/core/loader/LinkLoader.h
@@ -35,15 +35,15 @@
 #include "core/fetch/ResourceClient.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/loader/LinkLoaderClient.h"
-#include "core/platform/PrerenderClient.h"
+#include "platform/PrerenderClient.h"
 #include "platform/Timer.h"
-#include "wtf/RefPtr.h"
+#include "wtf/OwnPtr.h"
 
 namespace WebCore {
 
 class Document;
 class LinkRelAttribute;
-class Prerender;
+class PrerenderHandle;
 
 // The LinkLoader can load link rel types icon, dns-prefetch, subresource, prefetch and prerender.
 class LinkLoader : public ResourceClient, public PrerenderClient {
@@ -74,7 +74,7 @@
     Timer<LinkLoader> m_linkLoadTimer;
     Timer<LinkLoader> m_linkLoadingErrorTimer;
 
-    RefPtr<Prerender> m_prerender;
+    OwnPtr<PrerenderHandle> m_prerender;
 };
 
 }
diff --git a/Source/core/loader/MixedContentChecker.cpp b/Source/core/loader/MixedContentChecker.cpp
index 80ab42e..8908cda 100644
--- a/Source/core/loader/MixedContentChecker.cpp
+++ b/Source/core/loader/MixedContentChecker.cpp
@@ -46,7 +46,7 @@
 
 FrameLoaderClient* MixedContentChecker::client() const
 {
-    return m_frame->loader()->client();
+    return m_frame->loader().client();
 }
 
 // static
diff --git a/Source/core/loader/NavigationScheduler.cpp b/Source/core/loader/NavigationScheduler.cpp
index c03c216..60db841 100644
--- a/Source/core/loader/NavigationScheduler.cpp
+++ b/Source/core/loader/NavigationScheduler.cpp
@@ -113,7 +113,7 @@
         FrameLoadRequest request(m_securityOrigin.get(), ResourceRequest(KURL(ParsedURLString, m_url), m_referrer), "_self");
         request.setLockBackForwardList(lockBackForwardList());
         request.setClientRedirect(true);
-        frame->loader()->load(request);
+        frame->loader().load(request);
     }
 
     virtual void didStartTimer(Frame* frame, Timer<NavigationScheduler>* timer)
@@ -123,7 +123,7 @@
         m_haveToldClient = true;
 
         OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
-        if (frame->loader()->history()->currentItemShouldBeReplaced())
+        if (frame->loader().history()->currentItemShouldBeReplaced())
             setLockBackForwardList(true);
     }
 
@@ -146,7 +146,7 @@
         clearUserGesture();
     }
 
-    virtual bool shouldStartTimer(Frame* frame) { return frame->loader()->allAncestorsAreComplete(); }
+    virtual bool shouldStartTimer(Frame* frame) { return frame->loader().allAncestorsAreComplete(); }
 
     virtual void fire(Frame* frame)
     {
@@ -156,7 +156,7 @@
         if (equalIgnoringFragmentIdentifier(frame->document()->url(), request.resourceRequest().url()))
             request.resourceRequest().setCachePolicy(ReloadIgnoringCacheData);
         request.setClientRedirect(true);
-        frame->loader()->load(request);
+        frame->loader().load(request);
     }
 };
 
@@ -179,7 +179,7 @@
         FrameLoadRequest request(securityOrigin(), ResourceRequest(KURL(ParsedURLString, url()), referrer(), ReloadIgnoringCacheData), "_self");
         request.setLockBackForwardList(lockBackForwardList());
         request.setClientRedirect(true);
-        frame->loader()->load(request);
+        frame->loader().load(request);
     }
 };
 
@@ -200,12 +200,12 @@
             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.
-            frame->loader()->load(frameRequest);
+            frame->loader().load(frameRequest);
             return;
         }
         // go(i!=0) from a frame navigates into the history of the frame only,
         // in both IE and NS (but not in Mozilla). We can't easily do that.
-        frame->page()->mainFrame()->loader()->client()->navigateBackForward(m_historySteps);
+        frame->page()->mainFrame()->loader().client()->navigateBackForward(m_historySteps);
     }
 
 private:
@@ -230,7 +230,7 @@
         frameRequest.setLockBackForwardList(lockBackForwardList());
         frameRequest.setTriggeringEvent(m_submission->event());
         frameRequest.setFormState(m_submission->state());
-        frame->loader()->load(frameRequest);
+        frame->loader().load(frameRequest);
     }
 
     virtual void didStartTimer(Frame* frame, Timer<NavigationScheduler>* timer)
@@ -240,7 +240,7 @@
         m_haveToldClient = true;
 
         OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
-        if (frame->loader()->history()->currentItemShouldBeReplaced())
+        if (frame->loader().history()->currentItemShouldBeReplaced())
             setLockBackForwardList(true);
     }
 
@@ -310,7 +310,7 @@
     // Navigation of a subframe during loading of an ancestor frame does not create a new back/forward item.
     // The definition of "during load" is any time before all handlers for the load event have been run.
     // See https://bugs.webkit.org/show_bug.cgi?id=14957 for the original motivation for this.
-    return targetFrame->tree()->parent() && !targetFrame->tree()->parent()->loader()->allAncestorsAreComplete();
+    return targetFrame->tree().parent() && !targetFrame->tree().parent()->loader().allAncestorsAreComplete();
 }
 
 void NavigationScheduler::scheduleLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList)
@@ -322,8 +322,6 @@
 
     lockBackForwardList = lockBackForwardList || mustLockBackForwardList(m_frame);
 
-    FrameLoader* loader = m_frame->loader();
-
     // If the URL we're going to navigate to is the same as the current one, except for the
     // 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
@@ -334,7 +332,7 @@
             FrameLoadRequest request(securityOrigin, ResourceRequest(m_frame->document()->completeURL(url), referrer), "_self");
             request.setLockBackForwardList(lockBackForwardList);
             request.setClientRedirect(true);
-            loader->load(request);
+            m_frame->loader().load(request);
             return;
         }
     }
@@ -363,7 +361,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()->securityOrigin(), url.string(), m_frame->loader().outgoingReferrer())));
 }
 
 void NavigationScheduler::scheduleHistoryNavigation(int steps)
diff --git a/Source/core/loader/PingLoader.cpp b/Source/core/loader/PingLoader.cpp
index dad8321..078b3f6 100644
--- a/Source/core/loader/PingLoader.cpp
+++ b/Source/core/loader/PingLoader.cpp
@@ -61,10 +61,10 @@
     ResourceRequest request(url);
     request.setTargetType(ResourceRequest::TargetIsImage);
     request.setHTTPHeaderField("Cache-Control", "max-age=0");
-    String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), request.url(), frame->loader()->outgoingReferrer());
+    String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), request.url(), frame->loader().outgoingReferrer());
     if (!referrer.isEmpty())
         request.setHTTPReferrer(referrer);
-    frame->loader()->addExtraFieldsToRequest(request);
+    frame->loader().addExtraFieldsToRequest(request);
     OwnPtr<PingLoader> pingLoader = adoptPtr(new PingLoader(frame, request));
 
     // Leak the ping loader, since it will kill itself as soon as it receives a response.
@@ -81,16 +81,16 @@
     request.setHTTPContentType("text/ping");
     request.setHTTPBody(FormData::create("PING"));
     request.setHTTPHeaderField("Cache-Control", "max-age=0");
-    frame->loader()->addExtraFieldsToRequest(request);
+    frame->loader().addExtraFieldsToRequest(request);
 
     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())) {
+    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());
+            String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), pingURL, frame->loader().outgoingReferrer());
             if (!referrer.isEmpty())
                 request.setHTTPReferrer(referrer);
         }
@@ -109,9 +109,9 @@
     request.setHTTPMethod("POST");
     request.setHTTPContentType(type == ContentSecurityPolicyViolationReport ? "application/csp-report" : "application/json");
     request.setHTTPBody(report);
-    frame->loader()->addExtraFieldsToRequest(request);
+    frame->loader().addExtraFieldsToRequest(request);
 
-    String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), reportURL, frame->loader()->outgoingReferrer());
+    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));
@@ -124,7 +124,7 @@
 PingLoader::PingLoader(Frame* frame, ResourceRequest& request, StoredCredentials credentialsAllowed)
     : m_timeout(this, &PingLoader::timeout)
 {
-    frame->loader()->client()->didDispatchPingLoader(request.url());
+    frame->loader().client()->didDispatchPingLoader(request.url());
 
     unsigned long identifier = createUniqueIdentifier();
     m_loader = adoptPtr(WebKit::Platform::current()->createURLLoader());
@@ -133,7 +133,7 @@
     wrappedRequest.setAllowStoredCredentials(credentialsAllowed == AllowStoredCredentials);
     m_loader->loadAsynchronously(wrappedRequest, this);
 
-    InspectorInstrumentation::continueAfterPingLoader(frame, identifier, frame->loader()->activeDocumentLoader(), request, ResourceResponse());
+    InspectorInstrumentation::continueAfterPingLoader(frame, identifier, frame->loader().activeDocumentLoader(), request, ResourceResponse());
 
     // 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.
diff --git a/Source/core/loader/PrerenderHandle.cpp b/Source/core/loader/PrerenderHandle.cpp
new file mode 100644
index 0000000..e68a9b3
--- /dev/null
+++ b/Source/core/loader/PrerenderHandle.cpp
@@ -0,0 +1,108 @@
+/*
+ * 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/loader/PrerenderHandle.h"
+
+#include "core/dom/Document.h"
+#include "core/frame/Frame.h"
+#include "core/loader/FrameLoader.h"
+#include "core/loader/PrerendererClient.h"
+#include "platform/Prerender.h"
+#include "weborigin/ReferrerPolicy.h"
+#include "weborigin/SecurityPolicy.h"
+
+namespace WebCore {
+
+// static
+PassOwnPtr<PrerenderHandle> PrerenderHandle::create(Document& document, PrerenderClient* client, const KURL& url)
+{
+    // Prerenders are unlike requests in most ways (for instance, they pass down fragments, and they don't return data),
+    // but they do have referrers.
+    const ReferrerPolicy referrerPolicy = document.referrerPolicy();
+
+    if (!document.frame())
+        return PassOwnPtr<PrerenderHandle>();
+
+    const String referrer = SecurityPolicy::generateReferrerHeader(referrerPolicy, url, document.frame()->loader().outgoingReferrer());
+
+    RefPtr<Prerender> prerender = Prerender::create(client, url, referrer, referrerPolicy);
+
+    PrerendererClient* prerendererClient = PrerendererClient::from(document.page());
+    if (prerendererClient)
+        prerendererClient->willAddPrerender(prerender.get());
+    prerender->add();
+
+    return adoptPtr(new PrerenderHandle(document, prerender.release()));
+}
+
+PrerenderHandle::PrerenderHandle(Document& document, PassRefPtr<Prerender> prerender)
+    : DocumentLifecycleObserver(&document)
+    , m_prerender(prerender)
+{
+}
+
+PrerenderHandle::~PrerenderHandle()
+{
+    if (m_prerender)
+        detach();
+}
+
+void PrerenderHandle::cancel()
+{
+    // Avoid both abandoning and canceling the same prerender. In the abandon case, the LinkLoader cancels the
+    // PrerenderHandle as the Document is destroyed, even through the DocumentLifecycleObserver has already abandoned
+    // it.
+    if (!m_prerender)
+        return;
+    m_prerender->cancel();
+    detach();
+}
+
+const KURL& PrerenderHandle::url() const
+{
+    return m_prerender->url();
+}
+
+void PrerenderHandle::documentWasDetached()
+{
+    ASSERT(m_prerender);
+    m_prerender->abandon();
+    detach();
+}
+
+
+void PrerenderHandle::detach()
+{
+    m_prerender->removeClient();
+    m_prerender.clear();
+}
+
+}
diff --git a/Source/core/rendering/RenderingNodeProxy.h b/Source/core/loader/PrerenderHandle.h
similarity index 68%
copy from Source/core/rendering/RenderingNodeProxy.h
copy to Source/core/loader/PrerenderHandle.h
index ac5cb6d..1bf5d48 100644
--- a/Source/core/rendering/RenderingNodeProxy.h
+++ b/Source/core/loader/PrerenderHandle.h
@@ -28,44 +28,41 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef RenderingNodeProxy_h
-#define RenderingNodeProxy_h
+#ifndef PrerenderHandle_h
+#define PrerenderHandle_h
 
-#include "core/rendering/LayoutIndicator.h"
+#include "core/dom/DocumentLifecycleObserver.h"
+#include "weborigin/KURL.h"
 #include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
-class QualifiedName;
-class Node;
+class Document;
+class Prerender;
+class PrerenderClient;
 
-#define STRICT_LAYOUT_THREADING 0
-
-class RenderingNodeProxy {
-    WTF_MAKE_NONCOPYABLE(RenderingNodeProxy);
+class PrerenderHandle : public DocumentLifecycleObserver {
+    WTF_MAKE_NONCOPYABLE(PrerenderHandle);
 public:
-    explicit RenderingNodeProxy(Node*);
-    ~RenderingNodeProxy();
+    static PassOwnPtr<PrerenderHandle> create(Document&, PrerenderClient*, const KURL&);
 
-    bool hasTagName(const QualifiedName&) const;
+    virtual ~PrerenderHandle();
 
-    Node* unsafeNode() const
-    {
-#if STRICT_LAYOUT_THREADING
-        ASSERT(!LayoutIndicator::inLayout());
-#endif
-        return m_node;
-    }
+    void cancel();
+    const KURL& url() const;
 
-    void clear() { m_node = 0; }
-    void set(Node* node) { m_node = node; }
-
+    // From DocumentLifecycleObserver:
+    virtual void documentWasDetached() OVERRIDE;
 private:
-    Node* m_node;
-};
+    PrerenderHandle(Document&, PassRefPtr<Prerender>);
 
-#undef STRICT_LAYOUT_THREADING
+    void detach();
+
+    RefPtr<Prerender> m_prerender;
+};
 
 }
 
-#endif // RenderingNodeProxy_h
+#endif // PrerenderHandle_h
diff --git a/Source/core/loader/Prerenderer.cpp b/Source/core/loader/Prerenderer.cpp
deleted file mode 100644
index d053ffa..0000000
--- a/Source/core/loader/Prerenderer.cpp
+++ /dev/null
@@ -1,124 +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/loader/Prerenderer.h"
-
-#include "core/dom/Document.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/PrerendererClient.h"
-#include "core/frame/Frame.h"
-#include "core/platform/Prerender.h"
-#include "weborigin/ReferrerPolicy.h"
-#include "weborigin/SecurityPolicy.h"
-
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-Prerenderer::Prerenderer(Document* document)
-    : DocumentLifecycleObserver(document)
-    , m_initializedClient(false)
-    , m_client(0)
-{
-}
-
-Prerenderer::~Prerenderer()
-{
-}
-
-const char* Prerenderer::supplementName()
-{
-    return "Prerenderer";
-}
-
-Prerenderer* Prerenderer::from(Document* document)
-{
-    Prerenderer* prerenderer = static_cast<Prerenderer*>(DocumentSupplement::from(document, supplementName()));
-    if (!prerenderer) {
-        prerenderer = new Prerenderer(document);
-        DocumentSupplement::provideTo(document, supplementName(), adoptPtr(prerenderer));
-    }
-    return prerenderer;
-}
-
-PassRefPtr<Prerender> Prerenderer::render(PrerenderClient* prerenderClient, const KURL& url)
-{
-    // Prerenders are unlike requests in most ways (for instance, they pass down fragments, and they don't return data),
-    // but they do have referrers.
-    const ReferrerPolicy referrerPolicy = document()->referrerPolicy();
-
-    if (!document()->frame())
-        return 0;
-
-    const String referrer = SecurityPolicy::generateReferrerHeader(referrerPolicy, url, document()->frame()->loader()->outgoingReferrer());
-
-    RefPtr<Prerender> prerender = Prerender::create(prerenderClient, url, referrer, referrerPolicy);
-
-    if (client())
-        client()->willAddPrerender(prerender.get());
-    prerender->add();
-
-    // FIXME: This prerender isn't released until page unload, but it may be canceled before then. It should be released in that case.
-    m_activePrerenders.append(prerender);
-    return prerender;
-}
-
-void Prerenderer::documentWasDetached()
-{
-    while (!m_activePrerenders.isEmpty()) {
-        RefPtr<Prerender> prerender = m_activePrerenders[0].release();
-        m_activePrerenders.remove(0);
-        prerender->abandon();
-    }
-}
-
-Document* Prerenderer::document()
-{
-    ASSERT(executionContext()->isDocument());
-    return toDocument(executionContext());
-}
-
-PrerendererClient* Prerenderer::client()
-{
-    if (!m_initializedClient) {
-        // We can't initialize the client in our contructor, because the platform might not have
-        // provided our supplement by then.
-        m_initializedClient = true;
-        m_client = PrerendererClient::from(document()->page());
-    }
-    return m_client;
-}
-
-}
diff --git a/Source/core/loader/Prerenderer.h b/Source/core/loader/Prerenderer.h
deleted file mode 100644
index e5fd35a..0000000
--- a/Source/core/loader/Prerenderer.h
+++ /dev/null
@@ -1,80 +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 Prerenderer_h
-#define Prerenderer_h
-
-#include "core/dom/DocumentLifecycleObserver.h"
-#include "core/dom/DocumentSupplementable.h"
-#include "platform/Supplementable.h"
-#include "weborigin/KURL.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class PrerenderClient;
-class Prerender;
-class PrerendererClient;
-class Page;
-
-class Prerenderer : public DocumentLifecycleObserver, public DocumentSupplement {
-    WTF_MAKE_NONCOPYABLE(Prerenderer);
-public:
-    virtual ~Prerenderer();
-
-    PassRefPtr<Prerender> render(PrerenderClient*, const KURL&);
-
-    static const char* supplementName();
-    static Prerenderer* from(Document*);
-
-    // From DocumentLifecycleObserver:
-    virtual void documentWasDetached() OVERRIDE;
-
-private:
-    typedef Vector<RefPtr<Prerender> > PrerenderVector;
-    typedef Vector<KURL> KURLVector;
-
-    explicit Prerenderer(Document*);
-
-    Document* document();
-    PrerendererClient* client();
-
-    bool m_initializedClient;
-    PrerendererClient* m_client;
-    PrerenderVector m_activePrerenders;
-};
-
-}
-
-#endif // Prerenderer_h
diff --git a/Source/core/loader/ProgressTracker.cpp b/Source/core/loader/ProgressTracker.cpp
index 7824a91..3139dfa 100644
--- a/Source/core/loader/ProgressTracker.cpp
+++ b/Source/core/loader/ProgressTracker.cpp
@@ -104,14 +104,14 @@
 
 void ProgressTracker::progressStarted(Frame* frame)
 {
-    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());
+    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());
 
     if (m_numProgressTrackedFrames == 0 || m_originatingProgressFrame == frame) {
         reset();
         m_progressValue = initialProgressValue;
         m_originatingProgressFrame = frame;
 
-        m_originatingProgressFrame->loader()->client()->postProgressStartedNotification();
+        m_originatingProgressFrame->loader().client()->postProgressStartedNotification();
     }
     m_numProgressTrackedFrames++;
     InspectorInstrumentation::frameStartedLoading(frame);
@@ -119,7 +119,7 @@
 
 void ProgressTracker::progressCompleted(Frame* frame)
 {
-    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());
+    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());
 
     if (m_numProgressTrackedFrames <= 0)
         return;
@@ -138,11 +138,11 @@
     // with final progress value.
     if (!m_finalProgressChangedSent) {
         m_progressValue = 1;
-        frame->loader()->client()->postProgressEstimateChangedNotification();
+        frame->loader().client()->postProgressEstimateChangedNotification();
     }
 
     reset();
-    frame->loader()->client()->postProgressFinishedNotification();
+    frame->loader().client()->postProgressFinishedNotification();
     InspectorInstrumentation::frameStoppedLoading(frame.get());
 }
 
@@ -186,7 +186,7 @@
         item->estimatedLength = item->bytesReceived * 2;
     }
 
-    int numPendingOrLoadingRequests = frame->loader()->numPendingOrLoadingRequests(true);
+    int numPendingOrLoadingRequests = frame->loader().numPendingOrLoadingRequests(true);
     estimatedBytesForPendingRequests = progressItemDefaultEstimatedLength * numPendingOrLoadingRequests;
     remainingBytes = ((m_totalPageAndResourceBytesToLoad + estimatedBytesForPendingRequests) - m_totalBytesReceived);
     if (remainingBytes > 0)  // Prevent divide by 0.
@@ -216,7 +216,7 @@
             if (m_progressValue == 1)
                 m_finalProgressChangedSent = true;
 
-            frame->loader()->client()->postProgressEstimateChangedNotification();
+            frame->loader().client()->postProgressEstimateChangedNotification();
 
             m_lastNotifiedProgressValue = m_progressValue;
             m_lastNotifiedProgressTime = now;
diff --git a/Source/core/loader/TextResourceDecoderBuilder.cpp b/Source/core/loader/TextResourceDecoderBuilder.cpp
index 9dffcf5..0076f61 100644
--- a/Source/core/loader/TextResourceDecoderBuilder.cpp
+++ b/Source/core/loader/TextResourceDecoderBuilder.cpp
@@ -69,7 +69,7 @@
 inline void TextResourceDecoderBuilder::setupEncoding(TextResourceDecoder* decoder, Document* document)
 {
     Frame* frame = document->frame();
-    Frame* parentFrame = frame ? frame->tree()->parent() : 0;
+    Frame* parentFrame = frame ? frame->tree().parent() : 0;
 
     if (!m_encoding.isEmpty())
         decoder->setEncoding(m_encoding, m_encodingWasChosenByUser ? TextResourceDecoder::UserChosenEncoding : TextResourceDecoder::EncodingFromHTTPHeader);
diff --git a/Source/core/loader/TextTrackLoader.cpp b/Source/core/loader/TextTrackLoader.cpp
index 51c0813..5f6a2b2 100644
--- a/Source/core/loader/TextTrackLoader.cpp
+++ b/Source/core/loader/TextTrackLoader.cpp
@@ -100,8 +100,7 @@
     }
 }
 
-// FIXME: This is a very unusual pattern, no other ResourceClient does this. Refactor to use notifyFinished() instead.
-void TextTrackLoader::deprecatedDidReceiveResource(Resource* resource)
+void TextTrackLoader::dataReceived(Resource* resource, const char*, int)
 {
     ASSERT(m_cachedCueData == resource);
 
diff --git a/Source/core/loader/TextTrackLoader.h b/Source/core/loader/TextTrackLoader.h
index 59b7664..4ca0543 100644
--- a/Source/core/loader/TextTrackLoader.h
+++ b/Source/core/loader/TextTrackLoader.h
@@ -26,7 +26,7 @@
 #ifndef TextTrackLoader_h
 #define TextTrackLoader_h
 
-#include "core/fetch/ResourceClient.h"
+#include "core/fetch/RawResource.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/fetch/TextTrackResource.h"
 #include "core/html/track/WebVTTParser.h"
@@ -49,7 +49,7 @@
     virtual void newRegionsAvailable(TextTrackLoader*) = 0;
 };
 
-class TextTrackLoader : public ResourceClient, private WebVTTParserClient {
+class TextTrackLoader : public RawResourceClient, private WebVTTParserClient {
     WTF_MAKE_NONCOPYABLE(TextTrackLoader);
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -69,14 +69,14 @@
     void getNewRegions(Vector<RefPtr<TextTrackRegion> >& outputRegions);
 private:
 
-    // ResourceClient
-    virtual void notifyFinished(Resource*);
-    virtual void deprecatedDidReceiveResource(Resource*);
+    // RawResourceClient
+    virtual void dataReceived(Resource*, const char* data, int length) OVERRIDE;
+    virtual void notifyFinished(Resource*) OVERRIDE;
 
     // WebVTTParserClient
-    virtual void newCuesParsed();
-    virtual void newRegionsParsed();
-    virtual void fileFailedToParse();
+    virtual void newCuesParsed() OVERRIDE;
+    virtual void newRegionsParsed() OVERRIDE;
+    virtual void fileFailedToParse() OVERRIDE;
 
     TextTrackLoader(TextTrackLoaderClient*, Document&);
 
diff --git a/Source/core/loader/appcache/ApplicationCache.cpp b/Source/core/loader/appcache/ApplicationCache.cpp
index bc9ac05..460605a 100644
--- a/Source/core/loader/appcache/ApplicationCache.cpp
+++ b/Source/core/loader/appcache/ApplicationCache.cpp
@@ -57,9 +57,9 @@
 
 ApplicationCacheHost* ApplicationCache::applicationCacheHost() const
 {
-    if (!m_frame || !m_frame->loader()->documentLoader())
+    if (!m_frame || !m_frame->loader().documentLoader())
         return 0;
-    return m_frame->loader()->documentLoader()->applicationCacheHost();
+    return m_frame->loader().documentLoader()->applicationCacheHost();
 }
 
 unsigned short ApplicationCache::status() const
diff --git a/Source/core/loader/archive/MHTMLArchive.h b/Source/core/loader/archive/MHTMLArchive.h
index d102afd..60b7dbf 100644
--- a/Source/core/loader/archive/MHTMLArchive.h
+++ b/Source/core/loader/archive/MHTMLArchive.h
@@ -45,7 +45,7 @@
 
 struct SerializedResource;
 
-class MHTMLArchive : public RefCounted<MHTMLArchive> {
+class MHTMLArchive FINAL : public RefCounted<MHTMLArchive> {
 public:
     static PassRefPtr<MHTMLArchive> create();
     static PassRefPtr<MHTMLArchive> create(const KURL&, SharedBuffer*);
@@ -58,7 +58,7 @@
     // Binary encoding results in smaller MHTML files but they might not work in other browsers.
     static PassRefPtr<SharedBuffer> generateMHTMLData(const Vector<SerializedResource>&, EncodingPolicy, const String& title, const String& mimeType);
 
-    virtual ~MHTMLArchive();
+    ~MHTMLArchive();
     ArchiveResource* mainResource() { return m_mainResource.get(); }
     const Vector<RefPtr<ArchiveResource> >& subresources() const { return m_subresources; }
     const Vector<RefPtr<MHTMLArchive> >& subframeArchives() const { return m_subframeArchives; }
diff --git a/Source/core/make_core_derived_sources.target.darwin-arm.mk b/Source/core/make_core_derived_sources.target.darwin-arm.mk
index 35a4f47..d7ed305 100644
--- a/Source/core/make_core_derived_sources.target.darwin-arm.mk
+++ b/Source/core/make_core_derived_sources.target.darwin-arm.mk
@@ -21,7 +21,7 @@
 $(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; perl ../build/scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(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":
@@ -31,7 +31,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(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":
@@ -41,7 +41,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(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":
@@ -54,17 +54,6 @@
 	$(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 "RuntimeEnabledFeatures":
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_RuntimeEnabledFeatures ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp ;
-
 ### 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))
@@ -126,19 +115,19 @@
 $(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
 
 ### Rules for action "SVGNames":
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- ../build/scripts/Hasher.pm ../build/scripts/StaticString.pm ../build/scripts/make_names.pl svg/SVGTagNames.in svg/SVGAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=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\""
+	$(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/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
+$(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)
@@ -262,16 +251,6 @@
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
-### Rules for action "preprocess_grammar":
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl -I../build/scripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/blink" css/CSSGrammar.y.in css/CSSGrammar.y.includes
-
-
 ### Rules for action "MakeTokenMatcher":
 $(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))
@@ -295,13 +274,13 @@
 
 
 ### 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': ['$(gyp_shared_intermediate_dir)/blink/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']}":
+# "{'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: $(gyp_shared_intermediate_dir)/blink/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 "$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y" "$(gyp_shared_intermediate_dir)/blink" bison
+$(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
@@ -318,19 +297,6 @@
 .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
 
-
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_gperf":
-# "{'inputs': ['../build/scripts/make-hash-tools.pl'], 'msvs_cygwin_shell': '0', 'extension': 'gperf', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp'], 'rule_name': 'gperf', 'rule_sources': ['platform/ColorData.gperf'], 'action': ['perl', '../build/scripts/make-hash-tools.pl', '$(gyp_shared_intermediate_dir)/blink', '$(RULE_SOURCES)', 'gperf']}":
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/platform/ColorData.gperf $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make-hash-tools.pl $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; perl ../build/scripts/make-hash-tools.pl "$(gyp_shared_intermediate_dir)/blink" platform/ColorData.gperf gperf
-
-.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/ColorData.cpp
-
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
@@ -338,8 +304,6 @@
 	$(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/RuntimeEnabledFeatures.cpp \
-	$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h \
 	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp \
@@ -355,10 +319,10 @@
 	$(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/SVGNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.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 \
@@ -384,14 +348,12 @@
 	$(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/CSSGrammar.y \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(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 \
-	$(gyp_shared_intermediate_dir)/blink/ColorData.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)
@@ -444,13 +406,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -524,13 +486,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/make_core_derived_sources.target.darwin-mips.mk b/Source/core/make_core_derived_sources.target.darwin-mips.mk
index e274bae..925fca6 100644
--- a/Source/core/make_core_derived_sources.target.darwin-mips.mk
+++ b/Source/core/make_core_derived_sources.target.darwin-mips.mk
@@ -21,7 +21,7 @@
 $(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; perl ../build/scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(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":
@@ -31,7 +31,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(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":
@@ -41,7 +41,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(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":
@@ -54,17 +54,6 @@
 	$(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 "RuntimeEnabledFeatures":
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_RuntimeEnabledFeatures ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp ;
-
 ### 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))
@@ -126,19 +115,19 @@
 $(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
 
 ### Rules for action "SVGNames":
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- ../build/scripts/Hasher.pm ../build/scripts/StaticString.pm ../build/scripts/make_names.pl svg/SVGTagNames.in svg/SVGAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=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\""
+	$(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/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
+$(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)
@@ -262,16 +251,6 @@
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
-### Rules for action "preprocess_grammar":
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl -I../build/scripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/blink" css/CSSGrammar.y.in css/CSSGrammar.y.includes
-
-
 ### Rules for action "MakeTokenMatcher":
 $(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))
@@ -295,13 +274,13 @@
 
 
 ### 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': ['$(gyp_shared_intermediate_dir)/blink/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']}":
+# "{'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: $(gyp_shared_intermediate_dir)/blink/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 "$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y" "$(gyp_shared_intermediate_dir)/blink" bison
+$(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
@@ -318,19 +297,6 @@
 .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
 
-
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_gperf":
-# "{'inputs': ['../build/scripts/make-hash-tools.pl'], 'msvs_cygwin_shell': '0', 'extension': 'gperf', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp'], 'rule_name': 'gperf', 'rule_sources': ['platform/ColorData.gperf'], 'action': ['perl', '../build/scripts/make-hash-tools.pl', '$(gyp_shared_intermediate_dir)/blink', '$(RULE_SOURCES)', 'gperf']}":
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/platform/ColorData.gperf $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make-hash-tools.pl $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; perl ../build/scripts/make-hash-tools.pl "$(gyp_shared_intermediate_dir)/blink" platform/ColorData.gperf gperf
-
-.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/ColorData.cpp
-
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
@@ -338,8 +304,6 @@
 	$(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/RuntimeEnabledFeatures.cpp \
-	$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h \
 	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp \
@@ -355,10 +319,10 @@
 	$(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/SVGNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.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 \
@@ -384,14 +348,12 @@
 	$(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/CSSGrammar.y \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(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 \
-	$(gyp_shared_intermediate_dir)/blink/ColorData.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)
@@ -444,13 +406,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -524,13 +486,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/make_core_derived_sources.target.darwin-x86.mk b/Source/core/make_core_derived_sources.target.darwin-x86.mk
index 91342d0..8959cb2 100644
--- a/Source/core/make_core_derived_sources.target.darwin-x86.mk
+++ b/Source/core/make_core_derived_sources.target.darwin-x86.mk
@@ -21,7 +21,7 @@
 $(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; perl ../build/scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(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":
@@ -31,7 +31,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(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":
@@ -41,7 +41,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(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":
@@ -54,17 +54,6 @@
 	$(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 "RuntimeEnabledFeatures":
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_RuntimeEnabledFeatures ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp ;
-
 ### 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))
@@ -126,19 +115,19 @@
 $(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
 
 ### Rules for action "SVGNames":
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- ../build/scripts/Hasher.pm ../build/scripts/StaticString.pm ../build/scripts/make_names.pl svg/SVGTagNames.in svg/SVGAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=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\""
+	$(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/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
+$(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)
@@ -262,16 +251,6 @@
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
-### Rules for action "preprocess_grammar":
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl -I../build/scripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/blink" css/CSSGrammar.y.in css/CSSGrammar.y.includes
-
-
 ### Rules for action "MakeTokenMatcher":
 $(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))
@@ -295,13 +274,13 @@
 
 
 ### 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': ['$(gyp_shared_intermediate_dir)/blink/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']}":
+# "{'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: $(gyp_shared_intermediate_dir)/blink/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 "$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y" "$(gyp_shared_intermediate_dir)/blink" bison
+$(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
@@ -318,19 +297,6 @@
 .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
 
-
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_gperf":
-# "{'inputs': ['../build/scripts/make-hash-tools.pl'], 'msvs_cygwin_shell': '0', 'extension': 'gperf', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp'], 'rule_name': 'gperf', 'rule_sources': ['platform/ColorData.gperf'], 'action': ['perl', '../build/scripts/make-hash-tools.pl', '$(gyp_shared_intermediate_dir)/blink', '$(RULE_SOURCES)', 'gperf']}":
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/platform/ColorData.gperf $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make-hash-tools.pl $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; perl ../build/scripts/make-hash-tools.pl "$(gyp_shared_intermediate_dir)/blink" platform/ColorData.gperf gperf
-
-.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/ColorData.cpp
-
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
@@ -338,8 +304,6 @@
 	$(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/RuntimeEnabledFeatures.cpp \
-	$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h \
 	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp \
@@ -355,10 +319,10 @@
 	$(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/SVGNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.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 \
@@ -384,14 +348,12 @@
 	$(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/CSSGrammar.y \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(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 \
-	$(gyp_shared_intermediate_dir)/blink/ColorData.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)
@@ -446,13 +408,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -529,13 +491,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/make_core_derived_sources.target.linux-arm.mk b/Source/core/make_core_derived_sources.target.linux-arm.mk
index 35a4f47..d7ed305 100644
--- a/Source/core/make_core_derived_sources.target.linux-arm.mk
+++ b/Source/core/make_core_derived_sources.target.linux-arm.mk
@@ -21,7 +21,7 @@
 $(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; perl ../build/scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(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":
@@ -31,7 +31,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(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":
@@ -41,7 +41,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(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":
@@ -54,17 +54,6 @@
 	$(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 "RuntimeEnabledFeatures":
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_RuntimeEnabledFeatures ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp ;
-
 ### 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))
@@ -126,19 +115,19 @@
 $(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
 
 ### Rules for action "SVGNames":
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- ../build/scripts/Hasher.pm ../build/scripts/StaticString.pm ../build/scripts/make_names.pl svg/SVGTagNames.in svg/SVGAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=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\""
+	$(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/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
+$(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)
@@ -262,16 +251,6 @@
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
-### Rules for action "preprocess_grammar":
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl -I../build/scripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/blink" css/CSSGrammar.y.in css/CSSGrammar.y.includes
-
-
 ### Rules for action "MakeTokenMatcher":
 $(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))
@@ -295,13 +274,13 @@
 
 
 ### 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': ['$(gyp_shared_intermediate_dir)/blink/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']}":
+# "{'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: $(gyp_shared_intermediate_dir)/blink/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 "$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y" "$(gyp_shared_intermediate_dir)/blink" bison
+$(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
@@ -318,19 +297,6 @@
 .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
 
-
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_gperf":
-# "{'inputs': ['../build/scripts/make-hash-tools.pl'], 'msvs_cygwin_shell': '0', 'extension': 'gperf', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp'], 'rule_name': 'gperf', 'rule_sources': ['platform/ColorData.gperf'], 'action': ['perl', '../build/scripts/make-hash-tools.pl', '$(gyp_shared_intermediate_dir)/blink', '$(RULE_SOURCES)', 'gperf']}":
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/platform/ColorData.gperf $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make-hash-tools.pl $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; perl ../build/scripts/make-hash-tools.pl "$(gyp_shared_intermediate_dir)/blink" platform/ColorData.gperf gperf
-
-.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/ColorData.cpp
-
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
@@ -338,8 +304,6 @@
 	$(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/RuntimeEnabledFeatures.cpp \
-	$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h \
 	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp \
@@ -355,10 +319,10 @@
 	$(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/SVGNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.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 \
@@ -384,14 +348,12 @@
 	$(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/CSSGrammar.y \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(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 \
-	$(gyp_shared_intermediate_dir)/blink/ColorData.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)
@@ -444,13 +406,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -524,13 +486,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/make_core_derived_sources.target.linux-mips.mk b/Source/core/make_core_derived_sources.target.linux-mips.mk
index e274bae..925fca6 100644
--- a/Source/core/make_core_derived_sources.target.linux-mips.mk
+++ b/Source/core/make_core_derived_sources.target.linux-mips.mk
@@ -21,7 +21,7 @@
 $(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; perl ../build/scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(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":
@@ -31,7 +31,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(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":
@@ -41,7 +41,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(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":
@@ -54,17 +54,6 @@
 	$(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 "RuntimeEnabledFeatures":
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_RuntimeEnabledFeatures ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp ;
-
 ### 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))
@@ -126,19 +115,19 @@
 $(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
 
 ### Rules for action "SVGNames":
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- ../build/scripts/Hasher.pm ../build/scripts/StaticString.pm ../build/scripts/make_names.pl svg/SVGTagNames.in svg/SVGAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=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\""
+	$(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/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
+$(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)
@@ -262,16 +251,6 @@
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
-### Rules for action "preprocess_grammar":
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl -I../build/scripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/blink" css/CSSGrammar.y.in css/CSSGrammar.y.includes
-
-
 ### Rules for action "MakeTokenMatcher":
 $(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))
@@ -295,13 +274,13 @@
 
 
 ### 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': ['$(gyp_shared_intermediate_dir)/blink/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']}":
+# "{'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: $(gyp_shared_intermediate_dir)/blink/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 "$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y" "$(gyp_shared_intermediate_dir)/blink" bison
+$(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
@@ -318,19 +297,6 @@
 .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
 
-
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_gperf":
-# "{'inputs': ['../build/scripts/make-hash-tools.pl'], 'msvs_cygwin_shell': '0', 'extension': 'gperf', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp'], 'rule_name': 'gperf', 'rule_sources': ['platform/ColorData.gperf'], 'action': ['perl', '../build/scripts/make-hash-tools.pl', '$(gyp_shared_intermediate_dir)/blink', '$(RULE_SOURCES)', 'gperf']}":
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/platform/ColorData.gperf $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make-hash-tools.pl $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; perl ../build/scripts/make-hash-tools.pl "$(gyp_shared_intermediate_dir)/blink" platform/ColorData.gperf gperf
-
-.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/ColorData.cpp
-
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
@@ -338,8 +304,6 @@
 	$(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/RuntimeEnabledFeatures.cpp \
-	$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h \
 	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp \
@@ -355,10 +319,10 @@
 	$(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/SVGNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.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 \
@@ -384,14 +348,12 @@
 	$(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/CSSGrammar.y \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(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 \
-	$(gyp_shared_intermediate_dir)/blink/ColorData.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)
@@ -444,13 +406,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -524,13 +486,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/make_core_derived_sources.target.linux-x86.mk b/Source/core/make_core_derived_sources.target.linux-x86.mk
index 91342d0..8959cb2 100644
--- a/Source/core/make_core_derived_sources.target.linux-x86.mk
+++ b/Source/core/make_core_derived_sources.target.linux-x86.mk
@@ -21,7 +21,7 @@
 $(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; perl ../build/scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(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":
@@ -31,7 +31,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(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":
@@ -41,7 +41,7 @@
 $(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; perl ../build/scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(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":
@@ -54,17 +54,6 @@
 	$(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 "RuntimeEnabledFeatures":
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_RuntimeEnabledFeatures ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp ;
-
 ### 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))
@@ -126,19 +115,19 @@
 $(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
 
 ### Rules for action "SVGNames":
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
+$(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/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- ../build/scripts/Hasher.pm ../build/scripts/StaticString.pm ../build/scripts/make_names.pl svg/SVGTagNames.in svg/SVGAttributeNames.in -- --factory --extraDefines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=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\""
+	$(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/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
+$(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)
@@ -262,16 +251,6 @@
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
-### Rules for action "preprocess_grammar":
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl -I../build/scripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/blink" css/CSSGrammar.y.in css/CSSGrammar.y.includes
-
-
 ### Rules for action "MakeTokenMatcher":
 $(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))
@@ -295,13 +274,13 @@
 
 
 ### 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': ['$(gyp_shared_intermediate_dir)/blink/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']}":
+# "{'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: $(gyp_shared_intermediate_dir)/blink/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 "$(gyp_shared_intermediate_dir)/blink/CSSGrammar.y" "$(gyp_shared_intermediate_dir)/blink" bison
+$(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
@@ -318,19 +297,6 @@
 .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
 
-
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_gperf":
-# "{'inputs': ['../build/scripts/make-hash-tools.pl'], 'msvs_cygwin_shell': '0', 'extension': 'gperf', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp'], 'rule_name': 'gperf', 'rule_sources': ['platform/ColorData.gperf'], 'action': ['perl', '../build/scripts/make-hash-tools.pl', '$(gyp_shared_intermediate_dir)/blink', '$(RULE_SOURCES)', 'gperf']}":
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/ColorData.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/platform/ColorData.gperf $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make-hash-tools.pl $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; perl ../build/scripts/make-hash-tools.pl "$(gyp_shared_intermediate_dir)/blink" platform/ColorData.gperf gperf
-
-.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/ColorData.cpp
-
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
@@ -338,8 +304,6 @@
 	$(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/RuntimeEnabledFeatures.cpp \
-	$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h \
 	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp \
@@ -355,10 +319,10 @@
 	$(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/SVGNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.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 \
@@ -384,14 +348,12 @@
 	$(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/CSSGrammar.y \
 	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(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 \
-	$(gyp_shared_intermediate_dir)/blink/ColorData.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)
@@ -446,13 +408,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -529,13 +491,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/page/AutoscrollController.cpp b/Source/core/page/AutoscrollController.cpp
index 90a6b90..25eaf8a 100644
--- a/Source/core/page/AutoscrollController.cpp
+++ b/Source/core/page/AutoscrollController.cpp
@@ -119,7 +119,7 @@
     RenderObject* renderer = m_autoscrollRenderer;
 
 #if OS(WIN)
-    HitTestResult hitTest = renderer->frame()->eventHandler()->hitTestResultAtPoint(m_panScrollStartPos, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+    HitTestResult hitTest = renderer->frame()->eventHandler().hitTestResultAtPoint(m_panScrollStartPos, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
 
     if (Node* nodeAtPoint = hitTest.innerNode())
         renderer = nodeAtPoint->renderer();
@@ -221,19 +221,19 @@
         return;
     }
 
-    EventHandler* eventHandler = m_autoscrollRenderer->frame()->eventHandler();
+    EventHandler& eventHandler = m_autoscrollRenderer->frame()->eventHandler();
     switch (m_autoscrollType) {
     case AutoscrollForDragAndDrop:
         if (WTF::currentTime() - m_dragAndDropAutoscrollStartTime > autoscrollDelay)
             m_autoscrollRenderer->autoscroll(m_dragAndDropAutoscrollReferencePosition);
         break;
     case AutoscrollForSelection:
-        if (!eventHandler->mousePressed()) {
+        if (!eventHandler.mousePressed()) {
             stopAutoscrollTimer();
             return;
         }
-        eventHandler->updateSelectionForMouseDrag();
-        m_autoscrollRenderer->autoscroll(eventHandler->lastKnownMousePosition());
+        eventHandler.updateSelectionForMouseDrag();
+        m_autoscrollRenderer->autoscroll(eventHandler.lastKnownMousePosition());
         break;
     case NoAutoscroll:
         break;
@@ -245,7 +245,7 @@
             return;
         }
         if (FrameView* view = m_autoscrollRenderer->frame()->view())
-            updatePanScrollState(view, eventHandler->lastKnownMousePosition());
+            updatePanScrollState(view, eventHandler.lastKnownMousePosition());
         m_autoscrollRenderer->panScroll(m_panScrollStartPos);
         break;
 #endif
diff --git a/Source/core/page/Chrome.cpp b/Source/core/page/Chrome.cpp
index 5d5c9ad..e7a92ea 100644
--- a/Source/core/page/Chrome.cpp
+++ b/Source/core/page/Chrome.cpp
@@ -158,7 +158,7 @@
 
 static bool canRunModalIfDuringPageDismissal(Page* page, ChromeClient::DialogType dialog, const String& message)
 {
-    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
         Document::PageDismissalType dismissal = frame->document()->pageDismissalEventBeingDispatched();
         if (dismissal != Document::NoDismissal)
             return page->chrome().client().shouldRunModalDialogDuringPageDismissal(dialog, message, dismissal);
diff --git a/Source/core/page/Chrome.h b/Source/core/page/Chrome.h
index 7f8b681..304f518 100644
--- a/Source/core/page/Chrome.h
+++ b/Source/core/page/Chrome.h
@@ -67,13 +67,14 @@
     virtual IntPoint screenToRootView(const IntPoint&) const OVERRIDE;
     virtual IntRect rootViewToScreen(const IntRect&) const OVERRIDE;
     virtual WebKit::WebScreenInfo screenInfo() const OVERRIDE;
-    virtual void setCursor(const Cursor&) OVERRIDE;
 
     virtual void scheduleAnimation() OVERRIDE;
 
     void contentsSizeChanged(Frame*, const IntSize&) const;
     void layoutUpdated(Frame*) const;
 
+    void setCursor(const Cursor&);
+
     void setWindowRect(const FloatRect&) const;
     FloatRect windowRect() const;
 
diff --git a/Source/core/page/ChromeClient.h b/Source/core/page/ChromeClient.h
index cdef8f5..14834e8 100644
--- a/Source/core/page/ChromeClient.h
+++ b/Source/core/page/ChromeClient.h
@@ -159,9 +159,6 @@
     virtual void deviceOrPageScaleFactorChanged() const { }
     virtual void layoutUpdated(Frame*) const { }
 
-    // didProgrammaticallyScroll should be called whenever a Frame is programmatically scrolled.
-    virtual void didProgrammaticallyScroll(Frame*, const IntPoint& newScrollPosition) const { }
-
     virtual void mouseDidMoveOverElement(const HitTestResult&, unsigned modifierFlags) = 0;
 
     virtual void setToolTip(const String&, TextDirection) = 0;
diff --git a/Source/core/page/ContextMenuController.cpp b/Source/core/page/ContextMenuController.cpp
index 4570af4..449dbdc 100644
--- a/Source/core/page/ContextMenuController.cpp
+++ b/Source/core/page/ContextMenuController.cpp
@@ -41,11 +41,9 @@
 
 namespace WebCore {
 
-ContextMenuController::ContextMenuController(Page* page, ContextMenuClient* client)
-    : m_page(page)
-    , m_client(client)
+ContextMenuController::ContextMenuController(Page*, ContextMenuClient* client)
+    : m_client(client)
 {
-    ASSERT_ARG(page, page);
     ASSERT_ARG(client, client);
 }
 
@@ -111,7 +109,7 @@
     HitTestResult result(mouseEvent->absoluteLocation());
 
     if (Frame* frame = event->target()->toNode()->document().frame())
-        result = frame->eventHandler()->hitTestResultAtPoint(mouseEvent->absoluteLocation(), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+        result = frame->eventHandler().hitTestResultAtPoint(mouseEvent->absoluteLocation(), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
 
     if (!result.innerNonSharedNode())
         return nullptr;
diff --git a/Source/core/page/ContextMenuController.h b/Source/core/page/ContextMenuController.h
index e36bedb..025638e 100644
--- a/Source/core/page/ContextMenuController.h
+++ b/Source/core/page/ContextMenuController.h
@@ -67,7 +67,6 @@
         PassOwnPtr<ContextMenu> createContextMenu(Event*);
         void showContextMenu(Event*);
 
-        Page* m_page;
         ContextMenuClient* m_client;
         OwnPtr<ContextMenu> m_contextMenu;
         RefPtr<ContextMenuProvider> m_menuProvider;
diff --git a/Source/core/page/CreateWindow.cpp b/Source/core/page/CreateWindow.cpp
index b740d41..0cd7ee0 100644
--- a/Source/core/page/CreateWindow.cpp
+++ b/Source/core/page/CreateWindow.cpp
@@ -47,7 +47,7 @@
     ASSERT(!features.dialog || request.frameName().isEmpty());
 
     if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
-        if (Frame* frame = lookupFrame->loader()->findFrameForNavigation(request.frameName(), openerFrame->document())) {
+        if (Frame* frame = lookupFrame->loader().findFrameForNavigation(request.frameName(), openerFrame->document())) {
             if (request.frameName() != "_self") {
                 if (Page* page = frame->page())
                     page->chrome().focus();
@@ -66,7 +66,7 @@
 
     if (openerFrame->settings() && !openerFrame->settings()->supportsMultipleWindows()) {
         created = false;
-        return openerFrame->tree()->top();
+        return openerFrame->tree().top();
     }
 
     Page* oldPage = openerFrame->page();
@@ -79,10 +79,10 @@
 
     Frame* frame = page->mainFrame();
 
-    frame->loader()->forceSandboxFlags(openerFrame->document()->sandboxFlags());
+    frame->loader().forceSandboxFlags(openerFrame->document()->sandboxFlags());
 
     if (request.frameName() != "_blank")
-        frame->tree()->setName(request.frameName());
+        frame->tree().setName(request.frameName());
 
     page->chrome().setWindowFeatures(features);
 
@@ -125,10 +125,10 @@
     }
 
     // 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());
+    String referrer = SecurityPolicy::generateReferrerHeader(firstFrame->document()->referrerPolicy(), completedURL, firstFrame->loader().outgoingReferrer());
 
     ResourceRequest request(completedURL, referrer);
-    FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader()->outgoingOrigin());
+    FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader().outgoingOrigin());
     FrameLoadRequest frameRequest(activeWindow->document()->securityOrigin(), request, frameName);
 
     // We pass the opener frame for the lookupFrame in case the active frame is different from
@@ -138,7 +138,7 @@
     if (!newFrame)
         return 0;
 
-    newFrame->loader()->setOpener(openerFrame);
+    newFrame->loader().setOpener(openerFrame);
     newFrame->page()->setOpenedByDOM();
 
     if (newFrame->domWindow()->isInsecureScriptAccess(activeWindow, completedURL))
@@ -149,9 +149,9 @@
 
     if (created) {
         FrameLoadRequest request(activeWindow->document()->securityOrigin(), ResourceRequest(completedURL, referrer));
-        newFrame->loader()->load(request);
+        newFrame->loader().load(request);
     } else if (!urlString.isEmpty()) {
-        newFrame->navigationScheduler()->scheduleLocationChange(activeWindow->document()->securityOrigin(), completedURL.string(), referrer, false);
+        newFrame->navigationScheduler().scheduleLocationChange(activeWindow->document()->securityOrigin(), completedURL.string(), referrer, false);
     }
     return newFrame;
 }
diff --git a/Source/core/page/CreateWindow.h b/Source/core/page/CreateWindow.h
index 7226fa4..a6fe12d 100644
--- a/Source/core/page/CreateWindow.h
+++ b/Source/core/page/CreateWindow.h
@@ -32,7 +32,7 @@
 
 namespace WebCore {
 class Frame;
-class WindowFeatures;
+struct WindowFeatures;
 
 Frame* createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures&,
     DOMWindow* activeWindow, Frame* firstFrame, Frame* openerFrame, DOMWindow::PrepareDialogFunction = 0, void* functionContext = 0);
diff --git a/Source/core/page/DragController.cpp b/Source/core/page/DragController.cpp
index 26e14e1..0856398 100644
--- a/Source/core/page/DragController.cpp
+++ b/Source/core/page/DragController.cpp
@@ -221,7 +221,7 @@
         ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
         RefPtr<Clipboard> clipboard = createDraggingClipboard(policy, dragData);
         clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
-        mainFrame->eventHandler()->cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
+        mainFrame->eventHandler().cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
         clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
     }
     mouseMovedIntoDocument(0);
@@ -246,7 +246,7 @@
             // Sending an event can result in the destruction of the view and part.
             RefPtr<Clipboard> clipboard = createDraggingClipboard(ClipboardReadable, dragData);
             clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
-            preventedDefault = mainFrame->eventHandler()->performDragAndDrop(createMouseEvent(dragData), clipboard.get());
+            preventedDefault = mainFrame->eventHandler().performDragAndDrop(createMouseEvent(dragData), clipboard.get());
             clipboard->setAccessPolicy(ClipboardNumb); // Invalidate clipboard here for security
         }
         if (preventedDefault) {
@@ -265,7 +265,7 @@
     if (operationForLoad(dragData) == DragOperationNone)
         return false;
 
-    m_page->mainFrame()->loader()->load(FrameLoadRequest(0, ResourceRequest(dragData->asURL())));
+    m_page->mainFrame()->loader().load(FrameLoadRequest(0, ResourceRequest(dragData->asURL())));
     return true;
 }
 
@@ -528,7 +528,7 @@
 
     if (rootEditableElement) {
         if (Frame* frame = rootEditableElement->document().frame())
-            frame->eventHandler()->updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
+            frame->eventHandler().updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
     }
 
     return true;
@@ -546,7 +546,7 @@
     if (!m_page->mainFrame()->contentRenderer())
         return false;
 
-    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point);
+    result = m_page->mainFrame()->eventHandler().hitTestResultAtPoint(point);
 
     if (!result.innerNonSharedNode())
         return false;
@@ -601,7 +601,7 @@
     clipboard->setSourceOperation(srcOpMask);
 
     PlatformMouseEvent event = createMouseEvent(dragData);
-    if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
+    if (!mainFrame->eventHandler().updateDragAndDrop(event, clipboard.get())) {
         clipboard->setAccessPolicy(ClipboardNumb);    // invalidate clipboard here for security
         return false;
     }
@@ -697,7 +697,7 @@
     if (!src->view() || !src->contentRenderer())
         return false;
 
-    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
+    HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
     // FIXME: Can this even happen? I guess it's possible, but should verify
     // with a layout test.
     if (!state.m_dragSrc->contains(hitTestResult.innerNode())) {
@@ -817,7 +817,7 @@
     if (!src->view() || !src->contentRenderer())
         return false;
 
-    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin);
+    HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin);
     if (!state.m_dragSrc->contains(hitTestResult.innerNode()))
         // The original node being dragged isn't under the drag origin anymore... maybe it was
         // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index 154516a..530cae3 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -42,7 +42,7 @@
 #include "core/editing/FrameSelection.h"
 #include "core/editing/TextIterator.h"
 #include "core/editing/htmlediting.h"
-#include "core/events/DocumentEventQueue.h"
+#include "core/events/DOMWindowEventQueue.h"
 #include "core/events/EventPath.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/events/MouseEvent.h"
@@ -293,7 +293,7 @@
     , m_mouseDownWasInSubframe(false)
     , m_fakeMouseMoveEventTimer(this, &EventHandler::fakeMouseMoveEventTimerFired)
     , m_svgPan(false)
-    , m_resizeLayer(0)
+    , m_resizeScrollableArea(0)
     , m_eventHandlerWillResetCapturingMouseEventsNode(0)
     , m_clickCount(0)
     , m_shouldOnlyFireDragOverEvent(false)
@@ -327,7 +327,7 @@
     m_hoverTimer.stop();
     m_cursorUpdateTimer.stop();
     m_fakeMouseMoveEventTimer.stop();
-    m_resizeLayer = 0;
+    m_resizeScrollableArea = 0;
     m_nodeUnderMouse = 0;
     m_lastNodeUnderMouse = 0;
     m_instanceUnderMouse = 0;
@@ -880,7 +880,7 @@
             FrameView* mainView = mainFrame->view();
             if (frameView && mainView) {
                 IntPoint mainFramePoint = mainView->rootViewToContents(frameView->contentsToRootView(roundedIntPoint(point)));
-                return mainFrame->eventHandler()->hitTestResultAtPoint(mainFramePoint, hitType, padding);
+                return mainFrame->eventHandler().hitTestResultAtPoint(mainFramePoint, hitType, padding);
             }
         }
     }
@@ -974,10 +974,10 @@
     FrameView* view = frame->view();
     if (view && view->scroll(direction, granularity))
         return true;
-    frame = frame->tree()->parent();
+    frame = frame->tree().parent();
     if (!frame)
         return false;
-    return frame->eventHandler()->scrollRecursively(direction, granularity, m_frame->ownerElement());
+    return frame->eventHandler().scrollRecursively(direction, granularity, m_frame->ownerElement());
 }
 
 bool EventHandler::logicalScrollRecursively(ScrollLogicalDirection direction, ScrollGranularity granularity, Node* startingNode)
@@ -997,11 +997,11 @@
     if (scrolled)
         return true;
 
-    frame = frame->tree()->parent();
+    frame = frame->tree().parent();
     if (!frame)
         return false;
 
-    return frame->eventHandler()->logicalScrollRecursively(direction, granularity, m_frame->ownerElement());
+    return frame->eventHandler().logicalScrollRecursively(direction, granularity, m_frame->ownerElement());
 }
 
 IntPoint EventHandler::lastKnownMousePosition() const
@@ -1120,7 +1120,7 @@
 
 OptionalCursor EventHandler::selectCursor(const HitTestResult& result, bool shiftKey)
 {
-    if (m_resizeLayer && m_resizeLayer->inResizeMode())
+    if (m_resizeScrollableArea && m_resizeScrollableArea->inResizeMode())
         return NoCursorChange;
 
     Page* page = m_frame->page();
@@ -1271,8 +1271,8 @@
     RenderObject* renderer = node ? node->renderer() : 0;
     if (renderer) {
         if (RenderLayer* layer = renderer->enclosingLayer()) {
-            if (FrameView* view = m_frame->view())
-                inResizer = layer->isPointInResizeControl(view->windowToContents(roundedIntPoint(result.localPoint())), ResizerForPointer);
+            if (m_frame->view())
+                inResizer = layer->scrollableArea() && layer->scrollableArea()->isPointInResizeControl(result.roundedPointInMainFrame(), ResizerForPointer);
         }
     }
 
@@ -1307,7 +1307,7 @@
         return true;
 
     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
-    m_frame->tree()->top()->eventHandler()->m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
+    m_frame->tree().top()->eventHandler().m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
 
     cancelFakeMouseMoveEvent();
     if (m_eventHandlerWillResetCapturingMouseEventsNode)
@@ -1344,7 +1344,7 @@
     if (subframe && passMousePressEventToSubframe(mev, subframe.get())) {
         // Start capturing future events for this frame.  We only do this if we didn't clear
         // the m_mousePressed flag, which may happen if an AppKit widget entered a modal event loop.
-        m_capturesDragging = subframe->eventHandler()->capturesDragging();
+        m_capturesDragging = subframe->eventHandler().capturesDragging();
         if (m_mousePressed && m_capturesDragging) {
             m_capturingMouseEventsNode = mev.targetNode();
             m_eventHandlerWillResetCapturingMouseEventsNode = true;
@@ -1372,10 +1372,10 @@
     if (FrameView* view = m_frame->view()) {
         RenderLayer* layer = m_clickNode->renderer() ? m_clickNode->renderer()->enclosingLayer() : 0;
         IntPoint p = view->windowToContents(mouseEvent.position());
-        if (layer && layer->isPointInResizeControl(p, ResizerForPointer)) {
-            layer->setInResizeMode(true);
-            m_resizeLayer = layer;
-            m_offsetFromResizeCorner = layer->offsetFromResizeCorner(p);
+        if (layer && layer->scrollableArea() && layer->scrollableArea()->isPointInResizeControl(p, ResizerForPointer)) {
+            m_resizeScrollableArea = layer->scrollableArea();
+            m_resizeScrollableArea->setInResizeMode(true);
+            m_offsetFromResizeCorner = m_resizeScrollableArea->offsetFromResizeCorner(p);
             invalidateClick();
             return true;
         }
@@ -1550,8 +1550,8 @@
 
     Scrollbar* scrollbar = 0;
 
-    if (m_resizeLayer && m_resizeLayer->inResizeMode())
-        m_resizeLayer->resize(mouseEvent, m_offsetFromResizeCorner);
+    if (m_resizeScrollableArea && m_resizeScrollableArea->inResizeMode())
+        m_resizeScrollableArea->resize(mouseEvent, m_offsetFromResizeCorner);
     else {
         if (FrameView* view = m_frame->view())
             scrollbar = view->scrollbarAtPoint(mouseEvent.position());
@@ -1568,7 +1568,7 @@
     RefPtr<Frame> newSubframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
 
     // We want mouseouts to happen first, from the inside out.  First send a move event to the last subframe so that it will fire mouseouts.
-    if (m_lastMouseMoveEventSubframe && m_lastMouseMoveEventSubframe->tree()->isDescendantOf(m_frame) && m_lastMouseMoveEventSubframe != newSubframe)
+    if (m_lastMouseMoveEventSubframe && m_lastMouseMoveEventSubframe->tree().isDescendantOf(m_frame) && m_lastMouseMoveEventSubframe != newSubframe)
         passMouseMoveEventToSubframe(mev, m_lastMouseMoveEventSubframe.get());
 
     if (newSubframe) {
@@ -1645,8 +1645,8 @@
 
     OwnPtr<UserGestureIndicator> gestureIndicator;
 
-    if (m_frame->tree()->top()->eventHandler()->m_lastMouseDownUserGestureToken)
-        gestureIndicator = adoptPtr(new UserGestureIndicator(m_frame->tree()->top()->eventHandler()->m_lastMouseDownUserGestureToken.release()));
+    if (m_frame->tree().top()->eventHandler().m_lastMouseDownUserGestureToken)
+        gestureIndicator = adoptPtr(new UserGestureIndicator(m_frame->tree().top()->eventHandler().m_lastMouseDownUserGestureToken.release()));
     else
         gestureIndicator = adoptPtr(new UserGestureIndicator(DefinitelyProcessingUserGesture));
 
@@ -1694,9 +1694,9 @@
 
     bool swallowClickEvent = m_clickCount > 0 && !contextMenuEvent && mouseIsReleasedOnPressedElement(mev.targetNode(), m_clickNode.get()) && !dispatchMouseEvent(EventTypeNames::click, mev.targetNode(), true, m_clickCount, mouseEvent, true);
 
-    if (m_resizeLayer) {
-        m_resizeLayer->setInResizeMode(false);
-        m_resizeLayer = 0;
+    if (m_resizeScrollableArea) {
+        m_resizeScrollableArea->setInResizeMode(false);
+        m_resizeScrollableArea = 0;
     }
 
     bool swallowMouseReleaseEvent = false;
@@ -1835,7 +1835,7 @@
         Frame* targetFrame;
         if (targetIsFrame(newTarget.get(), targetFrame)) {
             if (targetFrame)
-                accept = targetFrame->eventHandler()->updateDragAndDrop(event, clipboard);
+                accept = targetFrame->eventHandler().updateDragAndDrop(event, clipboard);
         } else if (newTarget) {
             // As per section 7.9.4 of the HTML 5 spec., we must always fire a drag event before firing a dragenter, dragleave, or dragover event.
             if (dragState().m_dragSrc) {
@@ -1849,7 +1849,7 @@
 
         if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
             if (targetFrame)
-                accept = targetFrame->eventHandler()->updateDragAndDrop(event, clipboard);
+                accept = targetFrame->eventHandler().updateDragAndDrop(event, clipboard);
         } else if (m_dragTarget)
             dispatchDragEvent(EventTypeNames::dragleave, m_dragTarget.get(), event, clipboard);
 
@@ -1862,7 +1862,7 @@
         Frame* targetFrame;
         if (targetIsFrame(newTarget.get(), targetFrame)) {
             if (targetFrame)
-                accept = targetFrame->eventHandler()->updateDragAndDrop(event, clipboard);
+                accept = targetFrame->eventHandler().updateDragAndDrop(event, clipboard);
         } else if (newTarget) {
             // Note, when dealing with sub-frames, we may need to fire only a dragover event as a drag event may have been fired earlier.
             if (!m_shouldOnlyFireDragOverEvent && dragState().m_dragSrc) {
@@ -1885,7 +1885,7 @@
     Frame* targetFrame;
     if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
         if (targetFrame)
-            targetFrame->eventHandler()->cancelDragAndDrop(event, clipboard);
+            targetFrame->eventHandler().cancelDragAndDrop(event, clipboard);
     } else if (m_dragTarget.get()) {
         if (dragState().m_dragSrc)
             dispatchDragSrcEvent(EventTypeNames::drag, event);
@@ -1900,7 +1900,7 @@
     bool preventedDefault = false;
     if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
         if (targetFrame)
-            preventedDefault = targetFrame->eventHandler()->performDragAndDrop(event, clipboard);
+            preventedDefault = targetFrame->eventHandler().performDragAndDrop(event, clipboard);
     } else if (m_dragTarget.get())
         preventedDefault = dispatchDragEvent(EventTypeNames::drop, m_dragTarget.get(), event, clipboard);
     clearDragState();
@@ -2066,7 +2066,7 @@
 
     Element* element = 0;
     if (m_nodeUnderMouse)
-        element = m_nodeUnderMouse->isElementNode() ? toElement(m_nodeUnderMouse.get()) : m_nodeUnderMouse->parentOrShadowHostElement();
+        element = m_nodeUnderMouse->isElementNode() ? toElement(m_nodeUnderMouse) : m_nodeUnderMouse->parentOrShadowHostElement();
     for (; element; element = element->parentOrShadowHostElement()) {
         if (element->isFocusable() && element->focused())
             return !swallowEvent;
@@ -2346,6 +2346,7 @@
         return handleGestureLongTap(gestureEvent);
     case PlatformEvent::GestureTwoFingerTap:
         return handleGestureTwoFingerTap(gestureEvent);
+    case PlatformEvent::GestureTapDown:
     case PlatformEvent::GesturePinchBegin:
     case PlatformEvent::GesturePinchEnd:
     case PlatformEvent::GesturePinchUpdate:
@@ -2389,7 +2390,7 @@
     IntPoint adjustedPoint = gestureEvent.position();
     adjustGesturePosition(gestureEvent, adjustedPoint);
     RefPtr<Frame> subframe = getSubFrameForGestureEvent(adjustedPoint, gestureEvent);
-    if (subframe && subframe->eventHandler()->handleGestureLongPress(gestureEvent))
+    if (subframe && subframe->eventHandler().handleGestureLongPress(gestureEvent))
         return true;
 
     m_longTapShouldInvokeContextMenu = false;
@@ -2438,7 +2439,7 @@
     IntPoint adjustedPoint = gestureEvent.position();
     adjustGesturePosition(gestureEvent, adjustedPoint);
     RefPtr<Frame> subframe = getSubFrameForGestureEvent(adjustedPoint, gestureEvent);
-    if (subframe && subframe->eventHandler()->handleGestureLongTap(gestureEvent))
+    if (subframe && subframe->eventHandler().handleGestureLongTap(gestureEvent))
         return true;
 #if !OS(ANDROID)
     if (m_longTapShouldInvokeContextMenu) {
@@ -2453,22 +2454,22 @@
     if (gestureEvent.type() == PlatformEvent::GestureScrollBegin) {
         RenderLayer* layer = eventTarget->renderer() ? eventTarget->renderer()->enclosingLayer() : 0;
         IntPoint p = m_frame->view()->windowToContents(gestureEvent.position());
-        if (layer && layer->isPointInResizeControl(p, ResizerForTouch)) {
-            layer->setInResizeMode(true);
-            m_resizeLayer = layer;
-            m_offsetFromResizeCorner = layer->offsetFromResizeCorner(p);
+        if (layer && layer->scrollableArea() && layer->scrollableArea()->isPointInResizeControl(p, ResizerForTouch)) {
+            m_resizeScrollableArea = layer->scrollableArea();
+            m_resizeScrollableArea->setInResizeMode(true);
+            m_offsetFromResizeCorner = m_resizeScrollableArea->offsetFromResizeCorner(p);
             return true;
         }
     } else if (gestureEvent.type() == PlatformEvent::GestureScrollUpdate ||
                gestureEvent.type() == PlatformEvent::GestureScrollUpdateWithoutPropagation) {
-        if (m_resizeLayer && m_resizeLayer->inResizeMode()) {
-            m_resizeLayer->resize(gestureEvent, m_offsetFromResizeCorner);
+        if (m_resizeScrollableArea && m_resizeScrollableArea->inResizeMode()) {
+            m_resizeScrollableArea->resize(gestureEvent, m_offsetFromResizeCorner);
             return true;
         }
     } else if (gestureEvent.type() == PlatformEvent::GestureScrollEnd) {
-        if (m_resizeLayer && m_resizeLayer->inResizeMode()) {
-            m_resizeLayer->setInResizeMode(false);
-            m_resizeLayer = 0;
+        if (m_resizeScrollableArea && m_resizeScrollableArea->inResizeMode()) {
+            m_resizeScrollableArea->setInResizeMode(false);
+            m_resizeScrollableArea = 0;
             return false;
         }
     }
@@ -2489,7 +2490,7 @@
     if (!widget->isFrameView())
         return false;
 
-    return toFrameView(widget)->frame().eventHandler()->handleGestureEvent(gestureEvent);
+    return toFrameView(widget)->frame().eventHandler().handleGestureEvent(gestureEvent);
 }
 
 bool EventHandler::passGestureEventToWidgetIfPossible(const PlatformGestureEvent& gestureEvent, RenderObject* renderer)
@@ -2942,10 +2943,10 @@
     m_frameSetBeingResized = frameSet;
 }
 
-void EventHandler::resizeLayerDestroyed()
+void EventHandler::resizeScrollableAreaDestroyed()
 {
-    ASSERT(m_resizeLayer);
-    m_resizeLayer = 0;
+    ASSERT(m_resizeScrollableArea);
+    m_resizeScrollableArea = 0;
 }
 
 void EventHandler::hoverTimerFired(Timer<EventHandler>*)
@@ -3417,7 +3418,7 @@
     Page* page = m_frame->page();
     if (!page)
         return;
-    bool handledEvent = page->mainFrame()->loader()->client()->navigateBackForward(event->shiftKey() ? 1 : -1);
+    bool handledEvent = page->mainFrame()->loader().client()->navigateBackForward(event->shiftKey() ? 1 : -1);
     if (handledEvent)
         event->setDefaultHandled();
 }
@@ -3812,7 +3813,7 @@
         m_frame->selection().setSelection(newSelection);
     }
 
-    subframe->eventHandler()->handleMousePressEvent(mev.event());
+    subframe->eventHandler().handleMousePressEvent(mev.event());
     return true;
 }
 
@@ -3820,13 +3821,13 @@
 {
     if (m_mouseDownMayStartDrag && !m_mouseDownWasInSubframe)
         return false;
-    subframe->eventHandler()->handleMouseMoveOrLeaveEvent(mev.event(), hoveredNode);
+    subframe->eventHandler().handleMouseMoveOrLeaveEvent(mev.event(), hoveredNode);
     return true;
 }
 
 bool EventHandler::passMouseReleaseEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe)
 {
-    subframe->eventHandler()->handleMouseReleaseEvent(mev.event());
+    subframe->eventHandler().handleMouseReleaseEvent(mev.event());
     return true;
 }
 
@@ -3842,7 +3843,7 @@
     if (!widget->isFrameView())
         return false;
 
-    return toFrameView(widget)->frame().eventHandler()->handleWheelEvent(wheelEvent);
+    return toFrameView(widget)->frame().eventHandler().handleWheelEvent(wheelEvent);
 }
 
 bool EventHandler::passWidgetMouseDownEventToWidget(const MouseEventWithHitTestResults& event)
diff --git a/Source/core/page/EventHandler.h b/Source/core/page/EventHandler.h
index bc2206b..d7cd9bb 100644
--- a/Source/core/page/EventHandler.h
+++ b/Source/core/page/EventHandler.h
@@ -64,6 +64,7 @@
 class PlatformTouchEvent;
 class PlatformWheelEvent;
 class RenderLayer;
+class RenderLayerScrollableArea;
 class RenderObject;
 class RenderWidget;
 class SVGElementInstance;
@@ -121,7 +122,7 @@
 
     void setResizingFrameSet(HTMLFrameSetElement*);
 
-    void resizeLayerDestroyed();
+    void resizeScrollableAreaDestroyed();
 
     IntPoint lastKnownMousePosition() const;
     Cursor currentMouseCursor() const { return m_currentMouseCursor; }
@@ -319,7 +320,7 @@
     RefPtr<SVGElementInstance> m_instanceUnderMouse;
     RefPtr<SVGElementInstance> m_lastInstanceUnderMouse;
 
-    RenderLayer* m_resizeLayer;
+    RenderLayerScrollableArea* m_resizeScrollableArea;
 
     RefPtr<Node> m_capturingMouseEventsNode;
     bool m_eventHandlerWillResetCapturingMouseEventsNode;
@@ -338,7 +339,7 @@
 
     RefPtr<HTMLFrameSetElement> m_frameSetBeingResized;
 
-    LayoutSize m_offsetFromResizeCorner; // In the coords of m_resizeLayer.
+    LayoutSize m_offsetFromResizeCorner; // In the coords of m_resizeScrollableArea.
 
     bool m_mousePositionIsUnknown;
     IntPoint m_lastKnownMousePosition;
diff --git a/Source/core/page/EventSource.cpp b/Source/core/page/EventSource.cpp
index d616ad0..061c4d5 100644
--- a/Source/core/page/EventSource.cpp
+++ b/Source/core/page/EventSource.cpp
@@ -89,7 +89,7 @@
     bool shouldBypassMainWorldContentSecurityPolicy = false;
     if (context->isDocument()) {
         Document* document = toDocument(context);
-        shouldBypassMainWorldContentSecurityPolicy = document->frame()->script()->shouldBypassMainWorldContentSecurityPolicy();
+        shouldBypassMainWorldContentSecurityPolicy = document->frame()->script().shouldBypassMainWorldContentSecurityPolicy();
     }
     if (!shouldBypassMainWorldContentSecurityPolicy && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
         // We can safely expose the URL to JavaScript, as this exception is generate synchronously before any redirects take place.
diff --git a/Source/core/page/FocusController.cpp b/Source/core/page/FocusController.cpp
index f77ca1f..7358fd1 100644
--- a/Source/core/page/FocusController.cpp
+++ b/Source/core/page/FocusController.cpp
@@ -42,6 +42,9 @@
 #include "core/editing/htmlediting.h" // For firstPositionInOrBeforeNode
 #include "core/events/Event.h"
 #include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
 #include "core/html/HTMLAreaElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLTextAreaElement.h"
@@ -49,9 +52,7 @@
 #include "core/page/Chrome.h"
 #include "core/page/EditorClient.h"
 #include "core/page/EventHandler.h"
-#include "core/frame/Frame.h"
 #include "core/page/FrameTree.h"
-#include "core/frame/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
 #include "core/page/SpatialNavigation.h"
@@ -144,7 +145,9 @@
                 focusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, 0);
         }
     }
-    document->dispatchWindowEvent(Event::create(focused ? EventTypeNames::focus : EventTypeNames::blur));
+
+    if (DOMWindow* window = document->domWindow())
+        window->dispatchEvent(Event::create(focused ? EventTypeNames::focus : EventTypeNames::blur));
     if (focused && document->focusedElement()) {
         RefPtr<Element> focusedElement(document->focusedElement());
         focusedElement->dispatchFocusEvent(0, FocusDirectionPage);
@@ -236,12 +239,12 @@
     // Now that the frame is updated, fire events and update the selection focused states of both frames.
     if (oldFrame && oldFrame->view()) {
         oldFrame->selection().setFocused(false);
-        oldFrame->document()->dispatchWindowEvent(Event::create(EventTypeNames::blur));
+        oldFrame->domWindow()->dispatchEvent(Event::create(EventTypeNames::blur));
     }
 
     if (newFrame && newFrame->view() && isFocused()) {
         newFrame->selection().setFocused(true);
-        newFrame->document()->dispatchWindowEvent(Event::create(EventTypeNames::focus));
+        newFrame->domWindow()->dispatchEvent(Event::create(EventTypeNames::focus));
     }
 
     m_isChangingFocusedFrame = false;
@@ -262,7 +265,7 @@
     m_isFocused = focused;
 
     if (!m_isFocused)
-        focusedOrMainFrame()->eventHandler()->stopAutoscrollTimer();
+        focusedOrMainFrame()->eventHandler().stopAutoscrollTimer();
 
     if (!m_focusedFrame)
         setFocusedFrame(m_page->mainFrame());
@@ -366,7 +369,7 @@
         // FIXME: May need a way to focus a document here.
         return false;
 
-    Element* element = toElement(node.get());
+    Element* element = toElement(node);
     if (element->isFrameOwnerElement() && (!element->isPluginElement() || !element->isKeyboardFocusable())) {
         // We focus frames rather than frame owners.
         // FIXME: We should not focus frames that have no scrollbars, as focusing them isn't useful to the user.
@@ -595,7 +598,7 @@
     if (selectionStartNode == newFocusedNode || selectionStartNode->isDescendantOf(newFocusedNode) || selectionStartNode->deprecatedShadowAncestorNode() == newFocusedNode)
         return;
 
-    if (Node* mousePressNode = newFocusedFrame->eventHandler()->mousePressNode()) {
+    if (Node* mousePressNode = newFocusedFrame->eventHandler().mousePressNode()) {
         if (mousePressNode->renderer() && !mousePressNode->canStartSelection()) {
             // Don't clear the selection for contentEditable elements, but do clear it for input and textarea. See bug 38696.
             Node* root = selection.rootEditableElement();
@@ -696,7 +699,7 @@
 
     contentAreaDidShowOrHide(view, containingWindowIsVisible);
 
-    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
         FrameView* frameView = frame->view();
         if (!frameView)
             continue;
@@ -744,7 +747,7 @@
         // If 2 nodes are intersecting, do hit test to find which node in on top.
         LayoutUnit x = intersectionRect.x() + intersectionRect.width() / 2;
         LayoutUnit y = intersectionRect.y() + intersectionRect.height() / 2;
-        HitTestResult result = candidate.visibleNode->document().page()->mainFrame()->eventHandler()->hitTestResultAtPoint(IntPoint(x, y), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent);
+        HitTestResult result = candidate.visibleNode->document().page()->mainFrame()->eventHandler().hitTestResultAtPoint(IntPoint(x, y), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent);
         if (candidate.visibleNode->contains(result.innerNode())) {
             closest = candidate;
             return;
diff --git a/Source/core/page/FrameTree.cpp b/Source/core/page/FrameTree.cpp
index 7dbe45e..b7e7dc1 100644
--- a/Source/core/page/FrameTree.cpp
+++ b/Source/core/page/FrameTree.cpp
@@ -36,7 +36,7 @@
 
 FrameTree::~FrameTree()
 {
-    for (Frame* child = firstChild(); child; child = child->tree()->nextSibling())
+    for (Frame* child = firstChild(); child; child = child->tree().nextSibling())
         child->setView(0);
 }
 
@@ -48,7 +48,7 @@
         return;
     }
     m_uniqueName = AtomicString(); // Remove our old frame name so it's not considered in uniqueChildName.
-    m_uniqueName = parent()->tree()->uniqueChildName(name);
+    m_uniqueName = parent()->tree().uniqueChildName(name);
 }
 
 Frame* FrameTree::parent() const
@@ -59,37 +59,37 @@
 void FrameTree::appendChild(PassRefPtr<Frame> child)
 {
     ASSERT(child->page() == m_thisFrame->page());
-    child->tree()->m_parent = m_thisFrame;
+    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;
+        child->tree().m_previousSibling = oldLast;
+        oldLast->tree().m_nextSibling = child;
     } else
         m_firstChild = child;
 
     m_scopedChildCount = invalidCount;
 
-    ASSERT(!m_lastChild->tree()->m_nextSibling);
+    ASSERT(!m_lastChild->tree().m_nextSibling);
 }
 
 void FrameTree::removeChild(Frame* child)
 {
-    child->tree()->m_parent = 0;
+    child->tree().m_parent = 0;
 
     // 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.
 
-    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);
+    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);
+    std::swap(newLocationForPrevious, child->tree().m_previousSibling);
 
-    child->tree()->m_previousSibling = 0;
-    child->tree()->m_nextSibling = 0;
+    child->tree().m_previousSibling = 0;
+    child->tree().m_nextSibling = 0;
 
     m_scopedChildCount = invalidCount;
 }
@@ -113,21 +113,21 @@
     // Find the nearest parent that has a frame with a path in it.
     Vector<Frame*, 16> chain;
     Frame* frame;
-    for (frame = m_thisFrame; frame; frame = frame->tree()->parent()) {
-        if (frame->tree()->uniqueName().startsWith(framePathPrefix))
+    for (frame = m_thisFrame; frame; frame = frame->tree().parent()) {
+        if (frame->tree().uniqueName().startsWith(framePathPrefix))
             break;
         chain.append(frame);
     }
     StringBuilder name;
     name.append(framePathPrefix);
     if (frame) {
-        name.append(frame->tree()->uniqueName().string().substring(framePathPrefixLength,
-            frame->tree()->uniqueName().length() - framePathPrefixLength - framePathSuffixLength));
+        name.append(frame->tree().uniqueName().string().substring(framePathPrefixLength,
+            frame->tree().uniqueName().length() - framePathPrefixLength - framePathSuffixLength));
     }
     for (int i = chain.size() - 1; i >= 0; --i) {
         frame = chain[i];
         name.append('/');
-        name.append(frame->tree()->uniqueName());
+        name.append(frame->tree().uniqueName());
     }
 
     name.appendLiteral("/<!--frame");
@@ -144,7 +144,7 @@
         return 0;
 
     unsigned scopedIndex = 0;
-    for (Frame* result = firstChild(); result; result = result->tree()->nextSibling()) {
+    for (Frame* result = firstChild(); result; result = result->tree().nextSibling()) {
         if (result->inScope(scope)) {
             if (scopedIndex == index)
                 return result;
@@ -161,8 +161,8 @@
     if (!scope)
         return 0;
 
-    for (Frame* child = firstChild(); child; child = child->tree()->nextSibling())
-        if (child->tree()->uniqueName() == name && child->inScope(scope))
+    for (Frame* child = firstChild(); child; child = child->tree().nextSibling())
+        if (child->tree().uniqueName() == name && child->inScope(scope))
             return child;
     return 0;
 }
@@ -173,7 +173,7 @@
         return 0;
 
     unsigned scopedCount = 0;
-    for (Frame* result = firstChild(); result; result = result->tree()->nextSibling()) {
+    for (Frame* result = firstChild(); result; result = result->tree().nextSibling()) {
         if (result->inScope(scope))
             scopedCount++;
     }
@@ -191,15 +191,15 @@
 unsigned FrameTree::childCount() const
 {
     unsigned count = 0;
-    for (Frame* result = firstChild(); result; result = result->tree()->nextSibling())
+    for (Frame* result = firstChild(); result; result = result->tree().nextSibling())
         ++count;
     return count;
 }
 
 Frame* FrameTree::child(const AtomicString& name) const
 {
-    for (Frame* child = firstChild(); child; child = child->tree()->nextSibling())
-        if (child->tree()->uniqueName() == name)
+    for (Frame* child = firstChild(); child; child = child->tree().nextSibling())
+        if (child->tree().uniqueName() == name)
             return child;
     return 0;
 }
@@ -220,8 +220,8 @@
         return 0;
 
     // Search subtree starting with this frame first.
-    for (Frame* frame = m_thisFrame; frame; frame = frame->tree()->traverseNext(m_thisFrame))
-        if (frame->tree()->uniqueName() == name)
+    for (Frame* frame = m_thisFrame; frame; frame = frame->tree().traverseNext(m_thisFrame))
+        if (frame->tree().uniqueName() == name)
             return frame;
 
     // Search the entire tree for this page next.
@@ -231,8 +231,8 @@
     if (!page)
         return 0;
 
-    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
-        if (frame->tree()->uniqueName() == name)
+    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
+        if (frame->tree().uniqueName() == name)
             return frame;
 
     // Search the entire tree of each of the other pages in this namespace.
@@ -242,8 +242,8 @@
     for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) {
         Page* otherPage = *it;
         if (otherPage != page) {
-            for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
-                if (frame->tree()->uniqueName() == name)
+            for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+                if (frame->tree().uniqueName() == name)
                     return frame;
             }
         }
@@ -260,7 +260,7 @@
     if (m_thisFrame->page() != ancestor->page())
         return false;
 
-    for (Frame* frame = m_thisFrame; frame; frame = frame->tree()->parent())
+    for (Frame* frame = m_thisFrame; frame; frame = frame->tree().parent())
         if (frame == ancestor)
             return true;
     return false;
@@ -270,7 +270,7 @@
 {
     Frame* child = firstChild();
     if (child) {
-        ASSERT(!stayWithin || child->tree()->isDescendantOf(stayWithin));
+        ASSERT(!stayWithin || child->tree().isDescendantOf(stayWithin));
         return child;
     }
 
@@ -279,20 +279,20 @@
 
     Frame* sibling = nextSibling();
     if (sibling) {
-        ASSERT(!stayWithin || sibling->tree()->isDescendantOf(stayWithin));
+        ASSERT(!stayWithin || sibling->tree().isDescendantOf(stayWithin));
         return sibling;
     }
 
     Frame* frame = m_thisFrame;
-    while (!sibling && (!stayWithin || frame->tree()->parent() != stayWithin)) {
-        frame = frame->tree()->parent();
+    while (!sibling && (!stayWithin || frame->tree().parent() != stayWithin)) {
+        frame = frame->tree().parent();
         if (!frame)
             return 0;
-        sibling = frame->tree()->nextSibling();
+        sibling = frame->tree().nextSibling();
     }
 
     if (frame) {
-        ASSERT(!stayWithin || !sibling || sibling->tree()->isDescendantOf(stayWithin));
+        ASSERT(!stayWithin || !sibling || sibling->tree().isDescendantOf(stayWithin));
         return sibling;
     }
 
@@ -315,7 +315,7 @@
     // FIXME: besides the wrap feature, this is just the traversePreviousNode algorithm
 
     if (Frame* prevSibling = previousSibling())
-        return prevSibling->tree()->deepLastChild();
+        return prevSibling->tree().deepLastChild();
     if (Frame* parentFrame = parent())
         return parentFrame;
 
@@ -330,7 +330,7 @@
 Frame* FrameTree::deepLastChild() const
 {
     Frame* result = m_thisFrame;
-    for (Frame* last = lastChild(); last; last = last->tree()->lastChild())
+    for (Frame* last = lastChild(); last; last = last->tree().lastChild())
         result = last;
 
     return result;
@@ -339,7 +339,7 @@
 Frame* FrameTree::top() const
 {
     Frame* frame = m_thisFrame;
-    for (Frame* parent = m_thisFrame; parent; parent = parent->tree()->parent())
+    for (Frame* parent = m_thisFrame; parent; parent = parent->tree().parent())
         frame = parent;
     return frame;
 }
@@ -373,7 +373,7 @@
     printIndent(indent);
     printf("  uri=%s\n\n", frame->document()->documentURI().utf8().data());
 
-    for (WebCore::Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
+    for (WebCore::Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling())
         printFrames(child, targetFrame, indent + 1);
 }
 
@@ -384,7 +384,7 @@
         return;
     }
 
-    printFrames(frame->tree()->top(), frame, 0);
+    printFrames(frame->tree().top(), frame, 0);
 }
 
 #endif
diff --git a/Source/core/page/Page.cpp b/Source/core/page/Page.cpp
index bec97a1..b3de6eb 100644
--- a/Source/core/page/Page.cpp
+++ b/Source/core/page/Page.cpp
@@ -27,6 +27,8 @@
 #include "core/editing/Caret.h"
 #include "core/events/Event.h"
 #include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/DOMTimer.h"
+#include "core/frame/DOMWindow.h"
 #include "core/history/HistoryItem.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorInstrumentation.h"
@@ -36,7 +38,6 @@
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/ContextMenuController.h"
-#include "core/frame/DOMTimer.h"
 #include "core/page/DragController.h"
 #include "core/page/FocusController.h"
 #include "core/frame/Frame.h"
@@ -52,6 +53,7 @@
 #include "core/plugins/PluginData.h"
 #include "core/rendering/RenderView.h"
 #include "core/storage/StorageNamespace.h"
+#include "core/workers/SharedWorkerRepositoryClient.h"
 #include "wtf/HashMap.h"
 #include "wtf/RefCountedLeakCounter.h"
 #include "wtf/StdLibExtras.h"
@@ -73,14 +75,14 @@
     // 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) {
-        for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree()->traverseNext())
+        for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
             frames.append(frame);
         InspectorInstrumentation::networkStateChanged(*it, online);
     }
 
     AtomicString eventName = online ? EventTypeNames::online : EventTypeNames::offline;
     for (unsigned i = 0; i < frames.size(); i++)
-        frames[i]->document()->dispatchWindowEvent(Event::create(eventName));
+        frames[i]->domWindow()->dispatchEvent(Event::create(eventName));
 }
 
 float deviceScaleFactor(Frame* frame)
@@ -107,6 +109,7 @@
     , m_backForwardClient(pageClients.backForwardClient)
     , m_editorClient(pageClients.editorClient)
     , m_validationMessageClient(0)
+    , m_sharedWorkerRepositoryClient(0)
     , m_subframeCount(0)
     , m_openedByDOM(false)
     , m_tabKeyCyclesThroughElements(true)
@@ -142,7 +145,7 @@
     clearPageGroup();
     allPages->remove(this);
 
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
         frame->willDetachPage();
         frame->detachFromPage();
     }
@@ -262,6 +265,8 @@
     m_contextMenuController->documentDetached(document);
     if (m_validationMessageClient)
         m_validationMessageClient->documentDetached(*document);
+    if (m_sharedWorkerRepositoryClient)
+        m_sharedWorkerRepositoryClient->documentDetached(document);
 }
 
 bool Page::openedByDOM() const
@@ -280,10 +285,10 @@
     // being deref()-ed. Make sure we can still use it with HistoryController::goToItem later.
     RefPtr<HistoryItem> protector(item);
 
-    if (m_mainFrame->loader()->history()->shouldStopLoadingForHistoryItem(item))
-        m_mainFrame->loader()->stopAllLoaders();
+    if (m_mainFrame->loader().history()->shouldStopLoadingForHistoryItem(item))
+        m_mainFrame->loader().stopAllLoaders();
 
-    m_mainFrame->loader()->history()->goToItem(item);
+    m_mainFrame->loader().history()->goToItem(item);
 }
 
 void Page::clearPageGroup()
@@ -319,13 +324,13 @@
         return;
     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())
+        for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
             frame->document()->setNeedsStyleRecalc();
 }
 
 void Page::setNeedsRecalcStyleInAllFrames()
 {
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext())
+    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
         frame->document()->styleResolverChanged(RecalcStyleDeferred);
 }
 
@@ -349,19 +354,19 @@
         if (!reload)
             continue;
 
-        for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
-            if (frame->loader()->containsPlugins())
+        for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+            if (frame->loader().containsPlugins())
                 framesNeedingReload.append(frame);
         }
     }
 
     for (size_t i = 0; i < framesNeedingReload.size(); ++i)
-        framesNeedingReload[i]->loader()->reload();
+        framesNeedingReload[i]->loader().reload();
 }
 
 PluginData* Page::pluginData() const
 {
-    if (!mainFrame()->loader()->allowPlugins(NotAboutToInstantiatePlugin))
+    if (!mainFrame()->loader().allowPlugins(NotAboutToInstantiatePlugin))
         return 0;
     if (!m_pluginData)
         m_pluginData = PluginData::create(this);
@@ -371,8 +376,8 @@
 static Frame* incrementFrame(Frame* curr, bool forward, bool wrapFlag)
 {
     return forward
-        ? curr->tree()->traverseNextWithWrap(wrapFlag)
-        : curr->tree()->traversePreviousWithWrap(wrapFlag);
+        ? curr->tree().traverseNextWithWrap(wrapFlag)
+        : curr->tree().traversePreviousWithWrap(wrapFlag);
 }
 
 void Page::unmarkAllTextMatches()
@@ -393,8 +398,8 @@
         return;
 
     m_defersLoading = defers;
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext())
-        frame->loader()->setDefersLoading(defers);
+    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
+        frame->loader().setDefersLoading(defers);
 }
 
 void Page::setPageScaleFactor(float scale, const IntPoint& origin)
@@ -461,7 +466,7 @@
             m_userStyleSheet = String::fromUTF8(styleSheetAsUTF8.data(), styleSheetAsUTF8.size());
     }
 
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
         if (frame->document())
             frame->document()->styleEngine()->updatePageUserSheet();
     }
@@ -483,8 +488,8 @@
         Page* page = *it;
         if (page->m_group != group)
             continue;
-        for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree()->traverseNext())
-            frame->document()->visitedLinkState()->invalidateStyleForAllLinks();
+        for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree().traverseNext())
+            frame->document()->visitedLinkState().invalidateStyleForAllLinks();
     }
 }
 
@@ -499,8 +504,8 @@
         Page* page = *it;
         if (page->m_group != group)
             continue;
-        for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree()->traverseNext())
-            frame->document()->visitedLinkState()->invalidateStyleForLink(linkHash);
+        for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree().traverseNext())
+            frame->document()->visitedLinkState().invalidateStyleForLink(linkHash);
     }
 }
 
@@ -517,7 +522,7 @@
         return;
 
     m_timerAlignmentInterval = interval;
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNextWithWrap(false)) {
+    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNextWithWrap(false)) {
         if (frame->document())
             frame->document()->didChangeTimerAlignmentInterval();
     }
@@ -530,7 +535,7 @@
 
 void Page::dnsPrefetchingStateChanged()
 {
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext())
+    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
         frame->document()->initDNSPrefetch();
 }
 
@@ -540,7 +545,7 @@
     ASSERT(m_subframeCount >= 0);
 
     int subframeCount = 0;
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext())
+    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
         ++subframeCount;
 
     ASSERT(m_subframeCount + 1 == subframeCount);
@@ -559,7 +564,7 @@
         setTimerAlignmentInterval(DOMTimer::visiblePageAlignmentInterval());
 
     if (!isInitialState)
-        lifecycleNotifier()->notifyPageVisibilityChanged();
+        lifecycleNotifier().notifyPageVisibilityChanged();
 
     if (!isInitialState && m_mainFrame)
         m_mainFrame->dispatchVisibilityStateChangeEvent();
@@ -589,17 +594,17 @@
 
 void Page::didCommitLoad(Frame* frame)
 {
-    lifecycleNotifier()->notifyDidCommitLoad(frame);
+    lifecycleNotifier().notifyDidCommitLoad(frame);
     if (m_mainFrame == frame)
         useCounter().didCommitLoad();
 }
 
-PageLifecycleNotifier* Page::lifecycleNotifier()
+PageLifecycleNotifier& Page::lifecycleNotifier()
 {
-    return static_cast<PageLifecycleNotifier*>(LifecycleContext::lifecycleNotifier());
+    return static_cast<PageLifecycleNotifier&>(LifecycleContext::lifecycleNotifier());
 }
 
-PassOwnPtr<LifecycleNotifier> Page::createLifecycleNotifier()
+PassOwnPtr<LifecycleNotifier<Page> > Page::createLifecycleNotifier()
 {
     return PageLifecycleNotifier::create(this);
 }
diff --git a/Source/core/page/Page.h b/Source/core/page/Page.h
index bcfe290..b0d088f 100644
--- a/Source/core/page/Page.h
+++ b/Source/core/page/Page.h
@@ -24,8 +24,8 @@
 #include "core/dom/ViewportDescription.h"
 #include "core/page/PageVisibilityState.h"
 #include "core/page/UseCounter.h"
-#include "core/platform/LifecycleContext.h"
 #include "core/rendering/Pagination.h"
+#include "platform/LifecycleContext.h"
 #include "platform/Supplementable.h"
 #include "platform/geometry/LayoutRect.h"
 #include "platform/geometry/Region.h"
@@ -71,6 +71,7 @@
 class ScrollableArea;
 class ScrollingCoordinator;
 class Settings;
+class SharedWorkerRepositoryClient;
 class StorageNamespace;
 class ValidationMessageClient;
 
@@ -78,7 +79,7 @@
 
 float deviceScaleFactor(Frame*);
 
-class Page : public Supplementable<Page>, public LifecycleContext {
+class Page : public Supplementable<Page>, public LifecycleContext<Page> {
     WTF_MAKE_NONCOPYABLE(Page);
     friend class Settings;
 public:
@@ -146,6 +147,8 @@
     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; }
 
     bool autoscrollInProgress() const;
     bool autoscrollInProgress(const RenderBox*) const;
@@ -235,9 +238,10 @@
     void didCommitLoad(Frame*);
 
     static void networkStateChanged(bool online);
+    PassOwnPtr<LifecycleNotifier<Page> > createLifecycleNotifier();
 
 protected:
-    PageLifecycleNotifier* lifecycleNotifier();
+    PageLifecycleNotifier& lifecycleNotifier();
 
 private:
     void initGroup();
@@ -250,8 +254,6 @@
 
     void setTimerAlignmentInterval(double);
 
-    virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
-
     const OwnPtr<AutoscrollController> m_autoscrollController;
     const OwnPtr<Chrome> m_chrome;
     const OwnPtr<DragCaretController> m_dragCaretController;
@@ -272,6 +274,7 @@
     BackForwardClient* m_backForwardClient;
     EditorClient* const m_editorClient;
     ValidationMessageClient* m_validationMessageClient;
+    SharedWorkerRepositoryClient* m_sharedWorkerRepositoryClient;
 
     UseCounter m_useCounter;
 
@@ -286,8 +289,8 @@
 
     Pagination m_pagination;
 
-    mutable String m_userStyleSheet;
-    mutable bool m_didLoadUserStyleSheet;
+    String m_userStyleSheet;
+    bool m_didLoadUserStyleSheet;
 
     RefPtr<PageGroup> m_group;
 
diff --git a/Source/core/page/PageConsole.cpp b/Source/core/page/PageConsole.cpp
index 0cd21cb..be4a6af 100644
--- a/Source/core/page/PageConsole.cpp
+++ b/Source/core/page/PageConsole.cpp
@@ -55,8 +55,6 @@
 {
 }
 
-PageConsole::~PageConsole() { }
-
 void PageConsole::addMessage(MessageSource source, MessageLevel level, const String& message)
 {
     addMessage(source, level, message, String(), 0, 0, 0, 0, 0);
diff --git a/Source/core/page/PageConsole.h b/Source/core/page/PageConsole.h
index 8f92d69..b62d192 100644
--- a/Source/core/page/PageConsole.h
+++ b/Source/core/page/PageConsole.h
@@ -39,10 +39,9 @@
 
 class Page;
 
-class PageConsole {
+class PageConsole FINAL {
 public:
     static PassOwnPtr<PageConsole> create(Page* page) { return adoptPtr(new PageConsole(page)); }
-    virtual ~PageConsole();
 
     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);
diff --git a/Source/core/page/PageGroup.cpp b/Source/core/page/PageGroup.cpp
index d623f59..c163264 100644
--- a/Source/core/page/PageGroup.cpp
+++ b/Source/core/page/PageGroup.cpp
@@ -85,7 +85,7 @@
     // 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())
+        for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
             frame->document()->styleEngine()->invalidateInjectedStyleSheetCache();
     }
 }
diff --git a/Source/core/page/PageGroupLoadDeferrer.cpp b/Source/core/page/PageGroupLoadDeferrer.cpp
index d00a519..be7e7c2 100644
--- a/Source/core/page/PageGroupLoadDeferrer.cpp
+++ b/Source/core/page/PageGroupLoadDeferrer.cpp
@@ -45,11 +45,11 @@
 
                 // Ensure that we notify the client if the initial empty document is accessed before showing anything
                 // modal, to prevent spoofs while the modal window or sheet is visible.
-                otherPage->mainFrame()->loader()->notifyIfInitialDocumentAccessed();
+                otherPage->mainFrame()->loader().notifyIfInitialDocumentAccessed();
 
                 // This code is not logically part of load deferring, but we do not want JS code executed beneath modal
                 // windows or sheets, which is exactly when PageGroupLoadDeferrer is used.
-                for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext())
+                for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree().traverseNext())
                     frame->document()->suspendScheduledTasks();
             }
         }
@@ -67,7 +67,7 @@
         if (Page* page = m_deferredFrames[i]->page()) {
             page->setDefersLoading(false);
 
-            for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
+            for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
                 frame->document()->resumeScheduledTasks();
         }
     }
diff --git a/Source/core/page/PageLifecycleNotifier.cpp b/Source/core/page/PageLifecycleNotifier.cpp
index e786ba0..a48592b 100644
--- a/Source/core/page/PageLifecycleNotifier.cpp
+++ b/Source/core/page/PageLifecycleNotifier.cpp
@@ -29,14 +29,14 @@
 
 namespace WebCore {
 
-PageLifecycleNotifier::PageLifecycleNotifier(LifecycleContext* context)
+PageLifecycleNotifier::PageLifecycleNotifier(Page* context)
     : LifecycleNotifier(context)
 {
 }
 
-void PageLifecycleNotifier::addObserver(LifecycleObserver* observer)
+void PageLifecycleNotifier::addObserver(PageLifecycleNotifier::Observer* observer)
 {
-    if (observer->observerType() == LifecycleObserver::PageLifecycleObserverType) {
+    if (observer->observerType() == Observer::PageLifecycleObserverType) {
         RELEASE_ASSERT(m_iterating != IteratingOverPageObservers);
         m_pageObservers.add(static_cast<PageLifecycleObserver*>(observer));
     }
@@ -44,9 +44,9 @@
     LifecycleNotifier::addObserver(observer);
 }
 
-void PageLifecycleNotifier::removeObserver(LifecycleObserver* observer)
+void PageLifecycleNotifier::removeObserver(PageLifecycleNotifier::Observer* observer)
 {
-    if (observer->observerType() == LifecycleObserver::PageLifecycleObserverType) {
+    if (observer->observerType() == Observer::PageLifecycleObserverType) {
         RELEASE_ASSERT(m_iterating != IteratingOverPageObservers);
         m_pageObservers.remove(static_cast<PageLifecycleObserver*>(observer));
     }
diff --git a/Source/core/page/PageLifecycleNotifier.h b/Source/core/page/PageLifecycleNotifier.h
index 504cd68..5514101 100644
--- a/Source/core/page/PageLifecycleNotifier.h
+++ b/Source/core/page/PageLifecycleNotifier.h
@@ -27,7 +27,7 @@
 #define PageLifecycleNotifier_h
 
 #include "core/page/PageLifecycleObserver.h"
-#include "core/platform/LifecycleNotifier.h"
+#include "platform/LifecycleNotifier.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/TemporaryChange.h"
 
@@ -36,24 +36,24 @@
 class Page;
 class Frame;
 
-class PageLifecycleNotifier : public LifecycleNotifier {
+class PageLifecycleNotifier : public LifecycleNotifier<Page> {
 public:
-    static PassOwnPtr<PageLifecycleNotifier> create(LifecycleContext*);
+    static PassOwnPtr<PageLifecycleNotifier> create(Page*);
 
     void notifyPageVisibilityChanged();
     void notifyDidCommitLoad(Frame*);
 
-    virtual void addObserver(LifecycleObserver*) OVERRIDE;
-    virtual void removeObserver(LifecycleObserver*) OVERRIDE;
+    virtual void addObserver(Observer*) OVERRIDE;
+    virtual void removeObserver(Observer*) OVERRIDE;
 
 private:
-    explicit PageLifecycleNotifier(LifecycleContext*);
+    explicit PageLifecycleNotifier(Page*);
 
     typedef HashSet<PageLifecycleObserver*> PageObserverSet;
     PageObserverSet m_pageObservers;
 };
 
-inline PassOwnPtr<PageLifecycleNotifier> PageLifecycleNotifier::create(LifecycleContext* context)
+inline PassOwnPtr<PageLifecycleNotifier> PageLifecycleNotifier::create(Page* context)
 {
     return adoptPtr(new PageLifecycleNotifier(context));
 }
diff --git a/Source/core/page/PageLifecycleObserver.cpp b/Source/core/page/PageLifecycleObserver.cpp
index 175aca6..040dccc 100644
--- a/Source/core/page/PageLifecycleObserver.cpp
+++ b/Source/core/page/PageLifecycleObserver.cpp
@@ -31,6 +31,16 @@
 
 namespace WebCore {
 
+template<> void observerContext(Page* context, LifecycleObserver<Page>* observer)
+{
+    context->wasObservedBy(observer);
+}
+
+template<> void unobserverContext(Page* context, LifecycleObserver<Page>* observer)
+{
+    context->wasUnobservedBy(observer);
+}
+
 PageLifecycleObserver::PageLifecycleObserver(Page* page)
     : LifecycleObserver(page, PageLifecycleObserverType)
 {
diff --git a/Source/core/page/PageLifecycleObserver.h b/Source/core/page/PageLifecycleObserver.h
index 6262695..86c0eb0 100644
--- a/Source/core/page/PageLifecycleObserver.h
+++ b/Source/core/page/PageLifecycleObserver.h
@@ -27,14 +27,17 @@
 #ifndef PageLifecycleObserver_h
 #define PageLifecycleObserver_h
 
-#include "core/platform/LifecycleObserver.h"
+#include "platform/LifecycleObserver.h"
 
 namespace WebCore {
 
 class Frame;
 class Page;
 
-class PageLifecycleObserver : public LifecycleObserver {
+template<> void observerContext(Page*, LifecycleObserver<Page>*);
+template<> void unobserverContext(Page*, LifecycleObserver<Page>*);
+
+class PageLifecycleObserver : public LifecycleObserver<Page> {
 public:
     explicit PageLifecycleObserver(Page*);
     virtual ~PageLifecycleObserver();
diff --git a/Source/core/page/PagePopupController.cpp b/Source/core/page/PagePopupController.cpp
index 8950000..ba31b02 100644
--- a/Source/core/page/PagePopupController.cpp
+++ b/Source/core/page/PagePopupController.cpp
@@ -32,8 +32,8 @@
 #include "core/page/PagePopupController.h"
 
 #include "core/page/PagePopupClient.h"
-#include "core/platform/HistogramSupport.h"
 #include "platform/text/PlatformLocale.h"
+#include "public/platform/Platform.h"
 
 namespace WebCore {
 
@@ -101,7 +101,7 @@
 
 void PagePopupController::histogramEnumeration(const String& name, int sample, int boundaryValue)
 {
-    HistogramSupport::histogramEnumeration(name.utf8().data(), sample, boundaryValue);
+    WebKit::Platform::current()->histogramEnumeration(name.utf8().data(), sample, boundaryValue);
 }
 
 }
diff --git a/Source/core/page/PageSerializer.cpp b/Source/core/page/PageSerializer.cpp
index b6805d2..59a6542 100644
--- a/Source/core/page/PageSerializer.cpp
+++ b/Source/core/page/PageSerializer.cpp
@@ -248,7 +248,7 @@
         }
     }
 
-    for (Frame* childFrame = frame->tree()->firstChild(); childFrame; childFrame = childFrame->tree()->nextSibling())
+    for (Frame* childFrame = frame->tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling())
         serializeFrame(childFrame);
 }
 
diff --git a/Source/core/page/PointerLockController.cpp b/Source/core/page/PointerLockController.cpp
index 9230453..d83f7b4 100644
--- a/Source/core/page/PointerLockController.cpp
+++ b/Source/core/page/PointerLockController.cpp
@@ -27,6 +27,7 @@
 
 #include "core/dom/Element.h"
 #include "core/events/Event.h"
+#include "core/frame/DOMWindow.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/Page.h"
@@ -152,8 +153,8 @@
 
 void PointerLockController::enqueueEvent(const AtomicString& type, Document* document)
 {
-    if (document)
-        document->enqueueDocumentEvent(Event::create(type));
+    if (document && document->domWindow())
+        document->domWindow()->enqueueDocumentEvent(Event::create(type));
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/RuntimeEnabledFeatures.in b/Source/core/page/RuntimeEnabledFeatures.in
deleted file mode 100644
index 2cce886..0000000
--- a/Source/core/page/RuntimeEnabledFeatures.in
+++ /dev/null
@@ -1,124 +0,0 @@
-// http://dev.chromium.org/blink/runtime-enabled-features
-//
-// This list is used to generate RuntimeEnabledFeatures.h/cpp which contains
-// a class that stores static enablers for all experimental features.
-//
-// Each feature can be assigned a "status":
-// status=stable -> Enable this in all Blink configurations.  We are committed to these APIs indefinitely.
-// status=experimental -> In-progress features, Web Developers might play with, but are not on by default in stable.
-// status=test -> Enabled in ContentShell for testing, otherwise off.
-// Features without a status are not enabled anywhere by default.
-//
-// "stable" features listed here should be rare, as anything which we've shipped stable
-// can have its runtime flag removed soon after.
-//
-// condition=ENABLE_NAME is used for wrapping features in compile-time
-// #if ENABLE(FEATURE) guards.  These are deprecated and should all be removed.
-
-AnimatedWebP status=stable
-ApplicationCache status=stable
-AuthorShadowDOMForAnyElement
-Crypto status=experimental
-CSSAnimationUnprefixed status=experimental
-CSSCompositing status=experimental
-CSSCustomFilter status=experimental
-CSSExclusions status=experimental
-CSSGridLayout status=experimental
-CSSMaskSourceType status=experimental
-CSSRegions status=experimental
-CSSShapes status=experimental
-CSSStickyPosition status=experimental
-CSSTouchAction status=test
-CSSVariables status=experimental
-CSSViewport status=experimental
-CSS3Text status=experimental
-CSS3TextDecorations status=experimental
-CustomElements status=experimental
-Database status=stable
-DataListElement status=stable
-DateExtension status=stable
-DeviceMotion status=stable
-DeviceOrientation status=stable
-DevicePixelRatioIncludesZoom status=stable
-DialogElement status=experimental
-DirectoryUpload status=stable
-DirectWrite
-// FIXME: Remove this separate feature when CustomElements are always enabled
-EmbedderCustomElements
-EncodingAPI status=experimental
-EncryptedMedia status=experimental
-EncryptedMediaAnyVersion status=stable
-ExperimentalCanvasFeatures status=test
-ExperimentalContentSecurityPolicyFeatures status=experimental
-FileSystem status=stable
-FontLoadEvents status=experimental
-Fullscreen status=stable
-FastTextAutosizing
-Gamepad status=stable
-Geolocation status=stable
-HTMLImports status=test
-HighResolutionTimeInWorkers status=experimental
-IMEAPI status=test
-IndexedDB status=stable
-IndexedDBExperimental status=experimental
-InputModeAttribute status=test
-InputTypeColor status=stable
-InputTypeWeek status=stable
-LangAttributeAwareFormControlUI
-PrefixedEncryptedMedia status=stable
-LocalStorage status=stable
-Media status=stable
-MediaSource status=stable
-MediaStream status=stable
-Notifications status=stable
-ObjectFitPosition status=stable
-// Only enabled on Android, and for certain layout tests on Linux.
-OverlayFullscreenVideo
-PagePopup status=stable
-PartialLayout status=experimental
-PathOpsSVGClipping
-PeerConnection depends_on=MediaStream, status=stable
-// Implementation of this feature varies by platform for now.
-// Bug to track removal once completed everywhere:
-//   http://crbug.com/308649
-PointerEventsMaxTouchPoints status=experimental
-ProgrammaticScrollNotifications status=test
-Promise status=experimental
-Quota status=stable
-OverlayScrollbars
-RegionBasedColumns status=experimental
-RequestAutocomplete status=test
-RowSpanLogicalHeightSpreading status=stable
-ScriptedSpeech status=stable
-SeamlessIFrames status=experimental
-ServiceWorker status=experimental
-SessionStorage status=stable
-ShadowDOM status=experimental
-SharedWorker custom
-SpeechInput status=stable
-SpeechSynthesis status=experimental
-Srcset status=experimental
-Stream status=experimental
-StyleScoped status=experimental
-SubpixelFontScaling
-SVGPaintOrder status=experimental
-
-// Many websites disable mouse support when touch APIs are available.  We'd
-// like to enable this always but can't until more websites fix this bug.
-// Chromium sets this conditionally (eg. based on the presence of a
-// touchscreen) in ApplyWebPreferences.
-Touch status=stable
-
-UserSelectAll status=experimental
-Vibration status=experimental
-VideoTrack status=stable
-WebAnimations
-WebAnimationsCSS depends_on=WebAnimations
-WebAnimationsSVG depends_on=WebAnimations
-WebAudio condition=WEB_AUDIO, status=stable
-WebGLDraftExtensions status=experimental
-WebMIDI status=test
-WebKitMediaSource status=stable
-WebVTTRegions status=experimental
-WOFF2 status=experimental
-XSLT status=stable
diff --git a/Source/core/page/Settings.cpp b/Source/core/page/Settings.cpp
index 479a0a5..a74fe47 100644
--- a/Source/core/page/Settings.cpp
+++ b/Source/core/page/Settings.cpp
@@ -44,7 +44,7 @@
 
 static void setImageLoadingSettings(Page* page)
 {
-    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
         frame->document()->fetcher()->setImagesEnabled(page->settings().areImagesEnabled());
         frame->document()->fetcher()->setAutoLoadImages(page->settings().loadsImagesAutomatically());
     }
@@ -132,8 +132,8 @@
     , m_touchEventEmulationEnabled(false)
     , m_openGLMultisamplingEnabled(false)
     , m_viewportEnabled(false)
-    , m_setImageLoadingSettingsTimer(this, &Settings::imageLoadingSettingsTimerFired)
     , m_compositorDrivenAcceleratedScrollingEnabled(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.
 }
@@ -263,7 +263,7 @@
     m_textAutosizingFontScaleFactor = fontScaleFactor;
 
     // 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())
+    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext())
         frame->document()->textAutosizer()->recalculateMultipliers();
 
     m_page->setNeedsRecalcStyleInAllFrames();
diff --git a/Source/core/page/Settings.in b/Source/core/page/Settings.in
index 1b56131..4cbdad0 100644
--- a/Source/core/page/Settings.in
+++ b/Source/core/page/Settings.in
@@ -123,6 +123,7 @@
 privilegedWebGLExtensionsEnabled initial=false
 accelerated2dCanvasEnabled initial=false
 antialiased2dCanvasEnabled initial=true
+accelerated2dCanvasMSAASampleCount type=int, initial=0
 
 # WebAudio support.
 webAudioEnabled initial=false
diff --git a/Source/core/page/SpatialNavigation.cpp b/Source/core/page/SpatialNavigation.cpp
index 57ac410..e75aabd 100644
--- a/Source/core/page/SpatialNavigation.cpp
+++ b/Source/core/page/SpatialNavigation.cpp
@@ -502,7 +502,7 @@
 static LayoutRect rectToAbsoluteCoordinates(Frame* initialFrame, const LayoutRect& initialRect)
 {
     LayoutRect rect = initialRect;
-    for (Frame* frame = initialFrame; frame; frame = frame->tree()->parent()) {
+    for (Frame* frame = initialFrame; frame; frame = frame->tree().parent()) {
         if (Element* element = frame->ownerElement()) {
             do {
                 rect.move(element->offsetLeft(), element->offsetTop());
diff --git a/Source/core/page/TouchDisambiguation.cpp b/Source/core/page/TouchDisambiguation.cpp
index a2f46dc..c3e2a5f 100644
--- a/Source/core/page/TouchDisambiguation.cpp
+++ b/Source/core/page/TouchDisambiguation.cpp
@@ -97,7 +97,7 @@
     IntPoint touchPoint = touchBox.center();
     IntPoint contentsPoint = mainFrame->view()->windowToContents(touchPoint);
 
-    HitTestResult result = mainFrame->eventHandler()->hitTestResultAtPoint(contentsPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent, IntSize(touchPointPadding, touchPointPadding));
+    HitTestResult result = mainFrame->eventHandler().hitTestResultAtPoint(contentsPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent, IntSize(touchPointPadding, touchPointPadding));
     const ListHashSet<RefPtr<Node> >& hitResults = result.rectBasedTestResult();
 
     // Blacklist nodes that are container of disambiguated nodes.
diff --git a/Source/core/page/UseCounter.cpp b/Source/core/page/UseCounter.cpp
index 39b5d9b..e821e0f 100644
--- a/Source/core/page/UseCounter.cpp
+++ b/Source/core/page/UseCounter.cpp
@@ -34,7 +34,7 @@
 #include "core/frame/DOMWindow.h"
 #include "core/page/Page.h"
 #include "core/page/PageConsole.h"
-#include "core/platform/HistogramSupport.h"
+#include "public/platform/Platform.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -529,19 +529,19 @@
 UseCounter::~UseCounter()
 {
     // We always log PageDestruction so that we have a scale for the rest of the features.
-    HistogramSupport::histogramEnumeration("WebCore.FeatureObserver", PageDestruction, NumberOfFeatures);
+    WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", PageDestruction, NumberOfFeatures);
 
     updateMeasurements();
 }
 
 void UseCounter::updateMeasurements()
 {
-    HistogramSupport::histogramEnumeration("WebCore.FeatureObserver", PageVisits, NumberOfFeatures);
+    WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", PageVisits, NumberOfFeatures);
 
     if (m_countBits) {
         for (unsigned i = 0; i < NumberOfFeatures; ++i) {
             if (m_countBits->quickGet(i))
-                HistogramSupport::histogramEnumeration("WebCore.FeatureObserver", i, NumberOfFeatures);
+                WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", i, NumberOfFeatures);
         }
         // Clearing count bits is timing sensitive.
         m_countBits->clearAll();
@@ -554,13 +554,13 @@
     for (int i = firstCSSProperty; i <= lastCSSProperty; ++i) {
         if (m_CSSFeatureBits.quickGet(i)) {
             int cssSampleId = mapCSSPropertyIdToCSSSampleIdForHistogram(i);
-            HistogramSupport::histogramEnumeration("WebCore.FeatureObserver.CSSProperties", cssSampleId, maximumCSSSampleId());
+            WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver.CSSProperties", cssSampleId, maximumCSSSampleId());
             needsPagesMeasuredUpdate = true;
         }
     }
 
     if (needsPagesMeasuredUpdate)
-        HistogramSupport::histogramEnumeration("WebCore.FeatureObserver.CSSProperties", totalPagesMeasuredCSSSampleId(), maximumCSSSampleId());
+        WebKit::Platform::current()->histogramEnumeration("WebCore.FeatureObserver.CSSProperties", totalPagesMeasuredCSSSampleId(), maximumCSSSampleId());
 
     m_CSSFeatureBits.clearAll();
 }
@@ -693,8 +693,7 @@
     ASSERT(feature <= lastCSSProperty);
     ASSERT(!isInternalProperty(feature));
 
-    // We don't count the UA style sheet in our statistics.
-    if (context.mode == UASheetMode)
+    if (!isUseCounterEnabledForMode(context.mode))
         return;
 
     m_CSSFeatureBits.quickSet(feature);
diff --git a/Source/core/page/UseCounter.h b/Source/core/page/UseCounter.h
index b136951..030fd96 100644
--- a/Source/core/page/UseCounter.h
+++ b/Source/core/page/UseCounter.h
@@ -233,6 +233,22 @@
         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.
         // Add new features immediately above this line. Don't change assigned
         // numbers of each items, and don't reuse unused slots.
         NumberOfFeatures, // This enum value must be last.
diff --git a/Source/core/page/make_settings.pl b/Source/core/page/make_settings.pl
deleted file mode 100755
index dd29711..0000000
--- a/Source/core/page/make_settings.pl
+++ /dev/null
@@ -1,531 +0,0 @@
-#!/usr/bin/perl -w
-
-# Copyright (C) 2012 Tony Chang <tony@chromium.org>
-#
-# 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.
-
-use strict;
-
-use InFilesCompiler;
-
-my %defaultParameters = (
-);
-
-my %webcoreTypeToIdlType = (
-    'int' => 'long',
-    'unsigned' => 'unsigned long',
-    'size_t' => 'unsigned long',
-    'double' => 'double',
-    'float' => 'float',
-    'String' => 'DOMString',
-    'bool' => 'boolean'
-);
-
-sub defaultItemFactory
-{
-    return (
-        'conditional' => 0,
-        'initial' => '',
-        'type' => 'bool',
-        'setNeedsStyleRecalcInAllFrames' => 0,
-    );
-}
-
-my $InCompiler = InFilesCompiler->new(\%defaultParameters, \&defaultItemFactory);
-
-my $outputDir = $InCompiler->initializeFromCommandLine();
-$InCompiler->compile(\&generateCode);
-
-sub generateCode()
-{
-    my $parsedParametersRef = shift;
-    my $parsedItemsRef = shift;
-
-    generateSettingsMacrosHeader($parsedItemsRef);
-    generateInternalSettingsIdlFile($parsedItemsRef);
-    generateInternalSettingsHeaderFile($parsedItemsRef);
-    generateInternalSettingsCppFile($parsedItemsRef);
-}
-
-sub generateSettingsMacrosHeader($)
-{
-    my $parsedItemsRef = shift;
-
-    my %parsedItems = %{ $parsedItemsRef };
-    my $outputFile = "$outputDir/SettingsMacros.h";
-
-    my %unconditionalSettings = ();
-    my %settingsByConditional = ();
-
-    for my $settingName (sort keys %parsedItems) {
-        my $conditional = $parsedItems{$settingName}{"conditional"};
-
-        if ($conditional) {
-            if (!defined($settingsByConditional{$conditional})) {
-                $settingsByConditional{$conditional} = ();
-            }
-            $settingsByConditional{$conditional}{$settingName} = 1;
-        } else {
-            $unconditionalSettings{$settingName} = 1;
-        }
-    }
-
-    open my $file, ">$outputFile" or die "Failed to open file: $!";
-
-    print $file $InCompiler->license();
-
-    # FIXME: Sort by type so bools come last and are bit packed.
-
-    print $file "#ifndef SettingsMacros_h\n";
-    print $file "#define SettingsMacros_h\n\n";
-
-    printConditionalMacros($file, \%settingsByConditional, $parsedItemsRef);
-
-    printGettersAndSetters($file, \%unconditionalSettings, \%settingsByConditional, $parsedItemsRef);
-    printMemberVariables($file, \%unconditionalSettings, \%settingsByConditional, $parsedItemsRef);
-    printInitializerList($file, \%unconditionalSettings, \%settingsByConditional, $parsedItemsRef);
-    printSetterBodies($file, \%unconditionalSettings, \%settingsByConditional, $parsedItemsRef);
-
-    print $file "#endif // SettingsMacros_h\n";
-
-    close $file;
-}
-
-sub printConditionalMacros($$$)
-{
-    my ($file, $settingsByConditionalRef, $parsedItemsRef) = @_;
-    my %parsedItems = %{ $parsedItemsRef };
-    my %settingsByConditional = %{ $settingsByConditionalRef };
-
-    for my $conditional (sort keys %settingsByConditional) {
-        my $preferredConditional = $InCompiler->preferredConditional($conditional);
-        print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
-
-        print $file "#define ${preferredConditional}_SETTINGS_GETTER_AND_SETTERS \\\n";
-        for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
-            printGetterAndSetter($file, $settingName, $parsedItems{$settingName}{"type"}, $parsedItems{$settingName}{"setNeedsStyleRecalcInAllFrames"});
-        }
-        print $file "// End of ${preferredConditional}_SETTINGS_GETTER_AND_SETTERS\n";
-
-        print $file "#define ${preferredConditional}_SETTINGS_NON_BOOL_MEMBER_VARIABLES \\\n";
-        for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
-            my $type = $parsedItems{$settingName}{"type"};
-            next if $type eq "bool";
-            print $file "    $type m_$settingName; \\\n"
-        }
-        print $file "// End of ${preferredConditional}_SETTINGS_NON_BOOL_MEMBER_VARIABLES\n";
-
-        print $file "#define ${preferredConditional}_SETTINGS_BOOL_MEMBER_VARIABLES \\\n";
-        for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
-            next if $parsedItems{$settingName}{"type"} ne "bool";
-            print $file "    bool m_$settingName : 1; \\\n"
-        }
-        print $file "// End of ${preferredConditional}_SETTINGS_BOOL_MEMBER_VARIABLES\n";
-
-        print $file "#define ${preferredConditional}_SETTINGS_NON_BOOL_INITIALIZERS \\\n";
-        for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
-            next if $parsedItems{$settingName}{"type"} eq "bool";
-            printInitializer($file, $settingName, $parsedItemsRef);
-        }
-        print $file "// End of ${preferredConditional}_SETTINGS_NON_BOOL_INITIALIZERS\n";
-
-        print $file "#define ${preferredConditional}_SETTINGS_BOOL_INITIALIZERS \\\n";
-        for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
-            next if $parsedItems{$settingName}{"type"} ne "bool";
-            printInitializer($file, $settingName, $parsedItemsRef);
-        }
-        print $file "// End of ${preferredConditional}_SETTINGS_BOOL_INITIALIZERS\n";
-
-        print $file "#define ${preferredConditional}_SETTINGS_SETTER_BODIES \\\n";
-        for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
-            printSetterBody($file, $settingName, $parsedItems{$settingName}{"type"}, $parsedItems{$settingName}{"setNeedsStyleRecalcInAllFrames"});
-        }
-        print $file "// End of ${preferredConditional}_SETTINGS_SETTER_BODIES\n";
-
-        print $file "#else\n";
-        print $file "#define ${preferredConditional}_SETTINGS_GETTER_AND_SETTERS\n";
-        print $file "#define ${preferredConditional}_SETTINGS_NON_BOOL_MEMBER_VARIABLES\n";
-        print $file "#define ${preferredConditional}_SETTINGS_BOOL_MEMBER_VARIABLES\n";
-        print $file "#define ${preferredConditional}_SETTINGS_NON_BOOL_INITIALIZERS\n";
-        print $file "#define ${preferredConditional}_SETTINGS_BOOL_INITIALIZERS\n";
-        print $file "#define ${preferredConditional}_SETTINGS_SETTER_BODIES\n";
-        print $file "#endif\n";
-        print $file "\n";
-    }
-}
-
-sub printGettersAndSetters($$$$)
-{
-    my ($file, $unconditionalSettingsRef, $settingsByConditionalRef, $parsedItemsRef) = @_;
-    my %parsedItems = %{ $parsedItemsRef };
-    my %unconditionalSettings = %{ $unconditionalSettingsRef };
-    my %settingsByConditional = %{ $settingsByConditionalRef };
-
-    print $file "#define SETTINGS_GETTERS_AND_SETTERS \\\n";
-    for my $settingName (sort keys %unconditionalSettings) {
-        printGetterAndSetter($file, $settingName, $parsedItems{$settingName}{"type"}, $parsedItems{$settingName}{"setNeedsStyleRecalcInAllFrames"});
-    }
-    for my $conditional (sort keys %settingsByConditional) {
-        my $preferredConditional = $InCompiler->preferredConditional($conditional);
-        print $file "    ${preferredConditional}_SETTINGS_GETTER_AND_SETTERS \\\n";
-    }
-    print $file "// End of SETTINGS_GETTERS_AND_SETTERS.\n\n";
-}
-
-sub printMemberVariables($$$$)
-{
-    my ($file, $unconditionalSettingsRef, $settingsByConditionalRef, $parsedItemsRef) = @_;
-    my %parsedItems = %{ $parsedItemsRef };
-    my %unconditionalSettings = %{ $unconditionalSettingsRef };
-    my %settingsByConditional = %{ $settingsByConditionalRef };
-
-    print $file "#define SETTINGS_MEMBER_VARIABLES \\\n";
-    # We list the bools last so we can bit pack them.
-    for my $settingName (sort keys %unconditionalSettings) {
-        my $type = $parsedItems{$settingName}{"type"};
-        next if $type eq "bool";
-        print $file "    $type m_$settingName; \\\n"
-    }
-    for my $conditional (sort keys %settingsByConditional) {
-        my $preferredConditional = $InCompiler->preferredConditional($conditional);
-        print $file "    ${preferredConditional}_SETTINGS_NON_BOOL_MEMBER_VARIABLES \\\n";
-    }
-    for my $settingName (sort keys %unconditionalSettings) {
-        next if $parsedItems{$settingName}{"type"} ne "bool";
-        print $file "    bool m_$settingName : 1; \\\n"
-    }
-    for my $conditional (sort keys %settingsByConditional) {
-        my $preferredConditional = $InCompiler->preferredConditional($conditional);
-        print $file "    ${preferredConditional}_SETTINGS_BOOL_MEMBER_VARIABLES \\\n";
-    }
-    print $file "// End of SETTINGS_MEMBER_VARIABLES.\n\n";
-}
-
-sub setterFunctionName($)
-{
-    my $settingName = shift;
-    my $setterFunctionName = "set" . $settingName;
-    substr($setterFunctionName, 3, 1) = uc(substr($setterFunctionName, 3, 1));
-    my @prefixesToUpperCase = ("css", "xss", "ftp", "dom");
-    foreach my $prefix (@prefixesToUpperCase) {
-        my $prefixLength = length($prefix);
-        if (substr($settingName, 0, $prefixLength) eq $prefix) {
-            substr($setterFunctionName, $prefixLength, $prefixLength) = uc(substr($setterFunctionName, 3, 3));
-        }
-    }
-    return $setterFunctionName;
-}
-
-sub printGetterAndSetter($$$$)
-{
-    my ($file, $settingName, $type, $setNeedsStyleRecalcInAllFrames) = @_;
-    my $setterFunctionName = setterFunctionName($settingName);
-    if (lc(substr($type, 0, 1)) eq substr($type, 0, 1)) {
-        print $file "    $type $settingName() const { return m_$settingName; } \\\n";
-        print $file "    void $setterFunctionName($type $settingName)";
-    } else {
-        print $file "    const $type& $settingName() { return m_$settingName; } \\\n";
-        print $file "    void $setterFunctionName(const $type& $settingName)";
-    }
-    if ($setNeedsStyleRecalcInAllFrames) {
-        print $file "; \\\n";
-    } else {
-        print $file " { m_$settingName = $settingName; } \\\n";
-    }
-}
-
-sub printInitializerList($$$$)
-{
-    my ($file, $unconditionalSettingsRef, $settingsByConditionalRef, $parsedItemsRef) = @_;
-    my %parsedItems = %{ $parsedItemsRef };
-    my %unconditionalSettings = %{ $unconditionalSettingsRef };
-    my %settingsByConditional = %{ $settingsByConditionalRef };
-
-    print $file "#define SETTINGS_INITIALIZER_LIST \\\n";
-    for my $settingName (sort keys %unconditionalSettings) {
-        next if $parsedItems{$settingName}{"type"} eq "bool";
-        printInitializer($file, $settingName, $parsedItemsRef);
-    }
-    for my $conditional (sort keys %settingsByConditional) {
-        my $preferredConditional = $InCompiler->preferredConditional($conditional);
-        print $file "    ${preferredConditional}_SETTINGS_NON_BOOL_INITIALIZERS \\\n";
-    }
-    for my $settingName (sort keys %unconditionalSettings) {
-        next if $parsedItems{$settingName}{"type"} ne "bool";
-        printInitializer($file, $settingName, $parsedItemsRef);
-    }
-    for my $conditional (sort keys %settingsByConditional) {
-        my $preferredConditional = $InCompiler->preferredConditional($conditional);
-        print $file "    ${preferredConditional}_SETTINGS_BOOL_INITIALIZERS \\\n";
-    }
-    print $file "// End of SETTINGS_INITIALIZER_LIST.\n\n";
-}
-
-sub printInitializer($$$)
-{
-    my ($file, $settingName, $parsedItemsRef) = @_;
-    my %parsedItems = %{ $parsedItemsRef };
-
-    my $initialValue = $parsedItems{$settingName}{"initial"};
-    my $type = $parsedItems{$settingName}{"type"};
-    die "Must provide an initial value for $settingName." if ($initialValue eq '' && lc(substr($type, 0, 1)) eq substr($type, 0, 1));
-    return if ($initialValue eq '');
-    print $file "    , m_$settingName($initialValue) \\\n"
-}
-
-sub printSetterBodies($$$$)
-{
-    my ($file, $unconditionalSettingsRef, $settingsByConditionalRef, $parsedItemsRef) = @_;
-    my %parsedItems = %{ $parsedItemsRef };
-    my %unconditionalSettings = %{ $unconditionalSettingsRef };
-    my %settingsByConditional = %{ $settingsByConditionalRef };
-
-    print $file "#define SETTINGS_SETTER_BODIES \\\n";
-    for my $settingName (sort keys %unconditionalSettings) {
-        printSetterBody($file, $settingName, $parsedItems{$settingName}{"type"}, $parsedItems{$settingName}{"setNeedsStyleRecalcInAllFrames"});
-    }
-    for my $conditional (sort keys %settingsByConditional) {
-        my $preferredConditional = $InCompiler->preferredConditional($conditional);
-        print $file "    ${preferredConditional}_SETTINGS_SETTER_BODIES \\\n";
-    }
-    print $file "// End of SETTINGS_SETTER_BODIES.\n\n";
-}
-
-sub printSetterBody($$$$)
-{
-    my ($file, $settingName, $type, $setNeedsStyleRecalcInAllFrames) = @_;
-    return if (!$setNeedsStyleRecalcInAllFrames);
-
-    my $setterFunctionName = setterFunctionName($settingName);
-    if (lc(substr($type, 0, 1)) eq substr($type, 0, 1)) {
-        print $file "void Settings::$setterFunctionName($type $settingName) \\\n";
-    } else {
-        print $file "void Settings::$setterFunctionName(const $type& $settingName) \\\n";
-    }
-    print $file "{ \\\n";
-    print $file "    if (m_$settingName == $settingName) \\\n";
-    print $file "        return; \\\n";
-    print $file "    m_$settingName = $settingName; \\\n";
-    print $file "    m_page->setNeedsRecalcStyleInAllFrames(); \\\n";
-    print $file "} \\\n";
-}
-
-sub enumerateParsedItems($$$)
-{
-    my ($file, $parsedItemsRef, $visitorFunction) = @_;
-    my %parsedItems = %{ $parsedItemsRef };
-
-    for my $settingName (sort keys %parsedItems) {
-        my $type = $parsedItems{$settingName}{"type"};
-        # FIXME: Learn how to auto-generate code for enumerate types.
-        next if (!defined($webcoreTypeToIdlType{$type}));
-
-        &$visitorFunction($file, $parsedItemsRef, $settingName)
-    }
-}
-
-sub generateInternalSettingsIdlFile($)
-{
-    my $parsedItemsRef = shift;
-
-    my $filename = "$outputDir/InternalSettingsGenerated.idl";
-    open my $file, ">$filename" or die "Failed to open file: $!";
-    print $file $InCompiler->license();
-
-    print $file "interface InternalSettingsGenerated {\n";
-
-    sub writeIdlSetter($$$) {
-        my ($file, $parsedItemsRef, $settingName) = @_;
-        my %parsedItems = %{ $parsedItemsRef };
-        my $type = $parsedItems{$settingName}{"type"};
-        my $idlType = $webcoreTypeToIdlType{$type};
-        my $setterFunctionName = setterFunctionName($settingName);
-        print $file "    void $setterFunctionName($idlType $settingName);\n";
-    };
-
-    enumerateParsedItems($file, $parsedItemsRef, \&writeIdlSetter);
-
-    print $file "};\n";
-    close $file;
-}
-
-sub generateInternalSettingsHeaderFile($)
-{
-    my $parsedItemsRef = shift;
-    my %parsedItems = %{ $parsedItemsRef };
-
-    my $filename = "$outputDir/InternalSettingsGenerated.h";
-    open my $file, ">$filename" or die "Failed to open file: $!";
-    print $file $InCompiler->license();
-
-    print $file <<EOF;
-#ifndef InternalSettingsGenerated_h
-#define InternalSettingsGenerated_h
-
-#include "core/platform/RefCountedSupplement.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Page;
-
-class InternalSettingsGenerated : public RefCounted<InternalSettingsGenerated> {
-public:
-    explicit InternalSettingsGenerated(Page*);
-    virtual ~InternalSettingsGenerated();
-    void resetToConsistentState();
-EOF
-    sub writeHeaderPrototypes($$$) {
-        my ($file, $parsedItemsRef, $settingName) = @_;
-        my %parsedItems = %{ $parsedItemsRef };
-        my $type = $parsedItems{$settingName}{"type"};
-        my $setterFunctionName = setterFunctionName($settingName);
-        $type = "const String&" if $type eq "String";
-        print $file "    void $setterFunctionName($type $settingName);\n";
-    };
-    enumerateParsedItems($file, $parsedItemsRef, \&writeHeaderPrototypes);
-
-    print $file <<EOF;
-
-private:
-    Page* m_page;
-
-EOF
-
-    sub writeBackupMembers($$$) {
-        my ($file, $parsedItemsRef, $settingName) = @_;
-        my %parsedItems = %{ $parsedItemsRef };
-        my $type = $parsedItems{$settingName}{"type"};
-        my $conditional = $parsedItems{$settingName}{"conditional"};
-        if ($conditional) {
-            print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
-        }
-        print $file "    $type m_$settingName;\n";
-        if ($conditional) {
-            print $file "#endif\n";
-        }
-    };
-    enumerateParsedItems($file, $parsedItemsRef, \&writeBackupMembers);
-
-    print $file "};\n\n";
-    print $file "} // namespace WebCore\n";
-    print $file "#endif // InternalSettingsGenerated_h\n";
-
-    close $file;
-}
-
-sub generateInternalSettingsCppFile($)
-{
-    my $parsedItemsRef = shift;
-    my %parsedItems = %{ $parsedItemsRef };
-
-    my $filename = "$outputDir/InternalSettingsGenerated.cpp";
-    open my $file, ">$filename" or die "Failed to open file: $!";
-    print $file $InCompiler->license();
-
-    print $file <<EOF;
-#include "config.h"
-#include "InternalSettingsGenerated.h"
-
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-
-namespace WebCore {
-
-InternalSettingsGenerated::InternalSettingsGenerated(Page* page)
-    : m_page(page)
-EOF
-
-    sub writeBackupInitializers($$$) {
-        my ($file, $parsedItemsRef, $settingName) = @_;
-        my %parsedItems = %{ $parsedItemsRef };
-        my $type = $parsedItems{$settingName}{"type"};
-        my $conditional = $parsedItems{$settingName}{"conditional"};
-        if ($conditional) {
-            print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
-        }
-        print $file "    , m_$settingName(page->settings().$settingName())\n";
-        if ($conditional) {
-            print $file "#endif\n";
-        }
-    };
-    enumerateParsedItems($file, $parsedItemsRef, \&writeBackupInitializers);
-
-    print $file <<EOF;
-{
-}
-
-InternalSettingsGenerated::~InternalSettingsGenerated()
-{
-}
-
-void InternalSettingsGenerated::resetToConsistentState()
-{
-EOF
-    sub writeResetToConsistentState($$$) {
-        my ($file, $parsedItemsRef, $settingName) = @_;
-        my %parsedItems = %{ $parsedItemsRef };
-        my $type = $parsedItems{$settingName}{"type"};
-        my $setterFunctionName = setterFunctionName($settingName);
-        my $conditional = $parsedItems{$settingName}{"conditional"};
-        if ($conditional) {
-            print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
-        }
-        print $file "    m_page->settings().$setterFunctionName(m_$settingName);\n";
-        if ($conditional) {
-            print $file "#endif\n";
-        }
-    };
-    enumerateParsedItems($file, $parsedItemsRef, \&writeResetToConsistentState);
-
-    print $file "}\n";
-
-    sub writeSetterFunctions($$$) {
-        my ($file, $parsedItemsRef, $settingName) = @_;
-        my %parsedItems = %{ $parsedItemsRef };
-        my $type = $parsedItems{$settingName}{"type"};
-        my $conditional = $parsedItems{$settingName}{"conditional"};
-        my $setterFunctionName = setterFunctionName($settingName);
-        $type = "const String&" if $type eq "String";
-
-        print $file "void InternalSettingsGenerated::$setterFunctionName($type $settingName)\n";
-        print $file "{\n";
-
-        if ($conditional) {
-            print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
-        }
-        print $file "    m_page->settings().$setterFunctionName($settingName);\n";
-        if ($conditional) {
-            print $file "#else\n";
-            print $file "    UNUSED_PARAM($settingName);\n";
-            print $file "#endif\n";
-        }
-        print $file "}\n\n";
-    };
-    enumerateParsedItems($file, $parsedItemsRef, \&writeSetterFunctions);
-
-    print $file "} // namespace WebCore\n";
-
-    close $file;
-}
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.cpp b/Source/core/page/scrolling/ScrollingCoordinator.cpp
index 22e5026..2ac8455 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -322,6 +322,9 @@
         webLayer->setScrollable(true);
         webLayer->setScrollPosition(IntPoint(scrollableArea->scrollPosition() - scrollableArea->minimumScrollPosition()));
         webLayer->setMaxScrollPosition(IntSize(scrollableArea->scrollSize(HorizontalScrollbar), scrollableArea->scrollSize(VerticalScrollbar)));
+        bool canScrollX = scrollableArea->userInputScrollable(HorizontalScrollbar);
+        bool canScrollY = scrollableArea->userInputScrollable(VerticalScrollbar);
+        webLayer->setUserScrollable(canScrollX, canScrollY);
     }
     if (WebScrollbarLayer* scrollbarLayer = getWebScrollbarLayer(scrollableArea, HorizontalScrollbar)) {
         GraphicsLayer* horizontalScrollbarLayer = horizontalScrollbarLayerForScrollableArea(scrollableArea);
@@ -345,8 +348,8 @@
 static void makeLayerChildFrameMap(const Frame* currentFrame, LayerFrameMap* map)
 {
     map->clear();
-    const FrameTree* tree = currentFrame->tree();
-    for (const Frame* child = tree->firstChild(); child; child = child->tree()->nextSibling()) {
+    const FrameTree& tree = currentFrame->tree();
+    for (const Frame* child = tree.firstChild(); child; child = child->tree().nextSibling()) {
         const RenderLayer* containingLayer = child->ownerRenderer()->enclosingLayer();
         LayerFrameMap::iterator iter = map->find(containingLayer);
         if (iter == map->end())
@@ -629,8 +632,8 @@
         }
     }
 
-    FrameTree* tree = frame->tree();
-    for (Frame* subFrame = tree->firstChild(); subFrame; subFrame = subFrame->tree()->nextSibling())
+    const FrameTree& tree = frame->tree();
+    for (Frame* subFrame = tree.firstChild(); subFrame; subFrame = subFrame->tree().nextSibling())
         shouldHandleScrollGestureOnMainThreadRegion.unite(computeShouldHandleScrollGestureOnMainThreadRegion(subFrame, offset));
 
     return shouldHandleScrollGestureOnMainThreadRegion;
@@ -697,7 +700,7 @@
 {
     unsigned wheelEventHandlerCount = 0;
 
-    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
         if (frame->document())
             wheelEventHandlerCount += WheelController::from(frame->document())->wheelEventHandlerCount();
     }
@@ -822,11 +825,8 @@
 
 MainThreadScrollingReasons ScrollingCoordinator::mainThreadScrollingReasons() const
 {
-    // The main thread scrolling reasons are applicable to scrolls of the main
-    // 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;
diff --git a/Source/core/platform/AsyncFileSystemCallbacks.h b/Source/core/platform/AsyncFileSystemCallbacks.h
deleted file mode 100644
index b7f9cd8..0000000
--- a/Source/core/platform/AsyncFileSystemCallbacks.h
+++ /dev/null
@@ -1,96 +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 AsyncFileSystemCallbacks_h
-#define AsyncFileSystemCallbacks_h
-
-#include "platform/FileMetadata.h"
-#include "platform/FileSystemType.h"
-#include "platform/blob/BlobData.h"
-#include "public/platform/WebFileWriter.h"
-#include "wtf/Assertions.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class AsyncFileSystemCallbacks {
-    WTF_MAKE_NONCOPYABLE(AsyncFileSystemCallbacks);
-public:
-    AsyncFileSystemCallbacks() : m_blockUntilCompletion(false) { }
-
-    // Called when a requested operation is completed successfully.
-    virtual void didSucceed() { ASSERT_NOT_REACHED(); }
-
-    // Called when a requested file system is opened.
-    virtual void didOpenFileSystem(const String& name, const KURL& rootURL) { ASSERT_NOT_REACHED(); }
-
-    // Called when a filesystem URL is resolved.
-    virtual void didResolveURL(const String& name, const KURL& rootURL, FileSystemType, const String& filePath, bool isDirectory) { ASSERT_NOT_REACHED(); }
-
-    // Called when a file metadata is read successfully.
-    virtual void didReadMetadata(const FileMetadata&) { ASSERT_NOT_REACHED(); }
-
-    // Called when a snapshot file is created successfully.
-    virtual void didCreateSnapshotFile(const FileMetadata&, PassRefPtr<BlobDataHandle> snapshot) { ASSERT_NOT_REACHED(); }
-
-    // Called when a directory entry is read.
-    virtual void didReadDirectoryEntry(const String& name, bool isDirectory) { ASSERT_NOT_REACHED(); }
-
-    // Called after a chunk of directory entries have been read (i.e. indicates it's good time to call back to the application). If hasMore is true there can be more chunks.
-    virtual void didReadDirectoryEntries(bool hasMore) { ASSERT_NOT_REACHED(); }
-
-    // Called when an AsyncFileWrter has been created successfully.
-    virtual void didCreateFileWriter(PassOwnPtr<WebKit::WebFileWriter>, long long length) { ASSERT_NOT_REACHED(); }
-
-    // Called when there was an error.
-    virtual void didFail(int code) = 0;
-
-    // Returns true if the caller expects that the calling thread blocks
-    // until completion.
-    virtual bool shouldBlockUntilCompletion() const
-    {
-        return m_blockUntilCompletion;
-    }
-
-    void setShouldBlockUntilCompletion(bool flag)
-    {
-        m_blockUntilCompletion = flag;
-    }
-
-    virtual ~AsyncFileSystemCallbacks() { }
-
-private:
-    bool m_blockUntilCompletion;
-};
-
-} // namespace
-
-#endif // AsyncFileSystemCallbacks_h
diff --git a/Source/core/platform/ColorData.gperf b/Source/core/platform/ColorData.gperf
deleted file mode 100644
index cf2956a..0000000
--- a/Source/core/platform/ColorData.gperf
+++ /dev/null
@@ -1,175 +0,0 @@
-%{
-#include "core/platform/HashTools.h"
-#include <string.h>
-
-namespace WebCore {
-%}
-%struct-type
-struct NamedColor;
-%omit-struct-type
-%language=C++
-%readonly-tables
-%global-table
-%compare-strncmp
-%define class-name ColorDataHash
-%define lookup-function-name findColorImpl
-%define hash-function-name colordata_hash_function
-%enum
-%%
-aliceblue, 0xfff0f8ff
-antiquewhite, 0xfffaebd7
-aqua, 0xff00ffff
-aquamarine, 0xff7fffd4
-azure, 0xfff0ffff
-beige, 0xfff5f5dc
-bisque, 0xffffe4c4
-black, 0xff000000
-blanchedalmond, 0xffffebcd
-blue, 0xff0000ff
-blueviolet, 0xff8a2be2
-brown, 0xffa52a2a
-burlywood, 0xffdeb887
-cadetblue, 0xff5f9ea0
-chartreuse, 0xff7fff00
-chocolate, 0xffd2691e
-coral, 0xffff7f50
-cornflowerblue, 0xff6495ed
-cornsilk, 0xfffff8dc
-crimson, 0xffdc143c
-cyan, 0xff00ffff
-darkblue, 0xff00008b
-darkcyan, 0xff008b8b
-darkgoldenrod, 0xffb8860b
-darkgray, 0xffa9a9a9
-darkgrey, 0xffa9a9a9
-darkgreen, 0xff006400
-darkkhaki, 0xffbdb76b
-darkmagenta, 0xff8b008b
-darkolivegreen, 0xff556b2f
-darkorange, 0xffff8c00
-darkorchid, 0xff9932cc
-darkred, 0xff8b0000
-darksalmon, 0xffe9967a
-darkseagreen, 0xff8fbc8f
-darkslateblue, 0xff483d8b
-darkslategray, 0xff2f4f4f
-darkslategrey, 0xff2f4f4f
-darkturquoise, 0xff00ced1
-darkviolet, 0xff9400d3
-deeppink, 0xffff1493
-deepskyblue, 0xff00bfff
-dimgray, 0xff696969
-dimgrey, 0xff696969
-dodgerblue, 0xff1e90ff
-firebrick, 0xffb22222
-floralwhite, 0xfffffaf0
-forestgreen, 0xff228b22
-fuchsia, 0xffff00ff
-gainsboro, 0xffdcdcdc
-ghostwhite, 0xfff8f8ff
-gold, 0xffffd700
-goldenrod, 0xffdaa520
-gray, 0xff808080
-grey, 0xff808080
-green, 0xff008000
-greenyellow, 0xffadff2f
-honeydew, 0xfff0fff0
-hotpink, 0xffff69b4
-indianred, 0xffcd5c5c
-indigo, 0xff4b0082
-ivory, 0xfffffff0
-khaki, 0xfff0e68c
-lavender, 0xffe6e6fa
-lavenderblush, 0xfffff0f5
-lawngreen, 0xff7cfc00
-lemonchiffon, 0xfffffacd
-lightblue, 0xffadd8e6
-lightcoral, 0xfff08080
-lightcyan, 0xffe0ffff
-lightgoldenrodyellow, 0xfffafad2
-lightgray, 0xffd3d3d3
-lightgrey, 0xffd3d3d3
-lightgreen, 0xff90ee90
-lightpink, 0xffffb6c1
-lightsalmon, 0xffffa07a
-lightseagreen, 0xff20b2aa
-lightskyblue, 0xff87cefa
-lightslateblue, 0xff8470ff
-lightslategray, 0xff778899
-lightslategrey, 0xff778899
-lightsteelblue, 0xffb0c4de
-lightyellow, 0xffffffe0
-lime, 0xff00ff00
-limegreen, 0xff32cd32
-linen, 0xfffaf0e6
-magenta, 0xffff00ff
-maroon, 0xff800000
-mediumaquamarine, 0xff66cdaa
-mediumblue, 0xff0000cd
-mediumorchid, 0xffba55d3
-mediumpurple, 0xff9370db
-mediumseagreen, 0xff3cb371
-mediumslateblue, 0xff7b68ee
-mediumspringgreen, 0xff00fa9a
-mediumturquoise, 0xff48d1cc
-mediumvioletred, 0xffc71585
-midnightblue, 0xff191970
-mintcream, 0xfff5fffa
-mistyrose, 0xffffe4e1
-moccasin, 0xffffe4b5
-navajowhite, 0xffffdead
-navy, 0xff000080
-oldlace, 0xfffdf5e6
-olive, 0xff808000
-olivedrab, 0xff6b8e23
-orange, 0xffffa500
-orangered, 0xffff4500
-orchid, 0xffda70d6
-palegoldenrod, 0xffeee8aa
-palegreen, 0xff98fb98
-paleturquoise, 0xffafeeee
-palevioletred, 0xffdb7093
-papayawhip, 0xffffefd5
-peachpuff, 0xffffdab9
-peru, 0xffcd853f
-pink, 0xffffc0cb
-plum, 0xffdda0dd
-powderblue, 0xffb0e0e6
-purple, 0xff800080
-red, 0xffff0000
-rosybrown, 0xffbc8f8f
-royalblue, 0xff4169e1
-saddlebrown, 0xff8b4513
-salmon, 0xfffa8072
-sandybrown, 0xfff4a460
-seagreen, 0xff2e8b57
-seashell, 0xfffff5ee
-sienna, 0xffa0522d
-silver, 0xffc0c0c0
-skyblue, 0xff87ceeb
-slateblue, 0xff6a5acd
-slategray, 0xff708090
-slategrey, 0xff708090
-snow, 0xfffffafa
-springgreen, 0xff00ff7f
-steelblue, 0xff4682b4
-tan, 0xffd2b48c
-teal, 0xff008080
-thistle, 0xffd8bfd8
-tomato, 0xffff6347
-transparent, 0x00000000
-turquoise, 0xff40e0d0
-violet, 0xffee82ee
-violetred, 0xffd02090
-wheat, 0xfff5deb3
-white, 0xffffffff
-whitesmoke, 0xfff5f5f5
-yellow, 0xffffff00
-yellowgreen, 0xff9acd32
-%%
-const struct NamedColor* findColor(register const char* str, register unsigned int len)
-{
-    return ColorDataHash::findColorImpl(str, len);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/DEPS b/Source/core/platform/DEPS
index 33693a0..3d6511a 100644
--- a/Source/core/platform/DEPS
+++ b/Source/core/platform/DEPS
@@ -4,7 +4,6 @@
 include_rules = [
     "-core",
     "+core/platform",
-    "+core/tests", # Remove after https://codereview.chromium.org/26227002/
     "+dl",
     "+skia",
     "+third_party",
@@ -23,5 +22,4 @@
     "!core/page",
     "!core/plugins",
     "!core/rendering",
-    "!core/events/ThreadLocalEventNames.h",
 ]
diff --git a/Source/core/platform/DragImage.cpp b/Source/core/platform/DragImage.cpp
index 5a6b40c..76a5ec1 100644
--- a/Source/core/platform/DragImage.cpp
+++ b/Source/core/platform/DragImage.cpp
@@ -27,20 +27,20 @@
 #include "core/platform/DragImage.h"
 
 #include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/FontMetrics.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/Image.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/platform/graphics/StringTruncator.h"
 #include "core/platform/graphics/skia/NativeImageSkia.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/geometry/IntSize.h"
+#include "platform/graphics/Color.h"
 #include "platform/graphics/TextRun.h"
 #include "platform/transforms/AffineTransform.h"
 #include "skia/ext/image_operations.h"
@@ -58,10 +58,8 @@
 const float kDragLabelBorderX = 4;
 // Keep border_y in synch with DragController::LinkDragBorderInset.
 const float kDragLabelBorderY = 2;
-const float kDragLabelRadius = 5;
 const float kLabelBorderYOffset = 2;
 
-const float kMinDragLabelWidthBeforeClip = 120;
 const float kMaxDragLabelWidth = 300;
 const float kMaxDragLabelStringWidth = (kMaxDragLabelWidth - 2 * kDragLabelBorderX);
 
diff --git a/Source/core/platform/HistogramSupport.h b/Source/core/platform/HistogramSupport.h
deleted file mode 100644
index 9bb265a..0000000
--- a/Source/core/platform/HistogramSupport.h
+++ /dev/null
@@ -1,44 +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.
- */
-
-#ifndef HistogramSupport_h
-#define HistogramSupport_h
-
-namespace WebCore {
-
-class HistogramSupport {
-public:
-    static void histogramEnumeration(const char* name, int sample, int boundaryValue);
-    static void histogramCustomCounts(const char* name, int sample, int min, int max, int bucketCount);
-};
-
-} // namespace WebCore
-
-#endif // HistogramSupport_h
diff --git a/Source/core/platform/LifecycleContext.cpp b/Source/core/platform/LifecycleContext.cpp
deleted file mode 100644
index d0b2165..0000000
--- a/Source/core/platform/LifecycleContext.cpp
+++ /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:
- * 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/LifecycleContext.h"
-
-#include "core/platform/LifecycleNotifier.h"
-
-namespace WebCore {
-
-LifecycleContext::LifecycleContext()
-{
-}
-
-LifecycleContext::~LifecycleContext()
-{
-}
-
-void LifecycleContext::wasObservedBy(LifecycleObserver* observer)
-{
-    lifecycleNotifier()->addObserver(observer);
-}
-
-void LifecycleContext::wasUnobservedBy(LifecycleObserver* observer)
-{
-    lifecycleNotifier()->removeObserver(observer);
-}
-
-LifecycleNotifier* LifecycleContext::lifecycleNotifier()
-{
-    if (!m_lifecycleNotifier)
-        m_lifecycleNotifier = const_cast<LifecycleContext*>(this)->createLifecycleNotifier();
-    return m_lifecycleNotifier.get();
-}
-
-PassOwnPtr<LifecycleNotifier> LifecycleContext::createLifecycleNotifier()
-{
-    return LifecycleNotifier::create(this);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/LifecycleContext.h b/Source/core/platform/LifecycleContext.h
deleted file mode 100644
index c23e8d3..0000000
--- a/Source/core/platform/LifecycleContext.h
+++ /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:
- * 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 LifecycleContext_h
-#define LifecycleContext_h
-
-#include "core/platform/LifecycleObserver.h"
-#include "wtf/HashSet.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class LifecycleNotifier;
-class LifecycleObserver;
-
-class LifecycleContext {
-public:
-    LifecycleContext();
-    virtual ~LifecycleContext();
-
-    virtual bool isContextThread() const { return true; }
-
-    // Called from the constructor of observers.
-    void wasObservedBy(LifecycleObserver*);
-
-    // Called from the destructor of observers.
-    void wasUnobservedBy(LifecycleObserver*);
-
-protected:
-    LifecycleNotifier* lifecycleNotifier();
-
-private:
-    virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier();
-
-    OwnPtr<LifecycleNotifier> m_lifecycleNotifier;
-};
-
-} // namespace WebCore
-
-#endif // LifecycleContext_h
diff --git a/Source/core/platform/LifecycleNotifier.cpp b/Source/core/platform/LifecycleNotifier.cpp
deleted file mode 100644
index bf07d29..0000000
--- a/Source/core/platform/LifecycleNotifier.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2008 Apple 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 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/LifecycleNotifier.h"
-#include "wtf/TemporaryChange.h"
-
-namespace WebCore {
-
-LifecycleNotifier::LifecycleNotifier(LifecycleContext* context)
-    : m_context(context)
-    , m_iterating(IteratingNone)
-{
-}
-
-LifecycleNotifier::~LifecycleNotifier()
-{
-    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverAll);
-    for (ObserverSet::iterator it = m_observers.begin(); it != m_observers.end(); it = m_observers.begin()) {
-        LifecycleObserver* observer = *it;
-        m_observers.remove(observer);
-        ASSERT(observer->lifecycleContext() == m_context);
-        observer->contextDestroyed();
-    }
-}
-
-void LifecycleNotifier::addObserver(LifecycleObserver* observer)
-{
-    RELEASE_ASSERT(m_iterating != IteratingOverAll);
-    m_observers.add(observer);
-}
-
-void LifecycleNotifier::removeObserver(LifecycleObserver* observer)
-{
-    RELEASE_ASSERT(m_iterating != IteratingOverAll);
-    m_observers.remove(observer);
-}
-
-LifecycleContext* LifecycleNotifier::context()
-{
-    return m_context;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/LifecycleNotifier.h b/Source/core/platform/LifecycleNotifier.h
deleted file mode 100644
index ef960fa..0000000
--- a/Source/core/platform/LifecycleNotifier.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2008 Apple 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 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 LifecycleNotifier_h
-#define LifecycleNotifier_h
-
-#include "core/platform/LifecycleObserver.h"
-#include "wtf/HashSet.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class LifecycleContext;
-class LifecycleObserver;
-
-class LifecycleNotifier {
-public:
-    static PassOwnPtr<LifecycleNotifier> create(LifecycleContext*);
-
-    virtual ~LifecycleNotifier();
-
-    virtual void addObserver(LifecycleObserver*);
-    virtual void removeObserver(LifecycleObserver*);
-
-    bool isIteratingOverObservers() const { return m_iterating != IteratingNone; }
-
-protected:
-    explicit LifecycleNotifier(LifecycleContext*);
-
-    LifecycleContext* context();
-
-    enum IterationType {
-        IteratingNone,
-        IteratingOverAll,
-        IteratingOverActiveDOMObjects,
-        IteratingOverContextObservers,
-        IteratingOverDocumentObservers,
-        IteratingOverPageObservers,
-        IteratingOverDOMWindowObservers
-    };
-
-    IterationType m_iterating;
-
-private:
-    typedef HashSet<LifecycleObserver*> ObserverSet;
-
-    ObserverSet m_observers;
-    LifecycleContext* m_context;
-};
-
-inline PassOwnPtr<LifecycleNotifier> LifecycleNotifier::create(LifecycleContext* context)
-{
-    return adoptPtr(new LifecycleNotifier(context));
-}
-
-} // namespace WebCore
-
-#endif // LifecycleNotifier_h
diff --git a/Source/core/platform/LifecycleObserver.cpp b/Source/core/platform/LifecycleObserver.cpp
deleted file mode 100644
index 97452ba..0000000
--- a/Source/core/platform/LifecycleObserver.cpp
+++ /dev/null
@@ -1,66 +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 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/LifecycleObserver.h"
-
-#include "core/platform/LifecycleContext.h"
-
-namespace WebCore {
-
-LifecycleObserver::LifecycleObserver(LifecycleContext* lifecycleContext, Type type)
-    : m_lifecycleContext(0)
-    , m_observerType(type)
-{
-    observeContext(lifecycleContext);
-}
-
-LifecycleObserver::~LifecycleObserver()
-{
-    observeContext(0);
-}
-
-void LifecycleObserver::observeContext(LifecycleContext* context)
-{
-    if (m_lifecycleContext) {
-        ASSERT(m_lifecycleContext->isContextThread());
-        m_lifecycleContext->wasUnobservedBy(this);
-    }
-
-    m_lifecycleContext = context;
-
-    if (m_lifecycleContext) {
-        ASSERT(m_lifecycleContext->isContextThread());
-        m_lifecycleContext->wasObservedBy(this);
-    }
-}
-
-void LifecycleObserver::contextDestroyed()
-{
-    m_lifecycleContext = 0;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/LifecycleObserver.h b/Source/core/platform/LifecycleObserver.h
deleted file mode 100644
index 19b00f9..0000000
--- a/Source/core/platform/LifecycleObserver.h
+++ /dev/null
@@ -1,62 +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 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 LifecycleObserver_h
-#define LifecycleObserver_h
-
-namespace WebCore {
-
-class LifecycleContext;
-
-class LifecycleObserver {
-public:
-    enum Type {
-        ActiveDOMObjectType,
-        DocumentLifecycleObserverType,
-        GenericType,
-        PageLifecycleObserverType,
-        DOMWindowLifecycleObserverType
-    };
-
-    explicit LifecycleObserver(LifecycleContext*, Type = GenericType);
-
-    virtual void contextDestroyed();
-
-    LifecycleContext* lifecycleContext() const { return m_lifecycleContext; }
-    Type observerType() const { return m_observerType; }
-
-protected:
-    virtual ~LifecycleObserver();
-
-    void observeContext(LifecycleContext*);
-
-    LifecycleContext* m_lifecycleContext;
-    Type m_observerType;
-};
-
-} // namespace WebCore
-
-#endif // LifecycleObserver_h
diff --git a/Source/core/platform/MemoryUsageSupport.h b/Source/core/platform/MemoryUsageSupport.h
deleted file mode 100644
index 36128e1..0000000
--- a/Source/core/platform/MemoryUsageSupport.h
+++ /dev/null
@@ -1,69 +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 MemoryUsageSupport_h
-#define MemoryUsageSupport_h
-
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class MemoryUsageSupport {
-public:
-    // Returns the current space allocated for the pagefile, in MB.
-    // That is committed size for Windows and virtual memory size for POSIX.
-    static int memoryUsageMB();
-
-    // Same as above, but always returns actual value, without any
-    // caches.
-    static int actualMemoryUsageMB();
-
-    // Returns private and shared usage, in bytes. Private bytes is the amount of
-    // memory currently allocated to this process that cannot be shared. Returns
-    // false on platform specific error conditions.
-    static bool processMemorySizesInBytes(size_t* privateBytes, size_t* sharedBytes);
-
-    // A callback for requestProcessMemorySizes
-    class ProcessMemorySizesCallback {
-    public:
-        virtual ~ProcessMemorySizesCallback() { }
-        virtual void dataReceived(size_t privateBytes, size_t sharedBytes) = 0;
-    };
-
-    // Requests private and shared usage, in bytes. Private bytes is the amount of
-    // memory currently allocated to this process that cannot be shared.
-    static void requestProcessMemorySizes(PassOwnPtr<ProcessMemorySizesCallback> requestCallback);
-};
-
-} // namespace WebCore
-
-#endif // MemoryUsageSupport_h
diff --git a/Source/core/platform/OverscrollTheme.cpp b/Source/core/platform/OverscrollTheme.cpp
new file mode 100644
index 0000000..ab09339
--- /dev/null
+++ b/Source/core/platform/OverscrollTheme.cpp
@@ -0,0 +1,74 @@
+/*
+ * 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 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/OverscrollTheme.h"
+
+namespace WebCore {
+
+OverscrollTheme::OverscrollTheme()
+{
+#if USE(RUBBER_BANDING)
+    // Load the shadow and pattern for the overhang.
+    m_overhangShadow = Image::loadPlatformResource("overhangShadow");
+    m_overhangPattern = Image::loadPlatformResource("overhangPattern");
+#endif
+}
+
+PassRefPtr<Image> OverscrollTheme::getOverhangImage()
+{
+    return m_overhangPattern;
+}
+
+void OverscrollTheme::setUpOverhangShadowLayer(GraphicsLayer* overhangShadowLayer)
+{
+    // The shadow texture is has a 1-pixel aperture in the center, so the division by
+    // two is doing an intentional round-down.
+    overhangShadowLayer->setContentsToNinePatch(
+        m_overhangShadow.get(),
+        IntRect(m_overhangShadow->width() / 2, m_overhangShadow->height() / 2, 1, 1));
+}
+
+void OverscrollTheme::updateOverhangShadowLayer(GraphicsLayer* shadowLayer, GraphicsLayer* rootContentLayer)
+{
+    // Note that for the position, the division m_overhangShadow->width() / 2 is an intentional
+    // round-down, and that for the width and height, the 1-pixel aperture is being replaced
+    // by the root contents layer, hence subtracting 1 and adding the rootContentsLayer size.
+    IntRect shadowRect(
+        static_cast<int>(rootContentLayer->position().x()) - m_overhangShadow->width() / 2,
+        static_cast<int>(rootContentLayer->position().y()) -  m_overhangShadow->height() / 2,
+        static_cast<int>(rootContentLayer->size().width()) + m_overhangShadow->width() - 1,
+        static_cast<int>(rootContentLayer->size().height()) + m_overhangShadow->height() - 1);
+    shadowLayer->setContentsRect(shadowRect);
+}
+
+OverscrollTheme* OverscrollTheme::theme()
+{
+    DEFINE_STATIC_LOCAL(OverscrollTheme, theme, ());
+    return &theme;
+}
+
+}
diff --git a/Source/core/platform/graphics/WindRule.h b/Source/core/platform/OverscrollTheme.h
similarity index 61%
rename from Source/core/platform/graphics/WindRule.h
rename to Source/core/platform/OverscrollTheme.h
index d4f123e..4dca778 100644
--- a/Source/core/platform/graphics/WindRule.h
+++ b/Source/core/platform/OverscrollTheme.h
@@ -1,7 +1,5 @@
 /*
- * Copyright (C) 2003, 2006, 2009 Apple Inc. All rights reserved.
- *               2006 Rob Buis <buis@kde.org>
- * Copyright (C) 2007-2008 Torch Mobile, Inc.
+ * 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
@@ -12,7 +10,7 @@
  *    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
+ * 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
@@ -23,19 +21,34 @@
  * 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 WindRule_h
-#define WindRule_h
+#ifndef OverscrollTheme_h
+#define OverscrollTheme_h
+
+#include "core/platform/graphics/GraphicsLayer.h"
+#include "core/platform/graphics/Image.h"
 
 namespace WebCore {
 
-enum WindRule {
-    RULE_NONZERO = 0,
-    RULE_EVENODD = 1
+class OverscrollTheme {
+    WTF_MAKE_NONCOPYABLE(OverscrollTheme); WTF_MAKE_FAST_ALLOCATED;
+public:
+    OverscrollTheme();
+    virtual ~OverscrollTheme() { }
+
+    virtual PassRefPtr<Image> getOverhangImage();
+    virtual void setUpOverhangShadowLayer(GraphicsLayer*);
+    virtual void updateOverhangShadowLayer(GraphicsLayer* shadowLayer, GraphicsLayer* rootContentLayer);
+
+    static OverscrollTheme* theme();
+
+private:
+    RefPtr<Image> m_overhangShadow;
+    RefPtr<Image> m_overhangPattern;
 };
 
 }
 
-#endif // WindRule_h
-
+#endif
diff --git a/Source/core/platform/ParsingUtilities.h b/Source/core/platform/ParsingUtilities.h
deleted file mode 100644
index ba8fa9e..0000000
--- a/Source/core/platform/ParsingUtilities.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.
- *     * 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 ParsingUtilities_h
-#define ParsingUtilities_h
-
-template<typename CharType>
-bool skipExactly(const CharType*& position, const CharType* end, CharType delimiter)
-{
-    if (position < end && *position == delimiter) {
-        ++position;
-        return true;
-    }
-    return false;
-}
-
-template<typename CharType, bool characterPredicate(CharType)>
-bool skipExactly(const CharType*& position, const CharType* end)
-{
-    if (position < end && characterPredicate(*position)) {
-        ++position;
-        return true;
-    }
-    return false;
-}
-
-template<typename CharType>
-void skipUntil(const CharType*& position, const CharType* end, CharType delimiter)
-{
-    while (position < end && *position != delimiter)
-        ++position;
-}
-
-template<typename CharType, bool characterPredicate(CharType)>
-void skipUntil(const CharType*& position, const CharType* end)
-{
-    while (position < end && !characterPredicate(*position))
-        ++position;
-}
-
-template<typename CharType, bool characterPredicate(CharType)>
-void skipWhile(const CharType*& position, const CharType* end)
-{
-    while (position < end && characterPredicate(*position))
-        ++position;
-}
-
-#endif
-
diff --git a/Source/core/platform/PopupMenuStyle.h b/Source/core/platform/PopupMenuStyle.h
index eff33c5..fd34dff 100644
--- a/Source/core/platform/PopupMenuStyle.h
+++ b/Source/core/platform/PopupMenuStyle.h
@@ -26,9 +26,9 @@
 #ifndef PopupMenuStyle_h
 #define PopupMenuStyle_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/Font.h"
 #include "platform/Length.h"
+#include "platform/graphics/Color.h"
 #include "platform/text/TextDirection.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/Prerender.cpp b/Source/core/platform/Prerender.cpp
deleted file mode 100644
index 9b70ebf..0000000
--- a/Source/core/platform/Prerender.cpp
+++ /dev/null
@@ -1,136 +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/Prerender.h"
-
-#include "core/platform/PrerenderClient.h"
-#include "public/platform/WebPrerender.h"
-#include "public/platform/WebPrerenderingSupport.h"
-
-namespace WebCore {
-
-PassRefPtr<Prerender> Prerender::create(PrerenderClient* client, const KURL& url, const String& referrer, ReferrerPolicy policy)
-{
-    return adoptRef(new Prerender(client, url, referrer, policy));
-}
-
-Prerender::Prerender(PrerenderClient* client, const KURL& url, const String& referrer, ReferrerPolicy policy)
-    : m_client(client)
-    , m_url(url)
-    , m_referrer(referrer)
-    , m_referrerPolicy(policy)
-    , m_isActive(false)
-{
-}
-
-Prerender::~Prerender()
-{
-}
-
-void Prerender::removeClient()
-{
-    m_client = 0;
-}
-
-void Prerender::add()
-{
-    ASSERT(!m_isActive);
-    m_isActive = true;
-    WebKit::WebPrerenderingSupport* platform = WebKit::WebPrerenderingSupport::current();
-    if (!platform)
-        return;
-    platform->add(WebKit::WebPrerender(this));
-}
-
-void Prerender::cancel()
-{
-    // The LinkLoader and the Document (via Prerenderer) share ownership of
-    // the Prerender, so it may have been abandoned by the Prerenderer and
-    // then later canceled by the LinkLoader.
-    if (!m_isActive)
-        return;
-    m_isActive = false;
-    WebKit::WebPrerenderingSupport* platform = WebKit::WebPrerenderingSupport::current();
-    if (!platform)
-        return;
-    platform->cancel(WebKit::WebPrerender(this));
-}
-
-void Prerender::abandon()
-{
-    // The LinkLoader and the Document (via Prerenderer) share ownership of
-    // the Prerender, so it may have been canceled by the LinkLoader and
-    // then later abandoned by the Prerenderer.
-    if (!m_isActive)
-        return;
-    m_isActive = false;
-    WebKit::WebPrerenderingSupport* platform = WebKit::WebPrerenderingSupport::current();
-    if (!platform)
-        return;
-    platform->abandon(WebKit::WebPrerender(this));
-}
-
-void Prerender::suspend()
-{
-    abandon();
-}
-
-void Prerender::resume()
-{
-    add();
-}
-
-void Prerender::didStartPrerender()
-{
-    if (m_client)
-        m_client->didStartPrerender();
-}
-
-void Prerender::didStopPrerender()
-{
-    if (m_client)
-        m_client->didStopPrerender();
-}
-
-void Prerender::didSendLoadForPrerender()
-{
-    if (m_client)
-        m_client->didSendLoadForPrerender();
-}
-
-void Prerender::didSendDOMContentLoadedForPrerender()
-{
-    if (m_client)
-        m_client->didSendDOMContentLoadedForPrerender();
-}
-
-}
diff --git a/Source/core/platform/Prerender.h b/Source/core/platform/Prerender.h
deleted file mode 100644
index 282d218..0000000
--- a/Source/core/platform/Prerender.h
+++ /dev/null
@@ -1,99 +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 Prerender_h
-#define Prerender_h
-
-#include "weborigin/KURL.h"
-#include "weborigin/ReferrerPolicy.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebKit {
-class WebPrerender;
-}
-
-namespace WebCore {
-
-class PrerenderClient;
-
-class Prerender : public RefCounted<Prerender> {
-    WTF_MAKE_NONCOPYABLE(Prerender);
-public:
-    class ExtraData : public RefCounted<ExtraData> {
-    public:
-        virtual ~ExtraData() { }
-    };
-
-    static PassRefPtr<Prerender> create(PrerenderClient*, const KURL&, const String& referrer, ReferrerPolicy);
-    ~Prerender();
-
-    void removeClient();
-
-    void add();
-    void cancel();
-    void abandon();
-    void suspend();
-    void resume();
-
-    const KURL& url() const { return m_url; }
-    const String& referrer() const { return m_referrer; }
-    ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
-
-    void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
-    ExtraData* extraData() { return m_extraData.get(); }
-
-    void didStartPrerender();
-    void didStopPrerender();
-    void didSendLoadForPrerender();
-    void didSendDOMContentLoadedForPrerender();
-
-private:
-    Prerender(PrerenderClient*, const KURL&, const String& referrer, ReferrerPolicy);
-
-    PrerenderClient* m_client;
-
-    const KURL m_url;
-    const String m_referrer;
-    const ReferrerPolicy m_referrerPolicy;
-
-    bool m_isActive;
-
-    RefPtr<ExtraData> m_extraData;
-};
-
-}
-
-#endif // Prerender_h
diff --git a/Source/core/platform/PrerenderClient.h b/Source/core/platform/PrerenderClient.h
deleted file mode 100644
index 989d75f..0000000
--- a/Source/core/platform/PrerenderClient.h
+++ /dev/null
@@ -1,50 +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 PrerenderClient_h
-#define PrerenderClient_h
-
-namespace WebCore {
-
-class PrerenderClient {
-public:
-    virtual ~PrerenderClient() { }
-
-    virtual void didStartPrerender() = 0;
-    virtual void didStopPrerender() = 0;
-    virtual void didSendLoadForPrerender() = 0;
-    virtual void didSendDOMContentLoadedForPrerender() = 0;
-};
-
-}
-
-
-#endif
diff --git a/Source/core/platform/ScrollView.cpp b/Source/core/platform/ScrollView.cpp
index 21456c8..580fd8e 100644
--- a/Source/core/platform/ScrollView.cpp
+++ b/Source/core/platform/ScrollView.cpp
@@ -899,12 +899,7 @@
         paintContents(context, documentDirtyRect);
     }
 
-#if USE(RUBBER_BANDING)
-    if (!layerForOverhangAreas())
-        calculateAndPaintOverhangAreas(context, rect);
-#else
     calculateAndPaintOverhangAreas(context, rect);
-#endif
 
     // Now paint the scrollbars.
     if (!m_scrollbarsSuppressed && (m_horizontalScrollbar || m_verticalScrollbar)) {
@@ -973,14 +968,6 @@
     IntRect horizontalOverhangRect;
     IntRect verticalOverhangRect;
     calculateOverhangAreasForPainting(horizontalOverhangRect, verticalOverhangRect);
-#if USE(RUBBER_BANDING)
-    if (GraphicsLayer* overhangLayer = layerForOverhangAreas()) {
-        bool hasOverhangArea = !horizontalOverhangRect.isEmpty() || !verticalOverhangRect.isEmpty();
-        overhangLayer->setDrawsContent(hasOverhangArea);
-        if (hasOverhangArea)
-            overhangLayer->setNeedsDisplay();
-    }
-#endif
     if (!horizontalOverhangRect.isEmpty())
         window->invalidateContentsAndRootView(horizontalOverhangRect);
     if (!verticalOverhangRect.isEmpty())
diff --git a/Source/core/platform/ScrollableArea.h b/Source/core/platform/ScrollableArea.h
index b502b93..24294e0 100644
--- a/Source/core/platform/ScrollableArea.h
+++ b/Source/core/platform/ScrollableArea.h
@@ -172,6 +172,7 @@
 
     virtual bool usesCompositedScrolling() const { return false; }
     virtual void updateNeedsCompositedScrolling() { }
+    virtual void updateHasVisibleNonLayerContent() { }
 
     virtual bool userInputScrollable(ScrollbarOrientation) const = 0;
     virtual bool shouldPlaceVerticalScrollbarOnLeft() const = 0;
@@ -197,9 +198,6 @@
     virtual GraphicsLayer* layerForHorizontalScrollbar() const { return 0; }
     virtual GraphicsLayer* layerForVerticalScrollbar() const { return 0; }
     virtual GraphicsLayer* layerForScrollCorner() const { return 0; }
-#if USE(RUBBER_BANDING)
-    virtual GraphicsLayer* layerForOverhangAreas() const { return 0; }
-#endif
     bool hasLayerForHorizontalScrollbar() const;
     bool hasLayerForVerticalScrollbar() const;
     bool hasLayerForScrollCorner() const;
diff --git a/Source/core/platform/Scrollbar.cpp b/Source/core/platform/Scrollbar.cpp
index 6a4f511..a5fd76f 100644
--- a/Source/core/platform/Scrollbar.cpp
+++ b/Source/core/platform/Scrollbar.cpp
@@ -459,7 +459,7 @@
     }
 
     if (parent() && parent()->isFrameView())
-        toFrameView(parent())->frame().eventHandler()->setMousePressed(false);
+        toFrameView(parent())->frame().eventHandler().setMousePressed(false);
 }
 
 void Scrollbar::mouseDown(const PlatformMouseEvent& evt)
diff --git a/Source/core/platform/ScrollbarTheme.h b/Source/core/platform/ScrollbarTheme.h
index cd84390..5a9c492 100644
--- a/Source/core/platform/ScrollbarTheme.h
+++ b/Source/core/platform/ScrollbarTheme.h
@@ -36,10 +36,6 @@
 class ScrollbarThemeClient;
 class ScrollView;
 
-#if USE(RUBBER_BANDING)
-class GraphicsLayer;
-#endif
-
 class ScrollbarTheme {
     WTF_MAKE_NONCOPYABLE(ScrollbarTheme); WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -87,11 +83,6 @@
     virtual void paintOverhangBackground(ScrollView*, GraphicsContext*, const IntRect&, const IntRect&, const IntRect&);
     virtual void paintOverhangShadows(ScrollView*, GraphicsContext*, const IntRect&, const IntRect&, const IntRect&) { }
 
-#if USE(RUBBER_BANDING)
-    virtual void setUpOverhangShadowLayer(GraphicsLayer*) { }
-    virtual void updateOverhangShadowLayer(GraphicsLayer* shadowLayer, GraphicsLayer* rootContentLayer) { }
-#endif
-
     virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) { return false; }
     virtual bool shouldSnapBackToDragOrigin(ScrollbarThemeClient*, const PlatformMouseEvent&) { return false; }
     virtual bool shouldDragDocumentInsteadOfThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) { return false; }
diff --git a/Source/core/platform/ScrollbarThemeMacCommon.h b/Source/core/platform/ScrollbarThemeMacCommon.h
index 524d833..83263ea 100644
--- a/Source/core/platform/ScrollbarThemeMacCommon.h
+++ b/Source/core/platform/ScrollbarThemeMacCommon.h
@@ -48,9 +48,6 @@
     virtual void paintOverhangShadows(ScrollView*, GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect) OVERRIDE;
     virtual void paintTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
 
-    virtual void setUpOverhangShadowLayer(GraphicsLayer*) OVERRIDE;
-    virtual void updateOverhangShadowLayer(GraphicsLayer* shadowLayer, GraphicsLayer* rootContentLayer) OVERRIDE;
-
 protected:
     virtual int maxOverlapBetweenPages() OVERRIDE { return 40; }
 
@@ -62,7 +59,6 @@
 
     void paintGivenTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, const Vector<IntRect>&);
 
-    RefPtr<Image> m_overhangShadow;
     RefPtr<Pattern> m_overhangPattern;
 };
 
diff --git a/Source/core/platform/ScrollbarThemeMacCommon.mm b/Source/core/platform/ScrollbarThemeMacCommon.mm
index d0559f7..a5004e6 100644
--- a/Source/core/platform/ScrollbarThemeMacCommon.mm
+++ b/Source/core/platform/ScrollbarThemeMacCommon.mm
@@ -186,6 +186,12 @@
     const bool hasVerticalOverhang = !verticalOverhangRect.isEmpty();
 
     GraphicsContextStateSaver stateSaver(*context);
+
+    if (!m_overhangPattern) {
+        // Lazily load the linen pattern image used for overhang drawing.
+        RefPtr<Image> patternImage = Image::loadPlatformResource("overhangPattern");
+        m_overhangPattern = Pattern::create(patternImage, true, true);
+    }
     context->setFillPattern(m_overhangPattern);
     if (hasHorizontalOverhang)
         context->fillRect(intersection(horizontalOverhangRect, dirtyRect));
@@ -338,41 +344,12 @@
         [WebScrollbarPrefsObserver registerAsObserver];
         preferencesChanged();
     }
-
-    // Load the shadow for the overhang.
-    m_overhangShadow = Image::loadPlatformResource("overhangShadow");
-
-    // Load the linen pattern image used for overhang drawing.
-    RefPtr<Image> patternImage = Image::loadPlatformResource("overhangPattern");
-    m_overhangPattern = Pattern::create(patternImage, true, true);
 }
 
 ScrollbarThemeMacCommon::~ScrollbarThemeMacCommon()
 {
 }
 
-void ScrollbarThemeMacCommon::setUpOverhangShadowLayer(GraphicsLayer* overhangShadowLayer)
-{
-  // The shadow texture is has a 1-pixel aperture in the center, so the division by
-  // two is doing an intentional round-down.
-  overhangShadowLayer->setContentsToNinePatch(
-      m_overhangShadow.get(),
-      IntRect(m_overhangShadow->width() / 2, m_overhangShadow->height() / 2, 1, 1));
-}
-
-void ScrollbarThemeMacCommon::updateOverhangShadowLayer(GraphicsLayer* shadowLayer, GraphicsLayer* rootContentLayer)
-{
-  // Note that for the position, the division m_overhangShadow->width() / 2 is an intentional
-  // round-down, and that for the width and height, the 1-pixel aperture is being replaced
-  // by the root contents layer, hence subtracting 1 and adding the rootContentsLayer size.
-  IntRect shadowRect (
-    static_cast<int>(rootContentLayer->position().x()) - m_overhangShadow->width() / 2,
-    static_cast<int>(rootContentLayer->position().y()) -  m_overhangShadow->height() / 2,
-    static_cast<int>(rootContentLayer->size().width()) + m_overhangShadow->width() - 1,
-    static_cast<int>(rootContentLayer->size().height()) + m_overhangShadow->height() - 1);
-  shadowLayer->setContentsRect(shadowRect);
-}
-
 void ScrollbarThemeMacCommon::preferencesChanged()
 {
     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
diff --git a/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm b/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm
index d0434cc..0781d2c 100644
--- a/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm
+++ b/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm
@@ -108,7 +108,6 @@
     LocalCurrentGraphicsContext localContext(context);
 
     ScrollbarPainter scrollbarPainter = painterForScrollbar(scrollbar);
-    CGRect frameRect = scrollbar->frameRect();
     [scrollbarPainter setEnabled:scrollbar->enabled()];
     [scrollbarPainter setBoundsSize:NSSizeFromCGSize(rect.size())];
     [scrollbarPainter setDoubleValue:0];
diff --git a/Source/core/platform/ScrollbarThemeWin.cpp b/Source/core/platform/ScrollbarThemeWin.cpp
index 8a6ad25..78086bf 100644
--- a/Source/core/platform/ScrollbarThemeWin.cpp
+++ b/Source/core/platform/ScrollbarThemeWin.cpp
@@ -72,7 +72,7 @@
 
 bool ScrollbarThemeWin::invalidateOnMouseEnterExit()
 {
-    return windowsVersion() >= WindowsVista;
+    return isWindowsVistaOrGreater();
 }
 
 bool ScrollbarThemeWin::shouldSnapBackToDragOrigin(ScrollbarThemeClient* scrollbar, const PlatformMouseEvent& evt)
@@ -145,12 +145,12 @@
     if (scrollbar->pressedPart() == ThumbPart) {
         if (part == ThumbPart)
             return SCRBS_PRESSED;
-        return (windowsVersion() < WindowsVista) ? SCRBS_NORMAL : SCRBS_HOVER;
+        return isWindowsVistaOrGreater() ? SCRBS_HOVER : SCRBS_NORMAL;
     }
     if (!scrollbar->enabled())
         return SCRBS_DISABLED;
     if (scrollbar->hoveredPart() != part || part == BackTrackPart || part == ForwardTrackPart)
-        return (scrollbar->hoveredPart() == NoPart || (windowsVersion() < WindowsVista)) ? SCRBS_NORMAL : SCRBS_HOVER;
+        return (scrollbar->hoveredPart() == NoPart || !isWindowsVistaOrGreater()) ? SCRBS_NORMAL : SCRBS_HOVER;
     if (scrollbar->pressedPart() == NoPart)
         return SCRBS_HOT;
     return (scrollbar->pressedPart() == part) ? SCRBS_PRESSED : SCRBS_NORMAL;
@@ -164,43 +164,43 @@
     if (part == BackButtonStartPart || part == ForwardButtonStartPart) {
         if (scrollbar->orientation() == HorizontalScrollbar) {
             if (scrollbar->pressedPart() == ThumbPart)
-                return (windowsVersion() < WindowsVista) ? ABS_LEFTNORMAL : ABS_LEFTHOVER;
+                return isWindowsVistaOrGreater() ? ABS_LEFTHOVER : ABS_LEFTNORMAL;
             if (!scrollbar->enabled())
                 return ABS_LEFTDISABLED;
             if (scrollbar->hoveredPart() != part)
-                return ((scrollbar->hoveredPart() == NoPart) || (windowsVersion() < WindowsVista)) ? ABS_LEFTNORMAL : ABS_LEFTHOVER;
+                return ((scrollbar->hoveredPart() == NoPart) || !isWindowsVistaOrGreater()) ? ABS_LEFTNORMAL : ABS_LEFTHOVER;
             if (scrollbar->pressedPart() == NoPart)
                 return ABS_LEFTHOT;
             return (scrollbar->pressedPart() == part) ?
                 ABS_LEFTPRESSED : ABS_LEFTNORMAL;
         }
         if (scrollbar->pressedPart() == ThumbPart)
-            return (windowsVersion() < WindowsVista) ? ABS_UPNORMAL : ABS_UPHOVER;
+            return isWindowsVistaOrGreater() ? ABS_UPHOVER : ABS_UPNORMAL;
         if (!scrollbar->enabled())
             return ABS_UPDISABLED;
         if (scrollbar->hoveredPart() != part)
-            return ((scrollbar->hoveredPart() == NoPart) || (windowsVersion() < WindowsVista)) ? ABS_UPNORMAL : ABS_UPHOVER;
+            return ((scrollbar->hoveredPart() == NoPart) || !isWindowsVistaOrGreater()) ? ABS_UPNORMAL : ABS_UPHOVER;
         if (scrollbar->pressedPart() == NoPart)
             return ABS_UPHOT;
         return (scrollbar->pressedPart() == part) ? ABS_UPPRESSED : ABS_UPNORMAL;
     }
     if (scrollbar->orientation() == HorizontalScrollbar) {
         if (scrollbar->pressedPart() == ThumbPart)
-            return (windowsVersion() < WindowsVista) ? ABS_RIGHTNORMAL : ABS_RIGHTHOVER;
+            return isWindowsVistaOrGreater() ? ABS_RIGHTHOVER : ABS_RIGHTNORMAL;
         if (!scrollbar->enabled())
             return ABS_RIGHTDISABLED;
         if (scrollbar->hoveredPart() != part)
-            return ((scrollbar->hoveredPart() == NoPart) || (windowsVersion() < WindowsVista)) ? ABS_RIGHTNORMAL : ABS_RIGHTHOVER;
+            return ((scrollbar->hoveredPart() == NoPart) || !isWindowsVistaOrGreater()) ? ABS_RIGHTNORMAL : ABS_RIGHTHOVER;
         if (scrollbar->pressedPart() == NoPart)
             return ABS_RIGHTHOT;
         return (scrollbar->pressedPart() == part) ? ABS_RIGHTPRESSED : ABS_RIGHTNORMAL;
     }
     if (scrollbar->pressedPart() == ThumbPart)
-        return (windowsVersion() < WindowsVista) ? ABS_DOWNNORMAL : ABS_DOWNHOVER;
+        return isWindowsVistaOrGreater() ? ABS_DOWNHOVER : ABS_DOWNNORMAL;
     if (!scrollbar->enabled())
         return ABS_DOWNDISABLED;
     if (scrollbar->hoveredPart() != part)
-        return ((scrollbar->hoveredPart() == NoPart) || (windowsVersion() < WindowsVista)) ? ABS_DOWNNORMAL : ABS_DOWNHOVER;
+        return ((scrollbar->hoveredPart() == NoPart) || !isWindowsVistaOrGreater()) ? ABS_DOWNNORMAL : ABS_DOWNHOVER;
     if (scrollbar->pressedPart() == NoPart)
         return ABS_DOWNHOT;
     return (scrollbar->pressedPart() == part) ? ABS_DOWNPRESSED : ABS_DOWNNORMAL;
diff --git a/Source/core/platform/Theme.h b/Source/core/platform/Theme.h
index c964170..a0cc99d 100644
--- a/Source/core/platform/Theme.h
+++ b/Source/core/platform/Theme.h
@@ -27,11 +27,11 @@
 #define Theme_h
 
 #include "core/platform/ThemeTypes.h"
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/Font.h"
 #include "platform/LengthBox.h"
 #include "platform/LengthSize.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/graphics/Color.h"
 #include "wtf/Forward.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/animation/AnimationTranslationUtil.cpp b/Source/core/platform/animation/AnimationTranslationUtil.cpp
index e04a0be..318fb92 100644
--- a/Source/core/platform/animation/AnimationTranslationUtil.cpp
+++ b/Source/core/platform/animation/AnimationTranslationUtil.cpp
@@ -30,18 +30,18 @@
 #include "core/platform/animation/KeyframeValueList.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
 #include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/graphics/transforms/InterpolatedTransformOperation.h"
-#include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
-#include "core/platform/graphics/transforms/MatrixTransformOperation.h"
-#include "core/platform/graphics/transforms/PerspectiveTransformOperation.h"
-#include "core/platform/graphics/transforms/RotateTransformOperation.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-#include "core/platform/graphics/transforms/SkewTransformOperation.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
 #include "platform/LengthFunctions.h"
 #include "platform/geometry/FloatSize.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/Platform.h"
 #include "public/platform/WebAnimation.h"
diff --git a/Source/core/platform/animation/AnimationTranslationUtilTest.cpp b/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
index 801b62f..edd0c71 100644
--- a/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
+++ b/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
@@ -29,12 +29,12 @@
 #include "core/platform/animation/CSSAnimationData.h"
 #include "core/platform/animation/KeyframeValueList.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
-#include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
-#include "core/platform/graphics/transforms/RotateTransformOperation.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
 #include "platform/geometry/IntSize.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 "wtf/RefPtr.h"
 #include <gtest/gtest.h>
diff --git a/Source/core/platform/animation/AnimationValue.h b/Source/core/platform/animation/AnimationValue.h
index c6298dc..e531699 100644
--- a/Source/core/platform/animation/AnimationValue.h
+++ b/Source/core/platform/animation/AnimationValue.h
@@ -29,7 +29,7 @@
 
 #include "core/platform/animation/TimingFunction.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
+#include "platform/transforms/TransformOperations.h"
 
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/platform/animation/TimingFunction.h b/Source/core/platform/animation/TimingFunction.h
index 39ce2b4..3429257 100644
--- a/Source/core/platform/animation/TimingFunction.h
+++ b/Source/core/platform/animation/TimingFunction.h
@@ -274,11 +274,10 @@
         RELEASE_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);
-        const Segment* segment;
-        for (size_t i = 0; i < m_segments.size(); ++i) {
-            segment = &m_segments[i];
-            if (fraction < segment->max())
-                break;
+        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);
     }
diff --git a/Source/core/platform/chromium/ChromiumDataObject.cpp b/Source/core/platform/chromium/ChromiumDataObject.cpp
index 78086a5..f649954 100644
--- a/Source/core/platform/chromium/ChromiumDataObject.cpp
+++ b/Source/core/platform/chromium/ChromiumDataObject.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/platform/chromium/ChromiumDataObject.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/DataTransferItem.h"
@@ -99,7 +100,7 @@
 {
     RefPtr<ChromiumDataObjectItem> item = ChromiumDataObjectItem::createFromString(type, data);
     if (!internalAddStringItem(item)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("add", "DataTransferItemList"));
         return 0;
     }
     return item;
diff --git a/Source/core/platform/chromium/HistogramSupportChromium.cpp b/Source/core/platform/chromium/HistogramSupportChromium.cpp
deleted file mode 100644
index 3834958..0000000
--- a/Source/core/platform/chromium/HistogramSupportChromium.cpp
+++ /dev/null
@@ -1,48 +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 "core/platform/HistogramSupport.h"
-
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-void HistogramSupport::histogramEnumeration(const char* name, int sample, int boundaryValue)
-{
-    WebKit::Platform::current()->histogramEnumeration(name, sample, boundaryValue);
-}
-
-void HistogramSupport::histogramCustomCounts(const char* name, int sample, int min, int max, int bucketCount)
-{
-    WebKit::Platform::current()->histogramCustomCounts(name, sample, min, max, bucketCount);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp b/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp
deleted file mode 100644
index 2975d48..0000000
--- a/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp
+++ /dev/null
@@ -1,72 +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/MemoryUsageSupport.h"
-
-#include <SkGraphics.h>
-#include "public/platform/Platform.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-int MemoryUsageSupport::memoryUsageMB()
-{
-    return WebKit::Platform::current()->memoryUsageMB();
-}
-
-int MemoryUsageSupport::actualMemoryUsageMB()
-{
-    return WebKit::Platform::current()->actualMemoryUsageMB();
-}
-
-bool MemoryUsageSupport::processMemorySizesInBytes(size_t* privateBytes, size_t* sharedBytes)
-{
-    return WebKit::Platform::current()->processMemorySizesInBytes(privateBytes, sharedBytes);
-}
-
-void MemoryUsageSupport::requestProcessMemorySizes(PassOwnPtr<WebCore::MemoryUsageSupport::ProcessMemorySizesCallback> requestCallback)
-{
-    class ProcessMemorySizesCallbackImpl : public WebKit::Platform::ProcessMemorySizesCallback {
-    public:
-        ProcessMemorySizesCallbackImpl(PassOwnPtr<WebCore::MemoryUsageSupport::ProcessMemorySizesCallback> callback) :
-            m_callback(callback) { }
-        virtual void dataReceived(size_t privateBytes, size_t sharedBytes)
-        {
-            m_callback->dataReceived(privateBytes, sharedBytes);
-        }
-    private:
-        OwnPtr<WebCore::MemoryUsageSupport::ProcessMemorySizesCallback> m_callback;
-    };
-    WebKit::Platform::ProcessMemorySizesCallback* callback = new ProcessMemorySizesCallbackImpl(requestCallback);
-    WebKit::Platform::current()->requestProcessMemorySizes(callback);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp b/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
deleted file mode 100644
index 2a4805b..0000000
--- a/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
+++ /dev/null
@@ -1,140 +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/WebCryptoAlgorithm.h"
-
-#include "public/platform/WebCryptoAlgorithmParams.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/ThreadSafeRefCounted.h"
-
-namespace WebKit {
-
-class WebCryptoAlgorithmPrivate : public ThreadSafeRefCounted<WebCryptoAlgorithmPrivate> {
-public:
-    WebCryptoAlgorithmPrivate(WebCryptoAlgorithmId id, PassOwnPtr<WebCryptoAlgorithmParams> params)
-        : id(id)
-        , params(params)
-    {
-    }
-
-    WebCryptoAlgorithmId id;
-    OwnPtr<WebCryptoAlgorithmParams> params;
-};
-
-WebCryptoAlgorithm::WebCryptoAlgorithm(WebCryptoAlgorithmId id, PassOwnPtr<WebCryptoAlgorithmParams> params)
-    : m_private(adoptRef(new WebCryptoAlgorithmPrivate(id, params)))
-{
-}
-
-WebCryptoAlgorithm WebCryptoAlgorithm::adoptParamsAndCreate(WebCryptoAlgorithmId id, WebCryptoAlgorithmParams* params)
-{
-    return WebCryptoAlgorithm(id, adoptPtr(params));
-}
-
-WebCryptoAlgorithmId WebCryptoAlgorithm::id() const
-{
-    return m_private->id;
-}
-
-WebCryptoAlgorithmParamsType WebCryptoAlgorithm::paramsType() const
-{
-    if (!m_private->params)
-        return WebCryptoAlgorithmParamsTypeNone;
-    return m_private->params->type();
-}
-
-const WebCryptoAesCbcParams* WebCryptoAlgorithm::aesCbcParams() const
-{
-    if (paramsType() == WebCryptoAlgorithmParamsTypeAesCbcParams)
-        return static_cast<WebCryptoAesCbcParams*>(m_private->params.get());
-    return 0;
-}
-
-const WebCryptoAesKeyGenParams* WebCryptoAlgorithm::aesKeyGenParams() const
-{
-    if (paramsType() == WebCryptoAlgorithmParamsTypeAesKeyGenParams)
-        return static_cast<WebCryptoAesKeyGenParams*>(m_private->params.get());
-    return 0;
-}
-
-const WebCryptoHmacParams* WebCryptoAlgorithm::hmacParams() const
-{
-    if (paramsType() == WebCryptoAlgorithmParamsTypeHmacParams)
-        return static_cast<WebCryptoHmacParams*>(m_private->params.get());
-    return 0;
-}
-
-const WebCryptoHmacKeyParams* WebCryptoAlgorithm::hmacKeyParams() const
-{
-    if (paramsType() == WebCryptoAlgorithmParamsTypeHmacKeyParams)
-        return static_cast<WebCryptoHmacKeyParams*>(m_private->params.get());
-    return 0;
-}
-
-const WebCryptoRsaSsaParams* WebCryptoAlgorithm::rsaSsaParams() const
-{
-    if (paramsType() == WebCryptoAlgorithmParamsTypeRsaSsaParams)
-        return static_cast<WebCryptoRsaSsaParams*>(m_private->params.get());
-    return 0;
-}
-
-const WebCryptoRsaKeyGenParams* WebCryptoAlgorithm::rsaKeyGenParams() const
-{
-    if (paramsType() == WebCryptoAlgorithmParamsTypeRsaKeyGenParams)
-        return static_cast<WebCryptoRsaKeyGenParams*>(m_private->params.get());
-    return 0;
-}
-
-const WebCryptoAesGcmParams* WebCryptoAlgorithm::aesGcmParams() const
-{
-    if (paramsType() == WebCryptoAlgorithmParamsTypeAesGcmParams)
-        return static_cast<WebCryptoAesGcmParams*>(m_private->params.get());
-    return 0;
-}
-
-const WebCryptoRsaOaepParams* WebCryptoAlgorithm::rsaOaepParams() const
-{
-    if (paramsType() == WebCryptoAlgorithmParamsTypeRsaOaepParams)
-        return static_cast<WebCryptoRsaOaepParams*>(m_private->params.get());
-    return 0;
-}
-
-void WebCryptoAlgorithm::assign(const WebCryptoAlgorithm& other)
-{
-    m_private = other.m_private;
-}
-
-void WebCryptoAlgorithm::reset()
-{
-    m_private.reset();
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebCryptoKey.cpp b/Source/core/platform/chromium/support/WebCryptoKey.cpp
index 64e3b9c..85d4a77 100644
--- a/Source/core/platform/chromium/support/WebCryptoKey.cpp
+++ b/Source/core/platform/chromium/support/WebCryptoKey.cpp
@@ -46,6 +46,7 @@
         , algorithm(algorithm)
         , usages(usages)
     {
+        ASSERT(!algorithm.isNull());
     }
 
     const OwnPtr<WebCryptoKeyHandle> handle;
diff --git a/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp b/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp
deleted file mode 100644
index e5d564c..0000000
--- a/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp
+++ /dev/null
@@ -1,158 +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/WebFileSystemCallbacks.h"
-
-#include "core/platform/AsyncFileSystemCallbacks.h"
-#include "platform/FileMetadata.h"
-#include "public/platform/WebFileInfo.h"
-#include "public/platform/WebFileSystem.h"
-#include "public/platform/WebFileSystemEntry.h"
-#include "public/platform/WebFileWriter.h"
-#include "public/platform/WebString.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-class WebFileSystemCallbacksPrivate : public RefCounted<WebFileSystemCallbacksPrivate> {
-public:
-    static PassRefPtr<WebFileSystemCallbacksPrivate> create(const PassOwnPtr<AsyncFileSystemCallbacks>& callbacks)
-    {
-        return adoptRef(new WebFileSystemCallbacksPrivate(callbacks));
-    }
-
-    AsyncFileSystemCallbacks* callbacks() { return m_callbacks.get(); }
-
-private:
-    WebFileSystemCallbacksPrivate(const PassOwnPtr<AsyncFileSystemCallbacks>& callbacks) : m_callbacks(callbacks) { }
-    OwnPtr<AsyncFileSystemCallbacks> m_callbacks;
-};
-
-WebFileSystemCallbacks::WebFileSystemCallbacks(const PassOwnPtr<AsyncFileSystemCallbacks>& callbacks)
-{
-    m_private = WebFileSystemCallbacksPrivate::create(callbacks);
-}
-
-void WebFileSystemCallbacks::reset()
-{
-    m_private.reset();
-}
-
-void WebFileSystemCallbacks::assign(const WebFileSystemCallbacks& other)
-{
-    m_private = other.m_private;
-}
-
-void WebFileSystemCallbacks::didSucceed()
-{
-    ASSERT(!m_private.isNull());
-    m_private->callbacks()->didSucceed();
-    m_private.reset();
-}
-
-void WebFileSystemCallbacks::didReadMetadata(const WebFileInfo& webFileInfo)
-{
-    ASSERT(!m_private.isNull());
-    FileMetadata fileMetadata;
-    fileMetadata.modificationTime = webFileInfo.modificationTime;
-    fileMetadata.length = webFileInfo.length;
-    fileMetadata.type = static_cast<FileMetadata::Type>(webFileInfo.type);
-    fileMetadata.platformPath = webFileInfo.platformPath;
-    m_private->callbacks()->didReadMetadata(fileMetadata);
-    m_private.reset();
-}
-
-void WebFileSystemCallbacks::didCreateSnapshotFile(const WebFileInfo& webFileInfo)
-{
-    ASSERT(!m_private.isNull());
-    // It's important to create a BlobDataHandle that refers to the platform file path prior
-    // to return from this method so the underlying file will not be deleted.
-    OwnPtr<BlobData> blobData = BlobData::create();
-    blobData->appendFile(webFileInfo.platformPath);
-    RefPtr<BlobDataHandle> snapshotBlob = BlobDataHandle::create(blobData.release(), webFileInfo.length);
-
-    FileMetadata fileMetadata;
-    fileMetadata.modificationTime = webFileInfo.modificationTime;
-    fileMetadata.length = webFileInfo.length;
-    fileMetadata.type = static_cast<FileMetadata::Type>(webFileInfo.type);
-    fileMetadata.platformPath = webFileInfo.platformPath;
-    m_private->callbacks()->didCreateSnapshotFile(fileMetadata, snapshotBlob);
-    m_private.reset();
-}
-
-void WebFileSystemCallbacks::didReadDirectory(const WebVector<WebFileSystemEntry>& entries, bool hasMore)
-{
-    ASSERT(!m_private.isNull());
-    for (size_t i = 0; i < entries.size(); ++i)
-        m_private->callbacks()->didReadDirectoryEntry(entries[i].name, entries[i].isDirectory);
-    m_private->callbacks()->didReadDirectoryEntries(hasMore);
-    m_private.reset();
-}
-
-void WebFileSystemCallbacks::didOpenFileSystem(const WebString& name, const WebURL& rootURL)
-{
-    ASSERT(!m_private.isNull());
-    m_private->callbacks()->didOpenFileSystem(name, rootURL);
-    m_private.reset();
-}
-
-void WebFileSystemCallbacks::didResolveURL(const WebString& name, const WebURL& rootURL, WebFileSystemType type, const WebString& filePath, bool isDirectory)
-{
-    ASSERT(!m_private.isNull());
-    m_private->callbacks()->didResolveURL(name, rootURL, static_cast<WebCore::FileSystemType>(type), filePath, isDirectory);
-    m_private.reset();
-}
-
-void WebFileSystemCallbacks::didCreateFileWriter(WebFileWriter* webFileWriter, long long length)
-{
-    ASSERT(!m_private.isNull());
-    m_private->callbacks()->didCreateFileWriter(adoptPtr(webFileWriter), length);
-    m_private.reset();
-}
-
-void WebFileSystemCallbacks::didFail(WebFileError error)
-{
-    ASSERT(!m_private.isNull());
-    m_private->callbacks()->didFail(error);
-    m_private.reset();
-}
-
-bool WebFileSystemCallbacks::shouldBlockUntilCompletion() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->callbacks()->shouldBlockUntilCompletion();
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebFilterKeyframe.cpp b/Source/core/platform/chromium/support/WebFilterKeyframe.cpp
deleted file mode 100644
index 0372ec1..0000000
--- a/Source/core/platform/chromium/support/WebFilterKeyframe.cpp
+++ /dev/null
@@ -1,43 +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. 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/WebFilterKeyframe.h"
-
-#include "wtf/PassOwnPtr.h"
-
-namespace WebKit {
-
-WebFilterKeyframe::WebFilterKeyframe(double time, PassOwnPtr<WebFilterOperations> value)
-    : m_time(time)
-    , m_value(value)
-{
-}
-
-WebFilterKeyframe::~WebFilterKeyframe()
-{
-    m_value.reset(0);
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebFloatQuad.cpp b/Source/core/platform/chromium/support/WebFloatQuad.cpp
deleted file mode 100644
index 9bb616b..0000000
--- a/Source/core/platform/chromium/support/WebFloatQuad.cpp
+++ /dev/null
@@ -1,51 +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/WebFloatQuad.h"
-
-#include <algorithm>
-#include <math.h>
-
-using namespace std;
-
-namespace WebKit {
-
-WebRect WebFloatQuad::enclosingRect() const
-{
-    int left = static_cast<int>(floorf(min(min(min(p[0].x, p[1].x), p[2].x), p[3].x)));
-    int top = static_cast<int>(floorf(min(min(min(p[0].y, p[1].y), p[2].y), p[3].y)));
-    int right = static_cast<int>(ceilf(max(max(max(p[0].x, p[1].x), p[2].x), p[3].x)));
-    int bottom = static_cast<int>(ceilf(max(max(max(p[0].y, p[1].y), p[2].y), p[3].y)));
-
-    return WebRect(left, top, right - left, bottom - top);
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebPrerender.cpp b/Source/core/platform/chromium/support/WebPrerender.cpp
deleted file mode 100644
index adf9410..0000000
--- a/Source/core/platform/chromium/support/WebPrerender.cpp
+++ /dev/null
@@ -1,133 +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/WebPrerender.h"
-
-#include "core/platform/Prerender.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebKit {
-
-namespace {
-
-class ExtraDataContainer : public WebCore::Prerender::ExtraData {
-public:
-    static PassRefPtr<ExtraDataContainer> create(WebPrerender::ExtraData* extraData) { return adoptRef(new ExtraDataContainer(extraData)); }
-
-    virtual ~ExtraDataContainer() { }
-
-    WebPrerender::ExtraData* extraData() const { return m_extraData.get(); }
-
-private:
-    explicit ExtraDataContainer(WebPrerender::ExtraData* extraData)
-        : m_extraData(adoptPtr(extraData))
-    {
-    }
-
-    OwnPtr<WebPrerender::ExtraData> m_extraData;
-};
-
-} // anon namespace
-
-WebPrerender::WebPrerender(PassRefPtr<WebCore::Prerender> prerender)
-    : m_private(prerender)
-{
-}
-
-const WebCore::Prerender* WebPrerender::toPrerender() const
-{
-    return m_private.get();
-}
-
-void WebPrerender::reset()
-{
-    m_private.reset();
-}
-
-void WebPrerender::assign(const WebPrerender& other)
-{
-    m_private = other.m_private;
-}
-
-bool WebPrerender::isNull() const
-{
-    return m_private.isNull();
-}
-
-WebURL WebPrerender::url() const
-{
-    return WebURL(m_private->url());
-}
-
-WebString WebPrerender::referrer() const
-{
-    return m_private->referrer();
-}
-
-WebReferrerPolicy WebPrerender::referrerPolicy() const
-{
-    return static_cast<WebReferrerPolicy>(m_private->referrerPolicy());
-}
-
-void WebPrerender::setExtraData(WebPrerender::ExtraData* extraData)
-{
-    m_private->setExtraData(ExtraDataContainer::create(extraData));
-}
-
-const WebPrerender::ExtraData* WebPrerender::extraData() const
-{
-    RefPtr<WebCore::Prerender::ExtraData> webcoreExtraData = m_private->extraData();
-    if (!webcoreExtraData)
-        return 0;
-    return static_cast<ExtraDataContainer*>(webcoreExtraData.get())->extraData();
-}
-
-void WebPrerender::didStartPrerender()
-{
-    m_private->didStartPrerender();
-}
-
-void WebPrerender::didStopPrerender()
-{
-    m_private->didStopPrerender();
-}
-
-void WebPrerender::didSendLoadForPrerender()
-{
-    m_private->didSendLoadForPrerender();
-}
-
-void WebPrerender::didSendDOMContentLoadedForPrerender()
-{
-    m_private->didSendDOMContentLoadedForPrerender();
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebPrerenderingSupport.cpp b/Source/core/platform/chromium/support/WebPrerenderingSupport.cpp
deleted file mode 100644
index a8cbfc4..0000000
--- a/Source/core/platform/chromium/support/WebPrerenderingSupport.cpp
+++ /dev/null
@@ -1,52 +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 "public/platform/WebPrerenderingSupport.h"
-
-namespace WebKit {
-
-WebPrerenderingSupport* WebPrerenderingSupport::s_platform = 0;
-
-void WebPrerenderingSupport::initialize(WebPrerenderingSupport* platform)
-{
-    s_platform = platform;
-}
-
-void WebPrerenderingSupport::shutdown()
-{
-    s_platform = 0;
-}
-
-WebPrerenderingSupport* WebPrerenderingSupport::current()
-{
-    return s_platform;
-}
-
-}
diff --git a/Source/core/platform/chromium/support/WebRTCICECandidate.cpp b/Source/core/platform/chromium/support/WebRTCICECandidate.cpp
deleted file mode 100644
index 755e941..0000000
--- a/Source/core/platform/chromium/support/WebRTCICECandidate.cpp
+++ /dev/null
@@ -1,105 +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/WebRTCICECandidate.h"
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "public/platform/WebString.h"
-
-namespace WebKit {
-
-class WebRTCICECandidatePrivate : public RefCounted<WebRTCICECandidatePrivate> {
-public:
-    static PassRefPtr<WebRTCICECandidatePrivate> create(const WebString& candidate, const WebString& sdpMid, unsigned short sdpMLineIndex)
-    {
-        return adoptRef(new WebRTCICECandidatePrivate(candidate, sdpMid, sdpMLineIndex));
-    }
-    virtual ~WebRTCICECandidatePrivate();
-
-    const WebString& candidate() const { return m_candidate; }
-    const WebString& sdpMid() const { return m_sdpMid; }
-    unsigned short sdpMLineIndex() const { return m_sdpMLineIndex; }
-
-private:
-    WebRTCICECandidatePrivate(const WebString& candidate, const WebString& sdpMid, unsigned short sdpMLineIndex);
-
-    WebString m_candidate;
-    WebString m_sdpMid;
-    unsigned short m_sdpMLineIndex;
-};
-
-WebRTCICECandidatePrivate::WebRTCICECandidatePrivate(const WebString& candidate, const WebString& sdpMid, unsigned short sdpMLineIndex)
-    : m_candidate(candidate)
-    , m_sdpMid(sdpMid)
-    , m_sdpMLineIndex(sdpMLineIndex)
-{
-}
-
-WebRTCICECandidatePrivate::~WebRTCICECandidatePrivate()
-{
-}
-
-void WebRTCICECandidate::assign(const WebRTCICECandidate& other)
-{
-    m_private = other.m_private;
-}
-
-void WebRTCICECandidate::reset()
-{
-    m_private.reset();
-}
-
-void WebRTCICECandidate::initialize(const WebString& candidate, const WebString& sdpMid, unsigned short sdpMLineIndex)
-{
-    m_private = WebRTCICECandidatePrivate::create(candidate, sdpMid, sdpMLineIndex);
-}
-
-WebString WebRTCICECandidate::candidate() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->candidate();
-}
-
-WebString WebRTCICECandidate::sdpMid() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->sdpMid();
-}
-
-unsigned short WebRTCICECandidate::sdpMLineIndex() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->sdpMLineIndex();
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp b/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
index 8e29213..6a9d860 100644
--- a/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
+++ b/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
@@ -38,10 +38,9 @@
 
 namespace WebKit {
 
-class WebRTCSessionDescriptionPrivate : public RefCounted<WebRTCSessionDescriptionPrivate> {
+class WebRTCSessionDescriptionPrivate FINAL : public RefCounted<WebRTCSessionDescriptionPrivate> {
 public:
     static PassRefPtr<WebRTCSessionDescriptionPrivate> create(const WebString& type, const WebString& sdp);
-    virtual ~WebRTCSessionDescriptionPrivate();
 
     WebString type() { return m_type; }
     void setType(const WebString& type) { m_type = type; }
@@ -67,10 +66,6 @@
 {
 }
 
-WebRTCSessionDescriptionPrivate::~WebRTCSessionDescriptionPrivate()
-{
-}
-
 void WebRTCSessionDescription::assign(const WebRTCSessionDescription& other)
 {
     m_private = other.m_private;
diff --git a/Source/core/platform/chromium/support/WebSourceInfo.cpp b/Source/core/platform/chromium/support/WebSourceInfo.cpp
deleted file mode 100644
index 449e6d9..0000000
--- a/Source/core/platform/chromium/support/WebSourceInfo.cpp
+++ /dev/null
@@ -1,112 +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 "public/platform/WebSourceInfo.h"
-
-#include "public/platform/WebString.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebKit {
-
-class WebSourceInfoPrivate : public RefCounted<WebSourceInfoPrivate> {
-public:
-    static PassRefPtr<WebSourceInfoPrivate> create(const WebString& id, WebSourceInfo::SourceKind, const WebString& label, WebSourceInfo::VideoFacingMode);
-    virtual ~WebSourceInfoPrivate();
-
-    const WebString& id() const { return m_id; }
-    WebSourceInfo::SourceKind kind() const { return m_kind; }
-    const WebString& label() const { return m_label; }
-    WebSourceInfo::VideoFacingMode facing() const { return m_facing; }
-
-private:
-    WebSourceInfoPrivate(const WebString& id, WebSourceInfo::SourceKind, const WebString& label, WebSourceInfo::VideoFacingMode);
-
-    WebString m_id;
-    WebSourceInfo::SourceKind m_kind;
-    WebString m_label;
-    WebSourceInfo::VideoFacingMode m_facing;
-};
-
-PassRefPtr<WebSourceInfoPrivate> WebSourceInfoPrivate::create(const WebString& id, WebSourceInfo::SourceKind kind, const WebString& label, WebSourceInfo::VideoFacingMode facing)
-{
-    return adoptRef(new WebSourceInfoPrivate(id, kind, label, facing));
-}
-
-WebSourceInfoPrivate::WebSourceInfoPrivate(const WebString& id, WebSourceInfo::SourceKind kind, const WebString& label, WebSourceInfo::VideoFacingMode facing)
-    : m_id(id)
-    , m_kind(kind)
-    , m_label(label)
-    , m_facing(facing)
-{
-}
-
-WebSourceInfoPrivate::~WebSourceInfoPrivate()
-{
-}
-
-void WebSourceInfo::assign(const WebSourceInfo& other)
-{
-    m_private = other.m_private;
-}
-
-void WebSourceInfo::reset()
-{
-    m_private.reset();
-}
-
-void WebSourceInfo::initialize(const WebString& id, WebSourceInfo::SourceKind kind, const WebString& label, WebSourceInfo::VideoFacingMode facing)
-{
-    m_private = WebSourceInfoPrivate::create(id, kind, label, facing);
-}
-
-WebString WebSourceInfo::id() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->id();
-}
-
-WebSourceInfo::SourceKind WebSourceInfo::kind() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->kind();
-}
-
-WebString WebSourceInfo::label() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->label();
-}
-
-WebSourceInfo::VideoFacingMode WebSourceInfo::facing() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->facing();
-}
-
-} // namespace WebKit
-
diff --git a/Source/core/platform/chromium/support/WebTransformKeyframe.cpp b/Source/core/platform/chromium/support/WebTransformKeyframe.cpp
deleted file mode 100644
index 12eb5ff..0000000
--- a/Source/core/platform/chromium/support/WebTransformKeyframe.cpp
+++ /dev/null
@@ -1,53 +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/WebTransformKeyframe.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebKit {
-
-WebTransformKeyframe::WebTransformKeyframe(double time, PassOwnPtr<WebTransformOperations> value)
-    : m_time(time)
-    , m_value(value)
-{
-}
-
-WebTransformKeyframe::~WebTransformKeyframe()
-{
-    m_value.reset(0);
-}
-
-double WebTransformKeyframe::time() const
-{
-    return m_time;
-}
-
-const WebTransformOperations& WebTransformKeyframe::value() const
-{
-    return *m_value.get();
-}
-
-
-} // namespace WebKit
diff --git a/Source/core/platform/graphics/AlternateFontFamily.h b/Source/core/platform/graphics/AlternateFontFamily.h
index 9a735c2..d34f2be 100644
--- a/Source/core/platform/graphics/AlternateFontFamily.h
+++ b/Source/core/platform/graphics/AlternateFontFamily.h
@@ -31,7 +31,7 @@
 #ifndef AlternateFontFamily_h
 #define AlternateFontFamily_h
 
-#include "core/platform/graphics/FontDescription.h"
+#include "platform/fonts/FontDescription.h"
 #include "wtf/text/AtomicString.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/graphics/BitmapImage.h b/Source/core/platform/graphics/BitmapImage.h
index bbbf4d8..702ea8d 100644
--- a/Source/core/platform/graphics/BitmapImage.h
+++ b/Source/core/platform/graphics/BitmapImage.h
@@ -28,11 +28,11 @@
 #ifndef BitmapImage_h
 #define BitmapImage_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/FrameData.h"
 #include "core/platform/graphics/Image.h"
 #include "core/platform/graphics/ImageSource.h"
 #include "platform/geometry/IntSize.h"
+#include "platform/graphics/Color.h"
 #include "platform/graphics/ImageOrientation.h"
 #include "wtf/Forward.h"
 
diff --git a/Source/core/platform/graphics/Color.cpp b/Source/core/platform/graphics/Color.cpp
deleted file mode 100644
index c76efef..0000000
--- a/Source/core/platform/graphics/Color.cpp
+++ /dev/null
@@ -1,448 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 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/platform/graphics/Color.h"
-
-#include "core/platform/HashTools.h"
-#include "wtf/Assertions.h"
-#include "wtf/DecimalNumber.h"
-#include "wtf/HexNumber.h"
-#include "wtf/MathExtras.h"
-#include "wtf/text/StringBuilder.h"
-
-using namespace std;
-
-namespace WebCore {
-
-#if !COMPILER(MSVC)
-const RGBA32 Color::black;
-const RGBA32 Color::white;
-const RGBA32 Color::darkGray;
-const RGBA32 Color::gray;
-const RGBA32 Color::lightGray;
-const RGBA32 Color::transparent;
-#endif
-
-static const RGBA32 lightenedBlack = 0xFF545454;
-static const RGBA32 darkenedWhite = 0xFFABABAB;
-
-RGBA32 makeRGB(int r, int g, int b)
-{
-    return 0xFF000000 | max(0, min(r, 255)) << 16 | max(0, min(g, 255)) << 8 | max(0, min(b, 255));
-}
-
-RGBA32 makeRGBA(int r, int g, int b, int a)
-{
-    return max(0, min(a, 255)) << 24 | max(0, min(r, 255)) << 16 | max(0, min(g, 255)) << 8 | max(0, min(b, 255));
-}
-
-static int colorFloatToRGBAByte(float f)
-{
-    // We use lroundf and 255 instead of nextafterf(256, 0) to match CG's rounding
-    return max(0, min(static_cast<int>(lroundf(255.0f * f)), 255));
-}
-
-RGBA32 makeRGBA32FromFloats(float r, float g, float b, float a)
-{
-    return colorFloatToRGBAByte(a) << 24 | colorFloatToRGBAByte(r) << 16 | colorFloatToRGBAByte(g) << 8 | colorFloatToRGBAByte(b);
-}
-
-RGBA32 colorWithOverrideAlpha(RGBA32 color, float overrideAlpha)
-{
-    RGBA32 rgbOnly = color & 0x00FFFFFF;
-    RGBA32 rgba = rgbOnly | colorFloatToRGBAByte(overrideAlpha) << 24;
-    return rgba;
-}
-
-static double calcHue(double temp1, double temp2, double hueVal)
-{
-    if (hueVal < 0.0)
-        hueVal++;
-    else if (hueVal > 1.0)
-        hueVal--;
-    if (hueVal * 6.0 < 1.0)
-        return temp1 + (temp2 - temp1) * hueVal * 6.0;
-    if (hueVal * 2.0 < 1.0)
-        return temp2;
-    if (hueVal * 3.0 < 2.0)
-        return temp1 + (temp2 - temp1) * (2.0 / 3.0 - hueVal) * 6.0;
-    return temp1;
-}
-
-// Explanation of this algorithm can be found in the CSS3 Color Module
-// specification at http://www.w3.org/TR/css3-color/#hsl-color with further
-// explanation available at http://en.wikipedia.org/wiki/HSL_color_space
-
-// all values are in the range of 0 to 1.0
-RGBA32 makeRGBAFromHSLA(double hue, double saturation, double lightness, double alpha)
-{
-    const double scaleFactor = nextafter(256.0, 0.0);
-
-    if (!saturation) {
-        int greyValue = static_cast<int>(lightness * scaleFactor);
-        return makeRGBA(greyValue, greyValue, greyValue, static_cast<int>(alpha * scaleFactor));
-    }
-
-    double temp2 = lightness < 0.5 ? lightness * (1.0 + saturation) : lightness + saturation - lightness * saturation;
-    double temp1 = 2.0 * lightness - temp2;
-
-    return makeRGBA(static_cast<int>(calcHue(temp1, temp2, hue + 1.0 / 3.0) * scaleFactor),
-                    static_cast<int>(calcHue(temp1, temp2, hue) * scaleFactor),
-                    static_cast<int>(calcHue(temp1, temp2, hue - 1.0 / 3.0) * scaleFactor),
-                    static_cast<int>(alpha * scaleFactor));
-}
-
-RGBA32 makeRGBAFromCMYKA(float c, float m, float y, float k, float a)
-{
-    double colors = 1 - k;
-    int r = static_cast<int>(nextafter(256, 0) * (colors * (1 - c)));
-    int g = static_cast<int>(nextafter(256, 0) * (colors * (1 - m)));
-    int b = static_cast<int>(nextafter(256, 0) * (colors * (1 - y)));
-    return makeRGBA(r, g, b, static_cast<float>(nextafter(256, 0) * a));
-}
-
-// originally moved here from the CSS parser
-template <typename CharacterType>
-static inline bool parseHexColorInternal(const CharacterType* name, unsigned length, RGBA32& rgb)
-{
-    if (length != 3 && length != 6)
-        return false;
-    unsigned value = 0;
-    for (unsigned i = 0; i < length; ++i) {
-        if (!isASCIIHexDigit(name[i]))
-            return false;
-        value <<= 4;
-        value |= toASCIIHexValue(name[i]);
-    }
-    if (length == 6) {
-        rgb = 0xFF000000 | value;
-        return true;
-    }
-    // #abc converts to #aabbcc
-    rgb = 0xFF000000
-        | (value & 0xF00) << 12 | (value & 0xF00) << 8
-        | (value & 0xF0) << 8 | (value & 0xF0) << 4
-        | (value & 0xF) << 4 | (value & 0xF);
-    return true;
-}
-
-bool Color::parseHexColor(const LChar* name, unsigned length, RGBA32& rgb)
-{
-    return parseHexColorInternal(name, length, rgb);
-}
-
-bool Color::parseHexColor(const UChar* name, unsigned length, RGBA32& rgb)
-{
-    return parseHexColorInternal(name, length, rgb);
-}
-
-bool Color::parseHexColor(const String& name, RGBA32& rgb)
-{
-    unsigned length = name.length();
-
-    if (!length)
-        return false;
-    if (name.is8Bit())
-        return parseHexColor(name.characters8(), name.length(), rgb);
-    return parseHexColor(name.characters16(), name.length(), rgb);
-}
-
-int differenceSquared(const Color& c1, const Color& c2)
-{
-    int dR = c1.red() - c2.red();
-    int dG = c1.green() - c2.green();
-    int dB = c1.blue() - c2.blue();
-    return dR * dR + dG * dG + dB * dB;
-}
-
-Color::Color(const String& name)
-{
-    if (name[0] == '#') {
-        if (name.is8Bit())
-            m_valid = parseHexColor(name.characters8() + 1, name.length() - 1, m_color);
-        else
-            m_valid = parseHexColor(name.characters16() + 1, name.length() - 1, m_color);
-    } else {
-        setNamedColor(name);
-    }
-}
-
-Color::Color(const char* name)
-{
-    if (name[0] == '#') {
-        m_valid = parseHexColor(&name[1], m_color);
-    } else {
-        const NamedColor* foundColor = findColor(name, strlen(name));
-        m_color = foundColor ? foundColor->ARGBValue : 0;
-        m_valid = foundColor;
-    }
-}
-
-String Color::serialized() const
-{
-    if (!hasAlpha()) {
-        StringBuilder builder;
-        builder.reserveCapacity(7);
-        builder.append('#');
-        appendByteAsHex(red(), builder, Lowercase);
-        appendByteAsHex(green(), builder, Lowercase);
-        appendByteAsHex(blue(), builder, Lowercase);
-        return builder.toString();
-    }
-
-    StringBuilder result;
-    result.reserveCapacity(28);
-    const char commaSpace[] = ", ";
-    const char rgbaParen[] = "rgba(";
-
-    result.append(rgbaParen, 5);
-    result.appendNumber(red());
-    result.append(commaSpace, 2);
-    result.appendNumber(green());
-    result.append(commaSpace, 2);
-    result.appendNumber(blue());
-    result.append(commaSpace, 2);
-
-    if (!alpha())
-        result.append('0');
-    else {
-        NumberToLStringBuffer buffer;
-        unsigned length = DecimalNumber(alpha() / 255.0).toStringDecimal(buffer, WTF::NumberToStringBufferLength);
-        result.append(buffer, length);
-    }
-
-    result.append(')');
-    return result.toString();
-}
-
-String Color::nameForRenderTreeAsText() const
-{
-    if (alpha() < 0xFF)
-        return String::format("#%02X%02X%02X%02X", red(), green(), blue(), alpha());
-    return String::format("#%02X%02X%02X", red(), green(), blue());
-}
-
-static inline const NamedColor* findNamedColor(const String& name)
-{
-    char buffer[64]; // easily big enough for the longest color name
-    unsigned length = name.length();
-    if (length > sizeof(buffer) - 1)
-        return 0;
-    for (unsigned i = 0; i < length; ++i) {
-        UChar c = name[i];
-        if (!c || c > 0x7F)
-            return 0;
-        buffer[i] = toASCIILower(static_cast<char>(c));
-    }
-    buffer[length] = '\0';
-    return findColor(buffer, length);
-}
-
-void Color::setNamedColor(const String& name)
-{
-    const NamedColor* foundColor = findNamedColor(name);
-    m_color = foundColor ? foundColor->ARGBValue : 0;
-    m_valid = foundColor;
-}
-
-Color Color::light() const
-{
-    // Hardcode this common case for speed.
-    if (m_color == black)
-        return lightenedBlack;
-
-    const float scaleFactor = nextafterf(256.0f, 0.0f);
-
-    float r, g, b, a;
-    getRGBA(r, g, b, a);
-
-    float v = max(r, max(g, b));
-
-    if (v == 0.0f)
-        // Lightened black with alpha.
-        return Color(0x54, 0x54, 0x54, alpha());
-
-    float multiplier = min(1.0f, v + 0.33f) / v;
-
-    return Color(static_cast<int>(multiplier * r * scaleFactor),
-                 static_cast<int>(multiplier * g * scaleFactor),
-                 static_cast<int>(multiplier * b * scaleFactor),
-                 alpha());
-}
-
-Color Color::dark() const
-{
-    // Hardcode this common case for speed.
-    if (m_color == white)
-        return darkenedWhite;
-
-    const float scaleFactor = nextafterf(256.0f, 0.0f);
-
-    float r, g, b, a;
-    getRGBA(r, g, b, a);
-
-    float v = max(r, max(g, b));
-    float multiplier = max(0.0f, (v - 0.33f) / v);
-
-    return Color(static_cast<int>(multiplier * r * scaleFactor),
-                 static_cast<int>(multiplier * g * scaleFactor),
-                 static_cast<int>(multiplier * b * scaleFactor),
-                 alpha());
-}
-
-static int blendComponent(int c, int a)
-{
-    // We use white.
-    float alpha = a / 255.0f;
-    int whiteBlend = 255 - a;
-    c -= whiteBlend;
-    return static_cast<int>(c / alpha);
-}
-
-const int cStartAlpha = 153; // 60%
-const int cEndAlpha = 204; // 80%;
-const int cAlphaIncrement = 17; // Increments in between.
-
-Color Color::blend(const Color& source) const
-{
-    if (!alpha() || !source.hasAlpha())
-        return source;
-
-    if (!source.alpha())
-        return *this;
-
-    int d = 255 * (alpha() + source.alpha()) - alpha() * source.alpha();
-    int a = d / 255;
-    int r = (red() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.red()) / d;
-    int g = (green() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.green()) / d;
-    int b = (blue() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.blue()) / d;
-    return Color(r, g, b, a);
-}
-
-Color Color::blendWithWhite() const
-{
-    // If the color contains alpha already, we leave it alone.
-    if (hasAlpha())
-        return *this;
-
-    Color newColor;
-    for (int alpha = cStartAlpha; alpha <= cEndAlpha; alpha += cAlphaIncrement) {
-        // We have a solid color.  Convert to an equivalent color that looks the same when blended with white
-        // at the current alpha.  Try using less transparency if the numbers end up being negative.
-        int r = blendComponent(red(), alpha);
-        int g = blendComponent(green(), alpha);
-        int b = blendComponent(blue(), alpha);
-
-        newColor = Color(r, g, b, alpha);
-
-        if (r >= 0 && g >= 0 && b >= 0)
-            break;
-    }
-    return newColor;
-}
-
-void Color::getRGBA(float& r, float& g, float& b, float& a) const
-{
-    r = red() / 255.0f;
-    g = green() / 255.0f;
-    b = blue() / 255.0f;
-    a = alpha() / 255.0f;
-}
-
-void Color::getRGBA(double& r, double& g, double& b, double& a) const
-{
-    r = red() / 255.0;
-    g = green() / 255.0;
-    b = blue() / 255.0;
-    a = alpha() / 255.0;
-}
-
-void Color::getHSL(double& hue, double& saturation, double& lightness) const
-{
-    // http://en.wikipedia.org/wiki/HSL_color_space. This is a direct copy of
-    // the algorithm therein, although it's 360^o based and we end up wanting
-    // [0...1) based. It's clearer if we stick to 360^o until the end.
-    double r = static_cast<double>(red()) / 255.0;
-    double g = static_cast<double>(green()) / 255.0;
-    double b = static_cast<double>(blue()) / 255.0;
-    double max = std::max(std::max(r, g), b);
-    double min = std::min(std::min(r, g), b);
-
-    if (max == min)
-        hue = 0.0;
-    else if (max == r)
-        hue = (60.0 * ((g - b) / (max - min))) + 360.0;
-    else if (max == g)
-        hue = (60.0 * ((b - r) / (max - min))) + 120.0;
-    else
-        hue = (60.0 * ((r - g) / (max - min))) + 240.0;
-
-    if (hue >= 360.0)
-        hue -= 360.0;
-
-    // makeRGBAFromHSLA assumes that hue is in [0...1).
-    hue /= 360.0;
-
-    lightness = 0.5 * (max + min);
-    if (max == min)
-        saturation = 0.0;
-    else if (lightness <= 0.5)
-        saturation = ((max - min) / (max + min));
-    else
-        saturation = ((max - min) / (2.0 - (max + min)));
-}
-
-Color colorFromPremultipliedARGB(RGBA32 pixelColor)
-{
-    int alpha = alphaChannel(pixelColor);
-    if (alpha && alpha < 255) {
-        return Color::createUnchecked(
-            redChannel(pixelColor) * 255 / alpha,
-            greenChannel(pixelColor) * 255 / alpha,
-            blueChannel(pixelColor) * 255 / alpha,
-            alpha);
-    } else
-        return Color(pixelColor);
-}
-
-RGBA32 premultipliedARGBFromColor(const Color& color)
-{
-    unsigned pixelColor;
-
-    unsigned alpha = color.alpha();
-    if (alpha < 255) {
-        pixelColor = Color::createUnchecked(
-            (color.red() * alpha  + 254) / 255,
-            (color.green() * alpha  + 254) / 255,
-            (color.blue() * alpha  + 254) / 255,
-            alpha).rgb();
-    } else
-         pixelColor = color.rgb();
-
-    return pixelColor;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/Color.h b/Source/core/platform/graphics/Color.h
deleted file mode 100644
index 28983ed..0000000
--- a/Source/core/platform/graphics/Color.h
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 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 Color_h
-#define Color_h
-
-#include "platform/animation/AnimationUtilities.h"
-#include "wtf/FastAllocBase.h"
-#include "wtf/Forward.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-class Color;
-
-typedef unsigned RGBA32;        // RGBA quadruplet
-
-RGBA32 makeRGB(int r, int g, int b);
-RGBA32 makeRGBA(int r, int g, int b, int a);
-
-RGBA32 colorWithOverrideAlpha(RGBA32 color, float overrideAlpha);
-RGBA32 makeRGBA32FromFloats(float r, float g, float b, float a);
-RGBA32 makeRGBAFromHSLA(double h, double s, double l, double a);
-RGBA32 makeRGBAFromCMYKA(float c, float m, float y, float k, float a);
-
-int differenceSquared(const Color&, const Color&);
-
-inline int redChannel(RGBA32 color) { return (color >> 16) & 0xFF; }
-inline int greenChannel(RGBA32 color) { return (color >> 8) & 0xFF; }
-inline int blueChannel(RGBA32 color) { return color & 0xFF; }
-inline int alphaChannel(RGBA32 color) { return (color >> 24) & 0xFF; }
-
-class Color {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    Color() : m_color(0), m_valid(false) { }
-    Color(RGBA32 color, bool valid = true) : m_color(color), m_valid(valid) { ASSERT(!m_color || m_valid); }
-    Color(int r, int g, int b) : m_color(makeRGB(r, g, b)), m_valid(true) { }
-    Color(int r, int g, int b, int a) : m_color(makeRGBA(r, g, b, a)), m_valid(true) { }
-    // Color is currently limited to 32bit RGBA, perhaps some day we'll support better colors
-    Color(float r, float g, float b, float a) : m_color(makeRGBA32FromFloats(r, g, b, a)), m_valid(true) { }
-    // Creates a new color from the specific CMYK and alpha values.
-    Color(float c, float m, float y, float k, float a) : m_color(makeRGBAFromCMYKA(c, m, y, k, a)), m_valid(true) { }
-    explicit Color(const String&);
-    explicit Color(const char*);
-
-    static Color createUnchecked(int r, int g, int b)
-    {
-        RGBA32 color = 0xFF000000 | r << 16 | g << 8 | b;
-        return Color(color);
-    }
-    static Color createUnchecked(int r, int g, int b, int a)
-    {
-        RGBA32 color = a << 24 | r << 16 | g << 8 | b;
-        return Color(color);
-    }
-
-    // Returns the color serialized according to HTML5
-    // - http://www.whatwg.org/specs/web-apps/current-work/#serialization-of-a-color
-    String serialized() const;
-
-    // Returns the color serialized as either #RRGGBB or #RRGGBBAA
-    // The latter format is not a valid CSS color, and should only be seen in DRT dumps.
-    String nameForRenderTreeAsText() const;
-
-    void setNamedColor(const String&);
-
-    bool isValid() const { return m_valid; }
-
-    bool hasAlpha() const { return alpha() < 255; }
-
-    int red() const { return redChannel(m_color); }
-    int green() const { return greenChannel(m_color); }
-    int blue() const { return blueChannel(m_color); }
-    int alpha() const { return alphaChannel(m_color); }
-
-    RGBA32 rgb() const { return m_color; } // Preserve the alpha.
-    void setRGB(int r, int g, int b) { m_color = makeRGB(r, g, b); m_valid = true; }
-    void setRGB(RGBA32 rgb) { m_color = rgb; m_valid = true; }
-    void getRGBA(float& r, float& g, float& b, float& a) const;
-    void getRGBA(double& r, double& g, double& b, double& a) const;
-    void getHSL(double& h, double& s, double& l) const;
-
-    Color light() const;
-    Color dark() const;
-
-    // This is an implementation of Porter-Duff's "source-over" equation
-    Color blend(const Color&) const;
-    Color blendWithWhite() const;
-
-    static bool parseHexColor(const String&, RGBA32&);
-    static bool parseHexColor(const LChar*, unsigned, RGBA32&);
-    static bool parseHexColor(const UChar*, unsigned, RGBA32&);
-
-    static const RGBA32 black = 0xFF000000;
-    static const RGBA32 white = 0xFFFFFFFF;
-    static const RGBA32 darkGray = 0xFF808080;
-    static const RGBA32 gray = 0xFFA0A0A0;
-    static const RGBA32 lightGray = 0xFFC0C0C0;
-    static const RGBA32 transparent = 0x00000000;
-
-private:
-    RGBA32 m_color;
-    bool m_valid;
-};
-
-inline bool operator==(const Color& a, const Color& b)
-{
-    return a.rgb() == b.rgb() && a.isValid() == b.isValid();
-}
-
-inline bool operator!=(const Color& a, const Color& b)
-{
-    return !(a == b);
-}
-
-Color colorFromPremultipliedARGB(RGBA32);
-RGBA32 premultipliedARGBFromColor(const Color&);
-
-inline Color blend(const Color& from, const Color& to, double progress, bool blendPremultiplied = true)
-{
-    // We need to preserve the state of the valid flag at the end of the animation
-    if (progress == 1 && !to.isValid())
-        return Color();
-
-    if (blendPremultiplied) {
-        // Contrary to the name, RGBA32 actually stores ARGB, so we can initialize Color directly from premultipliedARGBFromColor().
-        // Also, premultipliedARGBFromColor() bails on zero alpha, so special-case that.
-        Color premultFrom = from.alpha() ? premultipliedARGBFromColor(from) : 0;
-        Color premultTo = to.alpha() ? premultipliedARGBFromColor(to) : 0;
-
-        Color premultBlended(blend(premultFrom.red(), premultTo.red(), progress),
-                     blend(premultFrom.green(), premultTo.green(), progress),
-                     blend(premultFrom.blue(), premultTo.blue(), progress),
-                     blend(premultFrom.alpha(), premultTo.alpha(), progress));
-
-        return Color(colorFromPremultipliedARGB(premultBlended.rgb()));
-    }
-
-    return Color(blend(from.red(), to.red(), progress),
-                 blend(from.green(), to.green(), progress),
-                 blend(from.blue(), to.blue(), progress),
-                 blend(from.alpha(), to.alpha(), progress));
-}
-} // namespace WebCore
-
-#endif // Color_h
diff --git a/Source/core/platform/graphics/ColorSpace.h b/Source/core/platform/graphics/ColorSpace.h
deleted file mode 100644
index 989d0fb..0000000
--- a/Source/core/platform/graphics/ColorSpace.h
+++ /dev/null
@@ -1,39 +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.
- *
- * 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 ColorSpace_h
-#define ColorSpace_h
-
-namespace WebCore {
-
-enum ColorSpace {
-    ColorSpaceDeviceRGB,
-    ColorSpaceSRGB,
-    ColorSpaceLinearRGB
-};
-
-} // namespace WebCore
-
-#endif // ColorSpace_h
diff --git a/Source/core/platform/graphics/DashArray.h b/Source/core/platform/graphics/DashArray.h
deleted file mode 100644
index 1134eb4..0000000
--- a/Source/core/platform/graphics/DashArray.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2008 Dirk Schulze <vbs85@gmx.de>
- *
- * 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 DashArray_h
-#define DashArray_h
-
-#include "wtf/Vector.h"
-
-typedef float DashArrayElement;
-
-typedef Vector<DashArrayElement> DashArray;
-
-#endif // DashArray_h
diff --git a/Source/core/platform/graphics/DrawLooper.cpp b/Source/core/platform/graphics/DrawLooper.cpp
deleted file mode 100644
index 270419b..0000000
--- a/Source/core/platform/graphics/DrawLooper.cpp
+++ /dev/null
@@ -1,108 +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/graphics/DrawLooper.h"
-
-#include "core/platform/graphics/Color.h"
-#include "platform/geometry/FloatSize.h"
-#include "third_party/skia/include/core/SkColor.h"
-#include "third_party/skia/include/core/SkColorFilter.h"
-#include "third_party/skia/include/core/SkDrawLooper.h"
-#include "third_party/skia/include/core/SkPaint.h"
-#include "third_party/skia/include/core/SkXfermode.h"
-#include "third_party/skia/include/effects/SkBlurMaskFilter.h"
-#include "third_party/skia/include/effects/SkLayerDrawLooper.h"
-
-namespace WebCore {
-
-DrawLooper::DrawLooper() : m_skDrawLooper(adoptRef(new SkLayerDrawLooper)) { }
-
-DrawLooper::~DrawLooper() { }
-
-SkDrawLooper* DrawLooper::skDrawLooper() const
-{
-    return m_skDrawLooper.get();
-}
-
-void DrawLooper::addUnmodifiedContent()
-{
-    SkLayerDrawLooper::LayerInfo info;
-    m_skDrawLooper->addLayerOnTop(info);
-}
-
-void DrawLooper::addShadow(const FloatSize& offset, float blur, const Color& color,
-    ShadowTransformMode shadowTransformMode, ShadowAlphaMode shadowAlphaMode)
-{
-    // Detect when there's no effective shadow.
-    if (!color.isValid() || !color.alpha())
-        return;
-
-    SkColor skColor;
-    if (color.isValid())
-        skColor = color.rgb();
-    else
-        skColor = SkColorSetARGB(0xFF / 3, 0, 0, 0); // "std" apple shadow color.
-
-    SkLayerDrawLooper::LayerInfo info;
-
-    switch (shadowAlphaMode) {
-    case ShadowRespectsAlpha:
-        info.fColorMode = SkXfermode::kDst_Mode;
-        break;
-    case ShadowIgnoresAlpha:
-        info.fColorMode = SkXfermode::kSrc_Mode;
-        break;
-    default:
-        ASSERT_NOT_REACHED();
-    }
-
-    if (blur)
-        info.fPaintBits |= SkLayerDrawLooper::kMaskFilter_Bit; // our blur
-    info.fPaintBits |= SkLayerDrawLooper::kColorFilter_Bit;
-    info.fOffset.set(offset.width(), offset.height());
-    info.fPostTranslate = (shadowTransformMode == ShadowIgnoresTransforms);
-
-    SkPaint* paint = m_skDrawLooper->addLayerOnTop(info);
-
-    if (blur) {
-        uint32_t mfFlags = SkBlurMaskFilter::kHighQuality_BlurFlag;
-        if (shadowTransformMode == ShadowIgnoresTransforms)
-            mfFlags |= SkBlurMaskFilter::kIgnoreTransform_BlurFlag;
-        RefPtr<SkMaskFilter> mf = adoptRef(SkBlurMaskFilter::Create(
-            (double)blur / 2.0, SkBlurMaskFilter::kNormal_BlurStyle, mfFlags));
-        paint->setMaskFilter(mf.get());
-    }
-
-    RefPtr<SkColorFilter> cf = adoptRef(SkColorFilter::CreateModeFilter(skColor, SkXfermode::kSrcIn_Mode));
-    paint->setColorFilter(cf.get());
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/DrawLooper.h b/Source/core/platform/graphics/DrawLooper.h
deleted file mode 100644
index 97a3b0d..0000000
--- a/Source/core/platform/graphics/DrawLooper.h
+++ /dev/null
@@ -1,78 +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 DrawLooper_h
-#define DrawLooper_h
-
-#include "wtf/Noncopyable.h"
-#include "wtf/RefPtr.h"
-
-class SkDrawLooper;
-class SkLayerDrawLooper;
-
-namespace WebCore {
-
-class Color;
-class FloatSize;
-
-class DrawLooper {
-    // Implementing the copy constructor properly would require writing code to
-    // copy the underlying SkDrawLooper.
-    WTF_MAKE_NONCOPYABLE(DrawLooper);
-
-public:
-    enum ShadowTransformMode {
-        ShadowRespectsTransforms,
-        ShadowIgnoresTransforms
-    };
-    enum ShadowAlphaMode {
-        ShadowRespectsAlpha,
-        ShadowIgnoresAlpha
-    };
-
-    DrawLooper();
-    ~DrawLooper();
-
-    // Callees should not modify this looper other than to iterate over it.
-    // A downcast to SkLayerDrawLooper* is tantamount to a const_cast.
-    SkDrawLooper* skDrawLooper() const;
-
-    void addUnmodifiedContent();
-    void addShadow(const FloatSize& offset, float blur, const Color&,
-        ShadowTransformMode = ShadowRespectsTransforms,
-        ShadowAlphaMode = ShadowRespectsAlpha);
-
-private:
-    RefPtr<SkLayerDrawLooper> m_skDrawLooper;
-};
-
-} // namespace WebCore
-
-#endif // DrawLooper_h
diff --git a/Source/core/platform/graphics/Extensions3D.h b/Source/core/platform/graphics/Extensions3D.h
index 80704c4..f321258 100644
--- a/Source/core/platform/graphics/Extensions3D.h
+++ b/Source/core/platform/graphics/Extensions3D.h
@@ -26,7 +26,7 @@
 #ifndef Extensions3D_h
 #define Extensions3D_h
 
-#include "core/platform/graphics/GraphicsTypes3D.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/platform/graphics/FloatPolygon.cpp b/Source/core/platform/graphics/FloatPolygon.cpp
deleted file mode 100644
index c455a3e..0000000
--- a/Source/core/platform/graphics/FloatPolygon.cpp
+++ /dev/null
@@ -1,254 +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 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/platform/graphics/FloatPolygon.h"
-
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-static inline float determinant(const FloatSize& a, const FloatSize& b)
-{
-    return a.width() * b.height() - a.height() * b.width();
-}
-
-static inline bool areCollinearPoints(const FloatPoint& p0, const FloatPoint& p1, const FloatPoint& p2)
-{
-    return !determinant(p1 - p0, p2 - p0);
-}
-
-static inline bool areCoincidentPoints(const FloatPoint& p0, const FloatPoint& p1)
-{
-    return p0.x() == p1.x() && p0.y() == p1.y();
-}
-
-static inline bool isPointOnLineSegment(const FloatPoint& vertex1, const FloatPoint& vertex2, const FloatPoint& point)
-{
-    return point.x() >= std::min(vertex1.x(), vertex2.x())
-        && point.x() <= std::max(vertex1.x(), vertex2.x())
-        && areCollinearPoints(vertex1, vertex2, point);
-}
-
-static inline unsigned nextVertexIndex(unsigned vertexIndex, unsigned nVertices, bool clockwise)
-{
-    return ((clockwise) ? vertexIndex + 1 : vertexIndex - 1 + nVertices) % nVertices;
-}
-
-static unsigned findNextEdgeVertexIndex(const FloatPolygon& polygon, unsigned vertexIndex1, bool clockwise)
-{
-    unsigned nVertices = polygon.numberOfVertices();
-    unsigned vertexIndex2 = nextVertexIndex(vertexIndex1, nVertices, clockwise);
-
-    while (vertexIndex2 && areCoincidentPoints(polygon.vertexAt(vertexIndex1), polygon.vertexAt(vertexIndex2)))
-        vertexIndex2 = nextVertexIndex(vertexIndex2, nVertices, clockwise);
-
-    while (vertexIndex2) {
-        unsigned vertexIndex3 = nextVertexIndex(vertexIndex2, nVertices, clockwise);
-        if (!areCollinearPoints(polygon.vertexAt(vertexIndex1), polygon.vertexAt(vertexIndex2), polygon.vertexAt(vertexIndex3)))
-            break;
-        vertexIndex2 = vertexIndex3;
-    }
-
-    return vertexIndex2;
-}
-
-FloatPolygon::FloatPolygon(PassOwnPtr<Vector<FloatPoint> > vertices, WindRule fillRule)
-    : m_vertices(vertices)
-    , m_fillRule(fillRule)
-{
-    unsigned nVertices = numberOfVertices();
-    m_edges.resize(nVertices);
-    m_empty = nVertices < 3;
-
-    if (nVertices)
-        m_boundingBox.setLocation(vertexAt(0));
-
-    if (m_empty)
-        return;
-
-    unsigned minVertexIndex = 0;
-    for (unsigned i = 1; i < nVertices; ++i) {
-        const FloatPoint& vertex = vertexAt(i);
-        if (vertex.y() < vertexAt(minVertexIndex).y() || (vertex.y() == vertexAt(minVertexIndex).y() && vertex.x() < vertexAt(minVertexIndex).x()))
-            minVertexIndex = i;
-    }
-    FloatPoint nextVertex = vertexAt((minVertexIndex + 1) % nVertices);
-    FloatPoint prevVertex = vertexAt((minVertexIndex + nVertices - 1) % nVertices);
-    bool clockwise = determinant(vertexAt(minVertexIndex) - prevVertex, nextVertex - prevVertex) > 0;
-
-    unsigned edgeIndex = 0;
-    unsigned vertexIndex1 = 0;
-    do {
-        m_boundingBox.extend(vertexAt(vertexIndex1));
-        unsigned vertexIndex2 = findNextEdgeVertexIndex(*this, vertexIndex1, clockwise);
-        m_edges[edgeIndex].m_polygon = this;
-        m_edges[edgeIndex].m_vertexIndex1 = vertexIndex1;
-        m_edges[edgeIndex].m_vertexIndex2 = vertexIndex2;
-        m_edges[edgeIndex].m_edgeIndex = edgeIndex;
-        ++edgeIndex;
-        vertexIndex1 = vertexIndex2;
-    } while (vertexIndex1);
-
-    if (edgeIndex > 3) {
-        const FloatPolygonEdge& firstEdge = m_edges[0];
-        const FloatPolygonEdge& lastEdge = m_edges[edgeIndex - 1];
-        if (areCollinearPoints(lastEdge.vertex1(), lastEdge.vertex2(), firstEdge.vertex2())) {
-            m_edges[0].m_vertexIndex1 = lastEdge.m_vertexIndex1;
-            edgeIndex--;
-        }
-    }
-
-    m_edges.resize(edgeIndex);
-    m_empty = m_edges.size() < 3;
-
-    if (m_empty)
-        return;
-
-    for (unsigned i = 0; i < m_edges.size(); ++i) {
-        FloatPolygonEdge* edge = &m_edges[i];
-        m_edgeTree.add(EdgeInterval(edge->minY(), edge->maxY(), edge));
-    }
-}
-
-bool FloatPolygon::overlappingEdges(float minY, float maxY, Vector<const FloatPolygonEdge*>& result) const
-{
-    Vector<FloatPolygon::EdgeInterval> overlappingEdgeIntervals;
-    m_edgeTree.allOverlaps(FloatPolygon::EdgeInterval(minY, maxY, 0), overlappingEdgeIntervals);
-    unsigned overlappingEdgeIntervalsSize = overlappingEdgeIntervals.size();
-    result.resize(overlappingEdgeIntervalsSize);
-    for (unsigned i = 0; i < overlappingEdgeIntervalsSize; ++i) {
-        const FloatPolygonEdge* edge = static_cast<const FloatPolygonEdge*>(overlappingEdgeIntervals[i].data());
-        ASSERT(edge);
-        result[i] = edge;
-    }
-    return overlappingEdgeIntervalsSize > 0;
-}
-
-static inline float leftSide(const FloatPoint& vertex1, const FloatPoint& vertex2, const FloatPoint& point)
-{
-    return ((point.x() - vertex1.x()) * (vertex2.y() - vertex1.y())) - ((vertex2.x() - vertex1.x()) * (point.y() - vertex1.y()));
-}
-
-bool FloatPolygon::containsEvenOdd(const FloatPoint& point) const
-{
-    unsigned crossingCount = 0;
-    for (unsigned i = 0; i < numberOfEdges(); ++i) {
-        const FloatPoint& vertex1 = edgeAt(i).vertex1();
-        const FloatPoint& vertex2 = edgeAt(i).vertex2();
-        if (isPointOnLineSegment(vertex1, vertex2, point))
-            return true;
-        if ((vertex1.y() <= point.y() && vertex2.y() > point.y()) || (vertex1.y() > point.y() && vertex2.y() <= point.y())) {
-            float vt = (point.y()  - vertex1.y()) / (vertex2.y() - vertex1.y());
-            if (point.x() < vertex1.x() + vt * (vertex2.x() - vertex1.x()))
-                ++crossingCount;
-        }
-    }
-    return crossingCount & 1;
-}
-
-bool FloatPolygon::containsNonZero(const FloatPoint& point) const
-{
-    int windingNumber = 0;
-    for (unsigned i = 0; i < numberOfEdges(); ++i) {
-        const FloatPoint& vertex1 = edgeAt(i).vertex1();
-        const FloatPoint& vertex2 = edgeAt(i).vertex2();
-        if (isPointOnLineSegment(vertex1, vertex2, point))
-            return true;
-        if (vertex2.y() < point.y()) {
-            if ((vertex1.y() > point.y()) && (leftSide(vertex1, vertex2, point) > 0))
-                ++windingNumber;
-        } else if (vertex2.y() > point.y()) {
-            if ((vertex1.y() <= point.y()) && (leftSide(vertex1, vertex2, point) < 0))
-                --windingNumber;
-        }
-    }
-    return windingNumber;
-}
-
-bool FloatPolygon::contains(const FloatPoint& point) const
-{
-    if (!m_boundingBox.contains(point))
-        return false;
-    return (fillRule() == RULE_NONZERO) ? containsNonZero(point) : containsEvenOdd(point);
-}
-
-bool VertexPair::overlapsRect(const FloatRect& rect) const
-{
-    bool boundsOverlap = (minX() < rect.maxX()) && (maxX() > rect.x()) && (minY() < rect.maxY()) && (maxY() > rect.y());
-    if (!boundsOverlap)
-        return false;
-
-    float leftSideValues[4] = {
-        leftSide(vertex1(), vertex2(), rect.minXMinYCorner()),
-        leftSide(vertex1(), vertex2(), rect.maxXMinYCorner()),
-        leftSide(vertex1(), vertex2(), rect.minXMaxYCorner()),
-        leftSide(vertex1(), vertex2(), rect.maxXMaxYCorner())
-    };
-
-    int currentLeftSideSign = 0;
-    for (unsigned i = 0; i < 4; ++i) {
-        if (!leftSideValues[i])
-            continue;
-        int leftSideSign = leftSideValues[i] > 0 ? 1 : -1;
-        if (!currentLeftSideSign)
-            currentLeftSideSign = leftSideSign;
-        else if (currentLeftSideSign != leftSideSign)
-            return true;
-    }
-
-    return false;
-}
-
-bool VertexPair::intersection(const VertexPair& other, FloatPoint& point) const
-{
-    // See: http://paulbourke.net/geometry/pointlineplane/, "Intersection point of two lines in 2 dimensions"
-
-    const FloatSize& thisDelta = vertex2() - vertex1();
-    const FloatSize& otherDelta = other.vertex2() - other.vertex1();
-    float denominator = determinant(thisDelta, otherDelta);
-    if (!denominator)
-        return false;
-
-    // The two line segments: "this" vertex1,vertex2 and "other" vertex1,vertex2, have been defined
-    // in parametric form. Each point on the line segment is: vertex1 + u * (vertex2 - vertex1),
-    // when 0 <= u <= 1. We're computing the values of u for each line at their intersection point.
-
-    const FloatSize& vertex1Delta = vertex1() - other.vertex1();
-    float uThisLine = determinant(otherDelta, vertex1Delta) / denominator;
-    float uOtherLine = determinant(thisDelta, vertex1Delta) / denominator;
-
-    if (uThisLine < 0 || uOtherLine < 0 || uThisLine > 1 || uOtherLine > 1)
-        return false;
-
-    point = vertex1() + uThisLine * thisDelta;
-    return true;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/FloatPolygon.h b/Source/core/platform/graphics/FloatPolygon.h
deleted file mode 100644
index acf033f..0000000
--- a/Source/core/platform/graphics/FloatPolygon.h
+++ /dev/null
@@ -1,153 +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 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 FloatPolygon_h
-#define FloatPolygon_h
-
-#include "core/platform/graphics/WindRule.h"
-#include "platform/PODIntervalTree.h"
-#include "platform/geometry/FloatPoint.h"
-#include "platform/geometry/FloatRect.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class FloatPolygonEdge;
-
-// This class is used by PODIntervalTree for debugging.
-#ifndef NDEBUG
-template <class> struct ValueToString;
-#endif
-
-class FloatPolygon {
-public:
-    FloatPolygon(PassOwnPtr<Vector<FloatPoint> > vertices, WindRule fillRule);
-
-    const FloatPoint& vertexAt(unsigned index) const { return (*m_vertices)[index]; }
-    unsigned numberOfVertices() const { return m_vertices->size(); }
-
-    WindRule fillRule() const { return m_fillRule; }
-
-    const FloatPolygonEdge& edgeAt(unsigned index) const { return m_edges[index]; }
-    unsigned numberOfEdges() const { return m_edges.size(); }
-
-    FloatRect boundingBox() const { return m_boundingBox; }
-    bool overlappingEdges(float minY, float maxY, Vector<const FloatPolygonEdge*>& result) const;
-    bool contains(const FloatPoint&) const;
-    bool isEmpty() const { return m_empty; }
-
-private:
-    typedef PODInterval<float, FloatPolygonEdge*> EdgeInterval;
-    typedef PODIntervalTree<float, FloatPolygonEdge*> EdgeIntervalTree;
-
-    bool containsNonZero(const FloatPoint&) const;
-    bool containsEvenOdd(const FloatPoint&) const;
-
-    OwnPtr<Vector<FloatPoint> > m_vertices;
-    WindRule m_fillRule;
-    FloatRect m_boundingBox;
-    bool m_empty;
-    Vector<FloatPolygonEdge> m_edges;
-    EdgeIntervalTree m_edgeTree; // Each EdgeIntervalTree node stores minY, maxY, and a ("UserData") pointer to a FloatPolygonEdge.
-
-};
-
-class VertexPair {
-public:
-    virtual ~VertexPair() { }
-
-    virtual const FloatPoint& vertex1() const = 0;
-    virtual const FloatPoint& vertex2() const = 0;
-
-    float minX() const { return std::min(vertex1().x(), vertex2().x()); }
-    float minY() const { return std::min(vertex1().y(), vertex2().y()); }
-    float maxX() const { return std::max(vertex1().x(), vertex2().x()); }
-    float maxY() const { return std::max(vertex1().y(), vertex2().y()); }
-
-    bool overlapsRect(const FloatRect&) const;
-    bool intersection(const VertexPair&, FloatPoint&) const;
-};
-
-class FloatPolygonEdge : public VertexPair {
-    friend class FloatPolygon;
-public:
-    virtual const FloatPoint& vertex1() const OVERRIDE
-    {
-        ASSERT(m_polygon);
-        return m_polygon->vertexAt(m_vertexIndex1);
-    }
-
-    virtual const FloatPoint& vertex2() const OVERRIDE
-    {
-        ASSERT(m_polygon);
-        return m_polygon->vertexAt(m_vertexIndex2);
-    }
-
-    const FloatPolygonEdge& previousEdge() const
-    {
-        ASSERT(m_polygon && m_polygon->numberOfEdges() > 1);
-        return m_polygon->edgeAt((m_edgeIndex + m_polygon->numberOfEdges() - 1) % m_polygon->numberOfEdges());
-    }
-
-    const FloatPolygonEdge& nextEdge() const
-    {
-        ASSERT(m_polygon && m_polygon->numberOfEdges() > 1);
-        return m_polygon->edgeAt((m_edgeIndex + 1) % m_polygon->numberOfEdges());
-    }
-
-    const FloatPolygon* polygon() const { return m_polygon; }
-    unsigned vertexIndex1() const { return m_vertexIndex1; }
-    unsigned vertexIndex2() const { return m_vertexIndex2; }
-    unsigned edgeIndex() const { return m_edgeIndex; }
-
-private:
-    // Edge vertex index1 is less than index2, except the last edge, where index2 is 0. When a polygon edge
-    // is defined by 3 or more colinear vertices, index2 can be the the index of the last colinear vertex.
-    unsigned m_vertexIndex1;
-    unsigned m_vertexIndex2;
-    unsigned m_edgeIndex;
-    const FloatPolygon* m_polygon;
-};
-
-// These structures are used by PODIntervalTree for debugging.
-#ifndef NDEBUG
-template <> struct ValueToString<float> {
-    static String string(const float value) { return String::number(value); }
-};
-
-template<> struct ValueToString<FloatPolygonEdge*> {
-    static String string(const FloatPolygonEdge* edge) { return String::format("%p (%f,%f %f,%f)", edge, edge->vertex1().x(), edge->vertex1().y(), edge->vertex2().x(), edge->vertex2().y()); }
-};
-#endif
-
-} // namespace WebCore
-
-#endif // FloatPolygon_h
diff --git a/Source/core/platform/graphics/Font.cpp b/Source/core/platform/graphics/Font.cpp
index e0cb2e1..3ba67d9 100644
--- a/Source/core/platform/graphics/Font.cpp
+++ b/Source/core/platform/graphics/Font.cpp
@@ -381,7 +381,7 @@
 
 Font::CodePath Font::characterRangeCodePath(const UChar* characters, unsigned len)
 {
-    static UChar complexCodePathRanges[] = {
+    static const UChar complexCodePathRanges[] = {
         // U+02E5 through U+02E9 (Modifier Letters : Tone letters)
         0x2E5, 0x2E9,
         // U+0300 through U+036F Combining diacritical marks
@@ -496,7 +496,7 @@
 
 bool Font::isCJKIdeograph(UChar32 c)
 {
-    static UChar32 cjkIdeographRanges[] = {
+    static const UChar32 cjkIdeographRanges[] = {
         // CJK Radicals Supplement and Kangxi Radicals.
         0x2E80, 0x2FDF,
         // CJK Strokes.
@@ -551,7 +551,7 @@
     if (isCJKIdeograph(c))
         return true;
 
-    static UChar32 cjkSymbolRanges[] = {
+    static const UChar32 cjkSymbolRanges[] = {
         0x2156, 0x215A,
         0x2160, 0x216B,
         0x2170, 0x217B,
diff --git a/Source/core/platform/graphics/Font.h b/Source/core/platform/graphics/Font.h
index 1b08ec3..f353f81 100644
--- a/Source/core/platform/graphics/Font.h
+++ b/Source/core/platform/graphics/Font.h
@@ -25,10 +25,10 @@
 #ifndef Font_h
 #define Font_h
 
-#include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/FontFallbackList.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/TypesettingFeatures.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/fonts/TypesettingFeatures.h"
 #include "platform/text/TextDirection.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
diff --git a/Source/core/platform/graphics/FontCache.cpp b/Source/core/platform/graphics/FontCache.cpp
index f5529f0..9f7e722 100644
--- a/Source/core/platform/graphics/FontCache.cpp
+++ b/Source/core/platform/graphics/FontCache.cpp
@@ -35,14 +35,14 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/platform/graphics/AlternateFontFamily.h"
 #include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontCacheKey.h"
-#include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/FontFallbackList.h"
 #include "core/platform/graphics/FontPlatformData.h"
-#include "core/platform/graphics/FontSelector.h"
-#include "core/platform/graphics/FontSmoothingMode.h"
-#include "core/platform/graphics/TextRenderingMode.h"
 #include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
+#include "platform/fonts/FontCacheKey.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/fonts/FontSelector.h"
+#include "platform/fonts/FontSmoothingMode.h"
+#include "platform/fonts/TextRenderingMode.h"
 #include "wtf/HashMap.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/StdLibExtras.h"
@@ -395,7 +395,7 @@
 
         if (fontSelector) {
             // Try the user's preferred standard font.
-            if (RefPtr<FontData> data = fontSelector->getFontData(font.fontDescription(), standardFamily))
+            if (RefPtr<FontData> data = fontSelector->getFontData(font.fontDescription(), FontFamilyNames::webkit_standard))
                 return data.release();
         }
 
diff --git a/Source/core/platform/graphics/FontCache.h b/Source/core/platform/graphics/FontCache.h
index 4f7cacd..30516f4 100644
--- a/Source/core/platform/graphics/FontCache.h
+++ b/Source/core/platform/graphics/FontCache.h
@@ -117,10 +117,6 @@
     static void getFontFamilyForCharacter(UChar32, const char* preferredLocale, SimpleFontFamily*);
 #endif
 
-    // Multiplying the floating point size by 100 gives two decimal
-    // point precision which should be sufficient.
-    static const unsigned s_fontSizePrecisionMultiplier = 100;
-
 private:
     FontCache();
     ~FontCache();
diff --git a/Source/core/platform/graphics/FontCacheKey.h b/Source/core/platform/graphics/FontCacheKey.h
deleted file mode 100644
index 186eb0a..0000000
--- a/Source/core/platform/graphics/FontCacheKey.h
+++ /dev/null
@@ -1,115 +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.
- */
-
-#ifndef FontCacheKey_h
-#define FontCacheKey_h
-
-#include "wtf/HashMap.h"
-#include "wtf/HashTableDeletedValueType.h"
-#include "wtf/text/AtomicStringHash.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-// Multiplying the floating point size by 100 gives two decimal point
-// precision which should be sufficient.
-static const unsigned s_fontSizePrecisionMultiplier = 100;
-
-struct FontCacheKey {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    FontCacheKey()
-        : m_familyName()
-        , m_fontSize(0)
-        , m_options(0) { }
-    FontCacheKey(AtomicString familyName, float fontSize, unsigned options)
-        : m_familyName(familyName)
-        , m_fontSize(fontSize * s_fontSizePrecisionMultiplier)
-        , m_options(options) { }
-    FontCacheKey(WTF::HashTableDeletedValueType)
-        : m_fontSize(hashTableDeletedSize()) { }
-
-    void setSynthetic(bool bold, bool  italic)
-    {
-        m_options |= (bold ? 1 << 6 : 0) | (italic ? 1 << 7 : 0);
-    }
-
-    unsigned hash() const
-    {
-        unsigned hashCodes[3] = {
-            CaseFoldingHash::hash(m_familyName),
-            m_fontSize,
-            m_options
-        };
-        return StringHasher::hashMemory<sizeof(hashCodes)>(hashCodes);
-    }
-
-    bool operator==(const FontCacheKey& other) const
-    {
-        return equalIgnoringCase(m_familyName, other.m_familyName)
-            && m_fontSize == other.m_fontSize
-            && m_options == other.m_options;
-    }
-
-    bool isHashTableDeletedValue() const
-    {
-        return m_fontSize == hashTableDeletedSize();
-    }
-
-private:
-    static unsigned hashTableDeletedSize()
-    {
-        return 0xFFFFFFFFU;
-    }
-
-    AtomicString m_familyName;
-    unsigned m_fontSize;
-    unsigned m_options;
-};
-
-struct FontCacheKeyHash {
-    static unsigned hash(const FontCacheKey& key)
-    {
-        return key.hash();
-    }
-
-    static bool equal(const FontCacheKey& a, const FontCacheKey& b)
-    {
-        return a == b;
-    }
-
-    static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-struct FontCacheKeyTraits : WTF::SimpleClassHashTraits<FontCacheKey> { };
-
-}
-
-#endif // FontCacheKey_h
diff --git a/Source/core/platform/graphics/FontCustomPlatformData.h b/Source/core/platform/graphics/FontCustomPlatformData.h
index 7a040e4..175709f 100644
--- a/Source/core/platform/graphics/FontCustomPlatformData.h
+++ b/Source/core/platform/graphics/FontCustomPlatformData.h
@@ -32,8 +32,8 @@
 #ifndef FontCustomPlatformData_h
 #define FontCustomPlatformData_h
 
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/FontWidthVariant.h"
+#include "platform/fonts/FontOrientation.h"
+#include "platform/fonts/FontWidthVariant.h"
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/platform/graphics/FontDescription.cpp b/Source/core/platform/graphics/FontDescription.cpp
deleted file mode 100644
index 03ca701..0000000
--- a/Source/core/platform/graphics/FontDescription.cpp
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2007 Nicholas Shanks <contact@nickshanks.com>
- * 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.
- * 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/platform/graphics/FontDescription.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "wtf/text/AtomicStringHash.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-struct SameSizeAsFontDescription {
-    FontFamily familyList;
-    RefPtr<FontFeatureSettings> m_featureSettings;
-    float sizes[2];
-    // FXIME: Make them fit into one word.
-    uint32_t bitfields;
-    uint32_t bitfields2 : 8;
-};
-
-COMPILE_ASSERT(sizeof(FontDescription) == sizeof(SameSizeAsFontDescription), FontDescription_should_stay_small);
-
-FontWeight FontDescription::lighterWeight(void) const
-{
-    switch (m_weight) {
-        case FontWeight100:
-        case FontWeight200:
-        case FontWeight300:
-        case FontWeight400:
-        case FontWeight500:
-            return FontWeight100;
-
-        case FontWeight600:
-        case FontWeight700:
-            return FontWeight400;
-
-        case FontWeight800:
-        case FontWeight900:
-            return FontWeight700;
-    }
-    ASSERT_NOT_REACHED();
-    return FontWeightNormal;
-}
-
-FontWeight FontDescription::bolderWeight(void) const
-{
-    switch (m_weight) {
-        case FontWeight100:
-        case FontWeight200:
-        case FontWeight300:
-            return FontWeight400;
-
-        case FontWeight400:
-        case FontWeight500:
-            return FontWeight700;
-
-        case FontWeight600:
-        case FontWeight700:
-        case FontWeight800:
-        case FontWeight900:
-            return FontWeight900;
-    }
-    ASSERT_NOT_REACHED();
-    return FontWeightNormal;
-}
-
-FontTraitsMask FontDescription::traitsMask() const
-{
-    return static_cast<FontTraitsMask>((m_italic ? FontStyleItalicMask : FontStyleNormalMask)
-            | (m_smallCaps ? FontVariantSmallCapsMask : FontVariantNormalMask)
-            | (FontWeight100Mask << (m_weight - FontWeight100)));
-
-}
-
-FontDescription FontDescription::makeNormalFeatureSettings() const
-{
-    FontDescription normalDescription(*this);
-    normalDescription.setFeatureSettings(0);
-    return normalDescription;
-}
-
-float FontDescription::effectiveFontSize() const
-{
-    return (RuntimeEnabledFeatures::subpixelFontScalingEnabled())
-        ? computedSize()
-        : computedPixelSize();
-}
-
-FontCacheKey FontDescription::cacheKey(const AtomicString& familyName, FontTraitsMask desiredTraits) const
-{
-    FontTraitsMask traits = desiredTraits
-        ? desiredTraits
-        : traitsMask();
-
-    unsigned options =
-        // synthetic bold, italics - bits 7-8
-        static_cast<unsigned>(m_fontSmoothing) << 4 | // bits 5-6
-        static_cast<unsigned>(m_textRendering) << 2 | // bits 3-4
-        static_cast<unsigned>(m_orientation) << 1 | // bit 2
-        static_cast<unsigned>(m_usePrinterFont); // bit 1
-
-    return FontCacheKey(familyName, effectiveFontSize(), options | traits << 8);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/FontDescription.h b/Source/core/platform/graphics/FontDescription.h
deleted file mode 100644
index 8e58b45..0000000
--- a/Source/core/platform/graphics/FontDescription.h
+++ /dev/null
@@ -1,235 +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, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.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.LIother.m_  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USm_
- *
- */
-
-#ifndef FontDescription_h
-#define FontDescription_h
-
-#include "FontFamilyNames.h"
-#include "core/platform/graphics/FontCacheKey.h"
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/FontSmoothingMode.h"
-#include "core/platform/graphics/FontTraitsMask.h"
-#include "core/platform/graphics/FontWidthVariant.h"
-#include "core/platform/graphics/TextRenderingMode.h"
-#include "platform/fonts/FontFamily.h"
-#include "platform/fonts/FontFeatureSettings.h"
-#include "platform/text/NonCJKGlyphOrientation.h"
-#include "wtf/MathExtras.h"
-
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-using namespace FontFamilyNames;
-
-enum FontWeight {
-    FontWeight100,
-    FontWeight200,
-    FontWeight300,
-    FontWeight400,
-    FontWeight500,
-    FontWeight600,
-    FontWeight700,
-    FontWeight800,
-    FontWeight900,
-    FontWeightNormal = FontWeight400,
-    FontWeightBold = FontWeight700
-};
-
-enum FontItalic {
-    FontItalicOff = 0,
-    FontItalicOn = 1
-};
-
-enum FontSmallCaps {
-    FontSmallCapsOff = 0,
-    FontSmallCapsOn = 1
-};
-
-class FontDescription {
-public:
-    enum GenericFamilyType { NoFamily, StandardFamily, SerifFamily, SansSerifFamily,
-                             MonospaceFamily, CursiveFamily, FantasyFamily, PictographFamily };
-
-    enum Kerning { AutoKerning, NormalKerning, NoneKerning };
-
-    enum LigaturesState { NormalLigaturesState, DisabledLigaturesState, EnabledLigaturesState };
-
-    FontDescription()
-        : m_specifiedSize(0)
-        , m_computedSize(0)
-        , m_orientation(Horizontal)
-        , m_nonCJKGlyphOrientation(NonCJKGlyphOrientationVerticalRight)
-        , m_widthVariant(RegularWidth)
-        , m_italic(FontItalicOff)
-        , m_smallCaps(FontSmallCapsOff)
-        , m_isAbsoluteSize(false)
-        , m_weight(FontWeightNormal)
-        , m_genericFamily(NoFamily)
-        , m_usePrinterFont(false)
-        , m_kerning(AutoKerning)
-        , m_commonLigaturesState(NormalLigaturesState)
-        , m_discretionaryLigaturesState(NormalLigaturesState)
-        , m_historicalLigaturesState(NormalLigaturesState)
-        , m_keywordSize(0)
-        , m_fontSmoothing(AutoSmoothing)
-        , m_textRendering(AutoTextRendering)
-        , m_isSpecifiedFont(false)
-        , m_script(USCRIPT_COMMON)
-    {
-    }
-
-    bool operator==(const FontDescription&) const;
-    bool operator!=(const FontDescription& other) const { return !(*this == other); }
-
-    const FontFamily& family() const { return m_familyList; }
-    FontFamily& firstFamily() { return m_familyList; }
-    float specifiedSize() const { return m_specifiedSize; }
-    float computedSize() const { return m_computedSize; }
-    FontItalic italic() const { return static_cast<FontItalic>(m_italic); }
-    int computedPixelSize() const { return int(m_computedSize + 0.5f); }
-    FontSmallCaps smallCaps() const { return static_cast<FontSmallCaps>(m_smallCaps); }
-    bool isAbsoluteSize() const { return m_isAbsoluteSize; }
-    FontWeight weight() const { return static_cast<FontWeight>(m_weight); }
-    FontWeight lighterWeight() const;
-    FontWeight bolderWeight() const;
-    GenericFamilyType genericFamily() const { return static_cast<GenericFamilyType>(m_genericFamily); }
-    bool usePrinterFont() const { return m_usePrinterFont; }
-    // only use fixed default size when there is only one font family, and that family is "monospace"
-    bool useFixedDefaultSize() const { return genericFamily() == MonospaceFamily && !family().next() && family().family() == monospaceFamily; }
-    Kerning kerning() const { return static_cast<Kerning>(m_kerning); }
-    LigaturesState commonLigaturesState() const { return static_cast<LigaturesState>(m_commonLigaturesState); }
-    LigaturesState discretionaryLigaturesState() const { return static_cast<LigaturesState>(m_discretionaryLigaturesState); }
-    LigaturesState historicalLigaturesState() const { return static_cast<LigaturesState>(m_historicalLigaturesState); }
-    unsigned keywordSize() const { return m_keywordSize; }
-    FontSmoothingMode fontSmoothing() const { return static_cast<FontSmoothingMode>(m_fontSmoothing); }
-    TextRenderingMode textRenderingMode() const { return static_cast<TextRenderingMode>(m_textRendering); }
-    UScriptCode script() const { return static_cast<UScriptCode>(m_script); }
-
-    FontTraitsMask traitsMask() const;
-    bool isSpecifiedFont() const { return m_isSpecifiedFont; }
-    FontOrientation orientation() const { return static_cast<FontOrientation>(m_orientation); }
-    NonCJKGlyphOrientation nonCJKGlyphOrientation() const { return static_cast<NonCJKGlyphOrientation>(m_nonCJKGlyphOrientation); }
-    FontWidthVariant widthVariant() const { return static_cast<FontWidthVariant>(m_widthVariant); }
-    FontFeatureSettings* featureSettings() const { return m_featureSettings.get(); }
-    FontDescription makeNormalFeatureSettings() const;
-
-    float effectiveFontSize() const; // Returns either the computedSize or the computedPixelSize
-    FontCacheKey cacheKey(const AtomicString& familyName, FontTraitsMask desiredTraits = static_cast<FontTraitsMask>(0)) const;
-
-    void setFamily(const FontFamily& family) { m_familyList = family; }
-    void setComputedSize(float s) { m_computedSize = clampToFloat(s); }
-    void setSpecifiedSize(float s) { m_specifiedSize = clampToFloat(s); }
-    void setItalic(FontItalic i) { m_italic = i; }
-    void setItalic(bool i) { setItalic(i ? FontItalicOn : FontItalicOff); }
-    void setSmallCaps(FontSmallCaps c) { m_smallCaps = c; }
-    void setSmallCaps(bool c) { setSmallCaps(c ? FontSmallCapsOn : FontSmallCapsOff); }
-    void setIsAbsoluteSize(bool s) { m_isAbsoluteSize = s; }
-    void setWeight(FontWeight w) { m_weight = w; }
-    void setGenericFamily(GenericFamilyType genericFamily) { m_genericFamily = genericFamily; }
-#if OS(MACOSX)
-    void setUsePrinterFont(bool) { }
-#else
-    void setUsePrinterFont(bool p) { m_usePrinterFont = p; }
-#endif
-    void setKerning(Kerning kerning) { m_kerning = kerning; }
-    void setCommonLigaturesState(LigaturesState commonLigaturesState) { m_commonLigaturesState = commonLigaturesState; }
-    void setDiscretionaryLigaturesState(LigaturesState discretionaryLigaturesState) { m_discretionaryLigaturesState = discretionaryLigaturesState; }
-    void setHistoricalLigaturesState(LigaturesState historicalLigaturesState) { m_historicalLigaturesState = historicalLigaturesState; }
-    void setKeywordSize(unsigned s) { m_keywordSize = s; }
-    void setFontSmoothing(FontSmoothingMode smoothing) { m_fontSmoothing = smoothing; }
-    void setTextRenderingMode(TextRenderingMode rendering) { m_textRendering = rendering; }
-    void setIsSpecifiedFont(bool isSpecifiedFont) { m_isSpecifiedFont = isSpecifiedFont; }
-    void setOrientation(FontOrientation orientation) { m_orientation = orientation; }
-    void setNonCJKGlyphOrientation(NonCJKGlyphOrientation orientation) { m_nonCJKGlyphOrientation = orientation; }
-    void setWidthVariant(FontWidthVariant widthVariant) { m_widthVariant = widthVariant; }
-    void setScript(UScriptCode s) { m_script = s; }
-    void setFeatureSettings(PassRefPtr<FontFeatureSettings> settings) { m_featureSettings = settings; }
-
-private:
-    FontFamily m_familyList; // The list of font families to be used.
-    RefPtr<FontFeatureSettings> m_featureSettings;
-
-    float m_specifiedSize;   // Specified CSS value. Independent of rendering issues such as integer
-                             // rounding, minimum font sizes, and zooming.
-    float m_computedSize;    // Computed size adjusted for the minimum font size and the zoom factor.
-
-    unsigned m_orientation : 1; // FontOrientation - Whether the font is rendering on a horizontal line or a vertical line.
-    unsigned m_nonCJKGlyphOrientation : 1; // NonCJKGlyphOrientation - Only used by vertical text. Determines the default orientation for non-ideograph glyphs.
-
-    unsigned m_widthVariant : 2; // FontWidthVariant
-
-    unsigned m_italic : 1; // FontItalic
-    unsigned m_smallCaps : 1; // FontSmallCaps
-    unsigned m_isAbsoluteSize : 1; // Whether or not CSS specified an explicit size
-                                  // (logical sizes like "medium" don't count).
-    unsigned m_weight : 8; // FontWeight
-    unsigned m_genericFamily : 3; // GenericFamilyType
-    unsigned m_usePrinterFont : 1;
-
-    unsigned m_kerning : 2; // Kerning
-
-    unsigned m_commonLigaturesState : 2;
-    unsigned m_discretionaryLigaturesState : 2;
-    unsigned m_historicalLigaturesState : 2;
-
-    unsigned m_keywordSize : 4; // We cache whether or not a font is currently represented by a CSS keyword (e.g., medium).  If so,
-                           // then we can accurately translate across different generic families to adjust for different preference settings
-                           // (e.g., 13px monospace vs. 16px everything else).  Sizes are 1-8 (like the HTML size values for <font>).
-
-    unsigned m_fontSmoothing : 2; // FontSmoothingMode
-    unsigned m_textRendering : 2; // TextRenderingMode
-    unsigned m_isSpecifiedFont : 1; // True if a web page specifies a non-generic font family as the first font family.
-    unsigned m_script : 7; // Used to help choose an appropriate font for generic font families.
-};
-
-inline bool FontDescription::operator==(const FontDescription& other) const
-{
-    return m_familyList == other.m_familyList
-        && m_specifiedSize == other.m_specifiedSize
-        && m_computedSize == other.m_computedSize
-        && m_italic == other.m_italic
-        && m_smallCaps == other.m_smallCaps
-        && m_isAbsoluteSize == other.m_isAbsoluteSize
-        && m_weight == other.m_weight
-        && m_genericFamily == other.m_genericFamily
-        && m_usePrinterFont == other.m_usePrinterFont
-        && m_kerning == other.m_kerning
-        && m_commonLigaturesState == other.m_commonLigaturesState
-        && m_discretionaryLigaturesState == other.m_discretionaryLigaturesState
-        && m_historicalLigaturesState == other.m_historicalLigaturesState
-        && m_keywordSize == other.m_keywordSize
-        && m_fontSmoothing == other.m_fontSmoothing
-        && m_textRendering == other.m_textRendering
-        && m_isSpecifiedFont == other.m_isSpecifiedFont
-        && m_orientation == other.m_orientation
-        && m_nonCJKGlyphOrientation == other.m_nonCJKGlyphOrientation
-        && m_widthVariant == other.m_widthVariant
-        && m_script == other.m_script
-        && m_featureSettings == other.m_featureSettings;
-}
-
-}
-
-#endif
diff --git a/Source/core/platform/graphics/FontFallbackList.cpp b/Source/core/platform/graphics/FontFallbackList.cpp
index 9152bf8..229f6ee 100644
--- a/Source/core/platform/graphics/FontFallbackList.cpp
+++ b/Source/core/platform/graphics/FontFallbackList.cpp
@@ -81,7 +81,7 @@
     else {
         const SegmentedFontData* segmentedFontData = static_cast<const SegmentedFontData*>(fontData);
         unsigned numRanges = segmentedFontData->numRanges();
-        if (numRanges == 1)
+        if (numRanges == 1 && segmentedFontData->rangeAt(0).isEntireRange())
             m_pitch = segmentedFontData->rangeAt(0).fontData()->pitch();
         else
             m_pitch = VariablePitch;
diff --git a/Source/core/platform/graphics/FontFallbackList.h b/Source/core/platform/graphics/FontFallbackList.h
index 9f4a4d3..8bda9d5 100644
--- a/Source/core/platform/graphics/FontFallbackList.h
+++ b/Source/core/platform/graphics/FontFallbackList.h
@@ -21,9 +21,9 @@
 #ifndef FontFallbackList_h
 #define FontFallbackList_h
 
-#include "core/platform/graphics/FontSelector.h"
 #include "core/platform/graphics/SimpleFontData.h"
 #include "core/platform/graphics/WidthCache.h"
+#include "platform/fonts/FontSelector.h"
 #include "wtf/Forward.h"
 #include "wtf/MainThread.h"
 
diff --git a/Source/core/platform/graphics/FontMetrics.h b/Source/core/platform/graphics/FontMetrics.h
deleted file mode 100644
index dbf1636..0000000
--- a/Source/core/platform/graphics/FontMetrics.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2010-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.
- */
-
-#ifndef FontMetrics_h
-#define FontMetrics_h
-
-#include "platform/fonts/FontBaseline.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-const unsigned gDefaultUnitsPerEm = 1000;
-
-class FontMetrics {
-public:
-    FontMetrics()
-        : m_unitsPerEm(gDefaultUnitsPerEm)
-        , m_ascent(0)
-        , m_descent(0)
-        , m_lineGap(0)
-        , m_lineSpacing(0)
-        , m_xHeight(0)
-        , m_zeroWidth(0)
-        , m_hasXHeight(false)
-        , m_hasZeroWidth(false)
-    {
-    }
-
-    unsigned unitsPerEm() const { return m_unitsPerEm; }
-    void setUnitsPerEm(unsigned unitsPerEm) { m_unitsPerEm = unitsPerEm; }
-
-    float floatAscent(FontBaseline baselineType = AlphabeticBaseline) const
-    {
-        if (baselineType == AlphabeticBaseline)
-            return m_ascent;
-        return floatHeight() / 2;
-    }
-
-    void setAscent(float ascent) { m_ascent = ascent; }
-
-    float floatDescent(FontBaseline baselineType = AlphabeticBaseline) const
-    {
-        if (baselineType == AlphabeticBaseline)
-            return m_descent;
-        return floatHeight() / 2;
-    }
-
-    void setDescent(float descent) { m_descent = descent; }
-
-    float floatHeight(FontBaseline baselineType = AlphabeticBaseline) const
-    {
-        return floatAscent(baselineType) + floatDescent(baselineType);
-    }
-
-    float floatLineGap() const { return m_lineGap; }
-    void setLineGap(float lineGap) { m_lineGap = lineGap; }
-
-    float floatLineSpacing() const { return m_lineSpacing; }
-    void setLineSpacing(float lineSpacing) { m_lineSpacing = lineSpacing; }
-
-    float xHeight() const { return m_xHeight; }
-    void setXHeight(float xHeight)
-    {
-        m_xHeight = xHeight;
-        m_hasXHeight = true;
-    }
-
-    bool hasXHeight() const { return m_hasXHeight && m_xHeight > 0; }
-    void setHasXHeight(bool hasXHeight) { m_hasXHeight = hasXHeight; }
-
-    // Integer variants of certain metrics, used for HTML rendering.
-    int ascent(FontBaseline baselineType = AlphabeticBaseline) const
-    {
-        if (baselineType == AlphabeticBaseline)
-            return lroundf(m_ascent);
-        return height() - height() / 2;
-    }
-
-    int descent(FontBaseline baselineType = AlphabeticBaseline) const
-    {
-        if (baselineType == AlphabeticBaseline)
-            return lroundf(m_descent);
-        return height() / 2;
-    }
-
-    int height(FontBaseline baselineType = AlphabeticBaseline) const
-    {
-        return ascent(baselineType) + descent(baselineType);
-    }
-
-    int lineGap() const { return lroundf(m_lineGap); }
-    int lineSpacing() const { return lroundf(m_lineSpacing); }
-
-    bool hasIdenticalAscentDescentAndLineGap(const FontMetrics& other) const
-    {
-        return ascent() == other.ascent() && descent() == other.descent() && lineGap() == other.lineGap();
-    }
-
-    float zeroWidth() const { return m_zeroWidth; }
-    void setZeroWidth(float zeroWidth)
-    {
-        m_zeroWidth = zeroWidth;
-        m_hasZeroWidth = true;
-    }
-
-    bool hasZeroWidth() const { return m_hasZeroWidth; }
-    void setHasZeroWidth(bool hasZeroWidth) { m_hasZeroWidth = hasZeroWidth; }
-
-private:
-    friend class SimpleFontData;
-
-    void reset()
-    {
-        m_unitsPerEm = gDefaultUnitsPerEm;
-        m_ascent = 0;
-        m_descent = 0;
-        m_lineGap = 0;
-        m_lineSpacing = 0;
-        m_xHeight = 0;
-        m_hasXHeight = false;
-    }
-
-    unsigned m_unitsPerEm;
-    float m_ascent;
-    float m_descent;
-    float m_lineGap;
-    float m_lineSpacing;
-    float m_xHeight;
-    float m_zeroWidth;
-    bool m_hasXHeight;
-    bool m_hasZeroWidth;
-};
-
-static inline float scaleEmToUnits(float x, unsigned unitsPerEm)
-{
-    return unitsPerEm ? x / unitsPerEm : x;
-}
-
-} // namespace WebCore
-
-#endif // FontMetrics_h
diff --git a/Source/core/platform/graphics/FontOrientation.h b/Source/core/platform/graphics/FontOrientation.h
deleted file mode 100644
index 9239e38..0000000
--- a/Source/core/platform/graphics/FontOrientation.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 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 FontOrientation_h
-#define FontOrientation_h
-
-namespace WebCore {
-
-enum FontOrientation { Horizontal, Vertical };
-
-} // namespace WebCore
-
-#endif // FontOrientation_h
diff --git a/Source/core/platform/graphics/FontPlatformData.h b/Source/core/platform/graphics/FontPlatformData.h
index 5571b23..e05bb03 100644
--- a/Source/core/platform/graphics/FontPlatformData.h
+++ b/Source/core/platform/graphics/FontPlatformData.h
@@ -33,8 +33,8 @@
 #ifndef FontPlatformData_h
 #define FontPlatformData_h
 
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/FontWidthVariant.h"
+#include "platform/fonts/FontOrientation.h"
+#include "platform/fonts/FontWidthVariant.h"
 
 #if OS(MACOSX)
 OBJC_CLASS NSFont;
diff --git a/Source/core/platform/graphics/FontSelector.h b/Source/core/platform/graphics/FontSelector.h
deleted file mode 100644
index 1225ffc..0000000
--- a/Source/core/platform/graphics/FontSelector.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2007, 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.
- */
-
-#ifndef FontSelector_h
-#define FontSelector_h
-
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class FontData;
-class FontDescription;
-class FontSelectorClient;
-
-class FontSelector : public RefCounted<FontSelector> {
-public:
-    virtual ~FontSelector() { }
-    virtual PassRefPtr<FontData> getFontData(const FontDescription&, const AtomicString& familyName) = 0;
-    virtual void willUseFontData(const FontDescription&, const AtomicString& familyName) = 0;
-
-    virtual void fontCacheInvalidated() { }
-
-    virtual void registerForInvalidationCallbacks(FontSelectorClient*) = 0;
-    virtual void unregisterForInvalidationCallbacks(FontSelectorClient*) = 0;
-
-    virtual unsigned version() const = 0;
-};
-
-class FontSelectorClient {
-public:
-    virtual ~FontSelectorClient() { }
-
-    virtual void fontsNeedUpdate(FontSelector*) = 0;
-};
-
-} // namespace WebCore
-
-#endif // FontSelector_h
diff --git a/Source/core/platform/graphics/FontSmoothingMode.h b/Source/core/platform/graphics/FontSmoothingMode.h
deleted file mode 100644
index 90b0c5c..0000000
--- a/Source/core/platform/graphics/FontSmoothingMode.h
+++ /dev/null
@@ -1,35 +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.
- *
- * 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 FontSmoothingMode_h
-#define FontSmoothingMode_h
-
-namespace WebCore {
-
-enum FontSmoothingMode { AutoSmoothing, NoSmoothing, Antialiased, SubpixelAntialiased };
-
-} // namespace WebCore
-
-#endif // FontSmoothingMode_h
diff --git a/Source/core/platform/graphics/FontTraitsMask.h b/Source/core/platform/graphics/FontTraitsMask.h
deleted file mode 100644
index b95d131..0000000
--- a/Source/core/platform/graphics/FontTraitsMask.h
+++ /dev/null
@@ -1,70 +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 FontTraitsMask_h
-#define FontTraitsMask_h
-
-namespace WebCore {
-
-enum {
-    FontStyleNormalBit = 0,
-    FontStyleItalicBit,
-    FontVariantNormalBit,
-    FontVariantSmallCapsBit,
-    FontWeight100Bit,
-    FontWeight200Bit,
-    FontWeight300Bit,
-    FontWeight400Bit,
-    FontWeight500Bit,
-    FontWeight600Bit,
-    FontWeight700Bit,
-    FontWeight800Bit,
-    FontWeight900Bit,
-    FontTraitsMaskWidth
-};
-
-enum FontTraitsMask {
-    FontStyleNormalMask = 1 << FontStyleNormalBit,
-    FontStyleItalicMask = 1 << FontStyleItalicBit,
-    FontStyleMask = FontStyleNormalMask | FontStyleItalicMask,
-
-    FontVariantNormalMask = 1 << FontVariantNormalBit,
-    FontVariantSmallCapsMask = 1 << FontVariantSmallCapsBit,
-    FontVariantMask = FontVariantNormalMask | FontVariantSmallCapsMask,
-
-    FontWeight100Mask = 1 << FontWeight100Bit,
-    FontWeight200Mask = 1 << FontWeight200Bit,
-    FontWeight300Mask = 1 << FontWeight300Bit,
-    FontWeight400Mask = 1 << FontWeight400Bit,
-    FontWeight500Mask = 1 << FontWeight500Bit,
-    FontWeight600Mask = 1 << FontWeight600Bit,
-    FontWeight700Mask = 1 << FontWeight700Bit,
-    FontWeight800Mask = 1 << FontWeight800Bit,
-    FontWeight900Mask = 1 << FontWeight900Bit,
-    FontWeightMask = FontWeight100Mask | FontWeight200Mask | FontWeight300Mask | FontWeight400Mask | FontWeight500Mask | FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask
-};
-
-} // namespace WebCore
-#endif // FontTraitsMask_h
diff --git a/Source/core/platform/graphics/FontWidthVariant.h b/Source/core/platform/graphics/FontWidthVariant.h
deleted file mode 100644
index 6016437..0000000
--- a/Source/core/platform/graphics/FontWidthVariant.h
+++ /dev/null
@@ -1,47 +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 FontWidthVariant_h
-#define FontWidthVariant_h
-
-#include "wtf/Assertions.h"
-
-namespace WebCore {
-
-enum FontWidthVariant {
-    RegularWidth,
-    HalfWidth,
-    ThirdWidth,
-    QuarterWidth,
-    LastFontWidthVariant = QuarterWidth
-};
-
-const unsigned FontWidthVariantWidth = 2;
-
-COMPILE_ASSERT(LastFontWidthVariant >> FontWidthVariantWidth == 0, FontWidthVariantWidth_is_correct);
-
-} // namespace WebCore
-
-#endif // FontWidthVariant_h
diff --git a/Source/core/platform/graphics/Glyph.h b/Source/core/platform/graphics/Glyph.h
deleted file mode 100644
index a96770f..0000000
--- a/Source/core/platform/graphics/Glyph.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. 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 Glyph_h
-#define Glyph_h
-
-namespace WebCore {
-
-typedef unsigned short Glyph;
-
-} // namespace WebCore
-
-#endif // Glyph_h
diff --git a/Source/core/platform/graphics/GlyphBuffer.h b/Source/core/platform/graphics/GlyphBuffer.h
index 4dcf46f..3c8914d 100644
--- a/Source/core/platform/graphics/GlyphBuffer.h
+++ b/Source/core/platform/graphics/GlyphBuffer.h
@@ -30,7 +30,7 @@
 #ifndef GlyphBuffer_h
 #define GlyphBuffer_h
 
-#include "core/platform/graphics/Glyph.h"
+#include "platform/fonts/Glyph.h"
 #include "platform/geometry/FloatSize.h"
 #include "wtf/UnusedParam.h"
 #include "wtf/Vector.h"
diff --git a/Source/core/platform/graphics/GlyphMetricsMap.h b/Source/core/platform/graphics/GlyphMetricsMap.h
index 40f8814..5348739 100644
--- a/Source/core/platform/graphics/GlyphMetricsMap.h
+++ b/Source/core/platform/graphics/GlyphMetricsMap.h
@@ -29,7 +29,7 @@
 #ifndef GlyphMetricsMap_h
 #define GlyphMetricsMap_h
 
-#include "core/platform/graphics/Glyph.h"
+#include "platform/fonts/Glyph.h"
 #include "platform/geometry/FloatRect.h"
 #include "wtf/Assertions.h"
 #include "wtf/HashMap.h"
diff --git a/Source/core/platform/graphics/GlyphPage.h b/Source/core/platform/graphics/GlyphPage.h
index 3c65ccb..93b99bd 100644
--- a/Source/core/platform/graphics/GlyphPage.h
+++ b/Source/core/platform/graphics/GlyphPage.h
@@ -30,8 +30,8 @@
 #ifndef GlyphPage_h
 #define GlyphPage_h
 
+#include "platform/fonts/Glyph.h"
 #include <string.h>
-#include "core/platform/graphics/Glyph.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/platform/graphics/Gradient.cpp b/Source/core/platform/graphics/Gradient.cpp
index 737bb80..d1b700a 100644
--- a/Source/core/platform/graphics/Gradient.cpp
+++ b/Source/core/platform/graphics/Gradient.cpp
@@ -28,10 +28,10 @@
 #include "config.h"
 #include "core/platform/graphics/Gradient.h"
 
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/skia/SkiaUtils.h"
 #include "platform/geometry/FloatRect.h"
+#include "platform/graphics/Color.h"
 #include "third_party/skia/include/core/SkColorShader.h"
 #include "third_party/skia/include/core/SkShader.h"
 #include "third_party/skia/include/effects/SkGradientShader.h"
diff --git a/Source/core/platform/graphics/Gradient.h b/Source/core/platform/graphics/Gradient.h
index 52576dc..cd7ba6c 100644
--- a/Source/core/platform/graphics/Gradient.h
+++ b/Source/core/platform/graphics/Gradient.h
@@ -29,8 +29,8 @@
 #ifndef Gradient_h
 #define Gradient_h
 
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "platform/geometry/FloatPoint.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "platform/transforms/AffineTransform.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
diff --git a/Source/core/platform/graphics/GraphicsContext.h b/Source/core/platform/graphics/GraphicsContext.h
index b4bf146..c9c19ec 100644
--- a/Source/core/platform/graphics/GraphicsContext.h
+++ b/Source/core/platform/graphics/GraphicsContext.h
@@ -28,8 +28,6 @@
 #ifndef GraphicsContext_h
 #define GraphicsContext_h
 
-#include "core/platform/graphics/DashArray.h"
-#include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/GraphicsContextAnnotation.h"
 #include "core/platform/graphics/GraphicsContextState.h"
@@ -38,6 +36,8 @@
 #include "core/platform/graphics/skia/SkiaUtils.h"
 #include "platform/TraceEvent.h"
 #include "platform/geometry/FloatRect.h"
+#include "platform/graphics/DashArray.h"
+#include "platform/graphics/DrawLooper.h"
 #include "platform/graphics/ImageOrientation.h"
 // TODO(robertphillips): replace this include with "class SkBaseDevice;"
 #include "third_party/skia/include/core/SkDevice.h"
diff --git a/Source/core/platform/graphics/GraphicsContext3D.cpp b/Source/core/platform/graphics/GraphicsContext3D.cpp
index 7641de7..c4e4f5b 100644
--- a/Source/core/platform/graphics/GraphicsContext3D.cpp
+++ b/Source/core/platform/graphics/GraphicsContext3D.cpp
@@ -52,15 +52,6 @@
 #include "public/platform/WebGraphicsContext3DProvider.h"
 #include "public/platform/WebGraphicsMemoryAllocation.h"
 
-namespace {
-
-// The limit of the number of textures we hold in the GrContext's bitmap->texture cache.
-const int maxGaneshTextureCacheCount = 2048;
-// The limit of the bytes allocated toward textures in the GrContext's bitmap->texture cache.
-const size_t maxGaneshTextureCacheBytes = 96 * 1024 * 1024;
-
-}
-
 namespace WebCore {
 
 namespace {
@@ -104,11 +95,6 @@
 {
     setContextLostCallback(nullptr);
     setErrorMessageCallback(nullptr);
-
-    if (m_ownedGrContext) {
-        m_ownedWebContext->setMemoryAllocationChangedCallbackCHROMIUM(0);
-        m_ownedGrContext->contextDestroyed();
-    }
 }
 
 // Macros to assist in delegating from GraphicsContext3D to
@@ -300,59 +286,8 @@
     return context.release();
 }
 
-class GrMemoryAllocationChangedCallbackAdapter : public WebKit::WebGraphicsContext3D::WebGraphicsMemoryAllocationChangedCallbackCHROMIUM {
-public:
-    GrMemoryAllocationChangedCallbackAdapter(GrContext* context)
-        : m_context(context)
-    {
-    }
-
-    virtual void onMemoryAllocationChanged(WebKit::WebGraphicsMemoryAllocation allocation) OVERRIDE
-    {
-        if (!m_context)
-            return;
-
-        if (!allocation.gpuResourceSizeInBytes) {
-            m_context->freeGpuResources();
-            m_context->setTextureCacheLimits(0, 0);
-        } else
-            m_context->setTextureCacheLimits(maxGaneshTextureCacheCount, maxGaneshTextureCacheBytes);
-    }
-
-private:
-    GrContext* m_context;
-};
-
-namespace {
-void bindWebGraphicsContext3DGLContextCallback(const GrGLInterface* interface)
-{
-    reinterpret_cast<WebKit::WebGraphicsContext3D*>(interface->fCallbackData)->makeContextCurrent();
-}
-}
-
 GrContext* GraphicsContext3D::grContext()
 {
-    if (m_grContext)
-        return m_grContext;
-    if (!m_ownedWebContext)
-        return 0;
-
-    SkAutoTUnref<GrGLInterface> interface(m_ownedWebContext->createGrGLInterface());
-    if (!interface)
-        return 0;
-
-    interface->fCallback = bindWebGraphicsContext3DGLContextCallback;
-    interface->fCallbackData = reinterpret_cast<GrGLInterfaceCallbackData>(m_ownedWebContext.get());
-
-    m_ownedGrContext.reset(GrContext::Create(kOpenGL_GrBackend, reinterpret_cast<GrBackendContext>(interface.get())));
-    m_grContext = m_ownedGrContext;
-    if (!m_grContext)
-        return 0;
-
-    m_grContext->setTextureCacheLimits(maxGaneshTextureCacheCount, maxGaneshTextureCacheBytes);
-    m_grContextMemoryAllocationCallbackAdapter = adoptPtr(new GrMemoryAllocationChangedCallbackAdapter(m_grContext));
-    m_ownedWebContext->setMemoryAllocationChangedCallbackCHROMIUM(m_grContextMemoryAllocationCallbackAdapter.get());
-
     return m_grContext;
 }
 
diff --git a/Source/core/platform/graphics/GraphicsContext3D.h b/Source/core/platform/graphics/GraphicsContext3D.h
index 91efcc6..6c5f839 100644
--- a/Source/core/platform/graphics/GraphicsContext3D.h
+++ b/Source/core/platform/graphics/GraphicsContext3D.h
@@ -27,9 +27,9 @@
 #define GraphicsContext3D_h
 
 #include "core/platform/graphics/Extensions3D.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
 #include "core/platform/graphics/Image.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "third_party/skia/include/core/SkBitmap.h"
 #include "weborigin/KURL.h"
 #include "wtf/HashMap.h"
@@ -58,7 +58,6 @@
 class Extensions3D;
 class GraphicsContext3DContextLostCallbackAdapter;
 class GraphicsContext3DErrorMessageCallbackAdapter;
-class GrMemoryAllocationChangedCallbackAdapter;
 class Image;
 class ImageBuffer;
 class ImageData;
@@ -830,7 +829,6 @@
     OwnPtr<GraphicsContext3DErrorMessageCallbackAdapter> m_errorMessageCallbackAdapter;
     OwnPtr<WebKit::WebGraphicsContext3D> m_ownedWebContext;
     OwnPtr<Extensions3D> m_extensions;
-    OwnPtr<GrMemoryAllocationChangedCallbackAdapter> m_grContextMemoryAllocationCallbackAdapter;
     bool m_initializedAvailableExtensions;
     HashSet<String> m_enabledExtensions;
     HashSet<String> m_requestableExtensions;
@@ -853,7 +851,6 @@
     SkBitmap m_resizingBitmap;
 
     GrContext* m_grContext;
-    SkAutoTUnref<GrContext> m_ownedGrContext;
 
     // Used to flip a bitmap vertically.
     Vector<uint8_t> m_scanline;
diff --git a/Source/core/platform/graphics/GraphicsContextState.h b/Source/core/platform/graphics/GraphicsContextState.h
index eed9fd5..c863ee0 100644
--- a/Source/core/platform/graphics/GraphicsContextState.h
+++ b/Source/core/platform/graphics/GraphicsContextState.h
@@ -30,10 +30,10 @@
 #define GraphicsContextState_h
 
 #include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/graphics/Path.h"
 #include "core/platform/graphics/Pattern.h"
 #include "core/platform/graphics/StrokeData.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "third_party/skia/include/core/SkColorFilter.h"
 #include "third_party/skia/include/core/SkColorPriv.h"
 #include "third_party/skia/include/core/SkDrawLooper.h"
diff --git a/Source/core/platform/graphics/GraphicsLayer.cpp b/Source/core/platform/graphics/GraphicsLayer.cpp
index 3600e42..dd83730 100644
--- a/Source/core/platform/graphics/GraphicsLayer.cpp
+++ b/Source/core/platform/graphics/GraphicsLayer.cpp
@@ -544,6 +544,16 @@
     }
 }
 
+void GraphicsLayer::collectTrackedRepaintRects(Vector<FloatRect>& rects) const
+{
+    if (!m_client->isTrackingRepaints())
+        return;
+
+    RepaintMap::iterator repaintIt = repaintRectMap().find(this);
+    if (repaintIt != repaintRectMap().end())
+        rects.append(repaintIt->value);
+}
+
 void GraphicsLayer::writeIndent(TextStream& ts, int indent)
 {
     for (int i = 0; i != indent; ++i)
@@ -1044,14 +1054,6 @@
     platformLayer()->removeAnimation(animationId);
 }
 
-void GraphicsLayer::suspendAnimations(double wallClockTime)
-{
-    // |wallClockTime| is in the wrong time base. Need to convert here.
-    // FIXME: find a more reliable way to do this.
-    double monotonicTime = wallClockTime + monotonicallyIncreasingTime() - currentTime();
-    platformLayer()->suspendAnimations(monotonicTime);
-}
-
 WebLayer* GraphicsLayer::platformLayer() const
 {
     return m_layer->layer();
@@ -1123,7 +1125,6 @@
         case FilterOperation::CUSTOM:
         case FilterOperation::VALIDATED_CUSTOM:
             return false; // Not supported.
-        case FilterOperation::PASSTHROUGH:
         case FilterOperation::NONE:
             break;
         }
diff --git a/Source/core/platform/graphics/GraphicsLayer.h b/Source/core/platform/graphics/GraphicsLayer.h
index 1870c88..38c61dd 100644
--- a/Source/core/platform/graphics/GraphicsLayer.h
+++ b/Source/core/platform/graphics/GraphicsLayer.h
@@ -27,7 +27,6 @@
 #ifndef GraphicsLayer_h
 #define GraphicsLayer_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/GraphicsLayerClient.h"
 #include "core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
@@ -35,6 +34,7 @@
 #include "platform/geometry/FloatPoint3D.h"
 #include "platform/geometry/FloatSize.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/graphics/Color.h"
 #include "platform/transforms/TransformationMatrix.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
@@ -229,8 +229,6 @@
     void pauseAnimation(int animationId, double /*timeOffset*/);
     void removeAnimation(int animationId);
 
-    void suspendAnimations(double time);
-
     // Layer contents
     void setContentsToImage(Image*);
     void setContentsToNinePatch(Image*, const IntRect& aperture);
@@ -283,6 +281,8 @@
     void resetTrackedRepaints();
     void addRepaintRect(const FloatRect&);
 
+    void collectTrackedRepaintRects(Vector<FloatRect>&) const;
+
     static bool supportsBackgroundColorContent()
     {
         return false;
diff --git a/Source/core/platform/graphics/GraphicsTypes.cpp b/Source/core/platform/graphics/GraphicsTypes.cpp
deleted file mode 100644
index 6273435..0000000
--- a/Source/core/platform/graphics/GraphicsTypes.cpp
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2012 Rik Cabanier (cabanier@adobe.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.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-
-#include "wtf/Assertions.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-static const char* const compositeOperatorNames[] = {
-    "clear",
-    "copy",
-    "source-over",
-    "source-in",
-    "source-out",
-    "source-atop",
-    "destination-over",
-    "destination-in",
-    "destination-out",
-    "destination-atop",
-    "xor",
-    "darker",
-    "lighter"
-};
-
-static const char* const blendOperatorNames[] = {
-    "multiply",
-    "screen",
-    "overlay",
-    "darken",
-    "lighten",
-    "color-dodge",
-    "color-burn",
-    "hard-light",
-    "soft-light",
-    "difference",
-    "exclusion",
-    "hue",
-    "saturation",
-    "color",
-    "luminosity"
-};
-const int numCompositeOperatorNames = WTF_ARRAY_LENGTH(compositeOperatorNames);
-const int numBlendOperatorNames = WTF_ARRAY_LENGTH(blendOperatorNames);
-
-bool parseCompositeAndBlendOperator(const String& s, CompositeOperator& op, BlendMode& blendOp)
-{
-    for (int i = 0; i < numCompositeOperatorNames; i++) {
-        if (s == compositeOperatorNames[i]) {
-            op = static_cast<CompositeOperator>(i);
-            blendOp = BlendModeNormal;
-            return true;
-        }
-    }
-
-    for (int i = 0; i < numBlendOperatorNames; i++) {
-        if (s == blendOperatorNames[i]) {
-            blendOp = static_cast<BlendMode>(i+1);
-            // For now, blending will always assume source-over. This will be fixed in the future
-            op = CompositeSourceOver;
-            return true;
-        }
-    }
-
-    return false;
-}
-
-// FIXME: when we support blend modes in combination with compositing other than source-over
-// this routine needs to be updated.
-String compositeOperatorName(CompositeOperator op, BlendMode blendOp)
-{
-    ASSERT(op >= 0);
-    ASSERT(op < numCompositeOperatorNames);
-    ASSERT(blendOp >= 0);
-    ASSERT(blendOp <= numBlendOperatorNames);
-    if (blendOp != BlendModeNormal)
-        return blendOperatorNames[blendOp-1];
-    return compositeOperatorNames[op];
-}
-
-bool parseLineCap(const String& s, LineCap& cap)
-{
-    if (s == "butt") {
-        cap = ButtCap;
-        return true;
-    }
-    if (s == "round") {
-        cap = RoundCap;
-        return true;
-    }
-    if (s == "square") {
-        cap = SquareCap;
-        return true;
-    }
-    return false;
-}
-
-String lineCapName(LineCap cap)
-{
-    ASSERT(cap >= 0);
-    ASSERT(cap < 3);
-    const char* const names[3] = { "butt", "round", "square" };
-    return names[cap];
-}
-
-bool parseLineJoin(const String& s, LineJoin& join)
-{
-    if (s == "miter") {
-        join = MiterJoin;
-        return true;
-    }
-    if (s == "round") {
-        join = RoundJoin;
-        return true;
-    }
-    if (s == "bevel") {
-        join = BevelJoin;
-        return true;
-    }
-    return false;
-}
-
-String lineJoinName(LineJoin join)
-{
-    ASSERT(join >= 0);
-    ASSERT(join < 3);
-    const char* const names[3] = { "miter", "round", "bevel" };
-    return names[join];
-}
-
-String textAlignName(TextAlign align)
-{
-    ASSERT(align >= 0);
-    ASSERT(align < 5);
-    const char* const names[5] = { "start", "end", "left", "center", "right" };
-    return names[align];
-}
-
-bool parseTextAlign(const String& s, TextAlign& align)
-{
-    if (s == "start") {
-        align = StartTextAlign;
-        return true;
-    }
-    if (s == "end") {
-        align = EndTextAlign;
-        return true;
-    }
-    if (s == "left") {
-        align = LeftTextAlign;
-        return true;
-    }
-    if (s == "center") {
-        align = CenterTextAlign;
-        return true;
-    }
-    if (s == "right") {
-        align = RightTextAlign;
-        return true;
-    }
-    return false;
-}
-
-String textBaselineName(TextBaseline baseline)
-{
-    ASSERT(baseline >= 0);
-    ASSERT(baseline < 6);
-    const char* const names[6] = { "alphabetic", "top", "middle", "bottom", "ideographic", "hanging" };
-    return names[baseline];
-}
-
-bool parseTextBaseline(const String& s, TextBaseline& baseline)
-{
-    if (s == "alphabetic") {
-        baseline = AlphabeticTextBaseline;
-        return true;
-    }
-    if (s == "top") {
-        baseline = TopTextBaseline;
-        return true;
-    }
-    if (s == "middle") {
-        baseline = MiddleTextBaseline;
-        return true;
-    }
-    if (s == "bottom") {
-        baseline = BottomTextBaseline;
-        return true;
-    }
-    if (s == "ideographic") {
-        baseline = IdeographicTextBaseline;
-        return true;
-    }
-    if (s == "hanging") {
-        baseline = HangingTextBaseline;
-        return true;
-    }
-    return false;
-}
-
-}
diff --git a/Source/core/platform/graphics/GraphicsTypes.h b/Source/core/platform/graphics/GraphicsTypes.h
deleted file mode 100644
index 5338129..0000000
--- a/Source/core/platform/graphics/GraphicsTypes.h
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 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 GraphicsTypes_h
-#define GraphicsTypes_h
-
-#include "third_party/skia/include/core/SkPaint.h"
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-enum StrokeStyle {
-    NoStroke,
-    SolidStroke,
-    DottedStroke,
-    DashedStroke,
-    DoubleStroke,
-    WavyStroke,
-};
-
-enum InterpolationQuality {
-    InterpolationDefault,
-    InterpolationNone,
-    InterpolationLow,
-    InterpolationMedium,
-    InterpolationHigh
-};
-
-enum CompositeOperator {
-    CompositeClear,
-    CompositeCopy,
-    CompositeSourceOver,
-    CompositeSourceIn,
-    CompositeSourceOut,
-    CompositeSourceAtop,
-    CompositeDestinationOver,
-    CompositeDestinationIn,
-    CompositeDestinationOut,
-    CompositeDestinationAtop,
-    CompositeXOR,
-    CompositePlusDarker,
-    CompositePlusLighter,
-    CompositeDifference
-};
-
-// keep it in sync with gMapBlendOpsToXfermodeModes array in SkiaUtils.h
-enum BlendMode {
-    BlendModeNormal,
-    BlendModeMultiply,
-    BlendModeScreen,
-    BlendModeOverlay,
-    BlendModeDarken,
-    BlendModeLighten,
-    BlendModeColorDodge,
-    BlendModeColorBurn,
-    BlendModeHardLight,
-    BlendModeSoftLight,
-    BlendModeDifference,
-    BlendModeExclusion,
-    BlendModeHue,
-    BlendModeSaturation,
-    BlendModeColor,
-    BlendModeLuminosity
-};
-
-enum GradientSpreadMethod {
-    SpreadMethodPad,
-    SpreadMethodReflect,
-    SpreadMethodRepeat
-};
-
-enum LineCap {
-    ButtCap = SkPaint::kButt_Cap,
-    RoundCap = SkPaint::kRound_Cap,
-    SquareCap = SkPaint::kSquare_Cap
-};
-
-enum LineJoin {
-    MiterJoin = SkPaint::kMiter_Join,
-    RoundJoin = SkPaint::kRound_Join,
-    BevelJoin = SkPaint::kBevel_Join
-};
-
-enum HorizontalAlignment { AlignLeft, AlignRight, AlignHCenter };
-
-enum TextBaseline { AlphabeticTextBaseline, TopTextBaseline, MiddleTextBaseline, BottomTextBaseline, IdeographicTextBaseline, HangingTextBaseline };
-
-enum TextAlign { StartTextAlign, EndTextAlign, LeftTextAlign, CenterTextAlign, RightTextAlign };
-
-enum TextDrawingMode {
-    TextModeFill      = 1 << 0,
-    TextModeStroke    = 1 << 1,
-};
-typedef unsigned TextDrawingModeFlags;
-
-enum ColorFilter {
-    ColorFilterNone,
-    ColorFilterLuminanceToAlpha,
-    ColorFilterSRGBToLinearRGB,
-    ColorFilterLinearRGBToSRGB
-};
-
-String compositeOperatorName(CompositeOperator, BlendMode);
-bool parseCompositeAndBlendOperator(const String&, CompositeOperator&, BlendMode&);
-
-String lineCapName(LineCap);
-bool parseLineCap(const String&, LineCap&);
-
-String lineJoinName(LineJoin);
-bool parseLineJoin(const String&, LineJoin&);
-
-String textAlignName(TextAlign);
-bool parseTextAlign(const String&, TextAlign&);
-
-String textBaselineName(TextBaseline);
-bool parseTextBaseline(const String&, TextBaseline&);
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/graphics/GraphicsTypes3D.h b/Source/core/platform/graphics/GraphicsTypes3D.h
deleted file mode 100644
index d55f10f..0000000
--- a/Source/core/platform/graphics/GraphicsTypes3D.h
+++ /dev/null
@@ -1,53 +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 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 GraphicsTypes3D_h
-#define GraphicsTypes3D_h
-
-#include "wtf/Forward.h"
-#include <stdint.h>
-
-// GC3D types match the corresponding GL types as defined in OpenGL ES 2.0
-// header file gl2.h from khronos.org.
-typedef unsigned int GC3Denum;
-typedef unsigned char GC3Dboolean;
-typedef unsigned int GC3Dbitfield;
-typedef signed char GC3Dbyte;
-typedef unsigned char GC3Dubyte;
-typedef short GC3Dshort;
-typedef unsigned short GC3Dushort;
-typedef int GC3Dint;
-typedef int GC3Dsizei;
-typedef unsigned int GC3Duint;
-typedef float GC3Dfloat;
-typedef unsigned short GC3Dhalffloat;
-typedef float GC3Dclampf;
-typedef intptr_t GC3Dintptr;
-typedef intptr_t GC3Dsizeiptr;
-typedef char GC3Dchar;
-
-typedef GC3Duint Platform3DObject;
-
-#endif
diff --git a/Source/core/platform/graphics/Image.cpp b/Source/core/platform/graphics/Image.cpp
index 858a02d..fd8bfd0 100644
--- a/Source/core/platform/graphics/Image.cpp
+++ b/Source/core/platform/graphics/Image.cpp
@@ -31,7 +31,6 @@
 #include "core/platform/graphics/BitmapImage.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "platform/Length.h"
 #include "platform/SharedBuffer.h"
 #include "platform/TraceEvent.h"
@@ -39,6 +38,7 @@
 #include "platform/geometry/FloatRect.h"
 #include "platform/geometry/FloatSize.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebData.h"
 #include "wtf/MainThread.h"
diff --git a/Source/core/platform/graphics/Image.h b/Source/core/platform/graphics/Image.h
index 7e74ba9..75bef94 100644
--- a/Source/core/platform/graphics/Image.h
+++ b/Source/core/platform/graphics/Image.h
@@ -27,10 +27,10 @@
 #ifndef Image_h
 #define Image_h
 
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/graphics/Color.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "platform/graphics/ImageOrientation.h"
 #include "third_party/skia/include/core/SkXfermode.h"
 #include "wtf/PassRefPtr.h"
diff --git a/Source/core/platform/graphics/ImageBuffer.cpp b/Source/core/platform/graphics/ImageBuffer.cpp
index ede72e9..f481ec1 100644
--- a/Source/core/platform/graphics/ImageBuffer.cpp
+++ b/Source/core/platform/graphics/ImageBuffer.cpp
@@ -64,13 +64,13 @@
 
 namespace WebCore {
 
-static PassRefPtr<SkCanvas> createAcceleratedCanvas(const IntSize& size, Canvas2DLayerBridgePtr* outLayerBridge, OpacityMode opacityMode)
+static PassRefPtr<SkCanvas> createAcceleratedCanvas(const IntSize& size, Canvas2DLayerBridgePtr* outLayerBridge, OpacityMode opacityMode, int msaaSampleCount)
 {
     RefPtr<GraphicsContext3D> context3D = SharedGraphicsContext3D::get();
     if (!context3D)
         return 0;
     Canvas2DLayerBridge::OpacityMode bridgeOpacityMode = opacityMode == Opaque ? Canvas2DLayerBridge::Opaque : Canvas2DLayerBridge::NonOpaque;
-    *outLayerBridge = Canvas2DLayerBridge::create(context3D.release(), size, bridgeOpacityMode);
+    *outLayerBridge = Canvas2DLayerBridge::create(context3D.release(), size, bridgeOpacityMode, msaaSampleCount);
     // If canvas buffer allocation failed, debug build will have asserted
     // For release builds, we must verify whether the device has a render target
     return (*outLayerBridge) ? (*outLayerBridge)->getCanvas() : 0;
@@ -122,13 +122,13 @@
     success = true;
 }
 
-ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, RenderingMode renderingMode, OpacityMode opacityMode, bool& success)
+ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, RenderingMode renderingMode, OpacityMode opacityMode, int acceleratedSampleCount, bool& success)
     : m_size(size)
     , m_logicalSize(size)
     , m_resolutionScale(resolutionScale)
 {
     if (renderingMode == Accelerated) {
-        m_canvas = createAcceleratedCanvas(size, &m_layerBridge, opacityMode);
+        m_canvas = createAcceleratedCanvas(size, &m_layerBridge, opacityMode, acceleratedSampleCount);
         if (!m_canvas)
             renderingMode = UnacceleratedNonPlatformBuffer;
     }
diff --git a/Source/core/platform/graphics/ImageBuffer.h b/Source/core/platform/graphics/ImageBuffer.h
index 9992425..edc8a65 100644
--- a/Source/core/platform/graphics/ImageBuffer.h
+++ b/Source/core/platform/graphics/ImageBuffer.h
@@ -28,13 +28,13 @@
 #ifndef ImageBuffer_h
 #define ImageBuffer_h
 
-#include "core/platform/graphics/ColorSpace.h"
 #include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
 #include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/geometry/IntSize.h"
+#include "platform/graphics/ColorSpace.h"
+#include "platform/graphics/GraphicsTypes.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "platform/transforms/AffineTransform.h"
 #include "wtf/Forward.h"
 #include "wtf/OwnPtr.h"
@@ -85,10 +85,10 @@
     WTF_MAKE_NONCOPYABLE(ImageBuffer); WTF_MAKE_FAST_ALLOCATED;
 public:
     // Will return a null pointer on allocation failure.
-    static PassOwnPtr<ImageBuffer> create(const IntSize& size, float resolutionScale = 1, RenderingMode renderingMode = Unaccelerated, OpacityMode opacityMode = NonOpaque)
+    static PassOwnPtr<ImageBuffer> create(const IntSize& size, float resolutionScale = 1, RenderingMode renderingMode = Unaccelerated, OpacityMode opacityMode = NonOpaque, int acceleratedMSAASampleCount = 0)
     {
         bool success = false;
-        OwnPtr<ImageBuffer> buf = adoptPtr(new ImageBuffer(size, resolutionScale, renderingMode, opacityMode, success));
+        OwnPtr<ImageBuffer> buf = adoptPtr(new ImageBuffer(size, resolutionScale, renderingMode, opacityMode, acceleratedMSAASampleCount, success));
         if (!success)
             return nullptr;
         return buf.release();
@@ -148,7 +148,7 @@
 
     // This constructor will place its success into the given out-variable
     // so that create() knows when it should return failure.
-    ImageBuffer(const IntSize&, float resolutionScale, RenderingMode, OpacityMode, bool& success);
+    ImageBuffer(const IntSize&, float resolutionScale, RenderingMode, OpacityMode, int acceleratedSampleCount, bool& success);
     ImageBuffer(const IntSize&, float resolutionScale, const GraphicsContext*, bool hasAlpha, bool& success);
 };
 
diff --git a/Source/core/platform/graphics/InbandTextTrackPrivateClient.h b/Source/core/platform/graphics/InbandTextTrackPrivateClient.h
index e0e3ca1..2382311 100644
--- a/Source/core/platform/graphics/InbandTextTrackPrivateClient.h
+++ b/Source/core/platform/graphics/InbandTextTrackPrivateClient.h
@@ -26,7 +26,7 @@
 #ifndef InbandTextTrackPrivateClient_h
 #define InbandTextTrackPrivateClient_h
 
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/platform/graphics/MediaPlayer.h b/Source/core/platform/graphics/MediaPlayer.h
index 4a96690..aeb42ce 100644
--- a/Source/core/platform/graphics/MediaPlayer.h
+++ b/Source/core/platform/graphics/MediaPlayer.h
@@ -26,7 +26,7 @@
 #ifndef MediaPlayer_h
 #define MediaPlayer_h
 
-#include "core/platform/graphics/GraphicsTypes3D.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
 
diff --git a/Source/core/platform/graphics/Path.h b/Source/core/platform/graphics/Path.h
index eacf5bd..35be9c0 100644
--- a/Source/core/platform/graphics/Path.h
+++ b/Source/core/platform/graphics/Path.h
@@ -29,8 +29,8 @@
 #ifndef Path_h
 #define Path_h
 
-#include "core/platform/graphics/WindRule.h"
 #include "platform/geometry/RoundedRect.h"
+#include "platform/graphics/WindRule.h"
 #include "third_party/skia/include/core/SkPath.h"
 #include "wtf/FastAllocBase.h"
 #include "wtf/Forward.h"
diff --git a/Source/core/platform/graphics/SVGGlyph.h b/Source/core/platform/graphics/SVGGlyph.h
index 740faae..9c487e3 100644
--- a/Source/core/platform/graphics/SVGGlyph.h
+++ b/Source/core/platform/graphics/SVGGlyph.h
@@ -24,8 +24,8 @@
 #define SVGGlyph_h
 
 #if ENABLE(SVG_FONTS)
-#include "core/platform/graphics/Glyph.h"
 #include "core/platform/graphics/Path.h"
+#include "platform/fonts/Glyph.h"
 
 #include <limits>
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/platform/graphics/SegmentedFontData.h b/Source/core/platform/graphics/SegmentedFontData.h
index 58e8042..ab80067 100644
--- a/Source/core/platform/graphics/SegmentedFontData.h
+++ b/Source/core/platform/graphics/SegmentedFontData.h
@@ -43,6 +43,7 @@
 
     UChar32 from() const { return m_from; }
     UChar32 to() const { return m_to; }
+    bool isEntireRange() const { return !m_from && m_to >= 0x10ffff; }
     PassRefPtr<SimpleFontData> fontData() const { return m_fontData; }
 
 private:
diff --git a/Source/core/platform/graphics/ShadowBlur.cpp b/Source/core/platform/graphics/ShadowBlur.cpp
deleted file mode 100644
index aa0bf4c..0000000
--- a/Source/core/platform/graphics/ShadowBlur.cpp
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Sencha, Inc. All rights reserved.
- * Copyright (C) 2010 Igalia S.L. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. 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/graphics/ShadowBlur.h"
-
-#include "wtf/MathExtras.h"
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-enum {
-    leftLobe = 0,
-    rightLobe = 1
-};
-
-ShadowBlur::ShadowBlur(const FloatSize& radius, const FloatSize& offset, const Color& color)
-    : m_color(color)
-    , m_blurRadius(radius)
-    , m_offset(offset)
-    , m_shadowsIgnoreTransforms(false)
-{
-    updateShadowBlurValues();
-}
-
-void ShadowBlur::updateShadowBlurValues()
-{
-    // Limit blur radius to 128 to avoid lots of very expensive blurring.
-    m_blurRadius = m_blurRadius.shrunkTo(FloatSize(128, 128));
-
-    // The type of shadow is decided by the blur radius, shadow offset, and shadow color.
-    if (!m_color.isValid() || !m_color.alpha()) {
-        // Can't paint the shadow with invalid or invisible color.
-        m_type = NoShadow;
-    } else if (m_blurRadius.width() > 0 || m_blurRadius.height() > 0) {
-        // Shadow is always blurred, even the offset is zero.
-        m_type = BlurShadow;
-    } else if (!m_offset.width() && !m_offset.height()) {
-        // Without blur and zero offset means the shadow is fully hidden.
-        m_type = NoShadow;
-    } else
-        m_type = SolidShadow;
-}
-
-// Instead of integer division, we use 17.15 for fixed-point division.
-static const int blurSumShift = 15;
-
-// Takes a two dimensional array with three rows and two columns for the lobes.
-static void calculateLobes(int lobes[][2], float blurRadius, bool shadowsIgnoreTransforms)
-{
-    int diameter;
-    if (shadowsIgnoreTransforms)
-        diameter = max(2, static_cast<int>(floorf((2 / 3.f) * blurRadius))); // Canvas shadow. FIXME: we should adjust the blur radius higher up.
-    else {
-        // http://dev.w3.org/csswg/css3-background/#box-shadow
-        // Approximate a Gaussian blur with a standard deviation equal to half the blur radius,
-        // which http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement tell us how to do.
-        // However, shadows rendered according to that spec will extend a little further than m_blurRadius,
-        // so we apply a fudge factor to bring the radius down slightly.
-        float stdDev = blurRadius / 2;
-        const float gaussianKernelFactor = 3 / 4.f * sqrtf(2 * piFloat);
-        const float fudgeFactor = 0.88f;
-        diameter = max(2, static_cast<int>(floorf(stdDev * gaussianKernelFactor * fudgeFactor + 0.5f)));
-    }
-
-    if (diameter & 1) {
-        // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
-        int lobeSize = (diameter - 1) / 2;
-        lobes[0][leftLobe] = lobeSize;
-        lobes[0][rightLobe] = lobeSize;
-        lobes[1][leftLobe] = lobeSize;
-        lobes[1][rightLobe] = lobeSize;
-        lobes[2][leftLobe] = lobeSize;
-        lobes[2][rightLobe] = lobeSize;
-    } else {
-        // if d is even, two box-blurs of size 'd' (the first one centered on the pixel boundary
-        // between the output pixel and the one to the left, the second one centered on the pixel
-        // boundary between the output pixel and the one to the right) and one box blur of size 'd+1' centered on the output pixel
-        int lobeSize = diameter / 2;
-        lobes[0][leftLobe] = lobeSize;
-        lobes[0][rightLobe] = lobeSize - 1;
-        lobes[1][leftLobe] = lobeSize - 1;
-        lobes[1][rightLobe] = lobeSize;
-        lobes[2][leftLobe] = lobeSize;
-        lobes[2][rightLobe] = lobeSize;
-    }
-}
-
-void ShadowBlur::blurLayerImage(unsigned char* imageData, const IntSize& size, int rowStride)
-{
-    const int channels[4] = { 3, 0, 1, 3 };
-
-    int lobes[3][2]; // indexed by pass, and left/right lobe
-    calculateLobes(lobes, m_blurRadius.width(), m_shadowsIgnoreTransforms);
-
-    // First pass is horizontal.
-    int stride = 4;
-    int delta = rowStride;
-    int final = size.height();
-    int dim = size.width();
-
-    // Two stages: horizontal and vertical
-    for (int pass = 0; pass < 2; ++pass) {
-        unsigned char* pixels = imageData;
-
-        if (!pass && !m_blurRadius.width())
-            final = 0; // Do no work if horizonal blur is zero.
-
-        for (int j = 0; j < final; ++j, pixels += delta) {
-            // For each step, we blur the alpha in a channel and store the result
-            // in another channel for the subsequent step.
-            // We use sliding window algorithm to accumulate the alpha values.
-            // This is much more efficient than computing the sum of each pixels
-            // covered by the box kernel size for each x.
-            for (int step = 0; step < 3; ++step) {
-                int side1 = lobes[step][leftLobe];
-                int side2 = lobes[step][rightLobe];
-                int pixelCount = side1 + 1 + side2;
-                int invCount = ((1 << blurSumShift) + pixelCount - 1) / pixelCount;
-                int ofs = 1 + side2;
-                int alpha1 = pixels[channels[step]];
-                int alpha2 = pixels[(dim - 1) * stride + channels[step]];
-
-                unsigned char* ptr = pixels + channels[step + 1];
-                unsigned char* prev = pixels + stride + channels[step];
-                unsigned char* next = pixels + ofs * stride + channels[step];
-
-                int i;
-                int sum = side1 * alpha1 + alpha1;
-                int limit = (dim < side2 + 1) ? dim : side2 + 1;
-
-                for (i = 1; i < limit; ++i, prev += stride)
-                    sum += *prev;
-
-                if (limit <= side2)
-                    sum += (side2 - limit + 1) * alpha2;
-
-                limit = (side1 < dim) ? side1 : dim;
-                for (i = 0; i < limit; ptr += stride, next += stride, ++i, ++ofs) {
-                    *ptr = (sum * invCount) >> blurSumShift;
-                    sum += ((ofs < dim) ? *next : alpha2) - alpha1;
-                }
-
-                prev = pixels + channels[step];
-                for (; ofs < dim; ptr += stride, prev += stride, next += stride, ++i, ++ofs) {
-                    *ptr = (sum * invCount) >> blurSumShift;
-                    sum += (*next) - (*prev);
-                }
-
-                for (; i < dim; ptr += stride, prev += stride, ++i) {
-                    *ptr = (sum * invCount) >> blurSumShift;
-                    sum += alpha2 - (*prev);
-                }
-            }
-        }
-
-        // Last pass is vertical.
-        stride = rowStride;
-        delta = 4;
-        final = size.width();
-        dim = size.height();
-
-        if (!m_blurRadius.height())
-            break;
-
-        if (m_blurRadius.width() != m_blurRadius.height())
-            calculateLobes(lobes, m_blurRadius.height(), m_shadowsIgnoreTransforms);
-    }
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/ShadowBlur.h b/Source/core/platform/graphics/ShadowBlur.h
deleted file mode 100644
index a93eb02..0000000
--- a/Source/core/platform/graphics/ShadowBlur.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc.
- * Copyright (C) 2010 Sencha, Inc.
- * Copyright (C) 2010 Igalia S.L.
- * 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 ShadowBlur_h
-#define ShadowBlur_h
-
-#include "core/platform/graphics/Color.h"
-#include "platform/geometry/FloatSize.h"
-
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class ShadowBlur {
-    WTF_MAKE_NONCOPYABLE(ShadowBlur);
-public:
-    enum ShadowType {
-        NoShadow,
-        SolidShadow,
-        BlurShadow
-    };
-
-    ShadowBlur(const FloatSize& radius, const FloatSize& offset, const Color&);
-
-    void blurLayerImage(unsigned char*, const IntSize&, int stride);
-
-private:
-    void updateShadowBlurValues();
-
-    ShadowType m_type;
-
-    Color m_color;
-    FloatSize m_blurRadius;
-    FloatSize m_offset;
-
-    bool m_shadowsIgnoreTransforms;
-};
-
-} // namespace WebCore
-
-#endif // ShadowBlur_h
diff --git a/Source/core/platform/graphics/SimpleFontData.h b/Source/core/platform/graphics/SimpleFontData.h
index 9acc79d..4f64dff 100644
--- a/Source/core/platform/graphics/SimpleFontData.h
+++ b/Source/core/platform/graphics/SimpleFontData.h
@@ -24,17 +24,17 @@
 #ifndef SimpleFontData_h
 #define SimpleFontData_h
 
-#include "core/platform/graphics/FontMetrics.h"
 #include "core/platform/graphics/FontPlatformData.h"
 #include "core/platform/graphics/GlyphBuffer.h"
 #include "core/platform/graphics/GlyphMetricsMap.h"
 #include "core/platform/graphics/GlyphPageTreeNode.h"
 #include "platform/fonts/FontBaseline.h"
 #include "platform/fonts/FontData.h"
+#include "platform/fonts/FontMetrics.h"
 #if ENABLE(OPENTYPE_VERTICAL)
 #include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
 #endif
-#include "core/platform/graphics/TypesettingFeatures.h"
+#include "platform/fonts/TypesettingFeatures.h"
 #include "platform/geometry/FloatRect.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
diff --git a/Source/core/platform/graphics/StrokeData.h b/Source/core/platform/graphics/StrokeData.h
index e5904e0..754c1c3 100644
--- a/Source/core/platform/graphics/StrokeData.h
+++ b/Source/core/platform/graphics/StrokeData.h
@@ -29,14 +29,12 @@
 #ifndef StrokeData_h
 #define StrokeData_h
 
-#include "core/platform/graphics/DashArray.h"
 #include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/graphics/Pattern.h"
-
+#include "platform/graphics/DashArray.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "third_party/skia/include/core/SkColorPriv.h"
 #include "third_party/skia/include/effects/SkDashPathEffect.h"
-
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/platform/graphics/TextRenderingMode.h b/Source/core/platform/graphics/TextRenderingMode.h
deleted file mode 100644
index 6c36b3a..0000000
--- a/Source/core/platform/graphics/TextRenderingMode.h
+++ /dev/null
@@ -1,35 +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.
- *
- * 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 TextRenderingMode_h
-#define TextRenderingMode_h
-
-namespace WebCore {
-
-enum TextRenderingMode { AutoTextRendering, OptimizeSpeed, OptimizeLegibility, GeometricPrecision };
-
-} // namespace WebCore
-
-#endif // TextRenderingMode_h
diff --git a/Source/core/platform/graphics/TypesettingFeatures.h b/Source/core/platform/graphics/TypesettingFeatures.h
deleted file mode 100644
index 1dec5e4..0000000
--- a/Source/core/platform/graphics/TypesettingFeatures.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 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 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 TypesettingFeatures_h
-#define TypesettingFeatures_h
-
-namespace WebCore {
-
-enum TypesettingFeature {
-    Kerning = 1 << 0,
-    Ligatures = 1 << 1,
-};
-
-typedef unsigned TypesettingFeatures;
-
-} // namespace WebCore
-
-#endif // TypesettingFeatures_h
diff --git a/Source/core/platform/graphics/WidthCache.h b/Source/core/platform/graphics/WidthCache.h
index a621e9d..4cedd2d 100644
--- a/Source/core/platform/graphics/WidthCache.h
+++ b/Source/core/platform/graphics/WidthCache.h
@@ -107,7 +107,7 @@
         static const bool hasIsEmptyValueFunction = true;
         static bool isEmptyValue(const SmallStringKey& key) { return key.isHashTableEmptyValue(); }
         static const bool needsDestruction = false;
-        static const int minimumTableSize = 16;
+        static const unsigned minimumTableSize = 16;
     };
 
     friend bool operator==(const SmallStringKey&, const SmallStringKey&);
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
index 1532d4f..a388ac3 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
@@ -59,7 +59,7 @@
     return *this;
 }
 
-static SkSurface* createSurface(GraphicsContext3D* context3D, const IntSize& size)
+static SkSurface* createSurface(GraphicsContext3D* context3D, const IntSize& size, int msaaSampleCount)
 {
     ASSERT(!context3D->webContext()->isContextLost());
     GrContext* gr = context3D->grContext();
@@ -71,24 +71,25 @@
     info.fHeight = size.height();
     info.fColorType = SkImage::kPMColor_ColorType;
     info.fAlphaType = kPremul_SkAlphaType;
-    return SkSurface::NewRenderTarget(gr, info);
+    return SkSurface::NewRenderTarget(gr, info,  msaaSampleCount);
 }
 
-PassRefPtr<Canvas2DLayerBridge> Canvas2DLayerBridge::create(PassRefPtr<GraphicsContext3D> context, const IntSize& size, OpacityMode opacityMode)
+PassRefPtr<Canvas2DLayerBridge> Canvas2DLayerBridge::create(PassRefPtr<GraphicsContext3D> context, const IntSize& size, OpacityMode opacityMode, int msaaSampleCount)
 {
     TRACE_EVENT_INSTANT0("test_gpu", "Canvas2DLayerBridgeCreation");
-    SkAutoTUnref<SkSurface> surface(createSurface(context.get(), size));
+    SkAutoTUnref<SkSurface> surface(createSurface(context.get(), size, msaaSampleCount));
     if (!surface.get()) {
         return PassRefPtr<Canvas2DLayerBridge>();
     }
     RefPtr<SkDeferredCanvas> canvas = adoptRef(SkDeferredCanvas::Create(surface.get()));
-    RefPtr<Canvas2DLayerBridge> layerBridge = adoptRef(new Canvas2DLayerBridge(context, canvas.release(), opacityMode));
+    RefPtr<Canvas2DLayerBridge> layerBridge = adoptRef(new Canvas2DLayerBridge(context, canvas.release(), msaaSampleCount, opacityMode));
     return layerBridge.release();
 }
 
-Canvas2DLayerBridge::Canvas2DLayerBridge(PassRefPtr<GraphicsContext3D> context, PassRefPtr<SkDeferredCanvas> canvas, OpacityMode opacityMode)
+Canvas2DLayerBridge::Canvas2DLayerBridge(PassRefPtr<GraphicsContext3D> context, PassRefPtr<SkDeferredCanvas> canvas, int msaaSampleCount, OpacityMode opacityMode)
     : m_canvas(canvas)
     , m_context(context)
+    , m_msaaSampleCount(msaaSampleCount)
     , m_bytesAllocated(0)
     , m_didRecordDrawCommand(false)
     , m_surfaceIsValid(true)
@@ -257,7 +258,7 @@
         } else {
             m_context = sharedContext;
             IntSize size(m_canvas->getTopDevice()->width(), m_canvas->getTopDevice()->height());
-            SkAutoTUnref<SkSurface> surface(createSurface(m_context.get(), size));
+            SkAutoTUnref<SkSurface> surface(createSurface(m_context.get(), size, m_msaaSampleCount));
             if (surface.get()) {
                 m_canvas->setSurface(surface.get());
                 m_surfaceIsValid = true;
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
index 3760891..47cd689 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
@@ -69,7 +69,7 @@
         NonOpaque
     };
 
-    static PassRefPtr<Canvas2DLayerBridge> create(PassRefPtr<GraphicsContext3D>, const IntSize&, OpacityMode);
+    static PassRefPtr<Canvas2DLayerBridge> create(PassRefPtr<GraphicsContext3D>, const IntSize&, OpacityMode, int msaaSampleCount);
 
     virtual ~Canvas2DLayerBridge();
 
@@ -102,12 +102,13 @@
 protected:
     void destroy();
     friend class Canvas2DLayerBridgePtr;
-    Canvas2DLayerBridge(PassRefPtr<GraphicsContext3D>, PassRefPtr<SkDeferredCanvas>, OpacityMode);
+    Canvas2DLayerBridge(PassRefPtr<GraphicsContext3D>, PassRefPtr<SkDeferredCanvas>, int, OpacityMode);
     void setRateLimitingEnabled(bool);
 
     RefPtr<SkDeferredCanvas> m_canvas;
     OwnPtr<WebKit::WebExternalTextureLayer> m_layer;
     RefPtr<GraphicsContext3D> m_context;
+    int m_msaaSampleCount;
     size_t m_bytesAllocated;
     bool m_didRecordDrawCommand;
     bool m_surfaceIsValid;
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp b/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
index 43bd3b1..6692672 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
@@ -61,7 +61,7 @@
     }
 protected:
     FakeCanvas2DLayerBridge(PassRefPtr<GraphicsContext3D> context, PassRefPtr<SkDeferredCanvas> canvas, OpacityMode opacityMode) :
-        Canvas2DLayerBridge(context, canvas, opacityMode)
+        Canvas2DLayerBridge(context, canvas, 0, opacityMode)
     { }
 };
 
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp b/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
index 884500e..c6d7398 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
@@ -45,7 +45,7 @@
 class FakeCanvas2DLayerBridge : public Canvas2DLayerBridge {
 public:
     FakeCanvas2DLayerBridge(PassRefPtr<GraphicsContext3D> context, PassRefPtr<SkDeferredCanvas> canvas)
-        : Canvas2DLayerBridge(context, canvas, NonOpaque)
+        : Canvas2DLayerBridge(context, canvas, 0, NonOpaque)
         , m_freeableBytes(0)
         , m_freeMemoryIfPossibleCount(0)
         , m_flushCount(0)
diff --git a/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp b/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp
index fa99b20..0bd09eb 100644
--- a/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp
+++ b/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp
@@ -29,13 +29,15 @@
 #include "SkBitmapDevice.h"
 #include "SkCanvas.h"
 #include "SkPicture.h"
-#include "platform/SharedBuffer.h"
 #include "core/platform/graphics/chromium/ImageDecodingStore.h"
 #include "core/platform/graphics/chromium/test/MockImageDecoder.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
+#include "platform/SharedBuffer.h"
+#include "platform/Task.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebThread.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
-#include "wtf/Threading.h"
 #include <gtest/gtest.h>
 
 namespace WebCore {
@@ -201,10 +203,9 @@
     EXPECT_EQ(SkColorSetARGB(255, 255, 255, 255), canvasBitmap.getColor(49, 50));
 }
 
-static void rasterizeMain(void* arg)
+static void rasterizeMain(SkCanvas* canvas, SkPicture* picture)
 {
-    Rasterizer* rasterizer = static_cast<Rasterizer*>(arg);
-    rasterizer->canvas->drawPicture(*rasterizer->picture);
+    canvas->drawPicture(*picture);
 }
 
 TEST_F(DeferredImageDecoderTest, decodeOnOtherThread)
@@ -222,11 +223,9 @@
     EXPECT_EQ(0, m_frameBufferRequestCount);
 
     // Create a thread to rasterize SkPicture.
-    Rasterizer rasterizer;
-    rasterizer.canvas = m_canvas;
-    rasterizer.picture = &m_picture;
-    ThreadIdentifier threadID = createThread(&rasterizeMain, &rasterizer, "RasterThread");
-    waitForThreadCompletion(threadID);
+    OwnPtr<WebKit::WebThread> thread = adoptPtr(WebKit::Platform::current()->createThread("RasterThread"));
+    thread->postTask(new Task(WTF::bind(&rasterizeMain, m_canvas.get(), &m_picture)));
+    thread.clear();
     EXPECT_EQ(0, m_frameBufferRequestCount);
 
     SkBitmap canvasBitmap;
diff --git a/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp b/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
index f8e2ded..45f487c 100644
--- a/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
+++ b/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
@@ -32,8 +32,8 @@
 #include "core/platform/graphics/FontCache.h"
 
 #include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/SimpleFontData.h"
+#include "platform/fonts/FontDescription.h"
 
 #include "SkTypeface_android.h"
 
diff --git a/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp b/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
index a89c355..b5a661a 100644
--- a/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
@@ -35,8 +35,8 @@
 #include <unicode/uniset.h>
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/SimpleFontData.h"
+#include "core/platform/graphics/chromium/FontFallbackWin.h"
 #include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
 #include "platform/LayoutTestSupport.h"
 #include "platform/win/HWndDC.h"
 #include "wtf/HashMap.h"
diff --git a/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.cpp b/Source/core/platform/graphics/chromium/FontFallbackWin.cpp
similarity index 70%
rename from Source/core/platform/graphics/chromium/FontUtilsChromiumWin.cpp
rename to Source/core/platform/graphics/chromium/FontFallbackWin.cpp
index 553ebfe..e0b4ac5 100644
--- a/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/FontFallbackWin.cpp
@@ -29,17 +29,16 @@
  */
 
 #include "config.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
+#include "core/platform/graphics/chromium/FontFallbackWin.h"
 
-#include <limits>
-
-#include <unicode/locid.h>
-#include <unicode/uchar.h>
 #include "core/platform/graphics/chromium/UniscribeHelper.h"
 #include "platform/win/HWndDC.h"
 #include "wtf/HashMap.h"
 #include "wtf/text/StringHash.h"
 #include "wtf/text/WTFString.h"
+#include <limits>
+#include <unicode/locid.h>
+#include <unicode/uchar.h>
 
 namespace WebCore {
 
@@ -47,8 +46,7 @@
 
 bool isFontPresent(const UChar* fontName)
 {
-    HFONT hfont = CreateFont(12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-                             fontName);
+    HFONT hfont = CreateFont(12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, fontName);
     if (!hfont)
         return false;
     HWndDC dc(0);
@@ -60,10 +58,11 @@
     DeleteObject(hfont);
     // We don't have to worry about East Asian fonts with locale-dependent
     // names here for now.
+    // FIXME: Why not?
     return !wcscmp(fontName, actualFontName);
 }
 
-// A simple mapping from UScriptCode to family name.  This is a sparse array,
+// A simple mapping from UScriptCode to family name. This is a sparse array,
 // which works well since the range of UScriptCode values is small.
 typedef const UChar* ScriptToFontMap[USCRIPT_CODE_LIMIT];
 
@@ -175,13 +174,13 @@
     // this ICU locale tells the current UI locale of Chrome.
     icu::Locale locale = icu::Locale::getDefault();
     const UChar* localeFamily = 0;
-    if (locale == icu::Locale::getJapanese())
+    if (locale == icu::Locale::getJapanese()) {
         localeFamily = scriptFontMap[USCRIPT_HIRAGANA];
-    else if (locale == icu::Locale::getKorean())
+    } else if (locale == icu::Locale::getKorean()) {
         localeFamily = scriptFontMap[USCRIPT_HANGUL];
-    else if (locale == icu::Locale::getTraditionalChinese())
+    } else if (locale == icu::Locale::getTraditionalChinese()) {
         localeFamily = scriptFontMap[USCRIPT_TRADITIONAL_HAN];
-    else {
+    } else {
         // For other locales, use the simplified Chinese font for Han.
         localeFamily = scriptFontMap[USCRIPT_SIMPLIFIED_HAN];
     }
@@ -235,55 +234,6 @@
     return script;
 }
 
-const int kUndefinedAscent = std::numeric_limits<int>::min();
-
-// Given an HFONT, return the ascent. If GetTextMetrics fails,
-// kUndefinedAscent is returned, instead.
-int getAscent(HFONT hfont)
-{
-    HWndDC dc(0);
-    HGDIOBJ oldFont = SelectObject(dc, hfont);
-    TEXTMETRIC tm;
-    BOOL gotMetrics = GetTextMetrics(dc, &tm);
-    SelectObject(dc, oldFont);
-    return gotMetrics ? tm.tmAscent : kUndefinedAscent;
-}
-
-const WORD kUnsupportedGlyph = 0xffff;
-
-WORD getSpaceGlyph(HFONT hfont)
-{
-    HWndDC dc(0);
-    HGDIOBJ oldFont = SelectObject(dc, hfont);
-    WCHAR space = L' ';
-    WORD spaceGlyph = kUnsupportedGlyph;
-    GetGlyphIndices(dc, &space, 1, &spaceGlyph, GGI_MARK_NONEXISTING_GLYPHS);
-    SelectObject(dc, oldFont);
-    return spaceGlyph;
-}
-
-struct FontData {
-    FontData()
-        : hfont(0)
-        , ascent(kUndefinedAscent)
-        , scriptCache(0)
-        , spaceGlyph(0)
-    {
-    }
-
-    HFONT hfont;
-    int ascent;
-    mutable SCRIPT_CACHE scriptCache;
-    WORD spaceGlyph;
-};
-
-// Again, using hash_map does not earn us much here.  page_cycler_test intl2
-// gave us a 'better' result with map than with hash_map even though they're
-// well-within 1-sigma of each other so that the difference is not significant.
-// On the other hand, some pages in intl2 seem to take longer to load with map
-// in the 1st pass. Need to experiment further.
-typedef HashMap<String, FontData> FontDataCache;
-
 } // namespace
 
 // FIXME: this is font fallback code version 0.1
@@ -302,7 +252,7 @@
 //  - Update script_font_cache in response to WM_FONTCHANGE
 
 const UChar* getFontFamilyForScript(UScriptCode script,
-                                    FontDescription::GenericFamilyType generic)
+    FontDescription::GenericFamilyType generic)
 {
     static ScriptToFontMap scriptFontMap;
     static bool initialized = false;
@@ -324,11 +274,59 @@
 //    and just return it.
 //  - All the characters (or characters up to the point a single
 //    font can cover) need to be taken into account
-const UChar* getFallbackFamily(const UChar* characters,
-                               int length,
-                               FontDescription::GenericFamilyType generic,
-                               UChar32* charChecked,
-                               UScriptCode* scriptChecked)
+const UChar* getFallbackFamily(UChar32 character,
+    FontDescription::GenericFamilyType generic,
+    UScriptCode* scriptChecked)
+{
+    ASSERT(character);
+    UScriptCode script = getScript(character);
+
+    // For the full-width ASCII characters (U+FF00 - U+FF5E), use the font for
+    // Han (determined in a locale-dependent way above). Full-width ASCII
+    // characters are rather widely used in Japanese and Chinese documents and
+    // they're fully covered by Chinese, Japanese and Korean fonts.
+    if (0xFF00 < character && character < 0xFF5F)
+        script = USCRIPT_HAN;
+
+    if (script == USCRIPT_COMMON)
+        script = getScriptBasedOnUnicodeBlock(character);
+
+    const UChar* family = getFontFamilyForScript(script, generic);
+    // Another lame work-around to cover non-BMP characters.
+    // If the font family for script is not found or the character is
+    // not in BMP (> U+FFFF), we resort to the hard-coded list of
+    // fallback fonts for now.
+    if (!family || character > 0xFFFF) {
+        int plane = character >> 16;
+        switch (plane) {
+        case 1:
+            family = L"code2001";
+            break;
+        case 2:
+            // Use a Traditional Chinese ExtB font if in Traditional Chinese locale.
+            // Otherwise, use a Simplified Chinese ExtB font. Windows Japanese
+            // fonts do support a small subset of ExtB (that are included in JIS X 0213),
+            // but its coverage is rather sparse.
+            // Eventually, this should be controlled by lang/xml:lang.
+            if (icu::Locale::getDefault() == icu::Locale::getTraditionalChinese())
+                family = L"pmingliu-extb";
+            else
+                family = L"simsun-extb";
+            break;
+        default:
+            family = L"lucida sans unicode";
+        }
+    }
+
+    if (scriptChecked)
+        *scriptChecked = script;
+    return family;
+}
+
+
+const UChar* getFallbackFamilyForFirstNonCommonCharacter(const UChar* characters,
+    int length,
+    FontDescription::GenericFamilyType generic)
 {
     ASSERT(characters && characters[0] && length > 0);
     UScriptCode script = USCRIPT_COMMON;
@@ -343,117 +341,9 @@
         script = getScript(ucs4);
     }
 
-    // For the full-width ASCII characters (U+FF00 - U+FF5E), use the font for
-    // Han (determined in a locale-dependent way above). Full-width ASCII
-    // characters are rather widely used in Japanese and Chinese documents and
-    // they're fully covered by Chinese, Japanese and Korean fonts.
-    if (0xFF00 < ucs4 && ucs4 < 0xFF5F)
-        script = USCRIPT_HAN;
+    const UChar* family = getFallbackFamily(ucs4, generic, 0);
 
-    if (script == USCRIPT_COMMON)
-        script = getScriptBasedOnUnicodeBlock(ucs4);
-
-    const UChar* family = getFontFamilyForScript(script, generic);
-    // Another lame work-around to cover non-BMP characters.
-    // If the font family for script is not found or the character is
-    // not in BMP (> U+FFFF), we resort to the hard-coded list of
-    // fallback fonts for now.
-    if (!family || ucs4 > 0xFFFF) {
-        int plane = ucs4 >> 16;
-        switch (plane) {
-        case 1:
-            family = L"code2001";
-            break;
-        case 2:
-            // Use a Traditional Chinese ExtB font if in Traditional Chinese locale.
-            // Otherwise, use a Simplified Chinese ExtB font. Windows Japanese
-            // fonts do support a small subset of ExtB (that are included in JIS X 0213),
-            // but its coverage is rather sparse.
-            // Eventually, this should be controlled by lang/xml:lang.
-            if (icu::Locale::getDefault() == icu::Locale::getTraditionalChinese())
-              family = L"pmingliu-extb";
-            else
-              family = L"simsun-extb";
-            break;
-        default:
-            family = L"lucida sans unicode";
-        }
-    }
-
-    if (charChecked)
-        *charChecked = ucs4;
-    if (scriptChecked)
-        *scriptChecked = script;
     return family;
 }
 
-// Be aware that this is not thread-safe.
-bool getDerivedFontData(const UChar* family,
-                        int style,
-                        LOGFONT* logfont,
-                        int* ascent,
-                        HFONT* hfont,
-                        SCRIPT_CACHE** scriptCache,
-                        WORD* spaceGlyph)
-{
-    ASSERT(logfont);
-    ASSERT(family);
-    ASSERT(*family);
-
-    // It does not matter that we leak font data when we exit.
-    static FontDataCache* gFontDataCache = 0;
-    if (!gFontDataCache)
-        gFontDataCache = new FontDataCache();
-
-    // FIXME: This comes up pretty high in the profile so that
-    // we need to measure whether using SHA256 (after coercing all the
-    // fields to char*) is faster than String::format.
-    String fontKey = String::format("%1d:%d:%ls", style, logfont->lfHeight, family);
-    FontDataCache::iterator iter = gFontDataCache->find(fontKey);
-    FontData* derived;
-    if (iter == gFontDataCache->end()) {
-        ASSERT(wcslen(family) < LF_FACESIZE);
-        wcscpy_s(logfont->lfFaceName, LF_FACESIZE, family);
-        // FIXME: CreateFontIndirect always comes up with
-        // a font even if there's no font matching the name. Need to
-        // check it against what we actually want (as is done in
-        // FontCacheWin.cpp)
-        FontDataCache::AddResult entry = gFontDataCache->add(fontKey, FontData());
-        derived = &entry.iterator->value;
-        derived->hfont = CreateFontIndirect(logfont);
-        // GetAscent may return kUndefinedAscent, but we still want to
-        // cache it so that we won't have to call CreateFontIndirect once
-        // more for HFONT next time.
-        derived->ascent = getAscent(derived->hfont);
-        derived->spaceGlyph = getSpaceGlyph(derived->hfont);
-    } else {
-        derived = &iter->value;
-        // Last time, getAscent or getSpaceGlyph failed so that only HFONT was
-        // cached. Try once more assuming that TryPreloadFont
-        // was called by a caller between calls.
-        if (kUndefinedAscent == derived->ascent)
-            derived->ascent = getAscent(derived->hfont);
-        if (kUnsupportedGlyph == derived->spaceGlyph)
-            derived->spaceGlyph = getSpaceGlyph(derived->hfont);
-    }
-    *hfont = derived->hfont;
-    *ascent = derived->ascent;
-    *scriptCache = &(derived->scriptCache);
-    *spaceGlyph = derived->spaceGlyph;
-    return *ascent != kUndefinedAscent && *spaceGlyph != kUnsupportedGlyph;
-}
-
-int getStyleFromLogfont(const LOGFONT* logfont)
-{
-    // FIXME: consider defining UNDEFINED or INVALID for style and
-    //                  returning it when logfont is 0
-    if (!logfont) {
-        ASSERT_NOT_REACHED();
-        return FontStyleNormal;
-    }
-    return (logfont->lfItalic ? FontStyleItalic : FontStyleNormal) |
-           (logfont->lfUnderline ? FontStyleUnderlined : FontStyleNormal) |
-           (logfont->lfWeight >= 700 ? FontStyleBold : FontStyleNormal);
-}
-
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/chromium/FontFallbackWin.h b/Source/core/platform/graphics/chromium/FontFallbackWin.h
new file mode 100644
index 0000000..bba33c8
--- /dev/null
+++ b/Source/core/platform/graphics/chromium/FontFallbackWin.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2006, 2007, 2008, 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.
+ */
+
+// A collection of utilities for font handling.
+
+// FIXME: Move all methods to the files that have their callsites and remove this file.
+// *Utils files are not very WebKit-ty.
+
+#ifndef FontFallbackWin_h
+#define FontFallbackWin_h
+
+#include "platform/fonts/FontDescription.h"
+#include <unicode/uscript.h>
+#include <usp10.h>
+#include <wchar.h>
+#include <windows.h>
+
+namespace WebCore {
+
+// Return a font family that can render |characters| based on
+// what script characters belong to.
+// FIXME: This function needs a total overhaul.
+const UChar* getFallbackFamilyForFirstNonCommonCharacter(const UChar* characters,
+    int length,
+    FontDescription::GenericFamilyType);
+
+// Return a font family that can render |character| based on what script
+// that characters belong to.
+// When scriptChecked is non-zero, the script used to determine
+// the family is returned.
+const UChar* getFallbackFamily(UChar32 character,
+    FontDescription::GenericFamilyType,
+    UScriptCode* scriptChecked);
+
+} // namespace WebCore
+
+#endif // FontFallbackWin_h
diff --git a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
index 521495c..9c0ccc7 100644
--- a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
@@ -177,7 +177,7 @@
     , m_fakeItalic(false)
     , m_orientation(Horizontal)
     , m_scriptCache(0)
-    , m_typeface(SkTypeface::RefDefault())
+    , m_typeface(adoptRef(SkTypeface::RefDefault()))
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(true)
 {
@@ -190,7 +190,7 @@
     , m_fakeItalic(false)
     , m_orientation(Horizontal)
     , m_scriptCache(0)
-    , m_typeface(SkTypeface::RefDefault())
+    , m_typeface(adoptRef(SkTypeface::RefDefault()))
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(false)
 {
@@ -218,7 +218,7 @@
     , m_fakeItalic(false)
     , m_orientation(Horizontal)
     , m_scriptCache(0)
-    , m_typeface(SkTypeface::RefDefault())
+    , m_typeface(adoptRef(SkTypeface::RefDefault()))
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(false)
 {
@@ -298,6 +298,7 @@
 
 String FontPlatformData::fontFamilyName() const
 {
+#if ENABLE(GDI_FONTS_ON_WINDOWS)
     HWndDC dc(0);
     HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont()));
     WCHAR name[LF_FACESIZE];
@@ -306,6 +307,14 @@
         resultLength--; // ignore the null terminator
     SelectObject(dc, oldFont);
     return String(name, resultLength);
+#else
+    // FIXME: This returns the requested name, perhaps a better solution would be to
+    // return the list of names provided by SkTypeface::createFamilyNameIterator.
+    ASSERT(typeface());
+    SkString familyName;
+    typeface()->getFamilyName(&familyName);
+    return String::fromUTF8(familyName.c_str());
+#endif
 }
 
 bool FontPlatformData::isFixedPitch() const
diff --git a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
index 252f7f1..fd228ba 100644
--- a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
+++ b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
@@ -37,9 +37,9 @@
 #include "SkPaint.h"
 #include "SkTypeface.h"
 #include "SkTypeface_win.h"
-#include "core/platform/graphics/FontOrientation.h"
 #include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
 #include "platform/SharedBuffer.h"
+#include "platform/fonts/FontOrientation.h"
 #include "wtf/Forward.h"
 #include "wtf/HashTableDeletedValueType.h"
 #include "wtf/OwnPtr.h"
@@ -121,6 +121,9 @@
     String description() const;
 #endif
 
+    // FIXME: Only used by Uniscribe, should be protected by a
+    // ENABLE(GDI_FONTS_ON_WINDOWS) macro once we have an abstraction layer
+    // for complex text shaping.
     SCRIPT_FONTPROPERTIES* scriptFontProperties() const;
     SCRIPT_CACHE* scriptCache() const { return &m_scriptCache; }
 
diff --git a/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.h b/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.h
deleted file mode 100644
index ef2eea2..0000000
--- a/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, 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.
- */
-
-// A collection of utilities for font handling.
-
-// FIXME: Move all methods to the files that have their callsites and remove this file.
-// *Utils files are not very WebKit-ty.
-
-#ifndef FontUtilsChromiumWin_h
-#define FontUtilsChromiumWin_h
-
-#include <windows.h>
-#include <usp10.h>
-#include <wchar.h>
-
-#include <unicode/uscript.h>
-#include "core/platform/graphics/FontDescription.h"
-
-namespace WebCore {
-
-// Return a font family that supports a script and belongs to |generic| font
-// family.  It can return NULL and a caller has to implement its own fallback.
-const UChar* getFontFamilyForScript(UScriptCode, FontDescription::GenericFamilyType);
-
-// Return a font family that can render |characters| based on
-// what script characters belong to. When char_checked is non-NULL,
-// it's filled with the character used to determine the script.
-// When script_checked is non-NULL, the script used to determine
-// the family is returned.
-// FIXME: This function needs a total overhaul.
-const UChar* getFallbackFamily(const UChar* characters, int length,
-                               FontDescription::GenericFamilyType,
-                               UChar32* charChecked,
-                               UScriptCode* scriptChecked);
-
-// Derive a new HFONT by replacing lfFaceName of LOGFONT with |family|,
-// calculate the ascent for the derived HFONT, and initialize SCRIPT_CACHE
-// in FontData.
-// |style| is only used for cache key generation. |style| is
-// bit-wise OR of BOLD(1), UNDERLINED(2) and ITALIC(4) and
-// should match what's contained in LOGFONT. It should be calculated
-// by calling GetStyleFromLogFont.
-// Returns false if the font is not accessible, in which case |ascent| field
-// of |fontdata| is set to kUndefinedAscent.
-// Be aware that this is not thread-safe.
-// FIXME: Instead of having three out params, we'd better have one
-// (|*FontData|), but somehow it mysteriously messes up the layout for
-// certain complex script pages (e.g. hi.wikipedia.org) and also crashes
-// at the start-up if recently visited page list includes pages with complex
-// scripts in their title. Moreover, somehow the very first-pass of
-// intl2 page-cycler test is noticeably slower with one out param than
-// the current version although the subsequent 9 passes take about the
-// same time.
-bool getDerivedFontData(const UChar* family, int style, LOGFONT*, int* ascent, HFONT*, SCRIPT_CACHE**, WORD* spaceGlyph);
-
-enum {
-    FontStyleNormal = 0,
-    FontStyleBold = 1,
-    FontStyleItalic = 2,
-    FontStyleUnderlined = 4
-};
-
-// Derive style (bit-wise OR of FONT_STYLE_BOLD, FONT_STYLE_UNDERLINED, and
-// FONT_STYLE_ITALIC) from LOGFONT. Returns 0 if |*logfont| is NULL.
-int getStyleFromLogfont(const LOGFONT*);
-
-}  // namespace WebCore
-
-#endif  // FontUtilsChromiumWin_h
diff --git a/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp b/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp
index 3620101..c9a3217 100644
--- a/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp
@@ -149,7 +149,7 @@
     bool haveGlyphs = false;
     int invalidGlyph = 0xFFFF;
     const DWORD cffTableTag = 0x20464643; // 4-byte identifier for OpenType CFF table ('CFF ').
-    if ((windowsVersion() < WindowsVista) && !(tm.tmPitchAndFamily & TMPF_TRUETYPE) && (GetFontData(dc, cffTableTag, 0, 0, 0) == GDI_ERROR))
+    if (!isWindowsVistaOrGreater() && !(tm.tmPitchAndFamily & TMPF_TRUETYPE) && (GetFontData(dc, cffTableTag, 0, 0, 0) == GDI_ERROR))
         invalidGlyph = 0x1F;
 
     Glyph spaceGlyph = 0;  // Glyph for a space. Lazily filled.
diff --git a/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp b/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp
index d79a78f..f8744b3 100644
--- a/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp
+++ b/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp
@@ -263,19 +263,19 @@
     return m_memoryUsageInBytes;
 }
 
-unsigned ImageDecodingStore::cacheEntries()
+int ImageDecodingStore::cacheEntries()
 {
     MutexLocker lock(m_mutex);
     return m_imageCacheMap.size() + m_decoderCacheMap.size();
 }
 
-unsigned ImageDecodingStore::imageCacheEntries()
+int ImageDecodingStore::imageCacheEntries()
 {
     MutexLocker lock(m_mutex);
     return m_imageCacheMap.size();
 }
 
-unsigned ImageDecodingStore::decoderCacheEntries()
+int ImageDecodingStore::decoderCacheEntries()
 {
     MutexLocker lock(m_mutex);
     return m_decoderCacheMap.size();
diff --git a/Source/core/platform/graphics/chromium/ImageDecodingStore.h b/Source/core/platform/graphics/chromium/ImageDecodingStore.h
index 8fc7d12..370146b 100644
--- a/Source/core/platform/graphics/chromium/ImageDecodingStore.h
+++ b/Source/core/platform/graphics/chromium/ImageDecodingStore.h
@@ -116,9 +116,9 @@
     void clear();
     void setCacheLimitInBytes(size_t);
     size_t memoryUsageInBytes();
-    unsigned cacheEntries();
-    unsigned imageCacheEntries();
-    unsigned decoderCacheEntries();
+    int cacheEntries();
+    int imageCacheEntries();
+    int decoderCacheEntries();
 
 private:
     // Image cache entry is identified by:
diff --git a/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp b/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp
index 3c2d95a..9b70cce 100644
--- a/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp
+++ b/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp
@@ -143,13 +143,13 @@
     insertCache(SkISize::Make(1, 1));
     insertCache(SkISize::Make(2, 2));
     insertCache(SkISize::Make(3, 3));
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
 
     evictOneCache();
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
 
     evictOneCache();
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
 }
 
 TEST_F(ImageDecodingStoreTest, pruneOrderIsLeastRecentlyUsed)
@@ -159,7 +159,7 @@
     insertCache(SkISize::Make(3, 3));
     insertCache(SkISize::Make(4, 4));
     insertCache(SkISize::Make(5, 5));
-    EXPECT_EQ(5u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(5, ImageDecodingStore::instance()->cacheEntries());
 
     // Use cache in the order 3, 2, 4, 1, 5.
     EXPECT_TRUE(isCacheAlive(SkISize::Make(3, 3)));
@@ -171,27 +171,27 @@
     // Evict 3.
     evictOneCache();
     EXPECT_FALSE(isCacheAlive(SkISize::Make(3, 3)));
-    EXPECT_EQ(4u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(4, ImageDecodingStore::instance()->cacheEntries());
 
     // Evict 2.
     evictOneCache();
     EXPECT_FALSE(isCacheAlive(SkISize::Make(2, 2)));
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
 
     // Evict 4.
     evictOneCache();
     EXPECT_FALSE(isCacheAlive(SkISize::Make(4, 4)));
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
 
     // Evict 1.
     evictOneCache();
     EXPECT_FALSE(isCacheAlive(SkISize::Make(1, 1)));
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
 
     // Evict 5.
     evictOneCache();
     EXPECT_FALSE(isCacheAlive(SkISize::Make(5, 5)));
-    EXPECT_EQ(0u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(0, ImageDecodingStore::instance()->cacheEntries());
 }
 
 TEST_F(ImageDecodingStoreTest, pruneCausedByInsertion)
@@ -203,12 +203,12 @@
     insertCache(SkISize::Make(1, 1));
     insertCache(SkISize::Make(2, 2));
     insertCache(SkISize::Make(3, 3));
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
 
     for (int i = 4; i <= 100; ++i)
         insertCache(SkISize::Make(i, i));
 
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
     for (int i = 1; i <= 99; ++i)
         EXPECT_FALSE(isCacheAlive(SkISize::Make(i, i)));
     EXPECT_TRUE(isCacheAlive(SkISize::Make(100, 100)));
@@ -219,7 +219,7 @@
     insertCache(SkISize::Make(1, 1));
     insertCache(SkISize::Make(2, 2));
     insertCache(SkISize::Make(3, 3));
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
 
     const ScaledImageFragment* cachedImage = lockCache(SkISize::Make(1, 1));
     ASSERT_TRUE(cachedImage);
@@ -230,7 +230,7 @@
     EXPECT_FALSE(isCacheAlive(SkISize::Make(2, 2)));
     EXPECT_TRUE(isCacheAlive(SkISize::Make(3, 3)));
 
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
     unlockCache(cachedImage);
 }
 
@@ -242,7 +242,7 @@
     OwnPtr<ImageDecoder> decoder = MockImageDecoder::create(this);
     decoder->setSize(1, 1);
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder.release(), false);
-    EXPECT_EQ(4u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(4, ImageDecodingStore::instance()->cacheEntries());
 
     m_generator.clear();
     EXPECT_FALSE(ImageDecodingStore::instance()->cacheEntries());
@@ -255,7 +255,7 @@
     decoder->setSize(1, 1);
     const ImageDecoder* refDecoder = decoder.get();
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder.release(), false);
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
     EXPECT_EQ(4u, ImageDecodingStore::instance()->memoryUsageInBytes());
 
     ImageDecoder* testDecoder;
@@ -263,7 +263,7 @@
     EXPECT_TRUE(testDecoder);
     EXPECT_EQ(refDecoder, testDecoder);
     ImageDecodingStore::instance()->unlockDecoder(m_generator.get(), testDecoder);
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
 }
 
 TEST_F(ImageDecodingStoreTest, evictDecoder)
@@ -277,15 +277,15 @@
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder1.release(), false);
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder2.release(), false);
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder3.release(), false);
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
     EXPECT_EQ(56u, ImageDecodingStore::instance()->memoryUsageInBytes());
 
     evictOneCache();
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
     EXPECT_EQ(52u, ImageDecodingStore::instance()->memoryUsageInBytes());
 
     evictOneCache();
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
     EXPECT_EQ(36u, ImageDecodingStore::instance()->memoryUsageInBytes());
 
     evictOneCache();
@@ -304,7 +304,7 @@
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder1.release(), false);
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder2.release(), false);
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder3.release(), false);
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
 
     ImageDecoder* testDecoder;
     EXPECT_TRUE(ImageDecodingStore::instance()->lockDecoder(m_generator.get(), SkISize::Make(2, 2), &testDecoder));
@@ -312,7 +312,7 @@
     evictOneCache();
     evictOneCache();
     evictOneCache();
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
     EXPECT_EQ(16u, ImageDecodingStore::instance()->memoryUsageInBytes());
 
     ImageDecodingStore::instance()->unlockDecoder(m_generator.get(), testDecoder);
@@ -328,7 +328,7 @@
     decoder->setSize(1, 1);
     const ImageDecoder* refDecoder = decoder.get();
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder.release(), false);
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
     EXPECT_EQ(4u, ImageDecodingStore::instance()->memoryUsageInBytes());
 
     ImageDecoder* testDecoder;
@@ -351,7 +351,7 @@
         m_generator.get(), createCompleteImage(size, false, 1));
     unlockCache(testImage);
     EXPECT_NE(refImage, testImage);
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
 
     EXPECT_TRUE(ImageDecodingStore::instance()->lockCache(m_generator.get(), size, 1, &refImage));
     EXPECT_EQ(refImage, testImage);
@@ -368,7 +368,7 @@
         m_generator.get(), createIncompleteImage(size, false, 1));
     unlockCache(testImage);
     EXPECT_NE(refImage, testImage);
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
 
     EXPECT_TRUE(ImageDecodingStore::instance()->lockCache(m_generator.get(), size, 0, &refImage));
     EXPECT_NE(refImage, testImage);
@@ -385,7 +385,7 @@
         m_generator.get(), createIncompleteImage(size, false, 2));
     unlockCache(testImage);
     EXPECT_NE(refImage, testImage);
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
 }
 
 TEST_F(ImageDecodingStoreTest, insertGenerationCollision)
@@ -398,7 +398,7 @@
         m_generator.get(), createIncompleteImage(size, false, 1));
     unlockCache(testImage);
     EXPECT_EQ(refImage, testImage);
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
 }
 
 TEST_F(ImageDecodingStoreTest, insertGenerationCollisionAfterMemoryDiscarded)
@@ -413,7 +413,7 @@
         m_generator.get(), createIncompleteImage(size, false, 1));
     unlockCache(testImage);
     EXPECT_NE(refImage, testImage);
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
 }
 
 TEST_F(ImageDecodingStoreTest, lockCacheFailedAfterMemoryDiscarded)
@@ -424,37 +424,37 @@
     MockDiscardablePixelRef* pixelRef = static_cast<MockDiscardablePixelRef*>(cachedImage->bitmap().pixelRef());
     pixelRef->discard();
     EXPECT_EQ(0, lockCache(SkISize::Make(1, 1)));
-    EXPECT_EQ(0u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(0, ImageDecodingStore::instance()->cacheEntries());
 }
 
 TEST_F(ImageDecodingStoreTest, clear)
 {
     insertCache(SkISize::Make(1, 1));
     insertCache(SkISize::Make(2, 2));
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
 
     OwnPtr<ImageDecoder> decoder = MockImageDecoder::create(this);
     decoder->setSize(1, 1);
     ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder.release(), false);
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
 
     ImageDecodingStore::instance()->clear();
-    EXPECT_EQ(0u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(0, ImageDecodingStore::instance()->cacheEntries());
 }
 
 TEST_F(ImageDecodingStoreTest, clearInUse)
 {
     insertCache(SkISize::Make(1, 1));
     insertCache(SkISize::Make(2, 2));
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
 
     const ScaledImageFragment* cachedImage = lockCache(SkISize::Make(1, 1));
     ASSERT_TRUE(cachedImage);
     ImageDecodingStore::instance()->clear();
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
 
     unlockCache(cachedImage);
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->cacheEntries());
 }
 
 } // namespace
diff --git a/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp b/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
index 2c41125..c5e9f6c 100644
--- a/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
+++ b/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
@@ -26,10 +26,12 @@
 #include "config.h"
 #include "core/platform/graphics/chromium/ImageFrameGenerator.h"
 
-#include "platform/SharedBuffer.h"
 #include "core/platform/graphics/chromium/ImageDecodingStore.h"
 #include "core/platform/graphics/chromium/test/MockImageDecoder.h"
-#include "wtf/Threading.h"
+#include "platform/SharedBuffer.h"
+#include "platform/Task.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebThread.h"
 #include <gtest/gtest.h>
 
 namespace WebCore {
@@ -198,18 +200,18 @@
     EXPECT_FALSE(tempImage->isComplete());
     EXPECT_EQ(1, m_frameBufferRequestCount);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->decoderCacheEntries());
 
     addNewData();
     tempImage = m_generator->decodeAndScale(fullSize());
     EXPECT_FALSE(tempImage->isComplete());
     EXPECT_EQ(2, m_frameBufferRequestCount);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->decoderCacheEntries());
     EXPECT_EQ(0, m_decodersDestroyed);
 }
 
@@ -221,18 +223,18 @@
     EXPECT_FALSE(tempImage->isComplete());
     EXPECT_EQ(1, m_frameBufferRequestCount);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->decoderCacheEntries());
 
     addNewData();
     tempImage = m_generator->decodeAndScale(scaledSize());
     EXPECT_FALSE(tempImage->isComplete());
     EXPECT_EQ(2, m_frameBufferRequestCount);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-    EXPECT_EQ(5u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(4u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(5, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(4, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->decoderCacheEntries());
     EXPECT_EQ(0, m_decodersDestroyed);
 }
 
@@ -245,9 +247,9 @@
     EXPECT_EQ(1, m_frameBufferRequestCount);
     EXPECT_EQ(0, m_decodersDestroyed);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->decoderCacheEntries());
 
     setFrameStatus(ImageFrame::FrameComplete);
     addNewData();
@@ -257,9 +259,9 @@
     EXPECT_EQ(2, m_frameBufferRequestCount);
     EXPECT_EQ(1, m_decodersDestroyed);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(0u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(0, ImageDecodingStore::instance()->decoderCacheEntries());
 
     tempImage = m_generator->decodeAndScale(fullSize());
     EXPECT_TRUE(tempImage->isComplete());
@@ -276,9 +278,9 @@
     EXPECT_EQ(1, m_frameBufferRequestCount);
     EXPECT_EQ(0, m_decodersDestroyed);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->decoderCacheEntries());
 
     setFrameStatus(ImageFrame::FrameComplete);
     addNewData();
@@ -288,9 +290,9 @@
     EXPECT_EQ(2, m_frameBufferRequestCount);
     EXPECT_EQ(1, m_decodersDestroyed);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-    EXPECT_EQ(4u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(4u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(0u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(4, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(4, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(0, ImageDecodingStore::instance()->decoderCacheEntries());
 
     tempImage = m_generator->decodeAndScale(scaledSize());
     EXPECT_TRUE(tempImage->isComplete());
@@ -303,9 +305,8 @@
     EXPECT_EQ(2, m_frameBufferRequestCount);
 }
 
-static void decodeThreadMain(void* arg)
+static void decodeThreadMain(ImageFrameGenerator* generator)
 {
-    ImageFrameGenerator* generator = reinterpret_cast<ImageFrameGenerator*>(arg);
     const ScaledImageFragment* tempImage = generator->decodeAndScale(fullSize());
     ImageDecodingStore::instance()->unlockCache(generator, tempImage);
 }
@@ -319,21 +320,22 @@
     EXPECT_EQ(1, m_frameBufferRequestCount);
     EXPECT_EQ(0, m_decodersDestroyed);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->decoderCacheEntries());
 
     // Frame can now be decoded completely.
     setFrameStatus(ImageFrame::FrameComplete);
     addNewData();
-    ThreadIdentifier threadID = createThread(&decodeThreadMain, m_generator.get(), "DecodeThread");
-    waitForThreadCompletion(threadID);
+    OwnPtr<WebKit::WebThread> thread = adoptPtr(WebKit::Platform::current()->createThread("DecodeThread"));
+    thread->postTask(new Task(WTF::bind(&decodeThreadMain, m_generator.get())));
+    thread.clear();
 
     EXPECT_EQ(2, m_frameBufferRequestCount);
     EXPECT_EQ(1, m_decodersDestroyed);
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(0u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(2, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(0, ImageDecodingStore::instance()->decoderCacheEntries());
 
     tempImage = m_generator->decodeAndScale(fullSize());
     EXPECT_TRUE(tempImage->isComplete());
@@ -352,9 +354,9 @@
     EXPECT_EQ(2, m_frameBufferRequestCount);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), fullImage);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), scaledImage);
-    EXPECT_EQ(4u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(3u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(4, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(3, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(1, ImageDecodingStore::instance()->decoderCacheEntries());
     EXPECT_EQ(0, m_decodersDestroyed);
 
     addNewData();
@@ -363,9 +365,9 @@
     EXPECT_TRUE(scaledImage->isComplete());
     EXPECT_EQ(3, m_frameBufferRequestCount);
     ImageDecodingStore::instance()->unlockCache(m_generator.get(), scaledImage);
-    EXPECT_EQ(5u, ImageDecodingStore::instance()->cacheEntries());
-    EXPECT_EQ(5u, ImageDecodingStore::instance()->imageCacheEntries());
-    EXPECT_EQ(0u, ImageDecodingStore::instance()->decoderCacheEntries());
+    EXPECT_EQ(5, ImageDecodingStore::instance()->cacheEntries());
+    EXPECT_EQ(5, ImageDecodingStore::instance()->imageCacheEntries());
+    EXPECT_EQ(0, ImageDecodingStore::instance()->decoderCacheEntries());
     EXPECT_EQ(1, m_decodersDestroyed);
 }
 
diff --git a/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp b/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp
index 0e9d41d..3f26a13 100644
--- a/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp
@@ -38,8 +38,8 @@
 #include <unicode/unorm.h>
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
+#include "platform/fonts/FontDescription.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/win/HWndDC.h"
 #include "wtf/MathExtras.h"
diff --git a/Source/core/platform/graphics/chromium/UniscribeHelper.cpp b/Source/core/platform/graphics/chromium/UniscribeHelper.cpp
index 9354c46..4695f93 100644
--- a/Source/core/platform/graphics/chromium/UniscribeHelper.cpp
+++ b/Source/core/platform/graphics/chromium/UniscribeHelper.cpp
@@ -34,7 +34,7 @@
 #include <windows.h>
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
+#include "core/platform/graphics/chromium/FontFallbackWin.h"
 #include "core/platform/graphics/skia/SkiaFontWin.h"
 #include "platform/win/HWndDC.h"
 #include "third_party/skia/include/core/SkPoint.h"
@@ -80,6 +80,27 @@
     gOpenTypeFunctionsLoaded = true;
 }
 
+enum {
+    FontStyleNormal = 0,
+    FontStyleBold = 1,
+    FontStyleItalic = 2,
+    FontStyleUnderlined = 4
+};
+
+int getStyleFromLogfont(const LOGFONT* logfont)
+{
+    // FIXME: consider defining UNDEFINED or INVALID for style and
+    //                  returning it when logfont is 0
+    if (!logfont) {
+        ASSERT_NOT_REACHED();
+        return FontStyleNormal;
+    }
+    return (logfont->lfItalic ? FontStyleItalic : FontStyleNormal) |
+        (logfont->lfUnderline ? FontStyleUnderlined : FontStyleNormal) |
+        (logfont->lfWeight >= 700 ? FontStyleBold : FontStyleNormal);
+}
+
+
 // HFONT is the 'incarnation' of 'everything' about font, but it's an opaque
 // handle and we can't directly query it to make a new HFONT sharing
 // its characteristics (height, style, etc) except for family name.
@@ -587,6 +608,124 @@
     }
 }
 
+const int kUndefinedAscent = std::numeric_limits<int>::min();
+
+// Given an HFONT, return the ascent. If GetTextMetrics fails,
+// kUndefinedAscent is returned, instead.
+int getAscent(HFONT hfont)
+{
+    HWndDC dc(0);
+    HGDIOBJ oldFont = SelectObject(dc, hfont);
+    TEXTMETRIC tm;
+    BOOL gotMetrics = GetTextMetrics(dc, &tm);
+    SelectObject(dc, oldFont);
+    return gotMetrics ? tm.tmAscent : kUndefinedAscent;
+}
+
+const WORD kUnsupportedGlyph = 0xffff;
+
+WORD getSpaceGlyph(HFONT hfont)
+{
+    HWndDC dc(0);
+    HGDIOBJ oldFont = SelectObject(dc, hfont);
+    WCHAR space = L' ';
+    WORD spaceGlyph = kUnsupportedGlyph;
+    GetGlyphIndices(dc, &space, 1, &spaceGlyph, GGI_MARK_NONEXISTING_GLYPHS);
+    SelectObject(dc, oldFont);
+    return spaceGlyph;
+}
+
+struct ShaperFontData {
+    ShaperFontData()
+        : hfont(0)
+        , ascent(kUndefinedAscent)
+        , scriptCache(0)
+        , spaceGlyph(0)
+    {
+    }
+
+    HFONT hfont;
+    int ascent;
+    mutable SCRIPT_CACHE scriptCache;
+    WORD spaceGlyph;
+};
+
+// Again, using hash_map does not earn us much here. page_cycler_test intl2
+// gave us a 'better' result with map than with hash_map even though they're
+// well-within 1-sigma of each other so that the difference is not significant.
+// On the other hand, some pages in intl2 seem to take longer to load with map
+// in the 1st pass. Need to experiment further.
+typedef HashMap<String, ShaperFontData> ShaperFontDataCache;
+
+// Derive a new HFONT by replacing lfFaceName of LOGFONT with |family|,
+// calculate the ascent for the derived HFONT, and initialize SCRIPT_CACHE
+// in ShaperFontData.
+// |style| is only used for cache key generation. |style| is
+// bit-wise OR of BOLD(1), UNDERLINED(2) and ITALIC(4) and
+// should match what's contained in LOGFONT. It should be calculated
+// by calling GetStyleFromLogFont.
+// Returns false if the font is not accessible, in which case |ascent| field
+// of |ShaperFontData| is set to kUndefinedAscent.
+// Be aware that this is not thread-safe.
+// FIXME: Instead of having three out params, we'd better have one
+// (|*ShaperFontData|), but somehow it mysteriously messes up the layout for
+// certain complex script pages (e.g. hi.wikipedia.org) and also crashes
+// at the start-up if recently visited page list includes pages with complex
+// scripts in their title. Moreover, somehow the very first-pass of
+// intl2 page-cycler test is noticeably slower with one out param than
+// the current version although the subsequent 9 passes take about the
+// same time.
+// Be aware that this is not thread-safe.
+static bool getDerivedFontData(const UChar* family, int style, LOGFONT* logfont,
+    int* ascent, HFONT* hfont, SCRIPT_CACHE** scriptCache, WORD* spaceGlyph)
+{
+    ASSERT(logfont);
+    ASSERT(family);
+    ASSERT(*family);
+
+    // It does not matter that we leak font data when we exit.
+    static ShaperFontDataCache* gFontDataCache = 0;
+    if (!gFontDataCache)
+        gFontDataCache = new ShaperFontDataCache();
+
+    // FIXME: This comes up pretty high in the profile so that
+    // we need to measure whether using SHA256 (after coercing all the
+    // fields to char*) is faster than String::format.
+    String fontKey = String::format("%1d:%d:%ls", style, logfont->lfHeight, family);
+    ShaperFontDataCache::iterator iter = gFontDataCache->find(fontKey);
+    ShaperFontData* derived;
+    if (iter == gFontDataCache->end()) {
+        ASSERT(wcslen(family) < LF_FACESIZE);
+        wcscpy_s(logfont->lfFaceName, LF_FACESIZE, family);
+        // FIXME: CreateFontIndirect always comes up with
+        // a font even if there's no font matching the name. Need to
+        // check it against what we actually want (as is done in
+        // FontCacheWin.cpp)
+        ShaperFontDataCache::AddResult entry = gFontDataCache->add(fontKey, ShaperFontData());
+        derived = &entry.iterator->value;
+        derived->hfont = CreateFontIndirect(logfont);
+        // GetAscent may return kUndefinedAscent, but we still want to
+        // cache it so that we won't have to call CreateFontIndirect once
+        // more for HFONT next time.
+        derived->ascent = getAscent(derived->hfont);
+        derived->spaceGlyph = getSpaceGlyph(derived->hfont);
+    } else {
+        derived = &iter->value;
+        // Last time, getAscent or getSpaceGlyph failed so that only HFONT was
+        // cached. Try once more assuming that TryPreloadFont
+        // was called by a caller between calls.
+        if (kUndefinedAscent == derived->ascent)
+            derived->ascent = getAscent(derived->hfont);
+        if (kUnsupportedGlyph == derived->spaceGlyph)
+            derived->spaceGlyph = getSpaceGlyph(derived->hfont);
+    }
+    *hfont = derived->hfont;
+    *ascent = derived->ascent;
+    *scriptCache = &(derived->scriptCache);
+    *spaceGlyph = derived->spaceGlyph;
+    return *ascent != kUndefinedAscent && *spaceGlyph != kUnsupportedGlyph;
+}
+
 bool UniscribeHelper::shape(const UChar* input,
                             int itemLength,
                             int numGlyphs,
@@ -702,8 +841,8 @@
 
             // TODO(jungshik): generic type should come from webkit for
             // UniscribeHelperTextRun (a derived class used in webkit).
-            const UChar *family = getFallbackFamily(input, itemLength,
-                FontDescription::StandardFamily, 0, 0);
+            const UChar *family = getFallbackFamilyForFirstNonCommonCharacter(input, itemLength,
+                FontDescription::StandardFamily);
             bool fontOk = getDerivedFontData(family, m_style, &m_logfont,
                                              &ascent, &hfont, &scriptCache,
                                              &spaceGlyph);
diff --git a/Source/core/platform/graphics/filters/FEBlend.cpp b/Source/core/platform/graphics/filters/FEBlend.cpp
index 838e39e..11d8f79 100644
--- a/Source/core/platform/graphics/filters/FEBlend.cpp
+++ b/Source/core/platform/graphics/filters/FEBlend.cpp
@@ -246,7 +246,8 @@
     RefPtr<SkImageFilter> foreground(builder->build(inputEffect(0), operatingColorSpace()));
     RefPtr<SkImageFilter> background(builder->build(inputEffect(1), operatingColorSpace()));
     SkAutoTUnref<SkXfermode> mode(SkXfermode::Create(toSkiaMode(m_mode)));
-    return adoptRef(new SkXfermodeImageFilter(mode, background.get(), foreground.get()));
+    SkImageFilter::CropRect cropRect = getCropRect(builder->cropOffset());
+    return adoptRef(new SkXfermodeImageFilter(mode, background.get(), foreground.get(), &cropRect));
 }
 
 static TextStream& operator<<(TextStream& ts, const BlendModeType& type)
diff --git a/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp b/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
index 0112c0a..3a4ebcc 100644
--- a/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
+++ b/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
@@ -529,7 +529,8 @@
     OwnPtr<SkScalar[]> kernel = adoptArrayPtr(new SkScalar[numElements]);
     for (int i = 0; i < numElements; ++i)
         kernel[i] = SkFloatToScalar(m_kernelMatrix[numElements - 1 - i]);
-    return adoptRef(new SkMatrixConvolutionImageFilter(kernelSize, kernel.get(), gain, bias, target, tileMode, convolveAlpha, input.get()));
+    SkImageFilter::CropRect cropRect = getCropRect(builder->cropOffset());
+    return adoptRef(new SkMatrixConvolutionImageFilter(kernelSize, kernel.get(), gain, bias, target, tileMode, convolveAlpha, input.get(), &cropRect));
 }
 
 static TextStream& operator<<(TextStream& ts, const EdgeModeType& type)
diff --git a/Source/core/platform/graphics/filters/FEDropShadow.cpp b/Source/core/platform/graphics/filters/FEDropShadow.cpp
index f2e840d..42edd8b 100644
--- a/Source/core/platform/graphics/filters/FEDropShadow.cpp
+++ b/Source/core/platform/graphics/filters/FEDropShadow.cpp
@@ -53,7 +53,7 @@
 void FEDropShadow::determineAbsolutePaintRect()
 {
     Filter* filter = this->filter();
-    ASSERT(filter);
+    ASSERT_UNUSED(filter, filter);
 
     FloatRect absolutePaintRect = mapRect(inputEffect(0)->absolutePaintRect());
 
diff --git a/Source/core/platform/graphics/filters/FEDropShadow.h b/Source/core/platform/graphics/filters/FEDropShadow.h
index 36cd2b1..8d3b0be 100644
--- a/Source/core/platform/graphics/filters/FEDropShadow.h
+++ b/Source/core/platform/graphics/filters/FEDropShadow.h
@@ -21,9 +21,9 @@
 #ifndef FEDropShadow_h
 #define FEDropShadow_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/Color.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/filters/FEFlood.h b/Source/core/platform/graphics/filters/FEFlood.h
index 633fc98..35e102c 100644
--- a/Source/core/platform/graphics/filters/FEFlood.h
+++ b/Source/core/platform/graphics/filters/FEFlood.h
@@ -23,9 +23,9 @@
 #ifndef FEFlood_h
 #define FEFlood_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/Color.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/filters/FELighting.h b/Source/core/platform/graphics/filters/FELighting.h
index de73e83..6b4e476 100644
--- a/Source/core/platform/graphics/filters/FELighting.h
+++ b/Source/core/platform/graphics/filters/FELighting.h
@@ -28,12 +28,12 @@
 #ifndef FELighting_h
 #define FELighting_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/graphics/filters/FilterEffect.h"
 #include "core/platform/graphics/filters/LightSource.h"
 #include "core/platform/graphics/filters/PointLightSource.h"
 #include "core/platform/graphics/filters/SpotLightSource.h"
+#include "platform/graphics/Color.h"
 #include "wtf/Uint8ClampedArray.h"
 
 // Common base class for FEDiffuseLighting and FESpecularLighting
diff --git a/Source/core/platform/graphics/filters/FilterEffect.h b/Source/core/platform/graphics/filters/FilterEffect.h
index 44dd7d6..ffe05d9 100644
--- a/Source/core/platform/graphics/filters/FilterEffect.h
+++ b/Source/core/platform/graphics/filters/FilterEffect.h
@@ -23,9 +23,9 @@
 #ifndef FilterEffect_h
 #define FilterEffect_h
 
-#include "core/platform/graphics/ColorSpace.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/graphics/ColorSpace.h"
 
 #include "third_party/skia/include/core/SkImageFilter.h"
 
diff --git a/Source/core/platform/graphics/filters/FilterOperation.cpp b/Source/core/platform/graphics/filters/FilterOperation.cpp
index 34ae228..de27ba4 100644
--- a/Source/core/platform/graphics/filters/FilterOperation.cpp
+++ b/Source/core/platform/graphics/filters/FilterOperation.cpp
@@ -31,121 +31,133 @@
 
 namespace WebCore {
 
-PassRefPtr<FilterOperation> BasicColorMatrixFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
+PassRefPtr<FilterOperation> FilterOperation::blend(const FilterOperation* from, const FilterOperation* to, double progress)
 {
-    if (from && !from->isSameType(*this))
-        return this;
-
-    if (blendToPassthrough)
-        return BasicColorMatrixFilterOperation::create(WebCore::blend(m_amount, passthroughAmount(), progress), m_type);
-
-    const BasicColorMatrixFilterOperation* fromOp = static_cast<const BasicColorMatrixFilterOperation*>(from);
-    double fromAmount = fromOp ? fromOp->amount() : passthroughAmount();
-    return BasicColorMatrixFilterOperation::create(WebCore::blend(fromAmount, m_amount, progress), m_type);
+    ASSERT(from || to);
+    if (to)
+        return to->blend(from, progress);
+    return from->blend(0, 1 - progress);
 }
 
-double BasicColorMatrixFilterOperation::passthroughAmount() const
+PassRefPtr<FilterOperation> BasicColorMatrixFilterOperation::blend(const FilterOperation* from, double progress) const
 {
+    double fromAmount;
+    if (from) {
+        ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
+        fromAmount = static_cast<const BasicColorMatrixFilterOperation*>(from)->amount();
+    } else {
+        switch (m_type) {
+        case GRAYSCALE:
+        case SEPIA:
+        case HUE_ROTATE:
+            fromAmount = 0;
+            break;
+        case SATURATE:
+            fromAmount = 1;
+            break;
+        default:
+            fromAmount = 0;
+            ASSERT_NOT_REACHED();
+        }
+    }
+
+    double result = WebCore::blend(fromAmount, m_amount, progress);
     switch (m_type) {
+    case HUE_ROTATE:
+        break;
     case GRAYSCALE:
     case SEPIA:
-    case HUE_ROTATE:
-        return 0;
+        result = clampTo<double>(result, 0, 1);
+        break;
     case SATURATE:
-        return 1;
+        result = clampTo<double>(result, 0);
+        break;
     default:
         ASSERT_NOT_REACHED();
-        return 0;
     }
+    return BasicColorMatrixFilterOperation::create(result, m_type);
 }
 
-PassRefPtr<FilterOperation> BasicComponentTransferFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
+PassRefPtr<FilterOperation> BasicComponentTransferFilterOperation::blend(const FilterOperation* from, double progress) const
 {
-    if (from && !from->isSameType(*this))
-        return this;
+    double fromAmount;
+    if (from) {
+        ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
+        fromAmount = static_cast<const BasicComponentTransferFilterOperation*>(from)->amount();
+    } else {
+        switch (m_type) {
+        case OPACITY:
+        case CONTRAST:
+        case BRIGHTNESS:
+            fromAmount = 1;
+            break;
+        case INVERT:
+            fromAmount = 0;
+            break;
+        default:
+            fromAmount = 0;
+            ASSERT_NOT_REACHED();
+        }
+    }
 
-    if (blendToPassthrough)
-        return BasicComponentTransferFilterOperation::create(WebCore::blend(m_amount, passthroughAmount(), progress), m_type);
-
-    const BasicComponentTransferFilterOperation* fromOp = static_cast<const BasicComponentTransferFilterOperation*>(from);
-    double fromAmount = fromOp ? fromOp->amount() : passthroughAmount();
-    return BasicComponentTransferFilterOperation::create(WebCore::blend(fromAmount, m_amount, progress), m_type);
-}
-
-double BasicComponentTransferFilterOperation::passthroughAmount() const
-{
+    double result = WebCore::blend(fromAmount, m_amount, progress);
     switch (m_type) {
-    case OPACITY:
-        return 1;
-    case INVERT:
-        return 0;
-    case CONTRAST:
-        return 1;
     case BRIGHTNESS:
-        return 1;
+    case CONTRAST:
+        result = clampTo<double>(result, 0);
+        break;
+    case INVERT:
+    case OPACITY:
+        result = clampTo<double>(result, 0, 1);
+        break;
     default:
         ASSERT_NOT_REACHED();
-        return 0;
     }
+    return BasicComponentTransferFilterOperation::create(result, m_type);
 }
 
-PassRefPtr<FilterOperation> GammaFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
+PassRefPtr<FilterOperation> GammaFilterOperation::blend(const FilterOperation* from, double progress) const
 {
-    if (from && !from->isSameType(*this))
-        return this;
-
-    if (blendToPassthrough)
+    if (!from)
         return GammaFilterOperation::create(
             WebCore::blend(m_amplitude, 1.0, progress),
             WebCore::blend(m_exponent, 1.0, progress),
             WebCore::blend(m_offset, 0.0, progress), m_type);
 
+    ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
     const GammaFilterOperation* fromOp = static_cast<const GammaFilterOperation*>(from);
-    double fromAmplitude = fromOp ? fromOp->amplitude() : 1;
-    double fromExponent = fromOp ? fromOp->exponent() : 1;
-    double fromOffset = fromOp ? fromOp->offset() : 0;
     return GammaFilterOperation::create(
-        WebCore::blend(fromAmplitude, m_amplitude, progress),
-        WebCore::blend(fromExponent, m_exponent, progress),
-        WebCore::blend(fromOffset, m_offset, progress), m_type);
+        WebCore::blend(fromOp->amplitude(), m_amplitude, progress),
+        WebCore::blend(fromOp->exponent(), m_exponent, progress),
+        WebCore::blend(fromOp->offset(), m_offset, progress), m_type);
 }
 
-PassRefPtr<FilterOperation> BlurFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
+PassRefPtr<FilterOperation> BlurFilterOperation::blend(const FilterOperation* from, double progress) const
 {
-    if (from && !from->isSameType(*this))
-        return this;
-
     LengthType lengthType = m_stdDeviation.type();
+    if (!from)
+        return BlurFilterOperation::create(m_stdDeviation.blend(Length(lengthType), progress, ValueRangeNonNegative), m_type);
 
-    if (blendToPassthrough)
-        return BlurFilterOperation::create(Length(lengthType).blend(m_stdDeviation, progress, ValueRangeNonNegative), m_type);
-
+    ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
     const BlurFilterOperation* fromOp = static_cast<const BlurFilterOperation*>(from);
-    Length fromLength = fromOp ? fromOp->m_stdDeviation : Length(lengthType);
-    return BlurFilterOperation::create(m_stdDeviation.blend(fromLength, progress, ValueRangeNonNegative), m_type);
+    return BlurFilterOperation::create(m_stdDeviation.blend(fromOp->m_stdDeviation, progress, ValueRangeNonNegative), m_type);
 }
 
-PassRefPtr<FilterOperation> DropShadowFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
+PassRefPtr<FilterOperation> DropShadowFilterOperation::blend(const FilterOperation* from, double progress) const
 {
-    if (from && !from->isSameType(*this))
-        return this;
-
-    if (blendToPassthrough)
+    if (!from)
         return DropShadowFilterOperation::create(
-            WebCore::blend(m_location, IntPoint(), progress),
-            WebCore::blend(m_stdDeviation, 0, progress),
-            WebCore::blend(m_color, Color(Color::transparent), progress),
+            WebCore::blend(IntPoint(), m_location, progress),
+            WebCore::blend(0, m_stdDeviation, progress),
+            WebCore::blend(Color(Color::transparent), m_color, progress),
             m_type);
 
+    ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
     const DropShadowFilterOperation* fromOp = static_cast<const DropShadowFilterOperation*>(from);
-    IntPoint fromLocation = fromOp ? fromOp->location() : IntPoint();
-    int fromStdDeviation = fromOp ? fromOp->stdDeviation() : 0;
-    Color fromColor = fromOp ? fromOp->color() : Color(Color::transparent);
-
     return DropShadowFilterOperation::create(
-        WebCore::blend(fromLocation, m_location, progress),
-        WebCore::blend(fromStdDeviation, m_stdDeviation, progress),
-        WebCore::blend(fromColor, m_color, progress), m_type);
+        WebCore::blend(fromOp->location(), m_location, progress),
+        WebCore::blend(fromOp->stdDeviation(), m_stdDeviation, progress),
+        WebCore::blend(fromOp->color(), m_color, progress), m_type);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/filters/FilterOperation.h b/Source/core/platform/graphics/filters/FilterOperation.h
index 9b3d21d..6b83c6e 100644
--- a/Source/core/platform/graphics/filters/FilterOperation.h
+++ b/Source/core/platform/graphics/filters/FilterOperation.h
@@ -27,20 +27,15 @@
 #define FilterOperation_h
 
 #include "core/fetch/DocumentResourceReference.h"
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/graphics/filters/ReferenceFilter.h"
 #include "platform/Length.h"
+#include "platform/graphics/Color.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
-// Annoyingly, wingdi.h #defines this.
-#ifdef PASSTHROUGH
-#undef PASSTHROUGH
-#endif
-
 namespace WebCore {
 
 // CSS Filters
@@ -61,20 +56,40 @@
         DROP_SHADOW,
         CUSTOM,
         VALIDATED_CUSTOM,
-        PASSTHROUGH,
         NONE
     };
 
+    static bool canInterpolate(FilterOperation::OperationType type)
+    {
+        switch (type) {
+        case GRAYSCALE:
+        case SEPIA:
+        case SATURATE:
+        case HUE_ROTATE:
+        case INVERT:
+        case OPACITY:
+        case BRIGHTNESS:
+        case CONTRAST:
+        case BLUR:
+        case DROP_SHADOW:
+        case CUSTOM:
+        case VALIDATED_CUSTOM:
+            return true;
+        case REFERENCE:
+            return false;
+        case NONE:
+            break;
+        }
+        ASSERT_NOT_REACHED();
+        return false;
+    }
+
     virtual ~FilterOperation() { }
 
+    static PassRefPtr<FilterOperation> blend(const FilterOperation* from, const FilterOperation* to, double progress);
     virtual bool operator==(const FilterOperation&) const = 0;
     bool operator!=(const FilterOperation& o) const { return !(*this == o); }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* /*from*/, double /*progress*/, bool /*blendToPassthrough*/ = false)
-    {
-        return 0;
-    }
-
     virtual OperationType getOperationType() const { return m_type; }
     virtual bool isSameType(const FilterOperation& o) const { return o.getOperationType() == m_type; }
 
@@ -92,6 +107,9 @@
     }
 
     OperationType m_type;
+
+private:
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const = 0;
 };
 
 class DefaultFilterOperation : public FilterOperation {
@@ -102,6 +120,11 @@
     }
 
 private:
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation*, double) const OVERRIDE
+    {
+        ASSERT_NOT_REACHED();
+        return 0;
+    }
 
     virtual bool operator==(const FilterOperation& o) const
     {
@@ -116,26 +139,6 @@
     }
 };
 
-class PassthroughFilterOperation : public FilterOperation {
-public:
-    static PassRefPtr<PassthroughFilterOperation> create()
-    {
-        return adoptRef(new PassthroughFilterOperation());
-    }
-
-private:
-
-    virtual bool operator==(const FilterOperation& o) const
-    {
-        return isSameType(o);
-    }
-
-    PassthroughFilterOperation()
-        : FilterOperation(PASSTHROUGH)
-    {
-    }
-};
-
 class ReferenceFilterOperation : public FilterOperation {
 public:
     static PassRefPtr<ReferenceFilterOperation> create(const String& url, const String& fragment, OperationType type)
@@ -156,6 +159,11 @@
     void setFilter(PassRefPtr<ReferenceFilter> filter) { m_filter = filter; }
 
 private:
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const OVERRIDE
+    {
+        ASSERT_NOT_REACHED();
+        return 0;
+    }
 
     virtual bool operator==(const FilterOperation& o) const
     {
@@ -189,9 +197,9 @@
 
     double amount() const { return m_amount; }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
 
 private:
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const OVERRIDE;
     virtual bool operator==(const FilterOperation& o) const
     {
         if (!isSameType(o))
@@ -200,8 +208,6 @@
         return m_amount == other->m_amount;
     }
 
-    double passthroughAmount() const;
-
     BasicColorMatrixFilterOperation(double amount, OperationType type)
         : FilterOperation(type)
         , m_amount(amount)
@@ -223,9 +229,9 @@
 
     virtual bool affectsOpacity() const { return m_type == OPACITY; }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
 
 private:
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const OVERRIDE;
     virtual bool operator==(const FilterOperation& o) const
     {
         if (!isSameType(o))
@@ -234,8 +240,6 @@
         return m_amount == other->m_amount;
     }
 
-    double passthroughAmount() const;
-
     BasicComponentTransferFilterOperation(double amount, OperationType type)
         : FilterOperation(type)
         , m_amount(amount)
@@ -256,9 +260,9 @@
     double exponent() const { return m_exponent; }
     double offset() const { return m_offset; }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
 
 private:
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const OVERRIDE;
     virtual bool operator==(const FilterOperation& o) const
     {
         if (!isSameType(o))
@@ -292,9 +296,9 @@
     virtual bool affectsOpacity() const { return true; }
     virtual bool movesPixels() const { return true; }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
 
 private:
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const OVERRIDE;
     virtual bool operator==(const FilterOperation& o) const
     {
         if (!isSameType(o))
@@ -328,10 +332,9 @@
     virtual bool affectsOpacity() const { return true; }
     virtual bool movesPixels() const { return true; }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
 
 private:
-
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const OVERRIDE;
     virtual bool operator==(const FilterOperation& o) const
     {
         if (!isSameType(o))
diff --git a/Source/core/platform/graphics/filters/FilterOperations.cpp b/Source/core/platform/graphics/filters/FilterOperations.cpp
index 8390910..768a8cf 100644
--- a/Source/core/platform/graphics/filters/FilterOperations.cpp
+++ b/Source/core/platform/graphics/filters/FilterOperations.cpp
@@ -70,15 +70,20 @@
     return true;
 }
 
-bool FilterOperations::operationsMatch(const FilterOperations& other) const
+bool FilterOperations::canInterpolateWith(const FilterOperations& other) const
 {
-    size_t numOperations = operations().size();
-    // If the sizes of the function lists don't match, the lists don't match
-    if (numOperations != other.operations().size())
-        return false;
+    for (size_t i = 0; i < operations().size(); ++i) {
+        if (!FilterOperation::canInterpolate(operations()[i]->getOperationType()))
+            return false;
+    }
 
-    // If the types of each function are not the same, the lists don't match
-    for (size_t i = 0; i < numOperations; ++i) {
+    for (size_t i = 0; i < other.operations().size(); ++i) {
+        if (!FilterOperation::canInterpolate(other.operations()[i]->getOperationType()))
+            return false;
+    }
+
+    size_t commonSize = std::min(operations().size(), other.operations().size());
+    for (size_t i = 0; i < commonSize; ++i) {
         if (!operations()[i]->isSameType(*other.operations()[i]))
             return false;
     }
diff --git a/Source/core/platform/graphics/filters/FilterOperations.h b/Source/core/platform/graphics/filters/FilterOperations.h
index 22064be..44556d1 100644
--- a/Source/core/platform/graphics/filters/FilterOperations.h
+++ b/Source/core/platform/graphics/filters/FilterOperations.h
@@ -61,7 +61,7 @@
     size_t size() const { return m_operations.size(); }
     const FilterOperation* at(size_t index) const { return index < m_operations.size() ? m_operations.at(index).get() : 0; }
 
-    bool operationsMatch(const FilterOperations&) const;
+    bool canInterpolateWith(const FilterOperations&) const;
 
     bool hasOutsets() const;
     FilterOutsets outsets() const;
diff --git a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
index 9527d6a..9d5f88f 100644
--- a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
+++ b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
@@ -185,7 +185,6 @@
         case FilterOperation::VALIDATED_CUSTOM:
         case FilterOperation::CUSTOM:
             return false; // Not supported.
-        case FilterOperation::PASSTHROUGH:
         case FilterOperation::NONE:
             break;
         }
diff --git a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
index 9fdf34a..b798f16 100644
--- a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
+++ b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
@@ -26,8 +26,8 @@
 #ifndef SkiaImageFilterBuilder_h
 #define SkiaImageFilterBuilder_h
 
-#include "core/platform/graphics/ColorSpace.h"
 #include "platform/geometry/FloatSize.h"
+#include "platform/graphics/ColorSpace.h"
 #include "public/platform/WebFilterOperations.h"
 #include "wtf/HashMap.h"
 
diff --git a/Source/core/platform/graphics/filters/SourceAlpha.cpp b/Source/core/platform/graphics/filters/SourceAlpha.cpp
index 4070da6..e963164 100644
--- a/Source/core/platform/graphics/filters/SourceAlpha.cpp
+++ b/Source/core/platform/graphics/filters/SourceAlpha.cpp
@@ -22,10 +22,10 @@
 
 #include "core/platform/graphics/filters/SourceAlpha.h"
 
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/rendering/RenderTreeAsText.h"
+#include "platform/graphics/Color.h"
 #include "platform/text/TextStream.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterMesh.h b/Source/core/platform/graphics/filters/custom/CustomFilterMesh.h
index 045742d..7ef99a9 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterMesh.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterMesh.h
@@ -30,9 +30,9 @@
 #ifndef CustomFilterMesh_h
 #define CustomFilterMesh_h
 
-#include "core/platform/graphics/GraphicsTypes3D.h"
 #include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
 #include "platform/geometry/FloatRect.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/RefCounted.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
index 99aa9db..13369fa 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
@@ -53,20 +53,22 @@
 {
 }
 
-PassRefPtr<FilterOperation> CustomFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
+PassRefPtr<FilterOperation> CustomFilterOperation::blend(const FilterOperation* from, double progress) const
 {
-    // FIXME: There's no way to decide what is the "passthrough filter" for shaders using the current CSS Syntax.
-    // https://bugs.webkit.org/show_bug.cgi?id=84903
-    // https://www.w3.org/Bugs/Public/show_bug.cgi?id=16861
-    if (blendToPassthrough || !from || !from->isSameType(*this))
-        return this;
+    if (!from) {
+        // FIXME: There's no way to decide what is the "passthrough filter" for shaders using the current CSS Syntax.
+        // https://bugs.webkit.org/show_bug.cgi?id=84903
+        // https://www.w3.org/Bugs/Public/show_bug.cgi?id=16861
+        return const_cast<CustomFilterOperation*>(this);
+    }
 
+    ASSERT_WITH_SECURITY_IMPLICATION(from->isSameType(*this));
     const CustomFilterOperation* fromOp = static_cast<const CustomFilterOperation*>(from);
     if (m_program.get() != fromOp->m_program.get()
         || m_meshRows != fromOp->m_meshRows
         || m_meshColumns != fromOp->m_meshColumns
         || m_meshType != fromOp->m_meshType)
-        return this;
+        return const_cast<CustomFilterOperation*>(this);
 
     CustomFilterParameterList animatedParameters;
     m_parameters.blend(fromOp->m_parameters, progress, animatedParameters);
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
index f7aa39f..7f2dfc3 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
@@ -62,12 +62,12 @@
     virtual bool affectsOpacity() const { return true; }
     virtual bool movesPixels() const { return true; }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
 
 protected:
     CustomFilterOperation(PassRefPtr<CustomFilterProgram>, const CustomFilterParameterList&, unsigned meshRows, unsigned meshColumns, CustomFilterMeshType);
 
 private:
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const OVERRIDE;
     virtual bool operator==(const FilterOperation& o) const
     {
         if (!isSameType(o))
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h b/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h
index 60f34c8..165f952 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h
@@ -30,9 +30,8 @@
 #ifndef CustomFilterProgramInfo_h
 #define CustomFilterProgramInfo_h
 
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-
+#include "platform/graphics/GraphicsTypes.h"
 #include "wtf/HashTableDeletedValueType.h"
 #include "wtf/HashTraits.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.h b/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.h
index 828dce8..3d01e59 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.h
@@ -32,10 +32,10 @@
 #ifndef CustomFilterRenderer_h
 #define CustomFilterRenderer_h
 
-#include "core/platform/graphics/GraphicsTypes3D.h"
 #include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
 #include "core/platform/graphics/filters/custom/CustomFilterParameterList.h"
 #include "platform/geometry/IntSize.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h b/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
index 32188fc..98291e1 100644
--- a/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
+++ b/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
@@ -31,8 +31,8 @@
 #define CustomFilterTransformParameter_h
 
 #include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
 #include "platform/geometry/FloatSize.h"
+#include "platform/transforms/TransformOperations.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/filters/custom/FECustomFilter.h b/Source/core/platform/graphics/filters/custom/FECustomFilter.h
index e3d42b2..393620a 100644
--- a/Source/core/platform/graphics/filters/custom/FECustomFilter.h
+++ b/Source/core/platform/graphics/filters/custom/FECustomFilter.h
@@ -31,11 +31,11 @@
 #ifndef FECustomFilter_h
 #define FECustomFilter_h
 
-#include "core/platform/graphics/GraphicsTypes3D.h"
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/graphics/filters/FilterEffect.h"
 #include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
 #include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/RefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp
index c285947..77049b5 100644
--- a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp
+++ b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp
@@ -52,13 +52,10 @@
 {
 }
 
-PassRefPtr<FilterOperation> ValidatedCustomFilterOperation::blend(const FilterOperation*, double progress, bool blendToPassthrough)
+PassRefPtr<FilterOperation> ValidatedCustomFilterOperation::blend(const FilterOperation*, double) const
 {
-    UNUSED_PARAM(progress);
-    UNUSED_PARAM(blendToPassthrough);
-
     ASSERT_NOT_REACHED();
-    return this;
+    return const_cast<ValidatedCustomFilterOperation*>(this);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
index 60b1801..1503365 100644
--- a/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
+++ b/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
@@ -51,7 +51,6 @@
     virtual bool affectsOpacity() const { return true; }
     virtual bool movesPixels() const { return true; }
 
-    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
 
     CustomFilterValidatedProgram* validatedProgram() const { return m_validatedProgram.get(); }
     const CustomFilterParameterList& parameters() const { return m_parameters; }
@@ -62,6 +61,7 @@
     CustomFilterMeshType meshType() const { return m_meshType; }
 
 private:
+    virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress) const OVERRIDE;
     virtual bool operator==(const FilterOperation& o) const
     {
         if (!isSameType(o))
diff --git a/Source/core/platform/graphics/gpu/DrawingBuffer.cpp b/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
index 0c5a28d..b85518d 100644
--- a/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
+++ b/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
@@ -121,6 +121,7 @@
     , m_multisampleFBO(0)
     , m_multisampleColorBuffer(0)
     , m_contentsChanged(true)
+    , m_contentsChangeCommitted(false)
     , m_internalColorFormat(0)
     , m_colorFormat(0)
     , m_internalRenderbufferFormat(0)
@@ -137,6 +138,12 @@
     releaseResources();
 }
 
+void DrawingBuffer::markContentsChanged()
+{
+    m_contentsChanged = true;
+    m_contentsChangeCommitted = false;
+}
+
 WebKit::WebGraphicsContext3D* DrawingBuffer::context()
 {
     if (!m_context)
@@ -289,7 +296,48 @@
 
 unsigned DrawingBuffer::frontColorBuffer() const
 {
-    return m_colorBuffer;
+    return m_frontColorBuffer;
+}
+
+bool DrawingBuffer::copyToPlatformTexture(GraphicsContext3D& context, Platform3DObject texture, GC3Denum internalFormat, GC3Denum destType, GC3Dint level, bool premultiplyAlpha, bool flipY)
+{
+    if (!m_context || !m_context->makeContextCurrent())
+        return false;
+    if (m_contentsChanged) {
+        if (multisample()) {
+            commit();
+            if (!m_framebufferBinding)
+                bind();
+            else
+                restoreFramebufferBinding();
+        }
+        m_context->flush();
+    }
+    Platform3DObject sourceTexture = frontColorBuffer() ? frontColorBuffer() : colorBuffer();
+
+    if (!context.makeContextCurrent())
+        return false;
+    Extensions3D* extensions = context.extensions();
+    if (!extensions->supports("GL_CHROMIUM_copy_texture") || !extensions->supports("GL_CHROMIUM_flipy")
+        || !extensions->canUseCopyTextureCHROMIUM(internalFormat, destType, level))
+        return false;
+
+    bool unpackPremultiplyAlphaNeeded = false;
+    bool unpackUnpremultiplyAlphaNeeded = false;
+    if (m_attributes.alpha && m_attributes.premultipliedAlpha && !premultiplyAlpha)
+        unpackUnpremultiplyAlphaNeeded = true;
+    else if (m_attributes.alpha && !m_attributes.premultipliedAlpha && premultiplyAlpha)
+        unpackPremultiplyAlphaNeeded = true;
+
+    context.pixelStorei(Extensions3D::UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, unpackUnpremultiplyAlphaNeeded);
+    context.pixelStorei(Extensions3D::UNPACK_PREMULTIPLY_ALPHA_CHROMIUM, unpackPremultiplyAlphaNeeded);
+    context.pixelStorei(Extensions3D::UNPACK_FLIP_Y_CHROMIUM, flipY);
+    extensions->copyTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, sourceTexture, texture, level, internalFormat, destType);
+    context.pixelStorei(Extensions3D::UNPACK_FLIP_Y_CHROMIUM, false);
+    context.pixelStorei(Extensions3D::UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, false);
+    context.pixelStorei(Extensions3D::UNPACK_PREMULTIPLY_ALPHA_CHROMIUM, false);
+
+    return true;
 }
 
 Platform3DObject DrawingBuffer::framebuffer() const
@@ -662,7 +710,7 @@
 
     m_context->makeContextCurrent();
 
-    if (m_multisampleFBO) {
+    if (m_multisampleFBO && !m_contentsChangeCommitted) {
         m_context->bindFramebuffer(Extensions3D::READ_FRAMEBUFFER, m_multisampleFBO);
         m_context->bindFramebuffer(Extensions3D::DRAW_FRAMEBUFFER, m_fbo);
 
@@ -677,6 +725,7 @@
     }
 
     m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_fbo);
+    m_contentsChangeCommitted = true;
 }
 
 void DrawingBuffer::restoreFramebufferBinding()
diff --git a/Source/core/platform/graphics/gpu/DrawingBuffer.h b/Source/core/platform/graphics/gpu/DrawingBuffer.h
index e9cfc1c..b327dbd 100644
--- a/Source/core/platform/graphics/gpu/DrawingBuffer.h
+++ b/Source/core/platform/graphics/gpu/DrawingBuffer.h
@@ -32,8 +32,8 @@
 #define DrawingBuffer_h
 
 #include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
 #include "platform/geometry/IntSize.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 
 #include "public/platform/WebExternalTextureLayerClient.h"
 #include "public/platform/WebExternalTextureMailbox.h"
@@ -118,7 +118,7 @@
 
     Platform3DObject framebuffer() const;
 
-    void markContentsChanged() { m_contentsChanged = true; }
+    void markContentsChanged();
 
     WebKit::WebLayer* platformLayer();
     void paintCompositedResultsToCanvas(ImageBuffer*);
@@ -128,6 +128,9 @@
     virtual bool prepareMailbox(WebKit::WebExternalTextureMailbox*, WebKit::WebExternalBitmap*) OVERRIDE;
     virtual void mailboxReleased(const WebKit::WebExternalTextureMailbox&) OVERRIDE;
 
+    bool copyToPlatformTexture(GraphicsContext3D&, Platform3DObject texture, GC3Denum internalFormat,
+        GC3Denum destType, GC3Dint level, bool premultiplyAlpha, bool flipY);
+
 private:
     DrawingBuffer(GraphicsContext3D*, const IntSize&, bool multisampleExtensionSupported,
                   bool packedDepthStencilExtensionSupported, PreserveDrawingBuffer, PassRefPtr<ContextEvictionManager>);
@@ -175,7 +178,6 @@
     Platform3DObject m_fbo;
     Platform3DObject m_colorBuffer;
     Platform3DObject m_frontColorBuffer;
-    bool m_separateFrontTexture;
 
     // This is used when we have OES_packed_depth_stencil.
     Platform3DObject m_depthStencilBuffer;
@@ -191,6 +193,9 @@
     // True if our contents have been modified since the last presentation of this buffer.
     bool m_contentsChanged;
 
+    // True if commit() has been called since the last time markContentsChanged() had been called.
+    bool m_contentsChangeCommitted;
+
     GraphicsContext3D::Attributes m_attributes;
     unsigned m_internalColorFormat;
     unsigned m_colorFormat;
diff --git a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
index 1f1251c..2a0d2cb 100644
--- a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
+++ b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
@@ -33,9 +33,9 @@
 
 #include "SkPaint.h"
 #include "platform/SharedBuffer.h"
-#include "core/platform/graphics/FontOrientation.h"
 #include "core/platform/graphics/chromium/FontRenderStyle.h"
 #include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
+#include "platform/fonts/FontOrientation.h"
 #include "wtf/Forward.h"
 #include "wtf/HashTableDeletedValueType.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
index 2594792..6f3cfb7 100644
--- a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
+++ b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
@@ -74,7 +74,7 @@
 };
 
 
-static const int cHarfBuzzCacheMaxSize = 256;
+static const unsigned cHarfBuzzCacheMaxSize = 256;
 
 struct CachedShapingResultsLRUNode;
 struct CachedShapingResults;
@@ -212,9 +212,9 @@
     : m_fontData(fontData)
     , m_startIndex(startIndex)
     , m_numCharacters(numCharacters)
+    , m_numGlyphs(0)
     , m_direction(direction)
     , m_script(script)
-    , m_numGlyphs(0)
     , m_width(0)
 {
 }
@@ -367,13 +367,9 @@
     setFontFeatures();
 }
 
-HarfBuzzShaper::~HarfBuzzShaper()
-{
-}
-
 static void normalizeSpacesAndMirrorChars(const UChar* source, unsigned length, UChar* destination, unsigned* destinationLength, HarfBuzzShaper::NormalizeMode normalizeMode)
 {
-    int position = 0;
+    unsigned position = 0;
     bool error = false;
     // Iterate characters in source and mirror character if needed.
     *destinationLength = 0;
diff --git a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h
index 5c006bc..54b01bd 100644
--- a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h
+++ b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h
@@ -46,7 +46,7 @@
 class Font;
 class SimpleFontData;
 
-class HarfBuzzShaper {
+class HarfBuzzShaper FINAL {
 public:
     enum NormalizeMode {
         DoNotNormalizeMirrorChars,
@@ -54,7 +54,6 @@
     };
 
     HarfBuzzShaper(const Font*, const TextRun&);
-    virtual ~HarfBuzzShaper();
 
     void setDrawRange(int from, int to);
     bool shape(GlyphBuffer* = 0);
diff --git a/Source/core/platform/graphics/mac/ColorMac.h b/Source/core/platform/graphics/mac/ColorMac.h
index da14b97..24b3648 100644
--- a/Source/core/platform/graphics/mac/ColorMac.h
+++ b/Source/core/platform/graphics/mac/ColorMac.h
@@ -29,7 +29,7 @@
 #ifndef ColorMac_h
 #define ColorMac_h
 
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 
 OBJC_CLASS NSColor;
 
diff --git a/Source/core/platform/graphics/mac/FontMac.cpp b/Source/core/platform/graphics/mac/FontMac.cpp
index 38f747c..5a9a1dd 100644
--- a/Source/core/platform/graphics/mac/FontMac.cpp
+++ b/Source/core/platform/graphics/mac/FontMac.cpp
@@ -31,11 +31,11 @@
 #include "config.h"
 #include "core/platform/graphics/Font.h"
 
-#include "core/platform/graphics/FontSmoothingMode.h"
 #include "core/platform/graphics/GlyphBuffer.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/SimpleFontData.h"
 #include "platform/LayoutTestSupport.h"
+#include "platform/fonts/FontSmoothingMode.h"
 
 #include "third_party/skia/include/core/SkCanvas.h"
 #include "third_party/skia/include/core/SkPaint.h"
diff --git a/Source/core/platform/graphics/mac/SimpleFontDataMac.mm b/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
index df004cf..ab68457 100644
--- a/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
+++ b/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
@@ -32,12 +32,12 @@
 #import <float.h>
 #import <unicode/uchar.h>
 #import "platform/SharedBuffer.h"
-#import "core/platform/graphics/Color.h"
 #import "core/platform/graphics/Font.h"
 #import "core/platform/graphics/FontCache.h"
-#import "core/platform/graphics/FontDescription.h"
 #import "core/platform/mac/BlockExceptions.h"
+#import "platform/fonts/FontDescription.h"
 #import "platform/geometry/FloatRect.h"
+#import "platform/graphics/Color.h"
 #import <wtf/Assertions.h>
 #import <wtf/RetainPtr.h>
 #import <wtf/StdLibExtras.h>
diff --git a/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h b/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h
index bad593e..e1a5fdf 100644
--- a/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h
+++ b/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h
@@ -27,7 +27,7 @@
 
 #if ENABLE(OPENTYPE_VERTICAL)
 
-#include "core/platform/graphics/Glyph.h"
+#include "platform/fonts/Glyph.h"
 #include "wtf/HashMap.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
diff --git a/Source/core/platform/graphics/skia/FontCacheSkia.cpp b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
index 6a04442..33118bc 100644
--- a/Source/core/platform/graphics/skia/FontCacheSkia.cpp
+++ b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
@@ -35,9 +35,9 @@
 #include "core/platform/graphics/AlternateFontFamily.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/SimpleFontData.h"
 #include "platform/NotImplemented.h"
+#include "platform/fonts/FontDescription.h"
 #include "wtf/Assertions.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/CString.h"
diff --git a/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
index a9817a7..7d2ee42 100644
--- a/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
+++ b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
@@ -34,11 +34,12 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "SkFontMgr.h"
+#include "SkTypeface.h"
 #include "SkTypeface_win.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/SimpleFontData.h"
+#include "core/platform/graphics/chromium/FontFallbackWin.h"
 #include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
 
 namespace WebCore {
 
@@ -57,41 +58,23 @@
     m_fontManager = adoptPtr(fontManager);
 }
 
-
-static bool fontContainsCharacter(const FontPlatformData* fontData, const wchar_t* family, UChar32 character)
+static bool fontContainsCharacter(const FontPlatformData* platformData, const wchar_t* family, UChar32 character)
 {
-    SkPaint paint;
-    fontData->setupPaint(&paint);
-    paint.setTextEncoding(SkPaint::kUTF32_TextEncoding);
-
-    uint16_t glyph;
-    paint.textToGlyphs(&character, sizeof(character), &glyph);
-    return glyph != 0;
+    SkTypeface* typeface = platformData->typeface();
+    return typeface->charsToGlyphs(&character, SkTypeface::kUTF32_Encoding, 0 /* glyph */, 1 /* length */) == 1;
 }
 
 // Given the desired base font, this will create a SimpleFontData for a specific
 // font that can be used to render the given range of characters.
-PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 inputC)
+PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, const UChar32 character)
 {
-    // FIXME: We should fix getFallbackFamily to take a UChar32
-    // and remove this split-to-UChar16 code.
-    UChar codeUnits[2];
-    int codeUnitsLength;
-    if (inputC <= 0xFFFF) {
-        codeUnits[0] = inputC;
-        codeUnitsLength = 1;
-    } else {
-        codeUnits[0] = U16_LEAD(inputC);
-        codeUnits[1] = U16_TRAIL(inputC);
-        codeUnitsLength = 2;
-    }
-
     // FIXME: Consider passing fontDescription.dominantScript()
     // to GetFallbackFamily here.
     FontDescription fontDescription = font.fontDescription();
-    UChar32 c;
     UScriptCode script;
-    const wchar_t* family = getFallbackFamily(codeUnits, codeUnitsLength, fontDescription.genericFamily(), &c, &script);
+    const wchar_t* family = getFallbackFamily(character,
+        fontDescription.genericFamily(),
+        &script);
     FontPlatformData* data = 0;
     if (family)
         data = getFontResourcePlatformData(font.fontDescription(),  AtomicString(family, wcslen(family)), false);
@@ -146,12 +129,12 @@
         panUniFonts = commonFonts;
         numFonts = WTF_ARRAY_LENGTH(commonFonts);
     }
-    // Font returned from GetFallbackFamily may not cover |characters|
+    // Font returned from getFallbackFamily may not cover |character|
     // because it's based on script to font mapping. This problem is
     // critical enough for non-Latin scripts (especially Han) to
     // warrant an additional (real coverage) check with fontCotainsCharacter.
     int i;
-    for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) {
+    for (i = 0; (!data || !fontContainsCharacter(data, family, character)) && i < numFonts; ++i) {
         family = panUniFonts[i];
         data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)));
     }
diff --git a/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp b/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
index e6f1915..eaf7581 100644
--- a/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
+++ b/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
@@ -35,6 +35,7 @@
 
 #include "SkPaint.h"
 #include "SkTemplates.h"
+#include "SkTypeface.h"
 #include "SkUtils.h"
 
 namespace WebCore {
@@ -46,10 +47,6 @@
         return false;
     }
 
-    SkPaint paint;
-    fontData->platformData().setupPaint(&paint);
-    paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
-
 #if OS(WIN)
     // FIXME: For some reason SkAutoSTMalloc fails to link on Windows.
     // SkAutoSTArray works fine though...
@@ -59,12 +56,8 @@
 #endif
 
     uint16_t* glyphs = glyphStorage.get();
-    // textToGlyphs takes a byte count, not a glyph count so we multiply by two.
-    unsigned count = paint.textToGlyphs(buffer, bufferLength * 2, glyphs);
-    if (count != length) {
-        SkDebugf("%s count != length\n", __FUNCTION__);
-        return false;
-    }
+    SkTypeface* typeface = fontData->platformData().typeface();
+    typeface->charsToGlyphs(buffer, SkTypeface::kUTF16_Encoding, glyphs, length);
 
     unsigned allGlyphs = 0; // track if any of the glyphIDs are non-zero
     for (unsigned i = 0; i < length; i++) {
diff --git a/Source/core/platform/graphics/skia/NativeImageSkia.h b/Source/core/platform/graphics/skia/NativeImageSkia.h
index f16cdfe..c34c19e 100644
--- a/Source/core/platform/graphics/skia/NativeImageSkia.h
+++ b/Source/core/platform/graphics/skia/NativeImageSkia.h
@@ -35,8 +35,8 @@
 #include "SkRect.h"
 #include "SkSize.h"
 #include "SkXfermode.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "platform/geometry/IntSize.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
diff --git a/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp b/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp
index 11e1454..1c0c1eb 100644
--- a/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp
+++ b/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp
@@ -45,10 +45,6 @@
 {
 }
 
-OpaqueRegionSkia::~OpaqueRegionSkia()
-{
-}
-
 IntRect OpaqueRegionSkia::asRect() const
 {
     // Returns the largest enclosed rect.
diff --git a/Source/core/platform/graphics/skia/OpaqueRegionSkia.h b/Source/core/platform/graphics/skia/OpaqueRegionSkia.h
index 35c63e5..3c06700 100644
--- a/Source/core/platform/graphics/skia/OpaqueRegionSkia.h
+++ b/Source/core/platform/graphics/skia/OpaqueRegionSkia.h
@@ -44,10 +44,9 @@
 
 // This class is an encapsulation of functionality for GraphicsContext, and its methods are mirrored
 // there for the outside world. It tracks paints and computes what area will be opaque.
-class OpaqueRegionSkia {
+class OpaqueRegionSkia FINAL {
 public:
     OpaqueRegionSkia();
-    virtual ~OpaqueRegionSkia();
 
     // The resulting opaque region as a single rect.
     IntRect asRect() const;
diff --git a/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp b/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
index fee552b..2e74476 100644
--- a/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
+++ b/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
@@ -36,8 +36,8 @@
 #include "SkPath.h"
 #include "SkTypeface.h"
 #include "SkTypes.h"
-#include "core/platform/graphics/FontDescription.h"
 #include "core/platform/graphics/chromium/VDMXParser.h"
+#include "platform/fonts/FontDescription.h"
 #include "platform/geometry/FloatRect.h"
 #include "wtf/unicode/Unicode.h"
 
@@ -133,14 +133,7 @@
     // In WebKit/WebCore/platform/graphics/SimpleFontData.cpp, m_spaceWidth is
     // calculated for us, but we need to calculate m_maxCharWidth and
     // m_avgCharWidth in order for text entry widgets to be sized correctly.
-#if OS(WIN)
     m_maxCharWidth = SkScalarRound(metrics.fMaxCharWidth);
-#else
-    // FIXME: This seems incorrect and should probably use fMaxCharWidth as
-    // the code path above.
-    SkScalar xRange = metrics.fXMax - metrics.fXMin;
-    m_maxCharWidth = SkScalarRound(xRange * SkScalarRound(m_platformData.size()));
-#endif
 
     if (metrics.fAvgCharWidth)
         m_avgCharWidth = SkScalarRound(metrics.fAvgCharWidth);
diff --git a/Source/core/platform/graphics/skia/SkiaUtils.h b/Source/core/platform/graphics/skia/SkiaUtils.h
index 664c5be..f95c307 100644
--- a/Source/core/platform/graphics/skia/SkiaUtils.h
+++ b/Source/core/platform/graphics/skia/SkiaUtils.h
@@ -36,9 +36,9 @@
 #include "SkMatrix.h"
 #include "SkPath.h"
 #include "SkXfermode.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "platform/geometry/FloatRect.h"
+#include "platform/graphics/Color.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "platform/transforms/AffineTransform.h"
 #include "wtf/MathExtras.h"
 #include "wtf/PassRefPtr.h"
diff --git a/Source/core/platform/graphics/transforms/IdentityTransformOperation.h b/Source/core/platform/graphics/transforms/IdentityTransformOperation.h
deleted file mode 100644
index 3f70d9a..0000000
--- a/Source/core/platform/graphics/transforms/IdentityTransformOperation.h
+++ /dev/null
@@ -1,67 +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 IdentityTransformOperation_h
-#define IdentityTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class IdentityTransformOperation : public TransformOperation {
-public:
-    static PassRefPtr<IdentityTransformOperation> create()
-    {
-        return adoptRef(new IdentityTransformOperation());
-    }
-
-private:
-    virtual bool isIdentity() const { return true; }
-    virtual OperationType getOperationType() const { return Identity; }
-    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Identity; }
-
-    virtual bool operator==(const TransformOperation& o) const
-    {
-        return isSameType(o);
-    }
-
-    virtual bool apply(TransformationMatrix&, const FloatSize&) const
-    {
-        return false;
-    }
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation*, double, bool = false)
-    {
-        return this;
-    }
-
-    IdentityTransformOperation()
-    {
-    }
-
-};
-
-} // namespace WebCore
-
-#endif // IdentityTransformOperation_h
diff --git a/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp b/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp
deleted file mode 100644
index 8f0e2b0..0000000
--- a/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp
+++ /dev/null
@@ -1,74 +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/graphics/transforms/InterpolatedTransformOperation.h"
-
-#include "core/platform/graphics/transforms/IdentityTransformOperation.h"
-
-namespace WebCore {
-
-bool InterpolatedTransformOperation::operator==(const TransformOperation& o) const
-{
-    if (!isSameType(o))
-        return false;
-    const InterpolatedTransformOperation* t = static_cast<const InterpolatedTransformOperation*>(&o);
-    return progress == t->progress && from == t->from && to == t->to;
-}
-
-bool InterpolatedTransformOperation::apply(TransformationMatrix& transform, const FloatSize& borderBoxSize) const
-{
-    TransformationMatrix fromTransform;
-    TransformationMatrix toTransform;
-    from.apply(borderBoxSize, fromTransform);
-    to.apply(borderBoxSize, toTransform);
-
-    toTransform.blend(fromTransform, progress);
-    transform.multiply(toTransform);
-    return true;
-}
-
-PassRefPtr<TransformOperation> InterpolatedTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
-    if (from && !from->isSameType(*this))
-        return this;
-
-    TransformOperations thisOperations;
-    thisOperations.operations().append(this);
-    TransformOperations fromOperations;
-    if (blendToIdentity)
-        fromOperations.operations().append(IdentityTransformOperation::create());
-    else
-        fromOperations.operations().append(const_cast<TransformOperation*>(from));
-    return InterpolatedTransformOperation::create(thisOperations, fromOperations, progress);
-}
-
-} // namespace WebCore
-
diff --git a/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h b/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h
deleted file mode 100644
index 97ef8d5..0000000
--- a/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h
+++ /dev/null
@@ -1,72 +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 InterpolatedTransformOperation_h
-#define InterpolatedTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-
-namespace WebCore {
-
-// This class is an implementation detail for deferred interpolations.
-class InterpolatedTransformOperation : public TransformOperation {
-public:
-    static PassRefPtr<InterpolatedTransformOperation> create(const TransformOperations& from, const TransformOperations& to, double progress)
-    {
-        return adoptRef(new InterpolatedTransformOperation(from, to, progress));
-    }
-
-private:
-    virtual bool isIdentity() const { return false; }
-
-    virtual OperationType getOperationType() const { return Interpolated; }
-    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Interpolated; }
-
-    virtual bool operator==(const TransformOperation&) const;
-    virtual bool apply(TransformationMatrix&, const FloatSize& borderBoxSize) const;
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
-    InterpolatedTransformOperation(const TransformOperations& from, const TransformOperations& to, double progress)
-        : from(from)
-        , to(to)
-        , progress(progress)
-    { }
-
-    const TransformOperations from;
-    const TransformOperations to;
-    double progress;
-};
-
-} // namespace WebCore
-
-#endif // InterpolatedTransformOperation_h
-
diff --git a/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp b/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp
deleted file mode 100644
index b8732b2..0000000
--- a/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp
+++ /dev/null
@@ -1,56 +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.
- *
- * 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/graphics/transforms/Matrix3DTransformOperation.h"
-
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> Matrix3DTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
-    if (from && !from->isSameType(*this))
-        return this;
-
-    // Convert the TransformOperations into matrices
-    FloatSize size;
-    TransformationMatrix fromT;
-    TransformationMatrix toT;
-    if (from)
-        from->apply(fromT, size);
-
-    apply(toT, size);
-
-    if (blendToIdentity)
-        std::swap(fromT, toT);
-
-    toT.blend(fromT, progress);
-    return Matrix3DTransformOperation::create(toT);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.h b/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.h
deleted file mode 100644
index 5a8e732..0000000
--- a/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.h
+++ /dev/null
@@ -1,74 +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.
- *
- * 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 Matrix3DTransformOperation_h
-#define Matrix3DTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class Matrix3DTransformOperation : public TransformOperation {
-public:
-    static PassRefPtr<Matrix3DTransformOperation> create(const TransformationMatrix& matrix)
-    {
-        return adoptRef(new Matrix3DTransformOperation(matrix));
-    }
-
-    TransformationMatrix matrix() const {return m_matrix; }
-
-private:
-    virtual bool isIdentity() const { return m_matrix.isIdentity(); }
-
-    virtual OperationType getOperationType() const { return Matrix3D; }
-    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Matrix3D; }
-
-    virtual bool operator==(const TransformOperation& o) const
-    {
-        if (!isSameType(o))
-            return false;
-        const Matrix3DTransformOperation* m = static_cast<const Matrix3DTransformOperation*>(&o);
-        return m_matrix == m->m_matrix;
-    }
-
-    virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
-    {
-        transform.multiply(TransformationMatrix(m_matrix));
-        return false;
-    }
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
-    Matrix3DTransformOperation(const TransformationMatrix& mat)
-    {
-        m_matrix = mat;
-    }
-
-    TransformationMatrix m_matrix;
-};
-
-} // namespace WebCore
-
-#endif // Matrix3DTransformOperation_h
diff --git a/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp b/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp
deleted file mode 100644
index d14c7bf..0000000
--- a/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 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.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/MatrixTransformOperation.h"
-
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> MatrixTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
-    if (from && !from->isSameType(*this))
-        return this;
-
-    // convert the TransformOperations into matrices
-    FloatSize size;
-    TransformationMatrix fromT;
-    TransformationMatrix toT(m_a, m_b, m_c, m_d, m_e, m_f);
-    if (from) {
-        const MatrixTransformOperation* m = static_cast<const MatrixTransformOperation*>(from);
-        fromT.setMatrix(m->m_a, m->m_b, m->m_c, m->m_d, m->m_e, m->m_f);
-    }
-
-    if (blendToIdentity)
-        std::swap(fromT, toT);
-
-    toT.blend(fromT, progress);
-    return MatrixTransformOperation::create(toT.a(), toT.b(), toT.c(), toT.d(), toT.e(), toT.f());
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/MatrixTransformOperation.h b/Source/core/platform/graphics/transforms/MatrixTransformOperation.h
deleted file mode 100644
index 56b0606..0000000
--- a/Source/core/platform/graphics/transforms/MatrixTransformOperation.h
+++ /dev/null
@@ -1,101 +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 MatrixTransformOperation_h
-#define MatrixTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-#include "platform/transforms/TransformationMatrix.h"
-
-namespace WebCore {
-
-class MatrixTransformOperation : public TransformOperation {
-public:
-    static PassRefPtr<MatrixTransformOperation> create(double a, double b, double c, double d, double e, double f)
-    {
-        return adoptRef(new MatrixTransformOperation(a, b, c, d, e, f));
-    }
-
-    static PassRefPtr<MatrixTransformOperation> create(const TransformationMatrix& t)
-    {
-        return adoptRef(new MatrixTransformOperation(t));
-    }
-
-    TransformationMatrix matrix() const { return TransformationMatrix(m_a, m_b, m_c, m_d, m_e, m_f); }
-
-private:
-    virtual bool isIdentity() const { return m_a == 1 && m_b == 0 && m_c == 0 && m_d == 1 && m_e == 0 && m_f == 0; }
-
-    virtual OperationType getOperationType() const { return Matrix; }
-    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Matrix; }
-
-    virtual bool operator==(const TransformOperation& o) const
-    {
-        if (!isSameType(o))
-            return false;
-
-        const MatrixTransformOperation* m = static_cast<const MatrixTransformOperation*>(&o);
-        return m_a == m->m_a && m_b == m->m_b && m_c == m->m_c && m_d == m->m_d && m_e == m->m_e && m_f == m->m_f;
-    }
-
-    virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
-    {
-        TransformationMatrix matrix(m_a, m_b, m_c, m_d, m_e, m_f);
-        transform.multiply(matrix);
-        return false;
-    }
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
-    MatrixTransformOperation(double a, double b, double c, double d, double e, double f)
-        : m_a(a)
-        , m_b(b)
-        , m_c(c)
-        , m_d(d)
-        , m_e(e)
-        , m_f(f)
-    {
-    }
-
-    MatrixTransformOperation(const TransformationMatrix& t)
-        : m_a(t.a())
-        , m_b(t.b())
-        , m_c(t.c())
-        , m_d(t.d())
-        , m_e(t.e())
-        , m_f(t.f())
-    {
-    }
-
-    double m_a;
-    double m_b;
-    double m_c;
-    double m_d;
-    double m_e;
-    double m_f;
-};
-
-} // namespace WebCore
-
-#endif // MatrixTransformOperation_h
diff --git a/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp b/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp
deleted file mode 100644
index b88a42f..0000000
--- a/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp
+++ /dev/null
@@ -1,66 +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.
- *
- * 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/graphics/transforms/PerspectiveTransformOperation.h"
-
-#include "platform/animation/AnimationUtilities.h"
-#include "wtf/MathExtras.h"
-
-using namespace std;
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> PerspectiveTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
-    if (from && !from->isSameType(*this))
-        return this;
-
-    if (blendToIdentity) {
-        double p = floatValueForLength(m_p, 1);
-        p = WebCore::blend(p, 1.0, progress); // FIXME: this seems wrong. https://bugs.webkit.org/show_bug.cgi?id=52700
-        return PerspectiveTransformOperation::create(Length(clampToPositiveInteger(p), Fixed));
-    }
-
-    const PerspectiveTransformOperation* fromOp = static_cast<const PerspectiveTransformOperation*>(from);
-    Length fromP = fromOp ? fromOp->m_p : Length(m_p.type());
-    Length toP = m_p;
-
-    TransformationMatrix fromT;
-    TransformationMatrix toT;
-    fromT.applyPerspective(floatValueForLength(fromP, 1));
-    toT.applyPerspective(floatValueForLength(toP, 1));
-    toT.blend(fromT, progress);
-    TransformationMatrix::DecomposedType decomp;
-    toT.decompose(decomp);
-
-    if (decomp.perspectiveZ) {
-        double val = -1.0 / decomp.perspectiveZ;
-        return PerspectiveTransformOperation::create(Length(clampToPositiveInteger(val), Fixed));
-    }
-    return PerspectiveTransformOperation::create(Length(0, Fixed));
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.h b/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.h
deleted file mode 100644
index 21b35e0..0000000
--- a/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.h
+++ /dev/null
@@ -1,76 +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.
- *
- * 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 PerspectiveTransformOperation_h
-#define PerspectiveTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-#include "platform/Length.h"
-#include "platform/LengthFunctions.h"
-
-namespace WebCore {
-
-class PerspectiveTransformOperation : public TransformOperation {
-public:
-    static PassRefPtr<PerspectiveTransformOperation> create(const Length& p)
-    {
-        return adoptRef(new PerspectiveTransformOperation(p));
-    }
-
-    Length perspective() const { return m_p; }
-
-private:
-    virtual bool isIdentity() const { return !floatValueForLength(m_p, 1); }
-    virtual OperationType getOperationType() const { return Perspective; }
-    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Perspective; }
-
-    virtual bool operator==(const TransformOperation& o) const
-    {
-        if (!isSameType(o))
-            return false;
-        const PerspectiveTransformOperation* p = static_cast<const PerspectiveTransformOperation*>(&o);
-        return m_p == p->m_p;
-    }
-
-    virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
-    {
-        transform.applyPerspective(floatValueForLength(m_p, 1));
-        return false;
-    }
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
-    PerspectiveTransformOperation(const Length& p)
-        : m_p(p)
-    {
-        ASSERT(p.isFixed());
-    }
-
-    Length m_p;
-};
-
-} // namespace WebCore
-
-#endif // PerspectiveTransformOperation_h
diff --git a/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp b/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp
deleted file mode 100644
index 4065709..0000000
--- a/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 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.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/RotateTransformOperation.h"
-
-#include "platform/animation/AnimationUtilities.h"
-#include "wtf/MathExtras.h"
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> RotateTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
-    if (from && !from->isSameType(*this))
-        return this;
-
-    if (blendToIdentity)
-        return RotateTransformOperation::create(m_x, m_y, m_z, m_angle - m_angle * progress, m_type);
-
-    const RotateTransformOperation* fromOp = static_cast<const RotateTransformOperation*>(from);
-
-    // Optimize for single axis rotation
-    if (!fromOp || (fromOp->m_x == 0 && fromOp->m_y == 0 && fromOp->m_z == 1) ||
-                   (fromOp->m_x == 0 && fromOp->m_y == 1 && fromOp->m_z == 0) ||
-                   (fromOp->m_x == 1 && fromOp->m_y == 0 && fromOp->m_z == 0)) {
-        double fromAngle = fromOp ? fromOp->m_angle : 0;
-        return RotateTransformOperation::create(fromOp ? fromOp->m_x : m_x,
-                                                fromOp ? fromOp->m_y : m_y,
-                                                fromOp ? fromOp->m_z : m_z,
-                                                WebCore::blend(fromAngle, m_angle, progress), m_type);
-    }
-
-    const RotateTransformOperation* toOp = this;
-
-    // Create the 2 rotation matrices
-    TransformationMatrix fromT;
-    TransformationMatrix toT;
-    fromT.rotate3d((fromOp ? fromOp->m_x : 0),
-        (fromOp ? fromOp->m_y : 0),
-        (fromOp ? fromOp->m_z : 1),
-        (fromOp ? fromOp->m_angle : 0));
-
-    toT.rotate3d((toOp ? toOp->m_x : 0),
-        (toOp ? toOp->m_y : 0),
-        (toOp ? toOp->m_z : 1),
-        (toOp ? toOp->m_angle : 0));
-
-    // Blend them
-    toT.blend(fromT, progress);
-
-    // Extract the result as a quaternion
-    TransformationMatrix::DecomposedType decomp;
-    toT.decompose(decomp);
-
-    // Convert that to Axis/Angle form
-    double x = -decomp.quaternionX;
-    double y = -decomp.quaternionY;
-    double z = -decomp.quaternionZ;
-    double length = sqrt(x * x + y * y + z * z);
-    double angle = 0;
-
-    if (length > 0.00001) {
-        x /= length;
-        y /= length;
-        z /= length;
-        angle = rad2deg(acos(decomp.quaternionW) * 2);
-    } else {
-        x = 0;
-        y = 0;
-        z = 1;
-    }
-    return RotateTransformOperation::create(x, y, z, angle, Rotate3D);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/RotateTransformOperation.h b/Source/core/platform/graphics/transforms/RotateTransformOperation.h
deleted file mode 100644
index 00d7983..0000000
--- a/Source/core/platform/graphics/transforms/RotateTransformOperation.h
+++ /dev/null
@@ -1,90 +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 RotateTransformOperation_h
-#define RotateTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class RotateTransformOperation : public TransformOperation {
-public:
-    static PassRefPtr<RotateTransformOperation> create(double angle, OperationType type)
-    {
-        return adoptRef(new RotateTransformOperation(0, 0, 1, angle, type));
-    }
-
-    static PassRefPtr<RotateTransformOperation> create(double x, double y, double z, double angle, OperationType type)
-    {
-        return adoptRef(new RotateTransformOperation(x, y, z, angle, type));
-    }
-
-    double x() const { return m_x; }
-    double y() const { return m_y; }
-    double z() const { return m_z; }
-    double angle() const { return m_angle; }
-
-private:
-    virtual bool isIdentity() const { return m_angle == 0; }
-
-    virtual OperationType getOperationType() const { return m_type; }
-    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == m_type; }
-
-    virtual bool operator==(const TransformOperation& o) const
-    {
-        if (!isSameType(o))
-            return false;
-        const RotateTransformOperation* r = static_cast<const RotateTransformOperation*>(&o);
-        return m_x == r->m_x && m_y == r->m_y && m_z == r->m_z && m_angle == r->m_angle;
-    }
-
-    virtual bool apply(TransformationMatrix& transform, const FloatSize& /*borderBoxSize*/) const
-    {
-        transform.rotate3d(m_x, m_y, m_z, m_angle);
-        return false;
-    }
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
-    RotateTransformOperation(double x, double y, double z, double angle, OperationType type)
-        : m_x(x)
-        , m_y(y)
-        , m_z(z)
-        , m_angle(angle)
-        , m_type(type)
-    {
-        ASSERT(type == RotateX || type == RotateY || type == RotateZ || type == Rotate3D);
-    }
-
-    double m_x;
-    double m_y;
-    double m_z;
-    double m_angle;
-    OperationType m_type;
-};
-
-} // namespace WebCore
-
-#endif // RotateTransformOperation_h
diff --git a/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp b/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp
deleted file mode 100644
index 9567779..0000000
--- a/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 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.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-
-#include "platform/animation/AnimationUtilities.h"
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> ScaleTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
-    if (from && !from->isSameType(*this))
-        return this;
-
-    if (blendToIdentity)
-        return ScaleTransformOperation::create(WebCore::blend(m_x, 1.0, progress),
-                                               WebCore::blend(m_y, 1.0, progress),
-                                               WebCore::blend(m_z, 1.0, progress), m_type);
-
-    const ScaleTransformOperation* fromOp = static_cast<const ScaleTransformOperation*>(from);
-    double fromX = fromOp ? fromOp->m_x : 1.0;
-    double fromY = fromOp ? fromOp->m_y : 1.0;
-    double fromZ = fromOp ? fromOp->m_z : 1.0;
-    return ScaleTransformOperation::create(WebCore::blend(fromX, m_x, progress),
-                                           WebCore::blend(fromY, m_y, progress),
-                                           WebCore::blend(fromZ, m_z, progress), m_type);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/ScaleTransformOperation.h b/Source/core/platform/graphics/transforms/ScaleTransformOperation.h
deleted file mode 100644
index c380416..0000000
--- a/Source/core/platform/graphics/transforms/ScaleTransformOperation.h
+++ /dev/null
@@ -1,87 +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 ScaleTransformOperation_h
-#define ScaleTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class ScaleTransformOperation : public TransformOperation {
-public:
-    static PassRefPtr<ScaleTransformOperation> create(double sx, double sy, OperationType type)
-    {
-        return adoptRef(new ScaleTransformOperation(sx, sy, 1, type));
-    }
-
-    static PassRefPtr<ScaleTransformOperation> create(double sx, double sy, double sz, OperationType type)
-    {
-        return adoptRef(new ScaleTransformOperation(sx, sy, sz, type));
-    }
-
-    double x() const { return m_x; }
-    double y() const { return m_y; }
-    double z() const { return m_z; }
-
-private:
-    virtual bool isIdentity() const { return m_x == 1 &&  m_y == 1 &&  m_z == 1; }
-
-    virtual OperationType getOperationType() const { return m_type; }
-    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == m_type; }
-
-    virtual bool operator==(const TransformOperation& o) const
-    {
-        if (!isSameType(o))
-            return false;
-        const ScaleTransformOperation* s = static_cast<const ScaleTransformOperation*>(&o);
-        return m_x == s->m_x && m_y == s->m_y && m_z == s->m_z;
-    }
-
-    virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
-    {
-        transform.scale3d(m_x, m_y, m_z);
-        return false;
-    }
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
-    ScaleTransformOperation(double sx, double sy, double sz, OperationType type)
-        : m_x(sx)
-        , m_y(sy)
-        , m_z(sz)
-        , m_type(type)
-    {
-        ASSERT(type == ScaleX || type == ScaleY || type == ScaleZ || type == Scale || type == Scale3D);
-    }
-
-    double m_x;
-    double m_y;
-    double m_z;
-    OperationType m_type;
-};
-
-} // namespace WebCore
-
-#endif // ScaleTransformOperation_h
diff --git a/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp b/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp
deleted file mode 100644
index 5266411..0000000
--- a/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 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.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/SkewTransformOperation.h"
-
-#include "platform/animation/AnimationUtilities.h"
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> SkewTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
-    if (from && !from->isSameType(*this))
-        return this;
-
-    if (blendToIdentity)
-        return SkewTransformOperation::create(WebCore::blend(m_angleX, 0.0, progress), WebCore::blend(m_angleY, 0.0, progress), m_type);
-
-    const SkewTransformOperation* fromOp = static_cast<const SkewTransformOperation*>(from);
-    double fromAngleX = fromOp ? fromOp->m_angleX : 0;
-    double fromAngleY = fromOp ? fromOp->m_angleY : 0;
-    return SkewTransformOperation::create(WebCore::blend(fromAngleX, m_angleX, progress), WebCore::blend(fromAngleY, m_angleY, progress), m_type);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/SkewTransformOperation.h b/Source/core/platform/graphics/transforms/SkewTransformOperation.h
deleted file mode 100644
index c64f8c8..0000000
--- a/Source/core/platform/graphics/transforms/SkewTransformOperation.h
+++ /dev/null
@@ -1,77 +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 SkewTransformOperation_h
-#define SkewTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class SkewTransformOperation : public TransformOperation {
-public:
-    static PassRefPtr<SkewTransformOperation> create(double angleX, double angleY, OperationType type)
-    {
-        return adoptRef(new SkewTransformOperation(angleX, angleY, type));
-    }
-
-    double angleX() const { return m_angleX; }
-    double angleY() const { return m_angleY; }
-
-private:
-    virtual bool isIdentity() const { return m_angleX == 0 && m_angleY == 0; }
-    virtual OperationType getOperationType() const { return m_type; }
-    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == m_type; }
-
-    virtual bool operator==(const TransformOperation& o) const
-    {
-        if (!isSameType(o))
-            return false;
-        const SkewTransformOperation* s = static_cast<const SkewTransformOperation*>(&o);
-        return m_angleX == s->m_angleX && m_angleY == s->m_angleY;
-    }
-
-    virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
-    {
-        transform.skew(m_angleX, m_angleY);
-        return false;
-    }
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
-    SkewTransformOperation(double angleX, double angleY, OperationType type)
-        : m_angleX(angleX)
-        , m_angleY(angleY)
-        , m_type(type)
-    {
-    }
-
-    double m_angleX;
-    double m_angleY;
-    OperationType m_type;
-};
-
-} // namespace WebCore
-
-#endif // SkewTransformOperation_h
diff --git a/Source/core/platform/graphics/transforms/TransformOperation.h b/Source/core/platform/graphics/transforms/TransformOperation.h
deleted file mode 100644
index 9cbf12a..0000000
--- a/Source/core/platform/graphics/transforms/TransformOperation.h
+++ /dev/null
@@ -1,88 +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 TransformOperation_h
-#define TransformOperation_h
-
-#include "platform/geometry/FloatSize.h"
-#include "platform/transforms/TransformationMatrix.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-// CSS Transforms (may become part of CSS3)
-
-class TransformOperation : public RefCounted<TransformOperation> {
-public:
-    enum OperationType {
-        ScaleX, ScaleY, Scale,
-        TranslateX, TranslateY, Translate,
-        Rotate,
-        RotateZ = Rotate,
-        SkewX, SkewY, Skew,
-        Matrix,
-        ScaleZ, Scale3D,
-        TranslateZ, Translate3D,
-        RotateX, RotateY, Rotate3D,
-        Matrix3D,
-        Perspective,
-        Interpolated,
-        Identity, None
-    };
-
-    virtual ~TransformOperation() { }
-
-    virtual bool operator==(const TransformOperation&) const = 0;
-    bool operator!=(const TransformOperation& o) const { return !(*this == o); }
-
-    virtual bool isIdentity() const = 0;
-
-    // Return true if the borderBoxSize was used in the computation, false otherwise.
-    virtual bool apply(TransformationMatrix&, const FloatSize& borderBoxSize) const = 0;
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false) = 0;
-
-    virtual OperationType getOperationType() const = 0;
-    virtual bool isSameType(const TransformOperation&) const { return false; }
-
-    bool is3DOperation() const
-    {
-        OperationType opType = getOperationType();
-        return opType == ScaleZ
-            || opType == Scale3D
-            || opType == TranslateZ
-            || opType == Translate3D
-            || opType == RotateX
-            || opType == RotateY
-            || opType == Rotate3D
-            || opType == Matrix3D
-            || opType == Perspective
-            || opType == Interpolated;
-    }
-};
-
-} // namespace WebCore
-
-#endif // TransformOperation_h
diff --git a/Source/core/platform/graphics/transforms/TransformOperations.cpp b/Source/core/platform/graphics/transforms/TransformOperations.cpp
deleted file mode 100644
index 3ca3d7f..0000000
--- a/Source/core/platform/graphics/transforms/TransformOperations.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 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.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-
-#include <algorithm>
-#include "core/platform/graphics/transforms/IdentityTransformOperation.h"
-#include "core/platform/graphics/transforms/InterpolatedTransformOperation.h"
-
-using namespace std;
-
-namespace WebCore {
-
-TransformOperations::TransformOperations(bool makeIdentity)
-{
-    if (makeIdentity)
-        m_operations.append(IdentityTransformOperation::create());
-}
-
-bool TransformOperations::operator==(const TransformOperations& o) const
-{
-    if (m_operations.size() != o.m_operations.size())
-        return false;
-
-    unsigned s = m_operations.size();
-    for (unsigned i = 0; i < s; i++) {
-        if (*m_operations[i] != *o.m_operations[i])
-            return false;
-    }
-
-    return true;
-}
-
-bool TransformOperations::operationsMatch(const TransformOperations& other) const
-{
-    size_t numOperations = operations().size();
-    // If the sizes of the function lists don't match, the lists don't match
-    if (numOperations != other.operations().size())
-        return false;
-
-    // If the types of each function are not the same, the lists don't match
-    for (size_t i = 0; i < numOperations; ++i) {
-        if (!operations()[i]->isSameType(*other.operations()[i]))
-            return false;
-    }
-    return true;
-}
-
-TransformOperations TransformOperations::blendByMatchingOperations(const TransformOperations& from, const double& progress) const
-{
-    TransformOperations result;
-
-    unsigned fromSize = from.operations().size();
-    unsigned toSize = operations().size();
-    unsigned size = max(fromSize, toSize);
-    for (unsigned i = 0; i < size; i++) {
-        RefPtr<TransformOperation> fromOperation = (i < fromSize) ? from.operations()[i].get() : 0;
-        RefPtr<TransformOperation> toOperation = (i < toSize) ? operations()[i].get() : 0;
-        RefPtr<TransformOperation> blendedOperation = toOperation ? toOperation->blend(fromOperation.get(), progress) : (fromOperation ? fromOperation->blend(0, progress, true) : 0);
-        if (blendedOperation)
-            result.operations().append(blendedOperation);
-        else {
-            RefPtr<TransformOperation> identityOperation = IdentityTransformOperation::create();
-            if (progress > 0.5)
-                result.operations().append(toOperation ? toOperation : identityOperation);
-            else
-                result.operations().append(fromOperation ? fromOperation : identityOperation);
-        }
-    }
-
-    return result;
-}
-
-TransformOperations TransformOperations::blendByUsingMatrixInterpolation(const TransformOperations& from, double progress) const
-{
-    TransformOperations result;
-    result.operations().append(InterpolatedTransformOperation::create(from, *this, progress));
-    return result;
-}
-
-TransformOperations TransformOperations::blend(const TransformOperations& from, double progress) const
-{
-    if (from == *this)
-        return *this;
-
-    if (from.size() && from.operationsMatch(*this))
-        return blendByMatchingOperations(from, progress);
-
-    return blendByUsingMatrixInterpolation(from, progress);
-}
-
-TransformOperations TransformOperations::add(const TransformOperations& addend) const
-{
-    TransformOperations result;
-    result.m_operations = operations();
-    result.m_operations.append(addend.operations());
-    return result;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/TransformOperations.h b/Source/core/platform/graphics/transforms/TransformOperations.h
deleted file mode 100644
index 0578336..0000000
--- a/Source/core/platform/graphics/transforms/TransformOperations.h
+++ /dev/null
@@ -1,86 +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 TransformOperations_h
-#define TransformOperations_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-#include "platform/geometry/LayoutSize.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class TransformOperations {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    explicit TransformOperations(bool makeIdentity = false);
-
-    bool operator==(const TransformOperations& o) const;
-    bool operator!=(const TransformOperations& o) const
-    {
-        return !(*this == o);
-    }
-
-    void apply(const FloatSize& sz, TransformationMatrix& t) const
-    {
-        for (unsigned i = 0; i < m_operations.size(); ++i)
-            m_operations[i]->apply(t, sz);
-    }
-
-    // Return true if any of the operation types are 3D operation types (even if the
-    // values describe affine transforms)
-    bool has3DOperation() const
-    {
-        for (unsigned i = 0; i < m_operations.size(); ++i)
-            if (m_operations[i]->is3DOperation())
-                return true;
-        return false;
-    }
-
-    bool operationsMatch(const TransformOperations&) const;
-
-    void clear()
-    {
-        m_operations.clear();
-    }
-
-    Vector<RefPtr<TransformOperation> >& operations() { return m_operations; }
-    const Vector<RefPtr<TransformOperation> >& operations() const { return m_operations; }
-
-    size_t size() const { return m_operations.size(); }
-    const TransformOperation* at(size_t index) const { return index < m_operations.size() ? m_operations.at(index).get() : 0; }
-
-    TransformOperations blendByMatchingOperations(const TransformOperations& from, const double& progress) const;
-    TransformOperations blendByUsingMatrixInterpolation(const TransformOperations& from, double progress) const;
-    TransformOperations blend(const TransformOperations& from, double progress) const;
-    TransformOperations add(const TransformOperations& addend) const;
-
-private:
-    Vector<RefPtr<TransformOperation> > m_operations;
-};
-
-} // namespace WebCore
-
-#endif // TransformOperations_h
diff --git a/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp b/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp
deleted file mode 100644
index 1b98c22..0000000
--- a/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 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.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> TranslateTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
-    if (from && !from->isSameType(*this))
-        return this;
-
-    const Length zeroLength(0, Fixed);
-    if (blendToIdentity)
-        return TranslateTransformOperation::create(zeroLength.blend(m_x, progress, ValueRangeAll), zeroLength.blend(m_y, progress, ValueRangeAll), zeroLength.blend(m_z, progress, ValueRangeAll), m_type);
-
-    const TranslateTransformOperation* fromOp = static_cast<const TranslateTransformOperation*>(from);
-    Length fromX = fromOp ? fromOp->m_x : zeroLength;
-    Length fromY = fromOp ? fromOp->m_y : zeroLength;
-    Length fromZ = fromOp ? fromOp->m_z : zeroLength;
-    return TranslateTransformOperation::create(m_x.blend(fromX, progress, ValueRangeAll), m_y.blend(fromY, progress, ValueRangeAll), m_z.blend(fromZ, progress, ValueRangeAll), m_type);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/transforms/TranslateTransformOperation.h b/Source/core/platform/graphics/transforms/TranslateTransformOperation.h
deleted file mode 100644
index 6895413..0000000
--- a/Source/core/platform/graphics/transforms/TranslateTransformOperation.h
+++ /dev/null
@@ -1,93 +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 TranslateTransformOperation_h
-#define TranslateTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-#include "platform/Length.h"
-#include "platform/LengthFunctions.h"
-
-namespace WebCore {
-
-class TranslateTransformOperation : public TransformOperation {
-public:
-    static PassRefPtr<TranslateTransformOperation> create(const Length& tx, const Length& ty, OperationType type)
-    {
-        return adoptRef(new TranslateTransformOperation(tx, ty, Length(0, Fixed), type));
-    }
-
-    static PassRefPtr<TranslateTransformOperation> create(const Length& tx, const Length& ty, const Length& tz, OperationType type)
-    {
-        return adoptRef(new TranslateTransformOperation(tx, ty, tz, type));
-    }
-
-    double x(const FloatSize& borderBoxSize) const { return floatValueForLength(m_x, borderBoxSize.width()); }
-    double y(const FloatSize& borderBoxSize) const { return floatValueForLength(m_y, borderBoxSize.height()); }
-    double z(const FloatSize&) const { return floatValueForLength(m_z, 1); }
-
-    Length x() const { return m_x; }
-    Length y() const { return m_y; }
-    Length z() const { return m_z; }
-
-private:
-    virtual bool isIdentity() const { return !floatValueForLength(m_x, 1) && !floatValueForLength(m_y, 1) && !floatValueForLength(m_z, 1); }
-
-    virtual OperationType getOperationType() const { return m_type; }
-    virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == m_type; }
-
-    virtual bool operator==(const TransformOperation& o) const
-    {
-        if (!isSameType(o))
-            return false;
-        const TranslateTransformOperation* t = static_cast<const TranslateTransformOperation*>(&o);
-        return m_x == t->m_x && m_y == t->m_y && m_z == t->m_z;
-    }
-
-    virtual bool apply(TransformationMatrix& transform, const FloatSize& borderBoxSize) const
-    {
-        transform.translate3d(x(borderBoxSize), y(borderBoxSize), z(borderBoxSize));
-        return m_x.type() == Percent || m_y.type() == Percent;
-    }
-
-    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
-    TranslateTransformOperation(const Length& tx, const Length& ty, const Length& tz, OperationType type)
-        : m_x(tx)
-        , m_y(ty)
-        , m_z(tz)
-        , m_type(type)
-    {
-        ASSERT(type == TranslateX || type == TranslateY || type == TranslateZ || type == Translate || type == Translate3D);
-    }
-
-    Length m_x;
-    Length m_y;
-    Length m_z;
-    OperationType m_type;
-};
-
-} // namespace WebCore
-
-#endif // TranslateTransformOperation_h
diff --git a/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp b/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
index f9984a5..91cb1d5 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
@@ -348,7 +348,6 @@
 bool GIFImageDecoder::initFrameBuffer(size_t frameIndex)
 {
     // Initialize the frame rect in our buffer.
-    const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
     ImageFrame* const buffer = &m_frameBufferCache[frameIndex];
 
     size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex();
diff --git a/Source/core/platform/image-decoders/gif/GIFImageReader.h b/Source/core/platform/image-decoders/gif/GIFImageReader.h
index ef85725..616f6e6 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageReader.h
+++ b/Source/core/platform/image-decoders/gif/GIFImageReader.h
@@ -285,7 +285,6 @@
         , m_version(0)
         , m_screenWidth(0)
         , m_screenHeight(0)
-        , m_isGlobalColormapDefined(false)
         , m_loopCount(cLoopCountNotSeen)
         , m_parseCompleted(false)
     {
@@ -351,7 +350,6 @@
     int m_version; // Either 89 for GIF89 or 87 for GIF87.
     unsigned m_screenWidth; // Logical screen width & height.
     unsigned m_screenHeight;
-    bool m_isGlobalColormapDefined;
     GIFColorMap m_globalColorMap;
     int m_loopCount; // Netscape specific extension block to control the number of animation loops a GIF renders.
 
diff --git a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
index 749cbea..9e01533 100644
--- a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
@@ -723,8 +723,8 @@
     // Initialize the framebuffer if needed.
     ImageFrame& buffer = m_frameBufferCache[0];
     if (buffer.status() == ImageFrame::FrameEmpty) {
-        ASSERT(info->output_width == m_decodedSize.width());
-        ASSERT(info->output_height == m_decodedSize.height());
+        ASSERT(info->output_width == static_cast<JDIMENSION>(m_decodedSize.width()));
+        ASSERT(info->output_height == static_cast<JDIMENSION>(m_decodedSize.height()));
 
         if (!buffer.setSize(info->output_width, info->output_height))
             return setFailed();
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
index 5fbfbf3..08ab0fe 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
@@ -158,6 +158,20 @@
     }
 }
 
+void testInvalidImage(const char* webpFile)
+{
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+
+    RefPtr<SharedBuffer> data = readFile(webpFile);
+    ASSERT_TRUE(data.get());
+    decoder->setData(data.get(), true);
+
+    EXPECT_EQ(0u, decoder->frameCount());
+    ImageFrame* frame = decoder->frameBufferAtIndex(0);
+    EXPECT_FALSE(frame);
+    EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
+}
+
 } // namespace
 
 class AnimatedWebPTests : public ::testing::Test {
@@ -335,18 +349,12 @@
     }
 }
 
-TEST_F(AnimatedWebPTests, invalidImage)
+TEST_F(AnimatedWebPTests, invalidImages)
 {
-    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
-
-    RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/invalid-animated-webp.webp");
-    ASSERT_TRUE(data.get());
-    decoder->setData(data.get(), true);
-
-    EXPECT_EQ(0u, decoder->frameCount());
-    ImageFrame* frame = decoder->frameBufferAtIndex(0);
-    EXPECT_FALSE(frame);
-    EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
+    // crbug.com/229641
+    testInvalidImage("/LayoutTests/fast/images/resources/invalid-animated-webp.webp");
+    // crbug.com/310257
+    testInvalidImage("/LayoutTests/fast/images/resources/invalid-animated-webp3.webp");
 }
 
 // Reproduce a crash that used to happen for a specific file with specific sequence of method calls.
diff --git a/Source/core/platform/mac/NSScrollerImpDetails.mm b/Source/core/platform/mac/NSScrollerImpDetails.mm
index cc0f64b..15e06c6 100644
--- a/Source/core/platform/mac/NSScrollerImpDetails.mm
+++ b/Source/core/platform/mac/NSScrollerImpDetails.mm
@@ -88,6 +88,7 @@
     // This function is hot.
     // http://crbug.com/303205
     static ScrollerStyleObserver* scrollerStyleObserver = [[ScrollerStyleObserver alloc] init];
+    (void)scrollerStyleObserver;
     return g_scrollerStyle;
 }
 
diff --git a/Source/core/platform/mac/ThemeMac.mm b/Source/core/platform/mac/ThemeMac.mm
index 152e4e6..d9a696a 100644
--- a/Source/core/platform/mac/ThemeMac.mm
+++ b/Source/core/platform/mac/ThemeMac.mm
@@ -469,7 +469,6 @@
 
     LocalCurrentGraphicsContext localContext(context);
     NSView *view = ThemeMac::ensuredView(scrollView);
-    NSWindow *window = [view window];
 
     [buttonCell drawWithFrame:NSRect(inflatedRect) inView:view];
 #if !BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING
diff --git a/Source/core/platform/mac/WebFontCache.mm b/Source/core/platform/mac/WebFontCache.mm
index 6f85e7b..bfcab60 100644
--- a/Source/core/platform/mac/WebFontCache.mm
+++ b/Source/core/platform/mac/WebFontCache.mm
@@ -33,7 +33,7 @@
 #import <AppKit/AppKit.h>
 #import <Foundation/Foundation.h>
 #import <math.h>
-#import "core/platform/graphics/FontTraitsMask.h"
+#import "platform/fonts/FontTraitsMask.h"
 #import <wtf/UnusedParam.h>
 
 using namespace WebCore;
diff --git a/Source/core/platform/mediastream/MediaStreamComponent.h b/Source/core/platform/mediastream/MediaStreamComponent.h
index e683ac0..b0cbd9c 100644
--- a/Source/core/platform/mediastream/MediaStreamComponent.h
+++ b/Source/core/platform/mediastream/MediaStreamComponent.h
@@ -59,7 +59,7 @@
     static PassRefPtr<MediaStreamComponent> create(MediaStreamDescriptor*, PassRefPtr<MediaStreamSource>);
 
     MediaStreamDescriptor* stream() const { return m_stream; }
-    void setStream(MediaStreamDescriptor* stream) { ASSERT(!m_stream && stream); m_stream = stream; }
+    void setStream(MediaStreamDescriptor* stream) { m_stream = stream; }
 
     MediaStreamSource* source() const { return m_source.get(); }
 
diff --git a/Source/core/platform/mediastream/MediaStreamDescriptor.cpp b/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
index bb67f40..90f9ff5 100644
--- a/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
+++ b/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
@@ -127,5 +127,14 @@
     }
 }
 
+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
index 0da128e..b9bcf4f 100644
--- a/Source/core/platform/mediastream/MediaStreamDescriptor.h
+++ b/Source/core/platform/mediastream/MediaStreamDescriptor.h
@@ -49,7 +49,7 @@
     virtual void removeRemoteTrack(MediaStreamComponent*) = 0;
 };
 
-class MediaStreamDescriptor : public RefCounted<MediaStreamDescriptor> {
+class MediaStreamDescriptor FINAL : public RefCounted<MediaStreamDescriptor> {
 public:
     class ExtraData : public RefCounted<ExtraData> {
     public:
@@ -60,6 +60,8 @@
 
     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; }
 
diff --git a/Source/core/platform/mediastream/RTCConfiguration.h b/Source/core/platform/mediastream/RTCConfiguration.h
index ddb5adb..94e38c3 100644
--- a/Source/core/platform/mediastream/RTCConfiguration.h
+++ b/Source/core/platform/mediastream/RTCConfiguration.h
@@ -39,13 +39,12 @@
 
 namespace WebCore {
 
-class RTCIceServer : public RefCounted<RTCIceServer> {
+class RTCIceServer FINAL : public RefCounted<RTCIceServer> {
 public:
     static PassRefPtr<RTCIceServer> create(const KURL& uri, const String& username, const String& credential)
     {
         return adoptRef(new RTCIceServer(uri, username, credential));
     }
-    virtual ~RTCIceServer() { }
 
     const KURL& uri() { return m_uri; }
     const String& username() { return m_username; }
@@ -64,10 +63,9 @@
     String m_credential;
 };
 
-class RTCConfiguration : public RefCounted<RTCConfiguration> {
+class RTCConfiguration FINAL : public RefCounted<RTCConfiguration> {
 public:
     static PassRefPtr<RTCConfiguration> create() { return adoptRef(new RTCConfiguration()); }
-    virtual ~RTCConfiguration() { }
 
     void appendServer(PassRefPtr<RTCIceServer> server) { m_servers.append(server); }
     size_t numberOfServers() { return m_servers.size(); }
diff --git a/Source/core/platform/testing/FakeWebGraphicsContext3D.h b/Source/core/platform/testing/FakeWebGraphicsContext3D.h
index 3bbebc5..2d37f7a 100644
--- a/Source/core/platform/testing/FakeWebGraphicsContext3D.h
+++ b/Source/core/platform/testing/FakeWebGraphicsContext3D.h
@@ -234,20 +234,48 @@
 
     virtual void viewport(WGC3Dint x, WGC3Dint y, WGC3Dsizei width, WGC3Dsizei height) { }
 
+    virtual void genBuffers(WGC3Dsizei count, WebGLId* ids)
+    {
+        for (int i = 0; i < count; ++i)
+            ids[i] = 1;
+    }
+    virtual void genFramebuffers(WGC3Dsizei count, WebGLId* ids)
+    {
+        for (int i = 0; i < count; ++i)
+            ids[i] = 1;
+    }
+    virtual void genRenderbuffers(WGC3Dsizei count, WebGLId* ids)
+    {
+        for (int i = 0; i < count; ++i)
+            ids[i] = 1;
+    }
+    virtual void genTextures(WGC3Dsizei count, WebGLId* ids)
+    {
+        for (int i = 0; i < count; ++i)
+            ids[i] = m_nextTextureId++;
+    }
+
+    virtual void deleteBuffers(WGC3Dsizei count, WebGLId* ids) { }
+    virtual void deleteFramebuffers(WGC3Dsizei count, WebGLId* ids) { }
+    virtual void deleteRenderbuffers(WGC3Dsizei count, WebGLId* ids) { }
+    virtual void deleteTextures(WGC3Dsizei count, WebGLId* ids) { }
+
     virtual WebGLId createBuffer() { return 1; }
     virtual WebGLId createFramebuffer() { return 1; }
-    virtual WebGLId createProgram() { return 1; }
     virtual WebGLId createRenderbuffer() { return 1; }
-    virtual WebGLId createShader(WGC3Denum) { return 1; }
     virtual WebGLId createTexture() { return m_nextTextureId++; }
 
     virtual void deleteBuffer(WebGLId) { }
     virtual void deleteFramebuffer(WebGLId) { }
-    virtual void deleteProgram(WebGLId) { }
     virtual void deleteRenderbuffer(WebGLId) { }
-    virtual void deleteShader(WebGLId) { }
     virtual void deleteTexture(WebGLId) { }
 
+    virtual WebGLId createProgram() { return 1; }
+    virtual WebGLId createShader(WGC3Denum) { return 1; }
+
+    virtual void deleteProgram(WebGLId) { }
+    virtual void deleteShader(WebGLId) { }
+
     virtual void texStorage2DEXT(WGC3Denum target, WGC3Dint levels, WGC3Duint internalformat, WGC3Dint width, WGC3Dint height) { }
 
     virtual WebGLId createQueryEXT() { return 1; }
diff --git a/Source/core/plugins/DOMMimeType.cpp b/Source/core/plugins/DOMMimeType.cpp
index e246848..4c8d65e 100644
--- a/Source/core/plugins/DOMMimeType.cpp
+++ b/Source/core/plugins/DOMMimeType.cpp
@@ -65,7 +65,7 @@
 
 PassRefPtr<DOMPlugin> DOMMimeType::enabledPlugin() const
 {
-    if (!m_frame || !m_frame->page() || !m_frame->page()->mainFrame()->loader()->allowPlugins(NotAboutToInstantiatePlugin))
+    if (!m_frame || !m_frame->page() || !m_frame->page()->mainFrame()->loader().allowPlugins(NotAboutToInstantiatePlugin))
         return 0;
 
     return DOMPlugin::create(m_pluginData.get(), m_frame, m_pluginData->mimePluginIndices()[m_index]);
diff --git a/Source/core/rendering/AutoTableLayout.h b/Source/core/rendering/AutoTableLayout.h
index 0a42043..dfdd985 100644
--- a/Source/core/rendering/AutoTableLayout.h
+++ b/Source/core/rendering/AutoTableLayout.h
@@ -31,14 +31,15 @@
 class RenderTable;
 class RenderTableCell;
 
-class AutoTableLayout : public TableLayout {
+class AutoTableLayout FINAL : public TableLayout {
 public:
     AutoTableLayout(RenderTable*);
     ~AutoTableLayout();
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth) OVERRIDE;
     virtual void applyPreferredLogicalWidthQuirks(LayoutUnit& minWidth, LayoutUnit& maxWidth) const OVERRIDE;
-    virtual void layout();
+    virtual void layout() OVERRIDE;
+    virtual void willChangeTableLayout() OVERRIDE { }
 
 private:
     void fullRecalc();
diff --git a/Source/core/rendering/CompositedLayerMapping.cpp b/Source/core/rendering/CompositedLayerMapping.cpp
index 9e1175c..83aac9e 100644
--- a/Source/core/rendering/CompositedLayerMapping.cpp
+++ b/Source/core/rendering/CompositedLayerMapping.cpp
@@ -315,6 +315,13 @@
     if (layerOrAncestorIsTransformedOrUsingCompositedScrolling(m_owningLayer))
         return false;
 
+    // Scrolled composited layers are clipped by their ancestor clipping layer,
+    // so don't clip these, either.
+    bool hasAncestorClippingLayer = compositor()->clippedByAncestor(m_owningLayer);
+    bool clippingAncestorIsScrollParent = m_owningLayer->renderer()->containingBlock()->enclosingLayer() == m_owningLayer->ancestorScrollingLayer();
+    if (hasAncestorClippingLayer && clippingAncestorIsScrollParent)
+        return false;
+
     return true;
 }
 
@@ -391,14 +398,14 @@
         // The solution is to update compositing children of this layer here,
         // via updateCompositingChildrenGeometry().
         updateCompositedBounds();
-        layerCompositor->updateCompositingDescendantGeometry(m_owningLayer, m_owningLayer, flags & CompositingChildrenOnly);
+        layerCompositor->updateCompositingDescendantGeometry(m_owningLayer->stackingNode(), m_owningLayer, flags & CompositingChildrenOnly);
 
         if (flags & IsUpdateRoot) {
             updateGraphicsLayerGeometry();
             layerCompositor->updateRootLayerPosition();
-            RenderLayer* stackingContainerLayer = m_owningLayer->enclosingStackingContainerLayer();
-            if (!layerCompositor->compositingLayersNeedRebuild() && stackingContainerLayer && (stackingContainerLayer != m_owningLayer))
-                layerCompositor->updateCompositingDescendantGeometry(stackingContainerLayer, stackingContainerLayer, flags & CompositingChildrenOnly);
+            RenderLayerStackingNode* stackingContainer = m_owningLayer->stackingNode()->enclosingStackingContainerNode();
+            if (!layerCompositor->compositingLayersNeedRebuild() && stackingContainer && (stackingContainer != m_owningLayer->stackingNode()))
+                layerCompositor->updateCompositingDescendantGeometry(stackingContainer, stackingContainer->layer(), flags & CompositingChildrenOnly);
         }
     }
 
@@ -435,7 +442,7 @@
     if (scrollParent) {
         // If our containing block is our ancestor scrolling layer, then we'll already be clipped
         // to it via our scroll parent and we don't need an ancestor clipping layer.
-        if (m_owningLayer->renderer()->containingBlock()->enclosingLayer() == m_owningLayer->ancestorScrollingLayer())
+        if (m_owningLayer->renderer()->containingBlock()->enclosingLayer() == m_owningLayer->ancestorCompositedScrollingLayer())
             needsAncestorClip = false;
     }
     if (updateClippingLayers(needsAncestorClip, needsDescendentsClippingLayer))
@@ -456,13 +463,13 @@
     if (updateMaskLayer(renderer->hasMask()))
         m_graphicsLayer->setMaskLayer(m_maskLayer.get());
 
-    bool needsChildClippingMask = renderer->style()->hasBorderRadius() && isAcceleratedContents(renderer);
+    bool needsChildClippingMask = (renderer->style()->hasBorderRadius() || renderer->style()->clipPath()) && isAcceleratedContents(renderer);
     if (updateClippingMaskLayers(needsChildClippingMask))
         m_graphicsLayer->setContentsClippingMaskLayer(m_childClippingMaskLayer.get());
 
-    if (m_owningLayer->hasReflection()) {
-        if (m_owningLayer->reflectionLayer()->compositedLayerMapping()) {
-            GraphicsLayer* reflectionLayer = m_owningLayer->reflectionLayer()->compositedLayerMapping()->mainGraphicsLayer();
+    if (m_owningLayer->reflectionInfo()) {
+        if (m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping()) {
+            GraphicsLayer* reflectionLayer = m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping()->mainGraphicsLayer();
             m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
         }
     } else {
@@ -697,8 +704,8 @@
         m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
     }
 
-    if (m_owningLayer->reflectionLayer() && m_owningLayer->reflectionLayer()->compositedLayerMapping()) {
-        CompositedLayerMapping* reflectionCompositedLayerMapping = m_owningLayer->reflectionLayer()->compositedLayerMapping();
+    if (m_owningLayer->reflectionInfo() && m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping()) {
+        CompositedLayerMapping* reflectionCompositedLayerMapping = m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping();
         reflectionCompositedLayerMapping->updateGraphicsLayerGeometry();
 
         // The reflection layer has the bounds of m_owningLayer->reflectionLayer(),
@@ -981,7 +988,7 @@
     }
 
     if (GraphicsLayer* layer = layerForScrollCorner()) {
-        const LayoutRect& scrollCornerAndResizer = m_owningLayer->scrollCornerAndResizerRect();
+        const LayoutRect& scrollCornerAndResizer = m_owningLayer->scrollableArea()->scrollCornerAndResizerRect();
         layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
         layer->setSize(scrollCornerAndResizer.size());
         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
@@ -1341,10 +1348,10 @@
     LayerListMutationDetector mutationChecker(parent->stackingNode());
 #endif
 
-    if (Vector<RenderLayer*>* normalFlowList = parent->stackingNode()->normalFlowList()) {
+    if (Vector<RenderLayerStackingNode*>* normalFlowList = parent->stackingNode()->normalFlowList()) {
         size_t listSize = normalFlowList->size();
         for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = normalFlowList->at(i);
+            RenderLayer* curLayer = normalFlowList->at(i)->layer();
             if (!curLayer->compositedLayerMapping()
                 && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
                 return true;
@@ -1356,20 +1363,20 @@
             return false;
 
         // Use the m_hasCompositingDescendant bit to optimize?
-        if (Vector<RenderLayer*>* negZOrderList = parent->stackingNode()->negZOrderList()) {
+        if (Vector<RenderLayerStackingNode*>* negZOrderList = parent->stackingNode()->negZOrderList()) {
             size_t listSize = negZOrderList->size();
             for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = negZOrderList->at(i);
+                RenderLayer* curLayer = negZOrderList->at(i)->layer();
                 if (!curLayer->compositedLayerMapping()
                     && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
                     return true;
             }
         }
 
-        if (Vector<RenderLayer*>* posZOrderList = parent->stackingNode()->posZOrderList()) {
+        if (Vector<RenderLayerStackingNode*>* posZOrderList = parent->stackingNode()->posZOrderList()) {
             size_t listSize = posZOrderList->size();
             for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = posZOrderList->at(i);
+                RenderLayer* curLayer = posZOrderList->at(i)->layer();
                 if (!curLayer->compositedLayerMapping()
                     && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
                     return true;
@@ -1632,24 +1639,24 @@
 
     FontCachePurgePreventer fontCachePurgePreventer;
 
-    RenderLayer::PaintLayerFlags paintFlags = 0;
+    PaintLayerFlags paintFlags = 0;
     if (paintInfo.paintingPhase & GraphicsLayerPaintBackground)
-        paintFlags |= RenderLayer::PaintLayerPaintingCompositingBackgroundPhase;
+        paintFlags |= PaintLayerPaintingCompositingBackgroundPhase;
     if (paintInfo.paintingPhase & GraphicsLayerPaintForeground)
-        paintFlags |= RenderLayer::PaintLayerPaintingCompositingForegroundPhase;
+        paintFlags |= PaintLayerPaintingCompositingForegroundPhase;
     if (paintInfo.paintingPhase & GraphicsLayerPaintMask)
-        paintFlags |= RenderLayer::PaintLayerPaintingCompositingMaskPhase;
+        paintFlags |= PaintLayerPaintingCompositingMaskPhase;
     if (paintInfo.paintingPhase & GraphicsLayerPaintChildClippingMask)
-        paintFlags |= RenderLayer::PaintLayerPaintingChildClippingMaskPhase;
+        paintFlags |= PaintLayerPaintingChildClippingMaskPhase;
     if (paintInfo.paintingPhase & GraphicsLayerPaintOverflowContents)
-        paintFlags |= RenderLayer::PaintLayerPaintingOverflowContents;
+        paintFlags |= PaintLayerPaintingOverflowContents;
     if (paintInfo.paintingPhase & GraphicsLayerPaintCompositedScroll)
-        paintFlags |= RenderLayer::PaintLayerPaintingCompositingScrollingPhase;
+        paintFlags |= PaintLayerPaintingCompositingScrollingPhase;
 
     if (paintInfo.isBackgroundLayer)
-        paintFlags |= (RenderLayer::PaintLayerPaintingRootBackgroundOnly | RenderLayer::PaintLayerPaintingCompositingForegroundPhase); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
+        paintFlags |= (PaintLayerPaintingRootBackgroundOnly | PaintLayerPaintingCompositingForegroundPhase); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
     else if (compositor()->fixedRootBackgroundLayer())
-        paintFlags |= RenderLayer::PaintLayerPaintingSkipRootBackground;
+        paintFlags |= PaintLayerPaintingSkipRootBackground;
 
     InspectorInstrumentation::willPaint(paintInfo.renderLayer->renderer());
 
@@ -1674,13 +1681,13 @@
 #endif
 
     // FIXME: GraphicsLayers need a way to split for RenderRegions.
-    RenderLayer::LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, LayoutSize());
+    LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, LayoutSize());
     paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags);
 
-    ASSERT(!paintInfo.isBackgroundLayer || paintFlags & RenderLayer::PaintLayerPaintingRootBackgroundOnly);
+    ASSERT(!paintInfo.isBackgroundLayer || paintFlags & PaintLayerPaintingRootBackgroundOnly);
 
     if (paintInfo.renderLayer->containsDirtyOverlayScrollbars())
-        paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags | RenderLayer::PaintLayerPaintingOverlayScrollbars);
+        paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags | PaintLayerPaintingOverlayScrollbars);
 
     ASSERT(!paintInfo.renderLayer->m_usedTransparency);
 
@@ -1733,13 +1740,13 @@
     } else if (graphicsLayer == layerForVerticalScrollbar()) {
         paintScrollbar(m_owningLayer->scrollableArea()->verticalScrollbar(), context, clip);
     } else if (graphicsLayer == layerForScrollCorner()) {
-        const IntRect& scrollCornerAndResizer = m_owningLayer->scrollCornerAndResizerRect();
+        const IntRect& scrollCornerAndResizer = m_owningLayer->scrollableArea()->scrollCornerAndResizerRect();
         context.save();
         context.translate(-scrollCornerAndResizer.x(), -scrollCornerAndResizer.y());
         IntRect transformedClip = clip;
         transformedClip.moveBy(scrollCornerAndResizer.location());
-        m_owningLayer->paintScrollCorner(&context, IntPoint(), transformedClip);
-        m_owningLayer->paintResizer(&context, IntPoint(), transformedClip);
+        m_owningLayer->scrollableArea()->paintScrollCorner(&context, IntPoint(), transformedClip);
+        m_owningLayer->scrollableArea()->paintResizer(&context, IntPoint(), transformedClip);
         context.restore();
     }
 #ifndef NDEBUG
@@ -1770,6 +1777,30 @@
     return client ? client->isTrackingRepaints() : false;
 }
 
+static void collectTrackedRepaintRectsForGraphicsLayer(GraphicsLayer* graphicsLayer, Vector<FloatRect>& rects)
+{
+    if (graphicsLayer)
+        graphicsLayer->collectTrackedRepaintRects(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);
+    return rects.release();
+}
+
 #ifndef NDEBUG
 void CompositedLayerMapping::verifyNotPainting()
 {
@@ -1886,12 +1917,6 @@
     renderer()->animation().notifyAnimationStarted(renderer(), time);
 }
 
-// This is used for the 'freeze' API, for testing only.
-void CompositedLayerMapping::suspendAnimations(double time)
-{
-    m_graphicsLayer->suspendAnimations(time);
-}
-
 IntRect CompositedLayerMapping::compositedBounds() const
 {
     return m_compositedBounds;
diff --git a/Source/core/rendering/CompositedLayerMapping.h b/Source/core/rendering/CompositedLayerMapping.h
index 3280eb8..0582e7e 100644
--- a/Source/core/rendering/CompositedLayerMapping.h
+++ b/Source/core/rendering/CompositedLayerMapping.h
@@ -137,8 +137,6 @@
     void animationPaused(double timeOffset, const String& name);
     void animationFinished(const String& name);
 
-    void suspendAnimations(double time = 0);
-
     IntRect compositedBounds() const;
     void setCompositedBounds(const IntRect&);
     void updateCompositedBounds();
@@ -157,6 +155,8 @@
 
     virtual bool isTrackingRepaints() const OVERRIDE;
 
+    PassOwnPtr<Vector<FloatRect> > collectTrackedRepaintRects() const;
+
 #ifndef NDEBUG
     virtual void verifyNotPainting();
 #endif
@@ -199,7 +199,7 @@
     bool updateClippingMaskLayers(bool needsChildClippingMaskLayer);
     bool requiresHorizontalScrollbarLayer() const { return m_owningLayer->scrollableArea() && m_owningLayer->scrollableArea()->horizontalScrollbar(); }
     bool requiresVerticalScrollbarLayer() const { return m_owningLayer->scrollableArea() && m_owningLayer->scrollableArea()->verticalScrollbar(); }
-    bool requiresScrollCornerLayer() const { return !m_owningLayer->scrollCornerAndResizerRect().isEmpty(); }
+    bool requiresScrollCornerLayer() const { return m_owningLayer->scrollableArea() && !m_owningLayer->scrollableArea()->scrollCornerAndResizerRect().isEmpty(); }
     bool updateScrollingLayers(bool scrollingLayers);
     void updateScrollParent(RenderLayer*);
     void updateClipParent(RenderLayer*);
diff --git a/Source/core/rendering/EllipsisBox.cpp b/Source/core/rendering/EllipsisBox.cpp
index 9570a89..c6e530f 100644
--- a/Source/core/rendering/EllipsisBox.cpp
+++ b/Source/core/rendering/EllipsisBox.cpp
@@ -20,7 +20,6 @@
 #include "config.h"
 #include "core/rendering/EllipsisBox.h"
 
-#include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/HitTestResult.h"
@@ -28,7 +27,8 @@
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RootInlineBox.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
+#include "platform/graphics/DrawLooper.h"
 #include "platform/graphics/TextRun.h"
 
 namespace WebCore {
@@ -41,7 +41,6 @@
     if (styleTextColor != context->fillColor())
         context->setFillColor(styleTextColor);
 
-    Color textColor = styleTextColor;
     const Font& font = style->font();
     if (selectionState() != RenderObject::SelectionNone) {
         paintSelection(context, paintOffset, style, font);
@@ -53,17 +52,18 @@
     }
 
     // Text shadows are disabled when printing. http://crbug.com/258321
-    const ShadowData* shadow = context->printing() ? 0 : style->textShadow();
-    bool hasShadow = shadow;
+    const ShadowList* shadowList = context->printing() ? 0 : style->textShadow();
+    bool hasShadow = shadowList;
     if (hasShadow) {
         DrawLooper drawLooper;
-        do {
-            int shadowX = isHorizontal() ? shadow->x() : shadow->y();
-            int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
+        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();
             FloatSize offset(shadowX, shadowY);
-            drawLooper.addShadow(offset, shadow->blur(), m_renderer->resolveColor(shadow->color()),
+            drawLooper.addShadow(offset, shadow.blur(), m_renderer->resolveColor(shadow.color()),
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
-        } while ((shadow = shadow->next()));
+        }
         drawLooper.addUnmodifiedContent();
         context->setDrawLooper(drawLooper);
     }
diff --git a/Source/core/rendering/FilterEffectRenderer.cpp b/Source/core/rendering/FilterEffectRenderer.cpp
index 91d92ae..1a5c1a2 100644
--- a/Source/core/rendering/FilterEffectRenderer.cpp
+++ b/Source/core/rendering/FilterEffectRenderer.cpp
@@ -32,7 +32,6 @@
 #include "core/fetch/DocumentResource.h"
 #include "core/fetch/DocumentResourceReference.h"
 #include "core/page/Page.h"
-#include "core/platform/graphics/ColorSpace.h"
 #include "core/platform/graphics/filters/FEColorMatrix.h"
 #include "core/platform/graphics/filters/FEComponentTransfer.h"
 #include "core/platform/graphics/filters/FEDropShadow.h"
@@ -48,6 +47,7 @@
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "platform/FloatConversion.h"
 #include "platform/LengthFunctions.h"
+#include "platform/graphics/ColorSpace.h"
 #include "wtf/MathExtras.h"
 #include <algorithm>
 
diff --git a/Source/core/rendering/FixedTableLayout.cpp b/Source/core/rendering/FixedTableLayout.cpp
index 69cd248..83cc6ce 100644
--- a/Source/core/rendering/FixedTableLayout.cpp
+++ b/Source/core/rendering/FixedTableLayout.cpp
@@ -318,4 +318,25 @@
         m_table->setColumnPosition(colPositionsSize - 1, pos);
 }
 
+void FixedTableLayout::willChangeTableLayout()
+{
+    // When switching table layout algorithm, we need to dirty the preferred
+    // logical widths as we cleared the bits without computing them.
+    // (see calcWidthArray above.) This optimization is preferred to always
+    // computing the logical widths we never intended to use.
+    m_table->recalcSectionsIfNeeded();
+    for (RenderTableSection* section = m_table->topNonEmptySection(); section; section = m_table->sectionBelow(section)) {
+        for (unsigned i = 0; i < section->numRows(); i++) {
+            RenderTableRow* row = section->rowRendererAt(i);
+            if (!row)
+                continue;
+            for (RenderObject* cell = row->firstChild(); cell; cell = cell->nextSibling()) {
+                if (!cell->isTableCell())
+                    continue;
+                cell->setPreferredLogicalWidthsDirty();
+            }
+        }
+    }
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/FixedTableLayout.h b/Source/core/rendering/FixedTableLayout.h
index 52d264d..39dffea 100644
--- a/Source/core/rendering/FixedTableLayout.h
+++ b/Source/core/rendering/FixedTableLayout.h
@@ -29,13 +29,14 @@
 
 class RenderTable;
 
-class FixedTableLayout : public TableLayout {
+class FixedTableLayout FINAL : public TableLayout {
 public:
     FixedTableLayout(RenderTable*);
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth) OVERRIDE;
     virtual void applyPreferredLogicalWidthQuirks(LayoutUnit& minWidth, LayoutUnit& maxWidth) const OVERRIDE;
-    virtual void layout();
+    virtual void layout() OVERRIDE;
+    virtual void willChangeTableLayout() OVERRIDE;
 
 private:
     int calcWidthArray();
diff --git a/Source/core/rendering/FloatingObjects.cpp b/Source/core/rendering/FloatingObjects.cpp
index b9ec441..332b30b 100644
--- a/Source/core/rendering/FloatingObjects.cpp
+++ b/Source/core/rendering/FloatingObjects.cpp
@@ -24,7 +24,7 @@
 #include "config.h"
 #include "core/rendering/FloatingObjects.h"
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderView.h"
 
@@ -104,7 +104,7 @@
 public:
     typedef FloatingObjectInterval IntervalType;
 
-    ComputeFloatOffsetAdapter(const RenderBlock* renderer, int lineTop, int lineBottom, LayoutUnit& offset)
+    ComputeFloatOffsetAdapter(const RenderBlockFlow* renderer, int lineTop, int lineBottom, LayoutUnit& offset)
         : m_renderer(renderer)
         , m_lineTop(lineTop)
         , m_lineBottom(lineBottom)
@@ -128,7 +128,7 @@
 private:
     bool updateOffsetIfNeeded(const FloatingObject*);
 
-    const RenderBlock* m_renderer;
+    const RenderBlockFlow* m_renderer;
     int m_lineTop;
     int m_lineBottom;
     LayoutUnit& m_offset;
@@ -154,7 +154,7 @@
 template<>
 inline bool ComputeFloatOffsetAdapter<FloatingObject::FloatLeft>::updateOffsetIfNeeded(const FloatingObject* floatingObject)
 {
-    LayoutUnit logicalRight = floatingObject->logicalRight(m_renderer->isHorizontalWritingMode());
+    LayoutUnit logicalRight = m_renderer->logicalRightForFloat(floatingObject);
     if (logicalRight > m_offset) {
         m_offset = logicalRight;
         return true;
@@ -162,7 +162,7 @@
     return false;
 }
 
-FloatingObjects::FloatingObjects(const RenderBlock* renderer, bool horizontalWritingMode)
+FloatingObjects::FloatingObjects(const RenderBlockFlow* renderer, bool horizontalWritingMode)
     : m_placedFloatsTree(UninitializedTree)
     , m_leftObjectsCount(0)
     , m_rightObjectsCount(0)
@@ -202,10 +202,10 @@
         LayoutUnit lowestFloatBottomLeft = 0;
         LayoutUnit lowestFloatBottomRight = 0;
         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-            FloatingObject* r = *it;
-            if (r->isPlaced()) {
-                FloatingObject::Type curType = r->type();
-                LayoutUnit curFloatLogicalBottom = r->logicalBottom(isInHorizontalWritingMode);
+            FloatingObject* floatingObject = *it;
+            if (floatingObject->isPlaced()) {
+                FloatingObject::Type curType = floatingObject->type();
+                LayoutUnit curFloatLogicalBottom = m_renderer->logicalBottomForFloat(floatingObject);
                 if (curType & FloatingObject::FloatLeft)
                     lowestFloatBottomLeft = max(lowestFloatBottomLeft, curFloatLogicalBottom);
                 if (curType & FloatingObject::FloatRight)
@@ -217,9 +217,9 @@
         setCachedLowestFloatLogicalBottom(isInHorizontalWritingMode, FloatingObject::FloatRight, lowestFloatBottomRight);
     } else {
         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-            FloatingObject* r = *it;
-            if (r->isPlaced() && r->type() == floatType)
-                lowestFloatBottom = max(lowestFloatBottom, r->logicalBottom(isInHorizontalWritingMode));
+            FloatingObject* floatingObject = *it;
+            if (floatingObject->isPlaced() && floatingObject->type() == floatType)
+                lowestFloatBottom = max(lowestFloatBottom, m_renderer->logicalBottomForFloat(floatingObject));
         }
         setCachedLowestFloatLogicalBottom(isInHorizontalWritingMode, floatType, lowestFloatBottom);
     }
@@ -230,7 +230,7 @@
 bool FloatingObjects::hasLowestFloatLogicalBottomCached(bool isHorizontal, FloatingObject::Type type) const
 {
     int floatIndex = static_cast<int>(type) - 1;
-    ASSERT(floatIndex < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue));
+    ASSERT(floatIndex < static_cast<int>(sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue)));
     ASSERT(floatIndex >= 0);
     return (m_cachedHorizontalWritingMode == isHorizontal && !m_lowestFloatBottomCache[floatIndex].dirty);
 }
@@ -238,7 +238,7 @@
 LayoutUnit FloatingObjects::getCachedlowestFloatLogicalBottom(FloatingObject::Type type) const
 {
     int floatIndex = static_cast<int>(type) - 1;
-    ASSERT(floatIndex < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue));
+    ASSERT(floatIndex < static_cast<int>(sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue)));
     ASSERT(floatIndex >= 0);
     return m_lowestFloatBottomCache[floatIndex].value;
 }
@@ -246,7 +246,7 @@
 void FloatingObjects::setCachedLowestFloatLogicalBottom(bool isHorizontal, FloatingObject::Type type, LayoutUnit value)
 {
     int floatIndex = static_cast<int>(type) - 1;
-    ASSERT(floatIndex < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue));
+    ASSERT(floatIndex < static_cast<int>(sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue)));
     ASSERT(floatIndex >= 0);
     m_cachedHorizontalWritingMode = isHorizontal;
     m_lowestFloatBottomCache[floatIndex].value = value;
@@ -255,7 +255,7 @@
 
 void FloatingObjects::markLowestFloatLogicalBottomCacheAsDirty()
 {
-    for (int i = 0; i < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue); ++i)
+    for (size_t i = 0; i < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue); ++i)
         m_lowestFloatBottomCache[i].dirty = true;
 }
 
@@ -431,7 +431,7 @@
 template<>
 inline bool ComputeFloatOffsetAdapter<FloatingObject::FloatRight>::updateOffsetIfNeeded(const FloatingObject* floatingObject)
 {
-    LayoutUnit logicalLeft = floatingObject->logicalLeft(m_renderer->isHorizontalWritingMode());
+    LayoutUnit logicalLeft = m_renderer->logicalLeftForFloat(floatingObject);
     if (logicalLeft < m_offset) {
         m_offset = logicalLeft;
         return true;
@@ -448,8 +448,8 @@
 
     // Make sure the float hasn't changed since it was added to the placed floats tree.
     ASSERT(floatingObject->isPlaced());
-    ASSERT(interval.low() == floatingObject->pixelSnappedLogicalTop(m_renderer->isHorizontalWritingMode()));
-    ASSERT(interval.high() == floatingObject->pixelSnappedLogicalBottom(m_renderer->isHorizontalWritingMode()));
+    ASSERT(interval.low() == m_renderer->pixelSnappedLogicalTopForFloat(floatingObject));
+    ASSERT(interval.high() == m_renderer->pixelSnappedLogicalBottomForFloat(floatingObject));
 
     bool floatIsNewExtreme = updateOffsetIfNeeded(floatingObject);
     if (floatIsNewExtreme)
@@ -459,7 +459,7 @@
 template <FloatingObject::Type FloatTypeValue>
 LayoutUnit ComputeFloatOffsetAdapter<FloatTypeValue>::getHeightRemaining() const
 {
-    return m_outermostFloat ? m_outermostFloat->logicalBottom(m_renderer->isHorizontalWritingMode()) - m_lineTop : LayoutUnit(1);
+    return m_outermostFloat ? m_renderer->logicalBottomForFloat(m_outermostFloat) - m_lineTop : LayoutUnit(1);
 }
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/FloatingObjects.h b/Source/core/rendering/FloatingObjects.h
index 2d3457b..570537c 100644
--- a/Source/core/rendering/FloatingObjects.h
+++ b/Source/core/rendering/FloatingObjects.h
@@ -32,7 +32,7 @@
 
 namespace WebCore {
 
-class RenderBlock;
+class RenderBlockFlow;
 class RenderBox;
 
 enum ShapeOutsideFloatOffsetMode { ShapeOutsideFloatShapeOffset, ShapeOutsideFloatMarginBoxOffset };
@@ -92,48 +92,6 @@
     RootInlineBox* originatingLine() const { return m_originatingLine; }
     void setOriginatingLine(RootInlineBox* line) { m_originatingLine = line; }
 
-    LayoutUnit logicalTop(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? y() : x(); }
-    LayoutUnit logicalBottom(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? maxY() : maxX(); }
-    LayoutUnit logicalLeft(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? x() : y(); }
-    LayoutUnit logicalRight(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? maxX() : maxY(); }
-    LayoutUnit logicalWidth(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? width() : height(); }
-    LayoutUnit logicalHeight(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? height() : width(); }
-    LayoutSize logicalSize(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? m_frameRect.size() : m_frameRect.size().transposedSize(); }
-
-    int pixelSnappedLogicalTop(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedY() : frameRect().pixelSnappedX(); }
-    int pixelSnappedLogicalBottom(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedMaxY() : frameRect().pixelSnappedMaxX(); }
-    int pixelSnappedLogicalLeft(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedX() : frameRect().pixelSnappedY(); }
-    int pixelSnappedLogicalRight(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedMaxX() : frameRect().pixelSnappedMaxY(); }
-
-    void setLogicalTop(LayoutUnit logicalTop, bool isHorizontalWritingMode)
-    {
-        if (isHorizontalWritingMode)
-            setY(logicalTop);
-        else
-            setX(logicalTop);
-    }
-    void setLogicalLeft(LayoutUnit logicalLeft, bool isHorizontalWritingMode)
-    {
-        if (isHorizontalWritingMode)
-            setX(logicalLeft);
-        else
-            setY(logicalLeft);
-    }
-    void setLogicalHeight(LayoutUnit logicalHeight, bool isHorizontalWritingMode)
-    {
-        if (isHorizontalWritingMode)
-            setHeight(logicalHeight);
-        else
-            setWidth(logicalHeight);
-    }
-    void setLogicalWidth(LayoutUnit logicalWidth, bool isHorizontalWritingMode)
-    {
-        if (isHorizontalWritingMode)
-            setWidth(logicalWidth);
-        else
-            setHeight(logicalWidth);
-    }
-
 private:
     explicit FloatingObject(RenderBox*);
     FloatingObject(RenderBox*, Type, const LayoutRect&, bool shouldPaint, bool isDescendant);
@@ -171,7 +129,7 @@
 class FloatingObjects {
     WTF_MAKE_NONCOPYABLE(FloatingObjects); WTF_MAKE_FAST_ALLOCATED;
 public:
-    FloatingObjects(const RenderBlock*, bool horizontalWritingMode);
+    FloatingObjects(const RenderBlockFlow*, bool horizontalWritingMode);
     ~FloatingObjects();
 
     void clear();
@@ -213,7 +171,7 @@
     unsigned m_leftObjectsCount;
     unsigned m_rightObjectsCount;
     bool m_horizontalWritingMode;
-    const RenderBlock* m_renderer;
+    const RenderBlockFlow* m_renderer;
 
     struct FloatBottomCachedValue {
         FloatBottomCachedValue();
diff --git a/Source/core/rendering/HitTestResult.cpp b/Source/core/rendering/HitTestResult.cpp
index 67b56d0..da3f4e6 100644
--- a/Source/core/rendering/HitTestResult.cpp
+++ b/Source/core/rendering/HitTestResult.cpp
@@ -66,16 +66,16 @@
 HitTestResult::HitTestResult(const LayoutPoint& centerPoint, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding)
     : m_hitTestLocation(centerPoint, topPadding, rightPadding, bottomPadding, leftPadding)
     , m_pointInInnerNodeFrame(centerPoint)
-    , m_isFirstLetter(false)
     , m_isOverWidget(false)
+    , m_isFirstLetter(false)
 {
 }
 
 HitTestResult::HitTestResult(const HitTestLocation& other)
     : m_hitTestLocation(other)
     , m_pointInInnerNodeFrame(m_hitTestLocation.point())
-    , m_isFirstLetter(false)
     , m_isOverWidget(false)
+    , m_isFirstLetter(false)
 {
 }
 
@@ -88,8 +88,8 @@
     , m_localPoint(other.localPoint())
     , m_innerURLElement(other.URLElement())
     , m_scrollbar(other.scrollbar())
-    , m_isFirstLetter(other.m_isFirstLetter)
     , m_isOverWidget(other.isOverWidget())
+    , m_isFirstLetter(other.m_isFirstLetter)
 {
     // Only copy the NodeSet in case of rect hit test.
     m_rectBasedTestResult = adoptPtr(other.m_rectBasedTestResult ? new NodeSet(*other.m_rectBasedTestResult) : 0);
@@ -201,7 +201,7 @@
     if (!frame)
         return 0;
 
-    return frame->tree()->find(m_innerURLElement->target());
+    return frame->tree().find(m_innerURLElement->target());
 }
 
 bool HitTestResult::isSelected() const
@@ -255,12 +255,12 @@
         return String();
 
     if (m_innerNonSharedNode->hasTagName(imgTag)) {
-        HTMLImageElement* image = toHTMLImageElement(m_innerNonSharedNode.get());
+        HTMLImageElement* image = toHTMLImageElement(m_innerNonSharedNode);
         return image->getAttribute(altAttr);
     }
 
     if (m_innerNonSharedNode->hasTagName(inputTag)) {
-        HTMLInputElement* input = toHTMLInputElement(m_innerNonSharedNode.get());
+        HTMLInputElement* input = toHTMLInputElement(m_innerNonSharedNode);
         return input->alt();
     }
 
@@ -304,8 +304,7 @@
         || m_innerNonSharedNode->hasTagName(objectTag)
         || m_innerNonSharedNode->hasTagName(SVGNames::imageTag)
        ) {
-        Element* element = toElement(m_innerNonSharedNode.get());
-        urlString = element->imageSourceURL();
+        urlString = toElement(m_innerNonSharedNode)->imageSourceURL();
     } else
         return KURL();
 
@@ -354,7 +353,7 @@
         return false;
 
     if (isHTMLAnchorElement(m_innerURLElement.get()))
-        return toHTMLAnchorElement(m_innerURLElement.get())->isLiveLink();
+        return toHTMLAnchorElement(m_innerURLElement)->isLiveLink();
 
     if (m_innerURLElement->hasTagName(SVGNames::aTag))
         return m_innerURLElement->isLink();
@@ -406,7 +405,7 @@
         return true;
 
     if (m_innerNonSharedNode->hasTagName(inputTag))
-        return toHTMLInputElement(m_innerNonSharedNode.get())->isTextField();
+        return toHTMLInputElement(m_innerNonSharedNode)->isTextField();
 
     return m_innerNonSharedNode->rendererIsEditable();
 }
diff --git a/Source/core/rendering/ImageQualityController.h b/Source/core/rendering/ImageQualityController.h
index 3e6a4c7..f24b732 100644
--- a/Source/core/rendering/ImageQualityController.h
+++ b/Source/core/rendering/ImageQualityController.h
@@ -44,10 +44,10 @@
 typedef HashMap<const void*, LayoutSize> LayerSizeMap;
 typedef HashMap<RenderObject*, LayerSizeMap> ObjectLayerSizeMap;
 
-class ImageQualityController {
+class ImageQualityController FINAL {
     WTF_MAKE_NONCOPYABLE(ImageQualityController); WTF_MAKE_FAST_ALLOCATED;
 public:
-    virtual ~ImageQualityController();
+    ~ImageQualityController();
 
     static ImageQualityController* imageQualityController();
 
diff --git a/Source/core/rendering/InlineBox.cpp b/Source/core/rendering/InlineBox.cpp
index eb32810..a6713e3 100644
--- a/Source/core/rendering/InlineBox.cpp
+++ b/Source/core/rendering/InlineBox.cpp
@@ -20,12 +20,12 @@
 #include "config.h"
 #include "core/rendering/InlineBox.h"
 
-#include "core/platform/graphics/FontMetrics.h"
 #include "core/rendering/InlineFlowBox.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RootInlineBox.h"
 #include "platform/Partitions.h"
+#include "platform/fonts/FontMetrics.h"
 
 #ifndef NDEBUG
 #include <stdio.h>
@@ -49,10 +49,6 @@
 COMPILE_ASSERT(sizeof(InlineBox) == sizeof(SameSizeAsInlineBox), InlineBox_size_guard);
 
 #ifndef NDEBUG
-static bool inInlineBoxDetach;
-#endif
-
-#ifndef NDEBUG
 
 InlineBox::~InlineBox()
 {
diff --git a/Source/core/rendering/InlineBox.h b/Source/core/rendering/InlineBox.h
index 0b2856f..ae0fff2 100644
--- a/Source/core/rendering/InlineBox.h
+++ b/Source/core/rendering/InlineBox.h
@@ -302,11 +302,6 @@
     InlineFlowBox* m_parent; // The box that contains us.
 
 public:
-    RenderObject* m_renderer;
-
-    FloatPoint m_topLeft;
-    float m_logicalWidth;
-
 #define ADD_BOOLEAN_BITFIELD(name, Name) \
     private:\
     unsigned m_##name : 1;\
@@ -385,9 +380,6 @@
     };
 #undef ADD_BOOLEAN_BITFIELD
 
-private:
-    InlineBoxBitfields m_bitfields;
-
 protected:
     // For RootInlineBox
     bool endsWithBreak() const { return m_bitfields.endsWithBreak(); }
@@ -408,8 +400,15 @@
     // For InlineFlowBox and InlineTextBox
     bool extracted() const { return m_bitfields.extracted(); }
 
-#ifndef NDEBUG
+    RenderObject* m_renderer;
+
+    FloatPoint m_topLeft;
+    float m_logicalWidth;
+
 private:
+    InlineBoxBitfields m_bitfields;
+
+#ifndef NDEBUG
     bool m_hasBadParent;
 #endif
 };
diff --git a/Source/core/rendering/InlineIterator.h b/Source/core/rendering/InlineIterator.h
index 1885f8e..0bc1128 100644
--- a/Source/core/rendering/InlineIterator.h
+++ b/Source/core/rendering/InlineIterator.h
@@ -25,6 +25,7 @@
 
 #include "core/rendering/BidiRun.h"
 #include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderText.h"
 #include "wtf/StdLibExtras.h"
 
@@ -469,11 +470,67 @@
 static inline void addPlaceholderRunForIsolatedInline(InlineBidiResolver& resolver, RenderObject* obj, unsigned pos)
 {
     ASSERT(obj);
-    BidiRun* isolatedRun = new BidiRun(pos, 0, obj, resolver.context(), resolver.dir());
+    BidiRun* isolatedRun = new BidiRun(pos, pos, obj, resolver.context(), resolver.dir());
     resolver.runs().addRun(isolatedRun);
     // FIXME: isolatedRuns() could be a hash of object->run and then we could cheaply
     // ASSERT here that we didn't create multiple objects for the same inline.
     resolver.isolatedRuns().append(isolatedRun);
+    LineMidpointState& lineMidpointState = resolver.midpointState();
+    resolver.setMidpointStateForIsolatedRun(isolatedRun, lineMidpointState);
+}
+
+static inline BidiRun* createRun(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
+{
+    return new BidiRun(start, end, obj, resolver.context(), resolver.dir());
+}
+
+enum AppendRunBehavior {
+    AppendingFakeRun,
+    AppendingRunsForObject
+};
+
+static void adjustMidpointsAndAppendRunsForObjectIfNeeded(RenderObject* obj, unsigned start, unsigned end, InlineBidiResolver& resolver, AppendRunBehavior behavior = AppendingFakeRun, BidiRunList<BidiRun>* runs = 0)
+{
+    if (start > end || RenderBlock::shouldSkipCreatingRunsForObject(obj))
+        return;
+
+    LineMidpointState& lineMidpointState = resolver.midpointState();
+    bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
+    InlineIterator nextMidpoint;
+    if (haveNextMidpoint)
+        nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
+    if (lineMidpointState.betweenMidpoints) {
+        if (!(haveNextMidpoint && nextMidpoint.m_obj == obj))
+            return;
+        // This is a new start point. Stop ignoring objects and
+        // adjust our start.
+        lineMidpointState.betweenMidpoints = false;
+        start = nextMidpoint.m_pos;
+        lineMidpointState.currentMidpoint++;
+        if (start < end)
+            return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, end, resolver, behavior, runs);
+    } else {
+        if (!haveNextMidpoint || (obj != nextMidpoint.m_obj)) {
+            if (behavior == AppendingFakeRun)
+                return;
+            runs->addRun(createRun(start, end, obj, resolver));
+            return;
+        }
+
+        // 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 && behavior == AppendingRunsForObject)
+                    runs->addRun(createRun(start, nextMidpoint.m_pos + 1, obj, resolver));
+                return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, nextMidpoint.m_pos + 1, end, resolver, behavior, runs);
+            }
+        } else if (behavior == AppendingRunsForObject) {
+            runs->addRun(createRun(start, end, obj, resolver));
+        }
+    }
 }
 
 class IsolateTracker {
@@ -498,26 +555,23 @@
     void embed(WTF::Unicode::Direction, BidiEmbeddingSource) { }
     void commitExplicitEmbedding() { }
 
-    void addFakeRunIfNecessary(RenderObject* obj, unsigned pos, InlineBidiResolver& resolver)
+
+    void addFakeRunIfNecessary(RenderObject* obj, unsigned pos, unsigned end, InlineBidiResolver& resolver)
     {
         // We only need to add a fake run for a given isolated span once during each call to createBidiRunsForLine.
         // We'll be called for every span inside the isolated span so we just ignore subsequent calls.
         // We also avoid creating a fake run until we hit a child that warrants one, e.g. we skip floats.
-        if (m_haveAddedFakeRunForRootIsolate || RenderBlock::shouldSkipCreatingRunsForObject(obj))
+        if (RenderBlock::shouldSkipCreatingRunsForObject(obj))
             return;
-        m_haveAddedFakeRunForRootIsolate = true;
+        if (!m_haveAddedFakeRunForRootIsolate) {
+            addPlaceholderRunForIsolatedInline(resolver, obj, pos);
+            m_haveAddedFakeRunForRootIsolate = true;
+        }
+        adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, pos, end, resolver);
+
         // obj and pos together denote a single position in the inline, from which the parsing of the isolate will start.
         // We don't need to mark the end of the run because this is implicit: it is either endOfLine or the end of the
         // isolate, when we call createBidiRunsForLine it will stop at whichever comes first.
-        addPlaceholderRunForIsolatedInline(resolver, obj, pos);
-        // FIXME: Inline isolates don't work properly with collapsing whitespace, see webkit.org/b/109624
-        // For now, if we enter an isolate between midpoints, we increment our current midpoint or else
-        // we'll leave the isolate and ignore the content that follows.
-        MidpointState<InlineIterator>& midpointState = resolver.midpointState();
-        if (midpointState.betweenMidpoints && midpointState.midpoints[midpointState.currentMidpoint].object() == obj) {
-            midpointState.betweenMidpoints = false;
-            ++midpointState.currentMidpoint;
-        }
     }
 
 private:
@@ -537,9 +591,9 @@
         RenderObject* obj = m_sor.m_obj;
         while (obj && obj != m_eor.m_obj && obj != endOfLine.m_obj) {
             if (isolateTracker.inIsolate())
-                isolateTracker.addFakeRunIfNecessary(obj, start, *this);
+                isolateTracker.addFakeRunIfNecessary(obj, start, obj->length(), *this);
             else
-                RenderBlock::appendRunsForObject(m_runs, start, obj->length(), obj, *this);
+                RenderBlockFlow::appendRunsForObject(m_runs, start, obj->length(), obj, *this);
             // FIXME: start/obj should be an InlineIterator instead of two separate variables.
             start = 0;
             obj = bidiNextSkippingEmptyInlines(m_sor.root(), obj, &isolateTracker);
@@ -553,9 +607,9 @@
             // 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;
             if (isolateTracker.inIsolate())
-                isolateTracker.addFakeRunIfNecessary(obj, start, *this);
+                isolateTracker.addFakeRunIfNecessary(obj, start, end, *this);
             else
-                RenderBlock::appendRunsForObject(m_runs, start, end, obj, *this);
+                RenderBlockFlow::appendRunsForObject(m_runs, start, end, obj, *this);
         }
 
         m_eor.increment();
diff --git a/Source/core/rendering/InlineTextBox.cpp b/Source/core/rendering/InlineTextBox.cpp
index 20e4204..c5eff52 100644
--- a/Source/core/rendering/InlineTextBox.cpp
+++ b/Source/core/rendering/InlineTextBox.cpp
@@ -32,7 +32,6 @@
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/WidthIterator.h"
@@ -46,8 +45,9 @@
 #include "core/rendering/RenderRubyRun.h"
 #include "core/rendering/RenderRubyText.h"
 #include "core/rendering/RenderTheme.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
+#include "platform/graphics/DrawLooper.h"
 #include "wtf/Vector.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
@@ -393,21 +393,21 @@
     const AtomicString& emphasisMark, int emphasisMarkOffset,
     int startOffset, int endOffset, int truncationPoint,
     const FloatPoint& textOrigin, const FloatRect& boxRect,
-    const ShadowData* shadow, bool stroked, bool horizontal)
+    const ShadowList* shadowList, bool stroked, bool horizontal)
 {
     // Text shadows are disabled when printing. http://crbug.com/258321
-    bool hasShadow = shadow && !context->printing();
-    Color fillColor = context->fillColor();
+    bool hasShadow = shadowList && !context->printing();
 
     if (hasShadow) {
         DrawLooper drawLooper;
-        do {
-            int shadowX = horizontal ? shadow->x() : shadow->y();
-            int shadowY = horizontal ? shadow->y() : -shadow->x();
+        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();
             FloatSize offset(shadowX, shadowY);
-            drawLooper.addShadow(offset, shadow->blur(), renderer->resolveColor(shadow->color()),
+            drawLooper.addShadow(offset, shadow.blur(), renderer->resolveColor(shadow.color()),
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
-        } while ((shadow = shadow->next()));
+        }
         drawLooper.addUnmodifiedContent();
         context->setDrawLooper(drawLooper);
     }
@@ -550,7 +550,7 @@
     float textStrokeWidth = styleToUse->textStrokeWidth();
 
     // Text shadows are disabled when printing. http://crbug.com/258321
-    const ShadowData* textShadow = (context->printing() || paintInfo.forceBlackText()) ? 0 : styleToUse->textShadow();
+    const ShadowList* textShadow = (context->printing() || paintInfo.forceBlackText()) ? 0 : styleToUse->textShadow();
 
     if (paintInfo.forceBlackText()) {
         textFillColor = Color::black;
@@ -591,7 +591,7 @@
     Color selectionStrokeColor = textStrokeColor;
     Color selectionEmphasisMarkColor = emphasisMarkColor;
     float selectionStrokeWidth = textStrokeWidth;
-    const ShadowData* selectionShadow = textShadow;
+    const ShadowList* selectionShadow = textShadow;
     if (haveSelection) {
         // Check foreground color first.
         Color foreground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionForegroundColor();
@@ -610,7 +610,7 @@
 
         if (RenderStyle* pseudoStyle = renderer()->getCachedPseudoStyle(SELECTION)) {
             // Text shadows are disabled when printing. http://crbug.com/258321
-            const ShadowData* shadow = (context->printing() || paintInfo.forceBlackText()) ? 0 : pseudoStyle->textShadow();
+            const ShadowList* shadow = (context->printing() || paintInfo.forceBlackText()) ? 0 : pseudoStyle->textShadow();
             if (shadow != selectionShadow) {
                 if (!paintSelectedTextOnly)
                     paintSelectedTextSeparately = true;
@@ -1065,12 +1065,11 @@
     context->strokePath(path);
 }
 
-void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, TextDecoration deco, TextDecorationStyle decorationStyle, const ShadowData* shadow)
+void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, TextDecoration deco, TextDecorationStyle decorationStyle, const ShadowList* shadowList)
 {
     GraphicsContextStateSaver stateSaver(*context);
 
-    // FIXME: We should improve this rule and not always just assume 1.
-    const float textDecorationThickness = 1.f;
+    float textDecorationThickness = 1.f;
 
     if (m_truncation == cFullTruncation)
         return;
@@ -1092,41 +1091,48 @@
 
     // Use a special function for underlines to get the positioning exactly right.
     bool isPrinting = textRenderer()->document().printing();
-    context->setStrokeThickness(textDecorationThickness);
 
     bool linesAreOpaque = !isPrinting && (!(deco & TextDecorationUnderline) || underline.alpha() == 255) && (!(deco & TextDecorationOverline) || overline.alpha() == 255) && (!(deco & TextDecorationLineThrough) || linethrough.alpha() == 255);
 
     RenderStyle* styleToUse = renderer()->style(isFirstLineStyle());
     int baseline = styleToUse->fontMetrics().ascent();
 
+    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.
+    textDecorationThickness = max(textDecorationThickness, styleToUse->computedFontSize() / 10.0f);
+    context->setStrokeThickness(textDecorationThickness);
+
     int extraOffset = 0;
-    if (!linesAreOpaque && shadow && shadow->next()) {
+    if (!linesAreOpaque && shadowCount > 1) {
         FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
-        for (const ShadowData* s = shadow; s; s = s->next()) {
+        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();
+            shadowRect.inflate(s.blur());
+            int shadowX = isHorizontal() ? s.x() : s.y();
+            int 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, shadowY) + s.blur());
         }
         context->clip(clipRect);
         extraOffset += baseline + 2;
         localOrigin.move(0, extraOffset);
     }
 
-    do {
-        if (shadow) {
-            if (!shadow->next()) {
+    for (size_t i = max(static_cast<size_t>(1), shadowCount); i--; ) {
+        // Even if we have no shadows, we still want to run the code below this once.
+        if (i < shadowCount) {
+            if (!i) {
                 // The last set of lines paints normally inside the clip.
                 localOrigin.move(0, -extraOffset);
                 extraOffset = 0;
             }
-            int shadowX = isHorizontal() ? shadow->x() : shadow->y();
-            int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
-            context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow->blur(), shadow->color());
-            shadow = shadow->next();
+            const ShadowData& shadow = shadowList->shadows()[i];
+            int shadowX = isHorizontal() ? shadow.x() : shadow.y();
+            int shadowY = isHorizontal() ? shadow.y() : -shadow.x();
+            context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow.blur(), shadow.color());
         }
 
         // Offset between lines - always non-zero, so lines never cross each other.
@@ -1185,7 +1191,7 @@
                     context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + doubleOffset + 2 * baseline / 3), width, isPrinting);
             }
         }
-    } while (shadow);
+    }
 }
 
 static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
diff --git a/Source/core/rendering/InlineTextBox.h b/Source/core/rendering/InlineTextBox.h
index fc25c1b..fcd133e 100644
--- a/Source/core/rendering/InlineTextBox.h
+++ b/Source/core/rendering/InlineTextBox.h
@@ -178,7 +178,7 @@
     void paintCompositionUnderline(GraphicsContext*, const FloatPoint& boxOrigin, const CompositionUnderline&);
 
 private:
-    void paintDecoration(GraphicsContext*, const FloatPoint& boxOrigin, TextDecoration, TextDecorationStyle, const ShadowData*);
+    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&);
diff --git a/Source/core/rendering/LayerPaintingInfo.h b/Source/core/rendering/LayerPaintingInfo.h
new file mode 100644
index 0000000..b9af031
--- /dev/null
+++ b/Source/core/rendering/LayerPaintingInfo.h
@@ -0,0 +1,100 @@
+/*
+ * 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 LayerPaintingInfo_h
+#define LayerPaintingInfo_h
+
+#include "core/rendering/PaintInfo.h"
+#include "platform/geometry/LayoutRect.h"
+
+namespace WebCore {
+
+class RenderLayer;
+
+enum PaintLayerFlag {
+    PaintLayerHaveTransparency = 1,
+    PaintLayerAppliedTransform = 1 << 1,
+    PaintLayerTemporaryClipRects = 1 << 2,
+    PaintLayerPaintingReflection = 1 << 3,
+    PaintLayerPaintingOverlayScrollbars = 1 << 4,
+    PaintLayerPaintingCompositingBackgroundPhase = 1 << 5,
+    PaintLayerPaintingCompositingForegroundPhase = 1 << 6,
+    PaintLayerPaintingCompositingMaskPhase = 1 << 7,
+    PaintLayerPaintingCompositingScrollingPhase = 1 << 8,
+    PaintLayerPaintingOverflowContents = 1 << 9,
+    PaintLayerPaintingRootBackgroundOnly = 1 << 10,
+    PaintLayerPaintingSkipRootBackground = 1 << 11,
+    PaintLayerPaintingChildClippingMaskPhase = 1 << 12,
+    PaintLayerPaintingCompositingAllPhases = (PaintLayerPaintingCompositingBackgroundPhase | PaintLayerPaintingCompositingForegroundPhase | PaintLayerPaintingCompositingMaskPhase)
+};
+
+typedef unsigned PaintLayerFlags;
+
+struct LayerPaintingInfo {
+    LayerPaintingInfo(RenderLayer* inRootLayer, const LayoutRect& inDirtyRect,
+        PaintBehavior inPaintBehavior, const LayoutSize& inSubPixelAccumulation,
+        RenderObject* inPaintingRoot = 0, RenderRegion*inRegion = 0,
+        OverlapTestRequestMap* inOverlapTestRequests = 0)
+        : rootLayer(inRootLayer)
+        , paintingRoot(inPaintingRoot)
+        , paintDirtyRect(inDirtyRect)
+        , subPixelAccumulation(inSubPixelAccumulation)
+        , region(inRegion)
+        , overlapTestRequests(inOverlapTestRequests)
+        , paintBehavior(inPaintBehavior)
+        , clipToDirtyRect(true)
+    { }
+    RenderLayer* rootLayer;
+    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;
+};
+
+} // namespace WebCore
+
+#endif // LayerPaintingInfo_h
diff --git a/Source/core/rendering/LineWidth.cpp b/Source/core/rendering/LineWidth.cpp
index a7b6659..ea720e2 100644
--- a/Source/core/rendering/LineWidth.cpp
+++ b/Source/core/rendering/LineWidth.cpp
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-LineWidth::LineWidth(RenderBlock& block, bool isFirstLine, IndentTextOrNot shouldIndentText)
+LineWidth::LineWidth(RenderBlockFlow& block, bool isFirstLine, IndentTextOrNot shouldIndentText)
     : m_block(block)
     , m_uncommittedWidth(0)
     , m_committedWidth(0)
@@ -69,7 +69,7 @@
 void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(FloatingObject* newFloat)
 {
     LayoutUnit height = m_block.logicalHeight();
-    if (height < newFloat->logicalTop(m_block.isHorizontalWritingMode()) || height >= newFloat->logicalBottom(m_block.isHorizontalWritingMode()))
+    if (height < m_block.logicalTopForFloat(newFloat) || height >= m_block.logicalBottomForFloat(newFloat))
         return;
 
     // When floats with shape outside are stacked, the floats are positioned based on the margin box of the float,
@@ -97,7 +97,7 @@
         shapeOutsideInfo->updateDeltasForContainingBlockLine(&m_block, newFloat, m_block.logicalHeight(), lineHeight);
 
     if (newFloat->type() == FloatingObject::FloatLeft) {
-        float newLeft = newFloat->logicalRight(m_block.isHorizontalWritingMode());
+        float newLeft = m_block.logicalRightForFloat(newFloat);
         if (previousShapeOutsideInfo)
             newLeft -= previousShapeOutsideInfo->rightMarginBoxDelta();
         if (shapeOutsideInfo)
@@ -107,7 +107,7 @@
             newLeft += floorToInt(m_block.textIndentOffset());
         m_left = std::max<float>(m_left, newLeft);
     } else {
-        float newRight = newFloat->logicalLeft(m_block.isHorizontalWritingMode());
+        float newRight = m_block.logicalLeftForFloat(newFloat);
         if (previousShapeOutsideInfo)
             newRight -= previousShapeOutsideInfo->leftMarginBoxDelta();
         if (shapeOutsideInfo)
diff --git a/Source/core/rendering/LineWidth.h b/Source/core/rendering/LineWidth.h
index 80a6efa..84b4ec5 100644
--- a/Source/core/rendering/LineWidth.h
+++ b/Source/core/rendering/LineWidth.h
@@ -38,6 +38,7 @@
 class RenderBlock;
 class RenderObject;
 class RenderRubyRun;
+class RenderBlockFlow;
 
 struct LineSegment;
 
@@ -45,7 +46,7 @@
 
 class LineWidth {
 public:
-    LineWidth(RenderBlock&, bool isFirstLine, IndentTextOrNot shouldIndentText);
+    LineWidth(RenderBlockFlow&, bool isFirstLine, IndentTextOrNot shouldIndentText);
 
     bool fitsOnLine() const { return currentWidth() <= m_availableWidth; }
     bool fitsOnLine(float extra) const { return currentWidth() + extra <= m_availableWidth; }
@@ -70,7 +71,7 @@
 private:
     void computeAvailableWidthFromLeftAndRight();
 
-    RenderBlock& m_block;
+    RenderBlockFlow& m_block;
     float m_uncommittedWidth;
     float m_committedWidth;
     float m_overhangWidth; // The amount by which |m_availableWidth| has been inflated to account for possible contraction due to ruby overhang.
diff --git a/Source/core/rendering/RenderBlock.cpp b/Source/core/rendering/RenderBlock.cpp
index ff6207f..16d51d7 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -28,7 +28,6 @@
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
-#include "core/dom/Text.h"
 #include "core/events/OverflowEvent.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
@@ -74,7 +73,7 @@
 using namespace HTMLNames;
 
 struct SameSizeAsRenderBlock : public RenderBox {
-    void* pointers[2];
+    void* pointers[1];
     RenderObjectChildList children;
     RenderLineBoxList lineBoxes;
     uint32_t bitfields;
@@ -99,8 +98,6 @@
 
 static bool gColumnFlowSplitEnabled = true;
 
-bool RenderBlock::s_canPropagateFloatIntoSibling = false;
-
 // This class helps dispatching the 'overflow' event on layout change. overflow can be set on RenderBoxes, yet the existing code
 // only works on RenderBlocks. If this changes, this class should be shared with other RenderBoxes.
 class OverflowEventDispatcher {
@@ -245,7 +242,6 @@
 void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
 {
     RenderStyle* oldStyle = style();
-    s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
 
     setReplaced(newStyle->isDisplayInlineType());
 
@@ -269,9 +265,6 @@
             if (cb->isRenderBlock())
                 toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
         }
-
-        if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
-            markAllDescendantsWithFloatsForLayout();
     }
 
     RenderBox::styleWillChange(diff, newStyle);
@@ -312,36 +305,6 @@
     propagateStyleToAnonymousChildren(true);
     m_lineHeight = -1;
 
-    // After our style changed, if we lose our ability to propagate floats into next sibling
-    // blocks, then we need to find the top most parent containing that overhanging float and
-    // then mark its descendants with floats for layout and clear all floats from its next
-    // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
-    bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
-    if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
-        RenderBlock* parentBlock = this;
-        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-        FloatingObjectSetIterator end = floatingObjectSet.end();
-
-        for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
-            if (curr->isRenderBlock()) {
-                RenderBlock* currBlock = toRenderBlock(curr);
-
-                if (currBlock->hasOverhangingFloats()) {
-                    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-                        RenderBox* renderer = (*it)->renderer();
-                        if (currBlock->hasOverhangingFloat(renderer)) {
-                            parentBlock = currBlock;
-                            break;
-                        }
-                    }
-                }
-            }
-        }
-
-        parentBlock->markAllDescendantsWithFloatsForLayout();
-        parentBlock->markSiblingsWithFloatsForLayout();
-    }
-
     // 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);
@@ -613,7 +576,8 @@
         // We can reuse this block and make it the preBlock of the next continuation.
         pre = block;
         pre->removePositionedObjects(0);
-        pre->removeFloatingObjects();
+        if (block->isRenderBlockFlow())
+            toRenderBlockFlow(pre)->removeFloatingObjects();
         block = toRenderBlock(block->parent());
     } else {
         // No anonymous block available for use.  Make one.
@@ -918,8 +882,6 @@
 
 void RenderBlock::deleteLineBoxTree()
 {
-    if (containsFloats())
-        m_floatingObjects->clearLineBoxTreePointers();
     m_lineBoxes.deleteLineBoxTree();
 
     if (AXObjectCache* cache = document().existingAXObjectCache())
@@ -1094,47 +1056,6 @@
     child->destroy();
 }
 
-void RenderBlock::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
-{
-    moveAllChildrenTo(toBlock, fullRemoveInsert);
-
-    // When a portion of the render tree is being detached, anonymous blocks
-    // will be combined as their children are deleted. In this process, the
-    // anonymous block later in the tree is merged into the one preceeding it.
-    // It can happen that the later block (this) contains floats that the
-    // previous block (toBlock) did not contain, and thus are not in the
-    // floating objects list for toBlock. This can result in toBlock containing
-    // floats that are not in it's floating objects list, but are in the
-    // floating objects lists of siblings and parents. This can cause problems
-    // when the float itself is deleted, since the deletion code assumes that
-    // if a float is not in it's containing block's floating objects list, it
-    // isn't in any floating objects list. In order to preserve this condition
-    // (removing it has serious performance implications), we need to copy the
-    // floating objects from the old block (this) to the new block (toBlock).
-    // The float's metrics will likely all be wrong, but since toBlock is
-    // already marked for layout, this will get fixed before anything gets
-    // displayed.
-    // See bug https://code.google.com/p/chromium/issues/detail?id=230907
-    if (m_floatingObjects) {
-        if (!toBlock->m_floatingObjects)
-            toBlock->createFloatingObjects();
-
-        const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
-        FloatingObjectSetIterator end = fromFloatingObjectSet.end();
-
-        for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
-            FloatingObject* floatingObject = *it;
-
-            // Don't insert the object again if it's already in the list
-            if (toBlock->containsFloat(floatingObject->renderer()))
-                continue;
-
-            toBlock->m_floatingObjects->add(floatingObject->unsafeClone());
-        }
-    }
-
-}
-
 void RenderBlock::removeChild(RenderObject* oldChild)
 {
     // No need to waste time in merging or removing empty anonymous blocks.
@@ -1317,7 +1238,7 @@
         for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
             RenderBlock* block = *it;
             if (block->hasOverflowClip()) {
-                block->layer()->updateScrollInfoAfterLayout();
+                block->layer()->scrollableArea()->updateAfterLayout();
             }
         }
     }
@@ -1331,14 +1252,14 @@
             // Workaround for now. We cannot delay the scroll info for overflow
             // for items with opposite writing directions, as the contents needs
             // to overflow in that direction
-            layer()->updateScrollInfoAfterLayout();
+            layer()->scrollableArea()->updateAfterLayout();
             return;
         }
 
         if (gDelayUpdateScrollInfo)
             gDelayedUpdateScrollInfoSet->add(this);
         else
-            layer()->updateScrollInfoAfterLayout();
+            layer()->scrollableArea()->updateAfterLayout();
     }
 }
 
@@ -1385,7 +1306,7 @@
         // 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)
+        if (region && region->logicalHeight())
             shapeInsideInfo = region->shapeInsideInfo();
     }
 
@@ -1585,16 +1506,13 @@
     }
 }
 
-void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
+void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool)
 {
     m_overflow.clear();
 
     // Add overflow from children.
     addOverflowFromChildren();
 
-    if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
-        addOverflowFromFloats();
-
     // Add in the overflow from positioned objects.
     addOverflowFromPositionedObjects();
 
@@ -1639,20 +1557,6 @@
     }
 }
 
-void RenderBlock::addOverflowFromFloats()
-{
-    if (!m_floatingObjects)
-        return;
-
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObjectSetIterator end = floatingObjectSet.end();
-    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-        FloatingObject* r = *it;
-        if (r->isDescendant())
-            addOverflowFromChild(r->renderer(), IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
-    }
-}
-
 void RenderBlock::addOverflowFromPositionedObjects()
 {
     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
@@ -2124,32 +2028,6 @@
         layoutScope.setChildNeedsLayout(this);
 }
 
-void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
-{
-    // Repaint any overhanging floats (if we know we're the one to paint them).
-    // Otherwise, bail out.
-    if (!hasOverhangingFloats())
-        return;
-
-    // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
-    // in this block. Better yet would be to push extra state for the containers of other floats.
-    LayoutStateDisabler layoutStateDisabler(view());
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObjectSetIterator end = floatingObjectSet.end();
-    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-        FloatingObject* r = *it;
-        // Only repaint the object if it is overhanging, is not in its own layer, and
-        // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
-        // condition is replaced with being a descendant of us.
-        if (r->logicalBottom(isHorizontalWritingMode()) > logicalHeight()
-            && !r->renderer()->hasSelfPaintingLayer()
-            && (r->shouldPaint() || (paintAllDescendants && r->renderer()->isDescendantOf(this)))) {
-            r->renderer()->repaint();
-            r->renderer()->repaintOverhangingFloats(false);
-        }
-    }
-}
-
 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
@@ -2185,7 +2063,7 @@
     // z-index.  We paint after we painted the background/border, so that the scrollbars will
     // sit above the background/border.
     if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(this) && !paintInfo.paintRootBackgroundOnly())
-        layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
+        layer()->scrollableArea()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect, false /* paintingOverlayControls */);
 }
 
 void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
@@ -2515,49 +2393,6 @@
     }
 }
 
-LayoutPoint RenderBlock::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
-{
-    if (!style()->isFlippedBlocksWritingMode())
-        return point;
-
-    // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
-    // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
-    // case.
-    if (isHorizontalWritingMode())
-        return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
-    return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
-}
-
-void RenderBlock::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
-{
-    if (!m_floatingObjects)
-        return;
-
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObjectSetIterator end = floatingObjectSet.end();
-    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-        FloatingObject* r = *it;
-        // Only paint the object if our m_shouldPaint flag is set.
-        if (r->shouldPaint() && !r->renderer()->hasSelfPaintingLayer()) {
-            PaintInfo currentPaintInfo(paintInfo);
-            currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
-            // FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make this much cleaner.
-            LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->renderer()->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->renderer()->y()));
-            r->renderer()->paint(currentPaintInfo, childPoint);
-            if (!preservePhase) {
-                currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
-                r->renderer()->paint(currentPaintInfo, childPoint);
-                currentPaintInfo.phase = PaintPhaseFloat;
-                r->renderer()->paint(currentPaintInfo, childPoint);
-                currentPaintInfo.phase = PaintPhaseForeground;
-                r->renderer()->paint(currentPaintInfo, childPoint);
-                currentPaintInfo.phase = PaintPhaseOutline;
-                r->renderer()->paint(currentPaintInfo, childPoint);
-            }
-        }
-    }
-}
-
 RenderInline* RenderBlock::inlineElementContinuation() const
 {
     RenderBoxModelObject* continuation = this->continuation();
@@ -2759,19 +2594,7 @@
         if (isBody() || isRoot()) // The <body> must make sure to examine its containingBlock's positioned objects.
             for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
                 clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->positionedObjects()); // FIXME: Not right for flipped writing modes.
-        if (m_floatingObjects) {
-            const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-            FloatingObjectSetIterator end = floatingObjectSet.end();
-            for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-                FloatingObject* r = *it;
-                LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(r),
-                                    offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(r),
-                                    r->renderer()->width(), r->renderer()->height());
-                rootBlock->flipForWritingMode(floatBox);
-                floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
-                paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
-            }
-        }
+        clipOutFloatingObjects(rootBlock, paintInfo, rootBlockPhysicalPosition, offsetFromRootBlock);
     }
 
     // FIXME: overflow: auto/scroll regions need more math here, since painting in the border box is different from painting in the padding box (one is scrolled, the other is
@@ -3163,310 +2986,6 @@
         removePositionedObject(deadObjects.at(i));
 }
 
-void RenderBlock::removeFloatingObjects()
-{
-    if (!m_floatingObjects)
-        return;
-
-    m_floatingObjects->clear();
-}
-
-FloatingObject* RenderBlock::insertFloatingObject(RenderBox* o)
-{
-    ASSERT(o->isFloating());
-
-    // Create the list of special objects if we don't aleady have one
-    if (!m_floatingObjects)
-        createFloatingObjects();
-    else {
-        // Don't insert the object again if it's already in the list
-        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-        FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(o);
-        if (it != floatingObjectSet.end())
-            return *it;
-    }
-
-    // Create the special object entry & append it to the list
-
-    OwnPtr<FloatingObject> newObj = FloatingObject::create(o);
-
-    // Our location is irrelevant if we're unsplittable or no pagination is in effect.
-    // Just go ahead and lay out the float.
-    bool isChildRenderBlock = o->isRenderBlock();
-    if (isChildRenderBlock && !o->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
-        o->setChildNeedsLayout(MarkOnlyThis);
-
-    bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
-    if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) // We are unsplittable if we're a block flow root.
-        o->layoutIfNeeded();
-    else {
-        o->updateLogicalWidth();
-        o->computeAndSetBlockDirectionMargins(this);
-    }
-
-    newObj->setLogicalWidth(logicalWidthForChild(o) + marginStartForChild(o) + marginEndForChild(o), isHorizontalWritingMode());
-
-    if (ShapeOutsideInfo* shapeOutside = o->shapeOutsideInfo())
-        shapeOutside->setShapeSize(logicalWidthForChild(o), logicalHeightForChild(o));
-
-    return m_floatingObjects->add(newObj.release());
-}
-
-void RenderBlock::removeFloatingObject(RenderBox* o)
-{
-    if (m_floatingObjects) {
-        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-        FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(o);
-        if (it != floatingObjectSet.end()) {
-            FloatingObject* r = *it;
-            if (childrenInline()) {
-                LayoutUnit logicalTop = r->logicalTop(isHorizontalWritingMode());
-                LayoutUnit logicalBottom = r->logicalBottom(isHorizontalWritingMode());
-
-                // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
-                if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max())
-                    logicalBottom = LayoutUnit::max();
-                else {
-                    // Special-case zero- and less-than-zero-height floats: those don't touch
-                    // the line that they're on, but it still needs to be dirtied. This is
-                    // accomplished by pretending they have a height of 1.
-                    logicalBottom = max(logicalBottom, logicalTop + 1);
-                }
-                if (r->originatingLine()) {
-                    if (!selfNeedsLayout()) {
-                        ASSERT(r->originatingLine()->renderer() == this);
-                        r->originatingLine()->markDirty();
-                    }
-#if !ASSERT_DISABLED
-                    r->setOriginatingLine(0);
-#endif
-                }
-                markLinesDirtyInBlockRange(0, logicalBottom);
-            }
-            m_floatingObjects->remove(r);
-        }
-    }
-}
-
-void RenderBlock::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
-{
-    if (!containsFloats())
-        return;
-
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObject* curr = floatingObjectSet.last();
-    while (curr != lastFloat && (!curr->isPlaced() || curr->logicalTop(isHorizontalWritingMode()) >= logicalOffset)) {
-        m_floatingObjects->remove(curr);
-        if (floatingObjectSet.isEmpty())
-            break;
-        curr = floatingObjectSet.last();
-    }
-}
-
-LayoutPoint RenderBlock::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
-{
-    RenderBox* childBox = floatingObject->renderer();
-    LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // 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();
-    // FIXME: Implement behavior for right floats.
-    if (shapeInsideInfo) {
-        LayoutSize floatLogicalSize = floatingObject->logicalSize(isHorizontalWritingMode());
-        // floatingObject's logicalSize doesn't contain the actual height at this point, so we need to calculate it
-        floatLogicalSize.setHeight(logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
-
-        // FIXME: If the float doesn't fit in the shape we should push it under the content box
-        logicalTopOffset = shapeInsideInfo->computeFirstFitPositionForFloat(floatLogicalSize);
-        if (logicalHeight() > logicalTopOffset)
-            logicalTopOffset = logicalHeight();
-
-        SegmentList segments = shapeInsideInfo->computeSegmentsForLine(logicalTopOffset, floatLogicalSize.height());
-        // FIXME: Add support for shapes with multiple segments.
-        if (segments.size() == 1) {
-            // The segment offsets are relative to the content box.
-            logicalRightOffset = logicalLeftOffset + segments[0].logicalRight;
-            logicalLeftOffset += segments[0].logicalLeft;
-        }
-    } else
-        logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset);
-
-    LayoutUnit floatLogicalWidth = min(floatingObject->logicalWidth(isHorizontalWritingMode()), logicalRightOffset - logicalLeftOffset); // The width we look for.
-
-    LayoutUnit floatLogicalLeft;
-
-    bool insideFlowThread = flowThreadContainingBlock();
-
-    if (childBox->style()->floating() == LeftFloat) {
-        LayoutUnit heightRemainingLeft = 1;
-        LayoutUnit heightRemainingRight = 1;
-        floatLogicalLeft = logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
-        while (logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
-            logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
-            floatLogicalLeft = logicalLeftOffsetForLineIgnoringShapeOutside(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.
-                floatLogicalWidth = min(floatingObject->logicalWidth(isHorizontalWritingMode()), logicalRightOffset - logicalLeftOffset);
-            }
-        }
-        floatLogicalLeft = max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
-    } else {
-        LayoutUnit heightRemainingLeft = 1;
-        LayoutUnit heightRemainingRight = 1;
-        floatLogicalLeft = logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
-        while (floatLogicalLeft - logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
-            logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
-            floatLogicalLeft = logicalRightOffsetForLineIgnoringShapeOutside(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.
-                floatLogicalWidth = min(floatingObject->logicalWidth(isHorizontalWritingMode()), logicalRightOffset - logicalLeftOffset);
-            }
-        }
-        floatLogicalLeft -= floatingObject->logicalWidth(isHorizontalWritingMode()); // Use the original width of the float here, since the local variable
-                                                                  // |floatLogicalWidth| was capped to the available line width.
-                                                                  // See fast/block/float/clamped-right-float.html.
-    }
-
-    return LayoutPoint(floatLogicalLeft, logicalTopOffset);
-}
-
-bool RenderBlock::positionNewFloats()
-{
-    if (!m_floatingObjects)
-        return false;
-
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    if (floatingObjectSet.isEmpty())
-        return false;
-
-    // If all floats have already been positioned, then we have no work to do.
-    if (floatingObjectSet.last()->isPlaced())
-        return false;
-
-    // Move backwards through our floating object list until we find a float that has
-    // already been positioned.  Then we'll be able to move forward, positioning all of
-    // the new floats that need it.
-    FloatingObjectSetIterator it = floatingObjectSet.end();
-    --it; // Go to last item.
-    FloatingObjectSetIterator begin = floatingObjectSet.begin();
-    FloatingObject* lastPlacedFloatingObject = 0;
-    while (it != begin) {
-        --it;
-        if ((*it)->isPlaced()) {
-            lastPlacedFloatingObject = *it;
-            ++it;
-            break;
-        }
-    }
-
-    LayoutUnit logicalTop = logicalHeight();
-
-    // The float cannot start above the top position of the last positioned float.
-    if (lastPlacedFloatingObject)
-        logicalTop = max(lastPlacedFloatingObject->logicalTop(isHorizontalWritingMode()), logicalTop);
-
-    FloatingObjectSetIterator end = floatingObjectSet.end();
-    // Now walk through the set of unpositioned floats and place them.
-    for (; it != end; ++it) {
-        FloatingObject* floatingObject = *it;
-        // The containing block is responsible for positioning floats, so if we have floats in our
-        // list that come from somewhere else, do not attempt to position them.
-        if (floatingObject->renderer()->containingBlock() != this)
-            continue;
-
-        RenderBox* childBox = floatingObject->renderer();
-        LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
-
-        LayoutRect oldRect = childBox->frameRect();
-
-        if (childBox->style()->clear() & CLEFT)
-            logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
-        if (childBox->style()->clear() & CRIGHT)
-            logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
-
-        LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
-
-        floatingObject->setLogicalLeft(floatLogicalLocation.x(), isHorizontalWritingMode());
-
-        setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
-        setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
-
-        SubtreeLayoutScope layoutScope(childBox);
-        LayoutState* layoutState = view()->layoutState();
-        bool isPaginated = layoutState->isPaginated();
-        if (isPaginated && !childBox->needsLayout())
-            childBox->markForPaginationRelayoutIfNeeded(layoutScope);
-
-        childBox->layoutIfNeeded();
-
-        if (isPaginated) {
-            // If we are unsplittable and don't fit, then we need to move down.
-            // We include our margins as part of the unsplittable area.
-            LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, floatLogicalLocation.y(), true);
-
-            // See if we have a pagination strut that is making us move down further.
-            // Note that an unsplittable child can't also have a pagination strut, so this is
-            // exclusive with the case above.
-            RenderBlock* childBlock = childBox->isRenderBlock() ? toRenderBlock(childBox) : 0;
-            if (childBlock && childBlock->paginationStrut()) {
-                newLogicalTop += childBlock->paginationStrut();
-                childBlock->setPaginationStrut(0);
-            }
-
-            if (newLogicalTop != floatLogicalLocation.y()) {
-                floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
-
-                floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
-                floatingObject->setLogicalLeft(floatLogicalLocation.x(), isHorizontalWritingMode());
-
-                setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
-                setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
-
-                if (childBlock)
-                    childBlock->setChildNeedsLayout(MarkOnlyThis);
-                childBox->layoutIfNeeded();
-            }
-        }
-
-        floatingObject->setLogicalTop(floatLogicalLocation.y(), isHorizontalWritingMode());
-
-        floatingObject->setLogicalHeight(logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox), isHorizontalWritingMode());
-
-        m_floatingObjects->addPlacedObject(floatingObject);
-
-        // If the child moved, we have to repaint it.
-        if (childBox->checkForRepaintDuringLayout())
-            childBox->repaintDuringLayoutIfMoved(oldRect);
-    }
-    return true;
-}
-
-void RenderBlock::clearFloats(EClear clear)
-{
-    positionNewFloats();
-    // set y position
-    LayoutUnit newY = 0;
-    switch (clear)
-    {
-        case CLEFT:
-            newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
-            break;
-        case CRIGHT:
-            newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
-            break;
-        case CBOTH:
-            newY = lowestFloatLogicalBottom();
-        default:
-            break;
-    }
-    if (height() < newY)
-        setLogicalHeight(newY);
-}
-
 void RenderBlock::addPercentHeightDescendant(RenderBox* descendant)
 {
     insertIntoTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
@@ -3579,14 +3098,6 @@
     return logicalRightOffset - (logicalWidth() - (isHorizontalWritingMode() ? boxRect.maxX() : boxRect.maxY()));
 }
 
-LayoutUnit RenderBlock::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
-{
-    if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
-        return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
-
-    return fixedOffset;
-}
-
 LayoutUnit RenderBlock::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
 {
     LayoutUnit left = offsetFromFloats;
@@ -3625,14 +3136,6 @@
     return left;
 }
 
-LayoutUnit RenderBlock::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
-{
-    if (m_floatingObjects && m_floatingObjects->hasRightObjects())
-        return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
-
-    return fixedOffset;
-}
-
 LayoutUnit RenderBlock::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
 {
     LayoutUnit right = offsetFromFloats;
@@ -3671,37 +3174,6 @@
     return right;
 }
 
-LayoutUnit RenderBlock::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
-{
-    if (!m_floatingObjects)
-        return logicalHeight;
-
-    LayoutUnit bottom = LayoutUnit::max();
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObjectSetIterator end = floatingObjectSet.end();
-    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-        FloatingObject* floatingObject = *it;
-        LayoutUnit floatBottom;
-        ShapeOutsideInfo* shapeOutside = floatingObject->renderer()->shapeOutsideInfo();
-        if (offsetMode == ShapeOutsideFloatShapeOffset && shapeOutside)
-            floatBottom = floatingObject->logicalTop(isHorizontalWritingMode()) + marginBeforeForChild(floatingObject->renderer()) + shapeOutside->shapeLogicalBottom();
-        else
-            floatBottom = floatingObject->logicalBottom(isHorizontalWritingMode());
-        if (floatBottom > logicalHeight)
-            bottom = min(floatBottom, bottom);
-    }
-
-    return bottom == LayoutUnit::max() ? LayoutUnit() : bottom;
-}
-
-LayoutUnit RenderBlock::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
-{
-    if (!m_floatingObjects)
-        return 0;
-
-    return m_floatingObjects->lowestFloatLogicalBottom(floatType);
-}
-
 void RenderBlock::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
 {
     if (logicalTop >= logicalBottom)
@@ -3720,124 +3192,12 @@
     }
 }
 
-LayoutUnit RenderBlock::addOverhangingFloats(RenderBlock* child, bool makeChildPaintOtherFloats)
-{
-    // Prevent floats from being added to the canvas by the root element, e.g., <html>.
-    if (child->hasOverflowClip() || !child->containsFloats() || child->isRoot() || child->hasColumns() || child->isWritingModeRoot())
-        return 0;
-
-    LayoutUnit childLogicalTop = child->logicalTop();
-    LayoutUnit childLogicalLeft = child->logicalLeft();
-    LayoutUnit lowestFloatLogicalBottom = 0;
-
-    // Floats that will remain the child's responsibility to paint should factor into its
-    // overflow.
-    FloatingObjectSetIterator childEnd = child->m_floatingObjects->set().end();
-    for (FloatingObjectSetIterator childIt = child->m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
-        FloatingObject* r = *childIt;
-        LayoutUnit logicalBottomForFloat = min(r->logicalBottom(isHorizontalWritingMode()), LayoutUnit::max() - childLogicalTop);
-        LayoutUnit logicalBottom = childLogicalTop + logicalBottomForFloat;
-        lowestFloatLogicalBottom = max(lowestFloatLogicalBottom, logicalBottom);
-
-        if (logicalBottom > logicalHeight()) {
-            // If the object is not in the list, we add it now.
-            if (!containsFloat(r->renderer())) {
-                LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
-                bool shouldPaint = false;
-
-                // The nearest enclosing layer always paints the float (so that zindex and stacking
-                // behaves properly).  We always want to propagate the desire to paint the float as
-                // far out as we can, to the outermost block that overlaps the float, stopping only
-                // if we hit a self-painting layer boundary.
-                if (r->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
-                    r->setShouldPaint(false);
-                    shouldPaint = true;
-                }
-                // We create the floating object list lazily.
-                if (!m_floatingObjects)
-                    createFloatingObjects();
-
-                m_floatingObjects->add(r->copyToNewContainer(offset, shouldPaint, true));
-            }
-        } else {
-            if (makeChildPaintOtherFloats && !r->shouldPaint() && !r->renderer()->hasSelfPaintingLayer()
-                && r->renderer()->isDescendantOf(child) && r->renderer()->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
-                // The float is not overhanging from this block, so if it is a descendant of the child, the child should
-                // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
-                // layer.
-                // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
-                // it should paint.
-                r->setShouldPaint(true);
-            }
-
-            // Since the float doesn't overhang, it didn't get put into our list.  We need to go ahead and add its overflow in to the
-            // child now.
-            if (r->isDescendant())
-                child->addOverflowFromChild(r->renderer(), LayoutSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
-        }
-    }
-    return lowestFloatLogicalBottom;
-}
-
-bool RenderBlock::hasOverhangingFloat(RenderBox* renderer)
-{
-    if (!m_floatingObjects || hasColumns() || !parent())
-        return false;
-
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(renderer);
-    if (it == floatingObjectSet.end())
-        return false;
-
-    return (*it)->logicalBottom(isHorizontalWritingMode()) > logicalHeight();
-}
-
-void RenderBlock::addIntrudingFloats(RenderBlock* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
-{
-    ASSERT(!avoidsFloats());
-
-    // If the parent or previous sibling doesn't have any floats to add, don't bother.
-    if (!prev->m_floatingObjects)
-        return;
-
-    logicalLeftOffset += marginLogicalLeft();
-
-    const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
-    FloatingObjectSetIterator prevEnd = prevSet.end();
-    for (FloatingObjectSetIterator prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
-        FloatingObject* r = *prevIt;
-        if (r->logicalBottom(isHorizontalWritingMode()) > logicalTopOffset) {
-            if (!m_floatingObjects || !m_floatingObjects->set().contains(r)) {
-                // We create the floating object list lazily.
-                if (!m_floatingObjects)
-                    createFloatingObjects();
-
-                // Applying the child's margin makes no sense in the case where the child was passed in.
-                // since this margin was added already through the modification of the |logicalLeftOffset| variable
-                // above.  |logicalLeftOffset| will equal the margin in this case, so it's already been taken
-                // into account.  Only apply this code if prev is the parent, since otherwise the left margin
-                // will get applied twice.
-                LayoutSize offset = isHorizontalWritingMode()
-                    ? LayoutSize(logicalLeftOffset - (prev != parent() ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
-                    : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != parent() ? prev->marginTop() : LayoutUnit()));
-
-                m_floatingObjects->add(r->copyToNewContainer(offset));
-            }
-        }
-    }
-}
-
 bool RenderBlock::avoidsFloats() const
 {
     // Floats can't intrude into our box if we have a non-auto column count or width.
     return RenderBox::avoidsFloats() || !style()->hasAutoColumnCount() || !style()->hasAutoColumnWidth();
 }
 
-bool RenderBlock::containsFloat(RenderBox* renderer) const
-{
-    return m_floatingObjects && m_floatingObjects->set().contains<RenderBox*, FloatingObjectHashTranslator>(renderer);
-}
-
 void RenderBlock::markShapeInsideDescendantsForLayout()
 {
     if (!everHadLayout())
@@ -3854,130 +3214,12 @@
     }
 }
 
-void RenderBlock::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
-{
-    if (!everHadLayout() && !containsFloats())
-        return;
-
-    MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
-    setChildNeedsLayout(markParents);
-
-    if (floatToRemove)
-        removeFloatingObject(floatToRemove);
-
-    // Iterate over our children and mark them as needed.
-    if (!childrenInline()) {
-        for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
-            if ((!floatToRemove && child->isFloatingOrOutOfFlowPositioned()) || !child->isRenderBlock())
-                continue;
-            RenderBlock* childBlock = toRenderBlock(child);
-            if ((floatToRemove ? childBlock->containsFloat(floatToRemove) : childBlock->containsFloats()) || childBlock->shrinkToAvoidFloats())
-                childBlock->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
-        }
-    }
-}
-
-void RenderBlock::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
-{
-    if (!m_floatingObjects)
-        return;
-
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObjectSetIterator end = floatingObjectSet.end();
-
-    for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
-        if (!next->isRenderBlock() || next->isFloatingOrOutOfFlowPositioned() || toRenderBlock(next)->avoidsFloats())
-            continue;
-
-        RenderBlock* nextBlock = toRenderBlock(next);
-        for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-            RenderBox* floatingBox = (*it)->renderer();
-            if (floatToRemove && floatingBox != floatToRemove)
-                continue;
-            if (nextBlock->containsFloat(floatingBox))
-                nextBlock->markAllDescendantsWithFloatsForLayout(floatingBox);
-        }
-    }
-}
-
-LayoutUnit RenderBlock::getClearDelta(RenderBox* child, LayoutUnit logicalTop)
-{
-    // There is no need to compute clearance if we have no floats.
-    if (!containsFloats())
-        return 0;
-
-    // At least one float is present.  We need to perform the clearance computation.
-    bool clearSet = child->style()->clear() != CNONE;
-    LayoutUnit logicalBottom = 0;
-    switch (child->style()->clear()) {
-        case CNONE:
-            break;
-        case CLEFT:
-            logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
-            break;
-        case CRIGHT:
-            logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
-            break;
-        case CBOTH:
-            logicalBottom = lowestFloatLogicalBottom();
-            break;
-    }
-
-    // We also clear floats if we are too big to sit on the same line as a float (and wish to avoid floats by default).
-    LayoutUnit result = clearSet ? max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
-    if (!result && child->avoidsFloats()) {
-        LayoutUnit newLogicalTop = logicalTop;
-        while (true) {
-            LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
-            if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent(newLogicalTop))
-                return newLogicalTop - logicalTop;
-
-            RenderRegion* region = regionAtBlockOffset(logicalTopForChild(child));
-            LayoutRect borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
-            LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
-
-            // FIXME: None of this is right for perpendicular writing-mode children.
-            LayoutUnit childOldLogicalWidth = child->logicalWidth();
-            LayoutUnit childOldMarginLeft = child->marginLeft();
-            LayoutUnit childOldMarginRight = child->marginRight();
-            LayoutUnit childOldLogicalTop = child->logicalTop();
-
-            child->setLogicalTop(newLogicalTop);
-            child->updateLogicalWidth();
-            region = regionAtBlockOffset(logicalTopForChild(child));
-            borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
-            LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
-
-            child->setLogicalTop(childOldLogicalTop);
-            child->setLogicalWidth(childOldLogicalWidth);
-            child->setMarginLeft(childOldMarginLeft);
-            child->setMarginRight(childOldMarginRight);
-
-            if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
-                // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
-                // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
-                // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
-                if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
-                    child->setChildNeedsLayout(MarkOnlyThis);
-                return newLogicalTop - logicalTop;
-            }
-
-            newLogicalTop = nextFloatLogicalBottomBelow(newLogicalTop);
-            ASSERT(newLogicalTop >= logicalTop);
-            if (newLogicalTop < logicalTop)
-                break;
-        }
-        ASSERT_NOT_REACHED();
-    }
-    return result;
-}
-
 bool RenderBlock::isPointInOverflowControl(HitTestResult& result, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset)
 {
     if (!scrollsOverflow())
         return false;
 
-    return layer()->hitTestOverflowControls(result, roundedIntPoint(locationInContainer - toLayoutSize(accumulatedOffset)));
+    return layer()->scrollableArea()->hitTestOverflowControls(result, roundedIntPoint(locationInContainer - toLayoutSize(accumulatedOffset)));
 }
 
 Node* RenderBlock::nodeForHitTest() const
@@ -4055,35 +3297,6 @@
     return false;
 }
 
-bool RenderBlock::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
-{
-    if (!m_floatingObjects)
-        return false;
-
-    LayoutPoint adjustedLocation = accumulatedOffset;
-    if (isRenderView()) {
-        adjustedLocation += toLayoutSize(toRenderView(this)->frameView()->scrollPosition());
-    }
-
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObjectSetIterator begin = floatingObjectSet.begin();
-    for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
-        --it;
-        FloatingObject* floatingObject = *it;
-        if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
-            LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
-            LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y();
-            LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
-            if (floatingObject->renderer()->hitTest(request, result, locationInContainer, childPoint)) {
-                updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
-                return true;
-            }
-        }
-    }
-
-    return false;
-}
-
 class ColumnRectIterator {
     WTF_MAKE_NONCOPYABLE(ColumnRectIterator);
 public:
@@ -5855,6 +5068,8 @@
     if (style()->styleType() == FIRST_LETTER)
         return;
 
+    // FIXME: We need to destroy the first-letter object if it is no longer the first child. Need to find
+    // an efficient way to check for that situation though before implementing anything.
     RenderObject* firstLetterBlock = findFirstLetterBlock(this);
     if (!firstLetterBlock)
         return;
@@ -5891,30 +5106,9 @@
     if (!currChild)
         return;
 
+    // If the child already has style, then it has already been created, so we just want
+    // to update it.
     if (currChild->parent()->style()->styleType() == FIRST_LETTER) {
-        // Check if the text fragment(currChild) for the first-letter is not related to the remainingText.
-        RenderObject* remainingText = currChild->parent()->nextSibling();
-        if (remainingText && currChild->node() != remainingText->node()) {
-            if (!remainingText->isText() || remainingText->isBR())
-                return;
-
-            if (RenderBoxModelObject* oldFirstLetter = currChild->parent()->isBoxModelObject() ? toRenderBoxModelObject(currChild->parent()) : 0) {
-                RenderObject* oldRemainingText = oldFirstLetter->firstLetterRemainingText();
-                if (oldRemainingText && oldRemainingText->isText()) {
-                    LayoutStateDisabler layoutStateDisabler(view());
-                    // Destroy the text fragment for the old first-letter and update oldRemainingText with its DOM text.
-                    toRenderText(oldRemainingText)->setText(toText(oldRemainingText->node())->data().impl());
-
-                    if (unsigned newLength = firstLetterLength(toRenderText(remainingText)->originalText()))
-                        createFirstLetterRenderer(firstLetterBlock, remainingText, newLength);
-                }
-            }
-
-            return;
-        }
-
-        // If the child already has style, then it has already been created, so we just want
-        // to update it.
         updateFirstLetterStyle(firstLetterBlock, currChild);
         return;
     }
@@ -6048,21 +5242,6 @@
                 }
             }
         }
-
-        if (m_floatingObjects) {
-            const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-            FloatingObjectSetIterator end = floatingObjectSet.end();
-            for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-                FloatingObject* r = *it;
-                // Only examine the object if our m_shouldPaint flag is set.
-                if (r->shouldPaint()) {
-                    LayoutUnit floatLeft = xPositionForFloatIncludingMargin(r) - r->renderer()->x();
-                    LayoutUnit floatRight = floatLeft + r->renderer()->width();
-                    left = min(left, floatLeft);
-                    right = max(right, floatRight);
-                }
-            }
-        }
     }
 }
 
@@ -6780,11 +5959,6 @@
     return "RenderBlock";
 }
 
-void RenderBlock::createFloatingObjects()
-{
-    m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
-}
-
 template <typename CharacterType>
 static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
 {
diff --git a/Source/core/rendering/RenderBlock.h b/Source/core/rendering/RenderBlock.h
index 5899b43..62205f3 100644
--- a/Source/core/rendering/RenderBlock.h
+++ b/Source/core/rendering/RenderBlock.h
@@ -43,13 +43,11 @@
 class InlineIterator;
 class LayoutStateMaintainer;
 class LineLayoutState;
-class LineWidth;
 class RenderInline;
 class RenderText;
 
 struct BidiRun;
 struct PaintInfo;
-class LineBreaker;
 class LineInfo;
 class RenderRubyRun;
 class TextLayout;
@@ -107,7 +105,8 @@
     InlineFlowBox* firstLineBox() const { return m_lineBoxes.firstLineBox(); }
     InlineFlowBox* lastLineBox() const { return m_lineBoxes.lastLineBox(); }
 
-    void deleteLineBoxTree();
+    // 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*);
@@ -118,8 +117,6 @@
     static void removePositionedObject(RenderBox*);
     void removePositionedObjects(RenderBlock*, ContainingBlockState = SameContainingBlock);
 
-    void removeFloatingObjects();
-
     TrackedRendererListHashSet* positionedObjects() const;
     bool hasPositionedObjects() const
     {
@@ -152,15 +149,13 @@
     bool generatesLineBoxesForInlineChild(RenderObject*);
 
     void markShapeInsideDescendantsForLayout();
-    void markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove = 0, bool inLayout = true);
-    void markSiblingsWithFloatsForLayout(RenderBox* floatToRemove = 0);
     void markPositionedObjectsForLayout();
     // FIXME: Do we really need this to be virtual? It's just so we can call this on
     // RenderBoxes without needed to check whether they're RenderBlocks first.
     virtual void markForPaginationRelayoutIfNeeded(SubtreeLayoutScope&) OVERRIDE FINAL;
 
-    bool containsFloats() const { return m_floatingObjects && !m_floatingObjects->set().isEmpty(); }
-    bool containsFloat(RenderBox*) const;
+    // 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.
@@ -282,8 +277,6 @@
         return obj->isFloating() || (obj->isOutOfFlowPositioned() && !obj->style()->isOriginalDisplayInlineType() && !obj->container()->isRenderInline());
     }
 
-    static void appendRunsForObject(BidiRunList<BidiRun>&, int start, int end, RenderObject*, InlineBidiResolver&);
-
     static TextRun constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style,
         TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, TextRunFlags = DefaultTextRunFlags);
 
@@ -511,10 +504,9 @@
     void setDesiredColumnCountAndWidth(int, LayoutUnit);
 
 public:
-    void computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats = false);
+    virtual void computeOverflow(LayoutUnit oldClientAfterEdge, bool = false);
 protected:
     virtual void addOverflowFromChildren();
-    void addOverflowFromFloats();
     void addOverflowFromPositionedObjects();
     void addOverflowFromBlockChildren();
     void addOverflowFromInlineChildren();
@@ -534,8 +526,10 @@
     virtual bool isInlineBlockOrInlineTable() const OVERRIDE FINAL { return isInline() && isReplaced(); }
 
 private:
-    LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const;
-    LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const;
+    // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+    virtual LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit*, LayoutUnit, ShapeOutsideFloatOffsetMode) const { return fixedOffset; }
+    // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+    virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit*, LayoutUnit, ShapeOutsideFloatOffsetMode) const { return fixedOffset; }
     LayoutUnit adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
     LayoutUnit adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
 
@@ -555,7 +549,8 @@
     virtual void removeLeftoverAnonymousBlock(RenderBlock* child);
 
     static void collapseAnonymousBlockChild(RenderBlock* parent, RenderBlock* child);
-    void moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert);
+    // 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); }
 
@@ -567,10 +562,6 @@
 
     virtual bool isSelfCollapsingBlock() const OVERRIDE FINAL;
 
-    virtual void repaintOverhangingFloats(bool paintAllDescendants) OVERRIDE FINAL;
-
-    BidiRun* handleTrailingSpaces(BidiRunList<BidiRun>&, BidiContext*);
-
     void insertIntoTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*&, TrackedContainerMap*&);
     static void removeFromTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*&, TrackedContainerMap*&);
 
@@ -597,52 +588,8 @@
         bool everHadLayout;
     };
 
-    LayoutPoint flipFloatForWritingModeForChild(const FloatingObject*, const LayoutPoint&) const;
-
-    LayoutUnit xPositionForFloatIncludingMargin(const FloatingObject* child) const
-    {
-        if (isHorizontalWritingMode())
-            return child->x() + child->renderer()->marginLeft();
-        else
-            return child->x() + marginBeforeForChild(child->renderer());
-    }
-
-    LayoutUnit yPositionForFloatIncludingMargin(const FloatingObject* child) const
-    {
-        if (isHorizontalWritingMode())
-            return child->y() + marginBeforeForChild(child->renderer());
-        else
-            return child->y() + child->renderer()->marginTop();
-    }
-
-    LayoutPoint computeLogicalLocationForFloat(const FloatingObject*, LayoutUnit logicalTopOffset) const;
-
-    void checkFloatsInCleanLine(RootInlineBox*, Vector<FloatWithRect>&, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat);
-    RootInlineBox* determineStartPosition(LineLayoutState&, InlineBidiResolver&);
-    void determineEndPosition(LineLayoutState&, RootInlineBox* startBox, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus);
-    bool matchedEndLine(LineLayoutState&, const InlineBidiResolver&, const InlineIterator& endLineStart, const BidiStatus& endLineStatus);
-    bool checkPaginationAndFloatsAtEndLine(LineLayoutState&);
-
-    RootInlineBox* constructLine(BidiRunList<BidiRun>&, const LineInfo&);
-    InlineFlowBox* createLineBoxes(RenderObject*, const LineInfo&, InlineBox* childBox, bool startsNewSegment);
-
-    void setMarginsForRubyRun(BidiRun*, RenderRubyRun*, RenderObject*, const LineInfo&);
-
-    BidiRun* computeInlineDirectionPositionsForSegment(RootInlineBox*, const LineInfo&, ETextAlign, float& logicalLeft,
-        float& availableLogicalWidth, BidiRun* firstRun, BidiRun* trailingSpaceRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache&, WordMeasurements&);
-    void computeInlineDirectionPositionsForLine(RootInlineBox*, const LineInfo&, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd, GlyphOverflowAndFallbackFontsMap&, VerticalPositionCache&, WordMeasurements&);
-    void computeBlockDirectionPositionsForLine(RootInlineBox*, BidiRun*, GlyphOverflowAndFallbackFontsMap&, VerticalPositionCache&);
-    void deleteEllipsisLineBoxes();
-    void checkLinesForTextOverflow();
-
-    // Positions new floats and also adjust all floats encountered on the line if any of them
-    // have to move to the next page/column.
-    bool positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo&, LineWidth&);
-    void appendFloatingObjectToLastLine(FloatingObject*);
-
-    // End of functions defined in RenderBlockLineLayout.cpp.
-
-    void paintFloats(PaintInfo&, const LayoutPoint&, bool preservePhase = false);
+    // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+    virtual void paintFloats(PaintInfo&, const LayoutPoint&, bool) { }
     void paintContents(PaintInfo&, const LayoutPoint&);
     void paintColumnContents(PaintInfo&, const LayoutPoint&, bool paintFloats = false);
     void paintColumnRules(PaintInfo&, const LayoutPoint&);
@@ -652,29 +599,12 @@
     bool hasCaret() const { return hasCaret(CursorCaret) || hasCaret(DragCaret); }
     bool hasCaret(CaretType) const;
 
-    FloatingObject* insertFloatingObject(RenderBox*);
-    void removeFloatingObject(RenderBox*);
-    void removeFloatingObjectsBelow(FloatingObject*, int logicalOffset);
-
-    // Called from lineWidth, to position the floats added in the last line.
-    // Returns true if and only if it has positioned any floats.
-    bool positionNewFloats();
-
-    LayoutUnit getClearDelta(RenderBox* child, LayoutUnit yPos);
-
     virtual bool avoidsFloats() const;
 
-    bool hasOverhangingFloats() { return parent() && !hasColumns() && containsFloats() && lowestFloatLogicalBottom() > logicalHeight(); }
-    bool hasOverhangingFloat(RenderBox*);
-    void addIntrudingFloats(RenderBlock* prev, LayoutUnit xoffset, LayoutUnit yoffset);
-    LayoutUnit addOverhangingFloats(RenderBlock* child, bool makeChildPaintOtherFloats);
-
-    LayoutUnit lowestFloatLogicalBottom(FloatingObject::Type = FloatingObject::FloatLeftRight) const;
-    LayoutUnit nextFloatLogicalBottomBelow(LayoutUnit, ShapeOutsideFloatOffsetMode = ShapeOutsideFloatMarginBoxOffset) const;
-
     bool hitTestColumns(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction);
     bool hitTestContents(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction);
-    bool hitTestFloats(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset);
+    // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+    virtual bool hitTestFloats(const HitTestRequest&, HitTestResult&, const HitTestLocation&, const LayoutPoint&) { return false; }
 
     virtual bool isPointInOverflowControl(HitTestResult&, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset);
 
@@ -710,6 +640,9 @@
     LayoutUnit logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position);
     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;
 
@@ -723,12 +656,10 @@
     void adjustPointToColumnContents(LayoutPoint&) const;
 
     void fitBorderToLinesIfNeeded(); // Shrink the box in which the border paints if border-fit is set.
-    void adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const; // Helper function for borderFitAdjust
+    virtual void adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const; // Helper function for borderFitAdjust
 
     void markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest = 0);
 
-    void clearFloats(EClear);
-
     Position positionForBox(InlineBox*, bool start = true) const;
     PositionWithAffinity positionForPointWithInlineChildren(const LayoutPoint&);
 
@@ -751,17 +682,6 @@
     void moveRunInToOriginalPosition(RenderObject* runIn);
     // End helper functions and structs used by layoutBlockChildren.
 
-    // Helper function for layoutInlineChildren()
-    RootInlineBox* createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>&, const InlineIterator& end, LineInfo&, VerticalPositionCache&, BidiRun* trailingSpaceRun, WordMeasurements&);
-    void layoutRunsAndFloats(LineLayoutState&, bool hasInlineChild);
-    void layoutRunsAndFloatsInRange(LineLayoutState&, InlineBidiResolver&, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines);
-    void updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*&, const LayoutSize&, LineLayoutState&);
-    void updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideInfo*&, LineLayoutState&);
-    bool adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo*, LayoutUnit, LineLayoutState&, InlineBidiResolver&, FloatingObject*, InlineIterator&, WordMeasurements&);
-    const InlineIterator& restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight,  FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver&,  const InlineIterator&);
-    void linkToEndLineIfNeeded(LineLayoutState&);
-    static void repaintDirtyFloats(Vector<FloatWithRect>& floats);
-
 protected:
     void determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode = DoNotApplyLayoutDelta);
 
@@ -821,10 +741,6 @@
     RenderRegion* regionAtBlockOffset(LayoutUnit) const;
     RenderRegion* clampToStartAndEndRegions(RenderRegion*) const;
 
-protected:
-
-    void createFloatingObjects();
-
 public:
 
     // Allocated only when some of these fields have non-default values
@@ -851,8 +767,6 @@
      };
 
 protected:
-
-    OwnPtr<FloatingObjects> m_floatingObjects;
     OwnPtr<RenderBlockRareData> m_rareData;
 
     RenderObjectChildList m_children;
@@ -868,15 +782,12 @@
     // RenderRubyBase objects need to be able to split and merge, moving their children around
     // (calling moveChildTo, moveAllChildrenTo, and makeChildrenNonInline).
     friend class RenderRubyBase;
+    // FIXME-BLOCKFLOW: Remove this when the line layout stuff has all moved out of RenderBlock
     friend class LineBreaker;
-    friend class LineWidth; // Needs to know FloatingObject
 
     // FIXME: This is temporary as we move code that accesses block flow
     // member variables out of RenderBlock and into RenderBlockFlow.
     friend class RenderBlockFlow;
-private:
-    // Used to store state between styleWillChange and styleDidChange
-    static bool s_canPropagateFloatIntoSibling;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderBlock, isRenderBlock());
diff --git a/Source/core/rendering/RenderBlockFlow.cpp b/Source/core/rendering/RenderBlockFlow.cpp
index 228d7dc..4c454a8 100644
--- a/Source/core/rendering/RenderBlockFlow.cpp
+++ b/Source/core/rendering/RenderBlockFlow.cpp
@@ -32,7 +32,9 @@
 #include "core/rendering/RenderBlockFlow.h"
 
 #include "core/frame/FrameView.h"
+#include "core/rendering/HitTestLocation.h"
 #include "core/rendering/LayoutRepainter.h"
+#include "core/rendering/LineWidth.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderNamedFlowThread.h"
 #include "core/rendering/RenderView.h"
@@ -41,6 +43,8 @@
 
 namespace WebCore {
 
+bool RenderBlockFlow::s_canPropagateFloatIntoSibling = false;
+
 struct SameSizeAsMarginInfo {
     uint16_t bitfields;
     LayoutUnit margins[2];
@@ -250,7 +254,7 @@
             // One of our children's floats may have become an overhanging float for us. We need to look for it.
             for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
                 if (child->isRenderBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
-                    RenderBlock* block = toRenderBlock(child);
+                    RenderBlockFlow* block = toRenderBlockFlow(child);
                     if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
                         addOverhangingFloats(block, false);
                 }
@@ -356,6 +360,7 @@
     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
 
     RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
+    RenderBlockFlow* childRenderBlockFlow = (childRenderBlock && child->isRenderBlockFlow()) ? toRenderBlockFlow(child) : 0;
     bool markDescendantsWithFloats = false;
     if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats()) {
         markDescendantsWithFloats = true;
@@ -373,11 +378,11 @@
             markDescendantsWithFloats = true;
     }
 
-    if (childRenderBlock) {
+    if (childRenderBlockFlow) {
         if (markDescendantsWithFloats)
-            childRenderBlock->markAllDescendantsWithFloatsForLayout();
+            childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
         if (!child->isWritingModeRoot())
-            previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
+            previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlockFlow->lowestFloatLogicalBottom());
     }
 
     SubtreeLayoutScope layoutScope(child);
@@ -425,7 +430,7 @@
 
         if (childRenderBlock) {
             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
-                childRenderBlock->markAllDescendantsWithFloatsForLayout();
+                childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
             if (!child->needsLayout())
                 child->markForPaginationRelayoutIfNeeded(layoutScope);
         }
@@ -453,8 +458,8 @@
     }
     // If the child has overhanging floats that intrude into following siblings (or possibly out
     // of this block), then the parent gets notified of the floats now.
-    if (childRenderBlock && childRenderBlock->containsFloats())
-        maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
+    if (childRenderBlockFlow && childRenderBlockFlow->containsFloats())
+        maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(childRenderBlockFlow, !childNeededLayout));
 
     if (childOffset.width() || childOffset.height()) {
         view()->addLayoutDelta(childOffset);
@@ -503,7 +508,7 @@
 
         if (childRenderBlock) {
             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
-                childRenderBlock->markAllDescendantsWithFloatsForLayout();
+                toRenderBlockFlow(childRenderBlock)->markAllDescendantsWithFloatsForLayout();
             if (!child->needsLayout())
                 child->markForPaginationRelayoutIfNeeded(layoutScope);
         }
@@ -600,16 +605,16 @@
             m_floatingObjects->clear();
     }
 
-    // We should not process floats if the parent node is not a RenderBlock. Otherwise, we will add
+    // We should not process floats if the parent node is not a RenderBlockFlow. Otherwise, we will add
     // floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
     // See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
-    if (!parent() || !parent()->isRenderBlock())
+    if (!parent() || !parent()->isRenderBlockFlow())
         return;
 
     // Attempt to locate a previous sibling with overhanging floats. We skip any elements that are
     // out of flow (like floating/positioned elements), and we also skip over any objects that may have shifted
     // to avoid floats.
-    RenderBlock* parentBlock = toRenderBlock(parent());
+    RenderBlockFlow* parentBlockFlow = toRenderBlockFlow(parent());
     bool parentHasFloats = false;
     RenderObject* prev = previousSibling();
     while (prev && (prev->isFloatingOrOutOfFlowPositioned() || !prev->isBox() || !prev->isRenderBlock() || toRenderBlock(prev)->avoidsFloats())) {
@@ -621,20 +626,20 @@
     // First add in floats from the parent.
     LayoutUnit logicalTopOffset = logicalTop();
     if (parentHasFloats)
-        addIntrudingFloats(parentBlock, parentBlock->logicalLeftOffsetForContent(), logicalTopOffset);
+        addIntrudingFloats(parentBlockFlow, parentBlockFlow->logicalLeftOffsetForContent(), logicalTopOffset);
 
     LayoutUnit logicalLeftOffset = 0;
     if (prev) {
         logicalTopOffset -= toRenderBox(prev)->logicalTop();
     } else {
-        prev = parentBlock;
-        logicalLeftOffset += parentBlock->logicalLeftOffsetForContent();
+        prev = parentBlockFlow;
+        logicalLeftOffset += parentBlockFlow->logicalLeftOffsetForContent();
     }
 
-    // Add overhanging floats from the previous RenderBlock, but only if it has a float that intrudes into our space.
-    RenderBlock* block = toRenderBlock(prev);
-    if (block->m_floatingObjects && block->lowestFloatLogicalBottom() > logicalTopOffset)
-        addIntrudingFloats(block, logicalLeftOffset, logicalTopOffset);
+    // Add overhanging floats from the previous RenderBlockFlow, but only if it has a float that intrudes into our space.
+    RenderBlockFlow* blockFlow = toRenderBlockFlow(prev);
+    if (blockFlow->m_floatingObjects && blockFlow->lowestFloatLogicalBottom() > logicalTopOffset)
+        addIntrudingFloats(blockFlow, logicalLeftOffset, logicalTopOffset);
 
     if (childrenInline()) {
         LayoutUnit changeLogicalTop = LayoutUnit::max();
@@ -643,12 +648,12 @@
             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
             FloatingObjectSetIterator end = floatingObjectSet.end();
             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-                FloatingObject* f = *it;
-                FloatingObject* oldFloatingObject = floatMap.get(f->renderer());
-                LayoutUnit logicalBottom = f->logicalBottom(isHorizontalWritingMode());
+                FloatingObject* floatingObject = *it;
+                FloatingObject* oldFloatingObject = floatMap.get(floatingObject->renderer());
+                LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
                 if (oldFloatingObject) {
-                    LayoutUnit oldLogicalBottom = oldFloatingObject->logicalBottom(isHorizontalWritingMode());
-                    if (f->logicalWidth(isHorizontalWritingMode()) != oldFloatingObject->logicalWidth(isHorizontalWritingMode()) || f->logicalLeft(isHorizontalWritingMode()) != oldFloatingObject->logicalLeft(isHorizontalWritingMode())) {
+                    LayoutUnit oldLogicalBottom = logicalBottomForFloat(oldFloatingObject);
+                    if (logicalWidthForFloat(floatingObject) != logicalWidthForFloat(oldFloatingObject) || logicalLeftForFloat(floatingObject) != logicalLeftForFloat(oldFloatingObject)) {
                         changeLogicalTop = 0;
                         changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
                     } else {
@@ -656,15 +661,15 @@
                             changeLogicalTop = min(changeLogicalTop, min(logicalBottom, oldLogicalBottom));
                             changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
                         }
-                        LayoutUnit logicalTop = f->logicalTop(isHorizontalWritingMode());
-                        LayoutUnit oldLogicalTop = oldFloatingObject->logicalTop(isHorizontalWritingMode());
+                        LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
+                        LayoutUnit oldLogicalTop = logicalTopForFloat(oldFloatingObject);
                         if (logicalTop != oldLogicalTop) {
                             changeLogicalTop = min(changeLogicalTop, min(logicalTop, oldLogicalTop));
                             changeLogicalBottom = max(changeLogicalBottom, max(logicalTop, oldLogicalTop));
                         }
                     }
 
-                    floatMap.remove(f->renderer());
+                    floatMap.remove(floatingObject->renderer());
                     if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
                         ASSERT(oldFloatingObject->originatingLine()->renderer() == this);
                         oldFloatingObject->originatingLine()->markDirty();
@@ -682,7 +687,7 @@
             FloatingObject* floatingObject = (*it).value;
             if (!floatingObject->isDescendant()) {
                 changeLogicalTop = 0;
-                changeLogicalBottom = max(changeLogicalBottom, floatingObject->logicalBottom(isHorizontalWritingMode()));
+                changeLogicalBottom = max(changeLogicalBottom, logicalBottomForFloat(floatingObject));
             }
         }
         deleteAllValues(floatMap);
@@ -1092,8 +1097,8 @@
     LayoutUnit logicalTop = yPos + heightIncrease;
     // After margin collapsing, one of our floats may now intrude into the child. If the child doesn't contain floats of its own it
     // won't get picked up for relayout even though the logical top estimate was wrong - so add the newly intruding float now.
-    if (containsFloats() && child->isRenderBlock() && !toRenderBlock(child)->containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
-        toRenderBlock(child)->addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
+    if (containsFloats() && child->isRenderBlockFlow() && !toRenderBlockFlow(child)->containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
+        toRenderBlockFlow(child)->addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
 
     return logicalTop;
 }
@@ -1436,4 +1441,849 @@
     return logicalOffset;
 }
 
+void RenderBlockFlow::addOverflowFromFloats()
+{
+    if (!m_floatingObjects)
+        return;
+
+    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+    FloatingObjectSetIterator end = floatingObjectSet.end();
+    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+        FloatingObject* floatingObject = *it;
+        if (floatingObject->isDescendant())
+            addOverflowFromChild(floatingObject->renderer(), IntSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
+    }
+}
+
+void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
+{
+    RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
+    if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
+        addOverflowFromFloats();
+}
+
+void RenderBlockFlow::deleteLineBoxTree()
+{
+    if (containsFloats())
+        m_floatingObjects->clearLineBoxTreePointers();
+    RenderBlock::deleteLineBoxTree();
+}
+
+void RenderBlockFlow::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
+{
+    if (!everHadLayout() && !containsFloats())
+        return;
+
+    MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
+    setChildNeedsLayout(markParents);
+
+    if (floatToRemove)
+        removeFloatingObject(floatToRemove);
+
+    // Iterate over our children and mark them as needed.
+    if (!childrenInline()) {
+        for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
+            if ((!floatToRemove && child->isFloatingOrOutOfFlowPositioned()) || !child->isRenderBlock())
+                continue;
+            if (!child->isRenderBlockFlow()) {
+                RenderBlock* childBlock = toRenderBlock(child);
+                if (childBlock->shrinkToAvoidFloats() && childBlock->everHadLayout())
+                    childBlock->setChildNeedsLayout(markParents);
+                continue;
+            }
+            RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
+            if ((floatToRemove ? childBlockFlow->containsFloat(floatToRemove) : childBlockFlow->containsFloats()) || childBlockFlow->shrinkToAvoidFloats())
+                childBlockFlow->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
+        }
+    }
+}
+
+void RenderBlockFlow::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
+{
+    if (!m_floatingObjects)
+        return;
+
+    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+    FloatingObjectSetIterator end = floatingObjectSet.end();
+
+    for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
+        if (!next->isRenderBlockFlow() || next->isFloatingOrOutOfFlowPositioned() || toRenderBlock(next)->avoidsFloats())
+            continue;
+
+        RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
+        for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+            RenderBox* floatingBox = (*it)->renderer();
+            if (floatToRemove && floatingBox != floatToRemove)
+                continue;
+            if (nextBlock->containsFloat(floatingBox))
+                nextBlock->markAllDescendantsWithFloatsForLayout(floatingBox);
+        }
+    }
+}
+
+LayoutUnit RenderBlockFlow::getClearDelta(RenderBox* child, LayoutUnit logicalTop)
+{
+    // There is no need to compute clearance if we have no floats.
+    if (!containsFloats())
+        return 0;
+
+    // At least one float is present. We need to perform the clearance computation.
+    bool clearSet = child->style()->clear() != CNONE;
+    LayoutUnit logicalBottom = 0;
+    switch (child->style()->clear()) {
+    case CNONE:
+        break;
+    case CLEFT:
+        logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
+        break;
+    case CRIGHT:
+        logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
+        break;
+    case CBOTH:
+        logicalBottom = lowestFloatLogicalBottom();
+        break;
+    }
+
+    // We also clear floats if we are too big to sit on the same line as a float (and wish to avoid floats by default).
+    LayoutUnit result = clearSet ? max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
+    if (!result && child->avoidsFloats()) {
+        LayoutUnit newLogicalTop = logicalTop;
+        while (true) {
+            LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
+            if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent(newLogicalTop))
+                return newLogicalTop - logicalTop;
+
+            RenderRegion* region = regionAtBlockOffset(logicalTopForChild(child));
+            LayoutRect borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
+            LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
+
+            // FIXME: None of this is right for perpendicular writing-mode children.
+            LayoutUnit childOldLogicalWidth = child->logicalWidth();
+            LayoutUnit childOldMarginLeft = child->marginLeft();
+            LayoutUnit childOldMarginRight = child->marginRight();
+            LayoutUnit childOldLogicalTop = child->logicalTop();
+
+            child->setLogicalTop(newLogicalTop);
+            child->updateLogicalWidth();
+            region = regionAtBlockOffset(logicalTopForChild(child));
+            borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
+            LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
+
+            child->setLogicalTop(childOldLogicalTop);
+            child->setLogicalWidth(childOldLogicalWidth);
+            child->setMarginLeft(childOldMarginLeft);
+            child->setMarginRight(childOldMarginRight);
+
+            if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
+                // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
+                // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
+                // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
+                if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
+                    child->setChildNeedsLayout(MarkOnlyThis);
+                return newLogicalTop - logicalTop;
+            }
+
+            newLogicalTop = nextFloatLogicalBottomBelow(newLogicalTop);
+            ASSERT(newLogicalTop >= logicalTop);
+            if (newLogicalTop < logicalTop)
+                break;
+        }
+        ASSERT_NOT_REACHED();
+    }
+    return result;
+}
+
+void RenderBlockFlow::createFloatingObjects()
+{
+    m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
+}
+
+void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+{
+    RenderStyle* oldStyle = style();
+    s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
+    if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle->position()
+        && containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
+            markAllDescendantsWithFloatsForLayout();
+
+    RenderBlock::styleWillChange(diff, newStyle);
+}
+
+void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
+{
+    RenderBlock::styleDidChange(diff, oldStyle);
+
+    // After our style changed, if we lose our ability to propagate floats into next sibling
+    // blocks, then we need to find the top most parent containing that overhanging float and
+    // then mark its descendants with floats for layout and clear all floats from its next
+    // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
+    bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
+    if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
+        RenderBlockFlow* parentBlockFlow = this;
+        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+        FloatingObjectSetIterator end = floatingObjectSet.end();
+
+        for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
+            if (curr->isRenderBlockFlow()) {
+                RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
+
+                if (currBlock->hasOverhangingFloats()) {
+                    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+                        RenderBox* renderer = (*it)->renderer();
+                        if (currBlock->hasOverhangingFloat(renderer)) {
+                            parentBlockFlow = currBlock;
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+
+        parentBlockFlow->markAllDescendantsWithFloatsForLayout();
+        parentBlockFlow->markSiblingsWithFloatsForLayout();
+    }
+}
+
+void RenderBlockFlow::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
+{
+    RenderBlockFlow* toBlockFlow = toRenderBlockFlow(toBlock);
+    moveAllChildrenTo(toBlockFlow, fullRemoveInsert);
+
+    // When a portion of the render tree is being detached, anonymous blocks
+    // will be combined as their children are deleted. In this process, the
+    // anonymous block later in the tree is merged into the one preceeding it.
+    // It can happen that the later block (this) contains floats that the
+    // previous block (toBlockFlow) did not contain, and thus are not in the
+    // floating objects list for toBlockFlow. This can result in toBlockFlow containing
+    // floats that are not in it's floating objects list, but are in the
+    // floating objects lists of siblings and parents. This can cause problems
+    // when the float itself is deleted, since the deletion code assumes that
+    // if a float is not in it's containing block's floating objects list, it
+    // isn't in any floating objects list. In order to preserve this condition
+    // (removing it has serious performance implications), we need to copy the
+    // floating objects from the old block (this) to the new block (toBlockFlow).
+    // The float's metrics will likely all be wrong, but since toBlockFlow is
+    // already marked for layout, this will get fixed before anything gets
+    // displayed.
+    // See bug https://code.google.com/p/chromium/issues/detail?id=230907
+    if (m_floatingObjects) {
+        if (!toBlockFlow->m_floatingObjects)
+            toBlockFlow->createFloatingObjects();
+
+        const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
+        FloatingObjectSetIterator end = fromFloatingObjectSet.end();
+
+        for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
+            FloatingObject* floatingObject = *it;
+
+            // Don't insert the object again if it's already in the list
+            if (toBlockFlow->containsFloat(floatingObject->renderer()))
+                continue;
+
+            toBlockFlow->m_floatingObjects->add(floatingObject->unsafeClone());
+        }
+    }
+
+}
+
+void RenderBlockFlow::repaintOverhangingFloats(bool paintAllDescendants)
+{
+    // Repaint any overhanging floats (if we know we're the one to paint them).
+    // Otherwise, bail out.
+    if (!hasOverhangingFloats())
+        return;
+
+    // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
+    // in this block. Better yet would be to push extra state for the containers of other floats.
+    LayoutStateDisabler layoutStateDisabler(view());
+    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+    FloatingObjectSetIterator end = floatingObjectSet.end();
+    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+        FloatingObject* floatingObject = *it;
+        // Only repaint the object if it is overhanging, is not in its own layer, and
+        // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
+        // condition is replaced with being a descendant of us.
+        if (logicalBottomForFloat(floatingObject) > logicalHeight()
+            && !floatingObject->renderer()->hasSelfPaintingLayer()
+            && (floatingObject->shouldPaint() || (paintAllDescendants && floatingObject->renderer()->isDescendantOf(this)))) {
+            floatingObject->renderer()->repaint();
+            floatingObject->renderer()->repaintOverhangingFloats(false);
+        }
+    }
+}
+
+void RenderBlockFlow::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
+{
+    if (!m_floatingObjects)
+        return;
+
+    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+    FloatingObjectSetIterator end = floatingObjectSet.end();
+    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+        FloatingObject* floatingObject = *it;
+        // Only paint the object if our m_shouldPaint flag is set.
+        if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
+            PaintInfo currentPaintInfo(paintInfo);
+            currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
+            // FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make this much cleaner.
+            LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x(), paintOffset.y() + yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y()));
+            floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+            if (!preservePhase) {
+                currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
+                floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+                currentPaintInfo.phase = PaintPhaseFloat;
+                floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+                currentPaintInfo.phase = PaintPhaseForeground;
+                floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+                currentPaintInfo.phase = PaintPhaseOutline;
+                floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+            }
+        }
+    }
+}
+
+void RenderBlockFlow::clipOutFloatingObjects(RenderBlock* rootBlock, const PaintInfo* paintInfo, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock)
+{
+    if (m_floatingObjects) {
+        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+        FloatingObjectSetIterator end = floatingObjectSet.end();
+        for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+            FloatingObject* floatingObject = *it;
+            LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(floatingObject),
+                offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(floatingObject),
+                floatingObject->renderer()->width(), floatingObject->renderer()->height());
+            rootBlock->flipForWritingMode(floatBox);
+            floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
+            paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
+        }
+    }
+}
+
+void RenderBlockFlow::clearFloats(EClear clear)
+{
+    positionNewFloats();
+    // set y position
+    LayoutUnit newY = 0;
+    switch (clear) {
+    case CLEFT:
+        newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
+        break;
+    case CRIGHT:
+        newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
+        break;
+    case CBOTH:
+        newY = lowestFloatLogicalBottom();
+    default:
+        break;
+    }
+    if (height() < newY)
+        setLogicalHeight(newY);
+}
+
+bool RenderBlockFlow::containsFloat(RenderBox* renderer) const
+{
+    return m_floatingObjects && m_floatingObjects->set().contains<RenderBox*, FloatingObjectHashTranslator>(renderer);
+}
+
+void RenderBlockFlow::removeFloatingObjects()
+{
+    if (!m_floatingObjects)
+        return;
+
+    m_floatingObjects->clear();
+}
+
+LayoutPoint RenderBlockFlow::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
+{
+    if (!style()->isFlippedBlocksWritingMode())
+        return point;
+
+    // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
+    // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
+    // case.
+    if (isHorizontalWritingMode())
+        return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
+    return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
+}
+
+LayoutPoint RenderBlockFlow::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
+{
+    RenderBox* childBox = floatingObject->renderer();
+    LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // 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();
+    // FIXME: Implement behavior for right floats.
+    if (shapeInsideInfo) {
+        LayoutSize floatLogicalSize = logicalSizeForFloat(floatingObject);
+        // floatingObject's logicalSize doesn't contain the actual height at this point, so we need to calculate it
+        floatLogicalSize.setHeight(logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
+
+        // FIXME: If the float doesn't fit in the shape we should push it under the content box
+        logicalTopOffset = shapeInsideInfo->computeFirstFitPositionForFloat(floatLogicalSize);
+        if (logicalHeight() > logicalTopOffset)
+            logicalTopOffset = logicalHeight();
+
+        SegmentList segments = shapeInsideInfo->computeSegmentsForLine(logicalTopOffset, floatLogicalSize.height());
+        // FIXME: Add support for shapes with multiple segments.
+        if (segments.size() == 1) {
+            // The segment offsets are relative to the content box.
+            logicalRightOffset = logicalLeftOffset + segments[0].logicalRight;
+            logicalLeftOffset += segments[0].logicalLeft;
+        }
+    } else {
+        logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset);
+    }
+
+    LayoutUnit floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
+
+    LayoutUnit floatLogicalLeft;
+
+    bool insideFlowThread = flowThreadContainingBlock();
+
+    if (childBox->style()->floating() == LeftFloat) {
+        LayoutUnit heightRemainingLeft = 1;
+        LayoutUnit heightRemainingRight = 1;
+        floatLogicalLeft = logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
+        while (logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
+            logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
+            floatLogicalLeft = logicalLeftOffsetForLineIgnoringShapeOutside(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.
+                floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
+            }
+        }
+        floatLogicalLeft = max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
+    } else {
+        LayoutUnit heightRemainingLeft = 1;
+        LayoutUnit heightRemainingRight = 1;
+        floatLogicalLeft = logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
+        while (floatLogicalLeft - logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
+            logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
+            floatLogicalLeft = logicalRightOffsetForLineIgnoringShapeOutside(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.
+                floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
+            }
+        }
+        // Use the original width of the float here, since the local variable
+        // |floatLogicalWidth| was capped to the available line width. See
+        // fast/block/float/clamped-right-float.html.
+        floatLogicalLeft -= logicalWidthForFloat(floatingObject);
+    }
+
+    return LayoutPoint(floatLogicalLeft, logicalTopOffset);
+}
+
+FloatingObject* RenderBlockFlow::insertFloatingObject(RenderBox* floatBox)
+{
+    ASSERT(floatBox->isFloating());
+
+    // Create the list of special objects if we don't aleady have one
+    if (!m_floatingObjects) {
+        createFloatingObjects();
+    } else {
+        // Don't insert the object again if it's already in the list
+        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+        FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(floatBox);
+        if (it != floatingObjectSet.end())
+            return *it;
+    }
+
+    // Create the special object entry & append it to the list
+
+    OwnPtr<FloatingObject> newObj = FloatingObject::create(floatBox);
+
+    // Our location is irrelevant if we're unsplittable or no pagination is in effect.
+    // Just go ahead and lay out the float.
+    bool isChildRenderBlock = floatBox->isRenderBlock();
+    if (isChildRenderBlock && !floatBox->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
+        floatBox->setChildNeedsLayout(MarkOnlyThis);
+
+    bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
+    if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) { // We are unsplittable if we're a block flow root.
+        floatBox->layoutIfNeeded();
+    } else {
+        floatBox->updateLogicalWidth();
+        floatBox->computeAndSetBlockDirectionMargins(this);
+    }
+
+    setLogicalWidthForFloat(newObj.get(), logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
+
+    if (ShapeOutsideInfo* shapeOutside = floatBox->shapeOutsideInfo())
+        shapeOutside->setShapeSize(logicalWidthForChild(floatBox), logicalHeightForChild(floatBox));
+
+    return m_floatingObjects->add(newObj.release());
+}
+
+void RenderBlockFlow::removeFloatingObject(RenderBox* floatBox)
+{
+    if (m_floatingObjects) {
+        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+        FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(floatBox);
+        if (it != floatingObjectSet.end()) {
+            FloatingObject* floatingObject = *it;
+            if (childrenInline()) {
+                LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
+                LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
+
+                // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
+                if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max()) {
+                    logicalBottom = LayoutUnit::max();
+                } else {
+                    // Special-case zero- and less-than-zero-height floats: those don't touch
+                    // the line that they're on, but it still needs to be dirtied. This is
+                    // accomplished by pretending they have a height of 1.
+                    logicalBottom = max(logicalBottom, logicalTop + 1);
+                }
+                if (floatingObject->originatingLine()) {
+                    if (!selfNeedsLayout()) {
+                        ASSERT(floatingObject->originatingLine()->renderer() == this);
+                        floatingObject->originatingLine()->markDirty();
+                    }
+#if !ASSERT_DISABLED
+                    floatingObject->setOriginatingLine(0);
+#endif
+                }
+                markLinesDirtyInBlockRange(0, logicalBottom);
+            }
+            m_floatingObjects->remove(floatingObject);
+        }
+    }
+}
+
+void RenderBlockFlow::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
+{
+    if (!containsFloats())
+        return;
+
+    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+    FloatingObject* curr = floatingObjectSet.last();
+    while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(curr) >= logicalOffset)) {
+        m_floatingObjects->remove(curr);
+        if (floatingObjectSet.isEmpty())
+            break;
+        curr = floatingObjectSet.last();
+    }
+}
+
+bool RenderBlockFlow::positionNewFloats()
+{
+    if (!m_floatingObjects)
+        return false;
+
+    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+    if (floatingObjectSet.isEmpty())
+        return false;
+
+    // If all floats have already been positioned, then we have no work to do.
+    if (floatingObjectSet.last()->isPlaced())
+        return false;
+
+    // Move backwards through our floating object list until we find a float that has
+    // already been positioned. Then we'll be able to move forward, positioning all of
+    // the new floats that need it.
+    FloatingObjectSetIterator it = floatingObjectSet.end();
+    --it; // Go to last item.
+    FloatingObjectSetIterator begin = floatingObjectSet.begin();
+    FloatingObject* lastPlacedFloatingObject = 0;
+    while (it != begin) {
+        --it;
+        if ((*it)->isPlaced()) {
+            lastPlacedFloatingObject = *it;
+            ++it;
+            break;
+        }
+    }
+
+    LayoutUnit logicalTop = logicalHeight();
+
+    // The float cannot start above the top position of the last positioned float.
+    if (lastPlacedFloatingObject)
+        logicalTop = max(logicalTopForFloat(lastPlacedFloatingObject), logicalTop);
+
+    FloatingObjectSetIterator end = floatingObjectSet.end();
+    // Now walk through the set of unpositioned floats and place them.
+    for (; it != end; ++it) {
+        FloatingObject* floatingObject = *it;
+        // The containing block is responsible for positioning floats, so if we have floats in our
+        // list that come from somewhere else, do not attempt to position them.
+        if (floatingObject->renderer()->containingBlock() != this)
+            continue;
+
+        RenderBox* childBox = floatingObject->renderer();
+        LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
+
+        LayoutRect oldRect = childBox->frameRect();
+
+        if (childBox->style()->clear() & CLEFT)
+            logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
+        if (childBox->style()->clear() & CRIGHT)
+            logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
+
+        LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
+
+        setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
+
+        setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
+        setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
+
+        SubtreeLayoutScope layoutScope(childBox);
+        LayoutState* layoutState = view()->layoutState();
+        bool isPaginated = layoutState->isPaginated();
+        if (isPaginated && !childBox->needsLayout())
+            childBox->markForPaginationRelayoutIfNeeded(layoutScope);
+
+        childBox->layoutIfNeeded();
+
+        if (isPaginated) {
+            // If we are unsplittable and don't fit, then we need to move down.
+            // We include our margins as part of the unsplittable area.
+            LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, floatLogicalLocation.y(), true);
+
+            // See if we have a pagination strut that is making us move down further.
+            // Note that an unsplittable child can't also have a pagination strut, so this is
+            // exclusive with the case above.
+            RenderBlock* childBlock = childBox->isRenderBlock() ? toRenderBlock(childBox) : 0;
+            if (childBlock && childBlock->paginationStrut()) {
+                newLogicalTop += childBlock->paginationStrut();
+                childBlock->setPaginationStrut(0);
+            }
+
+            if (newLogicalTop != floatLogicalLocation.y()) {
+                floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
+
+                floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
+                setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
+
+                setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
+                setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
+
+                if (childBlock)
+                    childBlock->setChildNeedsLayout(MarkOnlyThis);
+                childBox->layoutIfNeeded();
+            }
+        }
+
+        setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
+
+        setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
+
+        m_floatingObjects->addPlacedObject(floatingObject);
+
+        // If the child moved, we have to repaint it.
+        if (childBox->checkForRepaintDuringLayout())
+            childBox->repaintDuringLayoutIfMoved(oldRect);
+    }
+    return true;
+}
+
+bool RenderBlockFlow::hasOverhangingFloat(RenderBox* renderer)
+{
+    if (!m_floatingObjects || hasColumns() || !parent())
+        return false;
+
+    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+    FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(renderer);
+    if (it == floatingObjectSet.end())
+        return false;
+
+    return logicalBottomForFloat(*it) > logicalHeight();
+}
+
+void RenderBlockFlow::addIntrudingFloats(RenderBlockFlow* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
+{
+    ASSERT(!avoidsFloats());
+
+    // If the parent or previous sibling doesn't have any floats to add, don't bother.
+    if (!prev->m_floatingObjects)
+        return;
+
+    logicalLeftOffset += marginLogicalLeft();
+
+    const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
+    FloatingObjectSetIterator prevEnd = prevSet.end();
+    for (FloatingObjectSetIterator prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
+        FloatingObject* floatingObject = *prevIt;
+        if (logicalBottomForFloat(floatingObject) > logicalTopOffset) {
+            if (!m_floatingObjects || !m_floatingObjects->set().contains(floatingObject)) {
+                // We create the floating object list lazily.
+                if (!m_floatingObjects)
+                    createFloatingObjects();
+
+                // Applying the child's margin makes no sense in the case where the child was passed in.
+                // since this margin was added already through the modification of the |logicalLeftOffset| variable
+                // above. |logicalLeftOffset| will equal the margin in this case, so it's already been taken
+                // into account. Only apply this code if prev is the parent, since otherwise the left margin
+                // will get applied twice.
+                LayoutSize offset = isHorizontalWritingMode()
+                    ? LayoutSize(logicalLeftOffset - (prev != parent() ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
+                    : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != parent() ? prev->marginTop() : LayoutUnit()));
+
+                m_floatingObjects->add(floatingObject->copyToNewContainer(offset));
+            }
+        }
+    }
+}
+
+LayoutUnit RenderBlockFlow::addOverhangingFloats(RenderBlockFlow* child, bool makeChildPaintOtherFloats)
+{
+    // Prevent floats from being added to the canvas by the root element, e.g., <html>.
+    if (child->hasOverflowClip() || !child->containsFloats() || child->isRoot() || child->hasColumns() || child->isWritingModeRoot())
+        return 0;
+
+    LayoutUnit childLogicalTop = child->logicalTop();
+    LayoutUnit childLogicalLeft = child->logicalLeft();
+    LayoutUnit lowestFloatLogicalBottom = 0;
+
+    // Floats that will remain the child's responsibility to paint should factor into its
+    // overflow.
+    FloatingObjectSetIterator childEnd = child->m_floatingObjects->set().end();
+    for (FloatingObjectSetIterator childIt = child->m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
+        FloatingObject* floatingObject = *childIt;
+        LayoutUnit logicalBottomForFloat = min(this->logicalBottomForFloat(floatingObject), LayoutUnit::max() - childLogicalTop);
+        LayoutUnit logicalBottom = childLogicalTop + logicalBottomForFloat;
+        lowestFloatLogicalBottom = max(lowestFloatLogicalBottom, logicalBottom);
+
+        if (logicalBottom > logicalHeight()) {
+            // If the object is not in the list, we add it now.
+            if (!containsFloat(floatingObject->renderer())) {
+                LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
+                bool shouldPaint = false;
+
+                // The nearest enclosing layer always paints the float (so that zindex and stacking
+                // behaves properly). We always want to propagate the desire to paint the float as
+                // far out as we can, to the outermost block that overlaps the float, stopping only
+                // if we hit a self-painting layer boundary.
+                if (floatingObject->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
+                    floatingObject->setShouldPaint(false);
+                    shouldPaint = true;
+                }
+                // We create the floating object list lazily.
+                if (!m_floatingObjects)
+                    createFloatingObjects();
+
+                m_floatingObjects->add(floatingObject->copyToNewContainer(offset, shouldPaint, true));
+            }
+        } else {
+            if (makeChildPaintOtherFloats && !floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()
+                && floatingObject->renderer()->isDescendantOf(child) && floatingObject->renderer()->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
+                // The float is not overhanging from this block, so if it is a descendant of the child, the child should
+                // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
+                // layer.
+                // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
+                // it should paint.
+                floatingObject->setShouldPaint(true);
+            }
+
+            // Since the float doesn't overhang, it didn't get put into our list. We need to go ahead and add its overflow in to the
+            // child now.
+            if (floatingObject->isDescendant())
+                child->addOverflowFromChild(floatingObject->renderer(), LayoutSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
+        }
+    }
+    return lowestFloatLogicalBottom;
+}
+
+LayoutUnit RenderBlockFlow::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
+{
+    if (!m_floatingObjects)
+        return 0;
+
+    return m_floatingObjects->lowestFloatLogicalBottom(floatType);
+}
+
+LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
+{
+    if (!m_floatingObjects)
+        return logicalHeight;
+
+    LayoutUnit logicalBottom = LayoutUnit::max();
+    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+    FloatingObjectSetIterator end = floatingObjectSet.end();
+    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+        FloatingObject* floatingObject = *it;
+        LayoutUnit floatLogicalBottom = logicalBottomForFloat(floatingObject);
+        ShapeOutsideInfo* shapeOutside = floatingObject->renderer()->shapeOutsideInfo();
+        if (shapeOutside && (offsetMode == ShapeOutsideFloatShapeOffset)) {
+            LayoutUnit shapeLogicalBottom = logicalTopForFloat(floatingObject) + marginBeforeForChild(floatingObject->renderer()) + shapeOutside->shapeLogicalBottom();
+            // Use the shapeLogicalBottom unless it extends outside of the margin box, in which case it is clipped.
+            if (shapeLogicalBottom < floatLogicalBottom)
+                floatLogicalBottom = shapeLogicalBottom;
+        }
+        if (floatLogicalBottom > logicalHeight)
+            logicalBottom = min(floatLogicalBottom, logicalBottom);
+    }
+
+    return logicalBottom == LayoutUnit::max() ? LayoutUnit() : logicalBottom;
+}
+
+bool RenderBlockFlow::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
+{
+    if (!m_floatingObjects)
+        return false;
+
+    LayoutPoint adjustedLocation = accumulatedOffset;
+    if (isRenderView()) {
+        adjustedLocation += toLayoutSize(toRenderView(this)->frameView()->scrollPosition());
+    }
+
+    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+    FloatingObjectSetIterator begin = floatingObjectSet.begin();
+    for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
+        --it;
+        FloatingObject* floatingObject = *it;
+        if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
+            LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
+            LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y();
+            LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
+            if (floatingObject->renderer()->hitTest(request, result, locationInContainer, childPoint)) {
+                updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
+                return true;
+            }
+        }
+    }
+
+    return false;
+}
+
+void RenderBlockFlow::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const
+{
+    RenderBlock::adjustForBorderFit(x, left, right);
+    if (m_floatingObjects && style()->visibility() == VISIBLE) {
+        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+        FloatingObjectSetIterator end = floatingObjectSet.end();
+        for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+            FloatingObject* floatingObject = *it;
+            // Only examine the object if our m_shouldPaint flag is set.
+            if (floatingObject->shouldPaint()) {
+                LayoutUnit floatLeft = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
+                LayoutUnit floatRight = floatLeft + floatingObject->renderer()->width();
+                left = min(left, floatLeft);
+                right = max(right, floatRight);
+            }
+        }
+    }
+}
+
+LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
+{
+    if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
+        return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
+
+    return fixedOffset;
+}
+
+LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
+{
+    if (m_floatingObjects && m_floatingObjects->hasRightObjects())
+        return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
+
+    return fixedOffset;
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderBlockFlow.h b/Source/core/rendering/RenderBlockFlow.h
index d5d35a4..7ee99d0 100644
--- a/Source/core/rendering/RenderBlockFlow.h
+++ b/Source/core/rendering/RenderBlockFlow.h
@@ -36,11 +36,14 @@
 #ifndef RenderBlockFlow_h
 #define RenderBlockFlow_h
 
-#include "RenderBlock.h"
+#include "core/rendering/FloatingObjects.h"
+#include "core/rendering/RenderBlock.h"
 
 namespace WebCore {
 
 class MarginInfo;
+class LineBreaker;
+class LineWidth;
 
 class RenderBlockFlow : public RenderBlock {
 public:
@@ -50,6 +53,59 @@
     virtual bool isRenderBlockFlow() const OVERRIDE FINAL { return true; }
 
     virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE;
+
+    virtual void computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats = false) OVERRIDE;
+    virtual void deleteLineBoxTree() OVERRIDE FINAL;
+
+    void markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove = 0, bool inLayout = true);
+    void markSiblingsWithFloatsForLayout(RenderBox* floatToRemove = 0);
+
+    virtual bool containsFloats() const OVERRIDE FINAL { return m_floatingObjects && !m_floatingObjects->set().isEmpty(); }
+    bool containsFloat(RenderBox*) const;
+
+    void removeFloatingObjects();
+
+    LayoutUnit logicalTopForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->y() : floatingObject->x(); }
+    LayoutUnit logicalBottomForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->maxY() : floatingObject->maxX(); }
+    LayoutUnit logicalLeftForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->x() : floatingObject->y(); }
+    LayoutUnit logicalRightForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->maxX() : floatingObject->maxY(); }
+    LayoutUnit logicalWidthForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->width() : floatingObject->height(); }
+    LayoutUnit logicalHeightForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->height() : floatingObject->width(); }
+    LayoutSize logicalSizeForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? LayoutSize(floatingObject->width(), floatingObject->height()) : LayoutSize(floatingObject->height(), floatingObject->width()); }
+
+    int pixelSnappedLogicalTopForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->frameRect().pixelSnappedY() : floatingObject->frameRect().pixelSnappedX(); }
+    int pixelSnappedLogicalBottomForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->frameRect().pixelSnappedMaxY() : floatingObject->frameRect().pixelSnappedMaxX(); }
+    int pixelSnappedLogicalLeftForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->frameRect().pixelSnappedX() : floatingObject->frameRect().pixelSnappedY(); }
+    int pixelSnappedLogicalRightForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->frameRect().pixelSnappedMaxX() : floatingObject->frameRect().pixelSnappedMaxY(); }
+
+    void setLogicalTopForFloat(FloatingObject* floatingObject, LayoutUnit logicalTop)
+    {
+        if (isHorizontalWritingMode())
+            floatingObject->setY(logicalTop);
+        else
+            floatingObject->setX(logicalTop);
+    }
+    void setLogicalLeftForFloat(FloatingObject* floatingObject, LayoutUnit logicalLeft)
+    {
+        if (isHorizontalWritingMode())
+            floatingObject->setX(logicalLeft);
+        else
+            floatingObject->setY(logicalLeft);
+    }
+    void setLogicalHeightForFloat(FloatingObject* floatingObject, LayoutUnit logicalHeight)
+    {
+        if (isHorizontalWritingMode())
+            floatingObject->setHeight(logicalHeight);
+        else
+            floatingObject->setWidth(logicalHeight);
+    }
+    void setLogicalWidthForFloat(FloatingObject* floatingObject, LayoutUnit logicalWidth)
+    {
+        if (isHorizontalWritingMode())
+            floatingObject->setWidth(logicalWidth);
+        else
+            floatingObject->setHeight(logicalWidth);
+    }
 protected:
     // Only used by RenderSVGText, which explicitly overrides RenderBlock::layoutBlock(), do NOT use for anything else.
     void forceLayoutInlineChildren()
@@ -60,6 +116,12 @@
         layoutInlineChildren(true, repaintLogicalTop, repaintLogicalBottom);
     }
 
+    void createFloatingObjects();
+
+    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+
+    void addOverflowFromFloats();
 private:
     void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope&);
     void layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom);
@@ -70,6 +132,55 @@
 
     void rebuildFloatsFromIntruding();
 
+    LayoutPoint flipFloatForWritingModeForChild(const FloatingObject*, const LayoutPoint&) const;
+
+    LayoutUnit xPositionForFloatIncludingMargin(const FloatingObject* child) const
+    {
+        if (isHorizontalWritingMode())
+            return child->x() + child->renderer()->marginLeft();
+
+        return child->x() + marginBeforeForChild(child->renderer());
+    }
+
+    LayoutUnit yPositionForFloatIncludingMargin(const FloatingObject* child) const
+    {
+        if (isHorizontalWritingMode())
+            return child->y() + marginBeforeForChild(child->renderer());
+
+        return child->y() + child->renderer()->marginTop();
+    }
+
+    LayoutPoint computeLogicalLocationForFloat(const FloatingObject*, LayoutUnit logicalTopOffset) const;
+
+    FloatingObject* insertFloatingObject(RenderBox*);
+    void removeFloatingObject(RenderBox*);
+    void removeFloatingObjectsBelow(FloatingObject*, int logicalOffset);
+
+    // Called from lineWidth, to position the floats added in the last line.
+    // Returns true if and only if it has positioned any floats.
+    bool positionNewFloats();
+
+    LayoutUnit getClearDelta(RenderBox* child, LayoutUnit yPos);
+
+    bool hasOverhangingFloats() { return parent() && !hasColumns() && containsFloats() && lowestFloatLogicalBottom() > logicalHeight(); }
+    bool hasOverhangingFloat(RenderBox*);
+    void addIntrudingFloats(RenderBlockFlow* prev, LayoutUnit xoffset, LayoutUnit yoffset);
+    LayoutUnit addOverhangingFloats(RenderBlockFlow* child, bool makeChildPaintOtherFloats);
+
+    LayoutUnit lowestFloatLogicalBottom(FloatingObject::Type = FloatingObject::FloatLeftRight) const;
+    LayoutUnit nextFloatLogicalBottomBelow(LayoutUnit, ShapeOutsideFloatOffsetMode = ShapeOutsideFloatMarginBoxOffset) const;
+
+    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 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* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const OVERRIDE;
+    virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const OVERRIDE;
+    virtual void adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const OVERRIDE; // Helper function for borderFitAdjust
+
 public:
     class MarginValues {
     public:
@@ -179,10 +290,59 @@
 
     LayoutUnit adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock);
 
+    // Used to store state between styleWillChange and styleDidChange
+    static bool s_canPropagateFloatIntoSibling;
+
 protected:
     OwnPtr<RenderBlockFlowRareData> m_rareData;
+    OwnPtr<FloatingObjects> m_floatingObjects;
 
+    friend class BreakingContext; // FIXME: It uses insertFloatingObject and positionNewFloatOnLine, if we move those out from the private scope/add a helper to LineBreaker, we can remove this friend
     friend class MarginInfo;
+    friend class LineBreaker;
+    friend class LineWidth; // needs to know FloatingObject
+
+// FIXME-BLOCKFLOW: These methods have implementations in
+// RenderBlockLineLayout. They should be moved to the proper header once the
+// line layout code is separated from RenderBlock and RenderBlockFlow.
+// START METHODS DEFINED IN RenderBlockLineLayout
+public:
+    static void appendRunsForObject(BidiRunList<BidiRun>&, int start, int end, RenderObject*, InlineBidiResolver&);
+
+private:
+    InlineFlowBox* createLineBoxes(RenderObject*, const LineInfo&, InlineBox* childBox, bool startsNewSegment);
+    RootInlineBox* constructLine(BidiRunList<BidiRun>&, const LineInfo&);
+    void setMarginsForRubyRun(BidiRun*, RenderRubyRun*, RenderObject*, const LineInfo&);
+    void computeInlineDirectionPositionsForLine(RootInlineBox*, const LineInfo&, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd, GlyphOverflowAndFallbackFontsMap&, VerticalPositionCache&, WordMeasurements&);
+    BidiRun* computeInlineDirectionPositionsForSegment(RootInlineBox*, const LineInfo&, ETextAlign, float& logicalLeft,
+        float& availableLogicalWidth, BidiRun* firstRun, BidiRun* trailingSpaceRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache&, WordMeasurements&);
+    void computeBlockDirectionPositionsForLine(RootInlineBox*, BidiRun*, GlyphOverflowAndFallbackFontsMap&, VerticalPositionCache&);
+    BidiRun* handleTrailingSpaces(BidiRunList<BidiRun>&, BidiContext*);
+    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);
+    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&);
+    void updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideInfo*&, LineLayoutState&);
+    bool adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo*, LayoutUnit, LineLayoutState&, InlineBidiResolver&, FloatingObject*, InlineIterator&, WordMeasurements&);
+    void linkToEndLineIfNeeded(LineLayoutState&);
+    static void repaintDirtyFloats(Vector<FloatWithRect>& floats);
+    void checkFloatsInCleanLine(RootInlineBox*, Vector<FloatWithRect>&, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat);
+    RootInlineBox* determineStartPosition(LineLayoutState&, InlineBidiResolver&);
+    void determineEndPosition(LineLayoutState&, RootInlineBox* startBox, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus);
+    bool checkPaginationAndFloatsAtEndLine(LineLayoutState&);
+    bool matchedEndLine(LineLayoutState&, const InlineBidiResolver&, const InlineIterator& endLineStart, const BidiStatus& endLineStatus);
+    void deleteEllipsisLineBoxes();
+    void checkLinesForTextOverflow();
+    // Positions new floats and also adjust all floats encountered on the line if any of them
+    // have to move to the next page/column.
+    bool positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo&, LineWidth&);
+
+
+// END METHODS DEFINED IN RenderBlockLineLayout
+
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderBlockFlow, isRenderBlockFlow());
diff --git a/Source/core/rendering/RenderBlockLineLayout.cpp b/Source/core/rendering/RenderBlockLineLayout.cpp
index 66f002a..35540fa 100644
--- a/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -140,7 +140,8 @@
 
 class LineBreaker {
 public:
-    LineBreaker(RenderBlock* block)
+    friend class BreakingContext;
+    LineBreaker(RenderBlockFlow* block)
         : m_block(block)
     {
         reset();
@@ -155,122 +156,121 @@
     void reset();
 
     InlineIterator nextSegmentBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
-
-    class BreakingContext {
-    public:
-        BreakingContext(InlineBidiResolver& resolver, LineInfo& inLineInfo, LineWidth& lineWidth, RenderTextInfo& inRenderTextInfo, FloatingObject* inLastFloatFromPreviousLine, bool appliedStartWidth, RenderBlock* block)
-            : m_resolver(resolver)
-            , m_current(resolver.position())
-            , m_lineBreak(resolver.position())
-            , m_block(block)
-            , m_lastObject(m_current.m_obj)
-            , m_nextObject(0)
-            , m_currentStyle(0)
-            , m_blockStyle(block->style())
-            , m_lineInfo(inLineInfo)
-            , m_renderTextInfo(inRenderTextInfo)
-            , m_lastFloatFromPreviousLine(inLastFloatFromPreviousLine)
-            , m_width(lineWidth)
-            , m_currWS(NORMAL)
-            , m_lastWS(NORMAL)
-            , m_preservesNewline(false)
-            , m_atStart(true)
-            , m_ignoringSpaces(false)
-            , m_currentCharacterIsSpace(false)
-            , m_currentCharacterShouldCollapseIfPreWap(false)
-            , m_appliedStartWidth(appliedStartWidth)
-            , m_includeEndWidth(true)
-            , m_autoWrap(false)
-            , m_autoWrapWasEverTrueOnLine(false)
-            , m_floatsFitOnLine(true)
-            , m_collapseWhiteSpace(false)
-            , m_startingNewParagraph(m_lineInfo.previousLineBrokeCleanly())
-            , m_allowImagesToBreak(!block->document().inQuirksMode() || !block->isTableCell() || !m_blockStyle->logicalWidth().isIntrinsicOrAuto())
-            , m_atEnd(false)
-            , m_lineMidpointState(resolver.midpointState())
-        {
-            m_lineInfo.setPreviousLineBrokeCleanly(false);
-        }
-
-        RenderObject* currentObject() { return m_current.m_obj; }
-        InlineIterator lineBreak() { return m_lineBreak; }
-        bool atEnd() { return m_atEnd; }
-
-        void initializeForCurrentObject();
-
-        void increment();
-
-        void handleBR(EClear&);
-        void handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects);
-        void handleFloat();
-        void handleEmptyInline();
-        void handleReplaced();
-        bool handleText(WordMeasurements&, bool& hyphenated);
-        void commitAndUpdateLineBreakIfNeeded();
-        InlineIterator handleEndOfLine();
-
-        void clearLineBreakIfFitsOnLine()
-        {
-            if (m_width.fitsOnLine() || m_lastWS == NOWRAP)
-                m_lineBreak.clear();
-        }
-
-    private:
-        void skipTrailingWhitespace(InlineIterator&, const LineInfo&);
-
-        InlineBidiResolver& m_resolver;
-
-        InlineIterator m_current;
-        InlineIterator m_lineBreak;
-        InlineIterator m_startOfIgnoredSpaces;
-
-        RenderBlock* m_block;
-        RenderObject* m_lastObject;
-        RenderObject* m_nextObject;
-
-        RenderStyle* m_currentStyle;
-        RenderStyle* m_blockStyle;
-
-        LineInfo& m_lineInfo;
-
-        RenderTextInfo& m_renderTextInfo;
-
-        FloatingObject* m_lastFloatFromPreviousLine;
-
-        LineWidth m_width;
-
-        EWhiteSpace m_currWS;
-        EWhiteSpace m_lastWS;
-
-        bool m_preservesNewline;
-        bool m_atStart;
-        bool m_ignoringSpaces;
-        bool m_currentCharacterIsSpace;
-        bool m_currentCharacterShouldCollapseIfPreWap;
-        bool m_appliedStartWidth;
-        bool m_includeEndWidth;
-        bool m_autoWrap;
-        bool m_autoWrapWasEverTrueOnLine;
-        bool m_floatsFitOnLine;
-        bool m_collapseWhiteSpace;
-        bool m_startingNewParagraph;
-        bool m_allowImagesToBreak;
-        bool m_atEnd;
-
-        LineMidpointState& m_lineMidpointState;
-
-        TrailingObjects m_trailingObjects;
-    };
-
     void skipLeadingWhitespace(InlineBidiResolver&, LineInfo&, FloatingObject* lastFloatFromPreviousLine, LineWidth&);
 
-    RenderBlock* m_block;
+    RenderBlockFlow* m_block;
     bool m_hyphenated;
     EClear m_clear;
     Vector<RenderBox*> m_positionedObjects;
 };
 
-inline void LineBreaker::BreakingContext::initializeForCurrentObject()
+class BreakingContext {
+public:
+    BreakingContext(InlineBidiResolver& resolver, LineInfo& inLineInfo, LineWidth& lineWidth, RenderTextInfo& inRenderTextInfo, FloatingObject* inLastFloatFromPreviousLine, bool appliedStartWidth, RenderBlockFlow* block)
+        : m_resolver(resolver)
+        , m_current(resolver.position())
+        , m_lineBreak(resolver.position())
+        , m_block(block)
+        , m_lastObject(m_current.m_obj)
+        , m_nextObject(0)
+        , m_currentStyle(0)
+        , m_blockStyle(block->style())
+        , m_lineInfo(inLineInfo)
+        , m_renderTextInfo(inRenderTextInfo)
+        , m_lastFloatFromPreviousLine(inLastFloatFromPreviousLine)
+        , m_width(lineWidth)
+        , m_currWS(NORMAL)
+        , m_lastWS(NORMAL)
+        , m_preservesNewline(false)
+        , m_atStart(true)
+        , m_ignoringSpaces(false)
+        , m_currentCharacterIsSpace(false)
+        , m_currentCharacterShouldCollapseIfPreWap(false)
+        , m_appliedStartWidth(appliedStartWidth)
+        , m_includeEndWidth(true)
+        , m_autoWrap(false)
+        , m_autoWrapWasEverTrueOnLine(false)
+        , m_floatsFitOnLine(true)
+        , m_collapseWhiteSpace(false)
+        , m_startingNewParagraph(m_lineInfo.previousLineBrokeCleanly())
+        , m_allowImagesToBreak(!block->document().inQuirksMode() || !block->isTableCell() || !m_blockStyle->logicalWidth().isIntrinsicOrAuto())
+        , m_atEnd(false)
+        , m_lineMidpointState(resolver.midpointState())
+    {
+        m_lineInfo.setPreviousLineBrokeCleanly(false);
+    }
+
+    RenderObject* currentObject() { return m_current.m_obj; }
+    InlineIterator lineBreak() { return m_lineBreak; }
+    bool atEnd() { return m_atEnd; }
+
+    void initializeForCurrentObject();
+
+    void increment();
+
+    void handleBR(EClear&);
+    void handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects);
+    void handleFloat();
+    void handleEmptyInline();
+    void handleReplaced();
+    bool handleText(WordMeasurements&, bool& hyphenated);
+    void commitAndUpdateLineBreakIfNeeded();
+    InlineIterator handleEndOfLine();
+
+    void clearLineBreakIfFitsOnLine()
+    {
+        if (m_width.fitsOnLine() || m_lastWS == NOWRAP)
+            m_lineBreak.clear();
+    }
+
+private:
+    void skipTrailingWhitespace(InlineIterator&, const LineInfo&);
+
+    InlineBidiResolver& m_resolver;
+
+    InlineIterator m_current;
+    InlineIterator m_lineBreak;
+    InlineIterator m_startOfIgnoredSpaces;
+
+    RenderBlockFlow* m_block;
+    RenderObject* m_lastObject;
+    RenderObject* m_nextObject;
+
+    RenderStyle* m_currentStyle;
+    RenderStyle* m_blockStyle;
+
+    LineInfo& m_lineInfo;
+
+    RenderTextInfo& m_renderTextInfo;
+
+    FloatingObject* m_lastFloatFromPreviousLine;
+
+    LineWidth m_width;
+
+    EWhiteSpace m_currWS;
+    EWhiteSpace m_lastWS;
+
+    bool m_preservesNewline;
+    bool m_atStart;
+    bool m_ignoringSpaces;
+    bool m_currentCharacterIsSpace;
+    bool m_currentCharacterShouldCollapseIfPreWap;
+    bool m_appliedStartWidth;
+    bool m_includeEndWidth;
+    bool m_autoWrap;
+    bool m_autoWrapWasEverTrueOnLine;
+    bool m_floatsFitOnLine;
+    bool m_collapseWhiteSpace;
+    bool m_startingNewParagraph;
+    bool m_allowImagesToBreak;
+    bool m_atEnd;
+
+    LineMidpointState& m_lineMidpointState;
+
+    TrailingObjects m_trailingObjects;
+};
+
+inline void BreakingContext::initializeForCurrentObject()
 {
     m_currentStyle = m_current.m_obj->style();
     m_nextObject = bidiNextSkippingEmptyInlines(m_block, m_current.m_obj);
@@ -288,7 +288,7 @@
     m_collapseWhiteSpace = RenderStyle::collapseWhiteSpace(m_currWS);
 }
 
-inline void LineBreaker::BreakingContext::increment()
+inline void BreakingContext::increment()
 {
     // Clear out our character space bool, since inline <pre>s don't collapse whitespace
     // with adjacent inline normal/nowrap spans.
@@ -451,50 +451,9 @@
     stopIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.m_obj, textParagraphSeparator.m_pos));
 }
 
-static inline BidiRun* createRun(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
+void RenderBlockFlow::appendRunsForObject(BidiRunList<BidiRun>& runs, int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
 {
-    return new BidiRun(start, end, obj, resolver.context(), resolver.dir());
-}
-
-void RenderBlock::appendRunsForObject(BidiRunList<BidiRun>& runs, int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
-{
-    if (start > end || shouldSkipCreatingRunsForObject(obj))
-        return;
-
-    LineMidpointState& lineMidpointState = resolver.midpointState();
-    bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
-    InlineIterator nextMidpoint;
-    if (haveNextMidpoint)
-        nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
-    if (lineMidpointState.betweenMidpoints) {
-        if (!(haveNextMidpoint && nextMidpoint.m_obj == obj))
-            return;
-        // This is a new start point. Stop ignoring objects and
-        // adjust our start.
-        lineMidpointState.betweenMidpoints = false;
-        start = nextMidpoint.m_pos;
-        lineMidpointState.currentMidpoint++;
-        if (start < end)
-            return appendRunsForObject(runs, start, end, obj, resolver);
-    } else {
-        if (!haveNextMidpoint || (obj != nextMidpoint.m_obj)) {
-            runs.addRun(createRun(start, end, obj, resolver));
-            return;
-        }
-
-        // An end midpoint has been encountered within our object.  We
-        // need to go ahead and append a run with our endpoint.
-        if (static_cast<int>(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 include any of it.
-                if (static_cast<int>(nextMidpoint.m_pos + 1) > start)
-                    runs.addRun(createRun(start, nextMidpoint.m_pos + 1, obj, resolver));
-                return appendRunsForObject(runs, nextMidpoint.m_pos + 1, end, obj, resolver);
-            }
-        } else
-           runs.addRun(createRun(start, end, obj, resolver));
-    }
+    adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, end, resolver, AppendingRunsForObject, &runs);
 }
 
 static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
@@ -536,7 +495,7 @@
     return false;
 }
 
-InlineFlowBox* RenderBlock::createLineBoxes(RenderObject* obj, const LineInfo& lineInfo, InlineBox* childBox, bool startNewSegment)
+InlineFlowBox* RenderBlockFlow::createLineBoxes(RenderObject* obj, const LineInfo& lineInfo, InlineBox* childBox, bool startNewSegment)
 {
     // See if we have an unconstructed line box for this object that is also
     // the last item on the line.
@@ -629,7 +588,7 @@
     return endsWithASCIISpaces(renderText->characters16(), pos, length);
 }
 
-RootInlineBox* RenderBlock::constructLine(BidiRunList<BidiRun>& bidiRuns, const LineInfo& lineInfo)
+RootInlineBox* RenderBlockFlow::constructLine(BidiRunList<BidiRun>& bidiRuns, const LineInfo& lineInfo)
 {
     ASSERT(bidiRuns.firstRun());
 
@@ -766,7 +725,7 @@
         logicalLeft += totalLogicalWidth > availableLogicalWidth ? (availableLogicalWidth - totalLogicalWidth) : (availableLogicalWidth - totalLogicalWidth) / 2 - trailingSpaceWidth;
 }
 
-void RenderBlock::setMarginsForRubyRun(BidiRun* run, RenderRubyRun* renderer, RenderObject* previousObject, const LineInfo& lineInfo)
+void RenderBlockFlow::setMarginsForRubyRun(BidiRun* run, RenderRubyRun* renderer, RenderObject* previousObject, const LineInfo& lineInfo)
 {
     int startOverhang;
     int endOverhang;
@@ -977,7 +936,7 @@
     }
 }
 
-static void updateLogicalInlinePositions(RenderBlock* block, float& lineLogicalLeft, float& lineLogicalRight, float& availableLogicalWidth, bool firstLine, IndentTextOrNot shouldIndentText, LayoutUnit boxLogicalHeight)
+static void updateLogicalInlinePositions(RenderBlockFlow* block, float& lineLogicalLeft, float& lineLogicalRight, float& availableLogicalWidth, bool firstLine, IndentTextOrNot shouldIndentText, LayoutUnit boxLogicalHeight)
 {
     LayoutUnit lineLogicalHeight = block->minLineHeightForReplacedRenderer(firstLine, boxLogicalHeight);
     lineLogicalLeft = block->pixelSnappedLogicalLeftOffsetForLine(block->logicalHeight(), shouldIndentText == IndentText, lineLogicalHeight);
@@ -985,7 +944,7 @@
     availableLogicalWidth = lineLogicalRight - lineLogicalLeft;
 }
 
-void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd,
+void RenderBlockFlow::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd,
                                                          GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache, WordMeasurements& wordMeasurements)
 {
     ETextAlign textAlign = textAlignmentForLine(!reachedEnd && !lineBox->endsWithBreak());
@@ -1044,7 +1003,7 @@
     lineBox->placeBoxesInInlineDirection(lineLogicalLeft, needsWordSpacing, textBoxDataMap);
 }
 
-BidiRun* RenderBlock::computeInlineDirectionPositionsForSegment(RootInlineBox* lineBox, const LineInfo& lineInfo, ETextAlign textAlign, float& logicalLeft,
+BidiRun* RenderBlockFlow::computeInlineDirectionPositionsForSegment(RootInlineBox* lineBox, const LineInfo& lineInfo, ETextAlign textAlign, float& logicalLeft,
     float& availableLogicalWidth, BidiRun* firstRun, BidiRun* trailingSpaceRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache,
     WordMeasurements& wordMeasurements)
 {
@@ -1113,7 +1072,7 @@
     return r;
 }
 
-void RenderBlock::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
+void RenderBlockFlow::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
                                                         VerticalPositionCache& verticalPositionCache)
 {
     setLogicalHeight(lineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache));
@@ -1151,7 +1110,7 @@
 }
 
 
-static void setStaticPositions(RenderBlock* block, RenderBox* child)
+static void setStaticPositions(RenderBlockFlow* block, RenderBox* child)
 {
     // FIXME: The math here is actually not really right. It's a best-guess approximation that
     // will work for the common cases
@@ -1182,7 +1141,7 @@
     return firstSpace;
 }
 
-inline BidiRun* RenderBlock::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
+inline BidiRun* RenderBlockFlow::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
 {
     if (!bidiRuns.runCount()
         || !bidiRuns.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
@@ -1233,7 +1192,7 @@
     return trailingSpaceRun;
 }
 
-void RenderBlock::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
+void RenderBlockFlow::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
 {
     ASSERT(!floatingObject->originatingLine());
     floatingObject->setOriginatingLine(lastRootBox());
@@ -1259,6 +1218,15 @@
     }
 }
 
+static void restoreIsolatedMidpointStates(InlineBidiResolver& topResolver, InlineBidiResolver& isolatedResolver)
+{
+    while (!isolatedResolver.isolatedRuns().isEmpty()) {
+        BidiRun* run = isolatedResolver.isolatedRuns().last();
+        isolatedResolver.isolatedRuns().removeLast();
+        topResolver.setMidpointStateForIsolatedRun(run, isolatedResolver.midpointStateForIsolatedRun(run));
+    }
+}
+
 // FIXME: BidiResolver should have this logic.
 static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly, bool isNewUBAParagraph)
 {
@@ -1285,6 +1253,8 @@
         ASSERT(isolatedInline);
 
         InlineBidiResolver isolatedResolver;
+        LineMidpointState& isolatedLineMidpointState = isolatedResolver.midpointState();
+        isolatedLineMidpointState = topResolver.midpointStateForIsolatedRun(isolatedRun);
         EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi();
         TextDirection direction = isolatedInline->style()->direction();
         if (unicodeBidi == Plaintext) {
@@ -1321,8 +1291,8 @@
         // to the top resolver's list for later processing.
         if (!isolatedResolver.isolatedRuns().isEmpty()) {
             topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns());
-            isolatedResolver.isolatedRuns().clear();
             currentRoot = isolatedInline;
+            restoreIsolatedMidpointStates(topResolver, isolatedResolver);
         }
     }
 }
@@ -1332,7 +1302,7 @@
     return segmentStart == segmentEnd;
 }
 
-static inline void constructBidiRunsForLine(const RenderBlock* block, InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfLine, VisualDirectionOverride override, bool previousLineBrokeCleanly, bool isNewUBAParagraph)
+static inline void constructBidiRunsForLine(const RenderBlockFlow* block, InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfLine, VisualDirectionOverride override, bool previousLineBrokeCleanly, bool isNewUBAParagraph)
 {
     ShapeInsideInfo* shapeInsideInfo = block->layoutShapeInsideInfo();
     if (!shapeInsideInfo || !shapeInsideInfo->hasSegments()) {
@@ -1364,7 +1334,7 @@
 }
 
 // This function constructs line boxes for all of the text runs in the resolver and computes their position.
-RootInlineBox* RenderBlock::createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun, WordMeasurements& wordMeasurements)
+RootInlineBox* RenderBlockFlow::createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun, WordMeasurements& wordMeasurements)
 {
     if (!bidiRuns.runCount())
         return 0;
@@ -1508,7 +1478,7 @@
     }
 }
 
-void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
+void RenderBlockFlow::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
 {
     // We want to skip ahead to the first dirty line
     InlineBidiResolver resolver;
@@ -1583,7 +1553,7 @@
 }
 
 // Before restarting the layout loop with a new logicalHeight, remove all floats that were added and reset the resolver.
-inline const InlineIterator& RenderBlock::restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight,  FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver& resolver,  const InlineIterator& oldEnd)
+inline const InlineIterator& RenderBlockFlow::restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight,  FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver& resolver,  const InlineIterator& oldEnd)
 {
     removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight);
     setLogicalHeight(newLogicalHeight);
@@ -1614,7 +1584,7 @@
     return shapeInsideInfo->shapeLogicalBottom();
 }
 
-static inline void pushShapeContentOverflowBelowTheContentBox(RenderBlock* block, ShapeInsideInfo* shapeInsideInfo, LayoutUnit lineTop, LayoutUnit lineHeight)
+static inline void pushShapeContentOverflowBelowTheContentBox(RenderBlockFlow* block, ShapeInsideInfo* shapeInsideInfo, LayoutUnit lineTop, LayoutUnit lineHeight)
 {
     ASSERT(shapeInsideInfo);
 
@@ -1634,7 +1604,7 @@
     block->setLogicalHeight(newLogicalHeight);
 }
 
-void RenderBlock::updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*& shapeInsideInfo, const LayoutSize& logicalOffsetFromShapeContainer, LineLayoutState& layoutState)
+void RenderBlockFlow::updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*& shapeInsideInfo, const LayoutSize& logicalOffsetFromShapeContainer, LineLayoutState& layoutState)
 {
     if (layoutState.flowThread())
         return updateShapeAndSegmentsForCurrentLineInFlowThread(shapeInsideInfo, layoutState);
@@ -1652,47 +1622,49 @@
     pushShapeContentOverflowBelowTheContentBox(this, shapeInsideInfo, lineTop, lineHeight);
 }
 
-void RenderBlock::updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideInfo*& shapeInsideInfo, LineLayoutState& layoutState)
+void RenderBlockFlow::updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideInfo*& shapeInsideInfo, LineLayoutState& layoutState)
 {
     ASSERT(layoutState.flowThread());
 
-    LayoutUnit lineHeight = this->lineHeight(layoutState.lineInfo().isFirstLine(), isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
-
     RenderRegion* currentRegion = regionAtBlockOffset(logicalHeight());
-    if (!currentRegion)
+    if (!currentRegion || !currentRegion->logicalHeight())
         return;
 
     shapeInsideInfo = currentRegion->shapeInsideInfo();
 
+    RenderRegion* nextRegion = 0;
+    if (!currentRegion->isLastRegion()) {
+        RenderRegionList regionList = layoutState.flowThread()->renderRegionList();
+        RenderRegionList::const_iterator it = regionList.find(currentRegion);
+        nextRegion = *(++it);
+    }
+
+    // We only want to deal regions with shapes, so we check if the next region has a shape
+    if (!shapeInsideInfo && nextRegion && !nextRegion->shapeInsideInfo())
+        return;
+
+    LayoutUnit lineHeight = this->lineHeight(layoutState.lineInfo().isFirstLine(), isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
     LayoutUnit logicalLineTopInFlowThread = logicalHeight() + offsetFromLogicalTopOfFirstPage();
     LayoutUnit logicalLineBottomInFlowThread = logicalLineTopInFlowThread + lineHeight;
     LayoutUnit logicalRegionTopInFlowThread = currentRegion->logicalTopForFlowThreadContent();
     LayoutUnit logicalRegionBottomInFlowThread = logicalRegionTopInFlowThread + currentRegion->logicalHeight() - currentRegion->borderAndPaddingBefore() - currentRegion->borderAndPaddingAfter();
 
-    // We only want to deal regions with shapes, so we look up for the next region whether it has a shape
-    if (!shapeInsideInfo && !currentRegion->isLastRegion()) {
-        LayoutUnit deltaToNextRegion = logicalHeight() + logicalRegionBottomInFlowThread - logicalLineTopInFlowThread;
-        RenderRegion* lookupForNextRegion = regionAtBlockOffset(logicalHeight() + deltaToNextRegion);
-        if (!lookupForNextRegion->shapeInsideInfo())
-            return;
-    }
-
     LayoutUnit shapeBottomInFlowThread = LayoutUnit::max();
     if (shapeInsideInfo)
         shapeBottomInFlowThread = shapeInsideInfo->shapeLogicalBottom() + currentRegion->logicalTopForFlowThreadContent();
 
+    bool lineOverLapsWithShapeBottom = shapeBottomInFlowThread < logicalLineBottomInFlowThread;
+    bool lineOverLapsWithRegionBottom = logicalLineBottomInFlowThread > logicalRegionBottomInFlowThread;
+    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
-    RenderRegion* nextRegion = regionAtBlockOffset(logicalHeight() + lineHeight);
-    if ((currentRegion != nextRegion && (logicalLineBottomInFlowThread > logicalRegionBottomInFlowThread)) || (!currentRegion->isLastRegion() && shapeBottomInFlowThread < logicalLineBottomInFlowThread)) {
-        LayoutUnit deltaToNextRegion = logicalRegionBottomInFlowThread - logicalLineTopInFlowThread;
-        nextRegion = regionAtBlockOffset(logicalHeight() + deltaToNextRegion);
-
+    if (overFlowsToNextRegion) {
         ASSERT(currentRegion != nextRegion);
-
-        shapeInsideInfo = nextRegion->shapeInsideInfo();
+        LayoutUnit deltaToNextRegion = logicalRegionBottomInFlowThread - logicalLineTopInFlowThread;
         setLogicalHeight(logicalHeight() + deltaToNextRegion);
 
         currentRegion = nextRegion;
+        shapeInsideInfo = currentRegion->shapeInsideInfo();
 
         logicalLineTopInFlowThread = logicalHeight() + offsetFromLogicalTopOfFirstPage();
         logicalLineBottomInFlowThread = logicalLineTopInFlowThread + lineHeight;
@@ -1703,8 +1675,10 @@
     if (!shapeInsideInfo)
         return;
 
+    bool isFirstLineInRegion = logicalLineBottomInFlowThread <= (logicalRegionTopInFlowThread + lineHeight);
+    bool isFirstLineAdjusted = (logicalLineTopInFlowThread - logicalRegionTopInFlowThread) < (layoutState.adjustedLogicalLineTop() - currentRegion->borderAndPaddingBefore());
     // We position the first line to the top of the shape in the region or to the previously adjusted position in the shape
-    if (logicalLineBottomInFlowThread <= (logicalRegionTopInFlowThread + lineHeight) || (logicalLineTopInFlowThread - logicalRegionTopInFlowThread) < (layoutState.adjustedLogicalLineTop() - currentRegion->borderAndPaddingBefore())) {
+    if (isFirstLineInRegion || isFirstLineAdjusted) {
         LayoutUnit shapeTopOffset = layoutState.adjustedLogicalLineTop();
         if (!shapeTopOffset)
             shapeTopOffset = shapeInsideInfo->shapeLogicalTop();
@@ -1725,14 +1699,14 @@
         pushShapeContentOverflowBelowTheContentBox(this, shapeInsideInfo, lineTop, lineHeight);
 }
 
-bool RenderBlock::adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo* shapeInsideInfo, LayoutUnit absoluteLogicalTop, LineLayoutState& layoutState, InlineBidiResolver& resolver, FloatingObject* lastFloatFromPreviousLine, InlineIterator& end, WordMeasurements& wordMeasurements)
+bool RenderBlockFlow::adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo* shapeInsideInfo, LayoutUnit absoluteLogicalTop, LineLayoutState& layoutState, InlineBidiResolver& resolver, FloatingObject* lastFloatFromPreviousLine, InlineIterator& end, WordMeasurements& wordMeasurements)
 {
     LayoutUnit adjustedLogicalLineTop = adjustLogicalLineTop(shapeInsideInfo, resolver.position(), end, wordMeasurements);
 
-    if (shapeInsideInfo) {
-        lastFloatFromPreviousLine = (containsFloats()) ? m_floatingObjects->set().last() : 0;
-        if (!wordMeasurements.size() && lastFloatFromPreviousLine) {
-            LayoutUnit floatLogicalTopOffset = shapeInsideInfo->computeFirstFitPositionForFloat(lastFloatFromPreviousLine->logicalSize(isHorizontalWritingMode()));
+    if (shapeInsideInfo && containsFloats()) {
+        lastFloatFromPreviousLine = m_floatingObjects->set().last();
+        if (!wordMeasurements.size()) {
+            LayoutUnit floatLogicalTopOffset = shapeInsideInfo->computeFirstFitPositionForFloat(logicalSizeForFloat(lastFloatFromPreviousLine));
             if (logicalHeight() < floatLogicalTopOffset)
                 adjustedLogicalLineTop = floatLogicalTopOffset;
         }
@@ -1752,7 +1726,7 @@
     return true;
 }
 
-void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines)
+void RenderBlockFlow::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines)
 {
     RenderStyle* styleToUse = style();
     bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
@@ -1982,7 +1956,7 @@
     clearDidBreakAtLineToAvoidWidow();
 }
 
-void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState)
+void RenderBlockFlow::linkToEndLineIfNeeded(LineLayoutState& layoutState)
 {
     if (layoutState.endLine()) {
         if (layoutState.endLineMatched()) {
@@ -2057,7 +2031,7 @@
     }
 }
 
-void RenderBlock::repaintDirtyFloats(Vector<FloatWithRect>& floats)
+void RenderBlockFlow::repaintDirtyFloats(Vector<FloatWithRect>& floats)
 {
     size_t floatCount = floats.size();
     // Floats that did not have layout did not repaint when we laid them out. They would have
@@ -2179,7 +2153,7 @@
         checkLinesForTextOverflow();
 }
 
-void RenderBlock::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
+void RenderBlockFlow::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
 {
     Vector<RenderBox*>* cleanLineFloats = line->floatsPtr();
     if (!cleanLineFloats)
@@ -2209,7 +2183,7 @@
     }
 }
 
-RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState, InlineBidiResolver& resolver)
+RootInlineBox* RenderBlockFlow::determineStartPosition(LineLayoutState& layoutState, InlineBidiResolver& resolver)
 {
     RootInlineBox* curr = 0;
     RootInlineBox* last = 0;
@@ -2332,7 +2306,7 @@
     return curr;
 }
 
-void RenderBlock::determineEndPosition(LineLayoutState& layoutState, RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus)
+void RenderBlockFlow::determineEndPosition(LineLayoutState& layoutState, RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus)
 {
     ASSERT(!layoutState.endLine());
     size_t floatIndex = layoutState.floatIndex();
@@ -2369,7 +2343,7 @@
     layoutState.setEndLine(last);
 }
 
-bool RenderBlock::checkPaginationAndFloatsAtEndLine(LineLayoutState& layoutState)
+bool RenderBlockFlow::checkPaginationAndFloatsAtEndLine(LineLayoutState& layoutState)
 {
     LayoutUnit lineDelta = logicalHeight() - layoutState.endLineLogicalTop();
 
@@ -2406,15 +2380,15 @@
     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
     FloatingObjectSetIterator end = floatingObjectSet.end();
     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-        FloatingObject* f = *it;
-        if (f->logicalBottom(isHorizontalWritingMode()) >= logicalTop && f->logicalBottom(isHorizontalWritingMode()) < logicalBottom)
+        FloatingObject* floatingObject = *it;
+        if (logicalBottomForFloat(floatingObject) >= logicalTop && logicalBottomForFloat(floatingObject) < logicalBottom)
             return false;
     }
 
     return true;
 }
 
-bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
+bool RenderBlockFlow::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
 {
     if (resolver.position() == endLineStart) {
         if (resolver.status() != endLineStatus)
@@ -2514,7 +2488,7 @@
 // object iteration process.
 // NB. this function will insert any floating elements that would otherwise
 // be skipped but it will not position them.
-inline void LineBreaker::BreakingContext::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
+inline void BreakingContext::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
 {
     while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
         RenderObject* object = iterator.m_obj;
@@ -2557,7 +2531,7 @@
 
 // This is currently just used for list markers and inline flows that have line boxes. Neither should
 // have an effect on whitespace at the start of the line.
-static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState)
+static bool shouldSkipWhitespaceAfterStartObject(RenderBlockFlow* block, RenderObject* o, LineMidpointState& lineMidpointState)
 {
     RenderObject* next = bidiNextSkippingEmptyInlines(block, o);
     while (next && next->isFloatingOrOutOfFlowPositioned())
@@ -2724,7 +2698,7 @@
     return iter.m_obj == renderer && iter.m_pos >= renderer->textLength();
 }
 
-inline void LineBreaker::BreakingContext::handleBR(EClear& clear)
+inline void BreakingContext::handleBR(EClear& clear)
 {
     if (m_width.fitsOnLine()) {
         RenderObject* br = m_current.m_obj;
@@ -2753,7 +2727,7 @@
     m_atEnd = true;
 }
 
-inline void LineBreaker::BreakingContext::handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects)
+inline void BreakingContext::handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects)
 {
     // If our original display wasn't an inline type, then we can
     // go ahead and determine our static inline position now.
@@ -2781,7 +2755,7 @@
     m_renderTextInfo.m_lineBreakIterator.resetPriorContext();
 }
 
-inline void LineBreaker::BreakingContext::handleFloat()
+inline void BreakingContext::handleFloat()
 {
     RenderBox* floatBox = toRenderBox(m_current.m_obj);
     FloatingObject* floatingObject = m_block->insertFloatingObject(floatBox);
@@ -2789,7 +2763,7 @@
     // If it does, position it now, otherwise, position
     // it after moving to next line (in newLine() func)
     // FIXME: Bug 110372: Properly position multiple stacked floats with non-rectangular shape outside.
-    if (m_floatsFitOnLine && m_width.fitsOnLine(floatingObject->logicalWidth(m_block->isHorizontalWritingMode()))) {
+    if (m_floatsFitOnLine && m_width.fitsOnLine(m_block->logicalWidthForFloat(floatingObject))) {
         m_block->positionNewFloatOnLine(floatingObject, m_lastFloatFromPreviousLine, m_lineInfo, m_width);
         if (m_lineBreak.m_obj == m_current.m_obj) {
             ASSERT(!m_lineBreak.m_pos);
@@ -2802,7 +2776,7 @@
     m_renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);
 }
 
-inline void LineBreaker::BreakingContext::handleEmptyInline()
+inline void BreakingContext::handleEmptyInline()
 {
     // This should only end up being called on empty inlines
     ASSERT(isEmptyInline(m_current.m_obj));
@@ -2834,7 +2808,7 @@
     m_width.addUncommittedWidth(inlineLogicalWidth(m_current.m_obj) + borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
 }
 
-inline void LineBreaker::BreakingContext::handleReplaced()
+inline void BreakingContext::handleReplaced()
 {
     RenderBox* replacedBox = toRenderBox(m_current.m_obj);
 
@@ -2882,7 +2856,7 @@
     lastCharacter = currentCharacter;
 }
 
-static void updateSegmentsForShapes(RenderBlock* block, const FloatingObject* lastFloatFromPreviousLine, const WordMeasurements& wordMeasurements, LineWidth& width, bool isFirstLine)
+static void updateSegmentsForShapes(RenderBlockFlow* block, const FloatingObject* lastFloatFromPreviousLine, const WordMeasurements& wordMeasurements, LineWidth& width, bool isFirstLine)
 {
     ASSERT(lastFloatFromPreviousLine);
 
@@ -2897,8 +2871,8 @@
     LayoutUnit lineLogicalHeight = block->lineHeight(isFirstLine, isHorizontalWritingMode ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
     LayoutUnit lineLogicalBottom = lineLogicalTop + lineLogicalHeight;
 
-    LayoutUnit floatLogicalTop = lastFloatFromPreviousLine->logicalTop(isHorizontalWritingMode);
-    LayoutUnit floatLogicalBottom = lastFloatFromPreviousLine->logicalBottom(isHorizontalWritingMode);
+    LayoutUnit floatLogicalTop = block->logicalTopForFloat(lastFloatFromPreviousLine);
+    LayoutUnit floatLogicalBottom = block->logicalBottomForFloat(lastFloatFromPreviousLine);
 
     bool lineOverlapsWithFloat = (floatLogicalTop < lineLogicalBottom) && (lineLogicalTop < floatLogicalBottom);
     if (!lineOverlapsWithFloat)
@@ -2906,8 +2880,8 @@
 
     float minSegmentWidth = firstPositiveWidth(wordMeasurements);
 
-    LayoutUnit floatLogicalWidth = lastFloatFromPreviousLine->logicalWidth(isHorizontalWritingMode);
-    LayoutUnit availableLogicalWidth = block->logicalWidth() - lastFloatFromPreviousLine->logicalRight(isHorizontalWritingMode);
+    LayoutUnit floatLogicalWidth = block->logicalWidthForFloat(lastFloatFromPreviousLine);
+    LayoutUnit availableLogicalWidth = block->logicalWidth() - block->logicalRightForFloat(lastFloatFromPreviousLine);
     if (availableLogicalWidth < minSegmentWidth)
         block->setLogicalHeight(floatLogicalBottom);
 
@@ -2923,7 +2897,7 @@
     width.updateAvailableWidth();
 }
 
-inline bool LineBreaker::BreakingContext::handleText(WordMeasurements& wordMeasurements, bool& hyphenated)
+inline bool BreakingContext::handleText(WordMeasurements& wordMeasurements, bool& hyphenated)
 {
     if (!m_current.m_pos)
         m_appliedStartWidth = false;
@@ -3216,7 +3190,7 @@
     return false;
 }
 
-inline void LineBreaker::BreakingContext::commitAndUpdateLineBreakIfNeeded()
+inline void BreakingContext::commitAndUpdateLineBreakIfNeeded()
 {
     bool checkForBreak = m_autoWrap;
     if (m_width.committedWidth() && !m_width.fitsOnLine() && m_lineBreak.m_obj && m_currWS == NOWRAP) {
@@ -3281,7 +3255,7 @@
     }
 }
 
-InlineIterator LineBreaker::BreakingContext::handleEndOfLine()
+InlineIterator BreakingContext::handleEndOfLine()
 {
     ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo();
     bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments();
@@ -3388,7 +3362,7 @@
     }
 }
 
-void RenderBlock::deleteEllipsisLineBoxes()
+void RenderBlockFlow::deleteEllipsisLineBoxes()
 {
     ETextAlign textAlign = style()->textAlign();
     bool ltr = style()->isLeftToRightDirection();
@@ -3412,7 +3386,7 @@
     }
 }
 
-void RenderBlock::checkLinesForTextOverflow()
+void RenderBlockFlow::checkLinesForTextOverflow()
 {
     // Determine the width of the ellipsis using the current font.
     // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
@@ -3459,7 +3433,7 @@
     }
 }
 
-bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo& lineInfo, LineWidth& width)
+bool RenderBlockFlow::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo& lineInfo, LineWidth& width)
 {
     if (!positionNewFloats())
         return false;
@@ -3475,7 +3449,7 @@
     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
     ASSERT(floatingObjectSet.last() == newFloat);
 
-    LayoutUnit floatLogicalTop = newFloat->logicalTop(isHorizontalWritingMode());
+    LayoutUnit floatLogicalTop = logicalTopForFloat(newFloat);
     int paginationStrut = newFloat->paginationStrut();
 
     if (floatLogicalTop - paginationStrut != logicalHeight() + lineInfo.floatPaginationStrut())
@@ -3486,23 +3460,23 @@
     FloatingObjectSetIterator begin = floatingObjectSet.begin();
     while (it != begin) {
         --it;
-        FloatingObject* f = *it;
-        if (f == lastFloatFromPreviousLine)
+        FloatingObject* floatingObject = *it;
+        if (floatingObject == lastFloatFromPreviousLine)
             break;
-        if (f->logicalTop(isHorizontalWritingMode()) == logicalHeight() + lineInfo.floatPaginationStrut()) {
-            f->setPaginationStrut(paginationStrut + f->paginationStrut());
-            RenderBox* o = f->renderer();
-            setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
-            if (o->isRenderBlock())
-                o->forceChildLayout();
+        if (logicalTopForFloat(floatingObject) == logicalHeight() + lineInfo.floatPaginationStrut()) {
+            floatingObject->setPaginationStrut(paginationStrut + floatingObject->paginationStrut());
+            RenderBox* floatBox = floatingObject->renderer();
+            setLogicalTopForChild(floatBox, logicalTopForChild(floatBox) + marginBeforeForChild(floatBox) + paginationStrut);
+            if (floatBox->isRenderBlock())
+                floatBox->forceChildLayout();
             else
-                o->layoutIfNeeded();
+                floatBox->layoutIfNeeded();
             // Save the old logical top before calling removePlacedObject which will set
             // isPlaced to false. Otherwise it will trigger an assert in logicalTopForFloat.
-            LayoutUnit oldLogicalTop = f->logicalTop(isHorizontalWritingMode());
-            m_floatingObjects->removePlacedObject(f);
-            f->setLogicalTop(oldLogicalTop + paginationStrut, isHorizontalWritingMode());
-            m_floatingObjects->addPlacedObject(f);
+            LayoutUnit oldLogicalTop = logicalTopForFloat(floatingObject);
+            m_floatingObjects->removePlacedObject(floatingObject);
+            setLogicalTopForFloat(floatingObject, oldLogicalTop + paginationStrut);
+            m_floatingObjects->addPlacedObject(floatingObject);
         }
     }
 
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index f9ff382..824260a 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -32,6 +32,7 @@
 #include "core/dom/Document.h"
 #include "core/editing/htmlediting.h"
 #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"
@@ -172,22 +173,18 @@
         return;
 
     if (isFloating()) {
-        RenderBlock* parentBlock = 0;
+        RenderBlockFlow* parentBlockFlow = 0;
         for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
-            if (curr->isRenderBlock()) {
-                RenderBlock* currBlock = toRenderBlock(curr);
-                if (!parentBlock || currBlock->containsFloat(this))
-                    parentBlock = currBlock;
+            if (curr->isRenderBlockFlow()) {
+                RenderBlockFlow* currBlockFlow = toRenderBlockFlow(curr);
+                if (!parentBlockFlow || currBlockFlow->containsFloat(this))
+                    parentBlockFlow = currBlockFlow;
             }
         }
 
-        if (parentBlock) {
-            RenderObject* parent = parentBlock->parent();
-            if (parent && parent->isFlexibleBoxIncludingDeprecated())
-                parentBlock = toRenderBlock(parent);
-
-            parentBlock->markSiblingsWithFloatsForLayout(this);
-            parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
+        if (parentBlockFlow) {
+            parentBlockFlow->markSiblingsWithFloatsForLayout(this);
+            parentBlockFlow->markAllDescendantsWithFloatsForLayout(this, false);
         }
     }
 
@@ -508,6 +505,85 @@
     layer()->scrollableArea()->scrollToOffset(offset, ScrollOffsetClamped);
 }
 
+static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView)
+{
+    // If scrollbars aren't explicitly forbidden, permit scrolling.
+    if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
+        return true;
+
+    // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
+    if (frameView->wasScrolledByUser())
+        return false;
+
+    // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
+    // like navigation to an anchor.
+    Page* page = frameView->frame().page();
+    if (!page)
+        return false;
+    return !page->autoscrollInProgress();
+}
+
+void RenderBox::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
+{
+    RenderBox* parentBox = 0;
+    LayoutRect newRect = rect;
+
+    bool restrictedByLineClamp = false;
+    if (parent()) {
+        parentBox = parent()->enclosingBox();
+        restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
+    }
+
+    if (hasOverflowClip() && !restrictedByLineClamp) {
+        // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
+        // This will prevent us from revealing text hidden by the slider in Safari RSS.
+        newRect = layer()->scrollableArea()->exposeRect(rect, alignX, alignY);
+    } else if (!parentBox && canBeProgramaticallyScrolled()) {
+        if (FrameView* frameView = this->frameView()) {
+            Element* ownerElement = document().ownerElement();
+
+            if (ownerElement && ownerElement->renderer()) {
+                HTMLFrameElementBase* frameElementBase = 0;
+
+                if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))
+                    frameElementBase = toHTMLFrameElementBase(ownerElement);
+
+                if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
+                    LayoutRect viewRect = frameView->visibleContentRect();
+                    LayoutRect exposeRect = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
+
+                    int xOffset = roundToInt(exposeRect.x());
+                    int yOffset = roundToInt(exposeRect.y());
+                    // Adjust offsets if they're outside of the allowable range.
+                    xOffset = max(0, min(frameView->contentsWidth(), xOffset));
+                    yOffset = max(0, min(frameView->contentsHeight(), yOffset));
+
+                    frameView->setScrollPosition(IntPoint(xOffset, yOffset));
+                    if (frameView->safeToPropagateScrollToParent()) {
+                        parentBox = ownerElement->renderer()->enclosingBox();
+                        // FIXME: This doesn't correctly convert the rect to
+                        // absolute coordinates in the parent.
+                        newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
+                        newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
+                    } else {
+                        parentBox = 0;
+                    }
+                }
+            } else {
+                LayoutRect viewRect = frameView->visibleContentRect();
+                LayoutRect r = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
+                frameView->setScrollPosition(roundedIntPoint(r.location()));
+            }
+        }
+    }
+
+    if (frame()->page()->autoscrollInProgress())
+        parentBox = enclosingScrollableBox();
+
+    if (parentBox)
+        parentBox->scrollRectToVisible(newRect, alignX, alignY);
+}
+
 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
 {
     rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
@@ -712,8 +788,8 @@
 
 bool RenderBox::scrollImpl(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
 {
-    RenderLayer* l = layer();
-    return l && l->scroll(direction, granularity, multiplier);
+    RenderLayer* layer = this->layer();
+    return layer && layer->scrollableArea() && layer->scrollableArea()->scroll(direction, granularity, multiplier);
 }
 
 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
@@ -774,13 +850,21 @@
 
 bool RenderBox::usesCompositedScrolling() const
 {
-    return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
+    return hasOverflowClip() && hasLayer() && layer()->scrollableArea()->usesCompositedScrolling();
 }
 
 void RenderBox::autoscroll(const IntPoint& position)
 {
-    if (layer())
-        layer()->autoscroll(position);
+    Frame* frame = this->frame();
+    if (!frame)
+        return;
+
+    FrameView* frameView = frame->view();
+    if (!frameView)
+        return;
+
+    IntPoint currentDocumentPosition = frameView->windowToContents(position);
+    scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
 }
 
 bool RenderBox::autoscrollInProgress() const
@@ -866,7 +950,7 @@
     if (!frame)
         return;
 
-    IntPoint lastKnownMousePosition = frame->eventHandler()->lastKnownMousePosition();
+    IntPoint lastKnownMousePosition = frame->eventHandler().lastKnownMousePosition();
 
     // We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
     static IntPoint previousMousePosition;
diff --git a/Source/core/rendering/RenderBox.h b/Source/core/rendering/RenderBox.h
index a9a6499..cf11d56 100644
--- a/Source/core/rendering/RenderBox.h
+++ b/Source/core/rendering/RenderBox.h
@@ -254,6 +254,7 @@
 
     void scrollToOffset(const IntSize&);
     void scrollByRecursively(const IntSize& delta, ScrollOffsetClamping = ScrollOffsetUnclamped);
+    void scrollRectToVisible(const LayoutRect&, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
 
     virtual LayoutUnit marginTop() const OVERRIDE { return m_marginBox.top(); }
     virtual LayoutUnit marginBottom() const OVERRIDE { return m_marginBox.bottom(); }
diff --git a/Source/core/rendering/RenderBoxModelObject.cpp b/Source/core/rendering/RenderBoxModelObject.cpp
index 05c4e20..072a4cf 100644
--- a/Source/core/rendering/RenderBoxModelObject.cpp
+++ b/Source/core/rendering/RenderBoxModelObject.cpp
@@ -30,7 +30,6 @@
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/page/Settings.h"
 #include "core/page/scrolling/ScrollingConstraints.h"
-#include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/Path.h"
 #include "core/rendering/CompositedLayerMapping.h"
@@ -43,7 +42,9 @@
 #include "core/rendering/RenderNamedFlowThread.h"
 #include "core/rendering/RenderRegion.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/style/ShadowList.h"
 #include "platform/geometry/TransformState.h"
+#include "platform/graphics/DrawLooper.h"
 #include "wtf/CurrentTime.h"
 
 using namespace std;
@@ -141,13 +142,6 @@
     layer()->compositedLayerMapping()->animationFinished(name);
 }
 
-void RenderBoxModelObject::suspendAnimations(double time)
-{
-    ASSERT(hasLayer());
-    ASSERT(compositingState() == PaintsIntoOwnBacking);
-    layer()->compositedLayerMapping()->suspendAnimations(time);
-}
-
 bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
 {
     return ImageQualityController::imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
@@ -511,13 +505,17 @@
 
 static void applyBoxShadowForBackground(GraphicsContext* context, const RenderObject* renderer)
 {
-    const ShadowData* boxShadow = renderer->style()->boxShadow();
-    while (boxShadow->style() != Normal)
-        boxShadow = boxShadow->next();
-
-    FloatSize shadowOffset(boxShadow->x(), boxShadow->y());
-    context->setShadow(shadowOffset, boxShadow->blur(), renderer->resolveColor(boxShadow->color()),
-        DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
+    const ShadowList* shadowList = renderer->style()->boxShadow();
+    ASSERT(shadowList);
+    for (size_t i = shadowList->shadows().size(); i--; ) {
+        const ShadowData& boxShadow = shadowList->shadows()[i];
+        if (boxShadow.style() != Normal)
+            continue;
+        FloatSize shadowOffset(boxShadow.x(), boxShadow.y());
+        context->setShadow(shadowOffset, boxShadow.blur(), renderer->resolveColor(boxShadow.color()),
+            DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
+        return;
+    }
 }
 
 void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
@@ -2428,16 +2426,22 @@
     if (style()->hasAppearance())
         return false;
 
+    const ShadowList* shadowList = style()->boxShadow();
+    if (!shadowList)
+        return false;
+
     bool hasOneNormalBoxShadow = false;
-    for (const ShadowData* currentShadow = style()->boxShadow(); currentShadow; currentShadow = currentShadow->next()) {
-        if (currentShadow->style() != Normal)
+    size_t shadowCount = shadowList->shadows().size();
+    for (size_t i = 0; i < shadowCount; ++i) {
+        const ShadowData& currentShadow = shadowList->shadows()[i];
+        if (currentShadow.style() != Normal)
             continue;
 
         if (hasOneNormalBoxShadow)
             return false;
         hasOneNormalBoxShadow = true;
 
-        if (currentShadow->spread())
+        if (currentShadow.spread())
             return false;
     }
 
@@ -2496,20 +2500,23 @@
     bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
 
     GraphicsContextStateSaver stateSaver(*context, false);
-    for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
-        if (shadow->style() != shadowStyle)
+
+    const ShadowList* shadowList = s->boxShadow();
+    for (size_t i = shadowList->shadows().size(); i--; ) {
+        const ShadowData& shadow = shadowList->shadows()[i];
+        if (shadow.style() != shadowStyle)
             continue;
 
-        IntSize shadowOffset(shadow->x(), shadow->y());
-        int shadowBlur = shadow->blur();
-        int shadowSpread = shadow->spread();
+        IntSize shadowOffset(shadow.x(), shadow.y());
+        int shadowBlur = shadow.blur();
+        int shadowSpread = shadow.spread();
 
         if (shadowOffset.isZero() && !shadowBlur && !shadowSpread)
             continue;
 
-        const Color& shadowColor = resolveColor(shadow->color());
+        const Color& shadowColor = resolveColor(shadow.color());
 
-        if (shadow->style() == Normal) {
+        if (shadow.style() == Normal) {
             RoundedRect fillRect = border;
             fillRect.inflate(shadowSpread);
             if (fillRect.isEmpty())
@@ -2824,7 +2831,8 @@
     if (fullRemoveInsert && isRenderBlock()) {
         RenderBlock* block = toRenderBlock(this);
         block->removePositionedObjects(0);
-        block->removeFloatingObjects();
+        if (block->isRenderBlockFlow())
+            toRenderBlockFlow(block)->removeFloatingObjects();
     }
 
     ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent());
diff --git a/Source/core/rendering/RenderBoxModelObject.h b/Source/core/rendering/RenderBoxModelObject.h
index 13dd300..169438c 100644
--- a/Source/core/rendering/RenderBoxModelObject.h
+++ b/Source/core/rendering/RenderBoxModelObject.h
@@ -188,8 +188,6 @@
     void animationPaused(double timeOffset, const String& name);
     void animationFinished(const String& name);
 
-    void suspendAnimations(double time = 0);
-
     virtual void computeLayerHitTestRects(LayerHitTestRects&) const OVERRIDE;
 
 protected:
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
index fc6368d..4ea2e8f 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
@@ -308,7 +308,7 @@
     // Update our scrollbars if we're overflow:auto/scroll/hidden now that we know if
     // we overflow or not.
     if (hasOverflowClip())
-        layer()->updateScrollInfoAfterLayout();
+        layer()->scrollableArea()->updateAfterLayout();
 
     // Repaint with our new bounds if they are different from our old bounds.
     repainter.repaintAfterLayout();
diff --git a/Source/core/rendering/RenderEmbeddedObject.cpp b/Source/core/rendering/RenderEmbeddedObject.cpp
index 52702f6..163b160 100644
--- a/Source/core/rendering/RenderEmbeddedObject.cpp
+++ b/Source/core/rendering/RenderEmbeddedObject.cpp
@@ -31,13 +31,13 @@
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
 #include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontSelector.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/Path.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
+#include "platform/fonts/FontSelector.h"
 #include "platform/graphics/TextRun.h"
 #include "platform/text/PlatformLocale.h"
 
diff --git a/Source/core/rendering/RenderFileUploadControl.cpp b/Source/core/rendering/RenderFileUploadControl.cpp
index 43b2c04..c1440e9 100644
--- a/Source/core/rendering/RenderFileUploadControl.cpp
+++ b/Source/core/rendering/RenderFileUploadControl.cpp
@@ -88,7 +88,6 @@
 
 int RenderFileUploadControl::maxFilenameWidth() const
 {
-    HTMLInputElement* input = toHTMLInputElement(node());
     return max(0, contentBoxRect().pixelSnappedWidth() - nodeWidth(uploadButton()) - afterButtonSpacing);
 }
 
@@ -120,7 +119,6 @@
         if (!button)
             return;
 
-        HTMLInputElement* input = toHTMLInputElement(node());
         LayoutUnit buttonWidth = nodeWidth(button);
         LayoutUnit buttonAndSpacingWidth = buttonWidth + afterButtonSpacing;
         float textWidth = font.width(textRun);
diff --git a/Source/core/rendering/RenderFlowThread.cpp b/Source/core/rendering/RenderFlowThread.cpp
index 07f859e..fc3024f 100644
--- a/Source/core/rendering/RenderFlowThread.cpp
+++ b/Source/core/rendering/RenderFlowThread.cpp
@@ -173,9 +173,9 @@
                 LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
                 LayoutUnit regionLogicalHeight = region->pageLogicalHeight();
 
-                if (!firstRegionVisited)
+                if (!firstRegionVisited) {
                     firstRegionVisited = true;
-                else {
+                } else {
                     if (m_regionsHaveUniformLogicalWidth && previousRegionLogicalWidth != regionLogicalWidth)
                         m_regionsHaveUniformLogicalWidth = false;
                     if (m_regionsHaveUniformLogicalHeight && previousRegionLogicalHeight != regionLogicalHeight)
@@ -282,8 +282,9 @@
         LayoutRect flippedFlowThreadPortionRect(flowThreadPortionRect);
         flipForWritingMode(flippedFlowThreadPortionRect);
         portionLocation = flippedFlowThreadPortionRect.location();
-    } else
+    } 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.
@@ -303,7 +304,10 @@
         context->translate(adjustedPaintOffset.x(), adjustedPaintOffset.y());
         info.rect.moveBy(-adjustedPaintOffset);
 
-        layer()->paint(context, info.rect, 0, 0, region, RenderLayer::PaintLayerTemporaryClipRects);
+        if (info.phase == PaintPhaseTextClip)
+            info.paintBehavior = PaintBehaviorForceBlackText;
+
+        layer()->paint(context, info.rect, info.paintBehavior, 0, region, PaintLayerTemporaryClipRects);
 
         context->restore();
     }
@@ -327,8 +331,9 @@
         LayoutRect flippedFlowThreadPortionRect(flowThreadPortionRect);
         flipForWritingMode(flippedFlowThreadPortionRect);
         renderFlowThreadOffset = accumulatedOffset - flippedFlowThreadPortionRect.location();
-    } else
+    } 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::DisallowShadowContent);
@@ -440,9 +445,9 @@
 
             // Get the logical top coordinate of the current object.
             LayoutUnit top = 0;
-            if (boxModelObject.isRenderBlock())
+            if (boxModelObject.isRenderBlock()) {
                 top = toRenderBlock(&boxModelObject)->offsetFromLogicalTopOfFirstPage();
-            else {
+            } else {
                 if (boxModelObject.containingBlock())
                     top = boxModelObject.containingBlock()->offsetFromLogicalTopOfFirstPage();
 
@@ -944,8 +949,9 @@
         region->setComputedAutoHeight(regionComputedAutoHeight);
 
         currentRegionOffsetInFlowThread += regionComputedAutoHeight;
-    } else
+    } 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.
diff --git a/Source/core/rendering/RenderFrameSet.cpp b/Source/core/rendering/RenderFrameSet.cpp
index aac0a4a..8456c7c 100644
--- a/Source/core/rendering/RenderFrameSet.cpp
+++ b/Source/core/rendering/RenderFrameSet.cpp
@@ -594,7 +594,7 @@
             toRenderFrameSet(ancestor)->m_isChildResizing = isResizing;
     }
     if (Frame* frame = this->frame())
-        frame->eventHandler()->setResizingFrameSet(isResizing ? frameSet() : 0);
+        frame->eventHandler().setResizingFrameSet(isResizing ? frameSet() : 0);
 }
 
 bool RenderFrameSet::isResizingRow() const
diff --git a/Source/core/rendering/RenderGrid.cpp b/Source/core/rendering/RenderGrid.cpp
index 2cce825..77d1833 100644
--- a/Source/core/rendering/RenderGrid.cpp
+++ b/Source/core/rendering/RenderGrid.cpp
@@ -291,7 +291,7 @@
     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
     // we overflow or not.
     if (hasOverflowClip())
-        layer()->updateScrollInfoAfterLayout();
+        layer()->scrollableArea()->updateAfterLayout();
 
     repainter.repaintAfterLayout();
 
@@ -1076,9 +1076,10 @@
 {
     // The grid line inequality needs to be strict (which doesn't match the after / end case) because |resolvedOppositePosition|
     // is already converted to an index in our grid representation (ie one was removed from the grid line to account for the side).
-    // FIXME: This could be a binary search as |gridLines| is ordered.
-    int firstLineBeforeOppositePositionIndex = gridLines.size() - 1;
-    for (; firstLineBeforeOppositePositionIndex >= 0 && gridLines[firstLineBeforeOppositePositionIndex] > resolvedOppositePosition; --firstLineBeforeOppositePositionIndex) { }
+    size_t firstLineBeforeOppositePositionIndex = 0;
+    const size_t* firstLineBeforeOppositePosition = std::lower_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
+    if (firstLineBeforeOppositePosition != gridLines.end())
+        firstLineBeforeOppositePositionIndex = firstLineBeforeOppositePosition - gridLines.begin();
 
     size_t gridLineIndex = std::max<int>(0, firstLineBeforeOppositePositionIndex - position.spanPosition() + 1);
     size_t resolvedGridLinePosition = gridLines[gridLineIndex];
@@ -1089,9 +1090,10 @@
 
 PassOwnPtr<GridSpan> RenderGrid::resolveAfterEndNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
 {
-    // FIXME: This could be a binary search as |gridLines| is ordered.
-    size_t firstLineAfterOppositePositionIndex = 0;
-    for (; firstLineAfterOppositePositionIndex < gridLines.size() && gridLines[firstLineAfterOppositePositionIndex] <= resolvedOppositePosition; ++firstLineAfterOppositePositionIndex) { }
+    size_t firstLineAfterOppositePositionIndex = gridLines.size() - 1;
+    const size_t* firstLineAfterOppositePosition = std::upper_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
+    if (firstLineAfterOppositePosition != gridLines.end())
+        firstLineAfterOppositePositionIndex = firstLineAfterOppositePosition - gridLines.begin();
 
     size_t gridLineIndex = std::min(gridLines.size() - 1, firstLineAfterOppositePositionIndex + position.spanPosition() - 1);
     size_t resolvedGridLinePosition = adjustGridPositionForAfterEndSide(gridLines[gridLineIndex]);
diff --git a/Source/core/rendering/RenderGrid.h b/Source/core/rendering/RenderGrid.h
index d1f4adf..63db98b 100644
--- a/Source/core/rendering/RenderGrid.h
+++ b/Source/core/rendering/RenderGrid.h
@@ -31,8 +31,8 @@
 
 namespace WebCore {
 
-class GridCoordinate;
-class GridSpan;
+struct GridCoordinate;
+struct GridSpan;
 class GridTrack;
 
 enum GridPositionSide {
@@ -70,7 +70,7 @@
     bool namedGridLinesDefinitionDidChange(const RenderStyle*) const;
 
     class GridIterator;
-    class GridSizingData;
+    struct GridSizingData;
     enum TrackSizingDirection { ForColumns, ForRows };
     void computedUsedBreadthOfGridTracks(TrackSizingDirection, GridSizingData&);
     void computedUsedBreadthOfGridTracks(TrackSizingDirection, GridSizingData&, LayoutUnit& availableLogicalSpace);
diff --git a/Source/core/rendering/RenderImage.cpp b/Source/core/rendering/RenderImage.cpp
index 70479a8..c629a2a 100644
--- a/Source/core/rendering/RenderImage.cpp
+++ b/Source/core/rendering/RenderImage.cpp
@@ -37,7 +37,6 @@
 #include "core/html/HTMLMapElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/GraphicsContext.h"
@@ -164,6 +163,11 @@
     if (newImage != m_imageResource->imagePtr())
         return;
 
+    // Per the spec, we let the server-sent header override srcset/other sources of dpr.
+    // https://github.com/igrigorik/http-client-hints/blob/master/draft-grigorik-http-client-hints-01.txt#L255
+    if (m_imageResource->cachedImage() && m_imageResource->cachedImage()->hasDevicePixelRatioHeaderValue())
+        m_imageDevicePixelRatio = 1 / m_imageResource->cachedImage()->devicePixelRatioHeaderValue();
+
     if (!m_didIncrementVisuallyNonEmptyPixelCount) {
         // At a zoom level of 1 the image is guaranteed to have an integer size.
         view()->frameView()->incrementVisuallyNonEmptyPixelCount(flooredIntSize(m_imageResource->imageSize(1.0f)));
@@ -303,10 +307,6 @@
 
     GraphicsContext* context = paintInfo.context;
 
-    Page* page = 0;
-    if (Frame* frame = this->frame())
-        page = frame->page();
-
     if (!m_imageResource->hasImage() || m_imageResource->errorOccurred()) {
         if (paintInfo.phase == PaintPhaseSelection)
             return;
diff --git a/Source/core/rendering/RenderInline.cpp b/Source/core/rendering/RenderInline.cpp
index e4944c2..b5a16d6 100644
--- a/Source/core/rendering/RenderInline.cpp
+++ b/Source/core/rendering/RenderInline.cpp
@@ -439,7 +439,8 @@
         // We can reuse this block and make it the preBlock of the next continuation.
         pre = block;
         pre->removePositionedObjects(0);
-        pre->removeFloatingObjects();
+        if (pre->isRenderBlockFlow())
+            toRenderBlockFlow(pre)->removeFloatingObjects();
         block = block->containingBlock();
     } else {
         // No anonymous block available for use.  Make one.
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index 6df81bb..1cacda4 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -52,15 +52,12 @@
 #include "core/dom/Document.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLFrameElement.h"
-#include "core/html/HTMLFrameOwnerElement.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/page/UseCounter.h"
 #include "core/frame/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/HistogramSupport.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/filters/ReferenceFilter.h"
 #include "core/platform/graphics/filters/SourceGraphic.h"
@@ -68,18 +65,18 @@
 #include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
 #include "core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
 #include "core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
 #include "core/rendering/ColumnInfo.h"
 #include "core/rendering/CompositedLayerMapping.h"
 #include "core/rendering/FilterEffectRenderer.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/HitTestingTransformState.h"
+#include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderLayerStackingNodeIterator.h"
 #include "core/rendering/RenderReplica.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderScrollbarPart.h"
@@ -92,13 +89,14 @@
 #include "platform/TraceEvent.h"
 #include "platform/geometry/FloatPoint3D.h"
 #include "platform/geometry/FloatRect.h"
+#include "platform/transforms/ScaleTransformOperation.h"
 #include "platform/transforms/TransformationMatrix.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+#include "public/platform/Platform.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/UnusedParam.h"
 #include "wtf/text/CString.h"
 
-#define MIN_INTERSECT_FOR_REVEAL 32
-
 using namespace std;
 
 namespace WebCore {
@@ -113,17 +111,15 @@
     , m_hasUnclippedDescendant(false)
     , m_isUnclippedDescendant(false)
     , m_needsCompositedScrolling(false)
-    , m_willUseCompositedScrollingHasBeenRecorded(false)
-    , m_isScrollableAreaHasBeenRecorded(false)
     , m_isRootLayer(renderer->isRenderView())
     , m_usedTransparency(false)
     , m_childLayerHasBlendMode(false)
     , m_childLayerHasBlendModeStatusDirty(false)
-    , m_paintingInsideReflection(false)
     , m_visibleContentStatusDirty(true)
     , m_hasVisibleContent(false)
     , m_visibleDescendantStatusDirty(false)
     , m_hasVisibleDescendant(false)
+    , m_hasVisibleNonLayerContent(false)
     , m_isPaginated(false)
     , m_3DTransformedDescendantStatusDirty(true)
     , m_has3DTransformedDescendant(false)
@@ -139,7 +135,6 @@
     , m_last(0)
     , m_staticInlinePosition(0)
     , m_staticBlockPosition(0)
-    , m_reflection(0)
     , m_enclosingPaginationLayer(0)
     , m_forceNeedsCompositedScrolling(DoNotForceCompositedScrolling)
     , m_repainter(renderer)
@@ -167,9 +162,6 @@
             scrollingCoordinator->willDestroyRenderLayer(this);
     }
 
-    if (m_reflection)
-        removeReflection();
-
     removeFilterInfoIfNeeded();
 
     // Child layers will be deleted by their corresponding render objects, so
@@ -180,10 +172,9 @@
 
 String RenderLayer::debugName() const
 {
-    String name = renderer()->debugName();
-    if (!isReflection())
-        return name;
-    return name + " (reflection)";
+    if (isReflection())
+        return m_reflectionInfo->debugName();
+    return renderer()->debugName();
 }
 
 RenderLayerCompositor* RenderLayer::compositor() const
@@ -280,7 +271,7 @@
             // as canUseConvertToLayerCoords may be true for an ancestor layer.
             convertToLayerCoords(root(), offsetFromRoot);
         }
-        positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
+        scrollableArea()->positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
     }
 
     updateDescendantDependentFlags();
@@ -295,8 +286,8 @@
     repainter().repaintAfterLayout(geometryMap, flags & CheckForRepaint);
 
     // Go ahead and update the reflection's position and size.
-    if (m_reflection)
-        m_reflection->layout();
+    if (m_reflectionInfo)
+        m_reflectionInfo->reflection()->layout();
 
     // Clear the IsCompositingUpdateRoot flag once we've found the first compositing layer in this update.
     bool isUpdateRoot = (flags & IsCompositingUpdateRoot);
@@ -527,20 +518,6 @@
         geometryMap->popMappingsToAncestor(parent());
 }
 
-void RenderLayer::positionNewlyCreatedOverflowControls()
-{
-    if (!compositedLayerMapping()->hasUnpositionedOverflowControlsLayers())
-        return;
-
-    RenderGeometryMap geometryMap(UseTransforms);
-    RenderView* view = renderer()->view();
-    if (this != view->layer() && parent())
-        geometryMap.pushMappingsToAncestor(parent(), 0);
-
-    LayoutPoint offsetFromRoot = LayoutPoint(geometryMap.absolutePoint(FloatPoint()));
-    positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
-}
-
 bool RenderLayer::hasBlendMode() const
 {
     return RuntimeEnabledFeatures::cssCompositingEnabled() && renderer()->hasBlendMode();
@@ -719,13 +696,13 @@
     }
 
     // If we're not normal flow, then we need to look for a multi-column object between us and our stacking container.
-    RenderLayer* ancestorStackingContainerLayer = this->ancestorStackingContainerLayer();
+    RenderLayerStackingNode* ancestorStackingContainerNode = m_stackingNode->ancestorStackingContainerNode();
     for (RenderLayer* curr = parent(); curr; curr = curr->parent()) {
         if (curr->renderer()->hasColumns()) {
             m_isPaginated = checkContainingBlockChainForPagination(renderer(), curr->renderBox());
             return;
         }
-        if (curr == ancestorStackingContainerLayer)
+        if (curr->stackingNode() == ancestorStackingContainerNode)
             return;
     }
 }
@@ -744,9 +721,9 @@
         // We don't collect invisible layers in z-order lists if we are not in compositing mode.
         // As we became visible, we need to dirty our stacking containers ancestors to be properly
         // collected. FIXME: When compositing, we could skip this dirtying phase.
-        for (RenderLayer* sc = ancestorStackingContainerLayer(); sc; sc = sc->ancestorStackingContainerLayer()) {
-            sc->stackingNode()->dirtyZOrderLists();
-            if (sc->hasVisibleContent())
+        for (RenderLayerStackingNode* sc = m_stackingNode->ancestorStackingContainerNode(); sc; sc = sc->ancestorStackingContainerNode()) {
+            sc->dirtyZOrderLists();
+            if (sc->layer()->hasVisibleContent())
                 break;
         }
     }
@@ -837,6 +814,20 @@
     }
 }
 
+// FIXME: this is quite brute-force. We could be more efficient if we were to
+// track state and update it as appropriate as changes are made in the RenderObject tree.
+void RenderLayer::updateHasVisibleNonLayerContent()
+{
+    TRACE_EVENT0("blink_rendering", "RenderLayer::updateHasVisibleNonLayerContent");
+    m_hasVisibleNonLayerContent = false;
+    for (RenderObject* r = renderer()->firstChild(); r; r = r->nextSibling()) {
+        if (!r->hasLayer()) {
+            m_hasVisibleNonLayerContent = true;
+            break;
+        }
+    }
+}
+
 static bool subtreeContainsOutOfFlowPositionedLayer(const RenderLayer* subtreeRoot)
 {
     return (subtreeRoot->renderer() && subtreeRoot->renderer()->isOutOfFlowPositioned()) || subtreeRoot->hasOutOfFlowPositionedDescendant();
@@ -916,15 +907,17 @@
 
 void RenderLayer::dirty3DTransformedDescendantStatus()
 {
-    RenderLayer* curr = ancestorStackingContainerLayer();
-    if (curr)
-        curr->m_3DTransformedDescendantStatusDirty = true;
+    RenderLayerStackingNode* stackingNode = m_stackingNode->ancestorStackingContainerNode();
+    if (!stackingNode)
+        return;
+
+    stackingNode->layer()->m_3DTransformedDescendantStatusDirty = true;
 
     // This propagates up through preserve-3d hierarchies to the enclosing flattening layer.
     // Note that preserves3D() creates stacking context, so we can just run up the stacking containers.
-    while (curr && curr->preserves3D()) {
-        curr->m_3DTransformedDescendantStatusDirty = true;
-        curr = curr->ancestorStackingContainerLayer();
+    while (stackingNode && stackingNode->layer()->preserves3D()) {
+        stackingNode->layer()->m_3DTransformedDescendantStatusDirty = true;
+        stackingNode = stackingNode->ancestorStackingContainerNode();
     }
 }
 
@@ -938,16 +931,9 @@
 
         // Transformed or preserve-3d descendants can only be in the z-order lists, not
         // in the normal flow list, so we only need to check those.
-        if (Vector<RenderLayer*>* positiveZOrderList = m_stackingNode->posZOrderList()) {
-            for (unsigned i = 0; i < positiveZOrderList->size(); ++i)
-                m_has3DTransformedDescendant |= positiveZOrderList->at(i)->update3DTransformedDescendantStatus();
-        }
-
-        // Now check our negative z-index children.
-        if (Vector<RenderLayer*>* negativeZOrderList = m_stackingNode->negZOrderList()) {
-            for (unsigned i = 0; i < negativeZOrderList->size(); ++i)
-                m_has3DTransformedDescendant |= negativeZOrderList->at(i)->update3DTransformedDescendantStatus();
-        }
+        RenderLayerStackingNodeIterator iterator(*m_stackingNode.get(), PositiveZOrderChildren | NegativeZOrderChildren);
+        while (RenderLayerStackingNode* node = iterator.next())
+            m_has3DTransformedDescendant |= node->layer()->update3DTransformedDescendantStatus();
 
         m_3DTransformedDescendantStatusDirty = false;
     }
@@ -1087,32 +1073,6 @@
                       floatValueForLength(style->perspectiveOriginY(), borderBox.height()));
 }
 
-RenderLayer* RenderLayer::ancestorStackingContainerLayer() const
-{
-    RenderLayer* ancestor = parent();
-    while (ancestor && !ancestor->stackingNode()->isStackingContainer())
-        ancestor = ancestor->parent();
-    return ancestor;
-}
-
-RenderLayerStackingNode* RenderLayer::ancestorStackingContainerNode() const
-{
-    RenderLayer* ancestor = ancestorStackingContainerLayer();
-    if (ancestor)
-        return ancestor->stackingNode();
-    return 0;
-}
-
-RenderLayerStackingNode* RenderLayer::ancestorStackingNode() const
-{
-    RenderLayer* ancestor = parent();
-    while (ancestor && !ancestor->stackingNode()->isStackingContext())
-        ancestor = ancestor->parent();
-    if (ancestor)
-        return ancestor->stackingNode();
-    return 0;
-}
-
 static inline bool isFixedPositionedContainer(RenderLayer* layer)
 {
     return layer->isRootLayer() || layer->hasTransform();
@@ -1146,7 +1106,7 @@
 
 static inline const RenderLayer* compositingContainer(const RenderLayer* layer)
 {
-    return layer->stackingNode()->isNormalFlowOnly() ? layer->parent() : layer->ancestorStackingContainerLayer();
+    return layer->stackingNode()->isNormalFlowOnly() ? layer->parent() : (layer->stackingNode()->ancestorStackingContainerNode() ? layer->stackingNode()->ancestorStackingContainerNode()->layer() : 0);
 }
 
 // FIXME: having two different functions named enclosingCompositingLayer and enclosingCompositingLayerForRepaint
@@ -1179,7 +1139,7 @@
     return 0;
 }
 
-RenderLayer* RenderLayer::ancestorScrollingLayer() const
+RenderLayer* RenderLayer::ancestorCompositedScrollingLayer() const
 {
     if (!acceleratedCompositingForOverflowScrollEnabled())
         return 0;
@@ -1196,6 +1156,20 @@
     return 0;
 }
 
+RenderLayer* RenderLayer::ancestorScrollingLayer() const
+{
+    RenderObject* containingBlock = renderer()->containingBlock();
+    if (!containingBlock)
+        return 0;
+
+    for (RenderLayer* ancestorLayer = containingBlock->enclosingLayer(); ancestorLayer; ancestorLayer = ancestorLayer->parent()) {
+        if (ancestorLayer->scrollsOverflow())
+            return ancestorLayer;
+    }
+
+    return 0;
+}
+
 RenderLayer* RenderLayer::enclosingFilterLayer(bool includeSelf) const
 {
     const RenderLayer* curr = includeSelf ? this : parent();
@@ -1241,7 +1215,7 @@
 
 bool RenderLayer::cannotBlitToWindow() const
 {
-    if (isTransparent() || hasReflection() || hasTransform())
+    if (isTransparent() || m_reflectionInfo || hasTransform())
         return true;
     if (!parent())
         return false;
@@ -1291,7 +1265,7 @@
         // Note: we don't have to walk z-order lists since transparent elements always establish
         // a stacking container. This means we can just walk the layer tree directly.
         for (RenderLayer* curr = layer->firstChild(); curr; curr = curr->nextSibling()) {
-            if (!layer->reflection() || layer->reflectionLayer() != curr)
+            if (!layer->reflectionInfo() || layer->reflectionInfo()->reflectionLayer() != curr)
                 clipRect.unite(transparencyClipBox(curr, rootLayer, transparencyBehavior, DescendantsOfTransparencyClipBox, paintBehavior));
         }
     }
@@ -1420,7 +1394,7 @@
         m_stackingNode->dirtyNormalFlowList();
 
     if (!child->stackingNode()->isNormalFlowOnly() || child->firstChild()) {
-        // Dirty the z-order list in which we are contained. The ancestorStackingContainerLayer() can be null in the
+        // Dirty the z-order list in which we are contained. The ancestorStackingContainerNode() can be null in the
         // case where we're building up generated content layers. This is ok, since the lists will start
         // off dirty in that case anyway.
         child->stackingNode()->dirtyStackingContainerZOrderLists();
@@ -1521,8 +1495,8 @@
 
     // Remove the child reflection layer before moving other child layers.
     // The reflection layer should not be moved to the parent.
-    if (reflection())
-        removeChild(reflectionLayer());
+    if (m_reflectionInfo)
+        removeChild(m_reflectionInfo->reflectionLayer());
 
     // Now walk our kids and reattach them to our parent.
     RenderLayer* current = m_first;
@@ -1549,7 +1523,7 @@
         // Find our enclosingLayer and add ourselves.
         RenderLayer* parentLayer = renderer()->parent()->enclosingLayer();
         ASSERT(parentLayer);
-        RenderLayer* beforeChild = parentLayer->reflectionLayer() != this ? renderer()->parent()->findNextLayer(parentLayer, renderer()) : 0;
+        RenderLayer* beforeChild = !parentLayer->reflectionInfo() || parentLayer->reflectionInfo()->reflectionLayer() != this ? renderer()->parent()->findNextLayer(parentLayer, renderer()) : 0;
         parentLayer->addChild(this, beforeChild);
     }
 
@@ -1703,17 +1677,6 @@
     rect.move(-delta.x(), -delta.y());
 }
 
-bool RenderLayer::usesCompositedScrolling() const
-{
-    RenderBox* box = renderBox();
-
-    // Scroll form controls on the main thread so they exhibit correct touch scroll event bubbling
-    if (box && (box->isIntristicallyScrollable(VerticalScrollbar) || box->isIntristicallyScrollable(HorizontalScrollbar)))
-        return false;
-
-    return compositedLayerMapping() && compositedLayerMapping()->scrollingLayer();
-}
-
 bool RenderLayer::adjustForForceCompositedScrollingMode(bool value) const
 {
     switch (m_forceNeedsCompositedScrolling) {
@@ -1756,7 +1719,7 @@
     // our scrolling ancestor, and we will therefore not scroll with it. In this case, we must
     // be a composited layer since the compositor will need to take special measures to ensure
     // that we scroll with our scrolling ancestor and it cannot do this if we do not promote.
-    RenderLayer* scrollParent = ancestorScrollingLayer();
+    RenderLayer* scrollParent = ancestorCompositedScrollingLayer();
 
     if (!scrollParent || scrollParent->stackingNode()->isStackingContainer())
         return 0;
@@ -1784,59 +1747,6 @@
     return clipParent;
 }
 
-void RenderLayer::updateNeedsCompositedScrolling()
-{
-    TRACE_EVENT0("comp-scroll", "RenderLayer::updateNeedsCompositedScrolling");
-
-    m_stackingNode->updateDescendantsAreContiguousInStackingOrder();
-    updateDescendantDependentFlags();
-
-    ASSERT(scrollsOverflow());
-    const bool needsToBeStackingContainer = acceleratedCompositingForOverflowScrollEnabled()
-        && m_stackingNode->descendantsAreContiguousInStackingOrder()
-        && !hasUnclippedDescendant();
-
-    const bool needsToBeStackingContainerDidChange = m_stackingNode->setNeedsToBeStackingContainer(needsToBeStackingContainer);
-
-    const bool needsCompositedScrolling = needsToBeStackingContainer
-        || 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 (acceleratedCompositingForOverflowScrollEnabled())
-        HistogramSupport::histogramEnumeration("Renderer.NeedsCompositedScrolling", needsCompositedScrolling, 2);
-
-    const bool needsCompositedScrollingDidChange = setNeedsCompositedScrolling(needsCompositedScrolling);
-
-    if (needsToBeStackingContainerDidChange || needsCompositedScrollingDidChange) {
-        // Note, the z-order lists may need to be rebuilt, but our code guarantees
-        // that we have not affected stacking, so we will not dirty
-        // m_descendantsAreContiguousInStackingOrder for either us or our stacking
-        // context or container.
-        didUpdateNeedsCompositedScrolling();
-    }
-}
-
-bool RenderLayer::setNeedsCompositedScrolling(bool needsCompositedScrolling)
-{
-    if (m_needsCompositedScrolling == needsCompositedScrolling)
-        return false;
-
-    // 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 (acceleratedCompositingForOverflowScrollEnabled() && !m_willUseCompositedScrollingHasBeenRecorded) {
-        HistogramSupport::histogramEnumeration("Renderer.CompositedScrolling", WillUseCompositedScrollingBucket, CompositedScrollingHistogramMax);
-        m_willUseCompositedScrollingHasBeenRecorded = true;
-    }
-
-    m_needsCompositedScrolling = needsCompositedScrolling;
-
-    return true;
-}
-
 void RenderLayer::setForceNeedsCompositedScrolling(RenderLayer::ForceNeedsCompositedScrollingMode mode)
 {
     if (m_forceNeedsCompositedScrolling == mode)
@@ -1862,108 +1772,14 @@
     compositor()->setCompositingLayersNeedRebuild();
 }
 
-static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView)
+void RenderLayer::updateReflectionInfo(const RenderStyle* oldStyle)
 {
-    // If scrollbars aren't explicitly forbidden, permit scrolling.
-    if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
-        return true;
-
-    // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
-    if (frameView->wasScrolledByUser())
-        return false;
-
-    // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
-    // like navigation to an anchor.
-    Page* page = frameView->frame().page();
-    if (!page)
-        return false;
-    return !page->autoscrollInProgress();
-}
-
-void RenderLayer::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
-{
-    RenderLayer* parentLayer = 0;
-    LayoutRect newRect = rect;
-
-    bool restrictedByLineClamp = false;
-    if (renderer()->parent()) {
-        parentLayer = renderer()->parent()->enclosingLayer();
-        restrictedByLineClamp = !renderer()->parent()->style()->lineClamp().isNone();
-    }
-
-    if (renderer()->hasOverflowClip() && !restrictedByLineClamp) {
-        // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
-        // This will prevent us from revealing text hidden by the slider in Safari RSS.
-        RenderBox* box = renderBox();
-        ASSERT(box);
-        LayoutRect localExposeRect(box->absoluteToLocalQuad(FloatQuad(FloatRect(rect)), UseTransforms).boundingBox());
-        LayoutRect layerBounds(0, 0, box->clientWidth(), box->clientHeight());
-        LayoutRect r = getRectToExpose(layerBounds, localExposeRect, alignX, alignY);
-
-        IntSize clampedScrollOffset = scrollableArea()->clampScrollOffset(scrollableArea()->adjustedScrollOffset() + toIntSize(roundedIntRect(r).location()));
-        if (clampedScrollOffset != scrollableArea()->adjustedScrollOffset()) {
-            IntSize oldScrollOffset = scrollableArea()->adjustedScrollOffset();
-            m_scrollableArea->scrollToOffset(clampedScrollOffset);
-            IntSize scrollOffsetDifference = scrollableArea()->adjustedScrollOffset() - oldScrollOffset;
-            localExposeRect.move(-scrollOffsetDifference);
-            newRect = LayoutRect(box->localToAbsoluteQuad(FloatQuad(FloatRect(localExposeRect)), UseTransforms).boundingBox());
-        }
-    } else if (!parentLayer && renderer()->isBox() && renderBox()->canBeProgramaticallyScrolled()) {
-        if (FrameView* frameView = renderer()->frameView()) {
-            Element* ownerElement = renderer()->document().ownerElement();
-
-            if (ownerElement && ownerElement->renderer()) {
-                HTMLFrameElementBase* frameElementBase = 0;
-
-                if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))
-                    frameElementBase = toHTMLFrameElementBase(ownerElement);
-
-                if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
-                    LayoutRect viewRect = frameView->visibleContentRect();
-                    LayoutRect exposeRect = getRectToExpose(viewRect, rect, alignX, alignY);
-
-                    int xOffset = roundToInt(exposeRect.x());
-                    int yOffset = roundToInt(exposeRect.y());
-                    // Adjust offsets if they're outside of the allowable range.
-                    xOffset = max(0, min(frameView->contentsWidth(), xOffset));
-                    yOffset = max(0, min(frameView->contentsHeight(), yOffset));
-
-                    frameView->setScrollPosition(IntPoint(xOffset, yOffset));
-                    if (frameView->safeToPropagateScrollToParent()) {
-                        parentLayer = ownerElement->renderer()->enclosingLayer();
-                        // FIXME: This doesn't correctly convert the rect to
-                        // absolute coordinates in the parent.
-                        newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
-                        newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
-                    } else
-                        parentLayer = 0;
-                }
-            } else {
-                LayoutRect viewRect = frameView->visibleContentRect();
-                LayoutRect r = getRectToExpose(viewRect, rect, alignX, alignY);
-                frameView->setScrollPosition(roundedIntPoint(r.location()));
-            }
-        }
-    }
-
-    if (renderer()->frame()->page()->autoscrollInProgress())
-        parentLayer = enclosingScrollableLayer();
-
-    if (parentLayer)
-        parentLayer->scrollRectToVisible(newRect, alignX, alignY);
-}
-
-void RenderLayer::updateCompositingLayersAfterScroll()
-{
-    if (compositor()->inCompositingMode()) {
-        // Our stacking container is guaranteed to contain all of our descendants that may need
-        // repositioning, so update compositing layers from there.
-        if (RenderLayer* compositingAncestor = ancestorStackingContainerLayer()->enclosingCompositingLayer()) {
-            if (usesCompositedScrolling())
-                compositor()->updateCompositingLayers(CompositingUpdateOnCompositedScroll, compositingAncestor);
-            else
-                compositor()->updateCompositingLayers(CompositingUpdateOnScroll, compositingAncestor);
-        }
+    if (renderer()->hasReflection()) {
+        if (!m_reflectionInfo)
+            m_reflectionInfo = adoptPtr(new RenderLayerReflectionInfo(toRenderBox(renderer())));
+        m_reflectionInfo->updateAfterStyleChange(oldStyle);
+    } else if (m_reflectionInfo) {
+        m_reflectionInfo = nullptr;
     }
 }
 
@@ -1983,121 +1799,11 @@
         m_scrollableArea = nullptr;
 }
 
-LayoutRect RenderLayer::getRectToExpose(const LayoutRect &visibleRect, const LayoutRect &exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
+PassOwnPtr<Vector<FloatRect> > RenderLayer::collectTrackedRepaintRects() const
 {
-    // Determine the appropriate X behavior.
-    ScrollBehavior 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)
-        // If the rectangle is fully visible, use the specified visible behavior.
-        // If the rectangle is partially visible, but over a certain threshold,
-        // then treat it as fully visible to avoid unnecessary horizontal scrolling
-        scrollX = ScrollAlignment::getVisibleBehavior(alignX);
-    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 = ScrollAlignment::getVisibleBehavior(alignX);
-        if (scrollX == alignCenter)
-            scrollX = noScroll;
-    } else if (intersectWidth > 0)
-        // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
-        scrollX = ScrollAlignment::getPartialBehavior(alignX);
-    else
-        scrollX = ScrollAlignment::getHiddenBehavior(alignX);
-    if (scrollX == alignToClosestEdge) {
-        // 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;
-        }
-    }
-
-    // Given the X behavior, compute the X coordinate.
-    LayoutUnit x;
-    if (scrollX == noScroll)
-        x = visibleRect.x();
-    else if (scrollX == alignRight)
-        x = exposeRect.maxX() - visibleRect.width();
-    else if (scrollX == alignCenter)
-        x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
-    else
-        x = exposeRect.x();
-
-    // Determine the appropriate Y behavior.
-    ScrollBehavior scrollY;
-    LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
-    LayoutUnit intersectHeight = intersection(visibleRect, exposeRectY).height();
-    if (intersectHeight == exposeRect.height())
-        // If the rectangle is fully visible, use the specified visible behavior.
-        scrollY = ScrollAlignment::getVisibleBehavior(alignY);
-    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 = ScrollAlignment::getVisibleBehavior(alignY);
-        if (scrollY == alignCenter)
-            scrollY = noScroll;
-    } else if (intersectHeight > 0)
-        // If the rectangle is partially visible, use the specified partial behavior
-        scrollY = ScrollAlignment::getPartialBehavior(alignY);
-    else
-        scrollY = ScrollAlignment::getHiddenBehavior(alignY);
-    if (scrollY == alignToClosestEdge) {
-        // 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;
-        }
-    }
-
-    // Given the Y behavior, compute the Y coordinate.
-    LayoutUnit y;
-    if (scrollY == noScroll)
-        y = visibleRect.y();
-    else if (scrollY == alignBottom)
-        y = exposeRect.maxY() - visibleRect.height();
-    else if (scrollY == alignCenter)
-        y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
-    else
-        y = exposeRect.y();
-
-    return LayoutRect(LayoutPoint(x, y), visibleRect.size());
-}
-
-void RenderLayer::autoscroll(const IntPoint& position)
-{
-    Frame* frame = renderer()->frame();
-    if (!frame)
-        return;
-
-    FrameView* frameView = frame->view();
-    if (!frameView)
-        return;
-
-    IntPoint currentDocumentPosition = frameView->windowToContents(position);
-    scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
-}
-
-void RenderLayer::resize(const PlatformEvent& evt, const LayoutSize& oldOffset)
-{
-    m_scrollableArea->resize(evt, oldOffset);
-}
-
-bool RenderLayer::inResizeMode() const
-{
-    return m_scrollableArea->inResizeMode();
-}
-
-void RenderLayer::setInResizeMode(bool inResizeMode)
-{
-    return m_scrollableArea->setInResizeMode(inResizeMode);
-}
-
-IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
-{
-    return m_scrollableArea->offsetFromResizeCorner(absolutePoint);
+    if (CompositedLayerMapping* mapping = compositedLayerMapping())
+        return mapping->collectTrackedRepaintRects();
+    return nullptr;
 }
 
 bool RenderLayer::hasOverflowControls() const
@@ -2105,27 +1811,6 @@
     return m_scrollableArea && (m_scrollableArea->hasScrollbar() || m_scrollableArea->hasScrollCorner() || renderer()->style()->resize() != RESIZE_NONE);
 }
 
-void RenderLayer::updateScrollInfoAfterLayout()
-{
-    RenderBox* box = renderBox();
-    if (!box)
-        return;
-
-    m_scrollableArea->updateAfterLayout();
-
-    // Composited scrolling may need to be enabled or disabled if the amount of overflow changed.
-    if (renderer()->view() && compositor()->updateLayerCompositingState(this))
-        compositor()->setCompositingLayersNeedRebuild();
-}
-
-bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
-{
-    if (ScrollableArea* scrollableArea = this->scrollableArea())
-        return scrollableArea->scroll(direction, granularity, multiplier);
-
-    return false;
-}
-
 void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot, RenderRegion* region, PaintLayerFlags paintFlags)
 {
     OverlapTestRequestMap overlapTestRequests;
@@ -2228,9 +1913,9 @@
     return false;
 }
 
-static bool paintForFixedRootBackground(const RenderLayer* layer, RenderLayer::PaintLayerFlags paintFlags)
+static bool paintForFixedRootBackground(const RenderLayer* layer, PaintLayerFlags paintFlags)
 {
-    return layer->renderer()->isRoot() && (paintFlags & RenderLayer::PaintLayerPaintingRootBackgroundOnly);
+    return layer->renderer()->isRoot() && (paintFlags & PaintLayerPaintingRootBackgroundOnly);
 }
 
 void RenderLayer::paintLayer(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
@@ -2318,12 +2003,8 @@
     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
 
     // Paint the reflection first if we have one.
-    if (m_reflection && !m_paintingInsideReflection) {
-        // Mark that we are now inside replica painting.
-        m_paintingInsideReflection = true;
-        reflectionLayer()->paintLayer(context, paintingInfo, localPaintFlags | PaintLayerPaintingReflection);
-        m_paintingInsideReflection = false;
-    }
+    if (m_reflectionInfo)
+        m_reflectionInfo->paint(context, paintingInfo, localPaintFlags | PaintLayerPaintingReflection);
 
     localPaintFlags |= PaintLayerPaintingCompositingAllPhases;
     paintLayerContents(context, paintingInfo, localPaintFlags);
@@ -2409,7 +2090,8 @@
     }
 
     // Blending operations must be performed only with the nearest ancestor stacking context.
-    bool createTransparencyLayerForBlendMode = m_stackingNode->isStackingContext() && m_childLayerHasBlendMode;
+    // 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;
 
     if (createTransparencyLayerForBlendMode)
         beginTransparencyLayers(context, paintingInfo.rootLayer, paintingInfo.paintDirtyRect, paintingInfo.paintBehavior);
@@ -2473,7 +2155,7 @@
     bool shouldPaintNormalFlowAndPosZOrderLists = isPaintingCompositedForeground;
     bool shouldPaintOverlayScrollbars = isPaintingOverlayScrollbars;
     bool shouldPaintMask = (paintFlags & PaintLayerPaintingCompositingMaskPhase) && shouldPaintContent && renderer()->hasMask() && !selectionOnly;
-    bool shouldPaintClippingMask = (paintFlags & PaintLayerPaintingChildClippingMaskPhase) && renderer()->style()->hasBorderRadius() && shouldPaintContent && !selectionOnly;
+    bool shouldPaintClippingMask = (paintFlags & PaintLayerPaintingChildClippingMaskPhase) && shouldPaintContent && !selectionOnly;
 
     PaintBehavior paintBehavior = PaintBehaviorNormal;
     if (paintFlags & PaintLayerPaintingSkipRootBackground)
@@ -2534,7 +2216,7 @@
     }
 
     // End our transparency layer
-    if ((haveTransparency || hasBlendMode() || createTransparencyLayerForBlendMode) && m_usedTransparency && !m_paintingInsideReflection) {
+    if ((haveTransparency || hasBlendMode() || createTransparencyLayerForBlendMode) && m_usedTransparency && !(m_reflectionInfo && m_reflectionInfo->isPaintingInsideReflection())) {
         context->endLayer();
         context->restore();
         m_usedTransparency = false;
@@ -2569,7 +2251,7 @@
     paintLayerContentsAndReflection(context, transformedPaintingInfo, paintFlags);
 }
 
-void RenderLayer::paintList(Vector<RenderLayer*>* list, GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
+void RenderLayer::paintList(Vector<RenderLayerStackingNode*>* list, GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
 {
     if (!list)
         return;
@@ -2582,7 +2264,7 @@
 #endif
 
     for (size_t i = 0; i < list->size(); ++i) {
-        RenderLayer* childLayer = list->at(i);
+        RenderLayer* childLayer = list->at(i)->layer();
         if (!childLayer->isPaginated())
             childLayer->paintLayer(context, paintingInfo, paintFlags);
         else
@@ -2860,8 +2542,8 @@
     for (size_t i = 0; i < layerFragments.size(); ++i) {
         const LayerFragment& fragment = layerFragments.at(i);
         clipToRect(localPaintingInfo.rootLayer, context, localPaintingInfo.paintDirtyRect, fragment.backgroundRect);
-        paintOverflowControls(context, roundedIntPoint(toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation)),
-            pixelSnappedIntRect(fragment.backgroundRect.rect()), true);
+        if (RenderLayerScrollableArea* scrollableArea = this->scrollableArea())
+            scrollableArea->paintOverflowControls(context, roundedIntPoint(toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation)), pixelSnappedIntRect(fragment.backgroundRect.rect()), true);
         restoreClip(context, localPaintingInfo.paintDirtyRect, fragment.backgroundRect);
     }
 }
@@ -2870,11 +2552,11 @@
 {
     // We need to do multiple passes, breaking up our child layer into strips.
     Vector<RenderLayer*> columnLayers;
-    RenderLayer* ancestorLayer = m_stackingNode->isNormalFlowOnly() ? parent() : ancestorStackingContainerLayer();
+    RenderLayerStackingNode* ancestorNode = m_stackingNode->isNormalFlowOnly() ? parent()->stackingNode() : m_stackingNode->ancestorStackingContainerNode();
     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
             columnLayers.append(curr);
-        if (curr == ancestorLayer)
+        if (curr->stackingNode() == ancestorNode)
             break;
     }
 
@@ -3409,7 +3091,7 @@
     return true;
 }
 
-RenderLayer* RenderLayer::hitTestList(Vector<RenderLayer*>* list, RenderLayer* rootLayer,
+RenderLayer* RenderLayer::hitTestList(Vector<RenderLayerStackingNode*>* list, RenderLayer* rootLayer,
                                       const HitTestRequest& request, HitTestResult& result,
                                       const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation,
                                       const HitTestingTransformState* transformState,
@@ -3425,7 +3107,7 @@
 
     RenderLayer* resultLayer = 0;
     for (int i = list->size() - 1; i >= 0; --i) {
-        RenderLayer* childLayer = list->at(i);
+        RenderLayer* childLayer = list->at(i)->layer();
         RenderLayer* hitLayer = 0;
         HitTestResult tempResult(result.hitTestLocation());
         if (childLayer->isPaginated())
@@ -3454,11 +3136,11 @@
                                                      const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation, const HitTestingTransformState* transformState, double* zOffset)
 {
     Vector<RenderLayer*> columnLayers;
-    RenderLayer* ancestorLayer = m_stackingNode->isNormalFlowOnly() ? parent() : ancestorStackingContainerLayer();
+    RenderLayerStackingNode* ancestorNode = m_stackingNode->isNormalFlowOnly() ? parent()->stackingNode() : m_stackingNode->ancestorStackingContainerNode();
     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
             columnLayers.append(curr);
-        if (curr == ancestorLayer)
+        if (curr->stackingNode() == ancestorNode)
             break;
     }
 
@@ -3751,7 +3433,7 @@
     if (renderer()->hasOverflowClip()) {
         RenderBox* box = renderBox();
         rect.move(-box->scrolledContentOffset());
-        if (!usesCompositedScrolling())
+        if (!scrollableArea()->usesCompositedScrolling())
             rect.intersect(box->overflowClipRect(LayoutPoint(), 0)); // FIXME: Regions not accounted for.
     }
     if (renderer()->hasClip())
@@ -3760,6 +3442,11 @@
         renderer()->repaintRectangle(rect);
 }
 
+bool RenderLayer::hasBlockSelectionGapBounds() const
+{
+    return !m_blockSelectionGapsBounds.isEmpty();
+}
+
 bool RenderLayer::intersectsDamageRect(const LayoutRect& layerBounds, const LayoutRect& damageRect, const RenderLayer* rootLayer, const LayoutPoint* offsetFromRoot) const
 {
     // Always examine the canvas and the root.
@@ -3911,11 +3598,12 @@
     }
 
     LayoutRect unionBounds = boundingBoxRect;
+    bool shouldIncludeTransform = paintsWithTransform(PaintBehaviorNormal) || (transform() && flags & PretendLayerHasOwnBacking);
 
     if (flags & UseLocalClipRectIfPossible) {
         LayoutRect localClipRect = this->localClipRect();
         if (localClipRect != PaintInfo::infiniteRect()) {
-            if ((flags & IncludeSelfTransform) && paintsWithTransform(PaintBehaviorNormal))
+            if ((flags & IncludeSelfTransform) && shouldIncludeTransform)
                 localClipRect = transform()->mapRect(localClipRect);
 
             LayoutPoint ancestorRelOffset;
@@ -3930,9 +3618,10 @@
 
     const_cast<RenderLayer*>(this)->stackingNode()->updateLayerListsIfNeeded();
 
-    if (RenderLayer* reflection = reflectionLayer()) {
-        if (!reflection->compositedLayerMapping()) {
-            IntRect childUnionBounds = reflection->calculateLayerBounds(this, 0, descendantFlags);
+    if (m_reflectionInfo) {
+        RenderLayer* reflectionLayer = m_reflectionInfo->reflectionLayer();
+        if (!reflectionLayer->compositedLayerMapping()) {
+            IntRect childUnionBounds = reflectionLayer->calculateLayerBounds(this, 0, descendantFlags);
             unionBounds.unite(childUnionBounds);
         }
     }
@@ -3946,36 +3635,11 @@
     // FIXME: Descendants that are composited should not necessarily be skipped, if they don't paint into their own
     // separate backing. Instead, they ought to contribute to the bounds of the layer we're trying to compute.
     // This applies to all z-order lists below.
-    if (Vector<RenderLayer*>* negZOrderList = m_stackingNode->negZOrderList()) {
-        size_t listSize = negZOrderList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = negZOrderList->at(i);
-            if (flags & IncludeCompositedDescendants || !curLayer->compositedLayerMapping()) {
-                IntRect childUnionBounds = curLayer->calculateLayerBounds(this, 0, descendantFlags);
-                unionBounds.unite(childUnionBounds);
-            }
-        }
-    }
-
-    if (Vector<RenderLayer*>* posZOrderList = m_stackingNode->posZOrderList()) {
-        size_t listSize = posZOrderList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = posZOrderList->at(i);
-            if (flags & IncludeCompositedDescendants || !curLayer->compositedLayerMapping()) {
-                IntRect childUnionBounds = curLayer->calculateLayerBounds(this, 0, descendantFlags);
-                unionBounds.unite(childUnionBounds);
-            }
-        }
-    }
-
-    if (Vector<RenderLayer*>* normalFlowList = m_stackingNode->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = normalFlowList->at(i);
-            if (flags & IncludeCompositedDescendants || !curLayer->compositedLayerMapping()) {
-                IntRect curAbsBounds = curLayer->calculateLayerBounds(this, 0, descendantFlags);
-                unionBounds.unite(curAbsBounds);
-            }
+    RenderLayerStackingNodeIterator iterator(*m_stackingNode.get(), AllChildren);
+    while (RenderLayerStackingNode* node = iterator.next()) {
+        if (flags & IncludeCompositedDescendants || !node->layer()->compositedLayerMapping()) {
+            IntRect childUnionBounds = node->layer()->calculateLayerBounds(this, 0, descendantFlags);
+            unionBounds.unite(childUnionBounds);
         }
     }
 
@@ -3985,7 +3649,7 @@
     if (flags & IncludeLayerFilterOutsets)
         renderer->style()->filterOutsets().expandRect(unionBounds);
 
-    if ((flags & IncludeSelfTransform) && paintsWithTransform(PaintBehaviorNormal)) {
+    if ((flags & IncludeSelfTransform) && shouldIncludeTransform) {
         TransformationMatrix* affineTrans = transform();
         boundingBoxRect = affineTrans->mapRect(boundingBoxRect);
         unionBounds = affineTrans->mapRect(unionBounds);
@@ -4096,13 +3760,13 @@
         || listBackgroundIsKnownToBeOpaqueInRect(m_stackingNode->normalFlowList(), localRect);
 }
 
-bool RenderLayer::listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayer*>* list, const LayoutRect& localRect) const
+bool RenderLayer::listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayerStackingNode*>* list, const LayoutRect& localRect) const
 {
     if (!list || list->isEmpty())
         return false;
 
-    for (Vector<RenderLayer*>::const_reverse_iterator iter = list->rbegin(); iter != list->rend(); ++iter) {
-        const RenderLayer* childLayer = *iter;
+    for (Vector<RenderLayerStackingNode*>::const_reverse_iterator iter = list->rbegin(); iter != list->rend(); ++iter) {
+        const RenderLayer* childLayer = (*iter)->layer();
         if (childLayer->compositedLayerMapping())
             continue;
 
@@ -4276,7 +3940,7 @@
 inline bool RenderLayer::needsCompositingLayersRebuiltForOverflow(const RenderStyle* oldStyle, const RenderStyle* newStyle) const
 {
     ASSERT(newStyle);
-    return !compositedLayerMapping() && oldStyle && (oldStyle->overflowX() != newStyle->overflowX()) && ancestorStackingContainerLayer()->hasCompositingDescendant();
+    return !compositedLayerMapping() && oldStyle && (oldStyle->overflowX() != newStyle->overflowX()) && m_stackingNode->ancestorStackingContainerNode()->layer()->hasCompositingDescendant();
 }
 
 inline bool RenderLayer::needsCompositingLayersRebuiltForFilters(const RenderStyle* oldStyle, const RenderStyle* newStyle, bool didPaintWithFilters) const
@@ -4339,14 +4003,7 @@
     updateSelfPaintingLayer();
     updateOutOfFlowPositioned(oldStyle);
 
-    if (!hasReflection() && m_reflection)
-        removeReflection();
-    else if (hasReflection()) {
-        if (!m_reflection)
-            createReflection();
-        UseCounter::count(renderer()->document(), UseCounter::Reflection);
-        updateReflectionStyle();
-    }
+    updateReflectionInfo(oldStyle);
 
     if (RuntimeEnabledFeatures::cssCompositingEnabled())
         updateBlendMode();
@@ -4370,118 +4027,14 @@
         compositedLayerMapping()->updateGraphicsLayerGeometry();
 }
 
-void RenderLayer::updateScrollableAreaSet(bool hasOverflow)
-{
-    Frame* frame = renderer()->frame();
-    if (!frame)
-        return;
-
-    FrameView* frameView = frame->view();
-    if (!frameView)
-        return;
-
-    bool isVisibleToHitTest = renderer()->visibleToHitTesting();
-    if (HTMLFrameOwnerElement* owner = frame->ownerElement())
-        isVisibleToHitTest &= owner->renderer() && owner->renderer()->visibleToHitTesting();
-
-    bool requiresScrollableArea = hasOverflow && isVisibleToHitTest;
-    bool updatedScrollableAreaSet = false;
-    if (requiresScrollableArea) {
-        if (frameView->addScrollableArea(scrollableArea()))
-            updatedScrollableAreaSet = true;
-    } else {
-        if (frameView->removeScrollableArea(scrollableArea()))
-            updatedScrollableAreaSet = true;
-    }
-
-    if (updatedScrollableAreaSet) {
-        // 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) {
-            HistogramSupport::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 (compositorDrivenAcceleratedScrollingEnabled())
-            didUpdateNeedsCompositedScrolling();
-        else if (requiresScrollableArea)
-            compositor()->setNeedsUpdateCompositingRequirementsState();
-        else
-            setNeedsCompositedScrolling(false);
-    }
-}
-
 bool RenderLayer::scrollsOverflow() const
 {
-    if (RenderLayerScrollableArea* scrollableArea = this->scrollableArea()) {
-        if (FrameView* frameView = renderer()->view()->frameView())
-            return frameView->containsScrollableArea(scrollableArea);
-    }
+    if (RenderLayerScrollableArea* scrollableArea = this->scrollableArea())
+        return scrollableArea->scrollsOverflow();
+
     return false;
 }
 
-RenderLayer* RenderLayer::reflectionLayer() const
-{
-    return m_reflection ? m_reflection->layer() : 0;
-}
-
-void RenderLayer::createReflection()
-{
-    ASSERT(!m_reflection);
-    m_reflection = RenderReplica::createAnonymous(&renderer()->document());
-    m_reflection->setParent(renderer()); // We create a 1-way connection.
-}
-
-void RenderLayer::removeReflection()
-{
-    if (!m_reflection->documentBeingDestroyed())
-        m_reflection->removeLayers(this);
-
-    m_reflection->setParent(0);
-    m_reflection->destroy();
-    m_reflection = 0;
-}
-
-void RenderLayer::updateReflectionStyle()
-{
-    RefPtr<RenderStyle> newStyle = RenderStyle::create();
-    newStyle->inheritFrom(renderer()->style());
-
-    // Map in our transform.
-    TransformOperations transform;
-    switch (renderer()->style()->boxReflect()->direction()) {
-        case ReflectionBelow:
-            transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed), Length(100., Percent), TransformOperation::Translate));
-            transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed), renderer()->style()->boxReflect()->offset(), TransformOperation::Translate));
-            transform.operations().append(ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Scale));
-            break;
-        case ReflectionAbove:
-            transform.operations().append(ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Scale));
-            transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed), Length(100., Percent), TransformOperation::Translate));
-            transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed), renderer()->style()->boxReflect()->offset(), TransformOperation::Translate));
-            break;
-        case ReflectionRight:
-            transform.operations().append(TranslateTransformOperation::create(Length(100., Percent), Length(0, Fixed), TransformOperation::Translate));
-            transform.operations().append(TranslateTransformOperation::create(renderer()->style()->boxReflect()->offset(), Length(0, Fixed), TransformOperation::Translate));
-            transform.operations().append(ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Scale));
-            break;
-        case ReflectionLeft:
-            transform.operations().append(ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Scale));
-            transform.operations().append(TranslateTransformOperation::create(Length(100., Percent), Length(0, Fixed), TransformOperation::Translate));
-            transform.operations().append(TranslateTransformOperation::create(renderer()->style()->boxReflect()->offset(), Length(0, Fixed), TransformOperation::Translate));
-            break;
-    }
-    newStyle->setTransform(transform);
-
-    // Map in our mask.
-    newStyle->setMaskBoxImage(renderer()->style()->boxReflect()->mask());
-
-    m_reflection->setStyle(newStyle.release());
-}
-
 bool RenderLayer::isCSSCustomFilterEnabled() const
 {
     // We only want to enable shaders if WebGL is also enabled on this platform.
@@ -4627,54 +4180,6 @@
         child->addLayerHitTestRects(rects);
 }
 
-IntRect RenderLayer::scrollCornerAndResizerRect() const
-{
-    if (!m_scrollableArea)
-        return IntRect();
-
-    return m_scrollableArea->scrollCornerAndResizerRect();
-}
-
-void RenderLayer::positionOverflowControls(const IntSize& offsetFromRoot)
-{
-    if (m_scrollableArea)
-        m_scrollableArea->positionOverflowControls(offsetFromRoot);
-}
-
-void RenderLayer::paintScrollCorner(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
-{
-    if (m_scrollableArea)
-        m_scrollableArea->paintScrollCorner(context, paintOffset, damageRect);
-}
-
-bool RenderLayer::isPointInResizeControl(const IntPoint& absolutePoint, ResizerHitTestType resizerHitTestType) const
-{
-    if (!m_scrollableArea)
-        return false;
-
-    return m_scrollableArea->isPointInResizeControl(absolutePoint, resizerHitTestType);
-}
-
-void RenderLayer::paintOverflowControls(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
-{
-    if (m_scrollableArea)
-        return m_scrollableArea->paintOverflowControls(context, paintOffset, damageRect, paintingOverlayControls);
-}
-
-bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
-{
-    if (!m_scrollableArea)
-        return false;
-
-    return m_scrollableArea->hitTestOverflowControls(result, localPoint);
-}
-
-void RenderLayer::paintResizer(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
-{
-    if (m_scrollableArea)
-        m_scrollableArea->paintResizer(context, paintOffset, damageRect);
-}
-
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/RenderLayer.h b/Source/core/rendering/RenderLayer.h
index d3bb887..6aff239 100644
--- a/Source/core/rendering/RenderLayer.h
+++ b/Source/core/rendering/RenderLayer.h
@@ -46,9 +46,11 @@
 #define RenderLayer_h
 
 #include "core/rendering/CompositingReasons.h"
+#include "core/rendering/LayerPaintingInfo.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderLayerClipper.h"
+#include "core/rendering/RenderLayerReflectionInfo.h"
 #include "core/rendering/RenderLayerRepainter.h"
 #include "core/rendering/RenderLayerScrollableArea.h"
 #include "core/rendering/RenderLayerStackingNode.h"
@@ -115,10 +117,9 @@
     RenderLayer* transparentPaintingAncestor();
     void beginTransparencyLayers(GraphicsContext*, const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior);
 
-    bool hasReflection() const { return renderer()->hasReflection(); }
     bool isReflection() const { return renderer()->isReplica(); }
-    RenderReplica* reflection() const { return m_reflection; }
-    RenderLayer* reflectionLayer() const;
+    RenderLayerReflectionInfo* reflectionInfo() { return m_reflectionInfo.get(); }
+    const RenderLayerReflectionInfo* reflectionInfo() const { return m_reflectionInfo.get(); }
 
     const RenderLayer* root() const
     {
@@ -136,30 +137,6 @@
 
     LayoutRect rect() const { return LayoutRect(location(), size()); }
 
-    // Scrolling methods for layers that can scroll their overflow.
-    void scrollRectToVisible(const LayoutRect&, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
-
-    LayoutRect getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
-
-    // isPointInResizeControl() is used for testing if a pointer/touch position is in the resize control
-    // area.
-    bool isPointInResizeControl(const IntPoint& absolutePoint, ResizerHitTestType resizerHitTestType) const;
-    bool hitTestOverflowControls(HitTestResult&, const IntPoint& localPoint);
-    IntSize offsetFromResizeCorner(const IntPoint& absolutePoint) const;
-
-    void paintOverflowControls(GraphicsContext*, const IntPoint&, const IntRect& damageRect, bool paintingOverlayControls = false);
-    void paintScrollCorner(GraphicsContext*, const IntPoint&, const IntRect& damageRect);
-    void paintResizer(GraphicsContext*, const IntPoint&, const IntRect& damageRect);
-
-    void updateScrollInfoAfterLayout();
-
-    bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1);
-    void autoscroll(const IntPoint&);
-
-    void resize(const PlatformEvent&, const LayoutSize&);
-    bool inResizeMode() const;
-    void setInResizeMode(bool);
-
     bool isRootLayer() const { return m_isRootLayer; }
 
     RenderLayerCompositor* compositor() const;
@@ -185,8 +162,6 @@
     void updateLayerPositionsAfterOverflowScroll();
     void updateLayerPositionsAfterDocumentScroll();
 
-    void positionNewlyCreatedOverflowControls();
-
     bool isPaginated() const { return m_isPaginated; }
     RenderLayer* enclosingPaginationLayer() const { return m_enclosingPaginationLayer; }
 
@@ -199,18 +174,11 @@
     void addBlockSelectionGapsBounds(const LayoutRect&);
     void clearBlockSelectionGapsBounds();
     void repaintBlockSelectionGaps();
+    bool hasBlockSelectionGapBounds() const;
 
     RenderLayerStackingNode* stackingNode() { return m_stackingNode.get(); }
     const RenderLayerStackingNode* stackingNode() const { return m_stackingNode.get(); }
 
-    RenderLayer* ancestorStackingContainerLayer() const;
-    RenderLayerStackingNode* ancestorStackingContainerNode() const;
-    RenderLayerStackingNode* ancestorStackingNode() const;
-
-    // Gets the enclosing stacking container for this layer, possibly the layer
-    // itself, if it is a stacking container.
-    RenderLayer* enclosingStackingContainerLayer() { return m_stackingNode->isStackingContainer() ? this : ancestorStackingContainerLayer(); }
-
     bool subtreeIsInvisible() const { return !hasVisibleContent() && !hasVisibleDescendant(); }
 
     // FIXME: We should ASSERT(!m_visibleContentStatusDirty) here, but see https://bugs.webkit.org/show_bug.cgi?id=71044
@@ -245,6 +213,9 @@
     void updateHasUnclippedDescendant();
     bool isUnclippedDescendant() const { return m_isUnclippedDescendant; }
 
+    bool hasVisibleNonLayerContent() const { return m_hasVisibleNonLayerContent; }
+    void updateHasVisibleNonLayerContent();
+
     // Gets the nearest enclosing positioned ancestor layer (also includes
     // the <html> layer and the root layer).
     RenderLayer* enclosingPositionedAncestor() const;
@@ -261,6 +232,9 @@
     // Ancestor compositing layer, excluding this.
     RenderLayer* ancestorCompositingLayer() const { return enclosingCompositingLayer(false); }
 
+    // Ancestor composited scrolling layer at or above our containing block.
+    RenderLayer* ancestorCompositedScrollingLayer() const;
+
     // Ancestor scrolling layer at or above our containing block.
     RenderLayer* ancestorScrollingLayer() const;
 
@@ -279,25 +253,6 @@
     void convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutPoint& location) const;
     void convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutRect&) const;
 
-    enum PaintLayerFlag {
-        PaintLayerHaveTransparency = 1,
-        PaintLayerAppliedTransform = 1 << 1,
-        PaintLayerTemporaryClipRects = 1 << 2,
-        PaintLayerPaintingReflection = 1 << 3,
-        PaintLayerPaintingOverlayScrollbars = 1 << 4,
-        PaintLayerPaintingCompositingBackgroundPhase = 1 << 5,
-        PaintLayerPaintingCompositingForegroundPhase = 1 << 6,
-        PaintLayerPaintingCompositingMaskPhase = 1 << 7,
-        PaintLayerPaintingCompositingScrollingPhase = 1 << 8,
-        PaintLayerPaintingOverflowContents = 1 << 9,
-        PaintLayerPaintingRootBackgroundOnly = 1 << 10,
-        PaintLayerPaintingSkipRootBackground = 1 << 11,
-        PaintLayerPaintingChildClippingMaskPhase = 1 << 12,
-        PaintLayerPaintingCompositingAllPhases = (PaintLayerPaintingCompositingBackgroundPhase | PaintLayerPaintingCompositingForegroundPhase | PaintLayerPaintingCompositingMaskPhase)
-    };
-
-    typedef unsigned PaintLayerFlags;
-
     // The two main functions that use the layer system.  The paint method
     // paints the layers that intersect the damage rect from back to
     // front.  The hitTest method looks for mouse events by walking
@@ -330,6 +285,7 @@
         DontConstrainForMask = 1 << 4,
         IncludeCompositedDescendants = 1 << 5,
         UseFragmentBoxes = 1 << 6,
+        PretendLayerHasOwnBacking = 1 << 7,
         DefaultCalculateLayerBoundsFlags =  IncludeSelfTransform | UseLocalClipRectIfPossible | IncludeLayerFilterOutsets | UseFragmentBoxes
     };
     typedef unsigned CalculateLayerBoundsFlags;
@@ -488,6 +444,10 @@
         return isRootLayer() || layerRenderer->isPositioned() || hasTransform();
     }
 
+    void paintLayer(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
+
+    PassOwnPtr<Vector<FloatRect> > collectTrackedRepaintRects() const;
+
 private:
     bool hasOverflowControls() const;
 
@@ -539,32 +499,10 @@
 
     LayoutPoint renderBoxLocation() const { return renderer()->isBox() ? toRenderBox(renderer())->location() : LayoutPoint(); }
 
-    struct LayerPaintingInfo {
-        LayerPaintingInfo(RenderLayer* inRootLayer, const LayoutRect& inDirtyRect, PaintBehavior inPaintBehavior, const LayoutSize& inSubPixelAccumulation, RenderObject* inPaintingRoot = 0, RenderRegion*inRegion = 0, OverlapTestRequestMap* inOverlapTestRequests = 0)
-            : rootLayer(inRootLayer)
-            , paintingRoot(inPaintingRoot)
-            , paintDirtyRect(inDirtyRect)
-            , subPixelAccumulation(inSubPixelAccumulation)
-            , region(inRegion)
-            , overlapTestRequests(inOverlapTestRequests)
-            , paintBehavior(inPaintBehavior)
-            , clipToDirtyRect(true)
-        { }
-        RenderLayer* rootLayer;
-        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;
-    };
-
-    void paintLayer(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
     void paintLayerContentsAndReflection(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
     void paintLayerByApplyingTransform(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags, const LayoutPoint& translationOffset = LayoutPoint());
     void paintLayerContents(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
-    void paintList(Vector<RenderLayer*>*, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
+    void paintList(Vector<RenderLayerStackingNode*>*, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
     void paintPaginatedChildLayer(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
     void paintChildLayerIntoColumns(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags, const Vector<RenderLayer*>& columnLayers, size_t columnIndex);
 
@@ -590,7 +528,7 @@
     RenderLayer* hitTestLayerByApplyingTransform(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest&, HitTestResult&,
         const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* = 0, double* zOffset = 0,
         const LayoutPoint& translationOffset = LayoutPoint());
-    RenderLayer* hitTestList(Vector<RenderLayer*>*, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
+    RenderLayer* hitTestList(Vector<RenderLayerStackingNode*>*, RenderLayer* rootLayer, const HitTestRequest&, HitTestResult&,
                              const LayoutRect& hitTestRect, const HitTestLocation&,
                              const HitTestingTransformState* transformState, double* zOffsetForDescendants, double* zOffset,
                              const HitTestingTransformState* unflattenedTransformState, bool depthSortDescendants);
@@ -612,36 +550,22 @@
     RenderLayer* hitTestTransformedLayerInFragments(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest&, HitTestResult&,
         const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* = 0, double* zOffset = 0);
 
-    bool listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayer*>*, const LayoutRect&) const;
+    bool listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayerStackingNode*>*, const LayoutRect&) const;
 
     bool shouldBeSelfPaintingLayer() const;
 
-    // Start of ScrollableArea interface
-    // To be moved to RenderLayerScrollableArea
-    void updateNeedsCompositedScrolling();
-
-public:
-    bool usesCompositedScrolling() const;
-
-    // End of ScrollableArea interface
-
 private:
-    // Rectangle encompassing the scroll corner and resizer rect.
-    IntRect scrollCornerAndResizerRect() const;
-
-    void updateCompositingLayersAfterScroll();
-
     // FIXME: We should only create the stacking node if needed.
     bool requiresStackingNode() const { return true; }
     void updateStackingNode();
 
+    void updateReflectionInfo(const RenderStyle*);
+
     // FIXME: We could lazily allocate our ScrollableArea based on style properties ('overflow', ...)
     // but for now, we are always allocating it for RenderBox as it's safer.
     bool requiresScrollableArea() const { return renderBox(); }
     void updateScrollableArea();
 
-    void updateScrollableAreaSet(bool hasOverflow);
-
     // 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;
@@ -662,13 +586,6 @@
     // Both updates the status, and returns true if descendants of this have 3d.
     bool update3DTransformedDescendantStatus();
 
-    void createReflection();
-    void removeReflection();
-
-    void updateReflectionStyle();
-    bool paintingInsideReflection() const { return m_paintingInsideReflection; }
-    void setPaintingInsideReflection(bool b) { m_paintingInsideReflection = b; }
-
     void updateOrRemoveFilterClients();
     void updateOrRemoveFilterEffectRenderer();
 
@@ -679,8 +596,6 @@
 
     RenderLayer* enclosingTransformedAncestor() const;
 
-    void positionOverflowControls(const IntSize&);
-
     void updatePagination();
 
     // FIXME: Temporary. Remove when new columns come online.
@@ -689,6 +604,9 @@
     bool hasCompositingDescendant() const { return m_compositingProperties.hasCompositingDescendant; }
     void setHasCompositingDescendant(bool b)  { m_compositingProperties.hasCompositingDescendant = b; }
 
+    bool hasNonCompositedChild() const { return m_compositingProperties.hasNonCompositedChild; }
+    void setHasNonCompositedChild(bool b)  { m_compositingProperties.hasNonCompositedChild = b; }
+
     void setCompositingReasons(CompositingReasons reasons) { m_compositingProperties.compositingReasons = reasons; }
     CompositingReasons compositingReasons() const { return m_compositingProperties.compositingReasons; }
 
@@ -716,9 +634,6 @@
     unsigned m_isUnclippedDescendant : 1;
 
     unsigned m_needsCompositedScrolling : 1;
-    unsigned m_willUseCompositedScrollingHasBeenRecorded : 1;
-
-    unsigned m_isScrollableAreaHasBeenRecorded : 1;
 
     const unsigned m_isRootLayer : 1;
 
@@ -728,13 +643,14 @@
 
     unsigned m_childLayerHasBlendMode : 1;
     unsigned m_childLayerHasBlendModeStatusDirty : 1;
-    unsigned m_paintingInsideReflection : 1; // A state bit tracking if we are painting inside a replica.
 
     unsigned m_visibleContentStatusDirty : 1;
     unsigned m_hasVisibleContent : 1;
     unsigned m_visibleDescendantStatusDirty : 1;
     unsigned m_hasVisibleDescendant : 1;
 
+    unsigned m_hasVisibleNonLayerContent : 1;
+
     unsigned m_isPaginated : 1; // If we think this layer is split by a multi-column ancestor, then this bit will be set.
 
     unsigned m_3DTransformedDescendantStatusDirty : 1;
@@ -776,9 +692,6 @@
 
     OwnPtr<TransformationMatrix> m_transform;
 
-    // May ultimately be extended to many replicas (with their own paint order).
-    RenderReplica* m_reflection;
-
     // Pointer to the enclosing RenderLayer that caused us to be paginated. It is 0 if we are not paginated.
     RenderLayer* m_enclosingPaginationLayer;
 
@@ -787,6 +700,7 @@
     struct CompositingProperties {
         CompositingProperties()
             : hasCompositingDescendant(false)
+            , hasNonCompositedChild(false)
             , viewportConstrainedNotCompositedReason(NoNotCompositedReason)
             , compositingReasons(CompositingReasonNone)
         { }
@@ -794,6 +708,10 @@
         // Used only while determining what layers should be composited. Applies to the tree of z-order lists.
         bool hasCompositingDescendant : 1;
 
+        // Applies to the real render layer tree (i.e., the tree determined by the layer's parent and children and
+        // as opposed to the tree formed by the z-order and normal flow lists).
+        bool hasNonCompositedChild : 1;
+
         // The reason, if any exists, that a fixed-position layer is chosen not to be composited.
         unsigned viewportConstrainedNotCompositedReason : 2;
 
@@ -821,6 +739,7 @@
     RenderLayerRepainter m_repainter;
     RenderLayerClipper m_clipper; // FIXME: Lazily allocate?
     OwnPtr<RenderLayerStackingNode> m_stackingNode;
+    OwnPtr<RenderLayerReflectionInfo> m_reflectionInfo;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderLayerCompositor.cpp b/Source/core/rendering/RenderLayerCompositor.cpp
index 6b60b9c..216ca20 100644
--- a/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/RenderLayerCompositor.cpp
@@ -46,7 +46,7 @@
 #include "core/frame/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingConstraints.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/HistogramSupport.h"
+#include "core/platform/OverscrollTheme.h"
 #include "core/platform/ScrollbarTheme.h"
 #include "core/platform/graphics/GraphicsLayer.h"
 #include "core/platform/graphics/GraphicsLayerClient.h"
@@ -57,12 +57,15 @@
 #include "core/rendering/RenderFullScreen.h"
 #include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderIFrame.h"
+#include "core/rendering/RenderLayerStackingNode.h"
+#include "core/rendering/RenderLayerStackingNodeIterator.h"
 #include "core/rendering/RenderReplica.h"
 #include "core/rendering/RenderVideo.h"
 #include "core/rendering/RenderView.h"
 #include "platform/Logging.h"
 #include "platform/TraceEvent.h"
 #include "platform/geometry/TransformState.h"
+#include "public/platform/Platform.h"
 #include "wtf/TemporaryChange.h"
 
 #if !LOG_DISABLED
@@ -75,7 +78,9 @@
 
 #define WTF_USE_COMPOSITING_FOR_SMALL_CANVASES 1
 
+#if !USE(COMPOSITING_FOR_SMALL_CANVASES)
 static const int canvasAreaThresholdRequiringCompositing = 50 * 100;
+#endif
 
 namespace WebCore {
 
@@ -436,6 +441,12 @@
             // scrolling and animation bounds is implemented (crbug.com/252472).
             Vector<RenderLayer*> unclippedDescendants;
             computeCompositingRequirements(0, updateRoot, &overlapTestRequestMap, recursionData, layersChanged, saw3DTransform, unclippedDescendants);
+
+            const FrameView::ScrollableAreaSet* scrollableAreas = m_renderView->frameView()->scrollableAreas();
+            if (scrollableAreas) {
+                for (FrameView::ScrollableAreaSet::iterator it = scrollableAreas->begin(); it != scrollableAreas->end(); ++it)
+                    (*it)->updateHasVisibleNonLayerContent();
+            }
         }
         needHierarchyUpdate |= layersChanged;
     }
@@ -448,7 +459,7 @@
         m_secondaryBackingStoreBytes = 0;
 
         Frame& frame = m_renderView->frameView()->frame();
-        LOG(Compositing, "\nUpdate %d of %s.\n", m_rootLayerUpdateCount, isMainFrame() ? "main frame" : frame.tree()->uniqueName().string().utf8().data());
+        LOG(Compositing, "\nUpdate %d of %s.\n", m_rootLayerUpdateCount, isMainFrame() ? "main frame" : frame.tree().uniqueName().string().utf8().data());
     }
 #endif
 
@@ -760,33 +771,9 @@
     LayerListMutationDetector mutationChecker(layer->stackingNode());
 #endif
 
-    if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* negZOrderList = layer->stackingNode()->negZOrderList()) {
-            size_t listSize = negZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = negZOrderList->at(i);
-                addToOverlapMapRecursive(overlapMap, curLayer, layer);
-            }
-        }
-    }
-
-    if (Vector<RenderLayer*>* normalFlowList = layer->stackingNode()->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = normalFlowList->at(i);
-            addToOverlapMapRecursive(overlapMap, curLayer, layer);
-        }
-    }
-
-    if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* posZOrderList = layer->stackingNode()->posZOrderList()) {
-            size_t listSize = posZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = posZOrderList->at(i);
-                addToOverlapMapRecursive(overlapMap, curLayer, layer);
-            }
-        }
-    }
+    RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), AllChildren);
+    while (RenderLayerStackingNode* curNode = iterator.next())
+        addToOverlapMapRecursive(overlapMap, curNode->layer(), layer);
 
     if (ancestorLayer)
         overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
@@ -810,6 +797,7 @@
 
     // Clear the flag
     layer->setHasCompositingDescendant(false);
+    layer->setHasNonCompositedChild(false);
 
     // Start by assuming this layer will not need to composite.
     CompositingReasons reasonsToComposite = CompositingReasonNone;
@@ -906,36 +894,33 @@
     bool willHaveForegroundLayer = false;
 
     if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* negZOrderList = layer->stackingNode()->negZOrderList()) {
-            size_t listSize = negZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = negZOrderList->at(i);
-                computeCompositingRequirements(layer, curLayer, overlapMap, childRecursionData, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
+        RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
+        while (RenderLayerStackingNode* curNode = iterator.next()) {
+            computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, layersChanged, 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 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) {
-                        // make layer compositing
-                        childRecursionData.m_compositingAncestor = layer;
+                if (!willBeComposited) {
+                    // make layer compositing
+                    childRecursionData.m_compositingAncestor = layer;
+                    overlapMap->beginNewOverlapTestingContext();
+                    willBeComposited = true;
+                    willHaveForegroundLayer = true;
+
+                    // FIXME: temporary solution for the first negative z-index composited child:
+                    //        re-compute the absBounds for the child so that we can add the
+                    //        negative z-index child's bounds to the new overlap context.
+                    if (overlapMap) {
+                        overlapMap->geometryMap().pushMappingsToAncestor(curNode->layer(), layer);
+                        IntRect childAbsBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(curNode->layer()->overlapBounds()));
+                        bool boundsComputed = true;
                         overlapMap->beginNewOverlapTestingContext();
-                        willBeComposited = true;
-                        willHaveForegroundLayer = true;
-
-                        // FIXME: temporary solution for the first negative z-index composited child:
-                        //        re-compute the absBounds for the child so that we can add the
-                        //        negative z-index child's bounds to the new overlap context.
-                        if (overlapMap) {
-                            overlapMap->geometryMap().pushMappingsToAncestor(curLayer, layer);
-                            IntRect childAbsBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(curLayer->overlapBounds()));
-                            bool boundsComputed = true;
-                            overlapMap->beginNewOverlapTestingContext();
-                            addToOverlapMap(*overlapMap, curLayer, childAbsBounds, boundsComputed);
-                            overlapMap->finishCurrentOverlapTestingContext();
-                            overlapMap->geometryMap().popMappingsToAncestor(layer);
-                        }
+                        addToOverlapMap(*overlapMap, curNode->layer(), childAbsBounds, boundsComputed);
+                        overlapMap->finishCurrentOverlapTestingContext();
+                        overlapMap->geometryMap().popMappingsToAncestor(layer);
                     }
                 }
             }
@@ -955,23 +940,9 @@
         childRecursionData.m_testingOverlap = true;
     }
 
-    if (Vector<RenderLayer*>* normalFlowList = layer->stackingNode()->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = normalFlowList->at(i);
-            computeCompositingRequirements(layer, curLayer, overlapMap, childRecursionData, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
-        }
-    }
-
-    if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* posZOrderList = layer->stackingNode()->posZOrderList()) {
-            size_t listSize = posZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = posZOrderList->at(i);
-                computeCompositingRequirements(layer, curLayer, overlapMap, childRecursionData, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
-            }
-        }
-    }
+    RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
+    while (RenderLayerStackingNode* curNode = iterator.next())
+        computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
 
     // Now that the subtree has been traversed, we can check for compositing reasons that depended on the state of the subtree.
 
@@ -1003,10 +974,10 @@
     }
 
     // If the original layer is composited, the reflection needs to be, too.
-    if (layer->reflectionLayer()) {
+    if (layer->reflectionInfo()) {
         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
         CompositingReasons reflectionCompositingReason = willBeComposited ? CompositingReasonReflectionOfCompositedParent : CompositingReasonNone;
-        layer->reflectionLayer()->setCompositingReasons(layer->reflectionLayer()->compositingReasons() | reflectionCompositingReason);
+        layer->reflectionInfo()->reflectionLayer()->setCompositingReasons(layer->reflectionInfo()->reflectionLayer()->compositingReasons() | reflectionCompositingReason);
     }
 
     // Subsequent layers in the parent's stacking context may also need to composite.
@@ -1039,11 +1010,14 @@
     // At this point we have finished collecting all reasons to composite this layer.
     layer->setCompositingReasons(reasonsToComposite);
 
+    if (!willBeComposited && 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, CompositingChangeRepaintNow))
         layersChanged = true;
 
-    if (layer->reflectionLayer() && updateLayerCompositingState(layer->reflectionLayer(), CompositingChangeRepaintNow))
+    if (layer->reflectionInfo() && updateLayerCompositingState(layer->reflectionInfo()->reflectionLayer(), CompositingChangeRepaintNow))
         layersChanged = true;
 
     descendantHas3DTransform |= anyDescendantHas3DTransform || layer->has3DTransform();
@@ -1111,9 +1085,10 @@
         // we can compute and cache the composited bounds for this layer.
         currentCompositedLayerMapping->updateCompositedBounds();
 
-        if (RenderLayer* reflection = layer->reflectionLayer()) {
-            if (reflection->compositedLayerMapping())
-                reflection->compositedLayerMapping()->updateCompositedBounds();
+        if (layer->reflectionInfo()) {
+            RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
+            if (reflectionLayer->compositedLayerMapping())
+                reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
         }
 
         currentCompositedLayerMapping->updateGraphicsLayerConfiguration();
@@ -1128,7 +1103,7 @@
         UNUSED_PARAM(depth);
 #endif
         if (currentCompositedLayerMapping->hasUnpositionedOverflowControlsLayers())
-            layer->positionNewlyCreatedOverflowControls();
+            layer->scrollableArea()->positionNewlyCreatedOverflowControls();
 
         pixelsWithoutPromotingAllTransitions += layer->size().height() * layer->size().width();
     } else {
@@ -1148,36 +1123,18 @@
 #endif
 
     if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* negZOrderList = layer->stackingNode()->negZOrderList()) {
-            size_t listSize = negZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = negZOrderList->at(i);
-                rebuildCompositingLayerTree(curLayer, childList, depth + 1);
-            }
-        }
+        RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
+        while (RenderLayerStackingNode* curNode = iterator.next())
+            rebuildCompositingLayerTree(curNode->layer(), childList, depth + 1);
 
         // If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
         if (currentCompositedLayerMapping && currentCompositedLayerMapping->foregroundLayer())
             childList.append(currentCompositedLayerMapping->foregroundLayer());
     }
 
-    if (Vector<RenderLayer*>* normalFlowList = layer->stackingNode()->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = normalFlowList->at(i);
-            rebuildCompositingLayerTree(curLayer, childList, depth + 1);
-        }
-    }
-
-    if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* posZOrderList = layer->stackingNode()->posZOrderList()) {
-            size_t listSize = posZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = posZOrderList->at(i);
-                rebuildCompositingLayerTree(curLayer, childList, depth + 1);
-            }
-        }
-    }
+    RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
+    while (RenderLayerStackingNode* curNode = iterator.next())
+        rebuildCompositingLayerTree(curNode->layer(), childList, depth + 1);
 
     if (currentCompositedLayerMapping) {
         bool parented = false;
@@ -1211,7 +1168,7 @@
 
     if (!depth) {
         int percentageIncreaseInPixels = static_cast<int>(pixelsAddedByPromotingAllTransitions / pixelsWithoutPromotingAllTransitions * 100);
-        HistogramSupport::histogramCustomCounts("Renderer.PixelIncreaseFromTransitions", percentageIncreaseInPixels, 0, 1000, 50);
+        WebKit::Platform::current()->histogramCustomCounts("Renderer.PixelIncreaseFromTransitions", percentageIncreaseInPixels, 0, 1000, 50);
     }
 }
 
@@ -1229,11 +1186,6 @@
 
         frameViewDidScroll();
         updateOverflowControlsLayers();
-
-#if USE(RUBBER_BANDING)
-        if (m_layerForOverhangAreas)
-            m_layerForOverhangAreas->setSize(frameView->frameRect().size());
-#endif
     }
 }
 
@@ -1269,14 +1221,14 @@
         m_scrollLayer->setPosition(-scrollPosition);
 
 
-    HistogramSupport::histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
+    WebKit::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
         ScrolledMainFrameBucket,
         AcceleratedFixedRootBackgroundHistogramMax);
 
     if (!m_renderView->rootBackgroundIsEntirelyFixed())
         return;
 
-    HistogramSupport::histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
+    WebKit::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
         !!fixedRootBackgroundLayer()
             ? ScrolledMainFrameWithAcceleratedFixedRootBackground
             : ScrolledMainFrameWithUnacceleratedFixedRootBackground,
@@ -1387,9 +1339,10 @@
         // we can compute and cache the composited bounds for this layer.
         compositedLayerMapping->updateCompositedBounds();
 
-        if (RenderLayer* reflection = layer->reflectionLayer()) {
-            if (reflection->compositedLayerMapping())
-                reflection->compositedLayerMapping()->updateCompositedBounds();
+        if (layer->reflectionInfo()) {
+            RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
+            if (reflectionLayer->compositedLayerMapping())
+                reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
         }
 
         compositedLayerMapping->updateGraphicsLayerConfiguration();
@@ -1409,39 +1362,22 @@
     LayerListMutationDetector mutationChecker(layer->stackingNode());
 #endif
 
-    if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* negZOrderList = layer->stackingNode()->negZOrderList()) {
-            size_t listSize = negZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i)
-                updateLayerTreeGeometry(negZOrderList->at(i), depth + 1);
-        }
-    }
-
-    if (Vector<RenderLayer*>* normalFlowList = layer->stackingNode()->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i)
-            updateLayerTreeGeometry(normalFlowList->at(i), depth + 1);
-    }
-
-    if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* posZOrderList = layer->stackingNode()->posZOrderList()) {
-            size_t listSize = posZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i)
-                updateLayerTreeGeometry(posZOrderList->at(i), depth + 1);
-        }
-    }
+    RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), AllChildren);
+    while (RenderLayerStackingNode* curNode = iterator.next())
+        updateLayerTreeGeometry(curNode->layer(), depth + 1);
 }
 
 // Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
-void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer* layer, bool compositedChildrenOnly)
+void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayerStackingNode* compositingAncestor, RenderLayer* layer, bool compositedChildrenOnly)
 {
-    if (layer != compositingAncestor) {
+    if (layer->stackingNode() != compositingAncestor) {
         if (CompositedLayerMapping* compositedLayerMapping = layer->compositedLayerMapping()) {
             compositedLayerMapping->updateCompositedBounds();
 
-            if (RenderLayer* reflection = layer->reflectionLayer()) {
-                if (reflection->compositedLayerMapping())
-                    reflection->compositedLayerMapping()->updateCompositedBounds();
+            if (layer->reflectionInfo()) {
+                RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
+                if (reflectionLayer->compositedLayerMapping())
+                    reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
             }
 
             compositedLayerMapping->updateGraphicsLayerGeometry();
@@ -1450,8 +1386,8 @@
         }
     }
 
-    if (layer->reflectionLayer())
-        updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionLayer(), compositedChildrenOnly);
+    if (layer->reflectionInfo())
+        updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionInfo()->reflectionLayer(), compositedChildrenOnly);
 
     if (!layer->hasCompositingDescendant())
         return;
@@ -1460,27 +1396,9 @@
     LayerListMutationDetector mutationChecker(layer->stackingNode());
 #endif
 
-    if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* negZOrderList = layer->stackingNode()->negZOrderList()) {
-            size_t listSize = negZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i)
-                updateCompositingDescendantGeometry(compositingAncestor, negZOrderList->at(i), compositedChildrenOnly);
-        }
-    }
-
-    if (Vector<RenderLayer*>* normalFlowList = layer->stackingNode()->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i)
-            updateCompositingDescendantGeometry(compositingAncestor, normalFlowList->at(i), compositedChildrenOnly);
-    }
-
-    if (layer->stackingNode()->isStackingContainer()) {
-        if (Vector<RenderLayer*>* posZOrderList = layer->stackingNode()->posZOrderList()) {
-            size_t listSize = posZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i)
-                updateCompositingDescendantGeometry(compositingAncestor, posZOrderList->at(i), compositedChildrenOnly);
-        }
-    }
+    RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), AllChildren);
+    while (RenderLayerStackingNode* curNode = iterator.next())
+        updateCompositingDescendantGeometry(compositingAncestor, curNode->layer(), compositedChildrenOnly);
 }
 
 
@@ -1503,43 +1421,17 @@
     LayerListMutationDetector mutationChecker(layer->stackingNode());
 #endif
 
-    if (layer->hasCompositingDescendant()) {
-        if (Vector<RenderLayer*>* negZOrderList = layer->stackingNode()->negZOrderList()) {
-            size_t listSize = negZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = negZOrderList->at(i);
-                if (rect) {
-                    IntRect childRect(*rect);
-                    curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
-                    recursiveRepaintLayer(curLayer, &childRect);
-                } else
-                    recursiveRepaintLayer(curLayer);
-            }
-        }
-
-        if (Vector<RenderLayer*>* posZOrderList = layer->stackingNode()->posZOrderList()) {
-            size_t listSize = posZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = posZOrderList->at(i);
-                if (rect) {
-                    IntRect childRect(*rect);
-                    curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
-                    recursiveRepaintLayer(curLayer, &childRect);
-                } else
-                    recursiveRepaintLayer(curLayer);
-            }
-        }
-    }
-    if (Vector<RenderLayer*>* normalFlowList = layer->stackingNode()->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = normalFlowList->at(i);
-            if (rect) {
-                IntRect childRect(*rect);
-                curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
-                recursiveRepaintLayer(curLayer, &childRect);
-            } else
-                recursiveRepaintLayer(curLayer);
+    unsigned childrenToVisit = NormalFlowChildren;
+    if (layer->hasCompositingDescendant())
+        childrenToVisit |= PositiveZOrderChildren | NegativeZOrderChildren;
+    RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), childrenToVisit);
+    while (RenderLayerStackingNode* curNode = iterator.next()) {
+        if (rect) {
+            IntRect childRect(*rect);
+            curNode->layer()->convertToPixelSnappedLayerCoords(layer, childRect);
+            recursiveRepaintLayer(curNode->layer(), &childRect);
+        } else {
+            recursiveRepaintLayer(curNode->layer());
         }
     }
 }
@@ -1607,7 +1499,7 @@
         m_rootContentLayer->setPosition(documentRect.location());
 #if USE(RUBBER_BANDING)
         if (m_layerForOverhangShadow)
-            ScrollbarTheme::theme()->updateOverhangShadowLayer(m_layerForOverhangShadow.get(), m_rootContentLayer.get());
+            OverscrollTheme::theme()->updateOverhangShadowLayer(m_layerForOverhangShadow.get(), m_rootContentLayer.get());
 #endif
     }
     if (m_containerLayer) {
@@ -1968,7 +1860,10 @@
 {
     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
         return false;
-    return renderer->animation().isRunningAcceleratableAnimationOnRenderer(renderer);
+
+    return (renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyOpacity) && inCompositingMode())
+        || renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitFilter)
+        || renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
 }
 
 bool RenderLayerCompositor::requiresCompositingForTransition(RenderObject* renderer) const
@@ -2132,8 +2027,12 @@
     // Fixed position elements that are invisible in the current view don't get their own layer.
     if (FrameView* frameView = m_renderView->frameView()) {
         LayoutRect viewBounds = frameView->viewportConstrainedVisibleContentRect();
-        LayoutRect layerBounds = layer->calculateLayerBounds(rootRenderLayer(), 0, RenderLayer::DefaultCalculateLayerBoundsFlags
-            | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask | RenderLayer::IncludeCompositedDescendants);
+        LayoutRect layerBounds = layer->calculateLayerBounds(rootRenderLayer(), 0,
+            RenderLayer::DefaultCalculateLayerBoundsFlags
+            | RenderLayer::ExcludeHiddenDescendants
+            | RenderLayer::DontConstrainForMask
+            | RenderLayer::IncludeCompositedDescendants
+            | RenderLayer::PretendLayerHasOwnBacking);
         if (!viewBounds.intersects(enclosingIntRect(layerBounds))) {
             if (viewportConstrainedNotCompositedReason) {
                 *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForBoundsOutOfView;
@@ -2194,11 +2093,6 @@
         transformedClip.moveBy(scrollCorner.location());
         m_renderView->frameView()->paintScrollCorner(&context, transformedClip);
         context.restore();
-#if USE(RUBBER_BANDING)
-    } else if (graphicsLayer == layerForOverhangAreas()) {
-        ScrollView* view = m_renderView->frameView();
-        view->calculateAndPaintOverhangBackground(&context, clip);
-#endif
     }
 }
 
@@ -2322,26 +2216,13 @@
 {
 #if USE(RUBBER_BANDING)
     if (requiresOverhangLayers()) {
-        if (!m_layerForOverhangAreas) {
-            m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), this);
-            m_layerForOverhangAreas->setDrawsContent(false);
-            m_layerForOverhangAreas->setSize(m_renderView->frameView()->frameRect().size());
-
-            // We want the overhang areas layer to be positioned below the frame contents,
-            // so insert it below the clip layer.
-            m_overflowControlsHostLayer->addChildBelow(m_layerForOverhangAreas.get(), m_containerLayer.get());
-        }
         if (!m_layerForOverhangShadow) {
             m_layerForOverhangShadow = GraphicsLayer::create(graphicsLayerFactory(), this);
-            ScrollbarTheme::theme()->setUpOverhangShadowLayer(m_layerForOverhangShadow.get());
-            ScrollbarTheme::theme()->updateOverhangShadowLayer(m_layerForOverhangShadow.get(), m_rootContentLayer.get());
+            OverscrollTheme::theme()->setUpOverhangShadowLayer(m_layerForOverhangShadow.get());
+            OverscrollTheme::theme()->updateOverhangShadowLayer(m_layerForOverhangShadow.get(), m_rootContentLayer.get());
             m_scrollLayer->addChild(m_layerForOverhangShadow.get());
         }
     } else {
-        if (m_layerForOverhangAreas) {
-            m_layerForOverhangAreas->removeFromParent();
-            m_layerForOverhangAreas = nullptr;
-        }
         if (m_layerForOverhangShadow) {
             m_layerForOverhangShadow->removeFromParent();
             m_layerForOverhangShadow = nullptr;
@@ -2454,10 +2335,6 @@
     detachRootLayer();
 
 #if USE(RUBBER_BANDING)
-    if (m_layerForOverhangAreas) {
-        m_layerForOverhangAreas->removeFromParent();
-        m_layerForOverhangAreas = nullptr;
-    }
     if (m_layerForOverhangShadow) {
         m_layerForOverhangShadow->removeFromParent();
         m_layerForOverhangShadow = nullptr;
@@ -2576,7 +2453,7 @@
         return;
     Frame& frame = m_renderView->frameView()->frame();
 
-    for (Frame* child = frame.tree()->firstChild(); child; child = child->tree()->traverseNext(&frame)) {
+    for (Frame* child = frame.tree().firstChild(); child; child = child->tree().traverseNext(&frame)) {
         if (child->document() && child->document()->ownerElement())
             child->document()->ownerElement()->scheduleLayerUpdate();
     }
@@ -2604,34 +2481,12 @@
     LayerListMutationDetector mutationChecker(stackingNode);
 #endif
 
-    if (stackingNode->isStackingContainer()) {
-        if (Vector<RenderLayer*>* negZOrderList = stackingNode->negZOrderList()) {
-            size_t listSize = negZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = negZOrderList->at(i);
-                if (layerHas3DContent(curLayer))
-                    return true;
-            }
-        }
-
-        if (Vector<RenderLayer*>* posZOrderList = stackingNode->posZOrderList()) {
-            size_t listSize = posZOrderList->size();
-            for (size_t i = 0; i < listSize; ++i) {
-                RenderLayer* curLayer = posZOrderList->at(i);
-                if (layerHas3DContent(curLayer))
-                    return true;
-            }
-        }
+    RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), AllChildren);
+    while (RenderLayerStackingNode* curNode = iterator.next()) {
+        if (layerHas3DContent(curNode->layer()))
+            return true;
     }
 
-    if (Vector<RenderLayer*>* normalFlowList = stackingNode->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i) {
-            RenderLayer* curLayer = normalFlowList->at(i);
-            if (layerHas3DContent(curLayer))
-                return true;
-        }
-    }
     return false;
 }
 
@@ -2643,8 +2498,8 @@
     if (layer->renderer()->style()->position() != FixedPosition)
         return false;
 
-    for (RenderLayer* stackingContainerLayer = layer->ancestorStackingContainerLayer(); stackingContainerLayer; stackingContainerLayer = stackingContainerLayer->ancestorStackingContainerLayer()) {
-        if (stackingContainerLayer->compositedLayerMapping() && stackingContainerLayer->renderer()->style()->position() == FixedPosition)
+    for (RenderLayerStackingNode* stackingContainerNode = layer->stackingNode()->ancestorStackingContainerNode(); stackingContainerNode; stackingContainerNode = stackingContainerNode->ancestorStackingContainerNode()) {
+        if (stackingContainerNode->layer()->compositedLayerMapping() && stackingContainerNode->layer()->renderer()->style()->position() == FixedPosition)
             return false;
     }
 
@@ -2757,9 +2612,7 @@
     if (graphicsLayer == m_rootContentLayer.get()) {
         name = "Content Root Layer";
 #if USE(RUBBER_BANDING)
-    } else if (graphicsLayer == m_layerForOverhangAreas.get()) {
-        name = "Overhang Areas Layer";
-    } else if (graphicsLayer == m_layerForOverhangAreas.get()) {
+    } else if (graphicsLayer == m_layerForOverhangShadow.get()) {
         name = "Overhang Areas Shadow";
 #endif
     } else if (graphicsLayer == m_overflowControlsHostLayer.get()) {
diff --git a/Source/core/rendering/RenderLayerCompositor.h b/Source/core/rendering/RenderLayerCompositor.h
index 9c479bd..c053c06 100644
--- a/Source/core/rendering/RenderLayerCompositor.h
+++ b/Source/core/rendering/RenderLayerCompositor.h
@@ -36,6 +36,7 @@
 class FixedPositionViewportConstraints;
 class GraphicsLayer;
 class RenderEmbeddedObject;
+class RenderLayerStackingNode;
 class RenderPart;
 class RenderVideo;
 class ScrollingCoordinator;
@@ -99,7 +100,7 @@
     bool updateLayerCompositingState(RenderLayer*, CompositingChangeRepaint = CompositingChangeRepaintNow);
 
     // Update the geometry for compositing children of compositingAncestor.
-    void updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer*, bool compositedChildrenOnly);
+    void updateCompositingDescendantGeometry(RenderLayerStackingNode* compositingAncestor, RenderLayer*, bool compositedChildrenOnly);
 
     // Whether layer's compositedLayerMapping needs a GraphicsLayer to do clipping by an ancestor (non-stacking-context parent with overflow).
     bool clippedByAncestor(const RenderLayer*) const;
@@ -184,12 +185,6 @@
     GraphicsLayer* layerForHorizontalScrollbar() const { return m_layerForHorizontalScrollbar.get(); }
     GraphicsLayer* layerForVerticalScrollbar() const { return m_layerForVerticalScrollbar.get(); }
     GraphicsLayer* layerForScrollCorner() const { return m_layerForScrollCorner.get(); }
-#if USE(RUBBER_BANDING)
-    GraphicsLayer* layerForOverhangAreas() const { return m_layerForOverhangAreas.get(); }
-
-    GraphicsLayer* updateLayerForTopOverhangArea(bool wantsLayer);
-    GraphicsLayer* updateLayerForBottomOverhangArea(bool wantsLayer);
-#endif
 
     void updateViewportConstraintStatus(RenderLayer*);
     void removeViewportConstrainedLayer(RenderLayer*);
@@ -350,7 +345,6 @@
     OwnPtr<GraphicsLayer> m_layerForVerticalScrollbar;
     OwnPtr<GraphicsLayer> m_layerForScrollCorner;
 #if USE(RUBBER_BANDING)
-    OwnPtr<GraphicsLayer> m_layerForOverhangAreas;
     OwnPtr<GraphicsLayer> m_layerForOverhangShadow;
 #endif
 
diff --git a/Source/core/rendering/RenderLayerReflectionInfo.cpp b/Source/core/rendering/RenderLayerReflectionInfo.cpp
new file mode 100644
index 0000000..5a2fd69
--- /dev/null
+++ b/Source/core/rendering/RenderLayerReflectionInfo.cpp
@@ -0,0 +1,148 @@
+/*
+ * 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/RenderLayerReflectionInfo.h"
+
+#include "core/page/UseCounter.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderReplica.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+RenderLayerReflectionInfo::RenderLayerReflectionInfo(RenderBox* renderer)
+    : m_renderer(renderer)
+    , m_isPaintingInsideReflection(false)
+{
+    UseCounter::count(m_renderer->document(), UseCounter::Reflection);
+
+    m_reflection = RenderReplica::createAnonymous(&(m_renderer->document()));
+    m_reflection->setParent(m_renderer); // We create a 1-way connection.
+}
+
+RenderLayerReflectionInfo::~RenderLayerReflectionInfo()
+{
+    if (!m_reflection->documentBeingDestroyed())
+        m_reflection->removeLayers(renderer()->layer());
+
+    m_reflection->setParent(0);
+    m_reflection->destroy();
+    m_reflection = 0;
+}
+
+
+RenderLayer* RenderLayerReflectionInfo::reflectionLayer() const
+{
+    return m_reflection->layer();
+}
+
+void RenderLayerReflectionInfo::updateAfterStyleChange(const RenderStyle* oldStyle)
+{
+    RefPtr<RenderStyle> newStyle = RenderStyle::create();
+    newStyle->inheritFrom(renderer()->style());
+
+    // Map in our transform.
+    TransformOperations transform;
+    switch (renderer()->style()->boxReflect()->direction()) {
+    case ReflectionBelow:
+        transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed),
+            Length(100., Percent), TransformOperation::Translate));
+        transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed),
+            renderer()->style()->boxReflect()->offset(), TransformOperation::Translate));
+        transform.operations().append(ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Scale));
+        break;
+
+    case ReflectionAbove:
+        transform.operations().append(ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Scale));
+        transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed),
+            Length(100., Percent), TransformOperation::Translate));
+        transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed),
+            renderer()->style()->boxReflect()->offset(), TransformOperation::Translate));
+        break;
+
+    case ReflectionRight:
+        transform.operations().append(TranslateTransformOperation::create(Length(100., Percent),
+            Length(0, Fixed), TransformOperation::Translate));
+        transform.operations().append(TranslateTransformOperation::create(
+            renderer()->style()->boxReflect()->offset(), Length(0, Fixed), TransformOperation::Translate));
+        transform.operations().append(ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Scale));
+        break;
+
+    case ReflectionLeft:
+        transform.operations().append(ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Scale));
+        transform.operations().append(TranslateTransformOperation::create(Length(100., Percent),
+            Length(0, Fixed), TransformOperation::Translate));
+        transform.operations().append(TranslateTransformOperation::create(
+            renderer()->style()->boxReflect()->offset(), Length(0, Fixed), TransformOperation::Translate));
+        break;
+    }
+    newStyle->setTransform(transform);
+
+    // Map in our mask.
+    newStyle->setMaskBoxImage(renderer()->style()->boxReflect()->mask());
+
+    m_reflection->setStyle(newStyle.release());
+}
+
+void RenderLayerReflectionInfo::paint(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags flags)
+{
+    if (m_isPaintingInsideReflection)
+        return;
+
+    // Mark that we are now inside replica painting.
+    m_isPaintingInsideReflection = true;
+    reflectionLayer()->paintLayer(context, paintingInfo, flags);
+    m_isPaintingInsideReflection = false;
+}
+
+String RenderLayerReflectionInfo::debugName() const
+{
+    return renderer()->debugName() + " (reflection)";
+}
+
+} // namespace WebCore
diff --git a/Source/core/rendering/RenderLayerReflectionInfo.h b/Source/core/rendering/RenderLayerReflectionInfo.h
new file mode 100644
index 0000000..90ec789
--- /dev/null
+++ b/Source/core/rendering/RenderLayerReflectionInfo.h
@@ -0,0 +1,86 @@
+/*
+ * 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 RenderLayerReflectionInfo_h
+#define RenderLayerReflectionInfo_h
+
+#include "core/rendering/LayerPaintingInfo.h"
+#include "core/rendering/RenderLayerModelObject.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class RenderLayer;
+class RenderReplica;
+
+class RenderLayerReflectionInfo {
+    WTF_MAKE_NONCOPYABLE(RenderLayerReflectionInfo);
+public:
+    explicit RenderLayerReflectionInfo(RenderBox*);
+    ~RenderLayerReflectionInfo();
+
+    RenderReplica* reflection() const { return m_reflection; }
+    RenderLayer* reflectionLayer() const;
+
+    bool isPaintingInsideReflection() const { return m_isPaintingInsideReflection; }
+
+    void updateAfterStyleChange(const RenderStyle* oldStyle);
+
+    void paint(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
+
+    String debugName() const;
+
+private:
+    RenderBox* renderer() const { return m_renderer; }
+
+    RenderBox* m_renderer;
+    RenderReplica* m_reflection;
+
+    // A state bit tracking if we are painting inside a replica.
+    unsigned m_isPaintingInsideReflection : 1;
+};
+
+} // namespace WebCore
+
+#endif // RenderLayerReflectinInfo_h
diff --git a/Source/core/rendering/RenderLayerScrollableArea.cpp b/Source/core/rendering/RenderLayerScrollableArea.cpp
index bddefd4..5467932 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.cpp
+++ b/Source/core/rendering/RenderLayerScrollableArea.cpp
@@ -47,6 +47,7 @@
 #include "core/css/PseudoStyleRequest.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
+#include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FocusController.h"
@@ -59,12 +60,14 @@
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/GraphicsLayer.h"
 #include "core/rendering/CompositedLayerMapping.h"
+#include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderScrollbarPart.h"
 #include "core/rendering/RenderView.h"
 #include "platform/PlatformGestureEvent.h"
 #include "platform/PlatformMouseEvent.h"
+#include "public/platform/Platform.h"
 
 namespace WebCore {
 
@@ -75,6 +78,8 @@
     , m_inResizeMode(false)
     , m_scrollDimensionsDirty(true)
     , m_inOverflowRelayout(false)
+    , m_willUseCompositedScrollingHasBeenRecorded(false)
+    , m_isScrollableAreaHasBeenRecorded(false)
     , m_scrollCorner(0)
     , m_resizer(0)
 {
@@ -97,7 +102,7 @@
 {
     if (inResizeMode() && !m_box->documentBeingDestroyed()) {
         if (Frame* frame = m_box->frame())
-            frame->eventHandler()->resizeLayerDestroyed();
+            frame->eventHandler().resizeScrollableAreaDestroyed();
     }
 
     if (Frame* frame = m_box->frame()) {
@@ -141,11 +146,6 @@
     return 0;
 }
 
-void RenderLayerScrollableArea::updateNeedsCompositedScrolling()
-{
-    layer()->updateNeedsCompositedScrolling();
-}
-
 GraphicsLayer* RenderLayerScrollableArea::layerForScrolling() const
 {
     return m_box->compositedLayerMapping() ? m_box->compositedLayerMapping()->scrollingContentsLayer() : 0;
@@ -166,11 +166,6 @@
     return m_box->compositedLayerMapping() ? m_box->compositedLayerMapping()->layerForScrollCorner() : 0;
 }
 
-bool RenderLayerScrollableArea::usesCompositedScrolling() const
-{
-    return layer()->usesCompositedScrolling();
-}
-
 void RenderLayerScrollableArea::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
 {
     if (scrollbar == m_vBar.get()) {
@@ -352,7 +347,7 @@
             view->updateWidgetPositions();
         }
 
-        layer()->updateCompositingLayersAfterScroll();
+        updateCompositingLayersAfterScroll();
     }
 
     RenderLayerModelObject* repaintContainer = m_box->containerForRepaint();
@@ -363,13 +358,19 @@
         FloatQuad quadForFakeMouseMoveEvent = FloatQuad(layer()->repainter().repaintRect());
         if (repaintContainer)
             quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
-        frame->eventHandler()->dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
+        frame->eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
     }
 
     bool requiresRepaint = true;
 
-    if (m_box->view()->compositor()->inCompositingMode() && layer()->usesCompositedScrolling())
-        requiresRepaint = false;
+    if (m_box->view()->compositor()->inCompositingMode()) {
+        bool onlyScrolledCompositedLayers = !layer()->hasVisibleNonLayerContent()
+            && !layer()->hasNonCompositedChild()
+            && !layer()->hasBlockSelectionGapBounds();
+
+        if (usesCompositedScrolling() || onlyScrolledCompositedLayers)
+            requiresRepaint = false;
+    }
 
     // Just schedule a full repaint of our object.
     if (view && requiresRepaint)
@@ -435,7 +436,7 @@
 
 IntPoint RenderLayerScrollableArea::lastKnownMousePosition() const
 {
-    return m_box->frame() ? m_box->frame()->eventHandler()->lastKnownMousePosition() : IntPoint();
+    return m_box->frame() ? m_box->frame()->eventHandler().lastKnownMousePosition() : IntPoint();
 }
 
 bool RenderLayerScrollableArea::shouldSuspendScrollAnimations() const
@@ -599,7 +600,11 @@
         verticalScrollbar->setProportion(clientHeight, overflowRect().height());
     }
 
-    layer()->updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
+    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();
 }
 
 bool RenderLayerScrollableArea::hasHorizontalOverflow() const
@@ -643,7 +648,7 @@
         return;
 
     if (!m_scrollDimensionsDirty)
-        layer()->updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
+        updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
 
     EOverflow overflowX = m_box->style()->overflowX();
     EOverflow overflowY = m_box->style()->overflowY();
@@ -844,6 +849,16 @@
     return m_hBar->height();
 }
 
+void RenderLayerScrollableArea::positionOverflowControls()
+{
+    RenderGeometryMap geometryMap(UseTransforms);
+    RenderView* view = m_box->view();
+    if (m_box->layer() != view->layer() && m_box->layer()->parent())
+        geometryMap.pushMappingsToAncestor(m_box->layer()->parent(), 0);
+
+    LayoutPoint offsetFromRoot = LayoutPoint(geometryMap.absolutePoint(FloatPoint()));
+    positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
+}
 
 void RenderLayerScrollableArea::positionOverflowControls(const IntSize& offsetFromRoot)
 {
@@ -874,6 +889,28 @@
         m_box->compositedLayerMapping()->positionOverflowControlsLayers(offsetFromRoot);
 }
 
+void RenderLayerScrollableArea::positionNewlyCreatedOverflowControls()
+{
+    if (!m_box->compositedLayerMapping()->hasUnpositionedOverflowControlsLayers())
+        return;
+
+    RenderGeometryMap geometryMap(UseTransforms);
+    RenderView* view = m_box->view();
+    if (this != view->layer()->scrollableArea() && m_box->layer()->parent())
+        geometryMap.pushMappingsToAncestor(m_box->layer()->parent(), 0);
+
+    LayoutPoint offsetFromRoot = LayoutPoint(geometryMap.absolutePoint(FloatPoint()));
+    positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
+}
+
+bool RenderLayerScrollableArea::scrollsOverflow() const
+{
+    if (FrameView* frameView = m_box->view()->frameView())
+        return frameView->containsScrollableArea(this);
+
+    return false;
+}
+
 void RenderLayerScrollableArea::updateScrollCornerStyle()
 {
     RenderObject* actualRenderer = rendererForScrollbar(m_box);
@@ -1212,7 +1249,7 @@
 
     switch (evt.type()) {
     case PlatformEvent::MouseMoved:
-        if (!document.frame()->eventHandler()->mousePressed())
+        if (!document.frame()->eventHandler().mousePressed())
             return;
         pos = static_cast<const PlatformMouseEvent*>(&evt)->position();
         break;
@@ -1275,4 +1312,147 @@
     // FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
 }
 
+LayoutRect RenderLayerScrollableArea::exposeRect(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
+{
+    LayoutRect localExposeRect(m_box->absoluteToLocalQuad(FloatQuad(FloatRect(rect)), UseTransforms).boundingBox());
+    LayoutRect layerBounds(0, 0, m_box->clientWidth(), m_box->clientHeight());
+    LayoutRect r = ScrollAlignment::getRectToExpose(layerBounds, localExposeRect, alignX, alignY);
+
+    IntSize clampedScrollOffset = clampScrollOffset(adjustedScrollOffset() + toIntSize(roundedIntRect(r).location()));
+    if (clampedScrollOffset == adjustedScrollOffset())
+        return rect;
+
+    IntSize oldScrollOffset = adjustedScrollOffset();
+    scrollToOffset(clampedScrollOffset);
+    IntSize scrollOffsetDifference = adjustedScrollOffset() - oldScrollOffset;
+    localExposeRect.move(-scrollOffsetDifference);
+    return LayoutRect(m_box->localToAbsoluteQuad(FloatQuad(FloatRect(localExposeRect)), UseTransforms).boundingBox());
+}
+
+void RenderLayerScrollableArea::updateScrollableAreaSet(bool hasOverflow)
+{
+    Frame* frame = m_box->frame();
+    if (!frame)
+        return;
+
+    FrameView* frameView = frame->view();
+    if (!frameView)
+        return;
+
+    bool isVisibleToHitTest = m_box->visibleToHitTesting();
+    if (HTMLFrameOwnerElement* owner = frame->ownerElement())
+        isVisibleToHitTest &= owner->renderer() && owner->renderer()->visibleToHitTesting();
+
+    bool requiresScrollableArea = hasOverflow && isVisibleToHitTest;
+    bool updatedScrollableAreaSet = false;
+    if (requiresScrollableArea) {
+        if (frameView->addScrollableArea(this))
+            updatedScrollableAreaSet = true;
+    } else {
+        if (frameView->removeScrollableArea(this))
+            updatedScrollableAreaSet = true;
+    }
+
+    if (updatedScrollableAreaSet) {
+        // 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) {
+            WebKit::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::IsScrollableAreaBucket, RenderLayer::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())
+            layer()->didUpdateNeedsCompositedScrolling();
+        else if (requiresScrollableArea)
+            m_box->view()->compositor()->setNeedsUpdateCompositingRequirementsState();
+        else
+            setNeedsCompositedScrolling(false);
+    }
+}
+
+void RenderLayerScrollableArea::updateNeedsCompositedScrolling()
+{
+    TRACE_EVENT0("comp-scroll", "RenderLayer::updateNeedsCompositedScrolling");
+
+    layer()->stackingNode()->updateDescendantsAreContiguousInStackingOrder();
+    layer()->updateDescendantDependentFlags();
+
+    ASSERT(scrollsOverflow());
+    const bool needsToBeStackingContainer = layer()->acceleratedCompositingForOverflowScrollEnabled()
+        && layer()->stackingNode()->descendantsAreContiguousInStackingOrder()
+        && !layer()->hasUnclippedDescendant();
+
+    const bool needsToBeStackingContainerDidChange = layer()->stackingNode()->setNeedsToBeStackingContainer(needsToBeStackingContainer);
+
+    const bool needsCompositedScrolling = needsToBeStackingContainer
+        || layer()->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())
+        WebKit::Platform::current()->histogramEnumeration("Renderer.NeedsCompositedScrolling", needsCompositedScrolling, 2);
+
+    const bool needsCompositedScrollingDidChange = setNeedsCompositedScrolling(needsCompositedScrolling);
+
+    if (needsToBeStackingContainerDidChange || needsCompositedScrollingDidChange) {
+        // Note, the z-order lists may need to be rebuilt, but our code guarantees
+        // that we have not affected stacking, so we will not dirty
+        // m_descendantsAreContiguousInStackingOrder for either us or our stacking
+        // context or container.
+        layer()->didUpdateNeedsCompositedScrolling();
+    }
+}
+
+bool RenderLayerScrollableArea::setNeedsCompositedScrolling(bool needsCompositedScrolling)
+{
+    if (layer()->m_needsCompositedScrolling == needsCompositedScrolling)
+        return false;
+
+    // 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) {
+        WebKit::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::WillUseCompositedScrollingBucket, RenderLayer::CompositedScrollingHistogramMax);
+        m_willUseCompositedScrollingHasBeenRecorded = true;
+    }
+
+    layer()->m_needsCompositedScrolling = needsCompositedScrolling;
+
+    return true;
+}
+
+void RenderLayerScrollableArea::updateHasVisibleNonLayerContent()
+{
+    layer()->updateHasVisibleNonLayerContent();
+}
+
+void RenderLayerScrollableArea::updateCompositingLayersAfterScroll()
+{
+    RenderLayerCompositor* compositor = m_box->view()->compositor();
+    if (compositor->inCompositingMode()) {
+        // Our stacking container is guaranteed to contain all of our descendants that may need
+        // repositioning, so update compositing layers from there.
+        if (RenderLayer* compositingAncestor = m_box->layer()->stackingNode()->ancestorStackingContainerNode()->layer()->enclosingCompositingLayer()) {
+            if (usesCompositedScrolling())
+                compositor->updateCompositingLayers(CompositingUpdateOnCompositedScroll, compositingAncestor);
+            else
+                compositor->updateCompositingLayers(CompositingUpdateOnScroll, compositingAncestor);
+        }
+    }
+}
+
+bool RenderLayerScrollableArea::usesCompositedScrolling() const
+{
+    // Scroll form controls on the main thread so they exhibit correct touch scroll event bubbling
+    if (m_box && (m_box->isIntristicallyScrollable(VerticalScrollbar) || m_box->isIntristicallyScrollable(HorizontalScrollbar)))
+        return false;
+
+    return m_box->compositedLayerMapping() && m_box->compositedLayerMapping()->scrollingLayer();
+}
+
 } // Namespace WebCore
diff --git a/Source/core/rendering/RenderLayerScrollableArea.h b/Source/core/rendering/RenderLayerScrollableArea.h
index ce952c4..8d64e56 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.h
+++ b/Source/core/rendering/RenderLayerScrollableArea.h
@@ -72,8 +72,6 @@
     virtual Scrollbar* verticalScrollbar() const OVERRIDE { return m_vBar.get(); }
     virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
 
-    virtual void updateNeedsCompositedScrolling() OVERRIDE;
-
     virtual GraphicsLayer* layerForScrolling() const OVERRIDE;
     virtual GraphicsLayer* layerForHorizontalScrollbar() const OVERRIDE;
     virtual GraphicsLayer* layerForVerticalScrollbar() const OVERRIDE;
@@ -145,6 +143,28 @@
 
     IntSize adjustedScrollOffset() const { return IntSize(scrollXOffset(), scrollYOffset()); }
 
+    void paintResizer(GraphicsContext*, const IntPoint& paintOffset, const IntRect& damageRect);
+    void paintOverflowControls(GraphicsContext*, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls);
+    void paintScrollCorner(GraphicsContext*, const IntPoint&, const IntRect& damageRect);
+
+    // If IntSize is not given, then we must incur additional overhead to instantiate a RenderGeometryMap
+    // and compute the correct offset ourselves.
+    void positionOverflowControls();
+    void positionOverflowControls(const IntSize& offsetFromRoot);
+    void positionNewlyCreatedOverflowControls();
+
+    // isPointInResizeControl() is used for testing if a pointer/touch position is in the resize control
+    // area.
+    bool isPointInResizeControl(const IntPoint& absolutePoint, ResizerHitTestType) const;
+    bool hitTestOverflowControls(HitTestResult&, const IntPoint& localPoint);
+
+    LayoutRect exposeRect(const LayoutRect&, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
+
+    bool scrollsOverflow() const;
+
+    // Rectangle encompassing the scroll corner and resizer rect.
+    IntRect scrollCornerAndResizerRect() const;
+
 private:
     bool hasHorizontalOverflow() const;
     bool hasVerticalOverflow() const;
@@ -169,18 +189,11 @@
     void setHasHorizontalScrollbar(bool hasScrollbar);
     void setHasVerticalScrollbar(bool hasScrollbar);
 
-    void positionOverflowControls(const IntSize& offsetFromRoot);
     void updateScrollCornerStyle();
-    void paintOverflowControls(GraphicsContext*, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls);
-    void paintScrollCorner(GraphicsContext*, const IntPoint&, const IntRect& damageRect);
-    bool hitTestOverflowControls(HitTestResult&, const IntPoint& localPoint);
 
     // See comments on isPointInResizeControl.
     IntRect resizerCornerRect(const IntRect&, ResizerHitTestType) const;
-    IntRect scrollCornerAndResizerRect() const;
     bool overflowControlsIntersectRect(const IntRect& localRect) const;
-    void paintResizer(GraphicsContext*, const IntPoint& paintOffset, const IntRect& damageRect);
-    bool isPointInResizeControl(const IntPoint& absolutePoint, ResizerHitTestType) const;
     bool hitTestResizerInFragments(const LayerFragments&, const HitTestLocation&) const;
     void updateResizerAreaSet();
     void updateResizerStyle();
@@ -188,6 +201,14 @@
 
     RenderLayer* layer() const;
 
+    void updateScrollableAreaSet(bool hasOverflow);
+
+    void updateCompositingLayersAfterScroll();
+    virtual void updateNeedsCompositedScrolling() OVERRIDE;
+    bool setNeedsCompositedScrolling(bool);
+
+    virtual void updateHasVisibleNonLayerContent() OVERRIDE;
+
     RenderBox* m_box;
 
     // Keeps track of whether the layer is currently resizing, so events can cause resizing to start and stop.
@@ -196,6 +217,10 @@
     unsigned m_scrollDimensionsDirty : 1;
     unsigned m_inOverflowRelayout : 1;
 
+    unsigned m_willUseCompositedScrollingHasBeenRecorded : 1;
+
+    unsigned m_isScrollableAreaHasBeenRecorded : 1;
+
     // The width/height of our scrolled area.
     LayoutRect m_overflowRect;
 
diff --git a/Source/core/rendering/RenderLayerStackingNode.cpp b/Source/core/rendering/RenderLayerStackingNode.cpp
index 4a796cd..76a28e0 100644
--- a/Source/core/rendering/RenderLayerStackingNode.cpp
+++ b/Source/core/rendering/RenderLayerStackingNode.cpp
@@ -44,10 +44,10 @@
 #include "config.h"
 #include "core/rendering/RenderLayerStackingNode.h"
 
-#include "core/platform/HistogramSupport.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderView.h"
+#include "public/platform/Platform.h"
 
 namespace WebCore {
 
@@ -56,13 +56,14 @@
 // we have to ask the render layer about some of its state.
 RenderLayerStackingNode::RenderLayerStackingNode(RenderLayer* layer)
     : m_layer(layer)
-    , m_normalFlowListDirty(true)
     , m_descendantsAreContiguousInStackingOrder(false)
     , m_descendantsAreContiguousInStackingOrderDirty(true)
+    , m_normalFlowListDirty(true)
     , m_needsToBeStackingContainer(false)
     , m_needsToBeStackingContainerHasBeenRecorded(false)
 #if !ASSERT_DISABLED
     , m_layerListMutationAllowed(true)
+    , m_stackingParent(0)
 #endif
 {
     m_isNormalFlowOnly = shouldBeNormalFlowOnly();
@@ -72,15 +73,28 @@
     m_zOrderListsDirty = isStackingContainer();
 }
 
+RenderLayerStackingNode::~RenderLayerStackingNode()
+{
+#if !ASSERT_DISABLED
+    if (!renderer()->documentBeingDestroyed()) {
+        ASSERT(!isInStackingParentZOrderLists());
+        ASSERT(!isInStackingParentNormalFlowList());
+
+        updateStackingParentForZOrderLists(0);
+        updateStackingParentForNormalFlowList(0);
+    }
+#endif
+}
+
 bool RenderLayerStackingNode::isStackingContext(const RenderStyle* style) const
 {
     return !style->hasAutoZIndex() || layer()->isRootLayer();
 }
 
 // Helper for the sorting of layers by z-index.
-static inline bool compareZIndex(RenderLayer* first, RenderLayer* second)
+static inline bool compareZIndex(RenderLayerStackingNode* first, RenderLayerStackingNode* second)
 {
-    return first->stackingNode()->zIndex() < second->stackingNode()->zIndex();
+    return first->zIndex() < second->zIndex();
 }
 
 RenderLayerCompositor* RenderLayerStackingNode::compositor() const
@@ -98,25 +112,25 @@
         return;
 
     for (size_t index = 0; index < normalFlowList()->size(); ++index)
-        normalFlowList()->at(index)->stackingNode()->dirtyNormalFlowListCanBePromotedToStackingContainer();
+        normalFlowList()->at(index)->dirtyNormalFlowListCanBePromotedToStackingContainer();
 }
 
 void RenderLayerStackingNode::dirtySiblingStackingNodeCanBePromotedToStackingContainer()
 {
-    RenderLayerStackingNode* ancestorStackingNode = layer()->ancestorStackingNode();
-    if (!ancestorStackingNode)
+    RenderLayerStackingNode* stackingNode = ancestorStackingNode();
+    if (!stackingNode)
         return;
 
-    if (!ancestorStackingNode->zOrderListsDirty() && ancestorStackingNode->posZOrderList()) {
-        for (size_t index = 0; index < ancestorStackingNode->posZOrderList()->size(); ++index)
-            ancestorStackingNode->posZOrderList()->at(index)->stackingNode()->setDescendantsAreContiguousInStackingOrderDirty(true);
+    if (!stackingNode->zOrderListsDirty() && stackingNode->posZOrderList()) {
+        for (size_t index = 0; index < stackingNode->posZOrderList()->size(); ++index)
+            stackingNode->posZOrderList()->at(index)->setDescendantsAreContiguousInStackingOrderDirty(true);
     }
 
-    ancestorStackingNode->dirtyNormalFlowListCanBePromotedToStackingContainer();
+    stackingNode->dirtyNormalFlowListCanBePromotedToStackingContainer();
 
-    if (!ancestorStackingNode->zOrderListsDirty() && ancestorStackingNode->negZOrderList()) {
-        for (size_t index = 0; index < ancestorStackingNode->negZOrderList()->size(); ++index)
-            ancestorStackingNode->negZOrderList()->at(index)->stackingNode()->setDescendantsAreContiguousInStackingOrderDirty(true);
+    if (!stackingNode->zOrderListsDirty() && stackingNode->negZOrderList()) {
+        for (size_t index = 0; index < stackingNode->negZOrderList()->size(); ++index)
+            stackingNode->negZOrderList()->at(index)->setDescendantsAreContiguousInStackingOrderDirty(true);
     }
 }
 
@@ -125,6 +139,10 @@
     ASSERT(m_layerListMutationAllowed);
     ASSERT(isStackingContainer());
 
+#if !ASSERT_DISABLED
+    updateStackingParentForZOrderLists(0);
+#endif
+
     if (m_posZOrderList)
         m_posZOrderList->clear();
     if (m_negZOrderList)
@@ -149,7 +167,7 @@
     // m_descendantsAreContiguousInStackingOrder for that sibling.
     dirtySiblingStackingNodeCanBePromotedToStackingContainer();
 
-    RenderLayerStackingNode* stackingContainerNode = layer()->ancestorStackingContainerNode();
+    RenderLayerStackingNode* stackingContainerNode = ancestorStackingContainerNode();
     if (stackingContainerNode)
         stackingContainerNode->dirtyZOrderLists();
 
@@ -158,7 +176,7 @@
     // of composited scrolling. It is important that we make our stacking
     // context aware of these z-order changes so the appropriate updating can
     // happen.
-    RenderLayerStackingNode* stackingNode = layer()->ancestorStackingNode();
+    RenderLayerStackingNode* stackingNode = ancestorStackingNode();
     if (stackingNode && stackingNode != stackingContainerNode)
         stackingNode->dirtyZOrderLists();
 }
@@ -167,6 +185,10 @@
 {
     ASSERT(m_layerListMutationAllowed);
 
+#if !ASSERT_DISABLED
+    updateStackingParentForNormalFlowList(0);
+#endif
+
     if (m_normalFlowList)
         m_normalFlowList->clear();
     m_normalFlowListDirty = true;
@@ -183,17 +205,22 @@
     ASSERT(m_layerListMutationAllowed);
     ASSERT(isDirtyStackingContainer());
     rebuildZOrderLists(m_posZOrderList, m_negZOrderList);
+
+#if !ASSERT_DISABLED
+    updateStackingParentForZOrderLists(this);
+#endif
+
     m_zOrderListsDirty = false;
 }
 
-void RenderLayerStackingNode::rebuildZOrderLists(OwnPtr<Vector<RenderLayer*> >& posZOrderList,
-    OwnPtr<Vector<RenderLayer*> >& negZOrderList, const RenderLayer* layerToForceAsStackingContainer,
+void RenderLayerStackingNode::rebuildZOrderLists(OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList,
+    OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList, const RenderLayerStackingNode* nodeToForceAsStackingContainer,
     CollectLayersBehavior collectLayersBehavior)
 {
     bool includeHiddenLayers = compositor()->inCompositingMode();
     for (RenderLayer* child = layer()->firstChild(); child; child = child->nextSibling()) {
-        if (!layer()->reflection() || layer()->reflectionLayer() != child)
-            child->stackingNode()->collectLayers(includeHiddenLayers, posZOrderList, negZOrderList, layerToForceAsStackingContainer, collectLayersBehavior);
+        if (!layer()->reflectionInfo() || layer()->reflectionInfo()->reflectionLayer() != child)
+            child->stackingNode()->collectLayers(includeHiddenLayers, posZOrderList, negZOrderList, nodeToForceAsStackingContainer, collectLayersBehavior);
     }
 
     // Sort the two lists.
@@ -213,8 +240,8 @@
                 RenderLayer* layer = toRenderLayerModelObject(child)->layer();
                 // Create the buffer if it doesn't exist yet.
                 if (!posZOrderList)
-                    posZOrderList = adoptPtr(new Vector<RenderLayer*>);
-                posZOrderList->append(layer);
+                    posZOrderList = adoptPtr(new Vector<RenderLayerStackingNode*>);
+                posZOrderList->append(layer->stackingNode());
             }
         }
     }
@@ -229,19 +256,23 @@
 
     for (RenderLayer* child = layer()->firstChild(); child; child = child->nextSibling()) {
         // Ignore non-overflow layers and reflections.
-        if (child->stackingNode()->isNormalFlowOnly() && (!layer()->reflection() || layer()->reflectionLayer() != child)) {
+        if (child->stackingNode()->isNormalFlowOnly() && (!layer()->reflectionInfo() || layer()->reflectionInfo()->reflectionLayer() != child)) {
             if (!m_normalFlowList)
-                m_normalFlowList = adoptPtr(new Vector<RenderLayer*>);
-            m_normalFlowList->append(child);
+                m_normalFlowList = adoptPtr(new Vector<RenderLayerStackingNode*>);
+            m_normalFlowList->append(child->stackingNode());
         }
     }
 
+#if !ASSERT_DISABLED
+    updateStackingParentForNormalFlowList(this);
+#endif
+
     m_normalFlowListDirty = false;
 }
 
 void RenderLayerStackingNode::collectLayers(bool includeHiddenLayers,
-    OwnPtr<Vector<RenderLayer*> >& posBuffer, OwnPtr<Vector<RenderLayer*> >& negBuffer,
-    const RenderLayer* layerToForceAsStackingContainer, CollectLayersBehavior collectLayersBehavior)
+    OwnPtr<Vector<RenderLayerStackingNode*> >& posBuffer, OwnPtr<Vector<RenderLayerStackingNode*> >& negBuffer,
+    const RenderLayerStackingNode* nodeToForceAsStackingContainer, CollectLayersBehavior collectLayersBehavior)
 {
     if (layer()->isInTopLayer())
         return;
@@ -253,8 +284,8 @@
 
     switch (collectLayersBehavior) {
     case ForceLayerToStackingContainer:
-        ASSERT(layerToForceAsStackingContainer);
-        if (layer() == layerToForceAsStackingContainer) {
+        ASSERT(nodeToForceAsStackingContainer);
+        if (this == nodeToForceAsStackingContainer) {
             isStacking = true;
             isNormalFlow = false;
         } else {
@@ -263,7 +294,7 @@
         }
         break;
     case OverflowScrollCanBeStackingContainers:
-        ASSERT(!layerToForceAsStackingContainer);
+        ASSERT(!nodeToForceAsStackingContainer);
         isStacking = isStackingContainer();
         isNormalFlow = isNormalFlowOnly();
         break;
@@ -277,14 +308,14 @@
     bool includeHiddenLayer = includeHiddenLayers || (layer()->hasVisibleContent() || (layer()->hasVisibleDescendant() && isStacking));
     if (includeHiddenLayer && !isNormalFlow && !layer()->isOutOfFlowRenderFlowThread()) {
         // Determine which buffer the child should be in.
-        OwnPtr<Vector<RenderLayer*> >& buffer = (zIndex() >= 0) ? posBuffer : negBuffer;
+        OwnPtr<Vector<RenderLayerStackingNode*> >& buffer = (zIndex() >= 0) ? posBuffer : negBuffer;
 
         // Create the buffer if it doesn't exist yet.
         if (!buffer)
-            buffer = adoptPtr(new Vector<RenderLayer*>);
+            buffer = adoptPtr(new Vector<RenderLayerStackingNode*>);
 
         // Append ourselves at the end of the appropriate buffer.
-        buffer->append(layer());
+        buffer->append(this);
     }
 
     // Recur into our children to collect more layers, but only if we don't establish
@@ -292,21 +323,68 @@
     if ((includeHiddenLayers || layer()->hasVisibleDescendant()) && !isStacking) {
         for (RenderLayer* child = layer()->firstChild(); child; child = child->nextSibling()) {
             // Ignore reflections.
-            if (!layer()->reflection() || layer()->reflectionLayer() != child)
-                child->stackingNode()->collectLayers(includeHiddenLayers, posBuffer, negBuffer, layerToForceAsStackingContainer, collectLayersBehavior);
+            if (!layer()->reflectionInfo() || layer()->reflectionInfo()->reflectionLayer() != child)
+                child->stackingNode()->collectLayers(includeHiddenLayers, posBuffer, negBuffer, nodeToForceAsStackingContainer, collectLayersBehavior);
         }
     }
 }
 
+#if !ASSERT_DISABLED
+bool RenderLayerStackingNode::isInStackingParentZOrderLists() const
+{
+    if (!m_stackingParent || m_stackingParent->zOrderListsDirty())
+        return false;
+
+    if (m_stackingParent->posZOrderList() && m_stackingParent->posZOrderList()->find(this) != kNotFound)
+        return true;
+
+    if (m_stackingParent->negZOrderList() && m_stackingParent->negZOrderList()->find(this) != kNotFound)
+        return true;
+
+    return false;
+}
+
+bool RenderLayerStackingNode::isInStackingParentNormalFlowList() const
+{
+    if (!m_stackingParent || m_stackingParent->normalFlowListDirty())
+        return false;
+
+    return (m_stackingParent->normalFlowList() && m_stackingParent->normalFlowList()->find(this) != kNotFound);
+}
+
+void RenderLayerStackingNode::updateStackingParentForZOrderLists(RenderLayerStackingNode* stackingParent)
+{
+    if (m_posZOrderList) {
+        for (size_t i = 0; i < m_posZOrderList->size(); ++i)
+            m_posZOrderList->at(i)->setStackingParent(stackingParent);
+    }
+
+    if (m_negZOrderList) {
+        for (size_t i = 0; i < m_negZOrderList->size(); ++i)
+            m_negZOrderList->at(i)->setStackingParent(stackingParent);
+    }
+}
+
+void RenderLayerStackingNode::updateStackingParentForNormalFlowList(RenderLayerStackingNode* stackingParent)
+{
+    if (m_normalFlowList) {
+        for (size_t i = 0; i < m_normalFlowList->size(); ++i)
+            m_normalFlowList->at(i)->setStackingParent(stackingParent);
+    }
+}
+#endif
+
 void RenderLayerStackingNode::updateLayerListsIfNeeded()
 {
     updateZOrderLists();
     updateNormalFlowList();
 
-    if (RenderLayer* reflectionLayer = layer()->reflectionLayer()) {
-        reflectionLayer->stackingNode()->updateZOrderLists();
-        reflectionLayer->stackingNode()->updateNormalFlowList();
-    }
+    if (!layer()->reflectionInfo())
+        return;
+
+    RenderLayer* reflectionLayer = layer()->reflectionInfo()->reflectionLayer();
+    reflectionLayer->stackingNode()->updateZOrderLists();
+    reflectionLayer->stackingNode()->updateNormalFlowList();
 }
 
 void RenderLayerStackingNode::updateStackingNodesAfterStyleChange(const RenderStyle* oldStyle)
@@ -389,46 +467,46 @@
     if (!currentLayer->scrollsOverflow())
         return;
 
-    RenderLayerStackingNode* ancestorStackingNode = currentLayer->ancestorStackingNode();
-    if (!ancestorStackingNode)
+    RenderLayerStackingNode* stackingNode = ancestorStackingNode();
+    if (!stackingNode)
         return;
 
-    OwnPtr<Vector<RenderLayer*> > posZOrderListBeforePromote = adoptPtr(new Vector<RenderLayer*>);
-    OwnPtr<Vector<RenderLayer*> > negZOrderListBeforePromote = adoptPtr(new Vector<RenderLayer*>);
-    OwnPtr<Vector<RenderLayer*> > posZOrderListAfterPromote = adoptPtr(new Vector<RenderLayer*>);
-    OwnPtr<Vector<RenderLayer*> > negZOrderListAfterPromote = adoptPtr(new Vector<RenderLayer*>);
+    OwnPtr<Vector<RenderLayerStackingNode*> > posZOrderListBeforePromote = adoptPtr(new Vector<RenderLayerStackingNode*>);
+    OwnPtr<Vector<RenderLayerStackingNode*> > negZOrderListBeforePromote = adoptPtr(new Vector<RenderLayerStackingNode*>);
+    OwnPtr<Vector<RenderLayerStackingNode*> > posZOrderListAfterPromote = adoptPtr(new Vector<RenderLayerStackingNode*>);
+    OwnPtr<Vector<RenderLayerStackingNode*> > negZOrderListAfterPromote = adoptPtr(new Vector<RenderLayerStackingNode*>);
 
-    collectBeforePromotionZOrderList(ancestorStackingNode, posZOrderListBeforePromote, negZOrderListBeforePromote);
-    collectAfterPromotionZOrderList(ancestorStackingNode, posZOrderListAfterPromote, negZOrderListAfterPromote);
+    collectBeforePromotionZOrderList(stackingNode, posZOrderListBeforePromote, negZOrderListBeforePromote);
+    collectAfterPromotionZOrderList(stackingNode, posZOrderListAfterPromote, negZOrderListAfterPromote);
 
     size_t maxIndex = std::min(posZOrderListAfterPromote->size() + negZOrderListAfterPromote->size(), posZOrderListBeforePromote->size() + negZOrderListBeforePromote->size());
 
     m_descendantsAreContiguousInStackingOrderDirty = false;
     m_descendantsAreContiguousInStackingOrder = false;
 
-    const RenderLayer* layerAfterPromote = 0;
-    for (size_t i = 0; i < maxIndex && layerAfterPromote != currentLayer; ++i) {
-        const RenderLayer* layerBeforePromote = i < negZOrderListBeforePromote->size()
+    const RenderLayerStackingNode* nodeAfterPromote = 0;
+    for (size_t i = 0; i < maxIndex && nodeAfterPromote != this; ++i) {
+        const RenderLayerStackingNode* nodeBeforePromote = i < negZOrderListBeforePromote->size()
             ? negZOrderListBeforePromote->at(i)
             : posZOrderListBeforePromote->at(i - negZOrderListBeforePromote->size());
-        layerAfterPromote = i < negZOrderListAfterPromote->size()
+        nodeAfterPromote = i < negZOrderListAfterPromote->size()
             ? negZOrderListAfterPromote->at(i)
             : posZOrderListAfterPromote->at(i - negZOrderListAfterPromote->size());
 
-        if (layerBeforePromote != layerAfterPromote && (layerAfterPromote != currentLayer || renderer()->hasBackground()))
+        if (nodeBeforePromote != nodeAfterPromote && (nodeAfterPromote != this || renderer()->hasBackground()))
             return;
     }
 
-    layerAfterPromote = 0;
-    for (size_t i = 0; i < maxIndex && layerAfterPromote != currentLayer; ++i) {
-        const RenderLayer* layerBeforePromote = i < posZOrderListBeforePromote->size()
+    nodeAfterPromote = 0;
+    for (size_t i = 0; i < maxIndex && nodeAfterPromote != this; ++i) {
+        const RenderLayerStackingNode* nodeBeforePromote = i < posZOrderListBeforePromote->size()
             ? posZOrderListBeforePromote->at(posZOrderListBeforePromote->size() - i - 1)
             : negZOrderListBeforePromote->at(negZOrderListBeforePromote->size() + posZOrderListBeforePromote->size() - i - 1);
-        layerAfterPromote = i < posZOrderListAfterPromote->size()
+        nodeAfterPromote = i < posZOrderListAfterPromote->size()
             ? posZOrderListAfterPromote->at(posZOrderListAfterPromote->size() - i - 1)
             : negZOrderListAfterPromote->at(negZOrderListAfterPromote->size() + posZOrderListAfterPromote->size() - i - 1);
 
-        if (layerBeforePromote != layerAfterPromote && layerAfterPromote != currentLayer)
+        if (nodeBeforePromote != nodeAfterPromote && nodeAfterPromote != this)
             return;
     }
 
@@ -436,9 +514,9 @@
 }
 
 void RenderLayerStackingNode::collectBeforePromotionZOrderList(RenderLayerStackingNode* ancestorStackingNode,
-    OwnPtr<Vector<RenderLayer*> >& posZOrderList, OwnPtr<Vector<RenderLayer*> >& negZOrderList)
+    OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList, OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList)
 {
-    ancestorStackingNode->rebuildZOrderLists(posZOrderList, negZOrderList, layer(), OnlyStackingContextsCanBeStackingContainers);
+    ancestorStackingNode->rebuildZOrderLists(posZOrderList, negZOrderList, this, OnlyStackingContextsCanBeStackingContainers);
 
     const RenderLayer* currentLayer = layer();
     const RenderLayer* positionedAncestor = currentLayer->parent();
@@ -448,30 +526,30 @@
         positionedAncestor = 0;
 
     if (!posZOrderList)
-        posZOrderList = adoptPtr(new Vector<RenderLayer*>());
-    else if (posZOrderList->find(currentLayer) != kNotFound)
+        posZOrderList = adoptPtr(new Vector<RenderLayerStackingNode*>());
+    else if (posZOrderList->find(this) != kNotFound)
         return;
 
-    // The current layer will appear in the z-order lists after promotion, so
+    // The current node will appear in the z-order lists after promotion, so
     // for a meaningful comparison, we must insert it in the z-order lists
     // before promotion if it does not appear there already.
     if (!positionedAncestor) {
-        posZOrderList->prepend(layer());
+        posZOrderList->prepend(this);
         return;
     }
 
     for (size_t index = 0; index < posZOrderList->size(); index++) {
-        if (posZOrderList->at(index) == positionedAncestor) {
-            posZOrderList->insert(index + 1, layer());
+        if (posZOrderList->at(index)->layer() == positionedAncestor) {
+            posZOrderList->insert(index + 1, this);
             return;
         }
     }
 }
 
 void RenderLayerStackingNode::collectAfterPromotionZOrderList(RenderLayerStackingNode* ancestorStackingNode,
-    OwnPtr<Vector<RenderLayer*> >& posZOrderList, OwnPtr<Vector<RenderLayer*> >& negZOrderList)
+    OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList, OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList)
 {
-    ancestorStackingNode->rebuildZOrderLists(posZOrderList, negZOrderList, layer(), ForceLayerToStackingContainer);
+    ancestorStackingNode->rebuildZOrderLists(posZOrderList, negZOrderList, this, ForceLayerToStackingContainer);
 }
 
 // Compute what positive and negative z-order lists would look like before and
@@ -504,10 +582,10 @@
 //
 void RenderLayerStackingNode::computePaintOrderList(PaintOrderListType type, Vector<RefPtr<Node> >& list)
 {
-    OwnPtr<Vector<RenderLayer*> > posZOrderList;
-    OwnPtr<Vector<RenderLayer*> > negZOrderList;
+    OwnPtr<Vector<RenderLayerStackingNode*> > posZOrderList;
+    OwnPtr<Vector<RenderLayerStackingNode*> > negZOrderList;
 
-    RenderLayerStackingNode* stackingNode = layer()->ancestorStackingNode();
+    RenderLayerStackingNode* stackingNode = ancestorStackingNode();
     if (!stackingNode)
         return;
 
@@ -533,7 +611,7 @@
 
 bool RenderLayerStackingNode::descendantsAreContiguousInStackingOrder() const
 {
-    if (isStackingContext() || !layer()->ancestorStackingContainerLayer())
+    if (isStackingContext() || !ancestorStackingContainerNode())
         return true;
 
     ASSERT(!m_descendantsAreContiguousInStackingOrderDirty);
@@ -549,7 +627,7 @@
     // containers some point. This should be recorded at most once per
     // RenderLayer, so we check m_needsToBeStackingContainerHasBeenRecorded.
     if (layer()->acceleratedCompositingForOverflowScrollEnabled() && !m_needsToBeStackingContainerHasBeenRecorded) {
-        HistogramSupport::histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::NeedsToBeStackingContainerBucket, RenderLayer::CompositedScrollingHistogramMax);
+        WebKit::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::NeedsToBeStackingContainerBucket, RenderLayer::CompositedScrollingHistogramMax);
         m_needsToBeStackingContainerHasBeenRecorded = true;
     }
 
@@ -558,6 +636,26 @@
     return true;
 }
 
+RenderLayerStackingNode* RenderLayerStackingNode::ancestorStackingContainerNode() const
+{
+    RenderLayer* ancestor = layer()->parent();
+    while (ancestor && !ancestor->stackingNode()->isStackingContainer())
+        ancestor = ancestor->parent();
+    if (ancestor)
+        return ancestor->stackingNode();
+    return 0;
+}
+
+RenderLayerStackingNode* RenderLayerStackingNode::ancestorStackingNode() const
+{
+    RenderLayer* ancestor = layer()->parent();
+    while (ancestor && !ancestor->stackingNode()->isStackingContext())
+        ancestor = ancestor->parent();
+    if (ancestor)
+        return ancestor->stackingNode();
+    return 0;
+}
+
 RenderLayerModelObject* RenderLayerStackingNode::renderer() const
 {
     return m_layer->renderer();
diff --git a/Source/core/rendering/RenderLayerStackingNode.h b/Source/core/rendering/RenderLayerStackingNode.h
index 386e607..573ac69 100644
--- a/Source/core/rendering/RenderLayerStackingNode.h
+++ b/Source/core/rendering/RenderLayerStackingNode.h
@@ -61,6 +61,7 @@
     WTF_MAKE_NONCOPYABLE(RenderLayerStackingNode);
 public:
     explicit RenderLayerStackingNode(RenderLayer*);
+    ~RenderLayerStackingNode();
 
     int zIndex() const { return renderer()->style()->zIndex(); }
 
@@ -90,7 +91,8 @@
     void clearZOrderLists();
     void dirtyStackingContainerZOrderLists();
 
-    Vector<RenderLayer*>* posZOrderList() const
+    // FIXME: These accessors should be made private and callers moved to RenderLayerStackingNodeIterator.
+    Vector<RenderLayerStackingNode*>* posZOrderList() const
     {
         ASSERT(!m_zOrderListsDirty);
         ASSERT(isStackingContainer() || !m_posZOrderList);
@@ -99,7 +101,7 @@
 
     bool hasNegativeZOrderList() const { return negZOrderList() && negZOrderList()->size(); }
 
-    Vector<RenderLayer*>* negZOrderList() const
+    Vector<RenderLayerStackingNode*>* negZOrderList() const
     {
         ASSERT(!m_zOrderListsDirty);
         ASSERT(isStackingContainer() || !m_negZOrderList);
@@ -110,7 +112,7 @@
     void updateIsNormalFlowOnly();
     bool normalFlowListDirty() const { return m_normalFlowListDirty; }
     void dirtyNormalFlowList();
-    Vector<RenderLayer*>* normalFlowList() const
+    Vector<RenderLayerStackingNode*>* normalFlowList() const
     {
         ASSERT(!m_normalFlowListDirty);
         return m_normalFlowList.get();
@@ -121,6 +123,15 @@
 
     void updateStackingNodesAfterStyleChange(const RenderStyle* oldStyle);
 
+    RenderLayerStackingNode* ancestorStackingContainerNode() const;
+    RenderLayerStackingNode* ancestorStackingNode() const;
+
+    // Gets the enclosing stacking container for this node, possibly the node
+    // itself, if it is a stacking container.
+    RenderLayerStackingNode* enclosingStackingContainerNode() { return isStackingContainer() ? this : ancestorStackingContainerNode(); }
+
+    RenderLayer* layer() const { return m_layer; }
+
 #if !ASSERT_DISABLED
     bool layerListMutationAllowed() const { return m_layerListMutationAllowed; }
     void setLayerListMutationAllowed(bool flag) { m_layerListMutationAllowed = flag; }
@@ -141,14 +152,22 @@
     // post-promotion layer lists, by allowing us to treat a layer as if it is a
     // stacking context, without adding a new member to RenderLayer or modifying
     // the style (which could cause extra allocations).
-    void rebuildZOrderLists(OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&,
-        const RenderLayer* layerToForceAsStackingContainer = 0,
+    void rebuildZOrderLists(OwnPtr<Vector<RenderLayerStackingNode*> >&, OwnPtr<Vector<RenderLayerStackingNode*> >&,
+        const RenderLayerStackingNode* nodeToForceAsStackingContainer = 0,
         CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
 
-    void collectLayers(bool includeHiddenLayers, OwnPtr<Vector<RenderLayer*> >&,
-        OwnPtr<Vector<RenderLayer*> >&, const RenderLayer* layerToForceAsStackingContainer = 0,
+    void collectLayers(bool includeHiddenLayers, OwnPtr<Vector<RenderLayerStackingNode*> >&,
+        OwnPtr<Vector<RenderLayerStackingNode*> >&, const RenderLayerStackingNode* nodeToForceAsStackingContainer = 0,
         CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
 
+#if !ASSERT_DISABLED
+    bool isInStackingParentZOrderLists() const;
+    bool isInStackingParentNormalFlowList() const;
+    void updateStackingParentForZOrderLists(RenderLayerStackingNode* stackingParent);
+    void updateStackingParentForNormalFlowList(RenderLayerStackingNode* stackingParent);
+    void setStackingParent(RenderLayerStackingNode* stackingParent) { m_stackingParent = stackingParent; }
+#endif
+
     bool shouldBeNormalFlowOnly() const;
     bool shouldBeNormalFlowOnlyIgnoringCompositedScrolling() const;
 
@@ -158,31 +177,28 @@
     void dirtySiblingStackingNodeCanBePromotedToStackingContainer();
 
     void collectBeforePromotionZOrderList(RenderLayerStackingNode*,
-        OwnPtr<Vector<RenderLayer*> >& posZOrderList, OwnPtr<Vector<RenderLayer*> >& negZOrderList);
+        OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList, OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList);
     void collectAfterPromotionZOrderList(RenderLayerStackingNode*,
-        OwnPtr<Vector<RenderLayer*> >& posZOrderList, OwnPtr<Vector<RenderLayer*> >& negZOrderList);
+        OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList, OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList);
 
     bool isDirtyStackingContainer() const { return m_zOrderListsDirty && isStackingContainer(); }
 
     RenderLayerCompositor* compositor() const;
-    RenderLayer* layer() const { return m_layer; }
     // FIXME: Investigate changing this to Renderbox.
     RenderLayerModelObject* renderer() const;
 
     RenderLayer* m_layer;
 
-    // For layers that establish stacking contexts, m_posZOrderList holds a sorted list of all the
-    // descendant layers within the stacking context that have z-indices of 0 or greater
+    // For stacking contexts, m_posZOrderList holds a sorted list of all the
+    // descendant nodes within the stacking context that have z-indices of 0 or greater
     // (auto will count as 0). m_negZOrderList holds descendants within our stacking context with negative
     // z-indices.
-    OwnPtr<Vector<RenderLayer*> > m_posZOrderList;
-    OwnPtr<Vector<RenderLayer*> > m_negZOrderList;
+    OwnPtr<Vector<RenderLayerStackingNode*> > m_posZOrderList;
+    OwnPtr<Vector<RenderLayerStackingNode*> > m_negZOrderList;
 
-    // This list contains child layers that cannot create stacking contexts. For now it is just
+    // This list contains child nodes that cannot create stacking contexts. For now it is just
     // overflow layers, but that may change in the future.
-    // FIXME: This should be a vector of RenderLayerStackingNodes or
-    // RenderObjects, not RenderLayers.
-    OwnPtr<Vector<RenderLayer*> > m_normalFlowList;
+    OwnPtr<Vector<RenderLayerStackingNode*> > m_normalFlowList;
 
     // If this is true, then no non-descendant appears between any of our
     // descendants in stacking order. This is one of the requirements of being
@@ -199,6 +215,7 @@
 
 #if !ASSERT_DISABLED
     unsigned m_layerListMutationAllowed : 1;
+    RenderLayerStackingNode* m_stackingParent;
 #endif
 };
 
@@ -206,6 +223,10 @@
 {
     ASSERT(!isStackingContainer());
 
+#if !ASSERT_DISABLED
+    updateStackingParentForZOrderLists(0);
+#endif
+
     m_posZOrderList.clear();
     m_negZOrderList.clear();
 }
diff --git a/Source/core/rendering/RenderLayerStackingNodeIterator.cpp b/Source/core/rendering/RenderLayerStackingNodeIterator.cpp
new file mode 100644
index 0000000..d523c20
--- /dev/null
+++ b/Source/core/rendering/RenderLayerStackingNodeIterator.cpp
@@ -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:
+ *
+ *     * 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/rendering/RenderLayerStackingNodeIterator.h"
+
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderLayerStackingNode.h"
+
+namespace WebCore {
+
+RenderLayerStackingNode* RenderLayerStackingNodeIterator::next()
+{
+    if (m_remainingChildren & NegativeZOrderChildren) {
+        Vector<RenderLayerStackingNode*>* negZOrderList = m_root.negZOrderList();
+        if (negZOrderList && m_index < negZOrderList->size())
+            return negZOrderList->at(m_index++);
+
+        m_index = 0;
+        m_remainingChildren &= ~NegativeZOrderChildren;
+    }
+
+    if (m_remainingChildren & NormalFlowChildren) {
+        Vector<RenderLayerStackingNode*>* normalFlowList = m_root.normalFlowList();
+        if (normalFlowList && m_index < normalFlowList->size())
+            return normalFlowList->at(m_index++);
+
+        m_index = 0;
+        m_remainingChildren &= ~NormalFlowChildren;
+    }
+
+    if (m_remainingChildren & PositiveZOrderChildren) {
+        Vector<RenderLayerStackingNode*>* posZOrderList = m_root.posZOrderList();
+        if (posZOrderList && m_index < posZOrderList->size())
+            return posZOrderList->at(m_index++);
+
+        m_index = 0;
+        m_remainingChildren &= ~PositiveZOrderChildren;
+    }
+
+    return 0;
+}
+
+} // namespace WebCore
diff --git a/Source/core/rendering/RenderingNodeProxy.h b/Source/core/rendering/RenderLayerStackingNodeIterator.h
similarity index 66%
copy from Source/core/rendering/RenderingNodeProxy.h
copy to Source/core/rendering/RenderLayerStackingNodeIterator.h
index ac5cb6d..67abde5 100644
--- a/Source/core/rendering/RenderingNodeProxy.h
+++ b/Source/core/rendering/RenderLayerStackingNodeIterator.h
@@ -28,44 +28,41 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef RenderingNodeProxy_h
-#define RenderingNodeProxy_h
+#ifndef RenderLayerStackingNodeIterator_h
+#define RenderLayerStackingNodeIterator_h
 
-#include "core/rendering/LayoutIndicator.h"
 #include "wtf/Noncopyable.h"
 
 namespace WebCore {
 
-class QualifiedName;
-class Node;
-
-#define STRICT_LAYOUT_THREADING 0
-
-class RenderingNodeProxy {
-    WTF_MAKE_NONCOPYABLE(RenderingNodeProxy);
-public:
-    explicit RenderingNodeProxy(Node*);
-    ~RenderingNodeProxy();
-
-    bool hasTagName(const QualifiedName&) const;
-
-    Node* unsafeNode() const
-    {
-#if STRICT_LAYOUT_THREADING
-        ASSERT(!LayoutIndicator::inLayout());
-#endif
-        return m_node;
-    }
-
-    void clear() { m_node = 0; }
-    void set(Node* node) { m_node = node; }
-
-private:
-    Node* m_node;
+enum ChildrenIteration {
+    NegativeZOrderChildren = 1,
+    NormalFlowChildren = 1 << 1,
+    PositiveZOrderChildren = 1 << 2,
+    AllChildren = NegativeZOrderChildren | NormalFlowChildren | PositiveZOrderChildren
 };
 
-#undef STRICT_LAYOUT_THREADING
+class RenderLayer;
+class RenderLayerStackingNode;
 
-}
+class RenderLayerStackingNodeIterator {
+    WTF_MAKE_NONCOPYABLE(RenderLayerStackingNodeIterator);
+public:
+    RenderLayerStackingNodeIterator(const RenderLayerStackingNode& root, unsigned whichChildren)
+        : m_root(root)
+        , m_remainingChildren(whichChildren)
+        , m_index(0)
+    {
+    }
 
-#endif // RenderingNodeProxy_h
+    RenderLayerStackingNode* next();
+
+private:
+    const RenderLayerStackingNode& m_root;
+    unsigned m_remainingChildren;
+    unsigned m_index;
+};
+
+} // namespace WebCore
+
+#endif // RenderLayerStackingNodeIterator_h
diff --git a/Source/core/rendering/RenderListBox.cpp b/Source/core/rendering/RenderListBox.cpp
index b0a9637..6892283 100644
--- a/Source/core/rendering/RenderListBox.cpp
+++ b/Source/core/rendering/RenderListBox.cpp
@@ -274,7 +274,9 @@
 
 LayoutRect RenderListBox::itemBoundingBoxRect(const LayoutPoint& additionalOffset, int index)
 {
-    return LayoutRect(additionalOffset.x() + borderLeft() + paddingLeft(),
+    // For RTL, items start after the left-side vertical scrollbar.
+    int scrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? m_vBar->width() : 0;
+    return LayoutRect(additionalOffset.x() + borderLeft() + paddingLeft() + scrollbarOffset,
         additionalOffset.y() + borderTop() + paddingTop() + itemHeight() * (index - m_indexOffset),
         contentWidth(), itemHeight());
 }
@@ -348,10 +350,20 @@
     }
 }
 
+int RenderListBox::scrollbarLeft() const
+{
+    int scrollbarLeft = 0;
+    if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+        scrollbarLeft = borderLeft();
+    else
+        scrollbarLeft = width() - borderRight() - m_vBar->width();
+    return scrollbarLeft;
+}
+
 void RenderListBox::paintScrollbar(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     if (m_vBar) {
-        IntRect scrollRect = pixelSnappedIntRect(paintOffset.x() + width() - borderRight() - m_vBar->width(),
+        IntRect scrollRect = pixelSnappedIntRect(paintOffset.x() + scrollbarLeft(),
             paintOffset.y() + borderTop(),
             m_vBar->width(),
             height() - (borderTop() + borderBottom()));
@@ -461,7 +473,7 @@
     if (!m_vBar || !m_vBar->shouldParticipateInHitTesting())
         return false;
 
-    LayoutRect vertRect(accumulatedOffset.x() + width() - borderRight() - m_vBar->width(),
+    LayoutRect vertRect(accumulatedOffset.x() + scrollbarLeft(),
                         accumulatedOffset.y() + borderTop(),
                         m_vBar->width(),
                         height() - borderTop() - borderBottom());
@@ -482,7 +494,10 @@
         return -1;
 
     int scrollbarWidth = m_vBar ? m_vBar->width() : 0;
-    if (offset.width() < borderLeft() + paddingLeft() || offset.width() > width() - borderRight() - paddingRight() - scrollbarWidth)
+    int rightScrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? scrollbarWidth : 0;
+    int leftScrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? 0 : scrollbarWidth;
+    if (offset.width() < borderLeft() + paddingLeft() + rightScrollbarOffset
+        || offset.width() > width() - borderRight() - paddingRight() - leftScrollbarOffset)
         return -1;
 
     int newOffset = (offset.height() - borderTop() - paddingTop()) / itemHeight() + m_indexOffset;
@@ -498,7 +513,7 @@
     // FIXME: This doesn't work correctly with transforms.
     FloatPoint absOffset = localToAbsolute();
 
-    IntPoint lastKnownMousePosition = frame()->eventHandler()->lastKnownMousePosition();
+    IntPoint lastKnownMousePosition = frame()->eventHandler().lastKnownMousePosition();
     // We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
     static IntPoint previousMousePosition;
     if (lastKnownMousePosition.y() < 0)
@@ -555,7 +570,7 @@
 
 void RenderListBox::autoscroll(const IntPoint&)
 {
-    IntPoint pos = frame()->view()->windowToContents(frame()->eventHandler()->lastKnownMousePosition());
+    IntPoint pos = frame()->view()->windowToContents(frame()->eventHandler().lastKnownMousePosition());
 
     int endIndex = scrollToward(pos);
     if (selectElement()->isDisabledFormControl())
@@ -713,7 +728,10 @@
 LayoutRect RenderListBox::controlClipRect(const LayoutPoint& additionalOffset) const
 {
     LayoutRect clipRect = contentBoxRect();
-    clipRect.moveBy(additionalOffset);
+    if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+        clipRect.moveBy(additionalOffset + LayoutPoint(m_vBar->width(), 0));
+    else
+        clipRect.moveBy(additionalOffset);
     return clipRect;
 }
 
@@ -726,7 +744,10 @@
 void RenderListBox::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
 {
     IntRect scrollRect = rect;
-    scrollRect.move(width() - borderRight() - scrollbar->width(), borderTop());
+    if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+        scrollRect.move(borderLeft(), borderTop());
+    else
+        scrollRect.move(width() - borderRight() - scrollbar->width(), borderTop());
     repaintRectangle(scrollRect);
 }
 
@@ -738,9 +759,8 @@
 
     IntRect rect = scrollbarRect;
 
-    int scrollbarLeft = width() - borderRight() - scrollbar->width();
     int scrollbarTop = borderTop();
-    rect.move(scrollbarLeft, scrollbarTop);
+    rect.move(scrollbarLeft(), scrollbarTop);
 
     return view->frameView()->convertFromRenderer(this, rect);
 }
@@ -753,9 +773,8 @@
 
     IntRect rect = view->frameView()->convertToRenderer(this, parentRect);
 
-    int scrollbarLeft = width() - borderRight() - scrollbar->width();
     int scrollbarTop = borderTop();
-    rect.move(-scrollbarLeft, -scrollbarTop);
+    rect.move(-scrollbarLeft(), -scrollbarTop);
     return rect;
 }
 
@@ -767,9 +786,8 @@
 
     IntPoint point = scrollbarPoint;
 
-    int scrollbarLeft = width() - borderRight() - scrollbar->width();
     int scrollbarTop = borderTop();
-    point.move(scrollbarLeft, scrollbarTop);
+    point.move(scrollbarLeft(), scrollbarTop);
 
     return view->frameView()->convertFromRenderer(this, point);
 }
@@ -782,9 +800,8 @@
 
     IntPoint point = view->frameView()->convertToRenderer(this, parentPoint);
 
-    int scrollbarLeft = width() - borderRight() - scrollbar->width();
     int scrollbarTop = borderTop();
-    point.move(-scrollbarLeft, -scrollbarTop);
+    point.move(-scrollbarLeft(), -scrollbarTop);
     return point;
 }
 
diff --git a/Source/core/rendering/RenderListBox.h b/Source/core/rendering/RenderListBox.h
index fb10ceb..54beab1 100644
--- a/Source/core/rendering/RenderListBox.h
+++ b/Source/core/rendering/RenderListBox.h
@@ -146,6 +146,7 @@
     int numVisibleItems() const;
     int numItems() const;
     LayoutUnit listHeight() const;
+    int scrollbarLeft() const;
     void paintScrollbar(PaintInfo&, const LayoutPoint&);
     void paintItemForeground(PaintInfo&, const LayoutPoint&, int listIndex);
     void paintItemBackground(PaintInfo&, const LayoutPoint&, int listIndex);
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index 0f0f7ac..3d954cb 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -76,6 +76,7 @@
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/ContentData.h"
 #include "core/rendering/style/CursorList.h"
+#include "core/rendering/style/ShadowList.h"
 #include "core/rendering/svg/SVGRenderSupport.h"
 #include "platform/Partitions.h"
 #include "platform/geometry/FloatQuad.h"
@@ -225,7 +226,7 @@
 RenderObject::RenderObject(Node* node)
     : ImageResourceClient()
     , m_style(0)
-    , m_nodeProxy(node)
+    , m_node(node)
     , m_parent(0)
     , m_previous(0)
     , m_next(0)
@@ -575,11 +576,11 @@
 
 bool RenderObject::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
 {
-    RenderLayer* enclosingLayer = this->enclosingLayer();
-    if (!enclosingLayer)
+    RenderBox* enclosingBox = this->enclosingBox();
+    if (!enclosingBox)
         return false;
 
-    enclosingLayer->scrollRectToVisible(rect, alignX, alignY);
+    enclosingBox->scrollRectToVisible(rect, alignX, alignY);
     return true;
 }
 
@@ -874,8 +875,11 @@
     if (sizeType == SizeLength) {
         if (layer->sizeLength().width().isPercent() || layer->sizeLength().height().isPercent())
             return true;
-    } else if (img->usesImageContainerSize())
+        if (img->isGeneratedImage() && (layer->sizeLength().width().isAuto() || layer->sizeLength().height().isAuto()))
+            return true;
+    } else if (img->usesImageContainerSize()) {
         return true;
+    }
 
     return false;
 }
@@ -1375,7 +1379,7 @@
     if (parentRenderFlowThread) {
         // The ancestor document will do the reparenting when the repaint propagates further up.
         // We're just a seamless child document, and we don't need to do the hacking.
-        if (&parentRenderFlowThread && parentRenderFlowThread->document() != document())
+        if (parentRenderFlowThread->document() != document())
             return repaintContainer;
         // If we have already found a repaint container then we will repaint into that container only if it is part of the same
         // flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread.
@@ -2083,7 +2087,7 @@
 
     if (oldStyle && !areCursorsEqual(oldStyle, style())) {
         if (Frame* frame = this->frame())
-            frame->eventHandler()->scheduleCursorUpdate();
+            frame->eventHandler().scheduleCursorUpdate();
     }
 }
 
@@ -2555,11 +2559,6 @@
         children->destroyLeftoverChildren();
 
     // If this renderer is being autoscrolled, stop the autoscroll timer
-
-    // FIXME: RenderObject::destroy should not get called with a renderer whose document
-    // has a null frame, so we assert this. However, we don't want release builds to crash which is why we
-    // check that the frame is not null.
-    ASSERT(frame());
     if (Frame* frame = this->frame()) {
         if (frame->page())
             frame->page()->stopAutoscrollIfNeeded(this);
@@ -3122,7 +3121,7 @@
 void RenderObject::adjustRectForOutlineAndShadow(LayoutRect& rect) const
 {
     int outlineSize = outlineStyleForRepaint()->outlineSize();
-    if (const ShadowData* boxShadow = style()->boxShadow()) {
+    if (const ShadowList* boxShadow = style()->boxShadow()) {
         boxShadow->adjustRectForShadow(rect, outlineSize);
         return;
     }
diff --git a/Source/core/rendering/RenderObject.h b/Source/core/rendering/RenderObject.h
index 08a94f9..3a4da9a 100644
--- a/Source/core/rendering/RenderObject.h
+++ b/Source/core/rendering/RenderObject.h
@@ -34,7 +34,6 @@
 #include "core/rendering/LayoutIndicator.h"
 #include "core/rendering/PaintPhase.h"
 #include "core/rendering/RenderObjectChildList.h"
-#include "core/rendering/RenderingNodeProxy.h"
 #include "core/rendering/ScrollBehavior.h"
 #include "core/rendering/SubtreeLayoutScope.h"
 #include "core/rendering/style/RenderStyle.h"
@@ -141,6 +140,7 @@
 class RenderObject : public ImageResourceClient {
     friend class RenderBlock;
     friend class RenderLayer; // For setParent.
+    friend class RenderLayerReflectionInfo; // For setParent
     friend class RenderLayerScrollableArea; // For setParent.
     friend class RenderObjectChildList;
 public:
@@ -390,7 +390,7 @@
 
     virtual bool isRenderScrollbarPart() const { return false; }
 
-    bool isRoot() const { return document().documentElement() == m_nodeProxy.unsafeNode(); }
+    bool isRoot() const { return document().documentElement() == m_node; }
     bool isBody() const;
     bool isHR() const;
     bool isLegend() const;
@@ -602,7 +602,7 @@
     // Returns true if this renderer is rooted, and optionally returns the hosting view (the root of the hierarchy).
     bool isRooted(RenderView** = 0) const;
 
-    Node* node() const { return isAnonymous() ? 0 : m_nodeProxy.unsafeNode(); }
+    Node* node() const { return isAnonymous() ? 0 : m_node; }
     Node* nonPseudoNode() const
     {
         ASSERT(!LayoutIndicator::inLayout());
@@ -610,14 +610,14 @@
     }
 
     // FIXME: Why does RenderWidget need this?
-    void clearNode() { m_nodeProxy.clear(); }
+    void clearNode() { m_node = 0; }
 
     // Returns the styled node that caused the generation of this renderer.
     // This is the same as node() except for renderers of :before and :after
     // pseudo elements for which their parent node is returned.
     Node* generatingNode() const { return isPseudoElement() ? node()->parentOrShadowHostNode() : node(); }
 
-    Document& document() const { return m_nodeProxy.unsafeNode()->document(); }
+    Document& document() const { return m_node->document(); }
     Frame* frame() const { return document().frame(); }
 
     bool hasOutlineAnnotation() const;
@@ -1029,7 +1029,7 @@
     virtual void insertedIntoTree();
     virtual void willBeRemovedFromTree();
 
-    void setDocumentForAnonymous(Document* document) { ASSERT(isAnonymous()); m_nodeProxy.set(document); }
+    void setDocumentForAnonymous(Document* document) { ASSERT(isAnonymous()); m_node = document; }
 
     // Add hit-test rects for the render tree rooted at this node to the provided collection on a
     // per-RenderLayer basis.
@@ -1067,7 +1067,7 @@
 
     RefPtr<RenderStyle> m_style;
 
-    RenderingNodeProxy m_nodeProxy;
+    Node* m_node;
 
     RenderObject* m_parent;
     RenderObject* m_previous;
diff --git a/Source/core/rendering/RenderRegion.cpp b/Source/core/rendering/RenderRegion.cpp
index 31555f3..b53a28b 100644
--- a/Source/core/rendering/RenderRegion.cpp
+++ b/Source/core/rendering/RenderRegion.cpp
@@ -165,6 +165,13 @@
     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)
@@ -172,11 +179,14 @@
 
     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 for the selection and the foreground phase.
-    if (!isValid() || (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection))
+    // we allow the flow thread painting only in certain phases.
+    if (!shouldPaintRegionContentsInPhase(paintInfo.phase))
         return;
 
     setRegionObjectsRegionStyle();
@@ -240,9 +250,9 @@
     bool didHaveAutoLogicalHeight = m_hasAutoLogicalHeight;
     m_hasAutoLogicalHeight = shouldHaveAutoLogicalHeight();
     if (m_hasAutoLogicalHeight != didHaveAutoLogicalHeight) {
-        if (m_hasAutoLogicalHeight)
+        if (m_hasAutoLogicalHeight) {
             incrementAutoLogicalHeightCount();
-        else {
+        } else {
             clearComputedAutoHeight();
             decrementAutoLogicalHeightCount();
         }
@@ -292,9 +302,10 @@
             return;
         }
 
-        if (!isRenderRegionSet() && (oldRegionRect.width() != pageLogicalWidth() || oldRegionRect.height() != pageLogicalHeight()))
+        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
@@ -480,8 +491,9 @@
             objectStyleInRegion = it->value.style;
             ASSERT(it->value.cached);
             objectRegionStyleCached = true;
-        } else
+        } else {
             objectStyleInRegion = computeStyleInRegion(object);
+        }
 
         setObjectStyleInRegion(object, objectStyleInRegion, objectRegionStyleCached);
 
diff --git a/Source/core/rendering/RenderReplica.cpp b/Source/core/rendering/RenderReplica.cpp
index 5679d1b..169091a 100644
--- a/Source/core/rendering/RenderReplica.cpp
+++ b/Source/core/rendering/RenderReplica.cpp
@@ -81,8 +81,8 @@
         // 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();
-        RenderLayer::LayerPaintingInfo paintingInfo(rootPaintingLayer, paintInfo.rect, PaintBehaviorNormal, LayoutSize(), 0, paintInfo.renderRegion);
-        RenderLayer::PaintLayerFlags flags = RenderLayer::PaintLayerHaveTransparency | RenderLayer::PaintLayerAppliedTransform | RenderLayer::PaintLayerTemporaryClipRects | RenderLayer::PaintLayerPaintingReflection;
+        LayerPaintingInfo paintingInfo(rootPaintingLayer, paintInfo.rect, PaintBehaviorNormal, LayoutSize(), 0, paintInfo.renderRegion);
+        PaintLayerFlags flags = PaintLayerHaveTransparency | PaintLayerAppliedTransform | PaintLayerTemporaryClipRects | PaintLayerPaintingReflection;
         layer()->parent()->paintLayer(paintInfo.context, paintingInfo, flags);
     } else if (paintInfo.phase == PaintPhaseMask)
         paintMask(paintInfo, adjustedPaintOffset);
diff --git a/Source/core/rendering/RenderScrollbar.cpp b/Source/core/rendering/RenderScrollbar.cpp
index 6925a3d..a3aaeac 100644
--- a/Source/core/rendering/RenderScrollbar.cpp
+++ b/Source/core/rendering/RenderScrollbar.cpp
@@ -87,7 +87,7 @@
     return m_owner && m_owner->renderer() ? m_owner->renderer()->enclosingBox() : 0;
 }
 
-void RenderScrollbar::setParent(ScrollView* parent)
+void RenderScrollbar::setParent(Widget* parent)
 {
     Scrollbar::setParent(parent);
     if (!parent) {
diff --git a/Source/core/rendering/RenderScrollbar.h b/Source/core/rendering/RenderScrollbar.h
index a40ede8..198140c 100644
--- a/Source/core/rendering/RenderScrollbar.h
+++ b/Source/core/rendering/RenderScrollbar.h
@@ -60,7 +60,7 @@
     virtual bool isOverlayScrollbar() const { return false; }
 
 private:
-    virtual void setParent(ScrollView*);
+    virtual void setParent(Widget*) OVERRIDE;
     virtual void setEnabled(bool);
 
     virtual void paint(GraphicsContext*, const IntRect& damageRect);
diff --git a/Source/core/rendering/RenderTable.cpp b/Source/core/rendering/RenderTable.cpp
index 299fafb..4f8b9c1 100644
--- a/Source/core/rendering/RenderTable.cpp
+++ b/Source/core/rendering/RenderTable.cpp
@@ -89,6 +89,9 @@
     m_columnPos[0] = m_hSpacing;
 
     if (!m_tableLayout || style()->tableLayout() != oldTableLayout) {
+        if (m_tableLayout)
+            m_tableLayout->willChangeTableLayout();
+
         // According to the CSS2 spec, you only use fixed table layout if an
         // explicit width is specified on the table.  Auto width implies auto table layout.
         if (style()->tableLayout() == TFIXED && !style()->logicalWidth().isAuto())
diff --git a/Source/core/rendering/RenderTableSection.cpp b/Source/core/rendering/RenderTableSection.cpp
index 33b28e3..db5577a 100644
--- a/Source/core/rendering/RenderTableSection.cpp
+++ b/Source/core/rendering/RenderTableSection.cpp
@@ -478,7 +478,7 @@
     const unsigned rowSpan = cell->rowSpan();
     const unsigned rowIndex = cell->rowIndex();
 
-    ASSERT(rowSpan == spanningRowsHeight.rowHeight.size());
+    ASSERT_UNUSED(rowSpan, rowSpan == spanningRowsHeight.rowHeight.size());
 
     for (unsigned row = 0; row < spanningRowsHeight.rowHeight.size(); row++) {
         unsigned actualRow = row + rowIndex;
diff --git a/Source/core/rendering/RenderText.cpp b/Source/core/rendering/RenderText.cpp
index b53c969..dbee0a4 100644
--- a/Source/core/rendering/RenderText.cpp
+++ b/Source/core/rendering/RenderText.cpp
@@ -916,8 +916,6 @@
     // 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.
     float maxWordWidth = numeric_limits<float>::max();
-    int minimumPrefixLength = 0;
-    int minimumSuffixLength = 0;
     int firstGlyphLeftOverflow = -1;
 
     bool breakAll = (styleToUse->wordBreak() == BreakAllWordBreak || styleToUse->wordBreak() == BreakWordBreak) && styleToUse->autoWrap();
diff --git a/Source/core/rendering/RenderTextControl.cpp b/Source/core/rendering/RenderTextControl.cpp
index 38e54c6..1123f74 100644
--- a/Source/core/rendering/RenderTextControl.cpp
+++ b/Source/core/rendering/RenderTextControl.cpp
@@ -158,7 +158,7 @@
     result.setLocalPoint(localPoint);
 }
 
-static const char* fontFamiliesWithInvalidCharWidth[] = {
+static const char* const fontFamiliesWithInvalidCharWidth[] = {
     "American Typewriter",
     "Arial Hebrew",
     "Chalkboard",
diff --git a/Source/core/rendering/RenderTextControl.h b/Source/core/rendering/RenderTextControl.h
index c86f43f..4295d25 100644
--- a/Source/core/rendering/RenderTextControl.h
+++ b/Source/core/rendering/RenderTextControl.h
@@ -58,7 +58,6 @@
     virtual float getAvgCharWidth(AtomicString family);
     virtual LayoutUnit preferredContentLogicalWidth(float charWidth) const = 0;
     virtual LayoutUnit computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const = 0;
-    virtual RenderStyle* textBaseStyle() const = 0;
 
     virtual void updateFromElement();
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
diff --git a/Source/core/rendering/RenderTextControlMultiLine.cpp b/Source/core/rendering/RenderTextControlMultiLine.cpp
index 6faf2ac..01fa15a 100644
--- a/Source/core/rendering/RenderTextControlMultiLine.cpp
+++ b/Source/core/rendering/RenderTextControlMultiLine.cpp
@@ -83,15 +83,11 @@
     textBlockStyle->inheritFrom(startStyle);
     adjustInnerTextStyle(textBlockStyle.get());
     textBlockStyle->setDisplay(BLOCK);
+    textBlockStyle->setUnique();
 
     return textBlockStyle.release();
 }
 
-RenderStyle* RenderTextControlMultiLine::textBaseStyle() const
-{
-    return style();
-}
-
 RenderObject* RenderTextControlMultiLine::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
 {
     RenderObject* placeholderRenderer = RenderTextControl::layoutSpecialExcludedChild(relayoutChildren, layoutScope);
diff --git a/Source/core/rendering/RenderTextControlMultiLine.h b/Source/core/rendering/RenderTextControlMultiLine.h
index 2486f54..4726e22 100644
--- a/Source/core/rendering/RenderTextControlMultiLine.h
+++ b/Source/core/rendering/RenderTextControlMultiLine.h
@@ -43,7 +43,6 @@
     virtual LayoutUnit computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const OVERRIDE;
     virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
 
-    virtual RenderStyle* textBaseStyle() const;
     virtual PassRefPtr<RenderStyle> createInnerTextStyle(const RenderStyle* startStyle) const;
     virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
 };
diff --git a/Source/core/rendering/RenderTextControlSingleLine.cpp b/Source/core/rendering/RenderTextControlSingleLine.cpp
index c7d16d7..774be23 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.cpp
+++ b/Source/core/rendering/RenderTextControlSingleLine.cpp
@@ -68,12 +68,6 @@
     return toHTMLElement(inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
 }
 
-RenderStyle* RenderTextControlSingleLine::textBaseStyle() const
-{
-    Element* viewPort = editingViewPortElement();
-    return viewPort ? viewPort->renderer()->style() : style();
-}
-
 void RenderTextControlSingleLine::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     RenderTextControl::paint(paintInfo, paintOffset);
@@ -376,6 +370,7 @@
         textBlockStyle->setLineHeight(RenderStyle::initialLineHeight());
 
     textBlockStyle->setDisplay(BLOCK);
+    textBlockStyle->setUnique();
 
     return textBlockStyle.release();
 }
@@ -390,9 +385,8 @@
     RenderBox* renderer = innerTextElement()->renderBox();
     if (!renderer)
         return;
-    RenderLayer* layer = renderer->layer();
-    if (layer)
-        layer->autoscroll(position);
+
+    renderer->autoscroll(position);
 }
 
 int RenderTextControlSingleLine::scrollWidth() const
diff --git a/Source/core/rendering/RenderTextControlSingleLine.h b/Source/core/rendering/RenderTextControlSingleLine.h
index a752e90..64a07cc 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.h
+++ b/Source/core/rendering/RenderTextControlSingleLine.h
@@ -74,8 +74,6 @@
 
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
 
-    virtual RenderStyle* textBaseStyle() const;
-
     bool textShouldBeTruncated() const;
 
     HTMLElement* innerSpinButtonElement() const;
diff --git a/Source/core/rendering/RenderTheme.cpp b/Source/core/rendering/RenderTheme.cpp
index 0680bd9..59575f4 100644
--- a/Source/core/rendering/RenderTheme.cpp
+++ b/Source/core/rendering/RenderTheme.cpp
@@ -44,7 +44,6 @@
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/graphics/FontSelector.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/StringTruncator.h"
 #include "core/rendering/PaintInfo.h"
@@ -53,6 +52,7 @@
 #include "core/rendering/style/RenderStyle.h"
 #include "platform/FileMetadata.h"
 #include "platform/FloatConversion.h"
+#include "platform/fonts/FontSelector.h"
 #include "platform/text/PlatformLocale.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebFallbackThemeEngine.h"
@@ -215,28 +215,10 @@
     case InnerSpinButtonPart:
         return adjustInnerSpinButtonStyle(style, e);
 #endif
-    case TextFieldPart:
-        return adjustTextFieldStyle(style, e);
-    case TextAreaPart:
-        return adjustTextAreaStyle(style, e);
     case MenulistPart:
         return adjustMenuListStyle(style, e);
     case MenulistButtonPart:
         return adjustMenuListButtonStyle(style, e);
-    case MediaPlayButtonPart:
-    case MediaCurrentTimePart:
-    case MediaTimeRemainingPart:
-    case MediaEnterFullscreenButtonPart:
-    case MediaExitFullscreenButtonPart:
-    case MediaMuteButtonPart:
-    case MediaVolumeSliderContainerPart:
-        return adjustMediaControlStyle(style, e);
-    case MediaSliderPart:
-    case MediaVolumeSliderPart:
-    case MediaFullScreenVolumeSliderPart:
-    case SliderHorizontalPart:
-    case SliderVerticalPart:
-        return adjustSliderTrackStyle(style, e);
     case SliderThumbHorizontalPart:
     case SliderThumbVerticalPart:
         return adjustSliderThumbStyle(style, e);
@@ -248,14 +230,6 @@
         return adjustSearchFieldDecorationStyle(style, e);
     case SearchFieldResultsDecorationPart:
         return adjustSearchFieldResultsDecorationStyle(style, e);
-    case ProgressBarPart:
-        return adjustProgressBarStyle(style, e);
-    case MeterPart:
-    case RelevancyLevelIndicatorPart:
-    case ContinuousCapacityLevelIndicatorPart:
-    case DiscreteCapacityLevelIndicatorPart:
-    case RatingLevelIndicatorPart:
-        return adjustMeterStyle(style, e);
 #if ENABLE(INPUT_SPEECH)
     case InputSpeechButtonPart:
         return adjustInputFieldSpeechButtonStyle(style, e);
@@ -893,10 +867,6 @@
 
 void RenderTheme::adjustButtonStyle(RenderStyle* style, Element*) const
 {
-    // Most platforms will completely honor all CSS, and so we have no need to
-    // adjust the style at all by default. We will still allow the theme a crack
-    // at setting up a desired vertical size.
-    setButtonSize(style);
 }
 
 void RenderTheme::adjustInnerSpinButtonStyle(RenderStyle*, Element*) const
@@ -904,14 +874,6 @@
 }
 #endif
 
-void RenderTheme::adjustTextFieldStyle(RenderStyle*, Element*) const
-{
-}
-
-void RenderTheme::adjustTextAreaStyle(RenderStyle*, Element*) const
-{
-}
-
 void RenderTheme::adjustMenuListStyle(RenderStyle*, Element*) const
 {
 }
@@ -928,10 +890,6 @@
 }
 #endif
 
-void RenderTheme::adjustMeterStyle(RenderStyle* style, Element*) const
-{
-}
-
 IntSize RenderTheme::meterSizeForBounds(const RenderMeter*, const IntRect& bounds) const
 {
     return bounds.size();
@@ -947,11 +905,6 @@
     return true;
 }
 
-LayoutUnit RenderTheme::sliderTickSnappingThreshold() const
-{
-    return 5;
-}
-
 void RenderTheme::paintSliderTicks(RenderObject* o, const PaintInfo& paintInfo, const IntRect& rect)
 {
     Node* node = o->node();
@@ -1041,10 +994,6 @@
     return 0;
 }
 
-void RenderTheme::adjustProgressBarStyle(RenderStyle*, Element*) const
-{
-}
-
 bool RenderTheme::shouldHaveSpinButton(HTMLInputElement* inputElement) const
 {
     return inputElement->isSteppable() && !inputElement->isRangeControl();
@@ -1054,14 +1003,6 @@
 {
 }
 
-void RenderTheme::adjustMediaControlStyle(RenderStyle*, Element*) const
-{
-}
-
-void RenderTheme::adjustSliderTrackStyle(RenderStyle*, Element*) const
-{
-}
-
 void RenderTheme::adjustSliderThumbStyle(RenderStyle* style, Element* element) const
 {
     adjustSliderThumbSize(style, element);
diff --git a/Source/core/rendering/RenderTheme.h b/Source/core/rendering/RenderTheme.h
index e300ddd..7729b0b 100644
--- a/Source/core/rendering/RenderTheme.h
+++ b/Source/core/rendering/RenderTheme.h
@@ -175,19 +175,13 @@
     // Media controls
     virtual bool supportsClosedCaptioning() const { return false; }
     virtual bool hasOwnDisabledStateHandlingFor(ControlPart) const { return false; }
-    virtual bool usesMediaControlStatusDisplay() { return false; }
-    virtual bool usesMediaControlVolumeSlider() const { return true; }
     virtual bool usesVerticalVolumeSlider() const { return true; }
-    virtual double mediaControlsFadeInDuration() { return 0.1; }
-    virtual double mediaControlsFadeOutDuration() { return 0.3; }
     virtual String formatMediaControlsTime(float time) const;
     virtual String formatMediaControlsCurrentTime(float currentTime, float duration) const;
 
     virtual IntSize meterSizeForBounds(const RenderMeter*, const IntRect&) const;
     virtual bool supportsMeter(ControlPart) const;
 
-    // Returns the threshold distance for snapping to a slider tick mark.
-    virtual LayoutUnit sliderTickSnappingThreshold() const;
     // Returns size of one slider tick mark for a horizontal track.
     // For vertical tracks we rotate it and use it. i.e. Width is always length along the track.
     virtual IntSize sliderTickSize() const = 0;
@@ -236,16 +230,13 @@
 
     virtual void adjustButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
-    virtual void setButtonSize(RenderStyle*) const { }
 
     virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintInnerSpinButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 #endif
 
-    virtual void adjustTextFieldStyle(RenderStyle*, Element*) const;
     virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustTextAreaStyle(RenderStyle*, Element*) const;
     virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
     virtual void adjustMenuListStyle(RenderStyle*, Element*) const;
@@ -254,10 +245,8 @@
     virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const;
     virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustMeterStyle(RenderStyle*, Element*) const;
     virtual bool paintMeter(RenderObject*, const PaintInfo&, const IntRect&);
 
-    virtual void adjustProgressBarStyle(RenderStyle*, Element*) const;
     virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
 #if ENABLE(INPUT_SPEECH)
@@ -265,7 +254,6 @@
     virtual bool paintInputFieldSpeechButton(RenderObject*, const PaintInfo&, const IntRect&);
 #endif
 
-    virtual void adjustSliderTrackStyle(RenderStyle*, Element*) const;
     virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
     virtual void adjustSliderThumbStyle(RenderStyle*, Element*) const;
@@ -283,7 +271,6 @@
     virtual void adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const;
     virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
 
-    virtual void adjustMediaControlStyle(RenderStyle*, Element*) const;
     virtual bool paintMediaFullscreenButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaPlayButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaOverlayPlayButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
diff --git a/Source/core/rendering/RenderThemeChromiumAndroid.cpp b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
index 78ebcb1..98f7071 100644
--- a/Source/core/rendering/RenderThemeChromiumAndroid.cpp
+++ b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
@@ -29,13 +29,13 @@
 #include "CSSValueKeywords.h"
 #include "UserAgentStyleSheets.h"
 #include "core/platform/ScrollbarTheme.h"
-#include "core/platform/graphics/Color.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderMediaControls.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderProgress.h"
 #include "core/rendering/RenderSlider.h"
 #include "platform/LayoutTestSupport.h"
+#include "platform/graphics/Color.h"
 
 #include "public/platform/android/WebThemeEngine.h"
 #include "public/platform/Platform.h"
diff --git a/Source/core/rendering/RenderThemeChromiumDefault.cpp b/Source/core/rendering/RenderThemeChromiumDefault.cpp
index adaa2d4..0eec664 100644
--- a/Source/core/rendering/RenderThemeChromiumDefault.cpp
+++ b/Source/core/rendering/RenderThemeChromiumDefault.cpp
@@ -27,12 +27,12 @@
 
 #include "CSSValueKeywords.h"
 #include "UserAgentStyleSheets.h"
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderProgress.h"
+#include "platform/graphics/Color.h"
 #include "public/platform/default/WebThemeEngine.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebRect.h"
diff --git a/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp b/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
index 06fec41..3d1d026 100644
--- a/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
+++ b/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
@@ -27,7 +27,7 @@
 #include "core/rendering/RenderThemeChromiumFontProvider.h"
 
 #include "CSSValueKeywords.h"
-#include "core/platform/graphics/FontDescription.h"
+#include "platform/fonts/FontDescription.h"
 
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp b/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp
index c17695b..18305cc 100644
--- a/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp
+++ b/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp
@@ -29,7 +29,7 @@
 #include <windows.h>
 
 #include "CSSValueKeywords.h"
-#include "core/platform/graphics/FontDescription.h"
+#include "platform/fonts/FontDescription.h"
 #include "platform/win/HWndDC.h"
 #include "platform/win/SystemInfo.h"
 #include "wtf/text/WTFString.h"
@@ -78,7 +78,7 @@
 
 static void getNonClientMetrics(NONCLIENTMETRICS* metrics)
 {
-    static UINT size = (windowsVersion() >= WindowsVista) ?
+    static UINT size = isWindowsVistaOrGreater() ?
         sizeof(NONCLIENTMETRICS) : NONCLIENTMETRICS_SIZE_PRE_VISTA;
     metrics->cbSize = size;
     bool success = !!SystemParametersInfo(SPI_GETNONCLIENTMETRICS, size, metrics, 0);
diff --git a/Source/core/rendering/RenderThemeChromiumMac.h b/Source/core/rendering/RenderThemeChromiumMac.h
index 8cbe2ba..371ecc6 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.h
+++ b/Source/core/rendering/RenderThemeChromiumMac.h
@@ -95,10 +95,8 @@
     virtual bool supportsSelectionForegroundColors() const OVERRIDE { return false; }
 
     virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustTextFieldStyle(RenderStyle*, Element*) const;
 
     virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustTextAreaStyle(RenderStyle*, Element*) const;
 
     virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&);
     virtual void adjustMenuListStyle(RenderStyle*, Element*) const;
@@ -106,7 +104,6 @@
     virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&);
     virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const;
 
-    virtual void adjustProgressBarStyle(RenderStyle*, Element*) const;
     virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&);
 
     virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
@@ -186,7 +183,6 @@
     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 usesMediaControlStatusDisplay() { return false; }
     virtual bool hasOwnDisabledStateHandlingFor(ControlPart) const { return true; }
     virtual bool usesVerticalVolumeSlider() const { return false; }
     virtual String formatMediaControlsTime(float time) const;
diff --git a/Source/core/rendering/RenderThemeChromiumMac.mm b/Source/core/rendering/RenderThemeChromiumMac.mm
index 37c4bfb..d66988c 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.mm
+++ b/Source/core/rendering/RenderThemeChromiumMac.mm
@@ -31,7 +31,6 @@
 #import "core/html/HTMLInputElement.h"
 #import "core/html/HTMLMediaElement.h"
 #import "core/html/HTMLMeterElement.h"
-#import "core/html/HTMLPlugInImageElement.h"
 #import "core/html/TimeRanges.h"
 #import "core/html/shadow/MediaControlElements.h"
 #import "core/frame/FrameView.h"
@@ -53,6 +52,7 @@
 #import "core/rendering/RenderProgress.h"
 #import "core/rendering/RenderSlider.h"
 #import "core/rendering/RenderView.h"
+#import "core/rendering/style/ShadowList.h"
 #import "platform/LayoutTestSupport.h"
 #import "platform/SharedBuffer.h"
 #import "platform/text/PlatformLocale.h"
@@ -780,10 +780,6 @@
     return false;
 }
 
-void RenderThemeChromiumMac::adjustTextFieldStyle(RenderStyle*, Element*) const
-{
-}
-
 bool RenderThemeChromiumMac::paintCapsLockIndicator(RenderObject*, const PaintInfo& paintInfo, const IntRect& r)
 {
     if (paintInfo.context->paintingDisabled())
@@ -853,10 +849,6 @@
     return false;
 }
 
-void RenderThemeChromiumMac::adjustTextAreaStyle(RenderStyle*, Element*) const
-{
-}
-
 const int* RenderThemeChromiumMac::popupButtonMargins() const
 {
     static const int margins[3][4] =
@@ -1058,10 +1050,6 @@
     return progressAnimationNumFrames * progressAnimationFrameRate;
 }
 
-void RenderThemeChromiumMac::adjustProgressBarStyle(RenderStyle*, Element*) const
-{
-}
-
 bool RenderThemeChromiumMac::paintProgressBar(RenderObject* renderObject, const PaintInfo& paintInfo, const IntRect& rect)
 {
     if (!renderObject->isProgress())
@@ -1535,7 +1523,6 @@
     FloatRect borderBounds = unzoomedRect;
     borderBounds.inflate(sliderThumbBorderWidth / 2.0);
 
-    FloatRect shadowBounds = unzoomedRect;
     borderBounds.inflate(-sliderThumbBorderWidth);
     FloatSize shadowOffset(0, 1);
     paintInfo.context->setShadow(shadowOffset, sliderThumbShadowBlur, shadowColor);
diff --git a/Source/core/rendering/RenderThemeChromiumWin.cpp b/Source/core/rendering/RenderThemeChromiumWin.cpp
index 749a2ef..8324b05 100644
--- a/Source/core/rendering/RenderThemeChromiumWin.cpp
+++ b/Source/core/rendering/RenderThemeChromiumWin.cpp
@@ -34,15 +34,14 @@
 #include "core/html/HTMLMediaElement.h"
 #include "core/html/shadow/MediaControlElements.h"
 #include "core/platform/ScrollbarTheme.h"
-#include "core/platform/graphics/FontSelector.h"
 #include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
 #include "core/platform/graphics/chromium/TransparencyWin.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/win/SystemInfo.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebColor.h"
@@ -627,10 +626,6 @@
     return progressAnimationFrameRate;
 }
 
-void RenderThemeChromiumWin::adjustProgressBarStyle(RenderStyle*, Element*) const
-{
-}
-
 bool RenderThemeChromiumWin::paintProgressBar(RenderObject* o, const PaintInfo& i, const IntRect& r)
 {
     if (!o->isProgress())
diff --git a/Source/core/rendering/RenderThemeChromiumWin.h b/Source/core/rendering/RenderThemeChromiumWin.h
index 2b59a22..b44e44b 100644
--- a/Source/core/rendering/RenderThemeChromiumWin.h
+++ b/Source/core/rendering/RenderThemeChromiumWin.h
@@ -82,7 +82,6 @@
 
     virtual double animationRepeatIntervalForProgressBar(RenderProgress*) const OVERRIDE;
     virtual double animationDurationForProgressBar(RenderProgress*) const OVERRIDE;
-    virtual void adjustProgressBarStyle(RenderStyle*, Element*) const OVERRIDE;
     virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
     virtual bool shouldOpenPickerWithF4Key() const OVERRIDE;
diff --git a/Source/core/rendering/RenderTreeAsText.cpp b/Source/core/rendering/RenderTreeAsText.cpp
index 530a314..6327bc2 100644
--- a/Source/core/rendering/RenderTreeAsText.cpp
+++ b/Source/core/rendering/RenderTreeAsText.cpp
@@ -674,7 +674,8 @@
     l->stackingNode()->updateLayerListsIfNeeded();
 
     bool shouldPaint = (behavior & RenderAsTextShowAllLayers) ? true : l->intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer);
-    Vector<RenderLayer*>* negList = l->stackingNode()->negZOrderList();
+
+    Vector<RenderLayerStackingNode*>* negList = l->stackingNode()->negZOrderList();
     bool paintsBackgroundSeparately = negList && negList->size() > 0;
     if (shouldPaint && paintsBackgroundSeparately)
         write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), LayerPaintPhaseBackground, indent, behavior);
@@ -687,13 +688,13 @@
             ++currIndent;
         }
         for (unsigned i = 0; i != negList->size(); ++i)
-            writeLayers(ts, rootLayer, negList->at(i), paintDirtyRect, currIndent, behavior);
+            writeLayers(ts, rootLayer, negList->at(i)->layer(), paintDirtyRect, currIndent, behavior);
     }
 
     if (shouldPaint)
         write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), paintsBackgroundSeparately ? LayerPaintPhaseForeground : LayerPaintPhaseAll, indent, behavior);
 
-    if (Vector<RenderLayer*>* normalFlowList = l->stackingNode()->normalFlowList()) {
+    if (Vector<RenderLayerStackingNode*>* normalFlowList = l->stackingNode()->normalFlowList()) {
         int currIndent = indent;
         if (behavior & RenderAsTextShowLayerNesting) {
             writeIndent(ts, indent);
@@ -701,10 +702,10 @@
             ++currIndent;
         }
         for (unsigned i = 0; i != normalFlowList->size(); ++i)
-            writeLayers(ts, rootLayer, normalFlowList->at(i), paintDirtyRect, currIndent, behavior);
+            writeLayers(ts, rootLayer, normalFlowList->at(i)->layer(), paintDirtyRect, currIndent, behavior);
     }
 
-    if (Vector<RenderLayer*>* posList = l->stackingNode()->posZOrderList()) {
+    if (Vector<RenderLayerStackingNode*>* posList = l->stackingNode()->posZOrderList()) {
         int currIndent = indent;
         if (behavior & RenderAsTextShowLayerNesting) {
             writeIndent(ts, indent);
@@ -712,7 +713,7 @@
             ++currIndent;
         }
         for (unsigned i = 0; i != posList->size(); ++i)
-            writeLayers(ts, rootLayer, posList->at(i), paintDirtyRect, currIndent, behavior);
+            writeLayers(ts, rootLayer, posList->at(i)->layer(), paintDirtyRect, currIndent, behavior);
     }
 
     // Altough the RenderFlowThread requires a layer, it is not collected by its parent,
diff --git a/Source/core/rendering/RenderVideo.cpp b/Source/core/rendering/RenderVideo.cpp
index fb198bd..cdda831 100644
--- a/Source/core/rendering/RenderVideo.cpp
+++ b/Source/core/rendering/RenderVideo.cpp
@@ -107,12 +107,6 @@
     if (video->shouldDisplayPosterImage() && !m_cachedImageSize.isEmpty() && !imageResource()->errorOccurred())
         return m_cachedImageSize;
 
-    // When the natural size of the video is unavailable, we use the provided
-    // width and height attributes of the video element as the intrinsic size until
-    // better values become available.
-    if (video->hasAttribute(widthAttr) && video->hasAttribute(heightAttr))
-        return LayoutSize(video->width(), video->height());
-
     // <video> in standalone media documents should not use the default 300x150
     // size since they also have audio-only files. By setting the intrinsic
     // size to 300x1 the video will resize itself in these cases, and audio will
@@ -210,7 +204,7 @@
     if (!mediaPlayer)
         return;
 
-    if (!videoElement()->inActiveDocument())
+    if (!videoElement()->isActive())
         return;
 
     contentChanged(VideoChanged);
diff --git a/Source/core/rendering/RenderView.cpp b/Source/core/rendering/RenderView.cpp
index 44cc118..0928acd 100644
--- a/Source/core/rendering/RenderView.cpp
+++ b/Source/core/rendering/RenderView.cpp
@@ -521,7 +521,7 @@
             break;
         }
 
-        if (RenderLayer* compositingLayer = layer->enclosingCompositingLayerForRepaint()) {
+        if (layer->enclosingCompositingLayerForRepaint()) {
             frameView()->setCannotBlitToWindow();
             break;
         }
diff --git a/Source/core/rendering/RenderWidget.cpp b/Source/core/rendering/RenderWidget.cpp
index 8bd1a9e..ce7afc3 100644
--- a/Source/core/rendering/RenderWidget.cpp
+++ b/Source/core/rendering/RenderWidget.cpp
@@ -306,7 +306,7 @@
     }
 
     if (canResize())
-        layer()->paintResizer(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
+        layer()->scrollableArea()->paintResizer(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
 }
 
 void RenderWidget::setIsOverlapped(bool isOverlapped)
diff --git a/Source/core/rendering/RenderingNodeProxy.cpp b/Source/core/rendering/RenderingNodeProxy.cpp
deleted file mode 100644
index 303972b..0000000
--- a/Source/core/rendering/RenderingNodeProxy.cpp
+++ /dev/null
@@ -1,52 +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/rendering/RenderingNodeProxy.h"
-
-#include "core/dom/Node.h"
-
-namespace WebCore {
-
-RenderingNodeProxy::RenderingNodeProxy(Node* node)
-    : m_node(node)
-{
-}
-
-RenderingNodeProxy::~RenderingNodeProxy()
-{
-}
-
-bool RenderingNodeProxy::hasTagName(const QualifiedName& tagName) const
-{
-    return m_node->hasTagName(tagName);
-}
-
-}
diff --git a/Source/core/rendering/ScrollBehavior.cpp b/Source/core/rendering/ScrollBehavior.cpp
index d28c8e0..d331f1d 100644
--- a/Source/core/rendering/ScrollBehavior.cpp
+++ b/Source/core/rendering/ScrollBehavior.cpp
@@ -44,6 +44,8 @@
 #include "config.h"
 #include "core/rendering/ScrollBehavior.h"
 
+#include "platform/geometry/LayoutRect.h"
+
 namespace WebCore {
 
 const ScrollAlignment ScrollAlignment::alignCenterIfNeeded = { noScroll, alignCenter, alignToClosestEdge };
@@ -52,4 +54,93 @@
 const ScrollAlignment ScrollAlignment::alignTopAlways = { alignTop, alignTop, alignTop };
 const ScrollAlignment ScrollAlignment::alignBottomAlways = { alignBottom, alignBottom, alignBottom };
 
+#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;
+    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) {
+        // If the rectangle is fully visible, use the specified visible behavior.
+        // If the rectangle is partially visible, but over a certain threshold,
+        // then treat it as fully visible to avoid unnecessary horizontal scrolling
+        scrollX = getVisibleBehavior(alignX);
+    } 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;
+    } else if (intersectWidth > 0) {
+        // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
+        scrollX = getPartialBehavior(alignX);
+    } else {
+        scrollX = getHiddenBehavior(alignX);
+    }
+
+    if (scrollX == alignToClosestEdge) {
+        // 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;
+        }
+    }
+
+    // Given the X behavior, compute the X coordinate.
+    LayoutUnit x;
+    if (scrollX == noScroll)
+        x = visibleRect.x();
+    else if (scrollX == alignRight)
+        x = exposeRect.maxX() - visibleRect.width();
+    else if (scrollX == alignCenter)
+        x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
+    else
+        x = exposeRect.x();
+
+    // Determine the appropriate Y behavior.
+    ScrollBehavior scrollY;
+    LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
+    LayoutUnit intersectHeight = intersection(visibleRect, exposeRectY).height();
+    if (intersectHeight == exposeRect.height()) {
+        // If the rectangle is fully visible, use the specified visible behavior.
+        scrollY = getVisibleBehavior(alignY);
+    } 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;
+    } else if (intersectHeight > 0) {
+        // If the rectangle is partially visible, use the specified partial behavior
+        scrollY = getPartialBehavior(alignY);
+    } else {
+        scrollY = getHiddenBehavior(alignY);
+    }
+
+    if (scrollY == alignToClosestEdge) {
+        // 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;
+        }
+    }
+
+    // Given the Y behavior, compute the Y coordinate.
+    LayoutUnit y;
+    if (scrollY == noScroll)
+        y = visibleRect.y();
+    else if (scrollY == alignBottom)
+        y = exposeRect.maxY() - visibleRect.height();
+    else if (scrollY == alignCenter)
+        y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
+    else
+        y = exposeRect.y();
+
+    return LayoutRect(LayoutPoint(x, y), visibleRect.size());
+}
+
 }; // namespace WebCore
diff --git a/Source/core/rendering/ScrollBehavior.h b/Source/core/rendering/ScrollBehavior.h
index 5988f62..7c683d8 100644
--- a/Source/core/rendering/ScrollBehavior.h
+++ b/Source/core/rendering/ScrollBehavior.h
@@ -56,11 +56,16 @@
     alignToClosestEdge
 };
 
+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; }
 
+    // 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);
+
     static const ScrollAlignment alignCenterIfNeeded;
     static const ScrollAlignment alignToEdgeIfNeeded;
     static const ScrollAlignment alignCenterAlways;
diff --git a/Source/core/rendering/TableLayout.h b/Source/core/rendering/TableLayout.h
index 42be53d..20885dd 100644
--- a/Source/core/rendering/TableLayout.h
+++ b/Source/core/rendering/TableLayout.h
@@ -42,6 +42,7 @@
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth) = 0;
     virtual void applyPreferredLogicalWidthQuirks(LayoutUnit& minWidth, LayoutUnit& maxWidth) const = 0;
     virtual void layout() = 0;
+    virtual void willChangeTableLayout() = 0;
 
 protected:
     // FIXME: Once we enable SATURATED_LAYOUT_ARITHMETHIC, this should just be LayoutUnit::nearlyMax().
diff --git a/Source/core/rendering/TextAutosizer.cpp b/Source/core/rendering/TextAutosizer.cpp
index 9a2bb59..0424b5a 100644
--- a/Source/core/rendering/TextAutosizer.cpp
+++ b/Source/core/rendering/TextAutosizer.cpp
@@ -137,10 +137,6 @@
 {
 }
 
-TextAutosizer::~TextAutosizer()
-{
-}
-
 void TextAutosizer::recalculateMultipliers()
 {
     RenderObject* renderer = m_document->renderer();
@@ -166,8 +162,6 @@
 {
     TRACE_EVENT0("webkit", "TextAutosizer::processSubtree");
 
-    // FIXME: Text Autosizing should only be enabled when m_document->page()->mainFrame()->view()->useFixedLayout()
-    // is true, but for now it's useful to ignore this so that it can be tested on desktop.
     if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->document().printing() || !m_document->page())
         return false;
 
@@ -187,7 +181,7 @@
     // Largest area of block that can be visible at once (assuming the main
     // frame doesn't get scaled to less than overview scale), in CSS pixels.
     windowInfo.minLayoutSize = mainFrame->view()->layoutSize();
-    for (Frame* frame = m_document->frame(); frame; frame = frame->tree()->parent())
+    for (Frame* frame = m_document->frame(); frame; frame = frame->tree().parent())
         windowInfo.minLayoutSize = windowInfo.minLayoutSize.shrunkTo(frame->view()->layoutSize());
 
     // The layoutRoot could be neither a container nor a cluster, so walk up the tree till we find each of these.
diff --git a/Source/core/rendering/TextAutosizer.h b/Source/core/rendering/TextAutosizer.h
index 9632d82..7236009 100644
--- a/Source/core/rendering/TextAutosizer.h
+++ b/Source/core/rendering/TextAutosizer.h
@@ -40,14 +40,12 @@
 struct TextAutosizingWindowInfo;
 struct TextAutosizingClusterInfo;
 
-class TextAutosizer {
+class TextAutosizer FINAL {
     WTF_MAKE_NONCOPYABLE(TextAutosizer);
 
 public:
     static PassOwnPtr<TextAutosizer> create(Document* document) { return adoptPtr(new TextAutosizer(document)); }
 
-    virtual ~TextAutosizer();
-
     bool processSubtree(RenderObject* layoutRoot);
     void recalculateMultipliers();
 
diff --git a/Source/core/rendering/shapes/PolygonShape.h b/Source/core/rendering/shapes/PolygonShape.h
index 14cd30d..38b0d8e 100644
--- a/Source/core/rendering/shapes/PolygonShape.h
+++ b/Source/core/rendering/shapes/PolygonShape.h
@@ -30,8 +30,8 @@
 #ifndef PolygonShape_h
 #define PolygonShape_h
 
-#include "core/platform/graphics/FloatPolygon.h"
 #include "core/rendering/shapes/Shape.h"
+#include "platform/geometry/FloatPolygon.h"
 
 namespace WebCore {
 
diff --git a/Source/core/rendering/shapes/Shape.cpp b/Source/core/rendering/shapes/Shape.cpp
index 9962987..a3ea783 100644
--- a/Source/core/rendering/shapes/Shape.cpp
+++ b/Source/core/rendering/shapes/Shape.cpp
@@ -32,12 +32,12 @@
 
 #include "core/fetch/ImageResource.h"
 #include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/WindRule.h"
 #include "core/rendering/shapes/PolygonShape.h"
 #include "core/rendering/shapes/RasterShape.h"
 #include "core/rendering/shapes/RectangleShape.h"
 #include "platform/LengthFunctions.h"
 #include "platform/geometry/FloatSize.h"
+#include "platform/graphics/WindRule.h"
 #include "wtf/MathExtras.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
diff --git a/Source/core/rendering/shapes/ShapeInfo.cpp b/Source/core/rendering/shapes/ShapeInfo.cpp
index 6c74339..7723614 100644
--- a/Source/core/rendering/shapes/ShapeInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInfo.cpp
@@ -35,6 +35,19 @@
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
+
+bool checkShapeImageOrigin(Document& document, ImageResource& imageResource)
+{
+    if (imageResource.isAccessAllowed(document.securityOrigin()))
+        return true;
+
+    const KURL& url = imageResource.url();
+    String urlString = url.isNull() ? "''" : url.elidedString();
+    document.addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Unsafe attempt to load URL " + urlString + ".");
+
+    return false;
+}
+
 template<class RenderType>
 const Shape* ShapeInfo<RenderType>::computedShape() const
 {
diff --git a/Source/core/rendering/shapes/ShapeInfo.h b/Source/core/rendering/shapes/ShapeInfo.h
index b79cc59..9f98160 100644
--- a/Source/core/rendering/shapes/ShapeInfo.h
+++ b/Source/core/rendering/shapes/ShapeInfo.h
@@ -105,6 +105,7 @@
     ShapeInfo(const RenderType* renderer): m_renderer(renderer) { }
 
     const Shape* computedShape() const;
+
     virtual LayoutRect computedShapeLogicalBoundingBox() const = 0;
     virtual ShapeValue* shapeValue() const = 0;
     virtual void getIntervals(LayoutUnit, LayoutUnit, SegmentList&) const = 0;
@@ -121,5 +122,8 @@
     mutable OwnPtr<Shape> m_shape;
     LayoutSize m_shapeLogicalSize;
 };
+
+bool checkShapeImageOrigin(Document&, ImageResource&);
+
 }
 #endif
diff --git a/Source/core/rendering/shapes/ShapeInsideInfo.cpp b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
index fe8d53b..3a2e8ac 100644
--- a/Source/core/rendering/shapes/ShapeInsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
@@ -51,7 +51,7 @@
     case ShapeValue::Shape:
         return shapeValue->shape() && shapeValue->shape()->type() != BasicShape::BasicShapeInsetRectangleType;
     case ShapeValue::Image:
-        return shapeValue->isImageValid();
+        return shapeValue->isImageValid() && checkShapeImageOrigin(renderer->document(), *(shapeValue->image()->cachedImage()));
     case ShapeValue::Outside:
         return false;
     }
diff --git a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
index cfa4218..9925aef 100644
--- a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
@@ -31,7 +31,7 @@
 #include "core/rendering/shapes/ShapeOutsideInfo.h"
 
 #include "core/rendering/FloatingObjects.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderBox.h"
 
 namespace WebCore {
@@ -45,7 +45,7 @@
     case ShapeValue::Shape:
         return shapeValue->shape();
     case ShapeValue::Image:
-        return shapeValue->isImageValid();
+        return shapeValue->isImageValid() && checkShapeImageOrigin(box->document(), *(shapeValue->image()->cachedImage()));
     case ShapeValue::Outside:
         return false;
     }
@@ -53,9 +53,9 @@
     return false;
 }
 
-void ShapeOutsideInfo::updateDeltasForContainingBlockLine(const RenderBlock* containingBlock, const FloatingObject* floatingObject, LayoutUnit lineTop, LayoutUnit lineHeight)
+void ShapeOutsideInfo::updateDeltasForContainingBlockLine(const RenderBlockFlow* containingBlock, const FloatingObject* floatingObject, LayoutUnit lineTop, LayoutUnit lineHeight)
 {
-    LayoutUnit shapeTop = floatingObject->logicalTop(containingBlock->isHorizontalWritingMode()) + std::max(LayoutUnit(), containingBlock->marginBeforeForChild(m_renderer));
+    LayoutUnit shapeTop = containingBlock->logicalTopForFloat(floatingObject) + std::max(LayoutUnit(), containingBlock->marginBeforeForChild(m_renderer));
     LayoutUnit lineTopInShapeCoordinates = lineTop - shapeTop + logicalTopOffset();
 
     if (shapeSizeDirty() || m_lineTop != lineTopInShapeCoordinates || m_lineHeight != lineHeight) {
@@ -63,17 +63,30 @@
         m_shapeLineTop = lineTopInShapeCoordinates - logicalTopOffset();
         m_lineHeight = lineHeight;
 
+        LayoutUnit floatMarginBoxWidth = containingBlock->logicalWidthForFloat(floatingObject);
+
         if (lineOverlapsShapeBounds()) {
             SegmentList segments = computeSegmentsForLine(lineTopInShapeCoordinates, lineHeight);
             if (segments.size()) {
-                m_leftMarginBoxDelta = segments.first().logicalLeft + containingBlock->marginStartForChild(m_renderer);
-                m_rightMarginBoxDelta = segments.last().logicalRight - containingBlock->logicalWidthForChild(m_renderer) - containingBlock->marginEndForChild(m_renderer);
+                LayoutUnit rawLeftMarginBoxDelta = segments.first().logicalLeft + containingBlock->marginStartForChild(m_renderer);
+                m_leftMarginBoxDelta = clampTo<LayoutUnit>(rawLeftMarginBoxDelta, LayoutUnit(), floatMarginBoxWidth);
+
+                LayoutUnit rawRightMarginBoxDelta = segments.last().logicalRight - containingBlock->logicalWidthForChild(m_renderer) - containingBlock->marginEndForChild(m_renderer);
+                m_rightMarginBoxDelta = clampTo<LayoutUnit>(rawRightMarginBoxDelta, -floatMarginBoxWidth, LayoutUnit());
                 return;
             }
         }
 
-        m_leftMarginBoxDelta = containingBlock->logicalWidthForChild(m_renderer) + containingBlock->marginStartForChild(m_renderer);
-        m_rightMarginBoxDelta = -containingBlock->logicalWidthForChild(m_renderer) - containingBlock->marginEndForChild(m_renderer);
+        // Lines that do not overlap the shape should act as if the float
+        // wasn't there for layout purposes. So we set the deltas to remove the
+        // entire width of the float.
+        // FIXME: The latest CSS Shapes spec says that in this case, the
+        // content should interact with previously stacked floats on the line
+        // as if this outermost float did not exist. Perhaps obviously, this
+        // solution cannot do that, and will be revisted when that part of the
+        // spec is implemented.
+        m_leftMarginBoxDelta = floatMarginBoxWidth;
+        m_rightMarginBoxDelta = -floatMarginBoxWidth;
     }
 }
 
diff --git a/Source/core/rendering/shapes/ShapeOutsideInfo.h b/Source/core/rendering/shapes/ShapeOutsideInfo.h
index 3db3e5d..2da8c1f 100644
--- a/Source/core/rendering/shapes/ShapeOutsideInfo.h
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class RenderBlock;
+class RenderBlockFlow;
 class RenderBox;
 class FloatingObject;
 
@@ -44,7 +44,7 @@
     LayoutUnit leftMarginBoxDelta() const { return m_leftMarginBoxDelta; }
     LayoutUnit rightMarginBoxDelta() const { return m_rightMarginBoxDelta; }
 
-    void updateDeltasForContainingBlockLine(const RenderBlock*, const FloatingObject*, LayoutUnit lineTop, LayoutUnit lineHeight);
+    void updateDeltasForContainingBlockLine(const RenderBlockFlow*, const FloatingObject*, LayoutUnit lineTop, LayoutUnit lineHeight);
 
     static PassOwnPtr<ShapeOutsideInfo> createInfo(const RenderBox* renderer) { return adoptPtr(new ShapeOutsideInfo(renderer)); }
     static bool isEnabledFor(const RenderBox*);
diff --git a/Source/core/rendering/style/BasicShapes.h b/Source/core/rendering/style/BasicShapes.h
index 9c9474d..b8735a8 100644
--- a/Source/core/rendering/style/BasicShapes.h
+++ b/Source/core/rendering/style/BasicShapes.h
@@ -30,8 +30,8 @@
 #ifndef BasicShapes_h
 #define BasicShapes_h
 
-#include "core/platform/graphics/WindRule.h"
 #include "platform/Length.h"
+#include "platform/graphics/WindRule.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
diff --git a/Source/core/rendering/style/BorderValue.h b/Source/core/rendering/style/BorderValue.h
index fb8c61c..dcd5096 100644
--- a/Source/core/rendering/style/BorderValue.h
+++ b/Source/core/rendering/style/BorderValue.h
@@ -25,8 +25,8 @@
 #ifndef BorderValue_h
 #define BorderValue_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/graphics/Color.h"
 
 namespace WebCore {
 
diff --git a/Source/core/rendering/style/FillLayer.cpp b/Source/core/rendering/style/FillLayer.cpp
index ca66f47..fc784c8 100644
--- a/Source/core/rendering/style/FillLayer.cpp
+++ b/Source/core/rendering/style/FillLayer.cpp
@@ -52,9 +52,11 @@
     , m_repeatX(FillLayer::initialFillRepeatX(type))
     , m_repeatY(FillLayer::initialFillRepeatY(type))
     , m_composite(FillLayer::initialFillComposite(type))
-    , m_sizeType(FillLayer::initialFillSizeType(type))
+    , m_sizeType(SizeNone) // SizeNone indicates size is unset.
     , m_blendMode(FillLayer::initialFillBlendMode(type))
     , m_maskSourceType(FillLayer::initialFillMaskSourceType(type))
+    , m_backgroundXOrigin(LeftEdge)
+    , m_backgroundYOrigin(TopEdge)
     , m_imageSet(false)
     , m_attachmentSet(false)
     , m_clipSet(false)
@@ -63,9 +65,8 @@
     , m_repeatYSet(false)
     , m_xPosSet(false)
     , m_yPosSet(false)
-    , m_backgroundOriginSet(false)
-    , m_backgroundXOrigin(LeftEdge)
-    , m_backgroundYOrigin(TopEdge)
+    , m_backgroundXOriginSet(false)
+    , m_backgroundYOriginSet(false)
     , m_compositeSet(type == MaskFillLayer)
     , m_blendModeSet(false)
     , m_maskSourceTypeSet(false)
@@ -88,6 +89,8 @@
     , m_sizeType(o.m_sizeType)
     , m_blendMode(o.m_blendMode)
     , m_maskSourceType(o.m_maskSourceType)
+    , m_backgroundXOrigin(o.m_backgroundXOrigin)
+    , m_backgroundYOrigin(o.m_backgroundYOrigin)
     , m_imageSet(o.m_imageSet)
     , m_attachmentSet(o.m_attachmentSet)
     , m_clipSet(o.m_clipSet)
@@ -96,9 +99,8 @@
     , m_repeatYSet(o.m_repeatYSet)
     , m_xPosSet(o.m_xPosSet)
     , m_yPosSet(o.m_yPosSet)
-    , m_backgroundOriginSet(o.m_backgroundOriginSet)
-    , m_backgroundXOrigin(o.m_backgroundXOrigin)
-    , m_backgroundYOrigin(o.m_backgroundYOrigin)
+    , m_backgroundXOriginSet(o.m_backgroundXOriginSet)
+    , m_backgroundYOriginSet(o.m_backgroundYOriginSet)
     , m_compositeSet(o.m_compositeSet)
     , m_blendModeSet(o.m_blendModeSet)
     , m_maskSourceTypeSet(o.m_maskSourceTypeSet)
@@ -123,7 +125,8 @@
     m_yPosition = o.m_yPosition;
     m_backgroundXOrigin = o.m_backgroundXOrigin;
     m_backgroundYOrigin = o.m_backgroundYOrigin;
-    m_backgroundOriginSet = o.m_backgroundOriginSet;
+    m_backgroundXOriginSet = o.m_backgroundXOriginSet;
+    m_backgroundYOriginSet = o.m_backgroundYOriginSet;
     m_sizeLength = o.m_sizeLength;
     m_attachment = o.m_attachment;
     m_clip = o.m_clip;
@@ -173,10 +176,10 @@
         // We need to fill in the remaining values with the pattern specified.
         for (FillLayer* pattern = this; curr; curr = curr->next()) {
             curr->m_xPosition = pattern->m_xPosition;
-            if (pattern->isBackgroundOriginSet()) {
+            if (pattern->isBackgroundXOriginSet())
                 curr->m_backgroundXOrigin = pattern->m_backgroundXOrigin;
+            if (pattern->isBackgroundYOriginSet())
                 curr->m_backgroundYOrigin = pattern->m_backgroundYOrigin;
-            }
             pattern = pattern->next();
             if (pattern == curr || !pattern)
                 pattern = this;
@@ -188,10 +191,10 @@
         // We need to fill in the remaining values with the pattern specified.
         for (FillLayer* pattern = this; curr; curr = curr->next()) {
             curr->m_yPosition = pattern->m_yPosition;
-            if (pattern->isBackgroundOriginSet()) {
+            if (pattern->isBackgroundXOriginSet())
                 curr->m_backgroundXOrigin = pattern->m_backgroundXOrigin;
+            if (pattern->isBackgroundYOriginSet())
                 curr->m_backgroundYOrigin = pattern->m_backgroundYOrigin;
-            }
             pattern = pattern->next();
             if (pattern == curr || !pattern)
                 pattern = this;
diff --git a/Source/core/rendering/style/FillLayer.h b/Source/core/rendering/style/FillLayer.h
index 7806383..b285d81 100644
--- a/Source/core/rendering/style/FillLayer.h
+++ b/Source/core/rendering/style/FillLayer.h
@@ -25,11 +25,11 @@
 #ifndef FillLayer_h
 #define FillLayer_h
 
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "core/rendering/style/StyleImage.h"
 #include "platform/Length.h"
 #include "platform/LengthSize.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "wtf/RefPtr.h"
 
 namespace WebCore {
@@ -88,7 +88,8 @@
     bool isImageSet() const { return m_imageSet; }
     bool isXPositionSet() const { return m_xPosSet; }
     bool isYPositionSet() const { return m_yPosSet; }
-    bool isBackgroundOriginSet() const { return m_backgroundOriginSet; }
+    bool isBackgroundXOriginSet() const { return m_backgroundXOriginSet; }
+    bool isBackgroundYOriginSet() const { return m_backgroundYOriginSet; }
     bool isAttachmentSet() const { return m_attachmentSet; }
     bool isClipSet() const { return m_clipSet; }
     bool isOriginSet() const { return m_originSet; }
@@ -100,10 +101,10 @@
     bool isMaskSourceTypeSet() const { return m_maskSourceTypeSet; }
 
     void setImage(PassRefPtr<StyleImage> i) { m_image = i; m_imageSet = true; }
-    void setXPosition(Length l) { m_xPosition = l; m_xPosSet = true; }
-    void setYPosition(Length l) { m_yPosition = l; m_yPosSet = true; }
-    void setBackgroundXOrigin(BackgroundEdgeOrigin o) { m_backgroundXOrigin = o; m_backgroundOriginSet = true; }
-    void setBackgroundYOrigin(BackgroundEdgeOrigin o) { m_backgroundYOrigin = o; m_backgroundOriginSet = true; }
+    void setXPosition(Length position) { m_xPosition = position; m_xPosSet = true; m_backgroundXOriginSet = false; m_backgroundXOrigin = LeftEdge; }
+    void setYPosition(Length position) { m_yPosition = position; m_yPosSet = true; m_backgroundYOriginSet = false; m_backgroundYOrigin = TopEdge; }
+    void setBackgroundXOrigin(BackgroundEdgeOrigin origin) { m_backgroundXOrigin = origin; m_backgroundXOriginSet = true; }
+    void setBackgroundYOrigin(BackgroundEdgeOrigin origin) { m_backgroundYOrigin = origin; m_backgroundYOriginSet = true; }
     void setAttachment(EFillAttachment attachment) { m_attachment = attachment; m_attachmentSet = true; }
     void setClip(EFillBox b) { m_clip = b; m_clipSet = true; }
     void setOrigin(EFillBox b) { m_origin = b; m_originSet = true; }
@@ -120,12 +121,12 @@
     void clearXPosition()
     {
         m_xPosSet = false;
-        m_backgroundOriginSet = false;
+        m_backgroundXOriginSet = false;
     }
     void clearYPosition()
     {
         m_yPosSet = false;
-        m_backgroundOriginSet = false;
+        m_backgroundYOriginSet = false;
     }
 
     void clearAttachment() { m_attachmentSet = false; }
@@ -182,7 +183,7 @@
     static EFillRepeat initialFillRepeatY(EFillLayerType) { return RepeatFill; }
     static CompositeOperator initialFillComposite(EFillLayerType) { return CompositeSourceOver; }
     static BlendMode initialFillBlendMode(EFillLayerType) { return BlendModeNormal; }
-    static EFillSizeType initialFillSizeType(EFillLayerType) { return SizeNone; }
+    static EFillSizeType initialFillSizeType(EFillLayerType) { return SizeLength; }
     static LengthSize initialFillSizeLength(EFillLayerType) { return LengthSize(); }
     static FillSize initialFillSize(EFillLayerType type) { return FillSize(initialFillSizeType(type), initialFillSizeLength(type)); }
     static Length initialFillXPosition(EFillLayerType) { return Length(0.0, Percent); }
@@ -215,6 +216,8 @@
     unsigned m_sizeType : 2; // EFillSizeType
     unsigned m_blendMode : 5; // BlendMode
     unsigned m_maskSourceType : 1; // EMaskSourceType
+    unsigned m_backgroundXOrigin : 2; // BackgroundEdgeOrigin
+    unsigned m_backgroundYOrigin : 2; // BackgroundEdgeOrigin
 
     unsigned m_imageSet : 1;
     unsigned m_attachmentSet : 1;
@@ -224,9 +227,8 @@
     unsigned m_repeatYSet : 1;
     unsigned m_xPosSet : 1;
     unsigned m_yPosSet : 1;
-    unsigned m_backgroundOriginSet : 1;
-    unsigned m_backgroundXOrigin : 2; // BackgroundEdgeOrigin
-    unsigned m_backgroundYOrigin : 2; // BackgroundEdgeOrigin
+    unsigned m_backgroundXOriginSet : 1;
+    unsigned m_backgroundYOriginSet : 1;
     unsigned m_compositeSet : 1;
     unsigned m_blendModeSet : 1;
     unsigned m_maskSourceTypeSet : 1;
diff --git a/Source/core/rendering/style/GridTrackSize.h b/Source/core/rendering/style/GridTrackSize.h
index a75820e..584b47a 100644
--- a/Source/core/rendering/style/GridTrackSize.h
+++ b/Source/core/rendering/style/GridTrackSize.h
@@ -42,11 +42,31 @@
 
 class GridTrackSize {
 public:
-    GridTrackSize(LengthType type = Undefined)
+    GridTrackSize()
+        : m_type(LengthTrackSizing)
+        , m_minTrackBreadth(Undefined)
+        , m_maxTrackBreadth(Undefined)
+        , 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.
+    }
+
+    GridTrackSize(LengthType type)
         : m_type(LengthTrackSizing)
         , m_minTrackBreadth(type)
         , m_maxTrackBreadth(type)
+        , m_minTrackBreadthIsMinOrMaxContent(false)
+        , m_minTrackBreadthIsMaxContent(false)
+        , m_maxTrackBreadthIsMinOrMaxContent(false)
+        , m_maxTrackBreadthIsMaxContent(false)
     {
+        ASSERT(type != Undefined);
+
+        cacheMinMaxTrackBreadthTypes();
     }
 
     const GridLength& length() const
@@ -63,6 +83,8 @@
         m_type = LengthTrackSizing;
         m_minTrackBreadth = length;
         m_maxTrackBreadth = length;
+
+        cacheMinMaxTrackBreadthTypes();
     }
 
     const GridLength& minTrackBreadth() const
@@ -90,6 +112,8 @@
         m_type = MinMaxTrackSizing;
         m_minTrackBreadth = minTrackBreadth;
         m_maxTrackBreadth = maxTrackBreadth;
+
+        cacheMinMaxTrackBreadthTypes();
     }
 
     GridTrackSizeType type() const { return m_type; }
@@ -101,15 +125,27 @@
         return m_type == other.m_type && m_minTrackBreadth == other.m_minTrackBreadth && m_maxTrackBreadth == other.m_maxTrackBreadth;
     }
 
-    bool hasMinOrMaxContentMinTrackBreadth() const { return minTrackBreadth().isLength() && (minTrackBreadth().length().isMinContent() || minTrackBreadth().length().isMaxContent()); }
-    bool hasMaxContentMinTrackBreadth() const { return minTrackBreadth().isLength() && minTrackBreadth().length().isMaxContent(); }
-    bool hasMinOrMaxContentMaxTrackBreadth() const { return maxTrackBreadth().isLength() && (maxTrackBreadth().length().isMinContent() || maxTrackBreadth().length().isMaxContent()); }
-    bool hasMaxContentMaxTrackBreadth() const { return maxTrackBreadth().isLength() && maxTrackBreadth().length().isMaxContent(); }
+    void cacheMinMaxTrackBreadthTypes()
+    {
+        m_minTrackBreadthIsMaxContent = minTrackBreadth().isLength() && minTrackBreadth().length().isMaxContent();
+        m_minTrackBreadthIsMinOrMaxContent = m_minTrackBreadthIsMaxContent || (minTrackBreadth().isLength() && minTrackBreadth().length().isMinContent());
+        m_maxTrackBreadthIsMaxContent = maxTrackBreadth().isLength() && maxTrackBreadth().length().isMaxContent();
+        m_maxTrackBreadthIsMinOrMaxContent = m_maxTrackBreadthIsMaxContent || (maxTrackBreadth().isLength() && maxTrackBreadth().length().isMinContent());
+    }
+
+    bool hasMinOrMaxContentMinTrackBreadth() const { return m_minTrackBreadthIsMinOrMaxContent; }
+    bool hasMaxContentMinTrackBreadth() const { return m_minTrackBreadthIsMaxContent; }
+    bool hasMinOrMaxContentMaxTrackBreadth() const { return m_maxTrackBreadthIsMinOrMaxContent; }
+    bool hasMaxContentMaxTrackBreadth() const { return m_maxTrackBreadthIsMaxContent; }
 
 private:
     GridTrackSizeType m_type;
     GridLength m_minTrackBreadth;
     GridLength m_maxTrackBreadth;
+    bool m_minTrackBreadthIsMinOrMaxContent;
+    bool m_minTrackBreadthIsMaxContent;
+    bool m_maxTrackBreadthIsMinOrMaxContent;
+    bool m_maxTrackBreadthIsMaxContent;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/style/RenderStyle.cpp b/Source/core/rendering/style/RenderStyle.cpp
index 2d59087..7191c99 100644
--- a/Source/core/rendering/style/RenderStyle.cpp
+++ b/Source/core/rendering/style/RenderStyle.cpp
@@ -28,15 +28,15 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontSelector.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/TextAutosizer.h"
 #include "core/rendering/style/ContentData.h"
 #include "core/rendering/style/CursorList.h"
 #include "core/rendering/style/QuotesData.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
 #include "core/rendering/style/StyleImage.h"
 #include "core/rendering/style/StyleInheritedData.h"
+#include "platform/fonts/FontSelector.h"
 #include "wtf/MathExtras.h"
 #include "wtf/StdLibExtras.h"
 
@@ -910,30 +910,14 @@
     }
 }
 
-void RenderStyle::setTextShadow(PassOwnPtr<ShadowData> shadowData, bool add)
+void RenderStyle::setTextShadow(PassRefPtr<ShadowList> s)
 {
-    ASSERT(!shadowData || (!shadowData->spread() && shadowData->style() == Normal));
-
-    StyleRareInheritedData* rareData = rareInheritedData.access();
-    if (!add) {
-        rareData->textShadow = shadowData;
-        return;
-    }
-
-    shadowData->setNext(rareData->textShadow.release());
-    rareData->textShadow = shadowData;
+    rareInheritedData.access()->textShadow = s;
 }
 
-void RenderStyle::setBoxShadow(PassOwnPtr<ShadowData> shadowData, bool add)
+void RenderStyle::setBoxShadow(PassRefPtr<ShadowList> s)
 {
-    StyleRareNonInheritedData* rareData = rareNonInheritedData.access();
-    if (!add) {
-        rareData->m_boxShadow = shadowData;
-        return;
-    }
-
-    shadowData->setNext(rareData->m_boxShadow.release());
-    rareData->m_boxShadow = shadowData;
+    rareNonInheritedData.access()->m_boxShadow = s;
 }
 
 static RoundedRect::Radii calcRadiiFor(const BorderData& border, IntSize size, RenderView* renderView)
@@ -1294,72 +1278,80 @@
     font().update(currentFontSelector);
 }
 
-void RenderStyle::getShadowExtent(const ShadowData* shadow, LayoutUnit &top, LayoutUnit &right, LayoutUnit &bottom, LayoutUnit &left) const
+void RenderStyle::getShadowExtent(const ShadowList* shadowList, LayoutUnit &top, LayoutUnit &right, LayoutUnit &bottom, LayoutUnit &left) const
 {
     top = 0;
     right = 0;
     bottom = 0;
     left = 0;
 
-    for ( ; shadow; shadow = shadow->next()) {
-        if (shadow->style() == Inset)
+    size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
+    for (size_t i = 0; i < shadowCount; ++i) {
+        const ShadowData& shadow = shadowList->shadows()[i];
+        if (shadow.style() == Inset)
             continue;
-        int blurAndSpread = shadow->blur() + shadow->spread();
+        int blurAndSpread = shadow.blur() + shadow.spread();
 
-        top = min<LayoutUnit>(top, shadow->y() - blurAndSpread);
-        right = max<LayoutUnit>(right, shadow->x() + blurAndSpread);
-        bottom = max<LayoutUnit>(bottom, shadow->y() + blurAndSpread);
-        left = min<LayoutUnit>(left, shadow->x() - blurAndSpread);
+        top = min<LayoutUnit>(top, shadow.y() - blurAndSpread);
+        right = max<LayoutUnit>(right, shadow.x() + blurAndSpread);
+        bottom = max<LayoutUnit>(bottom, shadow.y() + blurAndSpread);
+        left = min<LayoutUnit>(left, shadow.x() - blurAndSpread);
     }
 }
 
-LayoutBoxExtent RenderStyle::getShadowInsetExtent(const ShadowData* shadow) const
+LayoutBoxExtent RenderStyle::getShadowInsetExtent(const ShadowList* shadowList) const
 {
     LayoutUnit top = 0;
     LayoutUnit right = 0;
     LayoutUnit bottom = 0;
     LayoutUnit left = 0;
 
-    for ( ; shadow; shadow = shadow->next()) {
-        if (shadow->style() == Normal)
+    size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
+    for (size_t i = 0; i < shadowCount; ++i) {
+        const ShadowData& shadow = shadowList->shadows()[i];
+        if (shadow.style() == Normal)
             continue;
-        int 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);
-        left = max<LayoutUnit>(left, shadow->x() + blurAndSpread);
+        int 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);
+        left = max<LayoutUnit>(left, shadow.x() + blurAndSpread);
     }
 
     return LayoutBoxExtent(top, right, bottom, left);
 }
 
-void RenderStyle::getShadowHorizontalExtent(const ShadowData* shadow, LayoutUnit &left, LayoutUnit &right) const
+void RenderStyle::getShadowHorizontalExtent(const ShadowList* shadowList, LayoutUnit &left, LayoutUnit &right) const
 {
     left = 0;
     right = 0;
 
-    for ( ; shadow; shadow = shadow->next()) {
-        if (shadow->style() == Inset)
+    size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
+    for (size_t i = 0; i < shadowCount; ++i) {
+        const ShadowData& shadow = shadowList->shadows()[i];
+        if (shadow.style() == Inset)
             continue;
-        int blurAndSpread = shadow->blur() + shadow->spread();
+        int blurAndSpread = shadow.blur() + shadow.spread();
 
-        left = min<LayoutUnit>(left, shadow->x() - blurAndSpread);
-        right = max<LayoutUnit>(right, shadow->x() + blurAndSpread);
+        left = min<LayoutUnit>(left, shadow.x() - blurAndSpread);
+        right = max<LayoutUnit>(right, shadow.x() + blurAndSpread);
     }
 }
 
-void RenderStyle::getShadowVerticalExtent(const ShadowData* shadow, LayoutUnit &top, LayoutUnit &bottom) const
+void RenderStyle::getShadowVerticalExtent(const ShadowList* shadowList, LayoutUnit &top, LayoutUnit &bottom) const
 {
     top = 0;
     bottom = 0;
 
-    for ( ; shadow; shadow = shadow->next()) {
-        if (shadow->style() == Inset)
+    size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
+    for (size_t i = 0; i < shadowCount; ++i) {
+        const ShadowData& shadow = shadowList->shadows()[i];
+        if (shadow.style() == Inset)
             continue;
-        int blurAndSpread = shadow->blur() + shadow->spread();
+        int blurAndSpread = shadow.blur() + shadow.spread();
 
-        top = min<LayoutUnit>(top, shadow->y() - blurAndSpread);
-        bottom = max<LayoutUnit>(bottom, shadow->y() + blurAndSpread);
+        top = min<LayoutUnit>(top, shadow.y() - blurAndSpread);
+        bottom = max<LayoutUnit>(bottom, shadow.y() + blurAndSpread);
     }
 }
 
diff --git a/Source/core/rendering/style/RenderStyle.h b/Source/core/rendering/style/RenderStyle.h
index 248c5f4..72f55cc 100644
--- a/Source/core/rendering/style/RenderStyle.h
+++ b/Source/core/rendering/style/RenderStyle.h
@@ -31,10 +31,6 @@
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/platform/ThemeTypes.h"
 #include "core/platform/animation/CSSAnimationDataList.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
 #include "core/rendering/style/BorderValue.h"
 #include "core/rendering/style/CounterDirectives.h"
 #include "core/rendering/style/DataRef.h"
@@ -43,7 +39,6 @@
 #include "core/rendering/style/OutlineValue.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "core/rendering/style/SVGRenderStyle.h"
-#include "core/rendering/style/ShadowData.h"
 #include "core/rendering/style/ShapeValue.h"
 #include "core/rendering/style/StyleBackgroundData.h"
 #include "core/rendering/style/StyleBoxData.h"
@@ -65,10 +60,14 @@
 #include "platform/LengthBox.h"
 #include "platform/LengthSize.h"
 #include "platform/fonts/FontBaseline.h"
+#include "platform/fonts/FontDescription.h"
 #include "platform/geometry/LayoutBoxExtent.h"
 #include "platform/geometry/RoundedRect.h"
+#include "platform/graphics/Color.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "platform/text/TextDirection.h"
 #include "platform/text/UnicodeBidi.h"
+#include "platform/transforms/TransformOperations.h"
 #include "wtf/Forward.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/RefCounted.h"
@@ -98,7 +97,7 @@
 class FontMetrics;
 class IntRect;
 class Pair;
-class ShadowData;
+class ShadowList;
 class StyleImage;
 class StyleInheritedData;
 class StyleResolver;
@@ -117,6 +116,7 @@
     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 StyleBuilderFunctions; // Sets color styles
+    friend class StyleBuilderConverter; // Reads unvisited color style for shadow currentColor
     friend class StyleBuilder; // FIXME: Revove this! StyleBuilder::oldApplyProperty reads color().
     friend class StyleResolver; // Sets members directly.
     friend class CachedUAStyle; // Saves Border/Background information for later comparison.
@@ -709,7 +709,7 @@
         return m_background->outline().offset();
     }
 
-    const ShadowData* textShadow() const { return rareInheritedData->textShadow.get(); }
+    ShadowList* textShadow() const { return rareInheritedData->textShadow.get(); }
     void getTextShadowExtent(LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const { getShadowExtent(textShadow(), top, right, bottom, left); }
     void getTextShadowHorizontalExtent(LayoutUnit& left, LayoutUnit& right) const { getShadowHorizontalExtent(textShadow(), left, right); }
     void getTextShadowVerticalExtent(LayoutUnit& top, LayoutUnit& bottom) const { getShadowVerticalExtent(textShadow(), top, bottom); }
@@ -765,7 +765,7 @@
     const GridPosition& gridRowStart() const { return rareNonInheritedData->m_gridItem->m_gridRowStart; }
     const GridPosition& gridRowEnd() const { return rareNonInheritedData->m_gridItem->m_gridRowEnd; }
 
-    const ShadowData* boxShadow() const { return rareNonInheritedData->m_boxShadow.get(); }
+    ShadowList* boxShadow() const { return rareNonInheritedData->m_boxShadow.get(); }
     void getBoxShadowExtent(LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const { getShadowExtent(boxShadow(), top, right, bottom, left); }
     LayoutBoxExtent getBoxShadowInsetExtent() const { return getShadowInsetExtent(boxShadow()); }
     void getBoxShadowHorizontalExtent(LayoutUnit& left, LayoutUnit& right) const { getShadowHorizontalExtent(boxShadow(), left, right); }
@@ -1192,7 +1192,7 @@
 
     // CSS3 Setters
     void setOutlineOffset(int v) { SET_VAR(m_background, m_outline.m_offset, v); }
-    void setTextShadow(PassOwnPtr<ShadowData>, bool add = false);
+    void setTextShadow(PassRefPtr<ShadowList>);
     void setTextStrokeColor(const Color& 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); }
@@ -1208,7 +1208,7 @@
     void setBoxOrdinalGroup(unsigned int og) { SET_VAR(rareNonInheritedData.access()->m_deprecatedFlexibleBox, ordinal_group, og); }
     void setBoxOrient(EBoxOrient o) { SET_VAR(rareNonInheritedData.access()->m_deprecatedFlexibleBox, orient, o); }
     void setBoxPack(EBoxPack p) { SET_VAR(rareNonInheritedData.access()->m_deprecatedFlexibleBox, pack, p); }
-    void setBoxShadow(PassOwnPtr<ShadowData>, bool add = false);
+    void setBoxShadow(PassRefPtr<ShadowList>);
     void setBoxReflect(PassRefPtr<StyleReflection> reflect) { if (rareNonInheritedData->m_boxReflect != reflect) rareNonInheritedData.access()->m_boxReflect = reflect; }
     void setBoxSizing(EBoxSizing s) { SET_VAR(m_box, m_boxSizing, s); }
     void setFlexGrow(float f) { SET_VAR(rareNonInheritedData.access()->m_flexibleBox, m_flexGrow, f); }
@@ -1487,6 +1487,8 @@
     bool unique() const { return noninherited_flags.unique; }
     void setUnique() { noninherited_flags.unique = true; }
 
+    bool isSharable() const;
+
     bool emptyState() const { return noninherited_flags.emptyState; }
     void setEmptyState(bool b) { setUnique(); noninherited_flags.emptyState = b; }
     bool firstChildState() const { return noninherited_flags.firstChildState; }
@@ -1642,6 +1644,8 @@
     static PrintColorAdjust initialPrintColorAdjust() { return PrintColorAdjustEconomy; }
     static TouchAction initialTouchAction() { return TouchActionAuto; }
     static TouchActionDelay initialTouchActionDelay() { return TouchActionDelayScript; }
+    static ShadowList* initialBoxShadow() { return 0; }
+    static ShadowList* initialTextShadow() { return 0; }
 
     // The initial value is 'none' for grid tracks.
     static Vector<GridTrackSize> initialGridDefinitionColumns() { return Vector<GridTrackSize>(); }
@@ -1705,15 +1709,15 @@
     void setVisitedLinkTextStrokeColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextStrokeColor, v); }
 
     void inheritUnicodeBidiFrom(const RenderStyle* parent) { noninherited_flags._unicodeBidi = parent->noninherited_flags._unicodeBidi; }
-    void getShadowExtent(const ShadowData*, LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const;
-    LayoutBoxExtent getShadowInsetExtent(const ShadowData*) const;
-    void getShadowHorizontalExtent(const ShadowData*, LayoutUnit& left, LayoutUnit& right) const;
-    void getShadowVerticalExtent(const ShadowData*, LayoutUnit& top, LayoutUnit& bottom) const;
-    void getShadowInlineDirectionExtent(const ShadowData* shadow, LayoutUnit& logicalLeft, LayoutUnit& logicalRight) const
+    void getShadowExtent(const ShadowList*, LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const;
+    LayoutBoxExtent getShadowInsetExtent(const ShadowList*) const;
+    void getShadowHorizontalExtent(const ShadowList*, LayoutUnit& left, LayoutUnit& right) const;
+    void getShadowVerticalExtent(const ShadowList*, LayoutUnit& top, LayoutUnit& bottom) const;
+    void getShadowInlineDirectionExtent(const ShadowList* shadow, LayoutUnit& logicalLeft, LayoutUnit& logicalRight) const
     {
         return isHorizontalWritingMode() ? getShadowHorizontalExtent(shadow, logicalLeft, logicalRight) : getShadowVerticalExtent(shadow, logicalLeft, logicalRight);
     }
-    void getShadowBlockDirectionExtent(const ShadowData* shadow, LayoutUnit& logicalTop, LayoutUnit& logicalBottom) const
+    void getShadowBlockDirectionExtent(const ShadowList* shadow, LayoutUnit& logicalTop, LayoutUnit& logicalBottom) const
     {
         return isHorizontalWritingMode() ? getShadowVerticalExtent(shadow, logicalTop, logicalBottom) : getShadowHorizontalExtent(shadow, logicalTop, logicalBottom);
     }
@@ -1808,6 +1812,17 @@
     return true;
 }
 
+inline bool RenderStyle::isSharable() const
+{
+    if (unique())
+        return false;
+    if (hasUniquePseudoStyle())
+        return false;
+    if (transitions() || animations())
+        return false;
+    return true;
+}
+
 inline bool RenderStyle::setTextOrientation(TextOrientation textOrientation)
 {
     if (compareEqual(rareInheritedData->m_textOrientation, textOrientation))
diff --git a/Source/core/rendering/style/SVGRenderStyle.h b/Source/core/rendering/style/SVGRenderStyle.h
index 658af07..2f06804 100644
--- a/Source/core/rendering/style/SVGRenderStyle.h
+++ b/Source/core/rendering/style/SVGRenderStyle.h
@@ -25,12 +25,12 @@
 
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/css/CSSValueList.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/graphics/Path.h"
 #include "core/rendering/style/DataRef.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "core/rendering/style/SVGRenderStyleDefs.h"
 #include "core/svg/SVGPaint.h"
+#include "platform/graphics/GraphicsTypes.h"
 
 namespace WebCore {
 
diff --git a/Source/core/rendering/style/ShadowData.cpp b/Source/core/rendering/style/ShadowData.cpp
index 391d713..7f81d90 100644
--- a/Source/core/rendering/style/ShadowData.cpp
+++ b/Source/core/rendering/style/ShadowData.cpp
@@ -22,28 +22,12 @@
 #include "config.h"
 #include "core/rendering/style/ShadowData.h"
 
-#include "platform/geometry/LayoutRect.h"
-
-using namespace std;
+#include "platform/animation/AnimationUtilities.h"
 
 namespace WebCore {
 
-ShadowData::ShadowData(const ShadowData& o)
-    : m_location(o.m_location)
-    , m_blur(o.m_blur)
-    , m_spread(o.m_spread)
-    , m_color(o.m_color)
-    , m_style(o.m_style)
-    , m_next(o.m_next ? adoptPtr(new ShadowData(*o.m_next)) : nullptr)
-{
-}
-
 bool ShadowData::operator==(const ShadowData& o) const
 {
-    if ((m_next && !o.m_next) || (!m_next && o.m_next)
-        || (m_next && o.m_next && *m_next != *o.m_next))
-        return false;
-
     return m_location == o.m_location
         && m_blur == o.m_blur
         && m_spread == o.m_spread
@@ -51,45 +35,16 @@
         && m_color == o.m_color;
 }
 
-static inline void calculateShadowExtent(const ShadowData* shadow, int additionalOutlineSize, int& shadowLeft, int& shadowRight, int& shadowTop, int& shadowBottom)
+ShadowData ShadowData::blend(const ShadowData& from, double progress) const
 {
-    do {
-        int blurAndSpread = shadow->blur() + shadow->spread() + additionalOutlineSize;
-        if (shadow->style() == Normal) {
-            shadowLeft = min(shadow->x() - blurAndSpread, shadowLeft);
-            shadowRight = max(shadow->x() + blurAndSpread, shadowRight);
-            shadowTop = min(shadow->y() - blurAndSpread, shadowTop);
-            shadowBottom = max(shadow->y() + blurAndSpread, shadowBottom);
-        }
+    if (style() != from.style())
+        return *this;
 
-        shadow = shadow->next();
-    } while (shadow);
-}
-
-void ShadowData::adjustRectForShadow(LayoutRect& rect, int 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);
-}
-
-void ShadowData::adjustRectForShadow(FloatRect& rect, int 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);
+    return ShadowData(WebCore::blend(from.location(), location(), progress),
+        clampTo<int>(WebCore::blend(from.blur(), blur(), progress), 0),
+        WebCore::blend(from.spread(), spread(), progress),
+        style(),
+        WebCore::blend(from.color(), color(), progress));
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/style/ShadowData.h b/Source/core/rendering/style/ShadowData.h
index cb82aa5..574b3f8 100644
--- a/Source/core/rendering/style/ShadowData.h
+++ b/Source/core/rendering/style/ShadowData.h
@@ -25,11 +25,8 @@
 #ifndef ShadowData_h
 #define ShadowData_h
 
-#include "core/platform/graphics/Color.h"
-#include "platform/geometry/FloatRect.h"
-#include "platform/geometry/LayoutRect.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
+#include "platform/geometry/IntPoint.h"
+#include "platform/graphics/Color.h"
 
 namespace WebCore {
 
@@ -39,42 +36,6 @@
 class ShadowData {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<ShadowData> create() { return adoptPtr(new ShadowData); }
-    static PassOwnPtr<ShadowData> create(const IntPoint& location, int blur, int spread, ShadowStyle style, const Color& color)
-    {
-        return adoptPtr(new ShadowData(location, blur, spread, style, color));
-    }
-    // This clones the whole ShadowData linked list.
-    PassOwnPtr<ShadowData> clone() const
-    {
-        return adoptPtr(new ShadowData(*this));
-    }
-
-    bool operator==(const ShadowData&) const;
-    bool operator!=(const ShadowData& o) const { return !(*this == o); }
-
-    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; }
-    ShadowStyle style() const { return m_style; }
-    const Color& color() const { return m_color; }
-
-    const ShadowData* next() const { return m_next.get(); }
-    void setNext(PassOwnPtr<ShadowData> shadow) { m_next = shadow; }
-
-    void adjustRectForShadow(LayoutRect&, int additionalOutlineSize = 0) const;
-    void adjustRectForShadow(FloatRect&, int additionalOutlineSize = 0) const;
-
-private:
-    ShadowData()
-        : m_blur(0)
-        , m_spread(0)
-        , m_style(Normal)
-    {
-    }
-
     ShadowData(const IntPoint& location, int blur, int spread, ShadowStyle style, const Color& color)
         : m_location(location)
         , m_blur(blur)
@@ -84,27 +45,27 @@
     {
     }
 
-    ShadowData(const ShadowData&);
+    bool operator==(const ShadowData&) const;
+    bool operator!=(const ShadowData& o) const { return !(*this == o); }
 
+    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; }
+    ShadowStyle style() const { return m_style; }
+    const Color& color() const { return m_color; }
+
+private:
     IntPoint m_location;
     int m_blur;
     int m_spread;
     Color m_color;
     ShadowStyle m_style;
-    OwnPtr<ShadowData> m_next;
 };
 
-// Helper method to handle nullptr, otherwise all callers need an ugly ternary.
-inline PassOwnPtr<ShadowData> cloneShadow(const ShadowData* shadow)
-{
-    return shadow ? shadow->clone() : nullptr;
-}
-
-inline PassOwnPtr<ShadowData> cloneShadow(const OwnPtr<ShadowData>& shadow)
-{
-    return cloneShadow(shadow.get());
-}
-
 } // namespace WebCore
 
 #endif // ShadowData_h
diff --git a/Source/core/rendering/style/ShadowList.cpp b/Source/core/rendering/style/ShadowList.cpp
new file mode 100644
index 0000000..675effe
--- /dev/null
+++ b/Source/core/rendering/style/ShadowList.cpp
@@ -0,0 +1,107 @@
+/*
+ * 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/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)
+{
+    ASSERT(shadowList);
+    size_t shadowCount = shadowList->shadows().size();
+    for (size_t i = 0; i < shadowCount; ++i) {
+        const ShadowData& shadow = shadowList->shadows()[i];
+        if (shadow.style() == Inset)
+            continue;
+        int 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);
+        shadowBottom = std::max(shadow.y() + blurAndSpread, shadowBottom);
+    }
+}
+
+void ShadowList::adjustRectForShadow(LayoutRect& rect, int 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);
+}
+
+void ShadowList::adjustRectForShadow(FloatRect& rect, int 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);
+}
+
+PassRefPtr<ShadowList> ShadowList::blend(const ShadowList* from, const ShadowList* to, double progress)
+{
+    size_t fromLength = from ? from->shadows().size() : 0;
+    size_t toLength = to ? to->shadows().size() : 0;
+    if (!fromLength && !toLength)
+        return 0;
+
+    ShadowDataVector shadows;
+
+    DEFINE_STATIC_LOCAL(ShadowData, defaultShadowData, (IntPoint(), 0, 0, Normal, Color::transparent));
+    DEFINE_STATIC_LOCAL(ShadowData, defaultInsetShadowData, (IntPoint(), 0, 0, Inset, Color::transparent));
+
+    size_t maxLength = std::max(fromLength, toLength);
+    for (size_t i = 0; i < maxLength; ++i) {
+        const ShadowData* fromShadow = i < fromLength ? &from->shadows()[i] : 0;
+        const ShadowData* toShadow = i < toLength ? &to->shadows()[i] : 0;
+        if (!fromShadow)
+            fromShadow = toShadow->style() == Inset ? &defaultInsetShadowData : &defaultShadowData;
+        else if (!toShadow)
+            toShadow = fromShadow->style() == Inset ? &defaultInsetShadowData : &defaultShadowData;
+        shadows.append(toShadow->blend(*fromShadow, progress));
+    }
+
+    return ShadowList::adopt(shadows);
+}
+
+} // namespace WebCore
diff --git a/Source/core/rendering/style/ShadowList.h b/Source/core/rendering/style/ShadowList.h
new file mode 100644
index 0000000..12acedf
--- /dev/null
+++ b/Source/core/rendering/style/ShadowList.h
@@ -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.
+ */
+
+#ifndef ShadowList_h
+#define ShadowList_h
+
+#include "core/rendering/style/ShadowData.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class FloatRect;
+class LayoutRect;
+
+typedef Vector<ShadowData, 1> ShadowDataVector;
+
+// These are used to store shadows in specified order, but we usually want to
+// iterate over them backwards as the first-specified shadow is painted on top.
+class ShadowList : public RefCounted<ShadowList> {
+public:
+    // This consumes passed in vector.
+    static PassRefPtr<ShadowList> adopt(ShadowDataVector& shadows)
+    {
+        return adoptRef(new ShadowList(shadows));
+    }
+    const ShadowDataVector& shadows() const { return m_shadows; }
+    bool operator==(const ShadowList& o) const { return m_shadows == o.m_shadows; }
+    bool operator!=(const ShadowList& o) const { return !(*this == o); }
+
+    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;
+
+private:
+    ShadowList(ShadowDataVector& shadows)
+    {
+        // If we have no shadows, we use a null ShadowList
+        ASSERT(!shadows.isEmpty());
+        m_shadows.swap(shadows);
+        m_shadows.shrinkToFit();
+    }
+    ShadowDataVector m_shadows;
+};
+
+} // namespace WebCore
+
+#endif // ShadowList_h
diff --git a/Source/core/rendering/style/StyleBackgroundData.h b/Source/core/rendering/style/StyleBackgroundData.h
index 78f2042..fda242f 100644
--- a/Source/core/rendering/style/StyleBackgroundData.h
+++ b/Source/core/rendering/style/StyleBackgroundData.h
@@ -25,9 +25,9 @@
 #ifndef StyleBackgroundData_h
 #define StyleBackgroundData_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/rendering/style/FillLayer.h"
 #include "core/rendering/style/OutlineValue.h"
+#include "platform/graphics/Color.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 
diff --git a/Source/core/rendering/style/StyleInheritedData.h b/Source/core/rendering/style/StyleInheritedData.h
index 776a5c2..828e303 100644
--- a/Source/core/rendering/style/StyleInheritedData.h
+++ b/Source/core/rendering/style/StyleInheritedData.h
@@ -25,9 +25,9 @@
 #ifndef StyleInheritedData_h
 #define StyleInheritedData_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/Font.h"
 #include "platform/Length.h"
+#include "platform/graphics/Color.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/rendering/style/StyleRareInheritedData.cpp b/Source/core/rendering/style/StyleRareInheritedData.cpp
index 40db1a1..99c7718 100644
--- a/Source/core/rendering/style/StyleRareInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareInheritedData.cpp
@@ -26,7 +26,7 @@
 #include "core/rendering/style/QuotesData.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/style/RenderStyleConstants.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
 #include "core/rendering/style/StyleImage.h"
 
 namespace WebCore {
@@ -74,7 +74,6 @@
     , textEmphasisFill(TextEmphasisFillFilled)
     , textEmphasisMark(TextEmphasisMarkNone)
     , textEmphasisPosition(TextEmphasisPositionOver)
-    , m_touchActionDelay(RenderStyle::initialTouchActionDelay())
     , m_textAlignLast(RenderStyle::initialTextAlignLast())
     , m_textJustify(RenderStyle::initialTextJustify())
     , m_textOrientation(TextOrientationVerticalRight)
@@ -87,6 +86,7 @@
     , m_textUnderlinePosition(RenderStyle::initialTextUnderlinePosition())
 #endif // CSS3_TEXT
     , m_rubyPosition(RenderStyle::initialRubyPosition())
+    , m_touchActionDelay(RenderStyle::initialTouchActionDelay())
     , hyphenationLimitBefore(-1)
     , hyphenationLimitAfter(-1)
     , hyphenationLimitLines(-1)
@@ -107,7 +107,7 @@
     , visitedLinkTextStrokeColor(o.visitedLinkTextStrokeColor)
     , visitedLinkTextFillColor(o.visitedLinkTextFillColor)
     , visitedLinkTextEmphasisColor(o.visitedLinkTextEmphasisColor)
-    , textShadow(cloneShadow(o.textShadow))
+    , textShadow(o.textShadow)
     , highlight(o.highlight)
     , cursorData(o.cursorData)
     , indent(o.indent)
@@ -128,7 +128,6 @@
     , textEmphasisFill(o.textEmphasisFill)
     , textEmphasisMark(o.textEmphasisMark)
     , textEmphasisPosition(o.textEmphasisPosition)
-    , m_touchActionDelay(o.m_touchActionDelay)
     , m_textAlignLast(o.m_textAlignLast)
     , m_textJustify(o.m_textJustify)
     , m_textOrientation(o.m_textOrientation)
@@ -141,6 +140,7 @@
     , m_textUnderlinePosition(o.m_textUnderlinePosition)
 #endif // CSS3_TEXT
     , m_rubyPosition(o.m_rubyPosition)
+    , m_touchActionDelay(o.m_touchActionDelay)
     , hyphenationString(o.hyphenationString)
     , hyphenationLimitBefore(o.hyphenationLimitBefore)
     , hyphenationLimitAfter(o.hyphenationLimitAfter)
diff --git a/Source/core/rendering/style/StyleRareInheritedData.h b/Source/core/rendering/style/StyleRareInheritedData.h
index 0a7ed20..d7b7441 100644
--- a/Source/core/rendering/style/StyleRareInheritedData.h
+++ b/Source/core/rendering/style/StyleRareInheritedData.h
@@ -25,10 +25,10 @@
 #ifndef StyleRareInheritedData_h
 #define StyleRareInheritedData_h
 
-#include "core/platform/graphics/Color.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"
 #include "wtf/RefCounted.h"
 #include "wtf/text/AtomicString.h"
@@ -37,7 +37,7 @@
 
 class CursorList;
 class QuotesData;
-class ShadowData;
+class ShadowList;
 class StyleImage;
 
 // This struct is for rarely used inherited CSS3, CSS2, and WebKit-specific properties.
@@ -67,7 +67,7 @@
     Color visitedLinkTextFillColor;
     Color visitedLinkTextEmphasisColor;
 
-    OwnPtr<ShadowData> textShadow; // Our text shadow information for shadowed text drawing.
+    RefPtr<ShadowList> textShadow; // Our text shadow information for shadowed text drawing.
     AtomicString highlight; // Apple-specific extension for custom highlight rendering.
 
     RefPtr<CursorList> cursorData;
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.cpp b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
index c97f2f9..66ef53e 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
@@ -24,7 +24,7 @@
 
 #include "core/rendering/style/ContentData.h"
 #include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
 #include "core/rendering/style/StyleFilterData.h"
 #include "core/rendering/style/StyleTransformData.h"
 
@@ -103,7 +103,7 @@
     , m_gridItem(o.m_gridItem)
     , m_content(o.m_content ? o.m_content->clone() : nullptr)
     , m_counterDirectives(o.m_counterDirectives ? clone(*o.m_counterDirectives) : nullptr)
-    , m_boxShadow(cloneShadow(o.m_boxShadow))
+    , m_boxShadow(o.m_boxShadow)
     , m_boxReflect(o.m_boxReflect)
     , m_animations(o.m_animations ? adoptPtr(new CSSAnimationDataList(*o.m_animations)) : nullptr)
     , m_transitions(o.m_transitions ? adoptPtr(new CSSAnimationDataList(*o.m_transitions)) : nullptr)
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.h b/Source/core/rendering/style/StyleRareNonInheritedData.h
index 945de6c..7009e42 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.h
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.h
@@ -43,7 +43,7 @@
 
 class ContentData;
 class CSSAnimationDataList;
-class ShadowData;
+class ShadowList;
 class StyleDeprecatedFlexibleBoxData;
 class StyleFilterData;
 class StyleFlexibleBoxData;
@@ -114,7 +114,7 @@
     OwnPtr<ContentData> m_content;
     OwnPtr<CounterDirectiveMap> m_counterDirectives;
 
-    OwnPtr<ShadowData> m_boxShadow;  // For box-shadow decorations.
+    RefPtr<ShadowList> m_boxShadow;
 
     RefPtr<StyleReflection> m_boxReflect;
 
diff --git a/Source/core/rendering/style/StyleTransformData.h b/Source/core/rendering/style/StyleTransformData.h
index a470a8f..3253652 100644
--- a/Source/core/rendering/style/StyleTransformData.h
+++ b/Source/core/rendering/style/StyleTransformData.h
@@ -25,8 +25,8 @@
 #ifndef StyleTransformData_h
 #define StyleTransformData_h
 
-#include "core/platform/graphics/transforms/TransformOperations.h"
 #include "platform/Length.h"
+#include "platform/transforms/TransformOperations.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 
diff --git a/Source/core/rendering/svg/RenderSVGBlock.cpp b/Source/core/rendering/svg/RenderSVGBlock.cpp
index c3bed7e..7ce9ad6 100644
--- a/Source/core/rendering/svg/RenderSVGBlock.cpp
+++ b/Source/core/rendering/svg/RenderSVGBlock.cpp
@@ -23,6 +23,7 @@
 
 #include "core/rendering/svg/RenderSVGBlock.h"
 
+#include "core/rendering/style/ShadowList.h"
 #include "core/rendering/svg/SVGResourcesCache.h"
 #include "core/svg/SVGElement.h"
 
@@ -37,7 +38,7 @@
 {
     LayoutRect borderRect = borderBoxRect();
 
-    if (const ShadowData* textShadow = style()->textShadow())
+    if (const ShadowList* textShadow = style()->textShadow())
         textShadow->adjustRectForShadow(borderRect);
 
     return borderRect;
@@ -89,15 +90,11 @@
     RenderBlock::willBeDestroyed();
 }
 
-void RenderSVGBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+void RenderSVGBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
     if (diff == StyleDifferenceLayout)
         setNeedsBoundariesUpdate();
-    RenderBlock::styleWillChange(diff, newStyle);
-}
 
-void RenderSVGBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
     RenderBlock::styleDidChange(diff, oldStyle);
     SVGResourcesCache::clientStyleChanged(this, diff, style());
 }
diff --git a/Source/core/rendering/svg/RenderSVGBlock.h b/Source/core/rendering/svg/RenderSVGBlock.h
index 7963e73..1d638cc 100644
--- a/Source/core/rendering/svg/RenderSVGBlock.h
+++ b/Source/core/rendering/svg/RenderSVGBlock.h
@@ -45,7 +45,6 @@
 
     virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE FINAL;
 
-    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE FINAL;
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
 };
 
diff --git a/Source/core/rendering/svg/RenderSVGInline.cpp b/Source/core/rendering/svg/RenderSVGInline.cpp
index 917ea33..68b1a40 100644
--- a/Source/core/rendering/svg/RenderSVGInline.cpp
+++ b/Source/core/rendering/svg/RenderSVGInline.cpp
@@ -112,15 +112,11 @@
     RenderInline::willBeDestroyed();
 }
 
-void RenderSVGInline::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+void RenderSVGInline::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
     if (diff == StyleDifferenceLayout)
         setNeedsBoundariesUpdate();
-    RenderInline::styleWillChange(diff, newStyle);
-}
 
-void RenderSVGInline::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
     RenderInline::styleDidChange(diff, oldStyle);
     SVGResourcesCache::clientStyleChanged(this, diff, style());
 }
diff --git a/Source/core/rendering/svg/RenderSVGInline.h b/Source/core/rendering/svg/RenderSVGInline.h
index 4cc390f..43634a3 100644
--- a/Source/core/rendering/svg/RenderSVGInline.h
+++ b/Source/core/rendering/svg/RenderSVGInline.h
@@ -54,7 +54,6 @@
     virtual InlineFlowBox* createInlineFlowBox() OVERRIDE FINAL;
 
     virtual void willBeDestroyed() OVERRIDE FINAL;
-    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE FINAL;
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
 
     virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE FINAL;
diff --git a/Source/core/rendering/svg/RenderSVGModelObject.cpp b/Source/core/rendering/svg/RenderSVGModelObject.cpp
index 124f5a0..56312a7 100644
--- a/Source/core/rendering/svg/RenderSVGModelObject.cpp
+++ b/Source/core/rendering/svg/RenderSVGModelObject.cpp
@@ -105,18 +105,14 @@
     // We don't walk into SVG trees at all - just report their container.
 }
 
-void RenderSVGModelObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+void RenderSVGModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
     if (diff == StyleDifferenceLayout) {
         setNeedsBoundariesUpdate();
-        if (newStyle->hasTransform())
+        if (style()->hasTransform())
             setNeedsTransformUpdate();
     }
-    RenderObject::styleWillChange(diff, newStyle);
-}
 
-void RenderSVGModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
     RenderObject::styleDidChange(diff, oldStyle);
     SVGResourcesCache::clientStyleChanged(this, diff, style());
 }
diff --git a/Source/core/rendering/svg/RenderSVGModelObject.h b/Source/core/rendering/svg/RenderSVGModelObject.h
index e06d688..c8df10a 100644
--- a/Source/core/rendering/svg/RenderSVGModelObject.h
+++ b/Source/core/rendering/svg/RenderSVGModelObject.h
@@ -58,7 +58,6 @@
 
     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 styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE FINAL;
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
 
     static bool checkIntersection(RenderObject*, const SVGRect&);
diff --git a/Source/core/rendering/svg/RenderSVGResource.h b/Source/core/rendering/svg/RenderSVGResource.h
index 5feaa1a..314a69e 100644
--- a/Source/core/rendering/svg/RenderSVGResource.h
+++ b/Source/core/rendering/svg/RenderSVGResource.h
@@ -62,7 +62,6 @@
 
     virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) = 0;
     virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short, const Path*, const RenderSVGShape*) { }
-    virtual FloatRect resourceBoundingBox(RenderObject*) = 0;
 
     virtual RenderSVGResourceType resourceType() const = 0;
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
index eaf1d81..d092800 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
@@ -38,7 +38,7 @@
 
 namespace WebCore {
 
-RenderSVGResourceType RenderSVGResourceClipper::s_resourceType = ClipperResourceType;
+const RenderSVGResourceType RenderSVGResourceClipper::s_resourceType = ClipperResourceType;
 
 RenderSVGResourceClipper::RenderSVGResourceClipper(SVGClipPathElement* node)
     : RenderSVGResourceContainer(node)
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.h b/Source/core/rendering/svg/RenderSVGResourceClipper.h
index 839583c..ceee186 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.h
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.h
@@ -62,15 +62,15 @@
     // 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&);
 
-    virtual FloatRect resourceBoundingBox(RenderObject*);
+    FloatRect resourceBoundingBox(RenderObject*);
 
-    virtual RenderSVGResourceType resourceType() const { return ClipperResourceType; }
+    virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
 
     bool hitTestClipContent(const FloatRect&, const FloatPoint&);
 
     SVGUnitTypes::SVGUnitType clipPathUnits() const { return toSVGClipPathElement(element())->clipPathUnitsCurrentValue(); }
 
-    static RenderSVGResourceType s_resourceType;
+    static const RenderSVGResourceType s_resourceType;
 private:
     bool tryPathOnlyClipping(GraphicsContext*, const AffineTransform&, const FloatRect&);
     void drawMaskContent(GraphicsContext*, const FloatRect& targetBoundingBox);
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
index 0f323dc..6280a41 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
@@ -39,10 +39,10 @@
 
 RenderSVGResourceContainer::RenderSVGResourceContainer(SVGElement* node)
     : RenderSVGHiddenContainer(node)
+    , m_isInLayout(false)
     , m_id(node->getIdAttribute())
     , m_registered(false)
     , m_isInvalidating(false)
-    , m_isInLayout(false)
 {
 }
 
@@ -54,16 +54,14 @@
 
 void RenderSVGResourceContainer::layout()
 {
+    // FIXME: Investigate a way to detect and break resource layout dependency cycles early.
+    // Then we can remove this method altogether, and fall back onto RenderSVGHiddenContainer::layout().
     ASSERT(needsLayout());
     if (m_isInLayout)
         return;
 
     TemporaryChange<bool> inLayoutChange(m_isInLayout, true);
 
-    // Invalidate all resources if our layout changed.
-    if (everHadLayout() && selfNeedsLayout())
-        removeAllClientsFromCache();
-
     RenderSVGHiddenContainer::layout();
 }
 
@@ -183,6 +181,17 @@
     m_clientLayers.remove(client);
 }
 
+void RenderSVGResourceContainer::invalidateCacheAndMarkForLayout(SubtreeLayoutScope* layoutScope)
+{
+    if (selfNeedsLayout())
+        return;
+
+    setNeedsLayout(MarkContainingBlockChain, layoutScope);
+
+    if (everHadLayout())
+        removeAllClientsFromCache();
+}
+
 void RenderSVGResourceContainer::registerResource()
 {
     SVGDocumentExtensions* extensions = svgExtensionsFromElement(element());
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.h b/Source/core/rendering/svg/RenderSVGResourceContainer.h
index b5d1d13..07bee61 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.h
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.h
@@ -46,6 +46,8 @@
     void addClientRenderLayer(RenderLayer*);
     void removeClientRenderLayer(RenderLayer*);
 
+    void invalidateCacheAndMarkForLayout(SubtreeLayoutScope* = 0);
+
 protected:
     enum InvalidationMode {
         LayoutAndBoundariesInvalidation,
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
index ba38c68..fccbe59 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-RenderSVGResourceType RenderSVGResourceFilter::s_resourceType = FilterResourceType;
+const RenderSVGResourceType RenderSVGResourceFilter::s_resourceType = FilterResourceType;
 
 RenderSVGResourceFilter::RenderSVGResourceFilter(SVGFilterElement* node)
     : RenderSVGResourceContainer(node)
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.h b/Source/core/rendering/svg/RenderSVGResourceFilter.h
index b8fe21e..6455b03 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.h
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.h
@@ -69,7 +69,7 @@
     virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode);
     virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*);
 
-    virtual FloatRect resourceBoundingBox(RenderObject*);
+    FloatRect resourceBoundingBox(RenderObject*);
 
     PassRefPtr<SVGFilterBuilder> buildPrimitives(SVGFilter*);
 
@@ -79,7 +79,7 @@
     void primitiveAttributeChanged(RenderObject*, const QualifiedName&);
 
     virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
-    static RenderSVGResourceType s_resourceType;
+    static const RenderSVGResourceType s_resourceType;
 
     FloatRect drawingRegion(RenderObject*) const;
 private:
diff --git a/Source/core/rendering/svg/RenderSVGResourceGradient.h b/Source/core/rendering/svg/RenderSVGResourceGradient.h
index 82ef84c..37fa1d7 100644
--- a/Source/core/rendering/svg/RenderSVGResourceGradient.h
+++ b/Source/core/rendering/svg/RenderSVGResourceGradient.h
@@ -50,7 +50,6 @@
 
     virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE FINAL;
     virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*) OVERRIDE FINAL;
-    virtual FloatRect resourceBoundingBox(RenderObject*) OVERRIDE FINAL { return FloatRect(); }
 
 protected:
     void addStops(GradientData*, const Vector<Gradient::ColorStop>&) const;
diff --git a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
index c8936a6..604c5db 100644
--- a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
@@ -27,7 +27,7 @@
 
 namespace WebCore {
 
-RenderSVGResourceType RenderSVGResourceLinearGradient::s_resourceType = LinearGradientResourceType;
+const RenderSVGResourceType RenderSVGResourceLinearGradient::s_resourceType = LinearGradientResourceType;
 
 RenderSVGResourceLinearGradient::RenderSVGResourceLinearGradient(SVGLinearGradientElement* node)
     : RenderSVGResourceGradient(node)
diff --git a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
index 048468c..ba1c3d2 100644
--- a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
+++ b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
@@ -36,7 +36,7 @@
     virtual const char* renderName() const { return "RenderSVGResourceLinearGradient"; }
 
     virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
-    static RenderSVGResourceType 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(); }
diff --git a/Source/core/rendering/svg/RenderSVGResourceMarker.cpp b/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
index 5f3108d..ce2aa98 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-RenderSVGResourceType RenderSVGResourceMarker::s_resourceType = MarkerResourceType;
+const RenderSVGResourceType RenderSVGResourceMarker::s_resourceType = MarkerResourceType;
 
 RenderSVGResourceMarker::RenderSVGResourceMarker(SVGMarkerElement* node)
     : RenderSVGResourceContainer(node)
@@ -138,7 +138,7 @@
     // An empty viewBox disables rendering.
     SVGMarkerElement* marker = toSVGMarkerElement(element());
     ASSERT(marker);
-    if (marker->hasAttribute(SVGNames::viewBoxAttr) && marker->viewBoxIsValid() && marker->viewBoxCurrentValue().isEmpty())
+    if (marker->hasAttribute(SVGNames::viewBoxAttr) && marker->viewBoxCurrentValue().isValid() && marker->viewBoxCurrentValue().isEmpty())
         return;
 
     PaintInfo info(paintInfo);
diff --git a/Source/core/rendering/svg/RenderSVGResourceMarker.h b/Source/core/rendering/svg/RenderSVGResourceMarker.h
index 95396f0..afe4913 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMarker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMarker.h
@@ -54,14 +54,13 @@
     AffineTransform markerTransformation(const FloatPoint& origin, float angle, float strokeWidth) const;
 
     virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short) { return false; }
-    virtual FloatRect resourceBoundingBox(RenderObject*) { return FloatRect(); }
 
     FloatPoint referencePoint() const;
     float angle() const;
     SVGMarkerUnitsType markerUnits() const { return toSVGMarkerElement(element())->markerUnitsCurrentValue(); }
 
     virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
-    static RenderSVGResourceType s_resourceType;
+    static const RenderSVGResourceType s_resourceType;
 
 private:
     // Generates a transformation matrix usable to render marker content. Handles scaling the marker content
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
index 4939aa1..2fe2919 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-RenderSVGResourceType RenderSVGResourceMasker::s_resourceType = MaskerResourceType;
+const RenderSVGResourceType RenderSVGResourceMasker::s_resourceType = MaskerResourceType;
 
 RenderSVGResourceMasker::RenderSVGResourceMasker(SVGMaskElement* node)
     : RenderSVGResourceContainer(node)
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.h b/Source/core/rendering/svg/RenderSVGResourceMasker.h
index acfde04..5c4fd8a 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.h
@@ -44,13 +44,13 @@
     virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true);
     virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE;
     virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short, const Path*, const RenderSVGShape*) OVERRIDE;
-    virtual FloatRect resourceBoundingBox(RenderObject*);
+    FloatRect resourceBoundingBox(RenderObject*);
 
     SVGUnitTypes::SVGUnitType maskUnits() const { return toSVGMaskElement(element())->maskUnitsCurrentValue(); }
     SVGUnitTypes::SVGUnitType maskContentUnits() const { return toSVGMaskElement(element())->maskContentUnitsCurrentValue(); }
 
     virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
-    static RenderSVGResourceType s_resourceType;
+    static const RenderSVGResourceType s_resourceType;
 
 private:
     void calculateMaskContentRepaintRect();
diff --git a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
index 74c11c5..1333841 100644
--- a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-RenderSVGResourceType RenderSVGResourcePattern::s_resourceType = PatternResourceType;
+const RenderSVGResourceType RenderSVGResourcePattern::s_resourceType = PatternResourceType;
 
 RenderSVGResourcePattern::RenderSVGResourcePattern(SVGPatternElement* node)
     : RenderSVGResourceContainer(node)
diff --git a/Source/core/rendering/svg/RenderSVGResourcePattern.h b/Source/core/rendering/svg/RenderSVGResourcePattern.h
index 3206cdf..6ffe71d 100644
--- a/Source/core/rendering/svg/RenderSVGResourcePattern.h
+++ b/Source/core/rendering/svg/RenderSVGResourcePattern.h
@@ -53,10 +53,9 @@
 
     virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode);
     virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*);
-    virtual FloatRect resourceBoundingBox(RenderObject*) { return FloatRect(); }
 
     virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
-    static RenderSVGResourceType s_resourceType;
+    static const RenderSVGResourceType s_resourceType;
 
 private:
     bool buildTileImageTransform(RenderObject*, const PatternAttributes&, const SVGPatternElement*, FloatRect& patternBoundaries, AffineTransform& tileImageTransform) const;
diff --git a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
index f9b9359..38e2049 100644
--- a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
@@ -28,7 +28,7 @@
 
 namespace WebCore {
 
-RenderSVGResourceType RenderSVGResourceRadialGradient::s_resourceType = RadialGradientResourceType;
+const RenderSVGResourceType RenderSVGResourceRadialGradient::s_resourceType = RadialGradientResourceType;
 
 RenderSVGResourceRadialGradient::RenderSVGResourceRadialGradient(SVGRadialGradientElement* node)
     : RenderSVGResourceGradient(node)
diff --git a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
index 739de28..3705c81 100644
--- a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
+++ b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
@@ -36,7 +36,7 @@
     virtual const char* renderName() const { return "RenderSVGResourceRadialGradient"; }
 
     virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
-    static RenderSVGResourceType 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(); }
diff --git a/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp b/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp
index eb60a76..ab8999a 100644
--- a/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-RenderSVGResourceType RenderSVGResourceSolidColor::s_resourceType = SolidColorResourceType;
+const RenderSVGResourceType RenderSVGResourceSolidColor::s_resourceType = SolidColorResourceType;
 
 RenderSVGResourceSolidColor::RenderSVGResourceSolidColor()
 {
diff --git a/Source/core/rendering/svg/RenderSVGResourceSolidColor.h b/Source/core/rendering/svg/RenderSVGResourceSolidColor.h
index ce31414..85937ce 100644
--- a/Source/core/rendering/svg/RenderSVGResourceSolidColor.h
+++ b/Source/core/rendering/svg/RenderSVGResourceSolidColor.h
@@ -20,9 +20,9 @@
 #ifndef RenderSVGResourceSolidColor_h
 #define RenderSVGResourceSolidColor_h
 
-#include "core/platform/graphics/Color.h"
 #include "core/rendering/svg/RenderSVGResource.h"
 #include "platform/geometry/FloatRect.h"
+#include "platform/graphics/Color.h"
 
 namespace WebCore {
 
@@ -36,10 +36,9 @@
 
     virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode);
     virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*);
-    virtual FloatRect resourceBoundingBox(RenderObject*) { return FloatRect(); }
 
     virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
-    static RenderSVGResourceType s_resourceType;
+    static const RenderSVGResourceType s_resourceType;
 
     const Color& color() const { return m_color; }
     void setColor(const Color& color) { m_color = color; }
diff --git a/Source/core/rendering/svg/RenderSVGRoot.cpp b/Source/core/rendering/svg/RenderSVGRoot.cpp
index 3a3c882..b3100fc 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.cpp
+++ b/Source/core/rendering/svg/RenderSVGRoot.cpp
@@ -290,15 +290,11 @@
     RenderReplaced::willBeDestroyed();
 }
 
-void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
     if (diff == StyleDifferenceLayout)
         setNeedsBoundariesUpdate();
-    RenderReplaced::styleWillChange(diff, newStyle);
-}
 
-void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
     RenderReplaced::styleDidChange(diff, oldStyle);
     SVGResourcesCache::clientStyleChanged(this, diff, style());
 }
diff --git a/Source/core/rendering/svg/RenderSVGRoot.h b/Source/core/rendering/svg/RenderSVGRoot.h
index e1e0664..c28ed7e 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.h
+++ b/Source/core/rendering/svg/RenderSVGRoot.h
@@ -76,7 +76,6 @@
     virtual void paintReplaced(PaintInfo&, const LayoutPoint&);
 
     virtual void willBeDestroyed();
-    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle);
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
     virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
     virtual void removeChild(RenderObject*) OVERRIDE;
diff --git a/Source/core/rendering/svg/RenderSVGShape.cpp b/Source/core/rendering/svg/RenderSVGShape.cpp
index dd301c9..d2a8112 100644
--- a/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -405,6 +405,8 @@
 void RenderSVGShape::updateRepaintBoundingBox()
 {
     m_repaintBoundingBox = strokeBoundingBox();
+    if (strokeWidth() < 1.0f)
+        m_repaintBoundingBox.inflate(1);
     SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGText.cpp b/Source/core/rendering/svg/RenderSVGText.cpp
index d30eb30..e9f50f7 100644
--- a/Source/core/rendering/svg/RenderSVGText.cpp
+++ b/Source/core/rendering/svg/RenderSVGText.cpp
@@ -35,6 +35,7 @@
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/PointerEventsHitRules.h"
+#include "core/rendering/style/ShadowList.h"
 #include "core/rendering/svg/RenderSVGInlineText.h"
 #include "core/rendering/svg/RenderSVGResource.h"
 #include "core/rendering/svg/RenderSVGRoot.h"
@@ -518,7 +519,7 @@
     FloatRect repaintRect = strokeBoundingBox();
     SVGRenderSupport::intersectRepaintRectWithResources(this, repaintRect);
 
-    if (const ShadowData* textShadow = style()->textShadow())
+    if (const ShadowList* textShadow = style()->textShadow())
         textShadow->adjustRectForShadow(repaintRect);
 
     return repaintRect;
diff --git a/Source/core/rendering/svg/SVGInlineTextBox.cpp b/Source/core/rendering/svg/SVGInlineTextBox.cpp
index e3b7c1b..8efa435 100644
--- a/Source/core/rendering/svg/SVGInlineTextBox.cpp
+++ b/Source/core/rendering/svg/SVGInlineTextBox.cpp
@@ -24,18 +24,19 @@
 
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
-#include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/InlineFlowBox.h"
 #include "core/rendering/PointerEventsHitRules.h"
+#include "core/rendering/style/ShadowList.h"
 #include "core/rendering/svg/RenderSVGInlineText.h"
 #include "core/rendering/svg/RenderSVGResource.h"
 #include "core/rendering/svg/RenderSVGResourceSolidColor.h"
 #include "core/rendering/svg/SVGResourcesCache.h"
 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
 #include "platform/FloatConversion.h"
+#include "platform/graphics/DrawLooper.h"
 
 using namespace std;
 
@@ -622,10 +623,10 @@
     ASSERT(scalingFactor);
 
     const Font& scaledFont = textRenderer->scaledFont();
-    const ShadowData* shadow = style->textShadow();
+    const ShadowList* shadowList = style->textShadow();
 
     // Text shadows are disabled when printing. http://crbug.com/258321
-    bool hasShadow = shadow && !context->printing();
+    bool hasShadow = shadowList && !context->printing();
 
     FloatPoint textOrigin(fragment.x, fragment.y);
     FloatSize textSize(fragment.width, fragment.height);
@@ -639,11 +640,12 @@
 
     if (hasShadow) {
         DrawLooper drawLooper;
-        do {
-            FloatSize offset(shadow->x(), shadow->y());
-            drawLooper.addShadow(offset, shadow->blur(), shadow->color(),
+        for (size_t i = shadowList->shadows().size(); i--; ) {
+            const ShadowData& shadow = shadowList->shadows()[i];
+            FloatSize offset(shadow.x(), shadow.y());
+            drawLooper.addShadow(offset, shadow.blur(), shadow.color(),
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowRespectsAlpha);
-        } while ((shadow = shadow->next()));
+        }
         drawLooper.addUnmodifiedContent();
         context->setDrawLooper(drawLooper);
     }
diff --git a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
index ab5fe5b..a68aa6a 100644
--- a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
+++ b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
@@ -31,7 +31,6 @@
 #include "core/rendering/svg/SVGRenderTreeAsText.h"
 
 #include "SVGNames.h"
-#include "core/platform/graphics/GraphicsTypes.h"
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderTreeAsText.h"
 #include "core/rendering/svg/RenderSVGGradientStop.h"
@@ -65,6 +64,7 @@
 #include "core/svg/SVGRadialGradientElement.h"
 #include "core/svg/SVGRectElement.h"
 #include "core/svg/SVGStopElement.h"
+#include "platform/graphics/GraphicsTypes.h"
 
 #include <math.h>
 #include <memory>
diff --git a/Source/core/rendering/svg/SVGResources.cpp b/Source/core/rendering/svg/SVGResources.cpp
index 248d44b..bf3579a 100644
--- a/Source/core/rendering/svg/SVGResources.cpp
+++ b/Source/core/rendering/svg/SVGResources.cpp
@@ -296,6 +296,16 @@
         if (RenderSVGResourceMarker* marker = m_markerData->markerEnd)
             marker->layoutIfNeeded();
     }
+
+    if (m_fillStrokeData) {
+        if (RenderSVGResourceContainer* fill = m_fillStrokeData->fill)
+            fill->layoutIfNeeded();
+        if (RenderSVGResourceContainer* stroke = m_fillStrokeData->stroke)
+            stroke->layoutIfNeeded();
+    }
+
+    if (m_linkedResource)
+        m_linkedResource->layoutIfNeeded();
 }
 
 void SVGResources::removeClientFromCache(RenderObject* object, bool markForInvalidation) const
diff --git a/Source/core/svg/ColorDistance.cpp b/Source/core/svg/ColorDistance.cpp
index df61eee..ba329f7 100644
--- a/Source/core/svg/ColorDistance.cpp
+++ b/Source/core/svg/ColorDistance.cpp
@@ -20,7 +20,7 @@
 #include "config.h"
 #include "core/svg/ColorDistance.h"
 
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/MathExtras.h"
 
 namespace WebCore {
diff --git a/Source/core/svg/SVGAElement.cpp b/Source/core/svg/SVGAElement.cpp
index fe3425a..facae10 100644
--- a/Source/core/svg/SVGAElement.cpp
+++ b/Source/core/svg/SVGAElement.cpp
@@ -183,7 +183,7 @@
                 return;
             FrameLoadRequest frameRequest(document().securityOrigin(), ResourceRequest(document().completeURL(url)), target);
             frameRequest.setTriggeringEvent(event);
-            frame->loader()->load(frameRequest);
+            frame->loader().load(frameRequest);
             return;
         }
     }
diff --git a/Source/core/svg/SVGAnimateElement.cpp b/Source/core/svg/SVGAnimateElement.cpp
index d90e22e..de4239b 100644
--- a/Source/core/svg/SVGAnimateElement.cpp
+++ b/Source/core/svg/SVGAnimateElement.cpp
@@ -32,6 +32,7 @@
 #include "core/svg/SVGAnimatedType.h"
 #include "core/svg/SVGAnimatedTypeAnimator.h"
 #include "core/svg/SVGAnimatorFactory.h"
+#include "core/svg/SVGDocumentExtensions.h"
 
 namespace WebCore {
 
@@ -50,6 +51,8 @@
 
 SVGAnimateElement::~SVGAnimateElement()
 {
+    if (targetElement())
+        clearAnimatedType(targetElement());
 }
 
 bool SVGAnimateElement::hasValidAttributeType()
@@ -211,6 +214,10 @@
     if (shouldApply == ApplyXMLAnimation) {
         // SVG DOM animVal animation code-path.
         m_animatedProperties = animator->findAnimatedPropertiesForAttributeName(targetElement, attributeName);
+        SVGElementAnimatedPropertyList::const_iterator end = m_animatedProperties.end();
+        for (SVGElementAnimatedPropertyList::const_iterator it = m_animatedProperties.begin(); it != end; ++it)
+            document().accessSVGExtensions()->addElementReferencingTarget(this, it->element);
+
         ASSERT(!m_animatedProperties.isEmpty());
 
         ASSERT(propertyTypesAreConsistent(m_animatedPropertyType, m_animatedProperties));
diff --git a/Source/core/svg/SVGAnimateMotionElement.cpp b/Source/core/svg/SVGAnimateMotionElement.cpp
index 70a94ce..6f0a5fd 100644
--- a/Source/core/svg/SVGAnimateMotionElement.cpp
+++ b/Source/core/svg/SVGAnimateMotionElement.cpp
@@ -49,6 +49,12 @@
     ScriptWrappable::init(this);
 }
 
+SVGAnimateMotionElement::~SVGAnimateMotionElement()
+{
+    if (targetElement())
+        clearAnimatedType(targetElement());
+}
+
 PassRefPtr<SVGAnimateMotionElement> SVGAnimateMotionElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGAnimateMotionElement(tagName, document));
diff --git a/Source/core/svg/SVGAnimateMotionElement.h b/Source/core/svg/SVGAnimateMotionElement.h
index 79c8415..3993759 100644
--- a/Source/core/svg/SVGAnimateMotionElement.h
+++ b/Source/core/svg/SVGAnimateMotionElement.h
@@ -30,6 +30,8 @@
 
 class SVGAnimateMotionElement FINAL : public SVGAnimationElement {
 public:
+    virtual ~SVGAnimateMotionElement();
+
     static PassRefPtr<SVGAnimateMotionElement> create(const QualifiedName&, Document&);
     void updateAnimationPath();
 
diff --git a/Source/core/svg/SVGAnimatedType.h b/Source/core/svg/SVGAnimatedType.h
index d5d6033..7c6aa01 100644
--- a/Source/core/svg/SVGAnimatedType.h
+++ b/Source/core/svg/SVGAnimatedType.h
@@ -35,10 +35,10 @@
 
 class SVGPathByteStream;
 
-class SVGAnimatedType {
+class SVGAnimatedType FINAL {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    virtual ~SVGAnimatedType();
+    ~SVGAnimatedType();
 
     static PassOwnPtr<SVGAnimatedType> createAngleAndEnumeration(std::pair<SVGAngle, unsigned>*);
     static PassOwnPtr<SVGAnimatedType> createBoolean(bool*);
diff --git a/Source/core/svg/SVGClipPathElement.cpp b/Source/core/svg/SVGClipPathElement.cpp
index de8058f..2971ac1 100644
--- a/Source/core/svg/SVGClipPathElement.cpp
+++ b/Source/core/svg/SVGClipPathElement.cpp
@@ -92,8 +92,9 @@
 
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
 
-    if (RenderObject* object = renderer())
-        object->setNeedsLayout();
+    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+    if (renderer)
+        renderer->invalidateCacheAndMarkForLayout();
 }
 
 void SVGClipPathElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/Source/core/svg/SVGColor.h b/Source/core/svg/SVGColor.h
index 7568688..0341666 100644
--- a/Source/core/svg/SVGColor.h
+++ b/Source/core/svg/SVGColor.h
@@ -23,7 +23,7 @@
 #define SVGColor_h
 
 #include "core/css/CSSValue.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/svg/SVGDocument.cpp b/Source/core/svg/SVGDocument.cpp
index 46acfef..876b66f 100644
--- a/Source/core/svg/SVGDocument.cpp
+++ b/Source/core/svg/SVGDocument.cpp
@@ -51,7 +51,7 @@
 
 void SVGDocument::dispatchZoomEvent(float prevScale, float newScale)
 {
-    RefPtr<SVGZoomEvent> event = static_pointer_cast<SVGZoomEvent>(createEvent("SVGZoomEvents", IGNORE_EXCEPTION));
+    RefPtr<SVGZoomEvent> event = SVGZoomEvent::create();
     event->initEvent(EventTypeNames::zoom, true, false);
     event->setPreviousScale(prevScale);
     event->setNewScale(newScale);
@@ -60,7 +60,7 @@
 
 void SVGDocument::dispatchScrollEvent()
 {
-    RefPtr<Event> event = createEvent("SVGEvents", IGNORE_EXCEPTION);
+    RefPtr<Event> event = Event::create();
     event->initEvent(EventTypeNames::scroll, true, false);
     rootElement()->dispatchEvent(event.release(), IGNORE_EXCEPTION);
 }
diff --git a/Source/core/svg/SVGElement.cpp b/Source/core/svg/SVGElement.cpp
index 325bdb0..791b37d 100644
--- a/Source/core/svg/SVGElement.cpp
+++ b/Source/core/svg/SVGElement.cpp
@@ -76,6 +76,7 @@
 #if !ASSERT_DISABLED
     , m_inRelativeLengthClientsInvalidation(false)
 #endif
+    , m_animatedPropertiesDestructed(false)
 {
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGElement();
@@ -84,6 +85,16 @@
 
 SVGElement::~SVGElement()
 {
+    ASSERT(inDocument() || !hasRelativeLengths());
+}
+
+void
+SVGElement::cleanupAnimatedProperties()
+{
+    if (m_animatedPropertiesDestructed)
+        return;
+    m_animatedPropertiesDestructed = true;
+
     if (!hasSVGRareData())
         ASSERT(!SVGElementRareData::rareDataMap().contains(this));
     else {
@@ -111,8 +122,7 @@
     }
     document().accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
     document().accessSVGExtensions()->removeAllElementReferencesForTarget(this);
-
-    ASSERT(inDocument() || !hasRelativeLengths());
+    SVGAnimatedProperty::detachAnimatedPropertiesForElement(this);
 }
 
 void SVGElement::willRecalcStyle(StyleRecalcChange change)
@@ -499,8 +509,13 @@
         if (*it == this)
             continue;
 
-        if ((*it)->renderer() && (*it)->selfHasRelativeLengths())
-            (*it)->renderer()->setNeedsLayout(MarkContainingBlockChain, layoutScope);
+        RenderObject* renderer = (*it)->renderer();
+        if (renderer && (*it)->selfHasRelativeLengths()) {
+            if (renderer->isSVGResourceContainer())
+                toRenderSVGResourceContainer(renderer)->invalidateCacheAndMarkForLayout(layoutScope);
+            else
+                renderer->setNeedsLayout(MarkContainingBlockChain, layoutScope);
+        }
 
         (*it)->invalidateRelativeLengthClients(layoutScope);
     }
@@ -571,13 +586,13 @@
     return svgRareData()->elementInstances();
 }
 
-bool SVGElement::getBoundingBox(FloatRect& rect, SVGLocatable::StyleUpdateStrategy styleUpdateStrategy)
+bool SVGElement::getBoundingBox(FloatRect& rect)
 {
-    if (isSVGGraphicsElement()) {
-        rect = toSVGGraphicsElement(this)->getBBox(styleUpdateStrategy);
-        return true;
-    }
-    return false;
+    if (!isSVGGraphicsElement())
+        return false;
+
+    rect = toSVGGraphicsElement(this)->getBBox();
+    return true;
 }
 
 void SVGElement::setCursorElement(SVGCursorElement* cursorElement)
diff --git a/Source/core/svg/SVGElement.h b/Source/core/svg/SVGElement.h
index 8b8f7f3..cf7374e 100644
--- a/Source/core/svg/SVGElement.h
+++ b/Source/core/svg/SVGElement.h
@@ -97,7 +97,7 @@
 
     const HashSet<SVGElementInstance*>& instancesForElement() const;
 
-    bool getBoundingBox(FloatRect&, SVGLocatable::StyleUpdateStrategy = SVGLocatable::AllowStyleUpdate);
+    bool getBoundingBox(FloatRect&);
 
     void setCursorElement(SVGCursorElement*);
     void cursorElementRemoved();
@@ -165,6 +165,25 @@
     void reportAttributeParsingError(SVGParsingError, const QualifiedName&, const AtomicString&);
     bool hasFocusEventListeners() const;
 
+    class CleanUpAnimatedPropertiesCaller {
+    public:
+        CleanUpAnimatedPropertiesCaller()
+        :   m_owner(0)
+        {
+        }
+
+        ~CleanUpAnimatedPropertiesCaller()
+        {
+            ASSERT(m_owner);
+            m_owner->cleanupAnimatedProperties();
+        }
+
+        void setOwner(SVGElement* owner) { m_owner = owner; }
+
+    private:
+        SVGElement* m_owner;
+    };
+
 private:
     friend class SVGElementInstance;
 
@@ -184,6 +203,9 @@
     void mapInstanceToElement(SVGElementInstance*);
     void removeInstanceMapping(SVGElementInstance*);
 
+    void cleanupAnimatedProperties();
+    friend class CleanUpAnimatedPropertiesCaller;
+
     HashSet<SVGElement*> m_elementsWithRelativeLengths;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGElement)
@@ -193,6 +215,7 @@
 #if !ASSERT_DISABLED
     bool m_inRelativeLengthClientsInvalidation;
 #endif
+    bool m_animatedPropertiesDestructed;
 };
 
 struct SVGAttributeHashTranslator {
diff --git a/Source/core/svg/SVGElementInstance.cpp b/Source/core/svg/SVGElementInstance.cpp
index 7bf6048..3e835c1 100644
--- a/Source/core/svg/SVGElementInstance.cpp
+++ b/Source/core/svg/SVGElementInstance.cpp
@@ -149,7 +149,7 @@
     m_directUseElement = 0;
     m_correspondingUseElement = 0;
 
-    removeDetachedChildrenInContainer<SVGElementInstance, SVGElementInstance>(this);
+    removeDetachedChildrenInContainer<SVGElementInstance, SVGElementInstance>(*this);
 }
 
 PassRefPtr<SVGElementInstanceList> SVGElementInstance::childNodes()
@@ -165,7 +165,7 @@
 
 void SVGElementInstance::appendChild(PassRefPtr<SVGElementInstance> child)
 {
-    appendChildToContainer<SVGElementInstance, SVGElementInstance>(child.get(), this);
+    appendChildToContainer<SVGElementInstance, SVGElementInstance>(*child, *this);
 }
 
 void SVGElementInstance::invalidateAllInstancesOfElement(SVGElement* element)
diff --git a/Source/core/svg/SVGElementInstance.h b/Source/core/svg/SVGElementInstance.h
index d2a1784..66de33c 100644
--- a/Source/core/svg/SVGElementInstance.h
+++ b/Source/core/svg/SVGElementInstance.h
@@ -29,7 +29,7 @@
 
 namespace Private {
 template<class GenericNode, class GenericNodeContainer>
-void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer* container);
+void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
 };
 
 class Document;
@@ -156,13 +156,13 @@
     void setShadowTreeElement(SVGElement*);
 
     template<class GenericNode, class GenericNodeContainer>
-    friend void appendChildToContainer(GenericNode* child, GenericNodeContainer* container);
+    friend void appendChildToContainer(GenericNode& child, GenericNodeContainer&);
 
     template<class GenericNode, class GenericNodeContainer>
-    friend void removeDetachedChildrenInContainer(GenericNodeContainer*);
+    friend void removeDetachedChildrenInContainer(GenericNodeContainer&);
 
     template<class GenericNode, class GenericNodeContainer>
-    friend void Private::addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer* container);
+    friend void Private::addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
 
     bool hasChildNodes() const { return m_firstChild; }
 
diff --git a/Source/core/svg/SVGElementInstanceList.cpp b/Source/core/svg/SVGElementInstanceList.cpp
index c9f112d..0e3d895 100644
--- a/Source/core/svg/SVGElementInstanceList.cpp
+++ b/Source/core/svg/SVGElementInstanceList.cpp
@@ -30,10 +30,6 @@
     ScriptWrappable::init(this);
 }
 
-SVGElementInstanceList::~SVGElementInstanceList()
-{
-}
-
 unsigned SVGElementInstanceList::length() const
 {
     // NOTE: We could use the same caching facilities, like the ones "ChildNodeList" uses.
diff --git a/Source/core/svg/SVGElementInstanceList.h b/Source/core/svg/SVGElementInstanceList.h
index 5cc7bf3..2ac1592 100644
--- a/Source/core/svg/SVGElementInstanceList.h
+++ b/Source/core/svg/SVGElementInstanceList.h
@@ -28,10 +28,9 @@
 
 class SVGElementInstance;
 
-class SVGElementInstanceList : public RefCounted<SVGElementInstanceList>, public ScriptWrappable {
+class SVGElementInstanceList FINAL : public RefCounted<SVGElementInstanceList>, public ScriptWrappable {
 public:
     static PassRefPtr<SVGElementInstanceList> create(PassRefPtr<SVGElementInstance> root) { return adoptRef(new SVGElementInstanceList(root)); }
-    virtual ~SVGElementInstanceList();
 
     unsigned length() const;
     SVGElementInstance* item(unsigned index);
diff --git a/Source/core/svg/SVGExternalResourcesRequired.h b/Source/core/svg/SVGExternalResourcesRequired.h
index c8781c3..04b94fd 100644
--- a/Source/core/svg/SVGExternalResourcesRequired.h
+++ b/Source/core/svg/SVGExternalResourcesRequired.h
@@ -45,7 +45,7 @@
 
 protected:
     // These types look a bit awkward, but have to match the generic types of the SVGAnimatedProperty macros.
-    virtual void setExternalResourcesRequiredBaseValue(const bool&, const bool validValue = true) = 0;
+    virtual void setExternalResourcesRequiredBaseValue(const bool&) = 0;
     virtual bool& externalResourcesRequiredBaseValue() const = 0;
 
     virtual void setHaveFiredLoadEvent(bool) { }
diff --git a/Source/core/svg/SVGFilterElement.cpp b/Source/core/svg/SVGFilterElement.cpp
index 391a1d8..8aac4d7 100644
--- a/Source/core/svg/SVGFilterElement.cpp
+++ b/Source/core/svg/SVGFilterElement.cpp
@@ -96,8 +96,9 @@
     setFilterResXBaseValue(filterResX);
     setFilterResYBaseValue(filterResY);
 
-    if (RenderObject* object = renderer())
-        object->setNeedsLayout();
+    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+    if (renderer)
+        renderer->invalidateCacheAndMarkForLayout();
 }
 
 bool SVGFilterElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -168,8 +169,9 @@
         || attrName == SVGNames::heightAttr)
         updateRelativeLengthsInformation();
 
-    if (RenderObject* object = renderer())
-        object->setNeedsLayout();
+    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+    if (renderer)
+        renderer->invalidateCacheAndMarkForLayout();
 }
 
 void SVGFilterElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/Source/core/svg/SVGFitToViewBox.h b/Source/core/svg/SVGFitToViewBox.h
index 7b5544c..ba8ca3c 100644
--- a/Source/core/svg/SVGFitToViewBox.h
+++ b/Source/core/svg/SVGFitToViewBox.h
@@ -24,7 +24,7 @@
 #include "SVGNames.h"
 #include "core/dom/QualifiedName.h"
 #include "core/svg/SVGPreserveAspectRatio.h"
-#include "platform/geometry/FloatRect.h"
+#include "core/svg/SVGRect.h"
 #include "wtf/HashSet.h"
 
 namespace WebCore {
@@ -46,7 +46,10 @@
         if (name == SVGNames::viewBoxAttr) {
             FloatRect viewBox;
             bool valueIsValid = !value.isNull() && parseViewBox(&target->document(), value, viewBox);
-            target->setViewBoxBaseValue(viewBox, valueIsValid);
+            if (valueIsValid)
+                target->setViewBoxBaseValue(viewBox);
+            else
+                target->setViewBoxBaseValue(SVGRect(SVGRect::InvalidSVGRectTag()));
             return true;
         }
 
diff --git a/Source/core/svg/SVGFontFaceElement.cpp b/Source/core/svg/SVGFontFaceElement.cpp
index 55945a5..46a3b3a 100644
--- a/Source/core/svg/SVGFontFaceElement.cpp
+++ b/Source/core/svg/SVGFontFaceElement.cpp
@@ -53,7 +53,7 @@
 {
     ASSERT(hasTagName(font_faceTag));
     ScriptWrappable::init(this);
-    RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create(CSSStrictMode);
+    RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create(HTMLStandardMode);
     m_fontFaceRule->setProperties(styleDeclaration.release());
 }
 
diff --git a/Source/core/svg/SVGGradientElement.cpp b/Source/core/svg/SVGGradientElement.cpp
index 2b8f617..063bc58 100644
--- a/Source/core/svg/SVGGradientElement.cpp
+++ b/Source/core/svg/SVGGradientElement.cpp
@@ -121,8 +121,9 @@
 
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
 
-    if (RenderObject* object = renderer())
-        object->setNeedsLayout();
+    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+    if (renderer)
+        renderer->invalidateCacheAndMarkForLayout();
 }
 
 void SVGGradientElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/Source/core/svg/SVGGraphicsElement.cpp b/Source/core/svg/SVGGraphicsElement.cpp
index 9da02b3..2d9afe5 100644
--- a/Source/core/svg/SVGGraphicsElement.cpp
+++ b/Source/core/svg/SVGGraphicsElement.cpp
@@ -74,6 +74,14 @@
 
         // Flatten any 3D transform.
         matrix = transform.toAffineTransform();
+
+        // CSS bakes the zoom factor into lengths, including translation components.
+        // In order to align CSS & SVG transforms, we need to invert this operation.
+        float zoom = style->effectiveZoom();
+        if (zoom != 1) {
+            matrix.setE(matrix.e() / zoom);
+            matrix.setF(matrix.f() / zoom);
+        }
     } else {
         transformCurrentValue().concatenate(matrix);
     }
@@ -129,8 +137,11 @@
 
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
 
-    if (SVGTests::handleAttributeChange(this, attrName))
+    // Reattach so the isValid() check will be run again during renderer creation.
+    if (SVGTests::isKnownAttribute(attrName)) {
+        lazyReattachIfAttached();
         return;
+    }
 
     RenderObject* object = renderer();
     if (!object)
@@ -155,9 +166,26 @@
     return SVGTransformable::farthestViewportElement(this);
 }
 
-SVGRect SVGGraphicsElement::getBBox(StyleUpdateStrategy styleUpdateStrategy)
+SVGRect SVGGraphicsElement::getBBox()
 {
-    return SVGTransformable::getBBox(this, styleUpdateStrategy);
+    document().updateLayoutIgnorePendingStylesheets();
+
+    // FIXME: Eventually we should support getBBox for detached elements.
+    if (!renderer())
+        return SVGRect();
+
+    return renderer()->objectBoundingBox();
+}
+
+SVGRect SVGGraphicsElement::getStrokeBBox()
+{
+    document().updateLayoutIgnorePendingStylesheets();
+
+    // FIXME: Eventually we should support getStrokeBBox for detached elements.
+    if (!renderer())
+        return SVGRect();
+
+    return renderer()->strokeBoundingBox();
 }
 
 RenderObject* SVGGraphicsElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGGraphicsElement.h b/Source/core/svg/SVGGraphicsElement.h
index d02a8db..1e20804 100644
--- a/Source/core/svg/SVGGraphicsElement.h
+++ b/Source/core/svg/SVGGraphicsElement.h
@@ -44,7 +44,8 @@
     virtual AffineTransform animatedLocalTransform() const;
     virtual AffineTransform* supplementalTransform();
 
-    virtual SVGRect getBBox(StyleUpdateStrategy = AllowStyleUpdate);
+    virtual SVGRect getBBox();
+    SVGRect getStrokeBBox();
 
     // "base class" methods for all the elements which render as paths
     virtual void toClipPath(Path&);
diff --git a/Source/core/svg/SVGGraphicsElement.idl b/Source/core/svg/SVGGraphicsElement.idl
index 0af2440..8732215 100644
--- a/Source/core/svg/SVGGraphicsElement.idl
+++ b/Source/core/svg/SVGGraphicsElement.idl
@@ -35,6 +35,7 @@
     readonly attribute SVGElement farthestViewportElement;
 
     SVGRect   getBBox();
+    SVGRect   getStrokeBBox();
     SVGMatrix getCTM();
     SVGMatrix getScreenCTM();
     [RaisesException] SVGMatrix getTransformToElement([Default=Undefined] optional SVGElement element);
diff --git a/Source/core/svg/SVGLengthContext.cpp b/Source/core/svg/SVGLengthContext.cpp
index 445bf84..0b75f92 100644
--- a/Source/core/svg/SVGLengthContext.cpp
+++ b/Source/core/svg/SVGLengthContext.cpp
@@ -27,12 +27,12 @@
 #include "bindings/v8/ExceptionState.h"
 #include "core/css/CSSHelper.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/platform/graphics/FontMetrics.h"
 #include "core/rendering/RenderPart.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/svg/RenderSVGRoot.h"
 #include "core/rendering/svg/RenderSVGViewportContainer.h"
 #include "core/svg/SVGSVGElement.h"
+#include "platform/fonts/FontMetrics.h"
 
 namespace WebCore {
 
diff --git a/Source/core/svg/SVGLinearGradientElement.cpp b/Source/core/svg/SVGLinearGradientElement.cpp
index cd1d6ea..0c6ae17 100644
--- a/Source/core/svg/SVGLinearGradientElement.cpp
+++ b/Source/core/svg/SVGLinearGradientElement.cpp
@@ -109,8 +109,9 @@
 
     updateRelativeLengthsInformation();
 
-    if (RenderObject* object = renderer())
-        object->setNeedsLayout();
+    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+    if (renderer)
+        renderer->invalidateCacheAndMarkForLayout();
 }
 
 RenderObject* SVGLinearGradientElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGLocatable.cpp b/Source/core/svg/SVGLocatable.cpp
index 5262edd..b8faf5e 100644
--- a/Source/core/svg/SVGLocatable.cpp
+++ b/Source/core/svg/SVGLocatable.cpp
@@ -61,19 +61,6 @@
     return farthest;
 }
 
-SVGRect SVGLocatable::getBBox(SVGElement* element, StyleUpdateStrategy styleUpdateStrategy)
-{
-    ASSERT(element);
-    if (styleUpdateStrategy == AllowStyleUpdate)
-        element->document().updateLayoutIgnorePendingStylesheets();
-
-    // FIXME: Eventually we should support getBBox for detached elements.
-    if (!element->renderer())
-        return SVGRect();
-
-    return element->renderer()->objectBoundingBox();
-}
-
 AffineTransform SVGLocatable::computeCTM(SVGElement* element, CTMScope mode, StyleUpdateStrategy styleUpdateStrategy)
 {
     ASSERT(element);
diff --git a/Source/core/svg/SVGLocatable.h b/Source/core/svg/SVGLocatable.h
index 10e1ff7..df44df4 100644
--- a/Source/core/svg/SVGLocatable.h
+++ b/Source/core/svg/SVGLocatable.h
@@ -40,7 +40,6 @@
 
     enum StyleUpdateStrategy { AllowStyleUpdate, DisallowStyleUpdate };
 
-    virtual SVGRect getBBox(StyleUpdateStrategy) = 0;
     virtual AffineTransform getCTM(StyleUpdateStrategy) = 0;
     virtual AffineTransform getScreenCTM(StyleUpdateStrategy) = 0;
     AffineTransform getTransformToElement(SVGElement*, ExceptionState&, StyleUpdateStrategy = AllowStyleUpdate);
@@ -56,7 +55,6 @@
 protected:
     virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const { return AffineTransform(); }
 
-    static SVGRect getBBox(SVGElement*, StyleUpdateStrategy);
     static AffineTransform computeCTM(SVGElement*, CTMScope, StyleUpdateStrategy);
 };
 
diff --git a/Source/core/svg/SVGMarkerElement.cpp b/Source/core/svg/SVGMarkerElement.cpp
index 9c62bac..c56b2c2 100644
--- a/Source/core/svg/SVGMarkerElement.cpp
+++ b/Source/core/svg/SVGMarkerElement.cpp
@@ -171,8 +171,9 @@
         || attrName == SVGNames::markerHeightAttr)
         updateRelativeLengthsInformation();
 
-    if (RenderObject* object = renderer())
-        object->setNeedsLayout();
+    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+    if (renderer)
+        renderer->invalidateCacheAndMarkForLayout();
 }
 
 void SVGMarkerElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/Source/core/svg/SVGMaskElement.cpp b/Source/core/svg/SVGMaskElement.cpp
index ecae018..f4d95bf 100644
--- a/Source/core/svg/SVGMaskElement.cpp
+++ b/Source/core/svg/SVGMaskElement.cpp
@@ -137,8 +137,9 @@
         || attrName == SVGNames::heightAttr)
         updateRelativeLengthsInformation();
 
-    if (RenderObject* object = renderer())
-        object->setNeedsLayout();
+    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+    if (renderer)
+        renderer->invalidateCacheAndMarkForLayout();
 }
 
 void SVGMaskElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/Source/core/svg/SVGPathElement.cpp b/Source/core/svg/SVGPathElement.cpp
index 33b20a2..247f948 100644
--- a/Source/core/svg/SVGPathElement.cpp
+++ b/Source/core/svg/SVGPathElement.cpp
@@ -385,17 +385,18 @@
     RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
 }
 
-FloatRect SVGPathElement::getBBox(StyleUpdateStrategy styleUpdateStrategy)
+SVGRect SVGPathElement::getBBox()
 {
-    if (styleUpdateStrategy == AllowStyleUpdate)
-        this->document().updateLayoutIgnorePendingStylesheets();
+    // By default, getBBox() returns objectBoundingBox but that will include
+    // markers so we override it to return just the path's bounding rect.
 
-    RenderSVGPath* renderer = toRenderSVGPath(this->renderer());
+    document().updateLayoutIgnorePendingStylesheets();
 
     // FIXME: Eventually we should support getBBox for detached elements.
-    if (!renderer)
-        return FloatRect();
+    if (!renderer())
+        return SVGRect();
 
+    RenderSVGPath* renderer = toRenderSVGPath(this->renderer());
     return renderer->path().boundingRect();
 }
 
diff --git a/Source/core/svg/SVGPathElement.h b/Source/core/svg/SVGPathElement.h
index 766dd1d..00d7ec9 100644
--- a/Source/core/svg/SVGPathElement.h
+++ b/Source/core/svg/SVGPathElement.h
@@ -91,7 +91,7 @@
 
     void pathSegListChanged(SVGPathSegRole, ListModification = ListModificationUnknown);
 
-    virtual FloatRect getBBox(StyleUpdateStrategy = AllowStyleUpdate);
+    virtual SVGRect getBBox() OVERRIDE FINAL;
 
     static const SVGPropertyInfo* dPropertyInfo();
 
diff --git a/Source/core/svg/SVGPatternElement.cpp b/Source/core/svg/SVGPatternElement.cpp
index 7a3851d..387f8d6 100644
--- a/Source/core/svg/SVGPatternElement.cpp
+++ b/Source/core/svg/SVGPatternElement.cpp
@@ -155,8 +155,9 @@
         || attrName == SVGNames::heightAttr)
         updateRelativeLengthsInformation();
 
-    if (RenderObject* object = renderer())
-        object->setNeedsLayout();
+    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+    if (renderer)
+        renderer->invalidateCacheAndMarkForLayout();
 }
 
 void SVGPatternElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -193,7 +194,7 @@
         if (!attributes.hasHeight() && current->hasAttribute(SVGNames::heightAttr))
             attributes.setHeight(current->heightCurrentValue());
 
-        if (!attributes.hasViewBox() && current->hasAttribute(SVGNames::viewBoxAttr) && current->viewBoxIsValid())
+        if (!attributes.hasViewBox() && current->hasAttribute(SVGNames::viewBoxAttr) && current->viewBoxCurrentValue().isValid())
             attributes.setViewBox(current->viewBoxCurrentValue());
 
         if (!attributes.hasPreserveAspectRatio() && current->hasAttribute(SVGNames::preserveAspectRatioAttr))
diff --git a/Source/core/svg/SVGRadialGradientElement.cpp b/Source/core/svg/SVGRadialGradientElement.cpp
index cb286b1..d3a227a 100644
--- a/Source/core/svg/SVGRadialGradientElement.cpp
+++ b/Source/core/svg/SVGRadialGradientElement.cpp
@@ -120,8 +120,9 @@
 
     updateRelativeLengthsInformation();
 
-    if (RenderObject* object = renderer())
-        object->setNeedsLayout();
+    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+    if (renderer)
+        renderer->invalidateCacheAndMarkForLayout();
 }
 
 RenderObject* SVGRadialGradientElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGRect.h b/Source/core/svg/SVGRect.h
index 0517baf..775c196 100644
--- a/Source/core/svg/SVGRect.h
+++ b/Source/core/svg/SVGRect.h
@@ -26,11 +26,36 @@
 
 namespace WebCore {
 
-typedef FloatRect SVGRect;
+class SVGRect : public FloatRect {
+public:
+    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) { }
+
+    bool isValid() const { return m_isValid; }
+
+private:
+    bool m_isValid;
+};
 
 template<>
 struct SVGPropertyTraits<SVGRect> {
-    static SVGRect initialValue() { return SVGRect(); }
+    static SVGRect initialValue() { return SVGRect(SVGRect::InvalidSVGRectTag()); }
     static String toString(const SVGRect& type)
     {
         StringBuilder builder;
diff --git a/Source/core/svg/SVGSVGElement.cpp b/Source/core/svg/SVGSVGElement.cpp
index 7c6bef2..4fefa5b 100644
--- a/Source/core/svg/SVGSVGElement.cpp
+++ b/Source/core/svg/SVGSVGElement.cpp
@@ -183,13 +183,12 @@
     if (!frame)
         return 1;
 
-    FrameTree* frameTree = frame->tree();
-    ASSERT(frameTree);
+    const FrameTree& frameTree = frame->tree();
 
     // The behaviour of currentScale() is undefined, when we're dealing with non-standalone SVG documents.
     // If the svg is embedded, the scaling is handled by the host renderer, so when asking from inside
     // the SVG document, a scale value of 1 seems reasonable, as it doesn't know anything about the parent scale.
-    return frameTree->parent() ? 1 : frame->pageZoomFactor();
+    return frameTree.parent() ? 1 : frame->pageZoomFactor();
 }
 
 void SVGSVGElement::setCurrentScale(float scale)
@@ -201,13 +200,12 @@
     if (!frame)
         return;
 
-    FrameTree* frameTree = frame->tree();
-    ASSERT(frameTree);
+    const FrameTree& frameTree = frame->tree();
 
     // The behaviour of setCurrentScale() is undefined, when we're dealing with non-standalone SVG documents.
     // We choose the ignore this call, it's pretty useless to support calling setCurrentScale() from within
     // an embedded SVG document, for the same reasons as in currentScale() - needs resolution by SVG WG.
-    if (frameTree->parent())
+    if (frameTree.parent())
         return;
 
     frame->setPageZoomFactor(scale);
diff --git a/Source/core/svg/SVGSVGElement.h b/Source/core/svg/SVGSVGElement.h
index 54b39de..48bc4bf 100644
--- a/Source/core/svg/SVGSVGElement.h
+++ b/Source/core/svg/SVGSVGElement.h
@@ -130,7 +130,7 @@
     SVGZoomAndPanType zoomAndPan() const { return m_zoomAndPan; }
     void setZoomAndPan(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
 
-    bool hasEmptyViewBox() const { return viewBoxIsValid() && viewBoxCurrentValue().isEmpty(); }
+    bool hasEmptyViewBox() const { return viewBoxCurrentValue().isValid() && viewBoxCurrentValue().isEmpty(); }
 
 private:
     SVGSVGElement(const QualifiedName&, Document&);
diff --git a/Source/core/svg/SVGTagNames.in b/Source/core/svg/SVGTagNames.in
index 094ccaf..caf925d 100644
--- a/Source/core/svg/SVGTagNames.in
+++ b/Source/core/svg/SVGTagNames.in
@@ -16,9 +16,7 @@
 set
 circle
 clipPath
-#if 0
-color_profile
-#endif
+# color-profile
 cursor
 defs
 desc
@@ -51,11 +49,11 @@
 filter
 #if ENABLE_SVG_FONTS
 font
-font_face
-font_face_format
-font_face_name
-font_face_src
-font_face_uri
+font-face
+font-face-format
+font-face-name
+font-face-src
+font-face-uri
 #endif
 foreignObject
 g
@@ -71,7 +69,7 @@
 mask
 metadata
 #if ENABLE_SVG_FONTS
-missing_glyph
+missing-glyph
 #endif
 mpath interfaceName=SVGMPathElement
 path
diff --git a/Source/core/svg/SVGTests.cpp b/Source/core/svg/SVGTests.cpp
index e7d49ad..9fc1927 100644
--- a/Source/core/svg/SVGTests.cpp
+++ b/Source/core/svg/SVGTests.cpp
@@ -146,23 +146,6 @@
         || attrName == SVGNames::systemLanguageAttr;
 }
 
-bool SVGTests::handleAttributeChange(SVGElement* targetElement, const QualifiedName& attrName)
-{
-    ASSERT(targetElement);
-    if (!isKnownAttribute(attrName))
-        return false;
-    if (!targetElement->inDocument())
-        return true;
-
-    bool valid = targetElement->isValid();
-    if (valid && !targetElement->confusingAndOftenMisusedAttached() && targetElement->parentNode()->confusingAndOftenMisusedAttached())
-        targetElement->lazyAttach();
-    else if (!valid && targetElement->confusingAndOftenMisusedAttached())
-        targetElement->detach();
-
-    return true;
-}
-
 void SVGTests::addSupportedAttributes(HashSet<QualifiedName>& supportedAttributes)
 {
     supportedAttributes.add(SVGNames::requiredFeaturesAttr);
diff --git a/Source/core/svg/SVGTests.h b/Source/core/svg/SVGTests.h
index 9350a15..7df0e22 100644
--- a/Source/core/svg/SVGTests.h
+++ b/Source/core/svg/SVGTests.h
@@ -44,7 +44,6 @@
     bool isKnownAttribute(const QualifiedName&);
 
     void addSupportedAttributes(HashSet<QualifiedName>&);
-    bool handleAttributeChange(SVGElement*, const QualifiedName&);
 
     static SVGAttributeToPropertyMap& attributeToPropertyMap();
 
diff --git a/Source/core/svg/SVGURIReference.h b/Source/core/svg/SVGURIReference.h
index e6901e6..f73a23b 100644
--- a/Source/core/svg/SVGURIReference.h
+++ b/Source/core/svg/SVGURIReference.h
@@ -51,7 +51,7 @@
     }
 
 protected:
-    virtual void setHrefBaseValue(const String&, const bool validValue = true) = 0;
+    virtual void setHrefBaseValue(const String&) = 0;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGViewSpec.cpp b/Source/core/svg/SVGViewSpec.cpp
index 64b4885..b63ed50 100644
--- a/Source/core/svg/SVGViewSpec.cpp
+++ b/Source/core/svg/SVGViewSpec.cpp
@@ -130,7 +130,7 @@
 
 String SVGViewSpec::viewBoxString() const
 {
-    return SVGPropertyTraits<FloatRect>::toString(viewBoxBaseValue());
+    return SVGPropertyTraits<SVGRect>::toString(viewBoxBaseValue());
 }
 
 String SVGViewSpec::preserveAspectRatioString() const
@@ -174,7 +174,7 @@
 {
     ASSERT(ownerType);
     ASSERT(ownerType->contextElement());
-    return SVGAnimatedProperty::lookupOrCreateWrapper<SVGElement, SVGAnimatedRect, FloatRect>(ownerType->contextElement(), viewBoxPropertyInfo(), ownerType->m_viewBox);
+    return SVGAnimatedProperty::lookupOrCreateWrapper<SVGElement, SVGAnimatedRect, SVGRect>(ownerType->contextElement(), viewBoxPropertyInfo(), ownerType->m_viewBox);
 }
 
 PassRefPtr<SVGAnimatedProperty> SVGViewSpec::lookupOrCreatePreserveAspectRatioWrapper(SVGViewSpec* ownerType)
@@ -195,7 +195,7 @@
 {
     m_zoomAndPan = SVGZoomAndPanMagnify;
     m_transform.clear();
-    m_viewBox = FloatRect();
+    m_viewBox = SVGRect();
     m_preserveAspectRatio = SVGPreserveAspectRatio();
     m_viewTargetString = emptyString();
 }
@@ -223,7 +223,7 @@
                 if (ptr >= end || *ptr != '(')
                     return false;
                 ptr++;
-                FloatRect viewBox;
+                SVGRect viewBox;
                 if (!SVGFitToViewBox::parseViewBox(&m_contextElement->document(), ptr, end, viewBox, false))
                     return false;
                 setViewBoxBaseValue(viewBox);
diff --git a/Source/core/svg/SVGViewSpec.h b/Source/core/svg/SVGViewSpec.h
index fd90616..f738a32 100644
--- a/Source/core/svg/SVGViewSpec.h
+++ b/Source/core/svg/SVGViewSpec.h
@@ -33,10 +33,8 @@
 class SVGElement;
 class SVGTransformListPropertyTearOff;
 
-class SVGViewSpec : public RefCounted<SVGViewSpec>, public ScriptWrappable, public SVGZoomAndPan, public SVGFitToViewBox {
+class SVGViewSpec FINAL : public RefCounted<SVGViewSpec>, public ScriptWrappable, public SVGZoomAndPan, public SVGFitToViewBox {
 public:
-    virtual ~SVGViewSpec() { }
-
     using RefCounted<SVGViewSpec>::ref;
     using RefCounted<SVGViewSpec>::deref;
 
@@ -73,9 +71,9 @@
 
     // Custom animated 'viewBox' property.
     PassRefPtr<SVGAnimatedRect> viewBox();
-    FloatRect& viewBoxCurrentValue() { return m_viewBox; }
-    FloatRect viewBoxBaseValue() const { return m_viewBox; }
-    void setViewBoxBaseValue(const FloatRect& viewBox) { m_viewBox = 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();
@@ -105,7 +103,7 @@
     SVGZoomAndPanType m_zoomAndPan;
 
     SVGTransformList m_transform;
-    FloatRect m_viewBox;
+    SVGRect m_viewBox;
     SVGPreserveAspectRatio m_preserveAspectRatio;
     String m_viewTargetString;
 };
diff --git a/Source/core/svg/animation/SVGSMILElement.cpp b/Source/core/svg/animation/SVGSMILElement.cpp
index 6e09485..68a4933 100644
--- a/Source/core/svg/animation/SVGSMILElement.cpp
+++ b/Source/core/svg/animation/SVGSMILElement.cpp
@@ -551,6 +551,8 @@
     else if (attrName.matches(XLinkNames::hrefAttr)) {
         SVGElementInstance::InvalidationGuard invalidationGuard(this);
         buildPendingResource();
+        if (m_targetElement)
+            clearAnimatedType(m_targetElement);
     } else if (inDocument()) {
         if (attrName == SVGNames::beginAttr)
             beginListChanged(elapsed());
diff --git a/Source/core/svg/graphics/SVGImage.cpp b/Source/core/svg/graphics/SVGImage.cpp
index d4b2002..6854294 100644
--- a/Source/core/svg/graphics/SVGImage.cpp
+++ b/Source/core/svg/graphics/SVGImage.cpp
@@ -62,7 +62,7 @@
     if (m_page) {
         // Store m_page in a local variable, clearing m_page, so that SVGImageChromeClient knows we're destructed.
         OwnPtr<Page> currentPage = m_page.release();
-        currentPage->mainFrame()->loader()->frameDetached(); // Break both the loader and view references to the frame
+        currentPage->mainFrame()->loader().frameDetached(); // Break both the loader and view references to the frame
     }
 
     // Verify that page teardown destroyed the Chrome
@@ -391,17 +391,17 @@
         RefPtr<Frame> frame = Frame::create(m_page.get(), 0, dummyFrameLoaderClient);
         frame->setView(FrameView::create(frame.get()));
         frame->init();
-        FrameLoader* loader = frame->loader();
-        loader->forceSandboxFlags(SandboxAll);
+        FrameLoader& loader = frame->loader();
+        loader.forceSandboxFlags(SandboxAll);
 
         frame->view()->setScrollbarsSuppressed(true);
         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");
+        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.activeDocumentLoader()->endWriting(writer);
         // Set the intrinsic size before a container size is available.
         m_intrinsicSize = containerSize();
     }
diff --git a/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h b/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
index cd6014b..e8a58cc 100644
--- a/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
@@ -33,7 +33,7 @@
     {
         // 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()) {
-            es.throwTypeError();
+            es.throwUninformativeAndGenericTypeError();
             return;
         }
         SVGAnimatedStaticPropertyTearOff<unsigned>::setBaseVal(property, es);
diff --git a/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h b/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h
index fdbd217..bebcc5a 100644
--- a/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h
@@ -39,6 +39,14 @@
     typedef SVGListPropertyTearOff<PropertyType> ListPropertyTearOff;
     typedef PropertyType ContentType;
 
+    virtual ~SVGAnimatedListPropertyTearOff()
+    {
+        if (m_baseVal)
+            static_cast<ListPropertyTearOff*>(m_baseVal.get())->clearAnimatedProperty();
+        if (m_animVal)
+            static_cast<ListPropertyTearOff*>(m_animVal.get())->clearAnimatedProperty();
+    }
+
     virtual ListProperty* baseVal()
     {
         if (!m_baseVal)
@@ -109,6 +117,7 @@
     {
         ASSERT(m_isAnimating);
         ASSERT(m_animVal);
+        ASSERT(contextElement());
         ASSERT(m_values.size() == m_wrappers.size());
 
         ListProperty* animVal = static_cast<ListProperty*>(m_animVal.get());
diff --git a/Source/core/svg/properties/SVGAnimatedProperty.cpp b/Source/core/svg/properties/SVGAnimatedProperty.cpp
index cfaf2a4..352f204 100644
--- a/Source/core/svg/properties/SVGAnimatedProperty.cpp
+++ b/Source/core/svg/properties/SVGAnimatedProperty.cpp
@@ -36,18 +36,27 @@
 
 SVGAnimatedProperty::~SVGAnimatedProperty()
 {
-    // Remove wrapper from cache.
+    // Assure that animationEnded() was called, if animationStarted() was called before.
+    ASSERT(!m_isAnimating);
+}
+
+void SVGAnimatedProperty::detachAnimatedPropertiesForElement(SVGElement* element)
+{
+    // Remove wrappers from cache.
     Cache* cache = animatedPropertyCache();
+
+    Vector<SVGAnimatedPropertyDescription> keysToRemove;
+
     const Cache::const_iterator end = cache->end();
     for (Cache::const_iterator it = cache->begin(); it != end; ++it) {
-        if (it->value == this) {
-            cache->remove(it->key);
-            break;
+        if (it->key.m_element == element) {
+            it->value->resetContextElement();
+            keysToRemove.append(it->key);
         }
     }
 
-    // Assure that animationEnded() was called, if animationStarted() was called before.
-    ASSERT(!m_isAnimating);
+    for (Vector<SVGAnimatedPropertyDescription>::const_iterator it = keysToRemove.begin(); it != keysToRemove.end(); ++it)
+        cache->remove(*it);
 }
 
 void SVGAnimatedProperty::commitChange()
diff --git a/Source/core/svg/properties/SVGAnimatedProperty.h b/Source/core/svg/properties/SVGAnimatedProperty.h
index 37eba88..eb0ba54 100644
--- a/Source/core/svg/properties/SVGAnimatedProperty.h
+++ b/Source/core/svg/properties/SVGAnimatedProperty.h
@@ -31,7 +31,8 @@
 
 class SVGAnimatedProperty : public RefCounted<SVGAnimatedProperty> {
 public:
-    SVGElement* contextElement() const { return m_contextElement.get(); }
+    SVGElement* contextElement() const { return m_contextElement; }
+    void resetContextElement() { m_contextElement = 0; }
     const QualifiedName& attributeName() const { return m_attributeName; }
     AnimatedPropertyType animatedPropertyType() const { return m_animatedPropertyType; }
     bool isAnimating() const { return m_isAnimating; }
@@ -43,7 +44,7 @@
     virtual bool isAnimatedListTearOff() const { return false; }
 
     // Caching facilities.
-    typedef HashMap<SVGAnimatedPropertyDescription, SVGAnimatedProperty*, SVGAnimatedPropertyDescriptionHash, SVGAnimatedPropertyDescriptionHashTraits> Cache;
+    typedef HashMap<SVGAnimatedPropertyDescription, RefPtr<SVGAnimatedProperty>, SVGAnimatedPropertyDescriptionHash, SVGAnimatedPropertyDescriptionHashTraits> Cache;
 
     virtual ~SVGAnimatedProperty();
 
@@ -57,7 +58,7 @@
             wrapper = TearOffType::create(element, info->attributeName, info->animatedPropertyType, property);
             if (info->animatedPropertyState == PropertyIsReadOnly)
                 wrapper->setIsReadOnly();
-            animatedPropertyCache()->set(key, wrapper.get());
+            animatedPropertyCache()->set(key, wrapper);
         }
         return static_pointer_cast<TearOffType>(wrapper);
     }
@@ -76,13 +77,15 @@
         return lookupWrapper<OwnerType, TearOffType>(const_cast<OwnerType*>(element), info);
     }
 
+    static void detachAnimatedPropertiesForElement(SVGElement*);
+
 protected:
     SVGAnimatedProperty(SVGElement*, const QualifiedName&, AnimatedPropertyType);
 
 private:
     static Cache* animatedPropertyCache();
 
-    RefPtr<SVGElement> m_contextElement;
+    SVGElement* m_contextElement;
     const QualifiedName& m_attributeName;
     AnimatedPropertyType m_animatedPropertyType;
 
diff --git a/Source/core/svg/properties/SVGAnimatedPropertyMacros.h b/Source/core/svg/properties/SVGAnimatedPropertyMacros.h
index e864b5c..74e377f 100644
--- a/Source/core/svg/properties/SVGAnimatedPropertyMacros.h
+++ b/Source/core/svg/properties/SVGAnimatedPropertyMacros.h
@@ -36,7 +36,6 @@
     SVGSynchronizableAnimatedProperty()
         : value(SVGPropertyTraits<PropertyType>::initialValue())
         , shouldSynchronize(false)
-        , isValid(false)
     {
     }
 
@@ -44,7 +43,6 @@
     SVGSynchronizableAnimatedProperty(const ConstructorParameter1& value1)
         : value(value1)
         , shouldSynchronize(false)
-        , isValid(false)
     {
     }
 
@@ -52,7 +50,6 @@
     SVGSynchronizableAnimatedProperty(const ConstructorParameter1& value1, const ConstructorParameter2& value2)
         : value(value1, value2)
         , shouldSynchronize(false)
-        , isValid(false)
     {
     }
 
@@ -63,7 +60,6 @@
 
     PropertyType value;
     bool shouldSynchronize : 1;
-    bool isValid : 1;
 };
 
 // Property registration helpers
@@ -79,8 +75,9 @@
     return attributeToPropertyMap(); \
 } \
 \
-static void registerAnimatedPropertiesFor##OwnerType() \
+void OwnerType::registerAnimatedPropertiesFor##OwnerType() \
 { \
+    OwnerType::m_cleanupAnimatedPropertiesCaller.setOwner(this); \
     SVGAttributeToPropertyMap& map = OwnerType::attributeToPropertyMap(); \
     if (!map.isEmpty()) \
         return; \
@@ -120,10 +117,9 @@
     return m_##LowerProperty.value; \
 } \
 \
-void OwnerType::set##UpperProperty##BaseValue(const PropertyType& type, const bool validValue) \
+void OwnerType::set##UpperProperty##BaseValue(const PropertyType& type) \
 { \
     m_##LowerProperty.value = type; \
-    m_##LowerProperty.isValid = validValue; \
 } \
 \
 PassRefPtr<TearOffType> OwnerType::LowerProperty() \
@@ -132,11 +128,6 @@
     return static_pointer_cast<TearOffType>(lookupOrCreate##UpperProperty##Wrapper(this)); \
 } \
 \
-bool OwnerType::LowerProperty##IsValid() const \
-{ \
-    return m_##LowerProperty.isValid; \
-} \
-\
 void OwnerType::synchronize##UpperProperty() \
 { \
     if (!m_##LowerProperty.shouldSynchronize) \
@@ -164,6 +155,7 @@
 public: \
     static SVGAttributeToPropertyMap& attributeToPropertyMap(); \
     virtual SVGAttributeToPropertyMap& localAttributeToPropertyMap() const; \
+    void registerAnimatedPropertiesFor##OwnerType(); \
     typedef OwnerType UseOwnerType;
 
 #define DECLARE_ANIMATED_PROPERTY(TearOffType, PropertyType, UpperProperty, LowerProperty) \
@@ -171,9 +163,8 @@
     static const SVGPropertyInfo* LowerProperty##PropertyInfo(); \
     PropertyType& LowerProperty##CurrentValue() const; \
     PropertyType& LowerProperty##BaseValue() const; \
-    void set##UpperProperty##BaseValue(const PropertyType& type, const bool = true); \
+    void set##UpperProperty##BaseValue(const PropertyType& type); \
     PassRefPtr<TearOffType> LowerProperty(); \
-    bool LowerProperty##IsValid() const; \
 \
 private: \
     void synchronize##UpperProperty(); \
@@ -182,7 +173,8 @@
 \
     mutable SVGSynchronizableAnimatedProperty<PropertyType> m_##LowerProperty;
 
-#define END_DECLARE_ANIMATED_PROPERTIES
+#define END_DECLARE_ANIMATED_PROPERTIES \
+    CleanUpAnimatedPropertiesCaller m_cleanupAnimatedPropertiesCaller;
 
 // List specific definition/declaration helpers
 #define DECLARE_ANIMATED_LIST_PROPERTY(TearOffType, PropertyType, UpperProperty, LowerProperty) \
diff --git a/Source/core/svg/properties/SVGListProperty.h b/Source/core/svg/properties/SVGListProperty.h
index c326795..250b0f5 100644
--- a/Source/core/svg/properties/SVGListProperty.h
+++ b/Source/core/svg/properties/SVGListProperty.h
@@ -147,7 +147,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwTypeError();
+            es.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
@@ -241,7 +241,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwTypeError();
+            es.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
@@ -314,7 +314,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwTypeError();
+            es.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
@@ -417,7 +417,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwTypeError();
+            es.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
diff --git a/Source/core/svg/properties/SVGListPropertyTearOff.h b/Source/core/svg/properties/SVGListPropertyTearOff.h
index c6246d7..2320435 100644
--- a/Source/core/svg/properties/SVGListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGListPropertyTearOff.h
@@ -92,7 +92,8 @@
 
     PassListItemTearOff getItem(unsigned index, ExceptionState& es)
     {
-        return Base::getItemValuesAndWrappers(m_animatedProperty.get(), index, es);
+        ASSERT(m_animatedProperty);
+        return Base::getItemValuesAndWrappers(m_animatedProperty, index, es);
     }
 
     PassListItemTearOff insertItemBefore(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
@@ -107,7 +108,8 @@
 
     PassListItemTearOff removeItem(unsigned index, ExceptionState& es)
     {
-        return Base::removeItemValuesAndWrappers(m_animatedProperty.get(), index, es);
+        ASSERT(m_animatedProperty);
+        return Base::removeItemValuesAndWrappers(m_animatedProperty, index, es);
     }
 
     PassListItemTearOff appendItem(PassListItemTearOff passNewItem, ExceptionState& es)
@@ -115,11 +117,24 @@
         return Base::appendItemValuesAndWrappers(passNewItem, es);
     }
 
+    SVGElement* contextElement() const
+    {
+        ASSERT(m_animatedProperty);
+        return m_animatedProperty->contextElement();
+    }
+
+    void clearAnimatedProperty()
+    {
+        ASSERT(m_animatedProperty);
+        m_animatedProperty = 0;
+    }
+
 protected:
     SVGListPropertyTearOff(AnimatedListPropertyTearOff* animatedProperty, SVGPropertyRole role, PropertyType& values, ListWrapperCache& wrappers)
         : SVGListProperty<PropertyType>(role, values, &wrappers)
         , m_animatedProperty(animatedProperty)
     {
+        ASSERT(m_animatedProperty);
     }
 
     virtual bool isReadOnly() const
@@ -135,6 +150,7 @@
     {
         ASSERT(m_values);
         ASSERT(m_wrappers);
+        ASSERT(m_animatedProperty);
 
         // Update existing wrappers, as the index in the values list has changed.
         unsigned size = m_wrappers->size();
@@ -143,7 +159,7 @@
             ListItemTearOff* item = m_wrappers->at(i).get();
             if (!item)
                 continue;
-            item->setAnimatedProperty(m_animatedProperty.get());
+            item->setAnimatedProperty(m_animatedProperty);
             item->setValue(m_values->at(i));
         }
 
@@ -179,6 +195,7 @@
 
         // 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.
+        ASSERT(m_animatedProperty);
         bool livesInOtherList = animatedPropertyOfItem != m_animatedProperty;
         AnimatedListPropertyTearOff* propertyTearOff = static_cast<AnimatedListPropertyTearOff*>(animatedPropertyOfItem);
         int indexToRemove = propertyTearOff->findItem(newItem.get());
@@ -206,7 +223,7 @@
 
     // Back pointer to the animated property that created us
     // For example (text.x.baseVal): m_animatedProperty points to the 'x' SVGAnimatedLengthList object
-    RefPtr<AnimatedListPropertyTearOff> m_animatedProperty;
+    AnimatedListPropertyTearOff* m_animatedProperty;
 };
 
 }
diff --git a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
index cfe7bb3..eee1ada 100644
--- a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
+++ b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -63,7 +63,7 @@
 {
     // Not specified, but FF/Opera do it this way, and it's just sane.
     if (!passNewItem) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return 0;
     }
 
diff --git a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
index 56055ed..b1a874a 100644
--- a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
@@ -41,6 +41,9 @@
         return adoptRef(new SVGPathSegListPropertyTearOff(animatedProperty, role, pathSegRole, values, wrappers));
     }
 
+    SVGPathElement* contextElement() const;
+    SVGAnimatedProperty* animatedProperty() const { return m_animatedProperty.get(); }
+
     int findItem(const ListItemType& item) const
     {
         ASSERT(m_values);
@@ -72,7 +75,7 @@
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwTypeError();
+            es.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
@@ -87,7 +90,7 @@
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwTypeError();
+            es.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
@@ -103,7 +106,7 @@
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            es.throwTypeError();
+            es.throwUninformativeAndGenericTypeError();
             return 0;
         }
 
@@ -119,8 +122,6 @@
     {
     }
 
-    SVGPathElement* contextElement() const;
-
     void clearContextAndRoles();
 
     using Base::m_role;
diff --git a/Source/core/svg/properties/SVGPropertyTearOff.h b/Source/core/svg/properties/SVGPropertyTearOff.h
index a78bdea..c9fe65b 100644
--- a/Source/core/svg/properties/SVGPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGPropertyTearOff.h
@@ -76,7 +76,8 @@
     {
         if (!m_animatedProperty || m_valueIsCopy)
             return 0;
-        return m_contextElement.get();
+        ASSERT(m_contextElement);
+        return m_contextElement;
     }
 
     void addChild(WeakPtr<SVGPropertyTearOffBase> child)
@@ -156,7 +157,7 @@
         m_childTearOffs.clear();
     }
 
-    RefPtr<SVGElement> m_contextElement;
+    SVGElement* m_contextElement;
     SVGAnimatedProperty* m_animatedProperty;
     SVGPropertyRole m_role;
     PropertyType* m_value;
diff --git a/Source/core/svg/properties/SVGStaticListPropertyTearOff.h b/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
index 367560f..1488c59 100644
--- a/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
@@ -43,6 +43,8 @@
         return adoptRef(new SVGStaticListPropertyTearOff<PropertyType>(contextElement, values));
     }
 
+    SVGElement* contextElement() const { return m_contextElement; }
+
     // SVGList API
     void clear(ExceptionState& es)
     {
@@ -94,7 +96,8 @@
     virtual void commitChange()
     {
         ASSERT(m_values);
-        m_values->commitChange(m_contextElement.get());
+        ASSERT(m_contextElement);
+        m_values->commitChange(m_contextElement);
     }
 
     virtual bool processIncomingListItemValue(const ListItemType&, unsigned*)
@@ -110,7 +113,7 @@
     }
 
 private:
-    RefPtr<SVGElement> m_contextElement;
+    SVGElement* m_contextElement;
 };
 
 }
diff --git a/Source/core/testing/Internals.cpp b/Source/core/testing/Internals.cpp
index c2ef314..988a820 100644
--- a/Source/core/testing/Internals.cpp
+++ b/Source/core/testing/Internals.cpp
@@ -66,6 +66,7 @@
 #include "core/dom/shadow/SelectRuleFeatureSet.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
+#include "core/editing/PlainTextRange.h"
 #include "core/editing/SpellCheckRequester.h"
 #include "core/editing/SpellChecker.h"
 #include "core/editing/TextIterator.h"
@@ -106,7 +107,6 @@
 #include "core/platform/graphics/filters/FilterOperation.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
 #include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
-#include "core/platform/mock/PlatformSpeechSynthesizerMock.h"
 #include "core/rendering/CompositedLayerMapping.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
@@ -116,11 +116,10 @@
 #include "core/rendering/RenderView.h"
 #include "core/testing/GCObservation.h"
 #include "core/workers/WorkerThread.h"
-#include "modules/speech/DOMWindowSpeechSynthesis.h"
-#include "modules/speech/SpeechSynthesis.h"
 #include "platform/Language.h"
 #include "platform/TraceEvent.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/geometry/LayoutRect.h"
 #include "public/platform/WebLayer.h"
 #include "weborigin/SchemeRegistry.h"
 #include "wtf/dtoa.h"
@@ -409,9 +408,10 @@
 unsigned Internals::numberOfActiveAnimations() const
 {
     Frame* contextFrame = frame();
+    Document* document = contextFrame->document();
     if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-        return contextFrame->document()->timeline()->numberOfActiveAnimationsForTesting();
-    return contextFrame->animation().numberOfActiveAnimations(contextFrame->document());
+        return document->timeline()->numberOfActiveAnimationsForTesting() + document->transitionTimeline()->numberOfActiveAnimationsForTesting();
+    return contextFrame->animation().numberOfActiveAnimations(document);
 }
 
 void Internals::pauseAnimations(double pauseTime, ExceptionState& es)
@@ -421,10 +421,12 @@
         return;
     }
 
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
         frame()->document()->timeline()->pauseAnimationsForTesting(pauseTime);
-    else
+        frame()->document()->transitionTimeline()->pauseAnimationsForTesting(pauseTime);
+    } else {
         frame()->animation().pauseAnimationsForTesting(pauseTime);
+    }
 }
 
 bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionState& es) const
@@ -454,16 +456,6 @@
     return toShadowRoot(root)->childShadowRootCount();
 }
 
-bool Internals::attached(Node* node, ExceptionState& es)
-{
-    if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
-        return false;
-    }
-
-    return node->confusingAndOftenMisusedAttached();
-}
-
 Node* Internals::nextSiblingByWalker(Node* node, ExceptionState& es)
 {
     if (!node) {
@@ -637,18 +629,6 @@
     }
 }
 
-Element* Internals::includerFor(Node* node, ExceptionState& es)
-{
-    if (!node) {
-        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
-        return 0;
-    }
-
-    NodeRenderingTraversal::ParentDetails parentDetails;
-    NodeRenderingTraversal::parent(node, &parentDetails);
-    return parentDetails.insertionPoint();
-}
-
 String Internals::shadowPseudoId(Element* element, ExceptionState& es)
 {
     if (!element) {
@@ -688,12 +668,12 @@
 
 Vector<String> Internals::formControlStateOfPreviousHistoryItem(ExceptionState& es)
 {
-    HistoryItem* mainItem = frame()->loader()->history()->previousItem();
+    HistoryItem* mainItem = frame()->loader().history()->previousItem();
     if (!mainItem) {
         es.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return Vector<String>();
     }
-    String uniqueName = frame()->tree()->uniqueName();
+    String uniqueName = frame()->tree().uniqueName();
     if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName)) {
         es.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return Vector<String>();
@@ -703,12 +683,12 @@
 
 void Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state, ExceptionState& es)
 {
-    HistoryItem* mainItem = frame()->loader()->history()->previousItem();
+    HistoryItem* mainItem = frame()->loader().history()->previousItem();
     if (!mainItem) {
         es.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
-    String uniqueName = frame()->tree()->uniqueName();
+    String uniqueName = frame()->tree().uniqueName();
     if (mainItem->target() == uniqueName)
         mainItem->setDocumentState(state);
     else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
@@ -717,18 +697,6 @@
         es.throwUninformativeAndGenericDOMException(InvalidAccessError);
 }
 
-void Internals::enableMockSpeechSynthesizer()
-{
-    Document* document = contextDocument();
-    if (!document || !document->domWindow())
-        return;
-    SpeechSynthesis* synthesis = DOMWindowSpeechSynthesis::speechSynthesis(document->domWindow());
-    if (!synthesis)
-        return;
-
-    synthesis->setPlatformSynthesizer(PlatformSpeechSynthesizerMock::create(synthesis));
-}
-
 void Internals::setEnableMockPagePopup(bool enabled, ExceptionState& es)
 {
     Document* document = contextDocument();
@@ -1085,7 +1053,7 @@
     // TextIterator depends on Layout information, make sure layout it up to date.
     scope->document().updateLayoutIgnorePendingStylesheets();
 
-    return TextIterator::rangeFromLocationAndLength(scope, rangeLocation, rangeLength);
+    return PlainTextRange(rangeLocation, rangeLocation + rangeLength).createRange(*scope);
 }
 
 unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionState& es)
@@ -1095,13 +1063,10 @@
         return 0;
     }
 
-    // TextIterator depends on Layout information, make sure layout it up to date.
+    // PlainTextRange depends on Layout information, make sure layout it up to date.
     scope->document().updateLayoutIgnorePendingStylesheets();
 
-    size_t location = 0;
-    size_t unusedLength = 0;
-    TextIterator::getLocationAndLengthFromRange(scope, range, location, unusedLength);
-    return location;
+    return PlainTextRange::create(*scope, *range).start();
 }
 
 unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionState& es)
@@ -1111,13 +1076,10 @@
         return 0;
     }
 
-    // TextIterator depends on Layout information, make sure layout it up to date.
+    // PlainTextRange depends on Layout information, make sure layout it up to date.
     scope->document().updateLayoutIgnorePendingStylesheets();
 
-    size_t unusedLocation = 0;
-    size_t length = 0;
-    TextIterator::getLocationAndLengthFromRange(scope, range, unusedLocation, length);
-    return length;
+    return PlainTextRange::create(*scope, *range).length();
 }
 
 String Internals::rangeAsText(const Range* range, ExceptionState& es)
@@ -1145,7 +1107,7 @@
     Node* targetNode;
     IntPoint adjustedPoint;
 
-    bool foundNode = document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
+    bool foundNode = document->frame()->eventHandler().bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
     if (foundNode)
         return DOMPoint::create(adjustedPoint.x(), adjustedPoint.y());
 
@@ -1166,7 +1128,7 @@
 
     Node* targetNode;
     IntPoint adjustedPoint;
-    document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
+    document->frame()->eventHandler().bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
     return targetNode;
 }
 
@@ -1185,7 +1147,7 @@
     Node* targetNode = 0;
     IntPoint adjustedPoint;
 
-    bool foundNode = document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
+    bool foundNode = document->frame()->eventHandler().bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
     if (foundNode)
         return DOMPoint::create(adjustedPoint.x(), adjustedPoint.y());
 
@@ -1206,7 +1168,7 @@
 
     Node* targetNode = 0;
     IntPoint adjustedPoint;
-    document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
+    document->frame()->eventHandler().bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
     return targetNode;
 }
 
@@ -1224,7 +1186,7 @@
 
     Node* targetNode;
     IntRect zoomableArea;
-    bool foundNode = document->frame()->eventHandler()->bestZoomableAreaForTouchPoint(point, radius, zoomableArea, targetNode);
+    bool foundNode = document->frame()->eventHandler().bestZoomableAreaForTouchPoint(point, radius, zoomableArea, targetNode);
     if (foundNode)
         return ClientRect::create(zoomableArea);
 
@@ -1514,17 +1476,11 @@
 
 unsigned Internals::numberOfLiveNodes() const
 {
-    if (StyleResolver* resolver = contextDocument()->styleResolverIfExists())
-        resolver->clearStyleSharingList();
-
     return InspectorCounters::counterValue(InspectorCounters::NodeCounter);
 }
 
 unsigned Internals::numberOfLiveDocuments() const
 {
-    if (StyleResolver* resolver = contextDocument()->styleResolverIfExists())
-        resolver->clearStyleSharingList();
-
     return InspectorCounters::counterValue(InspectorCounters::DocumentCounter);
 }
 
@@ -1617,7 +1573,7 @@
     if (frame->view()->scrollableAreas())
         count += frame->view()->scrollableAreas()->size();
 
-    for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
+    for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
         if (child->view() && child->view()->scrollableAreas())
             count += child->view()->scrollableAreas()->size();
     }
@@ -1836,6 +1792,29 @@
     return document->frame()->trackedRepaintRectsAsText();
 }
 
+PassRefPtr<ClientRectList> Internals::repaintRects(Element* element, ExceptionState& es) const
+{
+    if (!element) {
+        es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        return 0;
+    }
+
+    if (RenderLayer* layer = getRenderLayerForElement(element, es)) {
+        if (layer->compositingState() == PaintsIntoOwnBacking) {
+            OwnPtr<Vector<FloatRect> > rects = layer->collectTrackedRepaintRects();
+            ASSERT(rects.get());
+            Vector<FloatQuad> quads(rects->size());
+            for (size_t i = 0; i < rects->size(); ++i)
+                quads[i] = FloatRect(rects->at(i));
+            return ClientRectList::create(quads);
+        }
+    }
+
+    // It's an error to call this on an element that's not composited.
+    es.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    return 0;
+}
+
 String Internals::scrollingStateTreeAsText(Document* document, ExceptionState& es) const
 {
     return String();
@@ -1875,12 +1854,6 @@
         es.throwUninformativeAndGenericDOMException(InvalidAccessError);
         return;
     }
-
-    if (StyleResolver* resolver = contextDocument()->styleResolverIfExists())
-        resolver->clearStyleSharingList();
-    if (StyleResolver* resolver = document->styleResolverIfExists())
-        resolver->clearStyleSharingList();
-
     ResourceFetcher* fetcher = document->fetcher();
     if (!fetcher)
         return;
@@ -2055,8 +2028,8 @@
 
 Vector<String> Internals::getReferencedFilePaths() const
 {
-    frame()->loader()->history()->saveDocumentAndScrollState();
-    return FormController::getReferencedFilePaths(frame()->loader()->history()->currentItem()->documentState());
+    frame()->loader().history()->saveDocumentAndScrollState();
+    return FormController::getReferencedFilePaths(frame()->loader().history()->currentItem()->documentState());
 }
 
 void Internals::startTrackingRepaints(Document* document, ExceptionState& es)
@@ -2170,7 +2143,7 @@
         return String();
     }
 
-    Cursor cursor = document->frame()->eventHandler()->currentMouseCursor();
+    Cursor cursor = document->frame()->eventHandler().currentMouseCursor();
 
     StringBuilder result;
     result.append("type=");
@@ -2211,7 +2184,7 @@
 
 void Internals::forceReload(bool endToEnd)
 {
-    frame()->loader()->reload(endToEnd ? EndToEndReload : NormalReload);
+    frame()->loader().reload(endToEnd ? EndToEndReload : NormalReload);
 }
 
 PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionState& es)
diff --git a/Source/core/testing/Internals.h b/Source/core/testing/Internals.h
index a701bdd..97c7056 100644
--- a/Source/core/testing/Internals.h
+++ b/Source/core/testing/Internals.h
@@ -98,7 +98,6 @@
     bool hasShadowInsertionPoint(const Node*, ExceptionState&) const;
     bool hasContentElement(const Node*, ExceptionState&) const;
     size_t countElementShadow(const Node*, ExceptionState&) const;
-    Element* includerFor(Node*, ExceptionState&);
     String shadowPseudoId(Element*, ExceptionState&);
     void setShadowPseudoId(Element*, const String&, ExceptionState&);
 
@@ -225,6 +224,8 @@
     void setNeedsCompositedScrolling(Element*, unsigned value, ExceptionState&);
 
     String repaintRectsAsText(Document*, ExceptionState&) const;
+    PassRefPtr<ClientRectList> repaintRects(Element*, ExceptionState&) const;
+
     String scrollingStateTreeAsText(Document*, ExceptionState&) const;
     String mainThreadScrollingReasons(Document*, ExceptionState&) const;
     PassRefPtr<ClientRectList> nonFastScrollableRects(Document*, ExceptionState&) const;
@@ -287,8 +288,6 @@
 
     void forceReload(bool endToEnd);
 
-    void enableMockSpeechSynthesizer();
-
     String getImageSourceURL(Element*, ExceptionState&);
 
     bool isSelectPopupVisible(Node*);
diff --git a/Source/core/testing/Internals.idl b/Source/core/testing/Internals.idl
index c7e5314..864d1f9 100644
--- a/Source/core/testing/Internals.idl
+++ b/Source/core/testing/Internals.idl
@@ -51,7 +51,6 @@
     [RaisesException] boolean hasShadowInsertionPoint(Node root);
     [RaisesException] boolean hasContentElement(Node root);
     [RaisesException] unsigned long countElementShadow(Node Root);
-    [RaisesException] Element includerFor(Node node);
     [RaisesException] DOMString shadowPseudoId(Element element);
     [RaisesException] void setShadowPseudoId(Element element, DOMString id);
     [RaisesException] Element createContentElement();
@@ -74,8 +73,6 @@
     [RaisesException] Node nextNodeByWalker(Node node);
     [RaisesException] Node previousNodeByWalker(Node node);
 
-    [RaisesException] boolean attached(Node node);
-
     DOMString visiblePlaceholder(Element element);
 
     void selectColorInColorChooser(Element element, DOMString colorValue);
@@ -192,6 +189,7 @@
     [RaisesException] ClientRectList nonFastScrollableRects(Document document);
 
     [RaisesException] DOMString repaintRectsAsText(Document document);
+    [RaisesException] ClientRectList repaintRects(Element element);
 
     [RaisesException] void garbageCollectDocumentResources(Document document);
     void evictAllResources();
@@ -255,8 +253,6 @@
 
     void forceReload(boolean endToEnd);
 
-    void enableMockSpeechSynthesizer();
-
     [RaisesException] DOMString getImageSourceURL(Element element);
 
     boolean isSelectPopupVisible(Node node);
diff --git a/Source/core/testing/MockPagePopupDriver.cpp b/Source/core/testing/MockPagePopupDriver.cpp
index 48fceda..4902ca0 100644
--- a/Source/core/testing/MockPagePopupDriver.cpp
+++ b/Source/core/testing/MockPagePopupDriver.cpp
@@ -71,11 +71,11 @@
     if (document->body())
         document->body()->appendChild(m_iframe.get());
     Frame* contentFrame = m_iframe->contentFrame();
-    DocumentWriter* writer = contentFrame->loader()->activeDocumentLoader()->beginWriting("text/html", "UTF-8");
+    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);
+    contentFrame->loader().activeDocumentLoader()->endWriting(writer);
 }
 
 PassRefPtr<MockPagePopup> MockPagePopup::create(PagePopupClient* client, const IntRect& originBoundsInRootView, Frame* mainFrame)
diff --git a/Source/core/timing/Performance.cpp b/Source/core/timing/Performance.cpp
index 95f4728..7ccabeb 100644
--- a/Source/core/timing/Performance.cpp
+++ b/Source/core/timing/Performance.cpp
@@ -53,8 +53,8 @@
 Performance::Performance(Frame* frame)
     : DOMWindowProperty(frame)
     , m_resourceTimingBufferSize(defaultResourceTimingBufferSize)
-    , m_userTiming(0)
     , m_referenceTime(frame->document()->loader()->timing()->referenceMonotonicTime())
+    , m_userTiming(0)
 {
     ASSERT(m_referenceTime);
     ScriptWrappable::init(this);
diff --git a/Source/core/timing/PerformanceNavigation.cpp b/Source/core/timing/PerformanceNavigation.cpp
index 2a19b71..7e94d75 100644
--- a/Source/core/timing/PerformanceNavigation.cpp
+++ b/Source/core/timing/PerformanceNavigation.cpp
@@ -48,7 +48,7 @@
     if (!m_frame)
         return TYPE_NAVIGATE;
 
-    DocumentLoader* documentLoader = m_frame->loader()->documentLoader();
+    DocumentLoader* documentLoader = m_frame->loader().documentLoader();
     if (!documentLoader)
         return TYPE_NAVIGATE;
 
@@ -68,7 +68,7 @@
     if (!m_frame)
         return 0;
 
-    DocumentLoader* loader = m_frame->loader()->documentLoader();
+    DocumentLoader* loader = m_frame->loader().documentLoader();
     if (!loader)
         return 0;
 
diff --git a/Source/core/timing/PerformanceTiming.cpp b/Source/core/timing/PerformanceTiming.cpp
index afc17d3..0aa305e 100644
--- a/Source/core/timing/PerformanceTiming.cpp
+++ b/Source/core/timing/PerformanceTiming.cpp
@@ -312,7 +312,7 @@
     if (!m_frame)
         return 0;
 
-    return m_frame->loader()->documentLoader();
+    return m_frame->loader().documentLoader();
 }
 
 const DocumentTiming* PerformanceTiming::documentTiming() const
diff --git a/Source/core/timing/PerformanceUserTiming.cpp b/Source/core/timing/PerformanceUserTiming.cpp
index 7600337..d436560 100644
--- a/Source/core/timing/PerformanceUserTiming.cpp
+++ b/Source/core/timing/PerformanceUserTiming.cpp
@@ -31,7 +31,7 @@
 #include "core/timing/Performance.h"
 #include "core/timing/PerformanceMark.h"
 #include "core/timing/PerformanceMeasure.h"
-#include "core/platform/HistogramSupport.h"
+#include "public/platform/Platform.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -108,7 +108,7 @@
 
     double startTime = m_performance->now();
     insertPerformanceEntry(m_marksMap, PerformanceMark::create(markName, startTime));
-    HistogramSupport::histogramCustomCounts("PLT.UserTiming_Mark", static_cast<int>(startTime), 0, 600000, 100);
+    WebKit::Platform::current()->histogramCustomCounts("PLT.UserTiming_Mark", static_cast<int>(startTime), 0, 600000, 100);
 }
 
 void UserTiming::clearMarks(const String& markName)
@@ -157,7 +157,7 @@
 
     insertPerformanceEntry(m_measuresMap, PerformanceMeasure::create(measureName, startTime, endTime));
     if (endTime >= startTime)
-        HistogramSupport::histogramCustomCounts("PLT.UserTiming_MeasureDuration", static_cast<int>(endTime - startTime), 0, 600000, 100);
+        WebKit::Platform::current()->histogramCustomCounts("PLT.UserTiming_MeasureDuration", static_cast<int>(endTime - startTime), 0, 600000, 100);
 }
 
 void UserTiming::clearMeasures(const String& measureName)
diff --git a/Source/core/timing/ResourceTimingInfo.h b/Source/core/timing/ResourceTimingInfo.h
index ba8544c..a3784a6 100644
--- a/Source/core/timing/ResourceTimingInfo.h
+++ b/Source/core/timing/ResourceTimingInfo.h
@@ -61,6 +61,13 @@
     void addRedirect(const ResourceResponse& redirectResponse) { m_redirectChain.append(redirectResponse); }
     const Vector<ResourceResponse>& redirectChain() const { return m_redirectChain; }
 
+    void clearLoadTimings()
+    {
+        m_finalResponse.setResourceLoadTiming(0);
+        for (size_t i = 0; i < m_redirectChain.size(); ++i)
+            m_redirectChain[i].setResourceLoadTiming(0);
+    }
+
 private:
     ResourceTimingInfo(const AtomicString& type, const double time)
         : m_type(type)
diff --git a/Source/core/webcore.target.darwin-arm.mk b/Source/core/webcore.target.darwin-arm.mk
index 5cbd62f..5d0b4e9 100644
--- a/Source/core/webcore.target.darwin-arm.mk
+++ b/Source/core/webcore.target.darwin-arm.mk
@@ -15,7 +15,6 @@
 	$(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_platform_geometry_gyp)/third_party_WebKit_Source_core_webcore_platform_geometry_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 \
diff --git a/Source/core/webcore.target.darwin-mips.mk b/Source/core/webcore.target.darwin-mips.mk
index 04ed651..ee62396 100644
--- a/Source/core/webcore.target.darwin-mips.mk
+++ b/Source/core/webcore.target.darwin-mips.mk
@@ -15,7 +15,6 @@
 	$(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_platform_geometry_gyp)/third_party_WebKit_Source_core_webcore_platform_geometry_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 \
diff --git a/Source/core/webcore.target.darwin-x86.mk b/Source/core/webcore.target.darwin-x86.mk
index 04ed651..ee62396 100644
--- a/Source/core/webcore.target.darwin-x86.mk
+++ b/Source/core/webcore.target.darwin-x86.mk
@@ -15,7 +15,6 @@
 	$(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_platform_geometry_gyp)/third_party_WebKit_Source_core_webcore_platform_geometry_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 \
diff --git a/Source/core/webcore.target.linux-arm.mk b/Source/core/webcore.target.linux-arm.mk
index 5cbd62f..5d0b4e9 100644
--- a/Source/core/webcore.target.linux-arm.mk
+++ b/Source/core/webcore.target.linux-arm.mk
@@ -15,7 +15,6 @@
 	$(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_platform_geometry_gyp)/third_party_WebKit_Source_core_webcore_platform_geometry_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 \
diff --git a/Source/core/webcore.target.linux-mips.mk b/Source/core/webcore.target.linux-mips.mk
index 04ed651..ee62396 100644
--- a/Source/core/webcore.target.linux-mips.mk
+++ b/Source/core/webcore.target.linux-mips.mk
@@ -15,7 +15,6 @@
 	$(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_platform_geometry_gyp)/third_party_WebKit_Source_core_webcore_platform_geometry_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 \
diff --git a/Source/core/webcore.target.linux-x86.mk b/Source/core/webcore.target.linux-x86.mk
index 04ed651..ee62396 100644
--- a/Source/core/webcore.target.linux-x86.mk
+++ b/Source/core/webcore.target.linux-x86.mk
@@ -15,7 +15,6 @@
 	$(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_platform_geometry_gyp)/third_party_WebKit_Source_core_webcore_platform_geometry_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 \
diff --git a/Source/core/webcore_derived.target.darwin-arm.mk b/Source/core/webcore_derived.target.darwin-arm.mk
index a3757cd..db73705 100644
--- a/Source/core/webcore_derived.target.darwin-arm.mk
+++ b/Source/core/webcore_derived.target.darwin-arm.mk
@@ -20,6 +20,7 @@
 	$(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 \
@@ -70,8 +71,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/ColorData.cpp: $(gyp_shared_intermediate_dir)/blink/ColorData.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
@@ -112,8 +111,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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
@@ -160,7 +157,6 @@
 	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
-	$(gyp_intermediate_dir)/ColorData.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
@@ -181,7 +177,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
-	$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -209,7 +204,6 @@
 	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/DateExtension.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 \
@@ -302,7 +296,6 @@
 	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/V8HTMLImageElementConstructor.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -389,13 +382,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -546,13 +539,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_derived.target.darwin-mips.mk b/Source/core/webcore_derived.target.darwin-mips.mk
index c3b29b0..897b5c4 100644
--- a/Source/core/webcore_derived.target.darwin-mips.mk
+++ b/Source/core/webcore_derived.target.darwin-mips.mk
@@ -20,6 +20,7 @@
 	$(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 \
@@ -70,8 +71,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/ColorData.cpp: $(gyp_shared_intermediate_dir)/blink/ColorData.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
@@ -112,8 +111,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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
@@ -160,7 +157,6 @@
 	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
-	$(gyp_intermediate_dir)/ColorData.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
@@ -181,7 +177,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
-	$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -209,7 +204,6 @@
 	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/DateExtension.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 \
@@ -302,7 +296,6 @@
 	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/V8HTMLImageElementConstructor.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -389,13 +382,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -546,13 +539,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_derived.target.darwin-x86.mk b/Source/core/webcore_derived.target.darwin-x86.mk
index 4078d68..046cf6b 100644
--- a/Source/core/webcore_derived.target.darwin-x86.mk
+++ b/Source/core/webcore_derived.target.darwin-x86.mk
@@ -20,6 +20,7 @@
 	$(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 \
@@ -70,8 +71,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/ColorData.cpp: $(gyp_shared_intermediate_dir)/blink/ColorData.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
@@ -112,8 +111,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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
@@ -160,7 +157,6 @@
 	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
-	$(gyp_intermediate_dir)/ColorData.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
@@ -181,7 +177,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
-	$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -209,7 +204,6 @@
 	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/DateExtension.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 \
@@ -302,7 +296,6 @@
 	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/V8HTMLImageElementConstructor.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -391,13 +384,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -551,13 +544,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_derived.target.linux-arm.mk b/Source/core/webcore_derived.target.linux-arm.mk
index a3757cd..db73705 100644
--- a/Source/core/webcore_derived.target.linux-arm.mk
+++ b/Source/core/webcore_derived.target.linux-arm.mk
@@ -20,6 +20,7 @@
 	$(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 \
@@ -70,8 +71,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/ColorData.cpp: $(gyp_shared_intermediate_dir)/blink/ColorData.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
@@ -112,8 +111,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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
@@ -160,7 +157,6 @@
 	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
-	$(gyp_intermediate_dir)/ColorData.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
@@ -181,7 +177,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
-	$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -209,7 +204,6 @@
 	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/DateExtension.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 \
@@ -302,7 +296,6 @@
 	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/V8HTMLImageElementConstructor.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -389,13 +382,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -546,13 +539,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_derived.target.linux-mips.mk b/Source/core/webcore_derived.target.linux-mips.mk
index c3b29b0..897b5c4 100644
--- a/Source/core/webcore_derived.target.linux-mips.mk
+++ b/Source/core/webcore_derived.target.linux-mips.mk
@@ -20,6 +20,7 @@
 	$(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 \
@@ -70,8 +71,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/ColorData.cpp: $(gyp_shared_intermediate_dir)/blink/ColorData.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
@@ -112,8 +111,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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
@@ -160,7 +157,6 @@
 	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
-	$(gyp_intermediate_dir)/ColorData.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
@@ -181,7 +177,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
-	$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -209,7 +204,6 @@
 	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/DateExtension.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 \
@@ -302,7 +296,6 @@
 	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/V8HTMLImageElementConstructor.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -389,13 +382,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -546,13 +539,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_derived.target.linux-x86.mk b/Source/core/webcore_derived.target.linux-x86.mk
index 4078d68..046cf6b 100644
--- a/Source/core/webcore_derived.target.linux-x86.mk
+++ b/Source/core/webcore_derived.target.linux-x86.mk
@@ -20,6 +20,7 @@
 	$(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 \
@@ -70,8 +71,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/ColorData.cpp: $(gyp_shared_intermediate_dir)/blink/ColorData.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
@@ -112,8 +111,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp: $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.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
@@ -160,7 +157,6 @@
 	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
 	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
-	$(gyp_intermediate_dir)/ColorData.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
@@ -181,7 +177,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
-	$(gyp_intermediate_dir)/RuntimeEnabledFeatures.cpp \
 	$(gyp_intermediate_dir)/CSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
@@ -209,7 +204,6 @@
 	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/DateExtension.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 \
@@ -302,7 +296,6 @@
 	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/V8HTMLImageElementConstructor.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLMediaElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -391,13 +384,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -551,13 +544,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_dom.target.darwin-arm.mk b/Source/core/webcore_dom.target.darwin-arm.mk
index 81d5070..79d7ee1 100644
--- a/Source/core/webcore_dom.target.darwin-arm.mk
+++ b/Source/core/webcore_dom.target.darwin-arm.mk
@@ -73,6 +73,7 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtils.cpp \
 	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/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -165,7 +166,7 @@
 	third_party/WebKit/Source/core/events/ClipboardEvent.cpp \
 	third_party/WebKit/Source/core/events/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/events/CustomEvent.cpp \
-	third_party/WebKit/Source/core/events/DocumentEventQueue.cpp \
+	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 \
@@ -240,13 +241,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -392,13 +393,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_dom.target.darwin-mips.mk b/Source/core/webcore_dom.target.darwin-mips.mk
index cf12653..a744b09 100644
--- a/Source/core/webcore_dom.target.darwin-mips.mk
+++ b/Source/core/webcore_dom.target.darwin-mips.mk
@@ -73,6 +73,7 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtils.cpp \
 	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/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -165,7 +166,7 @@
 	third_party/WebKit/Source/core/events/ClipboardEvent.cpp \
 	third_party/WebKit/Source/core/events/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/events/CustomEvent.cpp \
-	third_party/WebKit/Source/core/events/DocumentEventQueue.cpp \
+	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 \
@@ -240,13 +241,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -392,13 +393,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_dom.target.darwin-x86.mk b/Source/core/webcore_dom.target.darwin-x86.mk
index 72d020c..dcddeba 100644
--- a/Source/core/webcore_dom.target.darwin-x86.mk
+++ b/Source/core/webcore_dom.target.darwin-x86.mk
@@ -73,6 +73,7 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtils.cpp \
 	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/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -165,7 +166,7 @@
 	third_party/WebKit/Source/core/events/ClipboardEvent.cpp \
 	third_party/WebKit/Source/core/events/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/events/CustomEvent.cpp \
-	third_party/WebKit/Source/core/events/DocumentEventQueue.cpp \
+	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 \
@@ -242,13 +243,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -397,13 +398,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_dom.target.linux-arm.mk b/Source/core/webcore_dom.target.linux-arm.mk
index 81d5070..79d7ee1 100644
--- a/Source/core/webcore_dom.target.linux-arm.mk
+++ b/Source/core/webcore_dom.target.linux-arm.mk
@@ -73,6 +73,7 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtils.cpp \
 	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/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -165,7 +166,7 @@
 	third_party/WebKit/Source/core/events/ClipboardEvent.cpp \
 	third_party/WebKit/Source/core/events/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/events/CustomEvent.cpp \
-	third_party/WebKit/Source/core/events/DocumentEventQueue.cpp \
+	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 \
@@ -240,13 +241,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -392,13 +393,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_dom.target.linux-mips.mk b/Source/core/webcore_dom.target.linux-mips.mk
index cf12653..a744b09 100644
--- a/Source/core/webcore_dom.target.linux-mips.mk
+++ b/Source/core/webcore_dom.target.linux-mips.mk
@@ -73,6 +73,7 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtils.cpp \
 	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/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -165,7 +166,7 @@
 	third_party/WebKit/Source/core/events/ClipboardEvent.cpp \
 	third_party/WebKit/Source/core/events/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/events/CustomEvent.cpp \
-	third_party/WebKit/Source/core/events/DocumentEventQueue.cpp \
+	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 \
@@ -240,13 +241,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -392,13 +393,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_dom.target.linux-x86.mk b/Source/core/webcore_dom.target.linux-x86.mk
index 72d020c..dcddeba 100644
--- a/Source/core/webcore_dom.target.linux-x86.mk
+++ b/Source/core/webcore_dom.target.linux-x86.mk
@@ -73,6 +73,7 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtils.cpp \
 	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/ElementRareData.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -165,7 +166,7 @@
 	third_party/WebKit/Source/core/events/ClipboardEvent.cpp \
 	third_party/WebKit/Source/core/events/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/events/CustomEvent.cpp \
-	third_party/WebKit/Source/core/events/DocumentEventQueue.cpp \
+	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 \
@@ -242,13 +243,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -397,13 +398,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_html.target.darwin-arm.mk b/Source/core/webcore_html.target.darwin-arm.mk
index afc6fe5..61f727b 100644
--- a/Source/core/webcore_html.target.darwin-arm.mk
+++ b/Source/core/webcore_html.target.darwin-arm.mk
@@ -91,7 +91,6 @@
 	third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLParamElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp \
-	third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
@@ -325,13 +324,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -477,13 +476,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_html.target.darwin-mips.mk b/Source/core/webcore_html.target.darwin-mips.mk
index 0237bf0..7e75c00 100644
--- a/Source/core/webcore_html.target.darwin-mips.mk
+++ b/Source/core/webcore_html.target.darwin-mips.mk
@@ -91,7 +91,6 @@
 	third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLParamElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp \
-	third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
@@ -325,13 +324,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -477,13 +476,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_html.target.darwin-x86.mk b/Source/core/webcore_html.target.darwin-x86.mk
index c861f91..50a4656 100644
--- a/Source/core/webcore_html.target.darwin-x86.mk
+++ b/Source/core/webcore_html.target.darwin-x86.mk
@@ -91,7 +91,6 @@
 	third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLParamElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp \
-	third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
@@ -327,13 +326,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -482,13 +481,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_html.target.linux-arm.mk b/Source/core/webcore_html.target.linux-arm.mk
index afc6fe5..61f727b 100644
--- a/Source/core/webcore_html.target.linux-arm.mk
+++ b/Source/core/webcore_html.target.linux-arm.mk
@@ -91,7 +91,6 @@
 	third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLParamElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp \
-	third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
@@ -325,13 +324,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -477,13 +476,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_html.target.linux-mips.mk b/Source/core/webcore_html.target.linux-mips.mk
index 0237bf0..7e75c00 100644
--- a/Source/core/webcore_html.target.linux-mips.mk
+++ b/Source/core/webcore_html.target.linux-mips.mk
@@ -91,7 +91,6 @@
 	third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLParamElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp \
-	third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
@@ -325,13 +324,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -477,13 +476,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_html.target.linux-x86.mk b/Source/core/webcore_html.target.linux-x86.mk
index c861f91..50a4656 100644
--- a/Source/core/webcore_html.target.linux-x86.mk
+++ b/Source/core/webcore_html.target.linux-x86.mk
@@ -91,7 +91,6 @@
 	third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLParamElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp \
-	third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
@@ -327,13 +326,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -482,13 +481,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_platform.target.darwin-arm.mk b/Source/core/webcore_platform.target.darwin-arm.mk
index f06c45b..1d108f1 100644
--- a/Source/core/webcore_platform.target.darwin-arm.mk
+++ b/Source/core/webcore_platform.target.darwin-arm.mk
@@ -30,16 +30,13 @@
 	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleContext.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
+	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
-	third_party/WebKit/Source/core/platform/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimator.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp \
 	third_party/WebKit/Source/core/platform/ScrollView.cpp \
@@ -56,21 +53,16 @@
 	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/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp \
-	third_party/WebKit/Source/core/platform/graphics/Color.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
-	third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
@@ -82,7 +74,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
@@ -90,7 +81,6 @@
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
@@ -163,15 +153,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
@@ -238,13 +219,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -391,13 +372,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_platform.target.darwin-mips.mk b/Source/core/webcore_platform.target.darwin-mips.mk
index 73b4dbe..2ad0c02 100644
--- a/Source/core/webcore_platform.target.darwin-mips.mk
+++ b/Source/core/webcore_platform.target.darwin-mips.mk
@@ -30,16 +30,13 @@
 	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleContext.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
+	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
-	third_party/WebKit/Source/core/platform/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimator.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp \
 	third_party/WebKit/Source/core/platform/ScrollView.cpp \
@@ -56,21 +53,16 @@
 	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/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp \
-	third_party/WebKit/Source/core/platform/graphics/Color.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
-	third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
@@ -82,7 +74,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
@@ -90,7 +81,6 @@
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
@@ -163,15 +153,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
@@ -238,13 +219,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -391,13 +372,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_platform.target.darwin-x86.mk b/Source/core/webcore_platform.target.darwin-x86.mk
index c8208a9..46d55bd 100644
--- a/Source/core/webcore_platform.target.darwin-x86.mk
+++ b/Source/core/webcore_platform.target.darwin-x86.mk
@@ -30,16 +30,13 @@
 	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleContext.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
+	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
-	third_party/WebKit/Source/core/platform/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimator.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp \
 	third_party/WebKit/Source/core/platform/ScrollView.cpp \
@@ -56,21 +53,16 @@
 	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/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp \
-	third_party/WebKit/Source/core/platform/graphics/Color.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
-	third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
@@ -82,7 +74,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
@@ -90,7 +81,6 @@
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
@@ -163,15 +153,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
@@ -240,13 +221,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -396,13 +377,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_platform.target.linux-arm.mk b/Source/core/webcore_platform.target.linux-arm.mk
index f06c45b..1d108f1 100644
--- a/Source/core/webcore_platform.target.linux-arm.mk
+++ b/Source/core/webcore_platform.target.linux-arm.mk
@@ -30,16 +30,13 @@
 	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleContext.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
+	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
-	third_party/WebKit/Source/core/platform/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimator.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp \
 	third_party/WebKit/Source/core/platform/ScrollView.cpp \
@@ -56,21 +53,16 @@
 	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/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp \
-	third_party/WebKit/Source/core/platform/graphics/Color.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
-	third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
@@ -82,7 +74,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
@@ -90,7 +81,6 @@
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
@@ -163,15 +153,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
@@ -238,13 +219,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -391,13 +372,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_platform.target.linux-mips.mk b/Source/core/webcore_platform.target.linux-mips.mk
index 73b4dbe..2ad0c02 100644
--- a/Source/core/webcore_platform.target.linux-mips.mk
+++ b/Source/core/webcore_platform.target.linux-mips.mk
@@ -30,16 +30,13 @@
 	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleContext.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
+	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
-	third_party/WebKit/Source/core/platform/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimator.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp \
 	third_party/WebKit/Source/core/platform/ScrollView.cpp \
@@ -56,21 +53,16 @@
 	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/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp \
-	third_party/WebKit/Source/core/platform/graphics/Color.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
-	third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
@@ -82,7 +74,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
@@ -90,7 +81,6 @@
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
@@ -163,15 +153,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
@@ -238,13 +219,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -391,13 +372,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_platform.target.linux-x86.mk b/Source/core/webcore_platform.target.linux-x86.mk
index c8208a9..46d55bd 100644
--- a/Source/core/webcore_platform.target.linux-x86.mk
+++ b/Source/core/webcore_platform.target.linux-x86.mk
@@ -30,16 +30,13 @@
 	third_party/WebKit/Source/core/platform/DragData.cpp \
 	third_party/WebKit/Source/core/platform/DragImage.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleContext.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
+	third_party/WebKit/Source/core/platform/OverscrollTheme.cpp \
 	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp \
 	third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp \
-	third_party/WebKit/Source/core/platform/Prerender.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimator.cpp \
 	third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp \
 	third_party/WebKit/Source/core/platform/ScrollView.cpp \
@@ -56,21 +53,16 @@
 	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/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp \
-	third_party/WebKit/Source/core/platform/graphics/Color.cpp \
 	third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GradientGeneratedImage.cpp \
-	third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Font.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontCache.cpp \
-	third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp \
 	third_party/WebKit/Source/core/platform/graphics/FrameData.cpp \
@@ -82,7 +74,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp \
@@ -90,7 +81,6 @@
 	third_party/WebKit/Source/core/platform/graphics/Path.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Pattern.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp \
-	third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp \
 	third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp \
@@ -163,15 +153,6 @@
 	third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp \
-	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
@@ -240,13 +221,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -396,13 +377,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-arm.mk b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
deleted file mode 100644
index 62d2eb4..0000000
--- a/Source/core/webcore_platform_geometry.target.darwin-arm.mk
+++ /dev/null
@@ -1,397 +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_geometry_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/graphics/FloatPolygon.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
-
-
-# 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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-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_geometry_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform_geometry
-webcore_platform_geometry: third_party_WebKit_Source_core_webcore_platform_geometry_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform_geometry.target.darwin-mips.mk b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
deleted file mode 100644
index 64fc8ee..0000000
--- a/Source/core/webcore_platform_geometry.target.darwin-mips.mk
+++ /dev/null
@@ -1,393 +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_geometry_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/graphics/FloatPolygon.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
-
-
-# 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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-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_geometry_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform_geometry
-webcore_platform_geometry: third_party_WebKit_Source_core_webcore_platform_geometry_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform_geometry.target.darwin-x86.mk b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
deleted file mode 100644
index b593964..0000000
--- a/Source/core/webcore_platform_geometry.target.darwin-x86.mk
+++ /dev/null
@@ -1,397 +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_geometry_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/graphics/FloatPolygon.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	--param=ssp-buffer-size=4 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-fno-stack-protector \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	--param=ssp-buffer-size=4 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-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' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
-
-
-# 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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-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_geometry_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform_geometry
-webcore_platform_geometry: third_party_WebKit_Source_core_webcore_platform_geometry_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform_geometry.target.linux-arm.mk b/Source/core/webcore_platform_geometry.target.linux-arm.mk
deleted file mode 100644
index 62d2eb4..0000000
--- a/Source/core/webcore_platform_geometry.target.linux-arm.mk
+++ /dev/null
@@ -1,397 +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_geometry_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/graphics/FloatPolygon.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
-
-
-# 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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-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_geometry_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform_geometry
-webcore_platform_geometry: third_party_WebKit_Source_core_webcore_platform_geometry_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform_geometry.target.linux-mips.mk b/Source/core/webcore_platform_geometry.target.linux-mips.mk
deleted file mode 100644
index 64fc8ee..0000000
--- a/Source/core/webcore_platform_geometry.target.linux-mips.mk
+++ /dev/null
@@ -1,393 +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_geometry_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/graphics/FloatPolygon.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
-
-
-# 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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-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_geometry_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform_geometry
-webcore_platform_geometry: third_party_WebKit_Source_core_webcore_platform_geometry_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform_geometry.target.linux-x86.mk b/Source/core/webcore_platform_geometry.target.linux-x86.mk
deleted file mode 100644
index b593964..0000000
--- a/Source/core/webcore_platform_geometry.target.linux-x86.mk
+++ /dev/null
@@ -1,397 +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_geometry_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/graphics/FloatPolygon.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	--param=ssp-buffer-size=4 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-fno-stack-protector \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	--param=ssp-buffer-size=4 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-Wno-format \
-	-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 \
-	-Wno-address \
-	-Wno-format-security \
-	-Wno-return-type \
-	-Wno-sequence-point \
-	-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' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CSS3_TEXT=0' \
-	'-DENABLE_CSS_EXCLUSIONS=1' \
-	'-DENABLE_CSS_REGIONS=1' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_CALENDAR_PICKER=0' \
-	'-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' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-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' \
-	'-DUSE_SYSTEM_LIBJPEG' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
-
-
-# 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/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(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/config \
-	$(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)/external/jpeg \
-	$(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 \
-	-Wno-c++0x-compat \
-	-Wno-deprecated \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo \
-	-Wno-non-virtual-dtor
-
-
-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_geometry_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform_geometry
-webcore_platform_geometry: third_party_WebKit_Source_core_webcore_platform_geometry_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_remaining.target.darwin-arm.mk b/Source/core/webcore_remaining.target.darwin-arm.mk
index 6dd0540..9073b9d 100644
--- a/Source/core/webcore_remaining.target.darwin-arm.mk
+++ b/Source/core/webcore_remaining.target.darwin-arm.mk
@@ -56,6 +56,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableImage.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp \
@@ -65,20 +66,23 @@
 	third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableShadow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	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/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
-	third_party/WebKit/Source/core/animation/ThreadedAnimation.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.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/TransitionTimeline.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 \
@@ -151,6 +155,7 @@
 	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
+	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
@@ -229,6 +234,7 @@
 	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 \
 	third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp \
 	third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp \
@@ -371,7 +377,7 @@
 	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
-	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
+	third_party/WebKit/Source/core/loader/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
@@ -440,7 +446,6 @@
 	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/page/RuntimeEnabledFeaturesCustom.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 \
@@ -562,13 +567,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -715,13 +720,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_remaining.target.darwin-mips.mk b/Source/core/webcore_remaining.target.darwin-mips.mk
index 3356d32..050d58e 100644
--- a/Source/core/webcore_remaining.target.darwin-mips.mk
+++ b/Source/core/webcore_remaining.target.darwin-mips.mk
@@ -56,6 +56,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableImage.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp \
@@ -65,20 +66,23 @@
 	third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableShadow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	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/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
-	third_party/WebKit/Source/core/animation/ThreadedAnimation.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.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/TransitionTimeline.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 \
@@ -151,6 +155,7 @@
 	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
+	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
@@ -229,6 +234,7 @@
 	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 \
 	third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp \
 	third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp \
@@ -371,7 +377,7 @@
 	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
-	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
+	third_party/WebKit/Source/core/loader/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
@@ -440,7 +446,6 @@
 	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/page/RuntimeEnabledFeaturesCustom.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 \
@@ -562,13 +567,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -715,13 +720,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_remaining.target.darwin-x86.mk b/Source/core/webcore_remaining.target.darwin-x86.mk
index 4fde99e..e15088a 100644
--- a/Source/core/webcore_remaining.target.darwin-x86.mk
+++ b/Source/core/webcore_remaining.target.darwin-x86.mk
@@ -56,6 +56,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableImage.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp \
@@ -65,20 +66,23 @@
 	third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableShadow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	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/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
-	third_party/WebKit/Source/core/animation/ThreadedAnimation.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.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/TransitionTimeline.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 \
@@ -151,6 +155,7 @@
 	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
+	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
@@ -229,6 +234,7 @@
 	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 \
 	third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp \
 	third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp \
@@ -371,7 +377,7 @@
 	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
-	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
+	third_party/WebKit/Source/core/loader/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
@@ -440,7 +446,6 @@
 	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/page/RuntimeEnabledFeaturesCustom.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 \
@@ -564,13 +569,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -720,13 +725,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_remaining.target.linux-arm.mk b/Source/core/webcore_remaining.target.linux-arm.mk
index 6dd0540..9073b9d 100644
--- a/Source/core/webcore_remaining.target.linux-arm.mk
+++ b/Source/core/webcore_remaining.target.linux-arm.mk
@@ -56,6 +56,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableImage.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp \
@@ -65,20 +66,23 @@
 	third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableShadow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	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/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
-	third_party/WebKit/Source/core/animation/ThreadedAnimation.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.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/TransitionTimeline.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 \
@@ -151,6 +155,7 @@
 	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
+	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
@@ -229,6 +234,7 @@
 	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 \
 	third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp \
 	third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp \
@@ -371,7 +377,7 @@
 	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
-	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
+	third_party/WebKit/Source/core/loader/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
@@ -440,7 +446,6 @@
 	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/page/RuntimeEnabledFeaturesCustom.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 \
@@ -562,13 +567,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -715,13 +720,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_remaining.target.linux-mips.mk b/Source/core/webcore_remaining.target.linux-mips.mk
index 3356d32..050d58e 100644
--- a/Source/core/webcore_remaining.target.linux-mips.mk
+++ b/Source/core/webcore_remaining.target.linux-mips.mk
@@ -56,6 +56,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableImage.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp \
@@ -65,20 +66,23 @@
 	third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableShadow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	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/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
-	third_party/WebKit/Source/core/animation/ThreadedAnimation.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.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/TransitionTimeline.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 \
@@ -151,6 +155,7 @@
 	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
+	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
@@ -229,6 +234,7 @@
 	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 \
 	third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp \
 	third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp \
@@ -371,7 +377,7 @@
 	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
-	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
+	third_party/WebKit/Source/core/loader/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
@@ -440,7 +446,6 @@
 	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/page/RuntimeEnabledFeaturesCustom.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 \
@@ -562,13 +567,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -715,13 +720,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_remaining.target.linux-x86.mk b/Source/core/webcore_remaining.target.linux-x86.mk
index 4fde99e..e15088a 100644
--- a/Source/core/webcore_remaining.target.linux-x86.mk
+++ b/Source/core/webcore_remaining.target.linux-x86.mk
@@ -56,6 +56,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableColor.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableDouble.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableImage.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp \
@@ -65,20 +66,23 @@
 	third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableShadow.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
 	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/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
 	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
-	third_party/WebKit/Source/core/animation/ThreadedAnimation.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.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/TransitionTimeline.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 \
@@ -151,6 +155,7 @@
 	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
+	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
 	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
@@ -229,6 +234,7 @@
 	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 \
 	third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp \
 	third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp \
@@ -371,7 +377,7 @@
 	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
-	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
+	third_party/WebKit/Source/core/loader/PrerenderHandle.cpp \
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
@@ -440,7 +446,6 @@
 	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/page/RuntimeEnabledFeaturesCustom.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 \
@@ -564,13 +569,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -720,13 +725,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_rendering.target.darwin-arm.mk b/Source/core/webcore_rendering.target.darwin-arm.mk
index f7280bc..3ec75fd 100644
--- a/Source/core/webcore_rendering.target.darwin-arm.mk
+++ b/Source/core/webcore_rendering.target.darwin-arm.mk
@@ -85,6 +85,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.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 \
@@ -143,7 +145,6 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -165,6 +166,7 @@
 	third_party/WebKit/Source/core/rendering/style/QuotesData.cpp \
 	third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp \
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
+	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/StyleFetchedImage.cpp \
@@ -228,13 +230,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -380,13 +382,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_rendering.target.darwin-mips.mk b/Source/core/webcore_rendering.target.darwin-mips.mk
index 282a907..c5c7523 100644
--- a/Source/core/webcore_rendering.target.darwin-mips.mk
+++ b/Source/core/webcore_rendering.target.darwin-mips.mk
@@ -85,6 +85,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.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 \
@@ -143,7 +145,6 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -165,6 +166,7 @@
 	third_party/WebKit/Source/core/rendering/style/QuotesData.cpp \
 	third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp \
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
+	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/StyleFetchedImage.cpp \
@@ -228,13 +230,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -380,13 +382,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_rendering.target.darwin-x86.mk b/Source/core/webcore_rendering.target.darwin-x86.mk
index 912caa4..a9a13f6 100644
--- a/Source/core/webcore_rendering.target.darwin-x86.mk
+++ b/Source/core/webcore_rendering.target.darwin-x86.mk
@@ -85,6 +85,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.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 \
@@ -143,7 +145,6 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -165,6 +166,7 @@
 	third_party/WebKit/Source/core/rendering/style/QuotesData.cpp \
 	third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp \
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
+	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/StyleFetchedImage.cpp \
@@ -231,13 +233,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -387,13 +389,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_rendering.target.linux-arm.mk b/Source/core/webcore_rendering.target.linux-arm.mk
index f7280bc..3ec75fd 100644
--- a/Source/core/webcore_rendering.target.linux-arm.mk
+++ b/Source/core/webcore_rendering.target.linux-arm.mk
@@ -85,6 +85,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.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 \
@@ -143,7 +145,6 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -165,6 +166,7 @@
 	third_party/WebKit/Source/core/rendering/style/QuotesData.cpp \
 	third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp \
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
+	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/StyleFetchedImage.cpp \
@@ -228,13 +230,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -380,13 +382,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_rendering.target.linux-mips.mk b/Source/core/webcore_rendering.target.linux-mips.mk
index 282a907..c5c7523 100644
--- a/Source/core/webcore_rendering.target.linux-mips.mk
+++ b/Source/core/webcore_rendering.target.linux-mips.mk
@@ -85,6 +85,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.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 \
@@ -143,7 +145,6 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -165,6 +166,7 @@
 	third_party/WebKit/Source/core/rendering/style/QuotesData.cpp \
 	third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp \
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
+	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/StyleFetchedImage.cpp \
@@ -228,13 +230,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -380,13 +382,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_rendering.target.linux-x86.mk b/Source/core/webcore_rendering.target.linux-x86.mk
index 912caa4..a9a13f6 100644
--- a/Source/core/webcore_rendering.target.linux-x86.mk
+++ b/Source/core/webcore_rendering.target.linux-x86.mk
@@ -85,6 +85,8 @@
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.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 \
@@ -143,7 +145,6 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
-	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -165,6 +166,7 @@
 	third_party/WebKit/Source/core/rendering/style/QuotesData.cpp \
 	third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp \
 	third_party/WebKit/Source/core/rendering/style/ShadowData.cpp \
+	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/StyleFetchedImage.cpp \
@@ -231,13 +233,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -387,13 +389,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_svg.target.darwin-arm.mk b/Source/core/webcore_svg.target.darwin-arm.mk
index 4d5bb1a..70b4a68 100644
--- a/Source/core/webcore_svg.target.darwin-arm.mk
+++ b/Source/core/webcore_svg.target.darwin-arm.mk
@@ -285,13 +285,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -437,13 +437,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_svg.target.darwin-mips.mk b/Source/core/webcore_svg.target.darwin-mips.mk
index 5a476e2..ce8e6b3 100644
--- a/Source/core/webcore_svg.target.darwin-mips.mk
+++ b/Source/core/webcore_svg.target.darwin-mips.mk
@@ -285,13 +285,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -437,13 +437,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_svg.target.darwin-x86.mk b/Source/core/webcore_svg.target.darwin-x86.mk
index 60252b1..e77bc75 100644
--- a/Source/core/webcore_svg.target.darwin-x86.mk
+++ b/Source/core/webcore_svg.target.darwin-x86.mk
@@ -287,13 +287,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -442,13 +442,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_svg.target.linux-arm.mk b/Source/core/webcore_svg.target.linux-arm.mk
index 4d5bb1a..70b4a68 100644
--- a/Source/core/webcore_svg.target.linux-arm.mk
+++ b/Source/core/webcore_svg.target.linux-arm.mk
@@ -285,13 +285,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -437,13 +437,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_svg.target.linux-mips.mk b/Source/core/webcore_svg.target.linux-mips.mk
index 5a476e2..ce8e6b3 100644
--- a/Source/core/webcore_svg.target.linux-mips.mk
+++ b/Source/core/webcore_svg.target.linux-mips.mk
@@ -285,13 +285,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -437,13 +437,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/webcore_svg.target.linux-x86.mk b/Source/core/webcore_svg.target.linux-x86.mk
index 60252b1..e77bc75 100644
--- a/Source/core/webcore_svg.target.linux-x86.mk
+++ b/Source/core/webcore_svg.target.linux-x86.mk
@@ -287,13 +287,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -442,13 +442,13 @@
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DDISABLE_NACL' \
 	'-DCHROMIUM_BUILD' \
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
+	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
+	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
diff --git a/Source/core/workers/DefaultSharedWorkerRepository.h b/Source/core/workers/DefaultSharedWorkerRepository.h
deleted file mode 100644
index d0da7a3..0000000
--- a/Source/core/workers/DefaultSharedWorkerRepository.h
+++ /dev/null
@@ -1,88 +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.
- */
-
-#ifndef DefaultSharedWorkerRepository_h
-#define DefaultSharedWorkerRepository_h
-
-#include "core/frame/ContentSecurityPolicy.h"
-#include "wtf/Forward.h"
-#include "wtf/HashMap.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Threading.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-    class Document;
-    class ExceptionState;
-    class KURL;
-    class MessagePortChannel;
-    class ExecutionContext;
-    class SharedWorker;
-    class SharedWorkerProxy;
-
-    // Platform-specific implementation of the SharedWorkerRepository static interface.
-    class DefaultSharedWorkerRepository {
-        WTF_MAKE_NONCOPYABLE(DefaultSharedWorkerRepository); WTF_MAKE_FAST_ALLOCATED;
-    public:
-        // Invoked once the worker script has been loaded to fire up the worker thread.
-        void workerScriptLoaded(SharedWorkerProxy&, const String& userAgent, const String& workerScript, PassRefPtr<MessagePortChannel>, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
-
-        // Internal implementation of SharedWorkerRepository::connect()
-        void connectToWorker(PassRefPtr<SharedWorker>, PassRefPtr<MessagePortChannel>, const KURL&, const String& name, ExceptionState&);
-
-        // Notification that a document has been detached.
-        void documentDetached(Document*);
-
-        // Removes the passed SharedWorkerProxy from the repository.
-        void removeProxy(SharedWorkerProxy*);
-
-        bool hasSharedWorkers(Document*);
-
-        static DefaultSharedWorkerRepository& instance();
-    private:
-        DefaultSharedWorkerRepository();
-        ~DefaultSharedWorkerRepository();
-
-        PassRefPtr<SharedWorkerProxy> getProxy(const String& name, const KURL&);
-        // Mutex used to protect internal data structures.
-        Mutex m_lock;
-
-        // List of shared workers. Expectation is that there will be a limited number of shared workers, and so tracking them in a Vector is more efficient than nested HashMaps.
-        typedef Vector<RefPtr<SharedWorkerProxy> > SharedWorkerProxyRepository;
-        SharedWorkerProxyRepository m_proxies;
-    };
-
-} // namespace WebCore
-
-#endif // DefaultSharedWorkerRepository_h
diff --git a/Source/core/workers/SharedWorker.cpp b/Source/core/workers/SharedWorker.cpp
index 781c4f6..a7a72c5 100644
--- a/Source/core/workers/SharedWorker.cpp
+++ b/Source/core/workers/SharedWorker.cpp
@@ -38,8 +38,9 @@
 #include "core/dom/MessageChannel.h"
 #include "core/dom/MessagePort.h"
 #include "core/inspector/InspectorInstrumentation.h"
+#include "core/page/Page.h"
 #include "core/page/UseCounter.h"
-#include "core/workers/SharedWorkerRepository.h"
+#include "core/workers/SharedWorkerRepositoryClient.h"
 #include "weborigin/KURL.h"
 #include "weborigin/SecurityOrigin.h"
 
@@ -54,6 +55,8 @@
 PassRefPtr<SharedWorker> SharedWorker::create(ExecutionContext* context, const String& url, const String& name, ExceptionState& es)
 {
     ASSERT(isMainThread());
+    ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
+
     UseCounter::count(toDocument(context)->domWindow(), UseCounter::SharedWorkerStart);
 
     RefPtr<SharedWorker> worker = adoptRef(new SharedWorker(context));
@@ -66,7 +69,6 @@
     worker->suspendIfNeeded();
 
     // We don't currently support nested workers, so workers can only be created from documents.
-    ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
     Document* document = toDocument(context);
     if (!document->securityOrigin()->canAccessSharedWorkers()) {
         es.throwSecurityError("Failed to create 'SharedWorker': access to shared workers is denied to origin '" + document->securityOrigin()->toString() + "'.");
@@ -77,7 +79,8 @@
     if (scriptURL.isEmpty())
         return 0;
 
-    SharedWorkerRepository::connect(worker.get(), remotePort.release(), scriptURL, name, es);
+    if (document->page() && document->page()->sharedWorkerRepositoryClient())
+        document->page()->sharedWorkerRepositoryClient()->connect(worker.get(), remotePort.release(), scriptURL, name, es);
 
     return worker.release();
 }
diff --git a/Source/core/workers/SharedWorkerRepository.h b/Source/core/workers/SharedWorkerRepository.h
deleted file mode 100644
index e9ab044..0000000
--- a/Source/core/workers/SharedWorkerRepository.h
+++ /dev/null
@@ -1,66 +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.
- */
-
-#ifndef SharedWorkerRepository_h
-#define SharedWorkerRepository_h
-
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-    class Document;
-    class ExceptionState;
-    class KURL;
-    class MessagePortChannel;
-    class SharedWorker;
-
-    // Interface to a repository which manages references to the set of active shared workers.
-    class SharedWorkerRepository {
-    public:
-        // Returns true if the platform supports SharedWorkers, otherwise false.
-        static bool isAvailable();
-
-        // Connects the passed SharedWorker object with the specified worker thread, creating a new thread if necessary.
-        static void connect(PassRefPtr<SharedWorker>, PassRefPtr<MessagePortChannel>, const KURL&, const String& name, ExceptionState&);
-
-        // Invoked when a document has been detached.
-        static void documentDetached(Document*);
-
-        // Returns true if the passed document is associated with any SharedWorkers.
-        static bool hasSharedWorkers(Document*);
-    private:
-        SharedWorkerRepository() { }
-    };
-
-} // namespace WebCore
-
-#endif // SharedWorkerRepository_h
diff --git a/Source/core/rendering/RenderingNodeProxy.h b/Source/core/workers/SharedWorkerRepositoryClient.h
similarity index 70%
rename from Source/core/rendering/RenderingNodeProxy.h
rename to Source/core/workers/SharedWorkerRepositoryClient.h
index ac5cb6d..c337e4e 100644
--- a/Source/core/rendering/RenderingNodeProxy.h
+++ b/Source/core/workers/SharedWorkerRepositoryClient.h
@@ -28,44 +28,31 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef RenderingNodeProxy_h
-#define RenderingNodeProxy_h
+#ifndef SharedWorkerRepositoryClient_h
+#define SharedWorkerRepositoryClient_h
 
-#include "core/rendering/LayoutIndicator.h"
+#include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
 
 namespace WebCore {
 
-class QualifiedName;
-class Node;
+class Document;
+class ExceptionState;
+class KURL;
+class MessagePortChannel;
+class SharedWorker;
 
-#define STRICT_LAYOUT_THREADING 0
-
-class RenderingNodeProxy {
-    WTF_MAKE_NONCOPYABLE(RenderingNodeProxy);
+class SharedWorkerRepositoryClient {
+    WTF_MAKE_NONCOPYABLE(SharedWorkerRepositoryClient);
 public:
-    explicit RenderingNodeProxy(Node*);
-    ~RenderingNodeProxy();
+    SharedWorkerRepositoryClient() { }
+    virtual ~SharedWorkerRepositoryClient() { }
 
-    bool hasTagName(const QualifiedName&) const;
+    virtual void connect(PassRefPtr<SharedWorker>, PassRefPtr<MessagePortChannel>, const KURL&, const String& name, ExceptionState&)  = 0;
 
-    Node* unsafeNode() const
-    {
-#if STRICT_LAYOUT_THREADING
-        ASSERT(!LayoutIndicator::inLayout());
-#endif
-        return m_node;
-    }
-
-    void clear() { m_node = 0; }
-    void set(Node* node) { m_node = node; }
-
-private:
-    Node* m_node;
+    virtual void documentDetached(Document*) = 0;
 };
 
-#undef STRICT_LAYOUT_THREADING
+} // namespace WebCore
 
-}
-
-#endif // RenderingNodeProxy_h
+#endif // SharedWorkerRepositoryClient_h
diff --git a/Source/core/workers/WorkerGlobalScope.cpp b/Source/core/workers/WorkerGlobalScope.cpp
index e6b4cc3..3b50908 100644
--- a/Source/core/workers/WorkerGlobalScope.cpp
+++ b/Source/core/workers/WorkerGlobalScope.cpp
@@ -84,8 +84,8 @@
     , m_workerInspectorController(adoptPtr(new WorkerInspectorController(this)))
     , m_closing(false)
     , m_eventQueue(WorkerEventQueue::create(this))
-    , m_timeOrigin(timeOrigin)
     , m_workerClients(workerClients)
+    , m_timeOrigin(timeOrigin)
 {
     ScriptWrappable::init(this);
     setClient(this);
@@ -242,6 +242,11 @@
     thread()->workerReportingProxy().postExceptionToWorkerObject(errorMessage, lineNumber, columnNumber, sourceURL);
 }
 
+void WorkerGlobalScope::reportBlockedScriptExecutionToInspector(const String& directiveText)
+{
+    InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
+}
+
 void WorkerGlobalScope::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
 {
     if (!isContextThread()) {
@@ -328,9 +333,4 @@
     return m_eventQueue.get();
 }
 
-PassOwnPtr<LifecycleNotifier> WorkerGlobalScope::createLifecycleNotifier()
-{
-    return ContextLifecycleNotifier::create(this);
-}
-
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerGlobalScope.h b/Source/core/workers/WorkerGlobalScope.h
index 0b88d3d..aa4a7c0 100644
--- a/Source/core/workers/WorkerGlobalScope.h
+++ b/Source/core/workers/WorkerGlobalScope.h
@@ -58,7 +58,7 @@
     class WorkerNavigator;
     class WorkerThread;
 
-    class WorkerGlobalScope : public RefCounted<WorkerGlobalScope>, public ScriptWrappable, public ExecutionContext, public ExecutionContextClient, public WorkerSupplementable, public EventTargetWithInlineData {
+    class WorkerGlobalScope : public RefCounted<WorkerGlobalScope>, public ScriptWrappable, public SecurityContext, public ExecutionContext, public ExecutionContextClient, public WorkerSupplementable, public EventTargetWithInlineData {
         REFCOUNTED_EVENT_TARGET(WorkerGlobalScope);
     public:
         virtual ~WorkerGlobalScope();
@@ -98,6 +98,7 @@
 
         // ExecutionContextClient
         virtual WorkerEventQueue* eventQueue() const OVERRIDE;
+        virtual SecurityContext& securityContext() OVERRIDE { return *this; }
 
         virtual bool isContextThread() const OVERRIDE;
         virtual bool isJSExecutionForbidden() const OVERRIDE;
@@ -135,6 +136,9 @@
 
         WorkerClients* clients() { return m_workerClients.get(); }
 
+        using SecurityContext::securityOrigin;
+        using SecurityContext::contentSecurityPolicy;
+
     protected:
         WorkerGlobalScope(const KURL&, const String& userAgent, WorkerThread*, double timeOrigin, PassOwnPtr<WorkerClients>);
         void applyContentSecurityPolicyFromString(const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
@@ -145,11 +149,11 @@
     private:
         virtual void refExecutionContext() OVERRIDE { ref(); }
         virtual void derefExecutionContext() OVERRIDE { deref(); }
-        virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
 
         virtual const KURL& virtualURL() const OVERRIDE;
         virtual KURL virtualCompleteURL(const String&) const;
 
+        virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE;
         virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* = 0) OVERRIDE;
 
         virtual EventTarget* errorEventTarget() OVERRIDE;
diff --git a/Source/core/workers/WorkerLocation.h b/Source/core/workers/WorkerLocation.h
index cd930e2..f34cd85 100644
--- a/Source/core/workers/WorkerLocation.h
+++ b/Source/core/workers/WorkerLocation.h
@@ -37,7 +37,7 @@
 
 namespace WebCore {
 
-class WorkerLocation : public RefCounted<WorkerLocation>, public ScriptWrappable, public DOMURLUtilsReadOnly {
+class WorkerLocation FINAL : public RefCounted<WorkerLocation>, public ScriptWrappable, public DOMURLUtilsReadOnly {
 public:
     static PassRefPtr<WorkerLocation> create(const KURL& url)
     {
diff --git a/Source/core/xml/XMLErrors.cpp b/Source/core/xml/XMLErrors.cpp
index 26a6d1a..caad7f0 100644
--- a/Source/core/xml/XMLErrors.cpp
+++ b/Source/core/xml/XMLErrors.cpp
@@ -129,7 +129,7 @@
         RefPtr<Element> body = m_document->createElement(bodyTag, true);
         rootElement->parserAppendChild(body);
 
-        m_document->parserRemoveChild(documentElement.get());
+        m_document->parserRemoveChild(*documentElement);
 
         body->parserAppendChild(documentElement);
         m_document->parserAppendChild(rootElement);
diff --git a/Source/core/xml/XMLHttpRequest.cpp b/Source/core/xml/XMLHttpRequest.cpp
index b617822..1e074ee 100644
--- a/Source/core/xml/XMLHttpRequest.cpp
+++ b/Source/core/xml/XMLHttpRequest.cpp
@@ -45,7 +45,6 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/ThreadableLoader.h"
 #include "core/page/Settings.h"
-#include "core/platform/HistogramSupport.h"
 #include "core/xml/XMLHttpRequestProgressEvent.h"
 #include "core/xml/XMLHttpRequestUpload.h"
 #include "platform/Logging.h"
@@ -55,6 +54,7 @@
 #include "platform/network/ParsedContentType.h"
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
+#include "public/platform/Platform.h"
 #include "weborigin/SecurityOrigin.h"
 #include "wtf/ArrayBuffer.h"
 #include "wtf/ArrayBufferView.h"
@@ -182,7 +182,7 @@
     , m_exceptionCode(0)
     , m_progressEventThrottle(this)
     , m_responseTypeCode(ResponseTypeDefault)
-    , m_protectionTimer(this, &XMLHttpRequest::dropProtection)
+    , m_dropProtectionRunner(this, &XMLHttpRequest::dropProtection)
     , m_securityOrigin(securityOrigin)
 {
     initializeXMLHttpRequestStaticData();
@@ -720,7 +720,7 @@
     String consoleMessage("ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead.");
     executionContext()->addConsoleMessage(JSMessageSource, WarningMessageLevel, consoleMessage);
 
-    HistogramSupport::histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBuffer, XMLHttpRequestSendArrayBufferOrViewMax);
+    WebKit::Platform::current()->histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBuffer, XMLHttpRequestSendArrayBufferOrViewMax);
 
     sendBytesData(body->data(), body->byteLength(), es);
 }
@@ -729,7 +729,7 @@
 {
     LOG(Network, "XMLHttpRequest %p send() ArrayBufferView %p", this, body);
 
-    HistogramSupport::histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBufferView, XMLHttpRequestSendArrayBufferOrViewMax);
+    WebKit::Platform::current()->histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBufferView, XMLHttpRequestSendArrayBufferOrViewMax);
 
     sendBytesData(body->baseAddress(), body->byteLength(), es);
 }
@@ -1004,12 +1004,10 @@
 
 void XMLHttpRequest::dropProtectionSoon()
 {
-    if (m_protectionTimer.isActive())
-        return;
-    m_protectionTimer.startOneShot(0);
+    m_dropProtectionRunner.runAsync();
 }
 
-void XMLHttpRequest::dropProtection(Timer<XMLHttpRequest>*)
+void XMLHttpRequest::dropProtection()
 {
     unsetPendingActivity(this);
 }
@@ -1059,10 +1057,8 @@
 
 String XMLHttpRequest::getAllResponseHeaders(ExceptionState& es) const
 {
-    if (m_state < HEADERS_RECEIVED) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("getAllResponseHeaders", "XMLHttpRequest", "the object's state must not be UNSENT or OPENED."));
+    if (m_state < HEADERS_RECEIVED || m_error)
         return "";
-    }
 
     StringBuilder stringBuilder;
 
@@ -1095,10 +1091,8 @@
 
 String XMLHttpRequest::getResponseHeader(const AtomicString& name, ExceptionState& es) const
 {
-    if (m_state < HEADERS_RECEIVED) {
-        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("getResponseHeader", "XMLHttpRequest", "the object's state must not be UNSENT or OPENED."));
+    if (m_state < HEADERS_RECEIVED || m_error)
         return String();
-    }
 
     // See comment in getAllResponseHeaders above.
     if (isSetCookieHeader(name) && !securityOrigin()->canLoadLocalResources()) {
diff --git a/Source/core/xml/XMLHttpRequest.h b/Source/core/xml/XMLHttpRequest.h
index 29efa0d..e5fdc6c 100644
--- a/Source/core/xml/XMLHttpRequest.h
+++ b/Source/core/xml/XMLHttpRequest.h
@@ -30,6 +30,7 @@
 #include "core/loader/ThreadableLoaderClient.h"
 #include "core/xml/XMLHttpRequestEventTarget.h"
 #include "core/xml/XMLHttpRequestProgressEventThrottle.h"
+#include "platform/AsyncMethodRunner.h"
 #include "platform/network/FormData.h"
 #include "platform/network/ResourceResponse.h"
 #include "weborigin/SecurityOrigin.h"
@@ -172,7 +173,7 @@
     void dispatchReadyStateChangeEvent();
 
     void dropProtectionSoon();
-    void dropProtection(Timer<XMLHttpRequest>* = 0);
+    void dropProtection();
     // Clears variables used only while the resource is being loaded.
     void clearVariablesForLoading();
     // Returns false iff reentry happened and a new load is started.
@@ -222,11 +223,11 @@
     ScriptString m_responseText;
     // Used to skip m_responseDocument creation if it's done previously. We need
     // this separate flag since m_responseDocument can be 0 for some cases.
-    mutable bool m_createdDocument;
-    mutable RefPtr<Document> m_responseDocument;
+    bool m_createdDocument;
+    RefPtr<Document> m_responseDocument;
 
     RefPtr<SharedBuffer> m_binaryResponseBuilder;
-    mutable RefPtr<ArrayBuffer> m_responseArrayBuffer;
+    RefPtr<ArrayBuffer> m_responseArrayBuffer;
 
     bool m_error;
 
@@ -249,7 +250,7 @@
 
     // An enum corresponding to the allowed string values for the responseType attribute.
     ResponseTypeCode m_responseTypeCode;
-    Timer<XMLHttpRequest> m_protectionTimer;
+    AsyncMethodRunner<XMLHttpRequest> m_dropProtectionRunner;
     RefPtr<SecurityOrigin> m_securityOrigin;
 };
 
diff --git a/Source/core/xml/XMLTreeViewer.cpp b/Source/core/xml/XMLTreeViewer.cpp
index d7a1f7b..287f32d 100644
--- a/Source/core/xml/XMLTreeViewer.cpp
+++ b/Source/core/xml/XMLTreeViewer.cpp
@@ -52,9 +52,9 @@
 {
     m_document->setIsViewSource(true);
     String scriptString(reinterpret_cast<const char*>(XMLViewer_js), sizeof(XMLViewer_js));
-    m_document->frame()->script()->executeScriptInMainWorld(scriptString, ScriptController::ExecuteScriptWhenScriptsDisabled);
+    m_document->frame()->script().executeScriptInMainWorld(scriptString, ScriptController::ExecuteScriptWhenScriptsDisabled);
     String noStyleMessage("This XML file does not appear to have any style information associated with it. The document tree is shown below.");
-    m_document->frame()->script()->executeScriptInMainWorld("prepareWebKitXMLViewer('" + noStyleMessage + "');", ScriptController::ExecuteScriptWhenScriptsDisabled);
+    m_document->frame()->script().executeScriptInMainWorld("prepareWebKitXMLViewer('" + noStyleMessage + "');", ScriptController::ExecuteScriptWhenScriptsDisabled);
 
     String cssString(reinterpret_cast<const char*>(XMLViewer_css), sizeof(XMLViewer_css));
     RefPtr<Text> text = m_document->createTextNode(cssString);
diff --git a/Source/core/xml/XMLTreeViewer.h b/Source/core/xml/XMLTreeViewer.h
index 73d4047..a9d0b0e 100644
--- a/Source/core/xml/XMLTreeViewer.h
+++ b/Source/core/xml/XMLTreeViewer.h
@@ -33,10 +33,9 @@
 
 class Document;
 
-class XMLTreeViewer {
+class XMLTreeViewer FINAL {
 public:
     explicit XMLTreeViewer(Document*);
-    virtual ~XMLTreeViewer() {};
 
     void transformDocumentToTreeView();
 
diff --git a/Source/core/xml/XPathResult.cpp b/Source/core/xml/XPathResult.cpp
index cf2eac8..99973d9 100644
--- a/Source/core/xml/XPathResult.cpp
+++ b/Source/core/xml/XPathResult.cpp
@@ -89,14 +89,14 @@
         case ANY_UNORDERED_NODE_TYPE:
         case FIRST_ORDERED_NODE_TYPE: // This is correct - singleNodeValue() will take care of ordering.
             if (!m_value.isNodeSet()) {
-                es.throwTypeError();
+                es.throwUninformativeAndGenericTypeError();
                 return;
             }
             m_resultType = type;
             break;
         case ORDERED_NODE_ITERATOR_TYPE:
             if (!m_value.isNodeSet()) {
-                es.throwTypeError();
+                es.throwUninformativeAndGenericTypeError();
                 return;
             }
             m_nodeSet.sort();
@@ -104,7 +104,7 @@
             break;
         case ORDERED_NODE_SNAPSHOT_TYPE:
             if (!m_value.isNodeSet()) {
-                es.throwTypeError();
+                es.throwUninformativeAndGenericTypeError();
                 return;
             }
             m_value.toNodeSet().sort();
@@ -121,7 +121,7 @@
 double XPathResult::numberValue(ExceptionState& es) const
 {
     if (resultType() != NUMBER_TYPE) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return 0.0;
     }
     return m_value.toNumber();
@@ -130,7 +130,7 @@
 String XPathResult::stringValue(ExceptionState& es) const
 {
     if (resultType() != STRING_TYPE) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return String();
     }
     return m_value.toString();
@@ -139,7 +139,7 @@
 bool XPathResult::booleanValue(ExceptionState& es) const
 {
     if (resultType() != BOOLEAN_TYPE) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return false;
     }
     return m_value.toBoolean();
@@ -148,7 +148,7 @@
 Node* XPathResult::singleNodeValue(ExceptionState& es) const
 {
     if (resultType() != ANY_UNORDERED_NODE_TYPE && resultType() != FIRST_ORDERED_NODE_TYPE) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return 0;
     }
 
@@ -171,7 +171,7 @@
 unsigned long XPathResult::snapshotLength(ExceptionState& es) const
 {
     if (resultType() != UNORDERED_NODE_SNAPSHOT_TYPE && resultType() != ORDERED_NODE_SNAPSHOT_TYPE) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return 0;
     }
 
@@ -181,7 +181,7 @@
 Node* XPathResult::iterateNext(ExceptionState& es)
 {
     if (resultType() != UNORDERED_NODE_ITERATOR_TYPE && resultType() != ORDERED_NODE_ITERATOR_TYPE) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return 0;
     }
 
@@ -203,7 +203,7 @@
 Node* XPathResult::snapshotItem(unsigned long index, ExceptionState& es)
 {
     if (resultType() != UNORDERED_NODE_SNAPSHOT_TYPE && resultType() != ORDERED_NODE_SNAPSHOT_TYPE) {
-        es.throwTypeError();
+        es.throwUninformativeAndGenericTypeError();
         return 0;
     }
 
diff --git a/Source/core/xml/XSLTProcessor.cpp b/Source/core/xml/XSLTProcessor.cpp
index f6418d9..ea47745 100644
--- a/Source/core/xml/XSLTProcessor.cpp
+++ b/Source/core/xml/XSLTProcessor.cpp
@@ -65,26 +65,29 @@
     String documentSource = sourceString;
 
     RefPtr<Document> result;
-    if (sourceMIMEType == "text/plain") {
-        result = Document::create(DocumentInit(sourceIsDocument ? ownerDocument->url() : KURL(), frame));
-        transformTextStringToXHTMLDocumentString(documentSource);
-    } else
-        result = DOMImplementation::createDocument(sourceMIMEType, frame, sourceIsDocument ? ownerDocument->url() : KURL(), false);
+    DocumentInit init(sourceIsDocument ? ownerDocument->url() : KURL(), frame);
 
-    // Before parsing, we need to save & detach the old document and get the new document
-    // in place. We have to do this only if we're rendering the result document.
+    bool forceXHTML = sourceMIMEType == "text/plain";
+    if (forceXHTML)
+        transformTextStringToXHTMLDocumentString(documentSource);
+
     if (frame) {
+        RefPtr<Document> oldDocument = frame->document();
+        result = frame->domWindow()->installNewDocument(sourceMIMEType, init, forceXHTML);
+
+        // Before parsing, we need to save & detach the old document and get the new document
+        // in place. We have to do this only if we're rendering the result document.
         if (FrameView* view = frame->view())
             view->clear();
 
-        if (Document* oldDocument = frame->document()) {
-            result->setTransformSourceDocument(oldDocument);
-            result->setSecurityOrigin(oldDocument->securityOrigin());
+        if (oldDocument) {
+            result->setTransformSourceDocument(oldDocument.get());
+            result->updateSecurityOrigin(oldDocument->securityOrigin());
             result->setCookieURL(oldDocument->cookieURL());
             result->contentSecurityPolicy()->copyStateFrom(oldDocument->contentSecurityPolicy());
         }
-
-        frame->domWindow()->setDocument(result);
+    } else {
+        result = DOMWindow::createDocument(sourceMIMEType, init, forceXHTML);
     }
 
     result->setEncoding(sourceEncoding.isEmpty() ? UTF8Encoding() : WTF::TextEncoding(sourceEncoding));
diff --git a/Source/core/xml/parser/XMLDocumentParser.cpp b/Source/core/xml/parser/XMLDocumentParser.cpp
index d2186da..5d6a1eb 100644
--- a/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -110,7 +110,7 @@
     if (!document->frame() || !document->frame()->page())
         return false;
 
-    if (document->frame()->tree()->parent())
+    if (document->frame()->tree().parent())
         return false; // This document is not in a top frame
 
     return true;
@@ -362,7 +362,7 @@
     if (isStopped())
         return;
 
-    if (document()->frame() && document()->frame()->script()->canExecuteScripts(NotAboutToExecuteScript))
+    if (document()->frame() && document()->frame()->script().canExecuteScripts(NotAboutToExecuteScript))
         ImageLoader::dispatchPendingBeforeLoadEvents();
 }
 
@@ -998,17 +998,16 @@
 
     m_currentNode->parserAppendChild(newElement.get());
 
-    const ContainerNode* currentNode = m_currentNode;
     if (newElement->hasTagName(HTMLNames::templateTag))
         pushCurrentNode(toHTMLTemplateElement(newElement.get())->content());
     else
         pushCurrentNode(newElement.get());
 
     if (isHTMLHtmlElement(newElement.get()))
-        toHTMLHtmlElement(newElement.get())->insertedByParser();
+        toHTMLHtmlElement(newElement)->insertedByParser();
 
     if (!m_parsingFragment && isFirstElement && document()->frame())
-        document()->frame()->loader()->dispatchDocumentElementAvailable();
+        document()->frame()->loader().dispatchDocumentElementAvailable();
 }
 
 void XMLDocumentParser::endElementNs()
@@ -1030,7 +1029,7 @@
     RefPtr<ContainerNode> n = m_currentNode;
     n->finishParsingChildren();
 
-    if (!scriptingContentIsAllowed(parserContentPolicy()) && n->isElementNode() && toScriptLoaderIfPossible(toElement(n.get()))) {
+    if (!scriptingContentIsAllowed(parserContentPolicy()) && n->isElementNode() && toScriptLoaderIfPossible(toElement(n))) {
         popCurrentNode();
         n->remove(IGNORE_EXCEPTION);
         return;
@@ -1041,7 +1040,7 @@
         return;
     }
 
-    Element* element = toElement(n.get());
+    Element* element = toElement(n);
 
     // The element's parent may have already been removed from document.
     // Parsing continues in this case, but scripts aren't executed.
diff --git a/Source/core/xml/parser/XMLParserInput.h b/Source/core/xml/parser/XMLParserInput.h
index 7404012..1d594eb 100644
--- a/Source/core/xml/parser/XMLParserInput.h
+++ b/Source/core/xml/parser/XMLParserInput.h
@@ -39,9 +39,9 @@
 public:
     explicit XMLParserInput(const String& source)
         : m_source(source)
+        , m_encoding(0)
         , m_data(0)
         , m_size(0)
-        , m_encoding(0)
     {
         if (m_source.isEmpty())
             return;