Merge from Chromium at DEPS revision 258528

This commit was generated by merge_to_master.py.

Change-Id: I28602a0bfd7a629ec7a60a73debd10637ad32fd4
diff --git a/Source/core/accessibility/AXMediaControls.cpp b/Source/core/accessibility/AXMediaControls.cpp
index ca7113e..7b7d52f 100644
--- a/Source/core/accessibility/AXMediaControls.cpp
+++ b/Source/core/accessibility/AXMediaControls.cpp
@@ -229,7 +229,7 @@
 
     MediaControlTimeDisplayElement* element = static_cast<MediaControlTimeDisplayElement*>(m_renderer->node());
 
-    return toParentMediaElement(element)->isVideo();
+    return isHTMLVideoElement(toParentMediaElement(element));
 }
 
 bool AXMediaControlsContainer::computeAccessibilityIsIgnored() const
diff --git a/Source/core/accessibility/AXNodeObject.cpp b/Source/core/accessibility/AXNodeObject.cpp
index fa59758..df7e964 100644
--- a/Source/core/accessibility/AXNodeObject.cpp
+++ b/Source/core/accessibility/AXNodeObject.cpp
@@ -1620,7 +1620,7 @@
 
     Node* owner = document->ownerElement();
     if (owner) {
-        if (isHTMLFrameElement(*owner) || isHTMLIFrameElement(*owner)) {
+        if (isHTMLFrameElementBase(*owner)) {
             const AtomicString& title = toElement(owner)->getAttribute(titleAttr);
             if (!title.isEmpty())
                 return title;
diff --git a/Source/core/animation/ActiveAnimations.cpp b/Source/core/animation/ActiveAnimations.cpp
index c0c06e9..ec48cb6 100644
--- a/Source/core/animation/ActiveAnimations.cpp
+++ b/Source/core/animation/ActiveAnimations.cpp
@@ -77,7 +77,16 @@
 
 bool ActiveAnimations::hasActiveAnimations(CSSPropertyID property) const
 {
-    return m_defaultStack.affects(property);
+    for (AnimationPlayerSet::const_iterator it = m_players.begin(); it != players().end(); ++it) {
+        const AnimationPlayer& player = *it->key;
+        ASSERT(player.source());
+        // FIXME: Needs to consider AnimationGroup once added.
+        ASSERT(player.source()->isAnimation());
+        const Animation& animation = *toAnimation(player.source());
+        if (animation.isCurrent() && animation.affects(property))
+            return true;
+    }
+    return false;
 }
 
 bool ActiveAnimations::hasActiveAnimationsOnCompositor(CSSPropertyID property) const
diff --git a/Source/core/animation/ActiveAnimations.h b/Source/core/animation/ActiveAnimations.h
index 0bbc264..67259ab 100644
--- a/Source/core/animation/ActiveAnimations.h
+++ b/Source/core/animation/ActiveAnimations.h
@@ -70,6 +70,8 @@
 
     bool isEmpty() const { return m_defaultStack.isEmpty() && m_cssAnimations.isEmpty(); }
 
+    // FIXME: This and most of this class needs to be renamed to consider 'current'
+    // rather than 'active' animations.
     bool hasActiveAnimations(CSSPropertyID) const;
     bool hasActiveAnimationsOnCompositor(CSSPropertyID) const;
     void cancelAnimationOnCompositor();
diff --git a/Source/core/animation/AnimatableImage.cpp b/Source/core/animation/AnimatableImage.cpp
index 49df97f..d67c9b4 100644
--- a/Source/core/animation/AnimatableImage.cpp
+++ b/Source/core/animation/AnimatableImage.cpp
@@ -40,48 +40,24 @@
 // FIXME: Once cross-fade works on generated image types, remove this method.
 bool AnimatableImage::usesDefaultInterpolationWith(const AnimatableValue* value) const
 {
-    RefPtrWillBeRawPtr<CSSValue> fromValue = toCSSValue();
-    if (fromValue->isImageGeneratorValue())
+    if (!m_value->isImageValue())
         return true;
-    if (!fromValue->isImageValue() && !m_image->isImageResource())
-        return true;
-    const AnimatableImage* image = toAnimatableImage(value);
-    RefPtrWillBeRawPtr<CSSValue> toValue = image->toCSSValue();
-    if (toValue->isImageGeneratorValue())
-        return true;
-    if (!toValue->isImageValue() && !image->m_image->isImageResource())
+    if (!toAnimatableImage(value)->toCSSValue()->isImageValue())
         return true;
     return false;
 }
 
 PassRefPtr<AnimatableValue> AnimatableImage::interpolateTo(const AnimatableValue* value, double fraction) const
 {
-    if (fraction <= 0 || fraction >= 1)
+    if (fraction <= 0 || fraction >= 1 || usesDefaultInterpolationWith(value))
         return defaultInterpolateTo(this, value, fraction);
-    RefPtrWillBeRawPtr<CSSValue> fromValue = toCSSValue();
-    // FIXME: Once cross-fade works on generated image types, remove this check.
-    if (fromValue->isImageGeneratorValue())
-        return defaultInterpolateTo(this, value, fraction);
-    if (!fromValue->isImageValue() && !fromValue->isImageGeneratorValue()) {
-        if (!m_image->isImageResource())
-            return defaultInterpolateTo(this, value, fraction);
-        ImageResource* resource = static_cast<ImageResource*>(m_image->data());
-        fromValue = CSSImageValue::create(resource->url(), m_image.get());
-    }
-    const AnimatableImage* image = toAnimatableImage(value);
-    RefPtrWillBeRawPtr<CSSValue> toValue = image->toCSSValue();
-    // FIXME: Once cross-fade works on generated image types, remove this check.
-    if (toValue->isImageGeneratorValue())
-        return defaultInterpolateTo(this, value, fraction);
-    if (!toValue->isImageValue() && !toValue->isImageGeneratorValue()) {
-        if (!image->m_image->isImageResource())
-            return defaultInterpolateTo(this, value, fraction);
-        ImageResource* resource = static_cast<ImageResource*>(image->m_image->data());
-        toValue = CSSImageValue::create(resource->url(), image->m_image.get());
-    }
+
+    CSSValue* fromValue = toCSSValue();
+    CSSValue* toValue = toAnimatableImage(value)->toCSSValue();
+
     RefPtrWillBeRawPtr<CSSCrossfadeValue> crossfadeValue = CSSCrossfadeValue::create(fromValue, toValue);
     crossfadeValue->setPercentage(CSSPrimitiveValue::create(fraction, CSSPrimitiveValue::CSS_NUMBER));
-    return create(StyleGeneratedImage::create(crossfadeValue.get()).get());
+    return create(crossfadeValue);
 }
 
 PassRefPtr<AnimatableValue> AnimatableImage::addWith(const AnimatableValue* value) const
@@ -92,7 +68,7 @@
 
 bool AnimatableImage::equalTo(const AnimatableValue* value) const
 {
-    return StyleImage::imagesEquivalent(m_image.get(), toAnimatableImage(value)->m_image.get());
+    return m_value->equals(*toAnimatableImage(value)->m_value.get());
 }
 
 }
diff --git a/Source/core/animation/AnimatableImage.h b/Source/core/animation/AnimatableImage.h
index 1c88d4c..eaf39d6 100644
--- a/Source/core/animation/AnimatableImage.h
+++ b/Source/core/animation/AnimatableImage.h
@@ -40,12 +40,11 @@
 class AnimatableImage FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableImage() { }
-    static PassRefPtr<AnimatableImage> create(StyleImage* image)
+    static PassRefPtr<AnimatableImage> create(const StyleImage& image)
     {
-        return adoptRef(new AnimatableImage(image));
+        return create(image.cssValue());
     }
-    PassRefPtrWillBeRawPtr<CSSValue> toCSSValue() const { return m_image->cssValue(); }
-    StyleImage* toStyleImage() const { return m_image.get(); }
+    CSSValue* toCSSValue() const { return m_value.get(); }
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
@@ -53,15 +52,18 @@
     virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
-    AnimatableImage(StyleImage* image)
-        : m_image(image)
+    static PassRefPtr<AnimatableImage> create(PassRefPtr<CSSValue> value)
     {
-        ASSERT(m_image);
+        return adoptRef(new AnimatableImage(value));
+    }
+    AnimatableImage(PassRefPtr<CSSValue> value)
+        : m_value(value)
+    {
     }
     virtual AnimatableType type() const OVERRIDE { return TypeImage; }
     virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
 
-    const RefPtr<StyleImage> m_image;
+    const RefPtr<CSSValue> m_value;
 };
 
 DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableImage, isImage());
diff --git a/Source/core/animation/AnimatableValue.h b/Source/core/animation/AnimatableValue.h
index de043f5..58ce56e 100644
--- a/Source/core/animation/AnimatableValue.h
+++ b/Source/core/animation/AnimatableValue.h
@@ -31,13 +31,12 @@
 #ifndef AnimatableValue_h
 #define AnimatableValue_h
 
-#include "core/animation/AnimationEffect.h"
 #include "core/css/CSSValue.h"
 #include "wtf/RefCounted.h"
 
 namespace WebCore {
 
-class AnimatableValue : public AnimationEffect::CompositableValue {
+class AnimatableValue : public RefCounted<AnimatableValue> {
 public:
     virtual ~AnimatableValue() { }
 
@@ -61,9 +60,6 @@
         return equals(&value);
     }
 
-    virtual bool dependsOnUnderlyingValue() const OVERRIDE FINAL { return false; }
-    virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue*) const OVERRIDE FINAL { return takeConstRef(this); }
-
     bool isClipPathOperation() const { return type() == TypeClipPathOperation; }
     bool isColor() const { return type() == TypeColor; }
     bool isDouble() const { return type() == TypeDouble; }
diff --git a/Source/core/animation/AnimatableValueTestHelper.cpp b/Source/core/animation/AnimatableValueTestHelper.cpp
index d43a914..4966358 100644
--- a/Source/core/animation/AnimatableValueTestHelper.cpp
+++ b/Source/core/animation/AnimatableValueTestHelper.cpp
@@ -60,7 +60,7 @@
 
 void PrintTo(const AnimatableImage& animImage, ::std::ostream* os)
 {
-    PrintTo(*(animImage.toCSSValue().get()), os, "AnimatableImage");
+    PrintTo(*(animImage.toCSSValue()), os, "AnimatableImage");
 }
 
 void PrintTo(const AnimatableLength& animLength, ::std::ostream* os)
diff --git a/Source/core/animation/Animation.cpp b/Source/core/animation/Animation.cpp
index b5fde0c..b724412 100644
--- a/Source/core/animation/Animation.cpp
+++ b/Source/core/animation/Animation.cpp
@@ -37,6 +37,7 @@
 #include "core/animation/AnimationPlayer.h"
 #include "core/animation/CompositorAnimations.h"
 #include "core/animation/DocumentTimeline.h"
+#include "core/animation/Interpolation.h"
 #include "core/animation/KeyframeEffectModel.h"
 #include "core/dom/Element.h"
 #include "core/rendering/RenderLayer.h"
@@ -121,7 +122,7 @@
     double iteration = currentIteration();
     ASSERT(iteration >= 0);
     // FIXME: Handle iteration values which overflow int.
-    m_compositableValues = m_effect->sample(static_cast<int>(iteration), timeFraction());
+    m_activeInterpolations = m_effect->sample(static_cast<int>(iteration), timeFraction());
     if (player())
         m_target->setNeedsAnimationStyleRecalc();
 }
@@ -141,7 +142,7 @@
     }
 
     m_activeInAnimationStack = false;
-    m_compositableValues.clear();
+    m_activeInterpolations.clear();
     m_target->setNeedsAnimationStyleRecalc();
     invalidate();
 }
diff --git a/Source/core/animation/Animation.h b/Source/core/animation/Animation.h
index abc1be3..a8f6200 100644
--- a/Source/core/animation/Animation.h
+++ b/Source/core/animation/Animation.h
@@ -71,10 +71,10 @@
 
     virtual bool isAnimation() const OVERRIDE { return true; }
 
-    const AnimationEffect::CompositableValueList* compositableValues() const
+    const Vector<RefPtr<Interpolation> >& activeInterpolations() const
     {
-        ASSERT(m_compositableValues);
-        return m_compositableValues.get();
+        ASSERT(m_activeInterpolations);
+        return *m_activeInterpolations;
     }
 
     bool affects(CSSPropertyID) const;
@@ -107,7 +107,7 @@
     RefPtrWillBePersistent<AnimationEffect> m_effect;
 
     bool m_activeInAnimationStack;
-    OwnPtr<AnimationEffect::CompositableValueList> m_compositableValues;
+    OwnPtr<Vector<RefPtr<Interpolation> > > m_activeInterpolations;
 
     Priority m_priority;
 
diff --git a/Source/core/animation/AnimationEffect.h b/Source/core/animation/AnimationEffect.h
index 8438c2c..e2304c2 100644
--- a/Source/core/animation/AnimationEffect.h
+++ b/Source/core/animation/AnimationEffect.h
@@ -40,6 +40,7 @@
 namespace WebCore {
 
 class AnimatableValue;
+class Interpolation;
 
 class AnimationEffect : public RefCountedWillBeGarbageCollectedFinalized<AnimationEffect> {
 public:
@@ -47,20 +48,9 @@
         CompositeReplace,
         CompositeAdd,
     };
-    // Encapsulates the value which results from applying a set of composition operations onto an
-    // underlying value. It is used to represent the output of the effect phase of the Web
-    // Animations model.
-    class CompositableValue : public RefCounted<CompositableValue> {
-    public:
-        virtual ~CompositableValue() { }
-        virtual bool dependsOnUnderlyingValue() const = 0;
-        virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue*) const = 0;
-    };
 
     virtual ~AnimationEffect() { }
-    typedef HashMap<CSSPropertyID, RefPtr<CompositableValue> > CompositableValueMap;
-    typedef Vector<std::pair<CSSPropertyID, RefPtr<CompositableValue> > > CompositableValueList;
-    virtual PassOwnPtr<CompositableValueList> sample(int iteration, double fraction) const = 0;
+    virtual PassOwnPtr<Vector<RefPtr<Interpolation> > > sample(int iteration, double fraction) const = 0;
 
     virtual bool affects(CSSPropertyID) { return false; };
     virtual bool isKeyframeEffectModel() const { return false; }
diff --git a/Source/core/animation/AnimationPlayer.h b/Source/core/animation/AnimationPlayer.h
index 371fc62..afe87ad 100644
--- a/Source/core/animation/AnimationPlayer.h
+++ b/Source/core/animation/AnimationPlayer.h
@@ -77,6 +77,7 @@
     double startTime() const { return m_startTime; }
     void setStartTime(double);
 
+    const TimedItem* source() const { return m_content.get(); }
     TimedItem* source() { return m_content.get(); }
     TimedItem* source(bool& isNull) { isNull = !m_content; return m_content.get(); }
     void setSource(TimedItem*);
diff --git a/Source/core/animation/AnimationStack.cpp b/Source/core/animation/AnimationStack.cpp
index 17f3852..6c83afb 100644
--- a/Source/core/animation/AnimationStack.cpp
+++ b/Source/core/animation/AnimationStack.cpp
@@ -30,6 +30,7 @@
 
 #include "config.h"
 #include "core/animation/AnimationStack.h"
+#include "core/animation/Interpolation.h"
 
 #include "core/animation/css/CSSAnimations.h"
 
@@ -37,12 +38,13 @@
 
 namespace {
 
-void copyToCompositableValueMap(const AnimationEffect::CompositableValueList* source, AnimationEffect::CompositableValueMap& target)
+void copyToActiveInterpolationMap(const Vector<RefPtr<WebCore::Interpolation> >& source, HashMap<CSSPropertyID, RefPtr<WebCore::Interpolation> >& target)
 {
-    if (!source)
-        return;
-    for (AnimationEffect::CompositableValueList::const_iterator iter = source->begin(); iter != source->end(); ++iter)
-        target.set(iter->first, iter->second);
+    for (Vector<RefPtr<WebCore::Interpolation> >::const_iterator iter = source.begin(); iter != source.end(); ++iter) {
+        RefPtr<WebCore::Interpolation> interpolation = *iter;
+        WebCore::StyleInterpolation *styleInterpolation = toStyleInterpolation(interpolation.get());
+        target.set(styleInterpolation->id(), styleInterpolation);
+    }
 }
 
 } // namespace
@@ -65,9 +67,9 @@
     return false;
 }
 
-AnimationEffect::CompositableValueMap AnimationStack::compositableValues(const AnimationStack* animationStack, const Vector<InertAnimation*>* newAnimations, const HashSet<const AnimationPlayer*>* cancelledAnimationPlayers, Animation::Priority priority)
+HashMap<CSSPropertyID, RefPtr<Interpolation> > AnimationStack::activeInterpolations(const AnimationStack* animationStack, const Vector<InertAnimation*>* newAnimations, const HashSet<const AnimationPlayer*>* cancelledAnimationPlayers, Animation::Priority priority)
 {
-    AnimationEffect::CompositableValueMap result;
+    HashMap<CSSPropertyID, RefPtr<Interpolation> > result;
 
     if (animationStack) {
         const Vector<Animation*>& animations = animationStack->m_activeAnimations;
@@ -77,13 +79,17 @@
                 continue;
             if (cancelledAnimationPlayers && cancelledAnimationPlayers->contains(animation->player()))
                 continue;
-            copyToCompositableValueMap(animation->compositableValues(), result);
+            copyToActiveInterpolationMap(animation->activeInterpolations(), result);
         }
     }
 
     if (newAnimations) {
-        for (size_t i = 0; i < newAnimations->size(); ++i)
-            copyToCompositableValueMap(newAnimations->at(i)->sample().get(), result);
+        for (size_t i = 0; i < newAnimations->size(); ++i) {
+            OwnPtr<Vector<RefPtr<Interpolation> > > sample = newAnimations->at(i)->sample();
+            if (sample) {
+                copyToActiveInterpolationMap(*sample, result);
+            }
+        }
     }
 
     return result;
diff --git a/Source/core/animation/AnimationStack.h b/Source/core/animation/AnimationStack.h
index f8fc1de..8507f0c 100644
--- a/Source/core/animation/AnimationStack.h
+++ b/Source/core/animation/AnimationStack.h
@@ -53,7 +53,7 @@
     bool isEmpty() const { return m_activeAnimations.isEmpty(); }
     bool affects(CSSPropertyID) const;
     bool hasActiveAnimationsOnCompositor(CSSPropertyID) const;
-    static AnimationEffect::CompositableValueMap compositableValues(const AnimationStack*, const Vector<InertAnimation*>* newAnimations, const HashSet<const AnimationPlayer*>* cancelledAnimationPlayers, Animation::Priority);
+    static HashMap<CSSPropertyID, RefPtr<Interpolation> > activeInterpolations(const AnimationStack*, const Vector<InertAnimation*>* newAnimations, const HashSet<const AnimationPlayer*>* cancelledAnimationPlayers, Animation::Priority);
 
 private:
     Vector<Animation*> m_activeAnimations;
diff --git a/Source/core/animation/CompositorAnimations.cpp b/Source/core/animation/CompositorAnimations.cpp
index 1807f38..4b45f2a 100644
--- a/Source/core/animation/CompositorAnimations.cpp
+++ b/Source/core/animation/CompositorAnimations.cpp
@@ -257,7 +257,11 @@
 void CompositorAnimations::cancelAnimationOnCompositor(const Element& element, int id)
 {
     if (!canStartAnimationOnCompositor(element)) {
-        ASSERT_NOT_REACHED();
+        // When an element is being detached, we cancel any associated
+        // AnimationPlayers for CSS animations. But by the time we get
+        // here the mapping will have been removed.
+        // FIXME: Defer remove/pause operations until after the
+        // compositing update.
         return;
     }
     toRenderBoxModelObject(element.renderer())->layer()->compositedLayerMapping()->mainGraphicsLayer()->removeAnimation(id);
@@ -401,13 +405,12 @@
             }
         }
 
-        ASSERT(!keyframes[i]->value()->dependsOnUnderlyingValue());
-        RefPtr<AnimatableValue> value = keyframes[i]->value()->compositeOnto(0);
+        const AnimatableValue* value = keyframes[i]->value();
 
         switch (curve.type()) {
         case blink::WebAnimationCurve::AnimationCurveTypeFilter: {
             OwnPtr<blink::WebFilterOperations> ops = adoptPtr(blink::Platform::current()->compositorSupport()->createFilterOperations());
-            bool converted = toWebFilterOperations(toAnimatableFilterOperations(value.get())->operations(), ops.get());
+            bool converted = toWebFilterOperations(toAnimatableFilterOperations(value)->operations(), ops.get());
             ASSERT_UNUSED(converted, converted);
 
             blink::WebFilterKeyframe filterKeyframe(keyframes[i]->offset(), ops.release());
@@ -416,14 +419,14 @@
             break;
         }
         case blink::WebAnimationCurve::AnimationCurveTypeFloat: {
-            blink::WebFloatKeyframe floatKeyframe(keyframes[i]->offset(), toAnimatableDouble(value.get())->toDouble());
+            blink::WebFloatKeyframe floatKeyframe(keyframes[i]->offset(), toAnimatableDouble(value)->toDouble());
             blink::WebFloatAnimationCurve* floatCurve = static_cast<blink::WebFloatAnimationCurve*>(&curve);
             addKeyframeWithTimingFunction(*floatCurve, floatKeyframe, keyframeTimingFunction);
             break;
         }
         case blink::WebAnimationCurve::AnimationCurveTypeTransform: {
             OwnPtr<blink::WebTransformOperations> ops = adoptPtr(blink::Platform::current()->compositorSupport()->createTransformOperations());
-            toWebTransformOperations(toAnimatableTransform(value.get())->transformOperations(), ops.get());
+            toWebTransformOperations(toAnimatableTransform(value)->transformOperations(), ops.get());
 
             blink::WebTransformKeyframe transformKeyframe(keyframes[i]->offset(), ops.release());
             blink::WebTransformAnimationCurve* transformCurve = static_cast<blink::WebTransformAnimationCurve*>(&curve);
diff --git a/Source/core/animation/DocumentTimelineTest.cpp b/Source/core/animation/DocumentTimelineTest.cpp
index ed90062..8be0696 100644
--- a/Source/core/animation/DocumentTimelineTest.cpp
+++ b/Source/core/animation/DocumentTimelineTest.cpp
@@ -159,7 +159,7 @@
     updateClockAndService(0);
     EXPECT_FLOAT_EQ(0, timeline->currentTime());
     EXPECT_TRUE(anim->isInEffect());
-    EXPECT_TRUE(anim->compositableValues()->isEmpty());
+    EXPECT_TRUE(anim->activeInterpolations().isEmpty());
 
     platformTiming->expectNoMoreActions();
     updateClockAndService(100);
diff --git a/Source/core/animation/EffectInput.cpp b/Source/core/animation/EffectInput.cpp
index 2f87c28..0d132da 100644
--- a/Source/core/animation/EffectInput.cpp
+++ b/Source/core/animation/EffectInput.cpp
@@ -55,12 +55,14 @@
     if (!unsafe && !checkDocumentAndRenderer(element))
         return nullptr;
 
+    StyleSheetContents* styleSheetContents = element->document().elementSheet().contents();
+
     // FIXME: Move this code into KeyframeEffectModel, it will be used by the IDL constructor for that class.
     KeyframeEffectModel::KeyframeVector keyframes;
-    Vector<RefPtr<MutableStylePropertySet> > propertySetVector;
+    WillBeHeapVector<RefPtrWillBeMember<MutableStylePropertySet> > propertySetVector;
 
     for (size_t i = 0; i < keyframeDictionaryVector.size(); ++i) {
-        RefPtr<MutableStylePropertySet> propertySet = MutableStylePropertySet::create();
+        RefPtrWillBeRawPtr<MutableStylePropertySet> propertySet = MutableStylePropertySet::create();
         propertySetVector.append(propertySet);
 
         RefPtrWillBeRawPtr<Keyframe> keyframe = Keyframe::create();
@@ -99,7 +101,7 @@
 
             String value;
             keyframeDictionaryVector[i].get(property, value);
-            propertySet->setProperty(id, value);
+            propertySet->setProperty(id, value, false, styleSheetContents);
         }
     }
 
diff --git a/Source/core/animation/InertAnimation.cpp b/Source/core/animation/InertAnimation.cpp
index 18a922b..a82b6ca 100644
--- a/Source/core/animation/InertAnimation.cpp
+++ b/Source/core/animation/InertAnimation.cpp
@@ -30,6 +30,7 @@
 
 #include "config.h"
 #include "core/animation/InertAnimation.h"
+#include "core/animation/Interpolation.h"
 
 namespace WebCore {
 
@@ -45,7 +46,7 @@
 {
 }
 
-PassOwnPtr<AnimationEffect::CompositableValueList> InertAnimation::sample()
+PassOwnPtr<Vector<RefPtr<Interpolation> > > InertAnimation::sample()
 {
     updateInheritedTime(0);
     if (!isInEffect())
diff --git a/Source/core/animation/InertAnimation.h b/Source/core/animation/InertAnimation.h
index 49a91a6..330fcc0 100644
--- a/Source/core/animation/InertAnimation.h
+++ b/Source/core/animation/InertAnimation.h
@@ -41,7 +41,7 @@
 
 public:
     static PassRefPtr<InertAnimation> create(PassRefPtrWillBeRawPtr<AnimationEffect>, const Timing&, bool paused);
-    PassOwnPtr<AnimationEffect::CompositableValueList> sample();
+    PassOwnPtr<Vector<RefPtr<Interpolation> > > sample();
     AnimationEffect* effect() const { return m_effect.get(); }
     bool paused() const { return m_paused; }
 
diff --git a/Source/core/animation/Interpolation.cpp b/Source/core/animation/Interpolation.cpp
index b552e0f..192fd24 100644
--- a/Source/core/animation/Interpolation.cpp
+++ b/Source/core/animation/Interpolation.cpp
@@ -5,6 +5,9 @@
 #include "config.h"
 #include "core/animation/Interpolation.h"
 
+#include "core/css/resolver/AnimatedStyleBuilder.h"
+#include "core/css/resolver/StyleResolverState.h"
+
 namespace WebCore {
 
 namespace {
@@ -15,6 +18,8 @@
         return end->isNumber();
     if (start->isBool())
         return end->isBool();
+    if (start->isAnimatableValue())
+        return end->isAnimatableValue();
     if (!(start->isList() && end->isList()))
         return false;
     const InterpolableList* startList = toInterpolableList(start);
@@ -49,4 +54,10 @@
     }
 }
 
+void LegacyStyleInterpolation::apply(StyleResolverState& state) const
+{
+    AnimatableValue* value = currentValue();
+    AnimatedStyleBuilder::applyProperty(m_id, state, value);
+}
+
 }
diff --git a/Source/core/animation/Interpolation.h b/Source/core/animation/Interpolation.h
index 206dab0..fe8dd98 100644
--- a/Source/core/animation/Interpolation.h
+++ b/Source/core/animation/Interpolation.h
@@ -5,12 +5,14 @@
 #ifndef Interpolation_h
 #define Interpolation_h
 
+#include "CSSPropertyNames.h"
 #include "core/animation/InterpolableValue.h"
-#include "core/css/resolver/StyleResolverState.h"
 #include "wtf/RefCounted.h"
 
 namespace WebCore {
 
+class StyleResolverState;
+
 class Interpolation : public RefCounted<Interpolation> {
 public:
     static PassRefPtr<Interpolation> create(PassOwnPtr<InterpolableValue> start, PassOwnPtr<InterpolableValue> end)
@@ -20,6 +22,12 @@
 
     void interpolate(int iteration, double fraction) const;
 
+    virtual bool isStyleInterpolation() const { return false; }
+    virtual bool isLegacyStyleInterpolation() const { return false; }
+
+    virtual ~Interpolation()
+    { }
+
 protected:
     const OwnPtr<InterpolableValue> m_start;
     const OwnPtr<InterpolableValue> m_end;
@@ -35,6 +43,7 @@
 
     friend class AnimationInterpolableValueTest;
     friend class AnimationInterpolationEffectTest;
+
 };
 
 class StyleInterpolation : public Interpolation {
@@ -45,7 +54,11 @@
     // (1) a CSSValue (and applied via StyleBuilder::applyProperty)
     // (2) an AnimatableValue (and applied via // AnimatedStyleBuilder::applyProperty)
     // (3) a custom value that is inserted directly into the StyleResolverState.
-    virtual void apply(StyleResolverState&) = 0;
+    virtual void apply(StyleResolverState&) const = 0;
+
+    virtual bool isStyleInterpolation() const OVERRIDE FINAL { return true; }
+
+    CSSPropertyID id() const { return m_id; }
 
 protected:
     CSSPropertyID m_id;
@@ -56,5 +69,30 @@
     { }
 };
 
+class LegacyStyleInterpolation : public StyleInterpolation {
+public:
+    static PassRefPtr<LegacyStyleInterpolation> create(PassRefPtr<AnimatableValue> start, PassRefPtr<AnimatableValue> end, CSSPropertyID id)
+    {
+        return adoptRef(new LegacyStyleInterpolation(InterpolableAnimatableValue::create(start), InterpolableAnimatableValue::create(end), id));
+    }
+
+    virtual void apply(StyleResolverState&) const;
+
+    virtual bool isLegacyStyleInterpolation() const OVERRIDE FINAL { return true; }
+    AnimatableValue* currentValue() const
+    {
+        InterpolableAnimatableValue *value = static_cast<InterpolableAnimatableValue *>(m_cachedValue.get());
+        return value->value();
+    }
+
+private:
+    LegacyStyleInterpolation(PassOwnPtr<InterpolableValue> start, PassOwnPtr<InterpolableValue> end, CSSPropertyID id)
+        : StyleInterpolation(start, end, id)
+    { }
+};
+
+DEFINE_TYPE_CASTS(StyleInterpolation, Interpolation, value, value->isStyleInterpolation(), value.isStyleInterpolation());
+DEFINE_TYPE_CASTS(LegacyStyleInterpolation, Interpolation, value, value->isLegacyStyleInterpolation(), value.isLegacyStyleInterpolation());
+
 }
 #endif
diff --git a/Source/core/animation/InterpolationEffect.h b/Source/core/animation/InterpolationEffect.h
index ace3aae..5dfcc94 100644
--- a/Source/core/animation/InterpolationEffect.h
+++ b/Source/core/animation/InterpolationEffect.h
@@ -10,7 +10,6 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefCounted.h"
 
-
 namespace WebCore {
 
 class InterpolationEffect : public RefCounted<InterpolationEffect> {
diff --git a/Source/core/animation/KeyframeEffectModel.cpp b/Source/core/animation/KeyframeEffectModel.cpp
index aec264d..b6f813f 100644
--- a/Source/core/animation/KeyframeEffectModel.cpp
+++ b/Source/core/animation/KeyframeEffectModel.cpp
@@ -34,64 +34,6 @@
 #include "core/animation/TimedItem.h"
 #include "wtf/text/StringHash.h"
 
-namespace {
-
-using namespace WebCore;
-
-class AddCompositableValue FINAL : public AnimationEffect::CompositableValue {
-public:
-    static PassRefPtr<AddCompositableValue> create(const AnimatableValue* value)
-    {
-        return adoptRef(new AddCompositableValue(value));
-    }
-    virtual bool dependsOnUnderlyingValue() const OVERRIDE
-    {
-        return true;
-    }
-    virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const OVERRIDE
-    {
-        return AnimatableValue::add(underlyingValue, m_value.get());
-    }
-private:
-    AddCompositableValue(const AnimatableValue* value)
-        : m_value(const_cast<AnimatableValue*>(value))
-    {
-    }
-    RefPtr<AnimatableValue> m_value;
-};
-
-class BlendedCompositableValue FINAL : public AnimationEffect::CompositableValue {
-public:
-    static PassRefPtr<BlendedCompositableValue> create(const AnimationEffect::CompositableValue* before, const AnimationEffect::CompositableValue* after, double fraction)
-    {
-        return adoptRef(new BlendedCompositableValue(before, after, fraction));
-    }
-    virtual bool dependsOnUnderlyingValue() const OVERRIDE
-    {
-        return m_dependsOnUnderlyingValue;
-    }
-    virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const OVERRIDE
-    {
-        return AnimatableValue::interpolate(m_before->compositeOnto(underlyingValue).get(), m_after->compositeOnto(underlyingValue).get(), m_fraction);
-    }
-private:
-    BlendedCompositableValue(const AnimationEffect::CompositableValue* before, const AnimationEffect::CompositableValue* after, double fraction)
-        : m_before(const_cast<AnimationEffect::CompositableValue*>(before))
-        , m_after(const_cast<AnimationEffect::CompositableValue*>(after))
-        , m_fraction(fraction)
-        , m_dependsOnUnderlyingValue(before->dependsOnUnderlyingValue() || after->dependsOnUnderlyingValue())
-    { }
-    RefPtr<AnimationEffect::CompositableValue> m_before;
-    RefPtr<AnimationEffect::CompositableValue> m_after;
-    double m_fraction;
-    bool m_dependsOnUnderlyingValue;
-};
-
-const double accuracyForKeyframeEasing = 0.0000001;
-
-} // namespace
-
-
 namespace WebCore {
 
 Keyframe::Keyframe()
@@ -170,15 +112,14 @@
     return result;
 }
 
-PassOwnPtr<AnimationEffect::CompositableValueList> KeyframeEffectModel::sample(int iteration, double fraction) const
+PassOwnPtr<Vector<RefPtr<Interpolation> > > KeyframeEffectModel::sample(int iteration, double fraction) const
 {
     ASSERT(iteration >= 0);
     ASSERT(!isNull(fraction));
-    const_cast<KeyframeEffectModel*>(this)->ensureKeyframeGroups();
-    OwnPtr<CompositableValueList> map = adoptPtr(new CompositableValueList());
-    for (KeyframeGroupMap::const_iterator iter = m_keyframeGroups->begin(); iter != m_keyframeGroups->end(); ++iter)
-        map->append(std::make_pair(iter->key, iter->value->sample(iteration, fraction)));
-    return map.release();
+    ensureKeyframeGroups();
+    ensureInterpolationEffect();
+
+    return m_interpolationEffect->getActiveInterpolations(fraction);
 }
 
 KeyframeEffectModel::KeyframeVector KeyframeEffectModel::normalizedKeyframes(const KeyframeVector& keyframes)
@@ -276,17 +217,41 @@
     }
 }
 
+void KeyframeEffectModel::ensureInterpolationEffect() const
+{
+    if (m_interpolationEffect)
+        return;
+    m_interpolationEffect = InterpolationEffect::create();
+
+    for (KeyframeGroupMap::const_iterator iter = m_keyframeGroups->begin(); iter != m_keyframeGroups->end(); ++iter) {
+        const PropertySpecificKeyframeVector& keyframes = iter->value->keyframes();
+        const AnimatableValue* start;
+        const AnimatableValue* end = keyframes[0]->value();
+        for (size_t i = 0; i < keyframes.size() - 1; i++) {
+            start = end;
+            end = keyframes[i + 1]->value();
+            double applyFrom = i ? keyframes[i]->offset() : (-std::numeric_limits<double>::infinity());
+            double applyTo = i == keyframes.size() - 2 ? std::numeric_limits<double>::infinity() : keyframes[i + 1]->offset();
+            if (applyTo == 1)
+                applyTo = std::numeric_limits<double>::infinity();
+            m_interpolationEffect->addInterpolation(
+                LegacyStyleInterpolation::create(
+                    AnimatableValue::takeConstRef(start),
+                    AnimatableValue::takeConstRef(end), iter->key),
+                keyframes[i]->easing(), keyframes[i]->offset(), keyframes[i + 1]->offset(), applyFrom, applyTo);
+        }
+    }
+}
 
 KeyframeEffectModel::PropertySpecificKeyframe::PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, const AnimatableValue* value, CompositeOperation composite)
     : m_offset(offset)
     , m_easing(easing)
-    , m_value(composite == AnimationEffect::CompositeReplace ?
-        AnimatableValue::takeConstRef(value) :
-        static_cast<PassRefPtr<CompositableValue> >(AddCompositableValue::create(value)))
 {
+    ASSERT(composite == AnimationEffect::CompositeReplace);
+    m_value = AnimatableValue::takeConstRef(value);
 }
 
-KeyframeEffectModel::PropertySpecificKeyframe::PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, PassRefPtr<CompositableValue> value)
+KeyframeEffectModel::PropertySpecificKeyframe::PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, PassRefPtr<AnimatableValue> value)
     : m_offset(offset)
     , m_easing(easing)
     , m_value(value)
@@ -296,7 +261,7 @@
 
 PassOwnPtr<KeyframeEffectModel::PropertySpecificKeyframe> KeyframeEffectModel::PropertySpecificKeyframe::cloneWithOffset(double offset) const
 {
-    return adoptPtr(new PropertySpecificKeyframe(offset, m_easing, PassRefPtr<CompositableValue>(m_value)));
+    return adoptPtr(new PropertySpecificKeyframe(offset, m_easing, m_value));
 }
 
 
@@ -345,58 +310,6 @@
         m_keyframes.insert(0, adoptPtr(new PropertySpecificKeyframe(0.0, nullptr, AnimatableValue::neutralValue(), CompositeAdd)));
 }
 
-PassRefPtr<AnimationEffect::CompositableValue> KeyframeEffectModel::PropertySpecificKeyframeGroup::sample(int iteration, double offset) const
-{
-    // FIXME: Implement accumulation.
-    ASSERT_UNUSED(iteration, iteration >= 0);
-    ASSERT(!isNull(offset));
-
-    // Bail if offset is null, as this can lead to buffer overflow below.
-    if (isNull(offset))
-        return const_cast<CompositableValue*>(m_keyframes.first()->value());
-
-    double minimumOffset = m_keyframes.first()->offset();
-    double maximumOffset = m_keyframes.last()->offset();
-    ASSERT(minimumOffset != maximumOffset);
-
-    PropertySpecificKeyframeVector::const_iterator before;
-    PropertySpecificKeyframeVector::const_iterator after;
-
-    // Note that this algorithm is simpler than that in the spec because we
-    // have removed keyframes with equal offsets in
-    // removeRedundantKeyframes().
-    if (offset < minimumOffset) {
-        before = m_keyframes.begin();
-        after = before + 1;
-        ASSERT((*before)->offset() > offset);
-        ASSERT((*after)->offset() > offset);
-    } else if (offset >= maximumOffset) {
-        after = m_keyframes.end() - 1;
-        before = after - 1;
-        ASSERT((*before)->offset() < offset);
-        ASSERT((*after)->offset() <= offset);
-    } else {
-        // FIXME: This is inefficient for large numbers of keyframes. Consider
-        // using binary search.
-        after = m_keyframes.begin();
-        while ((*after)->offset() <= offset)
-            ++after;
-        before = after - 1;
-        ASSERT((*before)->offset() <= offset);
-        ASSERT((*after)->offset() > offset);
-    }
-
-    if ((*before)->offset() == offset)
-        return const_cast<CompositableValue*>((*before)->value());
-    if ((*after)->offset() == offset)
-        return const_cast<CompositableValue*>((*after)->value());
-
-    double fraction = (offset - (*before)->offset()) / ((*after)->offset() - (*before)->offset());
-    if (const TimingFunction* timingFunction = (*before)->easing())
-        fraction = timingFunction->evaluate(fraction, accuracyForKeyframeEasing);
-    return BlendedCompositableValue::create((*before)->value(), (*after)->value(), fraction);
-}
-
 void KeyframeEffectModel::trace(Visitor* visitor)
 {
     visitor->trace(m_keyframes);
diff --git a/Source/core/animation/KeyframeEffectModel.h b/Source/core/animation/KeyframeEffectModel.h
index 9e896f5..e098a16 100644
--- a/Source/core/animation/KeyframeEffectModel.h
+++ b/Source/core/animation/KeyframeEffectModel.h
@@ -33,6 +33,7 @@
 
 #include "core/animation/AnimatableValue.h"
 #include "core/animation/AnimationEffect.h"
+#include "core/animation/InterpolationEffect.h"
 #include "heap/Handle.h"
 #include "platform/animation/TimingFunction.h"
 #include "wtf/HashMap.h"
@@ -101,7 +102,7 @@
     }
 
     // AnimationEffect implementation.
-    virtual PassOwnPtr<CompositableValueList> sample(int iteration, double fraction) const OVERRIDE;
+    virtual PassOwnPtr<Vector<RefPtr<Interpolation> > > sample(int iteration, double fraction) const OVERRIDE;
 
     // FIXME: Implement setFrames()
     const KeyframeVector& getFrames() const { return m_keyframes; }
@@ -114,21 +115,20 @@
     public:
         PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, const AnimatableValue*, CompositeOperation);
         double offset() const { return m_offset; }
-        const TimingFunction* easing() const { return m_easing.get(); }
-        const CompositableValue* value() const { return m_value.get(); }
+        TimingFunction* easing() const { return m_easing.get(); }
+        const AnimatableValue* value() const { return m_value.get(); }
         PassOwnPtr<PropertySpecificKeyframe> cloneWithOffset(double offset) const;
     private:
         // Used by cloneWithOffset().
-        PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, PassRefPtr<CompositableValue>);
+        PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, PassRefPtr<AnimatableValue>);
         double m_offset;
         RefPtr<TimingFunction> m_easing;
-        RefPtr<CompositableValue> m_value;
+        RefPtr<AnimatableValue> m_value;
     };
 
     class PropertySpecificKeyframeGroup {
     public:
         void appendKeyframe(PassOwnPtr<PropertySpecificKeyframe>);
-        PassRefPtr<CompositableValue> sample(int iteration, double offset) const;
         const PropertySpecificKeyframeVector& keyframes() const { return m_keyframes; }
     private:
         PropertySpecificKeyframeVector m_keyframes;
@@ -153,6 +153,7 @@
 
     // Lazily computes the groups of property-specific keyframes.
     void ensureKeyframeGroups() const;
+    void ensureInterpolationEffect() const;
 
     KeyframeVector m_keyframes;
     // The spec describes filtering the normalized keyframes at sampling time
@@ -161,6 +162,8 @@
     typedef HashMap<CSSPropertyID, OwnPtr<PropertySpecificKeyframeGroup> > KeyframeGroupMap;
     mutable OwnPtr<KeyframeGroupMap> m_keyframeGroups;
 
+    mutable RefPtr<InterpolationEffect> m_interpolationEffect;
+
     friend class KeyframeEffectModelTest;
 };
 
diff --git a/Source/core/animation/KeyframeEffectModelTest.cpp b/Source/core/animation/KeyframeEffectModelTest.cpp
index 0eabb5b..53cea3d 100644
--- a/Source/core/animation/KeyframeEffectModelTest.cpp
+++ b/Source/core/animation/KeyframeEffectModelTest.cpp
@@ -64,8 +64,17 @@
     return keyframes;
 }
 
-void expectDoubleValue(double expectedValue, PassRefPtr<AnimatableValue> value)
+void expectProperty(CSSPropertyID property, PassRefPtr<Interpolation> interpolationValue)
 {
+    LegacyStyleInterpolation* interpolation = toLegacyStyleInterpolation(interpolationValue.get());
+    ASSERT_EQ(property, interpolation->id());
+}
+
+void expectDoubleValue(double expectedValue, PassRefPtr<Interpolation> interpolationValue)
+{
+    LegacyStyleInterpolation* interpolation = toLegacyStyleInterpolation(interpolationValue.get());
+    RefPtr<AnimatableValue> value = interpolation->currentValue();
+
     ASSERT_TRUE(value->isLength() || value->isUnknown());
 
     double actualValue;
@@ -77,12 +86,12 @@
     EXPECT_FLOAT_EQ(static_cast<float>(expectedValue), actualValue);
 }
 
-const AnimationEffect::CompositableValue* findValue(const AnimationEffect::CompositableValueList& values, CSSPropertyID id)
+Interpolation* findValue(Vector<RefPtr<Interpolation> >& values, CSSPropertyID id)
 {
     for (size_t i = 0; i < values.size(); ++i) {
-        const std::pair<CSSPropertyID, RefPtr<AnimationEffect::CompositableValue> >& value = values.at(i);
-        if (value.first == id)
-            return value.second.get();
+        LegacyStyleInterpolation* value = toLegacyStyleInterpolation(values.at(i).get());
+        if (value->id() == id)
+            return value;
     }
     return 0;
 }
@@ -92,10 +101,10 @@
 {
     KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
+    OwnPtr<Vector<RefPtr<Interpolation> > > values = effect->sample(0, 0.6);
     ASSERT_EQ(1UL, values->size());
-    EXPECT_EQ(CSSPropertyLeft, values->at(0).first);
-    expectDoubleValue(5.0, values->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectProperty(CSSPropertyLeft, values->at(0));
+    expectDoubleValue(5.0, values->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, CompositeReplaceNonInterpolable)
@@ -104,7 +113,7 @@
     keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
     keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, CompositeReplace)
@@ -113,16 +122,16 @@
     keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
     keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(3.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectDoubleValue(3.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0));
 }
 
-TEST(AnimationKeyframeEffectModel, CompositeAdd)
+TEST(AnimationKeyframeEffectModel, DISABLED_CompositeAdd)
 {
     KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
     keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
     keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0).get()));
+    expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, CompositeEaseIn)
@@ -133,7 +142,7 @@
     keyframes[0]->setEasing(CSSToStyleMap::animationTimingFunction(timingFunction.get(), false));
     keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(3.8582394, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectDoubleValue(3.8582394, effect->sample(0, 0.6)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, CompositeCubicBezier)
@@ -144,16 +153,16 @@
     keyframes[0]->setEasing(CSSToStyleMap::animationTimingFunction(timingFunction.get(), false));
     keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(4.3362322, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectDoubleValue(4.3362322, effect->sample(0, 0.6)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, ExtrapolateReplaceNonInterpolable)
 {
     KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
-    RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
     keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
     keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
-    expectDoubleValue(5.0, effect->sample(0, 1.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(5.0, effect->sample(0, 1.6)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, ExtrapolateReplace)
@@ -162,16 +171,16 @@
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
     keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
     keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
-    expectDoubleValue(3.0 * -0.6 + 5.0 * 1.6, effect->sample(0, 1.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0).get()));
+    expectDoubleValue(3.0 * -0.6 + 5.0 * 1.6, effect->sample(0, 1.6)->at(0));
 }
 
-TEST(AnimationKeyframeEffectModel, ExtrapolateAdd)
+TEST(AnimationKeyframeEffectModel, DISABLED_ExtrapolateAdd)
 {
     KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
     keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
     keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue((7.0 + 3.0) * -0.6 + (7.0 + 5.0) * 1.6, effect->sample(0, 1.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0).get()));
+    expectDoubleValue((7.0 + 3.0) * -0.6 + (7.0 + 5.0) * 1.6, effect->sample(0, 1.6)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, ZeroKeyframes)
@@ -188,10 +197,10 @@
     keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0).get());
 
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(3.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectDoubleValue(3.0, effect->sample(0, 0.6)->at(0));
 }
 
-TEST(AnimationKeyframeEffectModel, SingleKeyframeAtOffsetOne)
+TEST(AnimationKeyframeEffectModel, DISABLED_SingleKeyframeAtOffsetOne)
 {
     KeyframeEffectModel::KeyframeVector keyframes(1);
     keyframes[0] = Keyframe::create();
@@ -199,7 +208,7 @@
     keyframes[0]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(5.0).get());
 
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(7.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0).get()));
+    expectDoubleValue(7.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, MoreThanTwoKeyframes)
@@ -216,8 +225,8 @@
     keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0).get());
 
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(4.0, effect->sample(0, 0.3)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    expectDoubleValue(5.0, effect->sample(0, 0.8)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectDoubleValue(4.0, effect->sample(0, 0.3)->at(0));
+    expectDoubleValue(5.0, effect->sample(0, 0.8)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, EndKeyframeOffsetsUnspecified)
@@ -232,9 +241,9 @@
     keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0).get());
 
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(3.0, effect->sample(0, 0.1)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    expectDoubleValue(4.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    expectDoubleValue(5.0, effect->sample(0, 0.9)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectDoubleValue(3.0, effect->sample(0, 0.1)->at(0));
+    expectDoubleValue(4.0, effect->sample(0, 0.6)->at(0));
+    expectDoubleValue(5.0, effect->sample(0, 0.9)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, SampleOnKeyframe)
@@ -251,37 +260,9 @@
     keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0).get());
 
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(3.0, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    expectDoubleValue(4.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    expectDoubleValue(5.0, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-}
-
-// Note that this tests an implementation detail, not behaviour defined by the spec.
-TEST(AnimationKeyframeEffectModel, SampleReturnsSameAnimatableValueInstance)
-{
-    RefPtr<AnimatableValue> threePixelsValue = unknownAnimatableValue(3.0);
-    RefPtr<AnimatableValue> fourPixelsValue = unknownAnimatableValue(4.0);
-    RefPtr<AnimatableValue> fivePixelsValue = unknownAnimatableValue(5.0);
-
-    KeyframeEffectModel::KeyframeVector keyframes(3);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, threePixelsValue.get());
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(0.5);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, fourPixelsValue.get());
-    keyframes[2] = Keyframe::create();
-    keyframes[2]->setOffset(1.0);
-    keyframes[2]->setPropertyValue(CSSPropertyLeft, fivePixelsValue.get());
-
-    RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    EXPECT_EQ(threePixelsValue, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    EXPECT_EQ(threePixelsValue, effect->sample(0, 0.1)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.4)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    EXPECT_EQ(fivePixelsValue, effect->sample(0, 0.9)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
-    EXPECT_EQ(fivePixelsValue, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectDoubleValue(3.0, effect->sample(0, 0.0)->at(0));
+    expectDoubleValue(4.0, effect->sample(0, 0.5)->at(0));
+    expectDoubleValue(5.0, effect->sample(0, 1.0)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, MultipleKeyframesWithSameOffset)
@@ -310,16 +291,16 @@
     keyframes[6]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(7.0).get());
 
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(2.0, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(8.0).get()));
-    expectDoubleValue(2.0, effect->sample(0, 0.2)->at(0).second->compositeOnto(unknownAnimatableValue(8.0).get()));
-    expectDoubleValue(3.0, effect->sample(0, 0.4)->at(0).second->compositeOnto(unknownAnimatableValue(8.0).get()));
-    expectDoubleValue(5.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(8.0).get()));
-    expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(8.0).get()));
-    expectDoubleValue(6.0, effect->sample(0, 0.8)->at(0).second->compositeOnto(unknownAnimatableValue(8.0).get()));
-    expectDoubleValue(6.0, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(8.0).get()));
+    expectDoubleValue(2.0, effect->sample(0, 0.0)->at(0));
+    expectDoubleValue(2.0, effect->sample(0, 0.2)->at(0));
+    expectDoubleValue(3.0, effect->sample(0, 0.4)->at(0));
+    expectDoubleValue(5.0, effect->sample(0, 0.5)->at(0));
+    expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0));
+    expectDoubleValue(6.0, effect->sample(0, 0.8)->at(0));
+    expectDoubleValue(6.0, effect->sample(0, 1.0)->at(0));
 }
 
-TEST(AnimationKeyframeEffectModel, PerKeyframeComposite)
+TEST(AnimationKeyframeEffectModel, DISABLED_PerKeyframeComposite)
 {
     KeyframeEffectModel::KeyframeVector keyframes(2);
     keyframes[0] = Keyframe::create();
@@ -331,7 +312,7 @@
     keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
 
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(3.0 * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0).get()));
+    expectDoubleValue(3.0 * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, MultipleProperties)
@@ -347,37 +328,37 @@
     keyframes[1]->setPropertyValue(CSSPropertyRight, unknownAnimatableValue(6.0).get());
 
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
+    OwnPtr<Vector<RefPtr<Interpolation> > > values = effect->sample(0, 0.6);
     EXPECT_EQ(2UL, values->size());
-    const AnimationEffect::CompositableValue* leftValue = findValue(*values.get(), CSSPropertyLeft);
+    Interpolation* leftValue = findValue(*values.get(), CSSPropertyLeft);
     ASSERT_TRUE(leftValue);
-    expectDoubleValue(5.0, leftValue->compositeOnto(unknownAnimatableValue(7.0).get()));
-    const AnimationEffect::CompositableValue* rightValue = findValue(*values.get(), CSSPropertyRight);
+    expectDoubleValue(5.0, leftValue);
+    Interpolation* rightValue = findValue(*values.get(), CSSPropertyRight);
     ASSERT_TRUE(rightValue);
-    expectDoubleValue(6.0, rightValue->compositeOnto(unknownAnimatableValue(7.0).get()));
+    expectDoubleValue(6.0, rightValue);
 }
 
-TEST(AnimationKeyframeEffectModel, RecompositeCompositableValue)
+TEST(AnimationKeyframeEffectModel, DISABLED_RecompositeCompositableValue)
 {
     KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
     keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
     keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
-    expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, values->at(0).second->compositeOnto(pixelAnimatableValue(7.0).get()));
-    expectDoubleValue((9.0 + 3.0) * 0.4 + (9.0 + 5.0) * 0.6, values->at(0).second->compositeOnto(pixelAnimatableValue(9.0).get()));
+    OwnPtr<Vector<RefPtr<Interpolation> > > values = effect->sample(0, 0.6);
+    expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, values->at(0));
+    expectDoubleValue((9.0 + 3.0) * 0.4 + (9.0 + 5.0) * 0.6, values->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, MultipleIterations)
 {
     KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(1.0), pixelAnimatableValue(3.0));
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    expectDoubleValue(2.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0).get()));
-    expectDoubleValue(2.0, effect->sample(1, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0).get()));
-    expectDoubleValue(2.0, effect->sample(2, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0).get()));
+    expectDoubleValue(2.0, effect->sample(0, 0.5)->at(0));
+    expectDoubleValue(2.0, effect->sample(1, 0.5)->at(0));
+    expectDoubleValue(2.0, effect->sample(2, 0.5)->at(0));
 }
 
-TEST(AnimationKeyframeEffectModel, DependsOnUnderlyingValue)
+TEST(AnimationKeyframeEffectModel, DISABLED_DependsOnUnderlyingValue)
 {
     KeyframeEffectModel::KeyframeVector keyframes(3);
     keyframes[0] = Keyframe::create();
@@ -392,15 +373,15 @@
     keyframes[2]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0).get());
 
     RefPtrWillBeRawPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
-    EXPECT_TRUE(effect->sample(0, 0)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_TRUE(effect->sample(0, 0.1)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_TRUE(effect->sample(0, 0.25)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_TRUE(effect->sample(0, 0.4)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 0.5)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 0.6)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 0.75)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 0.8)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 1)->at(0).second->dependsOnUnderlyingValue());
+    EXPECT_TRUE(effect->sample(0, 0)->at(0));
+    EXPECT_TRUE(effect->sample(0, 0.1)->at(0));
+    EXPECT_TRUE(effect->sample(0, 0.25)->at(0));
+    EXPECT_TRUE(effect->sample(0, 0.4)->at(0));
+    EXPECT_FALSE(effect->sample(0, 0.5)->at(0));
+    EXPECT_FALSE(effect->sample(0, 0.6)->at(0));
+    EXPECT_FALSE(effect->sample(0, 0.75)->at(0));
+    EXPECT_FALSE(effect->sample(0, 0.8)->at(0));
+    EXPECT_FALSE(effect->sample(0, 1)->at(0));
 }
 
 TEST(AnimationKeyframeEffectModel, ToKeyframeEffectModel)
diff --git a/Source/core/animation/css/CSSAnimatableValueFactory.cpp b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
index 6068a1b..3ffe9d9 100644
--- a/Source/core/animation/css/CSSAnimatableValueFactory.cpp
+++ b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
@@ -156,7 +156,7 @@
 inline static PassRefPtr<AnimatableValue> createFromStyleImage(StyleImage* image)
 {
     if (image)
-        return AnimatableImage::create(image);
+        return AnimatableImage::create(*image);
     return AnimatableUnknown::create(CSSValueNone);
 }
 
diff --git a/Source/core/animation/css/CSSAnimations.cpp b/Source/core/animation/css/CSSAnimations.cpp
index 567bc50..b2b0bd3 100644
--- a/Source/core/animation/css/CSSAnimations.cpp
+++ b/Source/core/animation/css/CSSAnimations.cpp
@@ -324,9 +324,9 @@
 {
     OwnPtr<CSSAnimationUpdate> update = adoptPtr(new CSSAnimationUpdate());
     calculateAnimationUpdate(update.get(), element, parentElement, style, parentStyle, resolver);
-    calculateAnimationCompositableValues(update.get(), element);
+    calculateAnimationActiveInterpolations(update.get(), element);
     calculateTransitionUpdate(update.get(), element, style);
-    calculateTransitionCompositableValues(update.get(), element);
+    calculateTransitionActiveInterpolations(update.get(), element);
     return update->isEmpty() ? nullptr : update.release();
 }
 
@@ -408,13 +408,13 @@
 void CSSAnimations::maybeApplyPendingUpdate(Element* element)
 {
     if (!m_pendingUpdate) {
-        m_previousCompositableValuesForAnimations.clear();
+        m_previousActiveInterpolationsForAnimations.clear();
         return;
     }
 
     OwnPtr<CSSAnimationUpdate> update = m_pendingUpdate.release();
 
-    m_previousCompositableValuesForAnimations.swap(update->compositableValuesForAnimations());
+    m_previousActiveInterpolationsForAnimations.swap(update->activeInterpolationsForAnimations());
 
     // FIXME: cancelling, pausing, unpausing animations all query compositingState, which is not necessarily up to date here
     // since we call this from recalc style.
@@ -499,10 +499,9 @@
             KeyframeEffectModel::KeyframeVector newFrames;
             newFrames.append(frames[0]->clone());
             newFrames[0]->clearPropertyValue(id);
-            ASSERT(oldAnimation->compositableValues()->size() == 1);
-            const AnimationEffect::CompositableValue* compositableValue = oldAnimation->compositableValues()->at(0).second.get();
-            ASSERT(!compositableValue->dependsOnUnderlyingValue());
-            newFrames[0]->setPropertyValue(id, compositableValue->compositeOnto(0).get());
+            ASSERT(oldAnimation->activeInterpolations().size() == 1);
+            const AnimatableValue* value = toLegacyStyleInterpolation(oldAnimation->activeInterpolations()[0].get())->currentValue();
+            newFrames[0]->setPropertyValue(id, value);
             newFrames.append(frames[1]->clone());
             effect = KeyframeEffectModel::create(newFrames);
         }
@@ -618,8 +617,8 @@
 
                 // FIXME: We should transition if an !important property changes even when an animation is running,
                 // but this is a bit hard to do with the current applyMatchedProperties system.
-                if (!update->compositableValuesForAnimations().contains(id)
-                    && (!activeAnimations || !activeAnimations->cssAnimations().m_previousCompositableValuesForAnimations.contains(id))) {
+                if (!update->activeInterpolationsForAnimations().contains(id)
+                    && (!activeAnimations || !activeAnimations->cssAnimations().m_previousActiveInterpolationsForAnimations.contains(id))) {
                     calculateTransitionUpdateForProperty(id, anim, oldStyle, style, activeTransitions, update, element);
                 }
             }
@@ -654,14 +653,14 @@
     m_pendingUpdate = nullptr;
 }
 
-void CSSAnimations::calculateAnimationCompositableValues(CSSAnimationUpdate* update, const Element* element)
+void CSSAnimations::calculateAnimationActiveInterpolations(CSSAnimationUpdate* update, const Element* element)
 {
     ActiveAnimations* activeAnimations = element ? element->activeAnimations() : 0;
     AnimationStack* animationStack = activeAnimations ? &activeAnimations->defaultStack() : 0;
 
     if (update->newAnimations().isEmpty() && update->cancelledAnimationAnimationPlayers().isEmpty()) {
-        AnimationEffect::CompositableValueMap compositableValuesForAnimations(AnimationStack::compositableValues(animationStack, 0, 0, Animation::DefaultPriority));
-        update->adoptCompositableValuesForAnimations(compositableValuesForAnimations);
+        HashMap<CSSPropertyID, RefPtr<Interpolation> > activeInterpolationsForAnimations(AnimationStack::activeInterpolations(animationStack, 0, 0, Animation::DefaultPriority));
+        update->adoptActiveInterpolationsForAnimations(activeInterpolationsForAnimations);
         return;
     }
 
@@ -671,18 +670,18 @@
         for (HashSet<RefPtr<InertAnimation> >::const_iterator animationsIter = animations.begin(); animationsIter != animations.end(); ++animationsIter)
             newAnimations.append(animationsIter->get());
     }
-    AnimationEffect::CompositableValueMap compositableValuesForAnimations(AnimationStack::compositableValues(animationStack, &newAnimations, &update->cancelledAnimationAnimationPlayers(), Animation::DefaultPriority));
-    update->adoptCompositableValuesForAnimations(compositableValuesForAnimations);
+    HashMap<CSSPropertyID, RefPtr<Interpolation> > activeInterpolationsForAnimations(AnimationStack::activeInterpolations(animationStack, &newAnimations, &update->cancelledAnimationAnimationPlayers(), Animation::DefaultPriority));
+    update->adoptActiveInterpolationsForAnimations(activeInterpolationsForAnimations);
 }
 
-void CSSAnimations::calculateTransitionCompositableValues(CSSAnimationUpdate* update, const Element* element)
+void CSSAnimations::calculateTransitionActiveInterpolations(CSSAnimationUpdate* update, const Element* element)
 {
     ActiveAnimations* activeAnimations = element ? element->activeAnimations() : 0;
     AnimationStack* animationStack = activeAnimations ? &activeAnimations->defaultStack() : 0;
 
-    AnimationEffect::CompositableValueMap compositableValuesForTransitions;
+    HashMap<CSSPropertyID, RefPtr<Interpolation> > activeInterpolationsForTransitions;
     if (update->newTransitions().isEmpty() && update->cancelledTransitions().isEmpty()) {
-        compositableValuesForTransitions = AnimationStack::compositableValues(animationStack, 0, 0, Animation::TransitionPriority);
+        activeInterpolationsForTransitions = AnimationStack::activeInterpolations(animationStack, 0, 0, Animation::TransitionPriority);
     } else {
         Vector<InertAnimation*> newTransitions;
         for (CSSAnimationUpdate::NewTransitionMap::const_iterator iter = update->newTransitions().begin(); iter != update->newTransitions().end(); ++iter)
@@ -698,15 +697,15 @@
             }
         }
 
-        compositableValuesForTransitions = AnimationStack::compositableValues(animationStack, &newTransitions, &cancelledAnimationPlayers, Animation::TransitionPriority);
+        activeInterpolationsForTransitions = AnimationStack::activeInterpolations(animationStack, &newTransitions, &cancelledAnimationPlayers, Animation::TransitionPriority);
     }
 
     // Properties being animated by animations don't get values from transitions applied.
-    if (!update->compositableValuesForAnimations().isEmpty() && !compositableValuesForTransitions.isEmpty()) {
-        for (AnimationEffect::CompositableValueMap::const_iterator iter = update->compositableValuesForAnimations().begin(); iter != update->compositableValuesForAnimations().end(); ++iter)
-            compositableValuesForTransitions.remove(iter->key);
+    if (!update->activeInterpolationsForAnimations().isEmpty() && !activeInterpolationsForTransitions.isEmpty()) {
+        for (HashMap<CSSPropertyID, RefPtr<Interpolation> >::const_iterator iter = update->activeInterpolationsForAnimations().begin(); iter != update->activeInterpolationsForAnimations().end(); ++iter)
+            activeInterpolationsForTransitions.remove(iter->key);
     }
-    update->adoptCompositableValuesForTransitions(compositableValuesForTransitions);
+    update->adoptActiveInterpolationsForTransitions(activeInterpolationsForTransitions);
 }
 
 void CSSAnimations::AnimationEventDelegate::maybeDispatch(Document::ListenerType listenerType, const AtomicString& eventName, double elapsedTime)
diff --git a/Source/core/animation/css/CSSAnimations.h b/Source/core/animation/css/CSSAnimations.h
index 85fe32f..e730fc1 100644
--- a/Source/core/animation/css/CSSAnimations.h
+++ b/Source/core/animation/css/CSSAnimations.h
@@ -34,6 +34,7 @@
 #include "core/animation/Animation.h"
 #include "core/animation/AnimationPlayer.h"
 #include "core/animation/InertAnimation.h"
+#include "core/animation/Interpolation.h"
 #include "core/animation/css/CSSAnimationData.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/Document.h"
@@ -50,7 +51,7 @@
 class StyleRuleKeyframes;
 
 // This class stores the CSS Animations/Transitions information we use during a style recalc.
-// This includes updates to animations/transitions as well as the CompositableValueMaps to be applied.
+// This includes updates to animations/transitions as well as the Interpolations to be applied.
 class CSSAnimationUpdate FINAL {
 public:
     void startAnimation(AtomicString& animationName, const HashSet<RefPtr<InertAnimation> >& animations)
@@ -104,11 +105,11 @@
     const NewTransitionMap& newTransitions() const { return m_newTransitions; }
     const HashSet<CSSPropertyID>& cancelledTransitions() const { return m_cancelledTransitions; }
 
-    void adoptCompositableValuesForAnimations(AnimationEffect::CompositableValueMap& newMap) { newMap.swap(m_compositableValuesForAnimations); }
-    void adoptCompositableValuesForTransitions(AnimationEffect::CompositableValueMap& newMap) { newMap.swap(m_compositableValuesForTransitions); }
-    const AnimationEffect::CompositableValueMap& compositableValuesForAnimations() const { return m_compositableValuesForAnimations; }
-    const AnimationEffect::CompositableValueMap& compositableValuesForTransitions() const { return m_compositableValuesForTransitions; }
-    AnimationEffect::CompositableValueMap& compositableValuesForAnimations() { return m_compositableValuesForAnimations; }
+    void adoptActiveInterpolationsForAnimations(HashMap<CSSPropertyID, RefPtr<Interpolation> >& newMap) { newMap.swap(m_activeInterpolationsForAnimations); }
+    void adoptActiveInterpolationsForTransitions(HashMap<CSSPropertyID, RefPtr<Interpolation> >& newMap) { newMap.swap(m_activeInterpolationsForTransitions); }
+    const HashMap<CSSPropertyID, RefPtr<Interpolation> >& activeInterpolationsForAnimations() const { return m_activeInterpolationsForAnimations; }
+    const HashMap<CSSPropertyID, RefPtr<Interpolation> >& activeInterpolationsForTransitions() const { return m_activeInterpolationsForTransitions; }
+    HashMap<CSSPropertyID, RefPtr<Interpolation> >& activeInterpolationsForAnimations() { return m_activeInterpolationsForAnimations; }
 
     bool isEmpty() const
     {
@@ -118,8 +119,8 @@
             && m_animationsWithPauseToggled.isEmpty()
             && m_newTransitions.isEmpty()
             && m_cancelledTransitions.isEmpty()
-            && m_compositableValuesForAnimations.isEmpty()
-            && m_compositableValuesForTransitions.isEmpty();
+            && m_activeInterpolationsForAnimations.isEmpty()
+            && m_activeInterpolationsForTransitions.isEmpty();
     }
 private:
     // Order is significant since it defines the order in which new animations
@@ -134,8 +135,8 @@
     NewTransitionMap m_newTransitions;
     HashSet<CSSPropertyID> m_cancelledTransitions;
 
-    AnimationEffect::CompositableValueMap m_compositableValuesForAnimations;
-    AnimationEffect::CompositableValueMap m_compositableValuesForTransitions;
+    HashMap<CSSPropertyID, RefPtr<Interpolation> > m_activeInterpolationsForAnimations;
+    HashMap<CSSPropertyID, RefPtr<Interpolation> > m_activeInterpolationsForTransitions;
 };
 
 class CSSAnimations FINAL {
@@ -172,14 +173,14 @@
     TransitionMap m_transitions;
     OwnPtr<CSSAnimationUpdate> m_pendingUpdate;
 
-    AnimationEffect::CompositableValueMap m_previousCompositableValuesForAnimations;
+    HashMap<CSSPropertyID, RefPtr<Interpolation> > m_previousActiveInterpolationsForAnimations;
 
     static void calculateAnimationUpdate(CSSAnimationUpdate*, Element*, const Element& parentElement, const RenderStyle&, RenderStyle* parentStyle, StyleResolver*);
     static void calculateTransitionUpdate(CSSAnimationUpdate*, const Element*, const RenderStyle&);
     static void calculateTransitionUpdateForProperty(CSSPropertyID, const CSSAnimationData*, const RenderStyle& oldStyle, const RenderStyle&, const TransitionMap* activeTransitions, CSSAnimationUpdate*, const Element*);
 
-    static void calculateAnimationCompositableValues(CSSAnimationUpdate*, const Element*);
-    static void calculateTransitionCompositableValues(CSSAnimationUpdate*, const Element*);
+    static void calculateAnimationActiveInterpolations(CSSAnimationUpdate*, const Element*);
+    static void calculateTransitionActiveInterpolations(CSSAnimationUpdate*, const Element*);
 
     class AnimationEventDelegate FINAL : public TimedItem::EventDelegate {
     public:
diff --git a/Source/core/core.gyp b/Source/core/core.gyp
index 3caa3af..2b71417 100644
--- a/Source/core/core.gyp
+++ b/Source/core/core.gyp
@@ -338,7 +338,9 @@
         ['OS=="win"', {
           # In generated bindings code: 'switch contains default but no case'.
           # Disable c4267 warnings until we fix size_t to int truncations.
-          'msvs_disabled_warnings': [ 4065, 4267 ],
+          # 4702 is disabled because of issues in Bison-generated
+          # XPathGrammar.cpp and CSSGrammar.cpp.
+          'msvs_disabled_warnings': [ 4065, 4267, 4702 ],
         }],
         ['OS in ("linux", "android") and "WTF_USE_WEBAUDIO_IPP=1" in feature_defines', {
           'cflags': [
diff --git a/Source/core/core.gypi b/Source/core/core.gypi
index ec14cb8..37d0c80 100644
--- a/Source/core/core.gypi
+++ b/Source/core/core.gypi
@@ -446,7 +446,8 @@
             'xml/XPathResult.idl',
             'xml/XSLTProcessor.idl',
         ],
-        # 'partial interface' or target (right side of) 'implements'
+        # 'partial interface', target (right side of) 'implements', and
+        # static bindings (in bindings/v8/)
         'core_dependency_idl_files': [
             'animation/DocumentAnimation.idl',
             'animation/ElementAnimation.idl',
@@ -457,6 +458,7 @@
             'dom/ParentNode.idl',
             'dom/URLUtils.idl',
             'dom/URLUtilsReadOnly.idl',
+            'events/EventListener.idl',
             'events/NavigatorEvents.idl',
             'frame/NavigatorID.idl',
             'frame/NavigatorOnLine.idl',
@@ -3300,6 +3302,7 @@
             'css/RuleSetTest.cpp',
             'css/MediaQuerySetTest.cpp',
             'css/analyzer/DescendantInvalidationSetTest.cpp',
+            'css/resolver/FontBuilderTest.cpp',
             'dom/ActiveDOMObjectTest.cpp',
             'dom/DOMImplementationTest.cpp',
             'css/parser/BisonCSSParserTest.cpp',
@@ -3315,6 +3318,7 @@
             'fetch/ResourceFetcherTest.cpp',
             'frame/ImageBitmapTest.cpp',
             'html/HTMLDimensionTest.cpp',
+            'html/HTMLLinkElementSizesAttributeTest.cpp',
             'html/LinkRelAttributeTest.cpp',
             'html/TimeRangesTest.cpp',
             'html/parser/HTMLParserThreadTest.cpp',
diff --git a/Source/core/core_generated.gyp b/Source/core/core_generated.gyp
index ef7d700..7272fe1 100644
--- a/Source/core/core_generated.gyp
+++ b/Source/core/core_generated.gyp
@@ -521,6 +521,7 @@
               'css/themeWin.css',
               'css/themeWinQuirks.css',
               'css/svg.css',
+              'css/mathml.css',
               'css/mediaControls.css',
               'css/mediaControlsAndroid.css',
               'css/fullscreen.css',
diff --git a/Source/core/css/CSSComputedStyleDeclaration.cpp b/Source/core/css/CSSComputedStyleDeclaration.cpp
index ee643ad..64b94f1 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -2055,9 +2055,9 @@
                 // RenderBox gives a marginRight() that is the distance between the right-edge of the child box
                 // and the right-edge of the containing box, when display == BLOCK. Let's calculate the absolute
                 // value of the specified margin-right % instead of relying on RenderBox's marginRight() value.
-                value = minimumValueForLength(marginRight, toRenderBox(renderer)->containingBlockLogicalWidthForContent());
+                value = minimumValueForLength(marginRight, toRenderBox(renderer)->containingBlockLogicalWidthForContent()).toFloat();
             } else {
-                value = toRenderBox(renderer)->marginRight();
+                value = toRenderBox(renderer)->marginRight().toFloat();
             }
             return zoomAdjustedPixelValue(value, *style);
         }
@@ -2905,7 +2905,7 @@
     return value && propertyValue && value->equals(*propertyValue);
 }
 
-PassRefPtr<MutableStylePropertySet> CSSComputedStyleDeclaration::copyProperties() const
+PassRefPtrWillBeRawPtr<MutableStylePropertySet> CSSComputedStyleDeclaration::copyProperties() const
 {
     return copyPropertiesInSet(computableProperties());
 }
@@ -2958,7 +2958,7 @@
     return list.release();
 }
 
-PassRefPtr<MutableStylePropertySet> CSSComputedStyleDeclaration::copyPropertiesInSet(const Vector<CSSPropertyID>& properties) const
+PassRefPtrWillBeRawPtr<MutableStylePropertySet> CSSComputedStyleDeclaration::copyPropertiesInSet(const Vector<CSSPropertyID>& properties) const
 {
     WillBeHeapVector<CSSProperty, 256> list;
     list.reserveInitialCapacity(properties.size());
diff --git a/Source/core/css/CSSComputedStyleDeclaration.h b/Source/core/css/CSSComputedStyleDeclaration.h
index 15b6f9e..5c9dc09 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/Source/core/css/CSSComputedStyleDeclaration.h
@@ -62,14 +62,14 @@
     String getPropertyValue(CSSPropertyID) const;
     bool getPropertyPriority(CSSPropertyID) const;
 
-    virtual PassRefPtr<MutableStylePropertySet> copyProperties() const OVERRIDE;
+    virtual PassRefPtrWillBeRawPtr<MutableStylePropertySet> copyProperties() const OVERRIDE;
 
     PassRefPtrWillBeRawPtr<CSSValue> getPropertyCSSValue(CSSPropertyID, EUpdateLayout) const;
     PassRefPtrWillBeRawPtr<CSSValue> getFontSizeCSSValuePreferringKeyword() const;
     bool useFixedFontDefaultSize() const;
     PassRefPtrWillBeRawPtr<CSSValue> getSVGPropertyCSSValue(CSSPropertyID, EUpdateLayout) const;
 
-    PassRefPtr<MutableStylePropertySet> copyPropertiesInSet(const Vector<CSSPropertyID>&) const;
+    PassRefPtrWillBeRawPtr<MutableStylePropertySet> copyPropertiesInSet(const Vector<CSSPropertyID>&) const;
 
 private:
     CSSComputedStyleDeclaration(PassRefPtr<Node>, bool allowVisitedStyle, const String&);
diff --git a/Source/core/css/CSSDefaultStyleSheets.cpp b/Source/core/css/CSSDefaultStyleSheets.cpp
index 0e62816..2e138aa 100644
--- a/Source/core/css/CSSDefaultStyleSheets.cpp
+++ b/Source/core/css/CSSDefaultStyleSheets.cpp
@@ -29,6 +29,7 @@
 #include "config.h"
 #include "core/css/CSSDefaultStyleSheets.h"
 
+#include "MathMLNames.h"
 #include "UserAgentStyleSheets.h"
 #include "core/css/MediaQueryEvaluator.h"
 #include "core/css/RuleSet.h"
@@ -88,6 +89,7 @@
     , m_viewportStyleSheet(nullptr)
     , m_quirksStyleSheet(nullptr)
     , m_svgStyleSheet(nullptr)
+    , m_mathmlStyleSheet(nullptr)
     , m_mediaControlsStyleSheet(nullptr)
     , m_fullscreenStyleSheet(nullptr)
 {
@@ -147,6 +149,16 @@
         changedDefaultStyle = true;
     }
 
+    // FIXME: We should assert that the sheet only styles MathML elements.
+    if (element->namespaceURI() == MathMLNames::mathmlNamespaceURI
+        && !m_mathmlStyleSheet) {
+        m_mathmlStyleSheet = parseUASheet(mathmlUserAgentStyleSheet,
+            sizeof(mathmlUserAgentStyleSheet));
+        m_defaultStyle->addRulesFromSheet(mathmlStyleSheet(), screenEval());
+        m_defaultPrintStyle->addRulesFromSheet(mathmlStyleSheet(), printEval());
+        changedDefaultStyle = true;
+    }
+
     // FIXME: We should assert that this sheet only contains rules for <video> and <audio>.
     if (!m_mediaControlsStyleSheet && (isHTMLVideoElement(*element) || isHTMLAudioElement(*element))) {
         String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::theme().extraMediaControlsStyleSheet();
@@ -182,6 +194,7 @@
     visitor->trace(m_viewportStyleSheet);
     visitor->trace(m_quirksStyleSheet);
     visitor->trace(m_svgStyleSheet);
+    visitor->trace(m_mathmlStyleSheet);
     visitor->trace(m_mediaControlsStyleSheet);
     visitor->trace(m_fullscreenStyleSheet);
 }
diff --git a/Source/core/css/CSSDefaultStyleSheets.h b/Source/core/css/CSSDefaultStyleSheets.h
index c427a4f..081e7d1 100644
--- a/Source/core/css/CSSDefaultStyleSheets.h
+++ b/Source/core/css/CSSDefaultStyleSheets.h
@@ -50,6 +50,7 @@
     StyleSheetContents* viewportStyleSheet() { return m_viewportStyleSheet.get(); }
     StyleSheetContents* quirksStyleSheet() { return m_quirksStyleSheet.get(); }
     StyleSheetContents* svgStyleSheet() { return m_svgStyleSheet.get(); }
+    StyleSheetContents* mathmlStyleSheet() { return m_mathmlStyleSheet.get(); }
     StyleSheetContents* mediaControlsStyleSheet() { return m_mediaControlsStyleSheet.get(); }
     StyleSheetContents* fullscreenStyleSheet() { return m_fullscreenStyleSheet.get(); }
 
@@ -69,6 +70,7 @@
     RefPtrWillBeMember<StyleSheetContents> m_viewportStyleSheet;
     RefPtrWillBeMember<StyleSheetContents> m_quirksStyleSheet;
     RefPtrWillBeMember<StyleSheetContents> m_svgStyleSheet;
+    RefPtrWillBeMember<StyleSheetContents> m_mathmlStyleSheet;
     RefPtrWillBeMember<StyleSheetContents> m_mediaControlsStyleSheet;
     RefPtrWillBeMember<StyleSheetContents> m_fullscreenStyleSheet;
 };
diff --git a/Source/core/css/CSSFontSelector.cpp b/Source/core/css/CSSFontSelector.cpp
index eacd0e9..a112a19 100644
--- a/Source/core/css/CSSFontSelector.cpp
+++ b/Source/core/css/CSSFontSelector.cpp
@@ -157,13 +157,13 @@
     UScriptCode script = fontDescription.script();
 
 #if OS(ANDROID)
-    if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
+    if (fontDescription.genericFamily() == FontDescription::StandardFamily)
         return FontCache::getGenericFamilyNameForScript(FontFamilyNames::webkit_standard, script);
 
     if (genericFamilyName.startsWith("-webkit-"))
         return FontCache::getGenericFamilyNameForScript(genericFamilyName, script);
 #else
-    if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
+    if (fontDescription.genericFamily() == FontDescription::StandardFamily)
         return settings.standard(script);
     if (genericFamilyName == FontFamilyNames::webkit_serif)
         return settings.serif(script);
diff --git a/Source/core/css/CSSImportRule.cpp b/Source/core/css/CSSImportRule.cpp
index 8d5af2f..e7d6219 100644
--- a/Source/core/css/CSSImportRule.cpp
+++ b/Source/core/css/CSSImportRule.cpp
@@ -41,9 +41,7 @@
 #if !ENABLE(OILPAN)
     if (m_styleSheetCSSOMWrapper)
         m_styleSheetCSSOMWrapper->clearOwnerRule();
-    // MediaList and the parent CSSImportRule are both on the oilpan heap and die together.
-    // Therefor clearing is not needed nor allowed since it could be touching already
-    // finalized memory.
+
     if (m_mediaCSSOMWrapper)
         m_mediaCSSOMWrapper->clearParentRule();
 #endif // ENABLE(OILPAN)
diff --git a/Source/core/css/CSSMatrix.cpp b/Source/core/css/CSSMatrix.cpp
index f37c7f0..6e11a82 100644
--- a/Source/core/css/CSSMatrix.cpp
+++ b/Source/core/css/CSSMatrix.cpp
@@ -57,7 +57,7 @@
     if (string.isEmpty())
         return;
 
-    RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create();
     if (BisonCSSParser::parseValue(styleDeclaration.get(), CSSPropertyWebkitTransform, string, true, HTMLStandardMode, 0)) {
         // Convert to TransformOperations. This can fail if a property
         // requires style (i.e., param uses 'ems' or 'exs')
diff --git a/Source/core/css/CSSSegmentedFontFace.cpp b/Source/core/css/CSSSegmentedFontFace.cpp
index 6f1ad97..bf92509 100644
--- a/Source/core/css/CSSSegmentedFontFace.cpp
+++ b/Source/core/css/CSSSegmentedFontFace.cpp
@@ -72,17 +72,6 @@
 void CSSSegmentedFontFace::fontLoaded(CSSFontFace*)
 {
     pruneTable();
-
-    if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && !isLoading()) {
-        Vector<RefPtr<LoadFontCallback> > callbacks;
-        m_callbacks.swap(callbacks);
-        for (size_t index = 0; index < callbacks.size(); ++index) {
-            if (isLoaded())
-                callbacks[index]->notifyLoaded(this);
-            else
-                callbacks[index]->notifyError(this);
-        }
-    }
 }
 
 void CSSSegmentedFontFace::fontLoadWaitLimitExceeded(CSSFontFace*)
@@ -208,20 +197,11 @@
     return true;
 }
 
-void CSSSegmentedFontFace::loadFont(const FontDescription& fontDescription, const String& text, PassRefPtr<LoadFontCallback> callback)
+void CSSSegmentedFontFace::match(const String& text, Vector<RefPtr<FontFace> >& faces) const
 {
-    for (FontFaceList::iterator it = m_fontFaces.begin(); it != m_fontFaces.end(); ++it) {
-        if ((*it)->loadStatus() == FontFace::Unloaded && (*it)->cssFontFace()->ranges().intersectsWith(text))
-            (*it)->cssFontFace()->load(fontDescription);
-    }
-
-    if (callback) {
-        if (isLoading())
-            m_callbacks.append(callback);
-        else if (isLoaded())
-            callback->notifyLoaded(this);
-        else
-            callback->notifyError(this);
+    for (FontFaceList::const_iterator it = m_fontFaces.begin(); it != m_fontFaces.end(); ++it) {
+        if ((*it)->cssFontFace()->ranges().intersectsWith(text))
+            faces.append(*it);
     }
 }
 
diff --git a/Source/core/css/CSSSegmentedFontFace.h b/Source/core/css/CSSSegmentedFontFace.h
index 18b49c6..119f709 100644
--- a/Source/core/css/CSSSegmentedFontFace.h
+++ b/Source/core/css/CSSSegmentedFontFace.h
@@ -63,15 +63,8 @@
 
     PassRefPtr<FontData> getFontData(const FontDescription&);
 
-    class LoadFontCallback : public RefCounted<LoadFontCallback> {
-    public:
-        virtual ~LoadFontCallback() { }
-        virtual void notifyLoaded(CSSSegmentedFontFace*) = 0;
-        virtual void notifyError(CSSSegmentedFontFace*) = 0;
-    };
-
     bool checkFont(const String&) const;
-    void loadFont(const FontDescription&, const String&, PassRefPtr<LoadFontCallback>);
+    void match(const String&, Vector<RefPtr<FontFace> >&) const;
     void willUseFontData(const FontDescription&);
 
 private:
@@ -90,7 +83,6 @@
     // All non-CSS-connected FontFaces are stored after the CSS-connected ones.
     FontFaceList m_fontFaces;
     FontFaceList::iterator m_firstNonCssConnectedFace;
-    Vector<RefPtr<LoadFontCallback> > m_callbacks;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSStyleDeclaration.h b/Source/core/css/CSSStyleDeclaration.h
index 9f570e4..36035ce 100644
--- a/Source/core/css/CSSStyleDeclaration.h
+++ b/Source/core/css/CSSStyleDeclaration.h
@@ -63,7 +63,7 @@
     virtual String getPropertyValueInternal(CSSPropertyID) = 0;
     virtual void setPropertyInternal(CSSPropertyID, const String& value, bool important, ExceptionState&) = 0;
 
-    virtual PassRefPtr<MutableStylePropertySet> copyProperties() const = 0;
+    virtual PassRefPtrWillBeRawPtr<MutableStylePropertySet> copyProperties() const = 0;
 
     virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const = 0;
     virtual CSSStyleSheet* parentStyleSheet() const { return 0; }
diff --git a/Source/core/css/CSSStyleSheet.cpp b/Source/core/css/CSSStyleSheet.cpp
index d9f73c8..1d0336a 100644
--- a/Source/core/css/CSSStyleSheet.cpp
+++ b/Source/core/css/CSSStyleSheet.cpp
@@ -87,25 +87,25 @@
 
 PassRefPtrWillBeRawPtr<CSSStyleSheet> CSSStyleSheet::create(PassRefPtrWillBeRawPtr<StyleSheetContents> sheet, CSSImportRule* ownerRule)
 {
-    return adoptRefWillBeRefCountedGarbageCollected(new CSSStyleSheet(sheet, ownerRule));
+    return adoptRefWillBeNoop(new CSSStyleSheet(sheet, ownerRule));
 }
 
 PassRefPtrWillBeRawPtr<CSSStyleSheet> CSSStyleSheet::create(PassRefPtrWillBeRawPtr<StyleSheetContents> sheet, Node* ownerNode)
 {
-    return adoptRefWillBeRefCountedGarbageCollected(new CSSStyleSheet(sheet, ownerNode, false, TextPosition::minimumPosition()));
+    return adoptRefWillBeNoop(new CSSStyleSheet(sheet, ownerNode, false, TextPosition::minimumPosition()));
 }
 
 PassRefPtrWillBeRawPtr<CSSStyleSheet> CSSStyleSheet::createInline(PassRefPtrWillBeRawPtr<StyleSheetContents> sheet, Node* ownerNode, const TextPosition& startPosition)
 {
     ASSERT(sheet);
-    return adoptRefWillBeRefCountedGarbageCollected(new CSSStyleSheet(sheet, ownerNode, true, startPosition));
+    return adoptRefWillBeNoop(new CSSStyleSheet(sheet, ownerNode, true, startPosition));
 }
 
 PassRefPtrWillBeRawPtr<CSSStyleSheet> CSSStyleSheet::createInline(Node* ownerNode, const KURL& baseURL, const TextPosition& startPosition, const String& encoding)
 {
     CSSParserContext parserContext(ownerNode->document(), 0, baseURL, encoding);
     RefPtrWillBeRawPtr<StyleSheetContents> sheet = StyleSheetContents::create(baseURL.string(), parserContext);
-    return adoptRefWillBeRefCountedGarbageCollected(new CSSStyleSheet(sheet.release(), ownerNode, true, startPosition));
+    return adoptRefWillBeNoop(new CSSStyleSheet(sheet.release(), ownerNode, true, startPosition));
 }
 
 CSSStyleSheet::CSSStyleSheet(PassRefPtrWillBeRawPtr<StyleSheetContents> contents, CSSImportRule* ownerRule)
@@ -158,11 +158,12 @@
 void CSSStyleSheet::willMutateRules()
 {
     InspectorInstrumentation::willMutateRules(this);
+
     // If we are the only client it is safe to mutate.
-    if (m_contents->hasOneClient() && !m_contents->isInMemoryCache()) {
+    if (m_contents->clientSize() <= 1 && !m_contents->isInMemoryCache()) {
         m_contents->clearRuleSet();
-        if (m_contents->maybeCacheable())
-            StyleEngine::removeSheet(m_contents.get());
+        if (Document* document = ownerDocument())
+            m_contents->removeSheetFromCache(document);
         m_contents->setMutable();
         return;
     }
@@ -183,7 +184,7 @@
 void CSSStyleSheet::didMutateRules()
 {
     ASSERT(m_contents->isMutable());
-    ASSERT(m_contents->hasOneClient());
+    ASSERT(m_contents->clientSize() <= 1);
 
     InspectorInstrumentation::didMutateRules(this);
     didMutate(PartialRuleUpdate);
@@ -255,6 +256,14 @@
     return cssRule.get();
 }
 
+void CSSStyleSheet::clearOwnerNode()
+{
+    didMutate(EntireStyleSheetUpdate);
+    if (m_ownerNode)
+        m_contents->unregisterClient(this);
+    m_ownerNode = 0;
+}
+
 bool CSSStyleSheet::canAccessRules() const
 {
     if (m_isInlineStylesheet)
diff --git a/Source/core/css/CSSStyleSheet.h b/Source/core/css/CSSStyleSheet.h
index ab7106e..2ced71a 100644
--- a/Source/core/css/CSSStyleSheet.h
+++ b/Source/core/css/CSSStyleSheet.h
@@ -79,7 +79,8 @@
     unsigned length() const;
     CSSRule* item(unsigned index);
 
-    virtual void clearOwnerNode() OVERRIDE { didMutate(EntireStyleSheetUpdate); m_ownerNode = 0; }
+    virtual void clearOwnerNode() OVERRIDE;
+
     virtual CSSRule* ownerRule() const OVERRIDE { return m_ownerRule; }
     virtual KURL baseURL() const OVERRIDE;
     virtual bool isLoading() const OVERRIDE;
@@ -92,13 +93,14 @@
 
     class RuleMutationScope {
         WTF_MAKE_NONCOPYABLE(RuleMutationScope);
+        STACK_ALLOCATED();
     public:
-        RuleMutationScope(CSSStyleSheet*);
-        RuleMutationScope(CSSRule*);
+        explicit RuleMutationScope(CSSStyleSheet*);
+        explicit RuleMutationScope(CSSRule*);
         ~RuleMutationScope();
 
     private:
-        CSSStyleSheet* m_styleSheet;
+        RawPtrWillBeMember<CSSStyleSheet> m_styleSheet;
     };
 
     void willMutateRules();
diff --git a/Source/core/css/CSSTestHelper.h b/Source/core/css/CSSTestHelper.h
index 58aa933..366835e 100644
--- a/Source/core/css/CSSTestHelper.h
+++ b/Source/core/css/CSSTestHelper.h
@@ -55,7 +55,7 @@
 
 private:
     RefPtr<Document> m_document;
-    RefPtr<CSSStyleSheet> m_styleSheet;
+    RefPtrWillBePersistent<CSSStyleSheet> m_styleSheet;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSValue.cpp b/Source/core/css/CSSValue.cpp
index 8db94f4..f6f81ed 100644
--- a/Source/core/css/CSSValue.cpp
+++ b/Source/core/css/CSSValue.cpp
@@ -397,7 +397,7 @@
     ASSERT_NOT_REACHED();
 }
 
-void CSSValue::finalize()
+void CSSValue::finalizeGarbageCollectedObject()
 {
     if (m_isTextClone) {
         ASSERT(isCSSOMSafe());
diff --git a/Source/core/css/CSSValue.h b/Source/core/css/CSSValue.h
index 3fd465e..ec6c872 100644
--- a/Source/core/css/CSSValue.h
+++ b/Source/core/css/CSSValue.h
@@ -120,7 +120,7 @@
 
     bool equals(const CSSValue&) const;
 
-    void finalize();
+    void finalizeGarbageCollectedObject();
     void traceAfterDispatch(Visitor*) { }
     void trace(Visitor*);
 
diff --git a/Source/core/css/DOMWindowCSS.cpp b/Source/core/css/DOMWindowCSS.cpp
index 229e127..ff5013d 100644
--- a/Source/core/css/DOMWindowCSS.cpp
+++ b/Source/core/css/DOMWindowCSS.cpp
@@ -74,7 +74,7 @@
     if (normalizedValue.isEmpty())
         return false;
 
-    RefPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
     return BisonCSSParser::parseValue(dummyStyle.get(), propertyID, normalizedValue, false, HTMLStandardMode, 0);
 }
 
diff --git a/Source/core/css/ElementRuleCollector.cpp b/Source/core/css/ElementRuleCollector.cpp
index cfc7ce3..6675cdc 100644
--- a/Source/core/css/ElementRuleCollector.cpp
+++ b/Source/core/css/ElementRuleCollector.cpp
@@ -81,7 +81,7 @@
 inline void ElementRuleCollector::addMatchedRule(const RuleData* rule, unsigned specificity, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex, const CSSStyleSheet* parentStyleSheet)
 {
     if (!m_matchedRules)
-        m_matchedRules = adoptPtr(new Vector<MatchedRule, 32>);
+        m_matchedRules = adoptPtrWillBeNoop(new WillBeHeapVector<MatchedRule, 32>);
     m_matchedRules->append(MatchedRule(rule, specificity, cascadeScope, cascadeOrder, styleSheetIndex, parentStyleSheet));
 }
 
@@ -234,7 +234,7 @@
 
     sortMatchedRules();
 
-    Vector<MatchedRule, 32>& matchedRules = *m_matchedRules;
+    WillBeHeapVector<MatchedRule, 32>& matchedRules = *m_matchedRules;
     if (m_mode == SelectorChecker::CollectingStyleRules) {
         for (unsigned i = 0; i < matchedRules.size(); ++i)
             ensureStyleRuleList()->m_list.append(matchedRules[i].ruleData()->rule());
diff --git a/Source/core/css/ElementRuleCollector.h b/Source/core/css/ElementRuleCollector.h
index 5c169b6..cea3352 100644
--- a/Source/core/css/ElementRuleCollector.h
+++ b/Source/core/css/ElementRuleCollector.h
@@ -47,9 +47,9 @@
 const CascadeOrder ignoreCascadeOrder = 0;
 
 class MatchedRule {
-    WTF_MAKE_FAST_ALLOCATED;
+    ALLOW_ONLY_INLINE_ALLOCATION();
 public:
-    explicit MatchedRule(const RuleData* ruleData, unsigned specificity, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex, const CSSStyleSheet* parentStyleSheet)
+    MatchedRule(const RuleData* ruleData, unsigned specificity, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex, const CSSStyleSheet* parentStyleSheet)
         : m_ruleData(ruleData)
         , m_specificity(specificity)
         , m_cascadeScope(cascadeScope)
@@ -66,15 +66,37 @@
     uint64_t position() const { return m_position; }
     unsigned specificity() const { return ruleData()->specificity() + m_specificity; }
     const CSSStyleSheet* parentStyleSheet() const { return m_parentStyleSheet; }
+    void trace(Visitor* visitor)
+    {
+        visitor->trace(m_parentStyleSheet);
+    }
 
 private:
+    // FIXME: Oilpan: RuleData is in the oilpan heap and this pointer
+    // really should be traced. However, RuleData objects are
+    // allocated inside larger TerminatedArray objects and we cannot
+    // trace a raw rule data pointer at this point.
     const RuleData* m_ruleData;
     unsigned m_specificity;
     CascadeScope m_cascadeScope;
     uint64_t m_position;
-    const CSSStyleSheet* m_parentStyleSheet;
+    RawPtrWillBeMember<const CSSStyleSheet> m_parentStyleSheet;
 };
 
+} // namespace WebCore
+
+
+namespace WTF {
+
+template <> struct VectorTraits<WebCore::MatchedRule> : VectorTraitsBase<WebCore::MatchedRule> {
+    static const bool canInitializeWithMemset = true;
+    static const bool canMoveWithMemcpy = true;
+};
+
+} // namespace WTF
+
+namespace WebCore {
+
 // FIXME: oilpan: when transition types are gone this class can be replaced with HeapVector.
 class StyleRuleList : public RefCounted<StyleRuleList> {
 public:
@@ -150,7 +172,7 @@
     bool m_sameOriginOnly;
     bool m_matchingUARules;
 
-    OwnPtr<Vector<MatchedRule, 32> > m_matchedRules;
+    OwnPtrWillBeMember<WillBeHeapVector<MatchedRule, 32> > m_matchedRules;
 
     // Output.
     RefPtrWillBeMember<StaticCSSRuleList> m_cssRuleList;
diff --git a/Source/core/css/FontFace.cpp b/Source/core/css/FontFace.cpp
index 34d2095..9083eed 100644
--- a/Source/core/css/FontFace.cpp
+++ b/Source/core/css/FontFace.cpp
@@ -101,7 +101,7 @@
 {
     if (s.isEmpty())
         return nullptr;
-    RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
     BisonCSSParser::parseValue(parsedStyle.get(), propertyID, s, true, *document);
     return parsedStyle->getPropertyCSSValue(propertyID);
 }
@@ -378,11 +378,45 @@
     m_status = status;
     if (m_status == Error)
         m_error = DOMError::create(NetworkError);
-    if (m_status == Loaded || m_status == Error)
+    if (m_status == Loaded || m_status == Error) {
         resolveReadyPromises();
+
+        Vector<RefPtr<LoadFontCallback> > callbacks;
+        m_callbacks.swap(callbacks);
+        for (size_t i = 0; i < callbacks.size(); ++i) {
+            if (m_status == Loaded)
+                callbacks[i]->notifyLoaded(this);
+            else
+                callbacks[i]->notifyError(this);
+        }
+    }
 }
 
-void FontFace::load(ExecutionContext* context)
+ScriptPromise FontFace::load(ExecutionContext* context)
+{
+    OwnPtr<FontFaceReadyPromiseResolver> resolver = FontFaceReadyPromiseResolver::create(context);
+    ScriptPromise promise = resolver->promise();
+    if (m_status == Loaded || m_status == Error)
+        resolver->resolve(this);
+    else
+        m_readyResolvers.append(resolver.release());
+
+    loadInternal(context);
+    return promise;
+}
+
+void FontFace::loadWithCallback(PassRefPtr<LoadFontCallback> callback, ExecutionContext* context)
+{
+    loadInternal(context);
+    if (m_status == Loaded)
+        callback->notifyLoaded(this);
+    else if (m_status == Error)
+        callback->notifyError(this);
+    else
+        m_callbacks.append(callback);
+}
+
+void FontFace::loadInternal(ExecutionContext* context)
 {
     if (m_status != Unloaded)
         return;
@@ -398,17 +432,6 @@
     fontSelector->loadPendingFonts();
 }
 
-ScriptPromise FontFace::ready(ExecutionContext* context)
-{
-    OwnPtr<FontFaceReadyPromiseResolver> resolver = FontFaceReadyPromiseResolver::create(context);
-    ScriptPromise promise = resolver->promise();
-    if (m_status == Loaded || m_status == Error)
-        resolver->resolve(this);
-    else
-        m_readyResolvers.append(resolver.release());
-    return promise;
-}
-
 void FontFace::resolveReadyPromises()
 {
     for (size_t i = 0; i < m_readyResolvers.size(); i++)
diff --git a/Source/core/css/FontFace.h b/Source/core/css/FontFace.h
index 5379cff..94a4aad 100644
--- a/Source/core/css/FontFace.h
+++ b/Source/core/css/FontFace.h
@@ -81,8 +81,7 @@
 
     String status() const;
 
-    void load(ExecutionContext*);
-    ScriptPromise ready(ExecutionContext*);
+    ScriptPromise load(ExecutionContext*);
 
     LoadStatus loadStatus() const { return m_status; }
     void setLoadStatus(LoadStatus);
@@ -94,6 +93,14 @@
 
     bool hadBlankText() const;
 
+    class LoadFontCallback : public RefCounted<LoadFontCallback> {
+    public:
+        virtual ~LoadFontCallback() { }
+        virtual void notifyLoaded(FontFace*) = 0;
+        virtual void notifyError(FontFace*) = 0;
+    };
+    void loadWithCallback(PassRefPtr<LoadFontCallback>, ExecutionContext*);
+
 private:
     FontFace();
 
@@ -104,6 +111,7 @@
     bool setPropertyValue(PassRefPtrWillBeRawPtr<CSSValue>, CSSPropertyID);
     bool setFamilyValue(CSSValueList*);
     void resolveReadyPromises();
+    void loadInternal(ExecutionContext*);
 
     AtomicString m_family;
     RefPtrWillBeMember<CSSValue> m_src;
@@ -118,6 +126,7 @@
 
     Vector<OwnPtr<FontFaceReadyPromiseResolver> > m_readyResolvers;
     OwnPtr<CSSFontFace> m_cssFontFace;
+    Vector<RefPtr<LoadFontCallback> > m_callbacks;
 };
 
 typedef Vector<RefPtr<FontFace> > FontFaceArray;
diff --git a/Source/core/css/FontFace.idl b/Source/core/css/FontFace.idl
index a3a0809..638b82f 100644
--- a/Source/core/css/FontFace.idl
+++ b/Source/core/css/FontFace.idl
@@ -54,6 +54,5 @@
 
     readonly attribute FontFaceLoadStatus status;
 
-    [CallWith=ExecutionContext] void load();
-    [CallWith=ExecutionContext] Promise ready();
+    [CallWith=ExecutionContext] Promise load();
 };
diff --git a/Source/core/css/FontFaceSet.cpp b/Source/core/css/FontFaceSet.cpp
index 54e200d..f147f91 100644
--- a/Source/core/css/FontFaceSet.cpp
+++ b/Source/core/css/FontFaceSet.cpp
@@ -49,54 +49,65 @@
 static const int defaultFontSize = 10;
 static const char defaultFontFamily[] = "sans-serif";
 
-class LoadFontPromiseResolver : public CSSSegmentedFontFace::LoadFontCallback {
+class LoadFontPromiseResolver : public FontFace::LoadFontCallback {
 public:
-    static PassRefPtr<LoadFontPromiseResolver> create(const FontFamily& family, ExecutionContext* context)
+    static PassRefPtr<LoadFontPromiseResolver> create(FontFaceArray faces, ExecutionContext* context)
     {
-        int numFamilies = 0;
-        for (const FontFamily* f = &family; f; f = f->next())
-            numFamilies++;
-        return adoptRef<LoadFontPromiseResolver>(new LoadFontPromiseResolver(numFamilies, context));
+        return adoptRef(new LoadFontPromiseResolver(faces, context));
     }
 
+    void loadFonts(ExecutionContext*);
     ScriptPromise promise() { return m_resolver->promise(); }
 
-    virtual void notifyLoaded(CSSSegmentedFontFace*) OVERRIDE { loaded(); }
-    virtual void notifyError(CSSSegmentedFontFace*) OVERRIDE { error(); }
-    void loaded();
-    void error();
+    virtual void notifyLoaded(FontFace*) OVERRIDE;
+    virtual void notifyError(FontFace*) OVERRIDE;
 
 private:
-    LoadFontPromiseResolver(int numLoading, ExecutionContext* context)
-        : m_numLoading(numLoading)
+    LoadFontPromiseResolver(FontFaceArray faces, ExecutionContext* context)
+        : m_numLoading(faces.size())
         , m_errorOccured(false)
         , m_scriptState(ScriptState::current())
         , m_resolver(ScriptPromiseResolver::create(context))
-    { }
+    {
+        m_fontFaces.swap(faces);
+    }
 
+    FontFaceArray m_fontFaces;
     int m_numLoading;
     bool m_errorOccured;
     ScriptState* m_scriptState;
     RefPtr<ScriptPromiseResolver> m_resolver;
 };
 
-void LoadFontPromiseResolver::loaded()
+void LoadFontPromiseResolver::loadFonts(ExecutionContext* context)
+{
+    if (!m_numLoading) {
+        m_resolver->resolve(m_fontFaces);
+        return;
+    }
+
+    for (size_t i = 0; i < m_fontFaces.size(); i++)
+        m_fontFaces[i]->loadWithCallback(this, context);
+}
+
+void LoadFontPromiseResolver::notifyLoaded(FontFace* fontFace)
 {
     m_numLoading--;
-    if (m_numLoading)
+    if (m_numLoading || m_errorOccured)
         return;
 
     ScriptScope scope(m_scriptState);
-    if (m_errorOccured)
-        m_resolver->reject(ScriptValue::createNull());
-    else
-        m_resolver->resolve(ScriptValue::createNull());
+    m_resolver->resolve(m_fontFaces);
 }
 
-void LoadFontPromiseResolver::error()
+void LoadFontPromiseResolver::notifyError(FontFace* fontFace)
 {
-    m_errorOccured = true;
-    loaded();
+    m_numLoading--;
+    if (!m_errorOccured) {
+        m_errorOccured = true;
+        ScriptScope scope(m_scriptState);
+        m_resolver->reject(fontFace->error());
+    }
 }
 
 class FontsReadyPromiseResolver {
@@ -423,30 +434,30 @@
     return s.isNull() ? space : s;
 }
 
-ScriptPromise FontFaceSet::load(const String& fontString, const String& text, ExceptionState& exceptionState)
+ScriptPromise FontFaceSet::load(const String& fontString, const String& text)
 {
     if (!inActiveDocumentContext())
         return ScriptPromise();
 
     Font font;
     if (!resolveFontStyle(fontString, font)) {
-        exceptionState.throwDOMException(SyntaxError, "Could not resolve '" + fontString + "' as a font.");
-        return ScriptPromise();
+        RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(executionContext());
+        ScriptPromise promise = resolver->promise();
+        resolver->reject(DOMError::create(SyntaxError, "Could not resolve '" + fontString + "' as a font."));
+        return promise;
     }
 
-    CSSFontSelector* fontSelector = document()->styleEngine()->fontSelector();
-    FontFaceCache* fontFaceCache = fontSelector->fontFaceCache();
-    RefPtr<LoadFontPromiseResolver> resolver = LoadFontPromiseResolver::create(font.fontDescription().family(), executionContext());
-    ScriptPromise promise = resolver->promise();
+    FontFaceCache* fontFaceCache = document()->styleEngine()->fontSelector()->fontFaceCache();
+    FontFaceArray faces;
     for (const FontFamily* f = &font.fontDescription().family(); f; f = f->next()) {
-        CSSSegmentedFontFace* face = fontFaceCache->get(font.fontDescription(), f->family());
-        if (!face) {
-            resolver->error();
-            continue;
-        }
-        face->loadFont(font.fontDescription(), nullToSpace(text), resolver);
+        CSSSegmentedFontFace* segmentedFontFace = fontFaceCache->get(font.fontDescription(), f->family());
+        if (segmentedFontFace)
+            segmentedFontFace->match(nullToSpace(text), faces);
     }
-    fontSelector->loadPendingFonts();
+
+    RefPtr<LoadFontPromiseResolver> resolver = LoadFontPromiseResolver::create(faces, executionContext());
+    ScriptPromise promise = resolver->promise();
+    resolver->loadFonts(executionContext()); // After this, resolver->promise() may return null.
     return promise;
 }
 
@@ -476,7 +487,7 @@
         return false;
 
     // Interpret fontString in the same way as the 'font' attribute of CanvasRenderingContext2D.
-    RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
     BisonCSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, HTMLStandardMode, 0);
     if (parsedStyle->isEmpty())
         return false;
diff --git a/Source/core/css/FontFaceSet.h b/Source/core/css/FontFaceSet.h
index 3303a26..298a67e 100644
--- a/Source/core/css/FontFaceSet.h
+++ b/Source/core/css/FontFaceSet.h
@@ -68,7 +68,7 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(loadingerror);
 
     bool check(const String& font, const String& text, ExceptionState&);
-    ScriptPromise load(const String& font, const String& text, ExceptionState&);
+    ScriptPromise load(const String& font, const String& text);
     ScriptPromise ready();
 
     void add(FontFace*, ExceptionState&);
diff --git a/Source/core/css/FontFaceSet.idl b/Source/core/css/FontFaceSet.idl
index 7f5b6ce..b17e7fc 100644
--- a/Source/core/css/FontFaceSet.idl
+++ b/Source/core/css/FontFaceSet.idl
@@ -42,7 +42,7 @@
     attribute EventHandler onloadingerror;
 
     [RaisesException] boolean check(DOMString font, [Default=NullString] optional DOMString text);
-    [RaisesException] Promise load(DOMString font, [Default=NullString] optional DOMString text);
+    Promise load(DOMString font, [Default=NullString] optional DOMString text);
     Promise ready();
 
     [RaisesException] void add(FontFace fontFace);
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.cpp b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
index 0f09c42..b948d36 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.cpp
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
@@ -296,7 +296,7 @@
     return cssStyleSheet ? cssStyleSheet->contents() : 0;
 }
 
-PassRefPtr<MutableStylePropertySet> AbstractPropertySetCSSStyleDeclaration::copyProperties() const
+PassRefPtrWillBeRawPtr<MutableStylePropertySet> AbstractPropertySetCSSStyleDeclaration::copyProperties() const
 {
     return propertySet().mutableCopy();
 }
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.h b/Source/core/css/PropertySetCSSStyleDeclaration.h
index 1bc15a9..ad87376 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.h
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.h
@@ -64,7 +64,7 @@
     virtual void setPropertyInternal(CSSPropertyID, const String& value, bool important, ExceptionState&) OVERRIDE FINAL;
 
     virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const OVERRIDE FINAL;
-    virtual PassRefPtr<MutableStylePropertySet> copyProperties() const OVERRIDE FINAL;
+    virtual PassRefPtrWillBeRawPtr<MutableStylePropertySet> copyProperties() const OVERRIDE FINAL;
 
     CSSValue* cloneAndCacheForCSSOM(CSSValue*);
 
diff --git a/Source/core/css/RuleFeature.cpp b/Source/core/css/RuleFeature.cpp
index 7b57fdc..d03bb12 100644
--- a/Source/core/css/RuleFeature.cpp
+++ b/Source/core/css/RuleFeature.cpp
@@ -105,8 +105,6 @@
     default:
         return false;
     }
-    ASSERT_NOT_REACHED();
-    return false;
 }
 
 // This method is somewhat conservative in what it accepts.
diff --git a/Source/core/css/SelectorChecker.cpp b/Source/core/css/SelectorChecker.cpp
index c6e5f46..4215a91 100644
--- a/Source/core/css/SelectorChecker.cpp
+++ b/Source/core/css/SelectorChecker.cpp
@@ -293,7 +293,7 @@
     case CSSSelector::IndirectAdjacent:
         if (m_mode == ResolvingStyle) {
             if (Node* parent = context.element->parentElementOrShadowRoot())
-                SiblingRuleHelper(parent).setChildrenAffectedByForwardPositionalRules();
+                SiblingRuleHelper(parent).setChildrenAffectedByIndirectAdjacentRules();
         }
         nextContext.element = ElementTraversal::previousSibling(*context.element);
         nextContext.isSubSelector = false;
@@ -837,7 +837,7 @@
             // element is an element in the document, the 'full-screen' pseudoclass applies to
             // that element. Also, an <iframe>, <object> or <embed> element whose child browsing
             // context's Document is in the fullscreen state has the 'full-screen' pseudoclass applied.
-            if (element.isFrameElementBase() && element.containsFullScreenElement())
+            if (isHTMLFrameElementBase(element) && element.containsFullScreenElement())
                 return true;
             if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(element.document())) {
                 if (!fullscreen->webkitIsFullScreen())
@@ -904,21 +904,23 @@
                     subContext.scope = shadowHost;
                     // Use NodeRenderingTraversal to traverse a composed ancestor list of a given element.
                     Element* nextElement = &element;
+                    SelectorCheckingContext hostContext(subContext);
                     do {
                         MatchResult subResult;
-                        subContext.element = nextElement;
-                        if (match(subContext, siblingTraversalStrategy, &subResult) == SelectorMatches) {
+                        hostContext.element = nextElement;
+                        if (match(hostContext, siblingTraversalStrategy, &subResult) == SelectorMatches) {
                             matched = true;
                             // Consider div:host(div:host(div:host(div:host...))).
-                            maxSpecificity = std::max(maxSpecificity, subContext.selector->specificity() + subResult.specificity);
+                            maxSpecificity = std::max(maxSpecificity, hostContext.selector->specificity() + subResult.specificity);
                             break;
                         }
-                        subContext.behaviorAtBoundary = DoesNotCrossBoundary;
-                        subContext.scope = 0;
+                        hostContext.behaviorAtBoundary = DoesNotCrossBoundary;
+                        hostContext.scope = 0;
 
                         if (selector.pseudoType() == CSSSelector::PseudoHost)
                             break;
 
+                        hostContext.elementStyle = 0;
                         nextElement = NodeRenderingTraversal::parentElement(nextElement);
                     } while (nextElement);
                 }
diff --git a/Source/core/css/StylePropertySet.cpp b/Source/core/css/StylePropertySet.cpp
index b7e7972..b943212 100644
--- a/Source/core/css/StylePropertySet.cpp
+++ b/Source/core/css/StylePropertySet.cpp
@@ -162,7 +162,7 @@
 }
 
 #if ENABLE(OILPAN)
-void StylePropertySet::finalize()
+void StylePropertySet::finalizeGarbageCollectedObject()
 {
     if (m_isMutable)
         toMutableStylePropertySet(this)->~MutableStylePropertySet();
@@ -431,7 +431,7 @@
     m_propertyVector.clear();
 }
 
-PassRefPtr<MutableStylePropertySet> StylePropertySet::copyBlockProperties() const
+PassRefPtrWillBeRawPtr<MutableStylePropertySet> StylePropertySet::copyBlockProperties() const
 {
     return copyPropertiesInSet(blockProperties());
 }
@@ -514,12 +514,12 @@
         removeProperty(propertiesToRemove[i]);
 }
 
-PassRefPtr<MutableStylePropertySet> StylePropertySet::mutableCopy() const
+PassRefPtrWillBeRawPtr<MutableStylePropertySet> StylePropertySet::mutableCopy() const
 {
     return adoptRefWillBeRefCountedGarbageCollected(new MutableStylePropertySet(*this));
 }
 
-PassRefPtr<MutableStylePropertySet> StylePropertySet::copyPropertiesInSet(const Vector<CSSPropertyID>& properties) const
+PassRefPtrWillBeRawPtr<MutableStylePropertySet> StylePropertySet::copyPropertiesInSet(const Vector<CSSPropertyID>& properties) const
 {
     WillBeHeapVector<CSSProperty, 256> list;
     list.reserveInitialCapacity(properties.size());
@@ -585,12 +585,12 @@
 }
 #endif
 
-PassRefPtr<MutableStylePropertySet> MutableStylePropertySet::create(CSSParserMode cssParserMode)
+PassRefPtrWillBeRawPtr<MutableStylePropertySet> MutableStylePropertySet::create(CSSParserMode cssParserMode)
 {
     return adoptRefWillBeRefCountedGarbageCollected(new MutableStylePropertySet(cssParserMode));
 }
 
-PassRefPtr<MutableStylePropertySet> MutableStylePropertySet::create(const CSSProperty* properties, unsigned count)
+PassRefPtrWillBeRawPtr<MutableStylePropertySet> MutableStylePropertySet::create(const CSSProperty* properties, unsigned count)
 {
     return adoptRefWillBeRefCountedGarbageCollected(new MutableStylePropertySet(properties, count));
 }
diff --git a/Source/core/css/StylePropertySet.h b/Source/core/css/StylePropertySet.h
index 549cc98..c7bb81a 100644
--- a/Source/core/css/StylePropertySet.h
+++ b/Source/core/css/StylePropertySet.h
@@ -49,7 +49,7 @@
     // When oilpan is enabled override the finalize method to dispatch to the subclasses'
     // destructor. This can be removed once the MutableStylePropertySet's OwnPtr is moved
     // to the heap.
-    void finalize();
+    void finalizeGarbageCollectedObject();
 #else
     // Override RefCounted's deref() to ensure operator delete is called on
     // the appropriate subclass type.
@@ -102,14 +102,14 @@
     CSSPropertyID getPropertyShorthand(CSSPropertyID) const;
     bool isPropertyImplicit(CSSPropertyID) const;
 
-    PassRefPtr<MutableStylePropertySet> copyBlockProperties() const;
+    PassRefPtrWillBeRawPtr<MutableStylePropertySet> copyBlockProperties() const;
 
     CSSParserMode cssParserMode() const { return static_cast<CSSParserMode>(m_cssParserMode); }
 
-    PassRefPtr<MutableStylePropertySet> mutableCopy() const;
+    PassRefPtrWillBeRawPtr<MutableStylePropertySet> mutableCopy() const;
     PassRefPtr<ImmutableStylePropertySet> immutableCopyIfNeeded() const;
 
-    PassRefPtr<MutableStylePropertySet> copyPropertiesInSet(const Vector<CSSPropertyID>&) const;
+    PassRefPtrWillBeRawPtr<MutableStylePropertySet> copyPropertiesInSet(const Vector<CSSPropertyID>&) const;
 
     String asText() const;
 
@@ -195,8 +195,8 @@
 class MutableStylePropertySet : public StylePropertySet {
 public:
     ~MutableStylePropertySet() { }
-    static PassRefPtr<MutableStylePropertySet> create(CSSParserMode = HTMLQuirksMode);
-    static PassRefPtr<MutableStylePropertySet> create(const CSSProperty* properties, unsigned count);
+    static PassRefPtrWillBeRawPtr<MutableStylePropertySet> create(CSSParserMode = HTMLQuirksMode);
+    static PassRefPtrWillBeRawPtr<MutableStylePropertySet> create(const CSSProperty* properties, unsigned count);
 
     unsigned propertyCount() const { return m_propertyVector.size(); }
 
diff --git a/Source/core/css/StyleRule.cpp b/Source/core/css/StyleRule.cpp
index 08e62bd..3465b2c 100644
--- a/Source/core/css/StyleRule.cpp
+++ b/Source/core/css/StyleRule.cpp
@@ -91,7 +91,7 @@
     ASSERT_NOT_REACHED();
 }
 
-void StyleRuleBase::finalize()
+void StyleRuleBase::finalizeGarbageCollectedObject()
 {
     switch (type()) {
     case Style:
diff --git a/Source/core/css/StyleRule.h b/Source/core/css/StyleRule.h
index 12d2e40..da767ba 100644
--- a/Source/core/css/StyleRule.h
+++ b/Source/core/css/StyleRule.h
@@ -82,7 +82,7 @@
 
     void trace(Visitor*);
     void traceAfterDispatch(Visitor*) { };
-    void finalize();
+    void finalizeGarbageCollectedObject();
 
 protected:
     StyleRuleBase(Type type) : m_type(type) { }
diff --git a/Source/core/css/StyleSheet.h b/Source/core/css/StyleSheet.h
index e92a7d6..8229de2 100644
--- a/Source/core/css/StyleSheet.h
+++ b/Source/core/css/StyleSheet.h
@@ -34,7 +34,7 @@
 class Node;
 class StyleSheet;
 
-class StyleSheet : public RefCountedWillBeRefCountedGarbageCollected<StyleSheet> {
+class StyleSheet : public RefCountedWillBeGarbageCollectedFinalized<StyleSheet> {
 public:
     virtual ~StyleSheet();
 
diff --git a/Source/core/css/StyleSheet.idl b/Source/core/css/StyleSheet.idl
index 1071475..ed83f14 100644
--- a/Source/core/css/StyleSheet.idl
+++ b/Source/core/css/StyleSheet.idl
@@ -22,6 +22,7 @@
 [
     Custom=Wrap,
     SetWrapperReferenceFrom=ownerNode,
+    WillBeGarbageCollected
 ] interface StyleSheet {
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString        type;
              attribute boolean          disabled;
diff --git a/Source/core/css/StyleSheetContents.cpp b/Source/core/css/StyleSheetContents.cpp
index 091de77..3903c26 100644
--- a/Source/core/css/StyleSheetContents.cpp
+++ b/Source/core/css/StyleSheetContents.cpp
@@ -66,6 +66,7 @@
     , m_isInMemoryCache(false)
     , m_hasFontFaceRule(false)
     , m_hasMediaQueries(false)
+    , m_hasSingleOwnerDocument(true)
     , m_parserContext(context)
 {
 }
@@ -84,6 +85,7 @@
     , m_isInMemoryCache(false)
     , m_hasFontFaceRule(o.m_hasFontFaceRule)
     , m_hasMediaQueries(o.m_hasMediaQueries)
+    , m_hasSingleOwnerDocument(true)
     , m_parserContext(o.m_parserContext)
 {
     ASSERT(o.isCacheable());
@@ -98,20 +100,24 @@
 StyleSheetContents::~StyleSheetContents()
 {
 #if !ENABLE(OILPAN)
-    StyleEngine::removeSheet(this);
     clearRules();
 #endif
 }
 
 void StyleSheetContents::setHasSyntacticallyValidCSSHeader(bool isValidCss)
 {
-    if (maybeCacheable() && !isValidCss)
-        StyleEngine::removeSheet(this);
+    if (!isValidCss) {
+        if (Document* document = clientSingleOwnerDocument())
+            removeSheetFromCache(document);
+    }
     m_hasSyntacticallyValidCSSHeader = isValidCss;
 }
 
-bool StyleSheetContents::maybeCacheable() const
+bool StyleSheetContents::isCacheable() const
 {
+    // This would require dealing with multiple clients for load callbacks.
+    if (!loadCompleted())
+        return false;
     // FIXME: StyleSheets with media queries can't be cached because their RuleSet
     // is processed differently based off the media queries, which might resolve
     // differently depending on the context of the parent CSSStyleSheet (e.g.
@@ -137,14 +143,6 @@
     return true;
 }
 
-bool StyleSheetContents::isCacheable() const
-{
-    // This would require dealing with multiple clients for load callbacks.
-    if (!loadCompleted())
-        return false;
-    return maybeCacheable();
-}
-
 void StyleSheetContents::parserAppendRule(PassRefPtrWillBeRawPtr<StyleRuleBase> rule)
 {
     ASSERT(!rule->isCharsetRule());
@@ -471,8 +469,8 @@
 
 Document* StyleSheetContents::singleOwnerDocument() const
 {
-    Node* ownerNode = singleOwnerNode();
-    return ownerNode ? &ownerNode->document() : 0;
+    StyleSheetContents* root = rootStyleSheet();
+    return root->clientSingleOwnerDocument();
 }
 
 KURL StyleSheetContents::completeURL(const String& url) const
@@ -520,6 +518,16 @@
     return childRulesHaveFailedOrCanceledSubresources(m_childRules);
 }
 
+Document* StyleSheetContents::clientSingleOwnerDocument() const
+{
+    if (!m_hasSingleOwnerDocument || clientSize() <= 0)
+        return 0;
+
+    if (m_loadingClients.size())
+        return (*m_loadingClients.begin())->ownerDocument();
+    return (*m_completedClients.begin())->ownerDocument();
+}
+
 StyleSheetContents* StyleSheetContents::parentStyleSheet() const
 {
     return m_ownerRule ? m_ownerRule->parentStyleSheet() : 0;
@@ -528,20 +536,41 @@
 void StyleSheetContents::registerClient(CSSStyleSheet* sheet)
 {
     ASSERT(!m_loadingClients.contains(sheet) && !m_completedClients.contains(sheet));
+
+    // InspectorCSSAgent::buildObjectForRule and document.implementation.createCSSStyleSheet
+    // creates CSSStyleSheet without any owner node.
+    if (!sheet->ownerDocument())
+        return;
+
+    if (Document* document = clientSingleOwnerDocument()) {
+        if (sheet->ownerDocument() != document)
+            m_hasSingleOwnerDocument = false;
+    }
     m_loadingClients.add(sheet);
 }
 
 void StyleSheetContents::unregisterClient(CSSStyleSheet* sheet)
 {
-    ASSERT(m_loadingClients.contains(sheet) || m_completedClients.contains(sheet));
     m_loadingClients.remove(sheet);
     m_completedClients.remove(sheet);
+
+    if (!sheet->ownerDocument() || !m_loadingClients.isEmpty() || !m_completedClients.isEmpty())
+        return;
+
+    if (m_hasSingleOwnerDocument)
+        removeSheetFromCache(sheet->ownerDocument());
+    m_hasSingleOwnerDocument = true;
 }
 
 void StyleSheetContents::clientLoadCompleted(CSSStyleSheet* sheet)
 {
-    ASSERT(m_loadingClients.contains(sheet));
+    ASSERT(m_loadingClients.contains(sheet) || !sheet->ownerDocument());
     m_loadingClients.remove(sheet);
+    // In m_ownerNode->sheetLoaded, the CSSStyleSheet might be detached.
+    // (i.e. clearOwnerNode was invoked.)
+    // In this case, we don't need to add the stylesheet to completed clients.
+    if (!sheet->ownerDocument())
+        return;
     m_completedClients.add(sheet);
 }
 
@@ -552,6 +581,12 @@
     m_loadingClients.add(sheet);
 }
 
+void StyleSheetContents::removeSheetFromCache(Document* document)
+{
+    ASSERT(document);
+    document->styleEngine()->removeSheet(this);
+}
+
 void StyleSheetContents::addedToMemoryCache()
 {
     ASSERT(!m_isInMemoryCache);
diff --git a/Source/core/css/StyleSheetContents.h b/Source/core/css/StyleSheetContents.h
index 8090f8e..ad289d2 100644
--- a/Source/core/css/StyleSheetContents.h
+++ b/Source/core/css/StyleSheetContents.h
@@ -71,7 +71,6 @@
     bool parseStringAtPosition(const String&, const TextPosition&, bool);
 
     bool isCacheable() const;
-    bool maybeCacheable() const;
 
     bool isLoading() const;
 
@@ -139,19 +138,24 @@
 
     void registerClient(CSSStyleSheet*);
     void unregisterClient(CSSStyleSheet*);
-    bool hasOneClient() { return (m_loadingClients.size() + m_completedClients.size()) == 1; }
+    size_t clientSize() const { return m_loadingClients.size() + m_completedClients.size(); }
+    bool hasOneClient() { return clientSize() == 1; }
     void clientLoadCompleted(CSSStyleSheet*);
     void clientLoadStarted(CSSStyleSheet*);
 
     bool isMutable() const { return m_isMutable; }
     void setMutable() { m_isMutable = true; }
 
+    void removeSheetFromCache(Document*);
+
     bool isInMemoryCache() const { return m_isInMemoryCache; }
     void addedToMemoryCache();
     void removedFromMemoryCache();
 
     void setHasMediaQueries();
-    bool hasMediaQueries() { return m_hasMediaQueries; }
+    bool hasMediaQueries() const { return m_hasMediaQueries; }
+
+    bool didLoadErrorOccur() const { return m_didLoadErrorOccur; }
 
     void shrinkToFit();
     RuleSet& ruleSet() { ASSERT(m_ruleSet); return *m_ruleSet.get(); }
@@ -165,6 +169,7 @@
     StyleSheetContents(const StyleSheetContents&);
     void notifyRemoveFontFaceRule(const StyleRuleFontFace*);
 
+    Document* clientSingleOwnerDocument() const;
     void clearCharsetRule();
 
     RawPtrWillBeMember<StyleRuleImport> m_ownerRule;
@@ -184,6 +189,7 @@
     bool m_isInMemoryCache : 1;
     bool m_hasFontFaceRule : 1;
     bool m_hasMediaQueries : 1;
+    bool m_hasSingleOwnerDocument : 1;
 
     CSSParserContext m_parserContext;
 
diff --git a/Source/core/css/StyleSheetList.cpp b/Source/core/css/StyleSheetList.cpp
index d05babe..4581cb1 100644
--- a/Source/core/css/StyleSheetList.cpp
+++ b/Source/core/css/StyleSheetList.cpp
@@ -49,6 +49,11 @@
 
 void StyleSheetList::detachFromDocument()
 {
+    // FIXME: Oilpan: This is safe currently because the Document is
+    // *not* in the oilpan heap and the style engine is alive when the
+    // document dies. When the Document is in the oilpan heap, we need
+    // the StyleSheetList and the document to die together and get rid
+    // of the detachedStyleSheets.
     m_detachedStyleSheets = document()->styleEngine()->styleSheetsForStyleSheetList(*m_treeScope);
     m_treeScope = 0;
 }
diff --git a/Source/core/css/html.css b/Source/core/css/html.css
index bea688b..2e90588 100644
--- a/Source/core/css/html.css
+++ b/Source/core/css/html.css
@@ -686,7 +686,7 @@
     text-align: start !important;
 }
 
-input:-webkit-autofill, textarea:-webkit-autofill {
+input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill {
     background-color: #FAFFBD !important;
     background-image:none !important;
     color: #000000 !important;
diff --git a/Source/core/css/mathml.css b/Source/core/css/mathml.css
new file mode 100644
index 0000000..cef10e3
--- /dev/null
+++ b/Source/core/css/mathml.css
@@ -0,0 +1,49 @@
+/*
+ * The default style sheet used to render MathML.
+ *
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+@namespace "http://www.w3.org/1998/Math/MathML";
+
+/* By default, we only display the MathML formulas without any formatting other than the one specified by the display attribute. */
+math {
+    display: inline;
+}
+
+math[display="block"] {
+    display: block;
+    text-align: center;
+}
+
+/* We hide the PresentationExpression constructions that are children of a <semantics> element.
+   http://www.w3.org/TR/MathML/appendixa.html#parsing_PresentationExpression */
+semantics > mi, semantics > mn, semantics > mo, semantics > mtext, semantics > mspace, semantics > ms, semantics > maligngroup, semantics > malignmark, semantics > mrow, semantics > mfrac, semantics > msqrt, semantics > mroot, semantics > mstyle, semantics > merror, semantics > mpadded, semantics > mphantom, semantics > mfenced, semantics > menclose, semantics > msub, semantics > msup, semantics > msubsup, semantics > munder, semantics > mover, semantics > munderover, semantics > mmultiscripts, semantics > mtable, semantics > mstack, semantics > mlongdiv, semantics > maction {
+    display: none;
+}
+
+/* However, we display all the annotations. */
+annotation, annotation-xml {
+    display: inline-block;
+}
diff --git a/Source/core/css/parser/BisonCSSParser-in.cpp b/Source/core/css/parser/BisonCSSParser-in.cpp
index 8ab5561..b0df31b 100644
--- a/Source/core/css/parser/BisonCSSParser-in.cpp
+++ b/Source/core/css/parser/BisonCSSParser-in.cpp
@@ -993,7 +993,7 @@
 {
     if (string.isEmpty())
         return nullptr;
-    RefPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
     if (!parseValue(dummyStyle.get(), CSSPropertyFontFamily, string, false, HTMLQuirksMode, 0))
         return nullptr;
 
@@ -1008,7 +1008,7 @@
 {
     if (string.isEmpty())
         return nullptr;
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     if (!parseValue(style.get(), CSSPropertyAnimationTimingFunction, string, false, HTMLStandardMode, 0))
         return nullptr;
 
diff --git a/Source/core/css/parser/CSSPropertyParser.cpp b/Source/core/css/parser/CSSPropertyParser.cpp
index 89f3140..44d4a11 100644
--- a/Source/core/css/parser/CSSPropertyParser.cpp
+++ b/Source/core/css/parser/CSSPropertyParser.cpp
@@ -4150,7 +4150,7 @@
     ASSERT(args);
 
     // circle(radius)
-    // circle(radius at <position>
+    // circle(radius at <position>)
     // circle(at <position>)
     // where position defines centerX and centerY using a CSS <position> data type.
     RefPtrWillBeRawPtr<CSSBasicShapeCircle> shape = CSSBasicShapeCircle::create();
@@ -4171,10 +4171,9 @@
             return nullptr;
         }
 
-        if (argument->id == CSSValueAt) {
+        if (argument->id == CSSValueAt && args->next()) {
             RefPtrWillBeRawPtr<CSSValue> centerX;
             RefPtrWillBeRawPtr<CSSValue> centerY;
-            args->next(); // set list to start of position center
             parseFillPosition(args, centerX, centerY);
             if (centerX && centerY && !args->current()) {
                 ASSERT(centerX->isPrimitiveValue());
@@ -4247,9 +4246,9 @@
     ASSERT(args);
 
     // ellipse(radiusX)
-    // ellipse(radiusX at <position>
+    // ellipse(radiusX at <position>)
     // ellipse(radiusX radiusY)
-    // ellipse(radiusX radiusY at <position>
+    // ellipse(radiusX radiusY at <position>)
     // ellipse(at <position>)
     // where position defines centerX and centerY using a CSS <position> data type.
     RefPtrWillBeRawPtr<CSSBasicShapeEllipse> shape = CSSBasicShapeEllipse::create();
@@ -4273,11 +4272,10 @@
             return nullptr;
         }
 
-        if (argument->id != CSSValueAt)
+        if (argument->id != CSSValueAt || !args->next()) // expecting ellipse(.. at <position>)
             return nullptr;
         RefPtrWillBeRawPtr<CSSValue> centerX;
         RefPtrWillBeRawPtr<CSSValue> centerY;
-        args->next(); // set list to start of position center
         parseFillPosition(args, centerX, centerY);
         if (!centerX || !centerY || args->current())
             return nullptr;
diff --git a/Source/core/css/parser/MediaQueryTokenizer.cpp b/Source/core/css/parser/MediaQueryTokenizer.cpp
index 4486a4d..fb3a61e 100644
--- a/Source/core/css/parser/MediaQueryTokenizer.cpp
+++ b/Source/core/css/parser/MediaQueryTokenizer.cpp
@@ -11,7 +11,7 @@
 
 namespace WebCore {
 
-const unsigned codePointsNumber = SCHAR_MAX;
+const unsigned codePointsNumber = SCHAR_MAX + 1;
 
 class MediaQueryTokenizer::CodePoints {
 public:
diff --git a/Source/core/css/parser/MediaQueryTokenizerTest.cpp b/Source/core/css/parser/MediaQueryTokenizerTest.cpp
index 1138de9..2adbbf3 100644
--- a/Source/core/css/parser/MediaQueryTokenizerTest.cpp
+++ b/Source/core/css/parser/MediaQueryTokenizerTest.cpp
@@ -24,4 +24,46 @@
     }
 }
 
+void testToken(UChar c, MediaQueryTokenType tokenType)
+{
+    Vector<MediaQueryToken> tokens;
+    StringBuilder input;
+    input.append(c);
+    MediaQueryTokenizer::tokenize(input.toString(), tokens);
+    ASSERT_EQ(tokens[0].type(), tokenType);
+}
+
+TEST(MediaQueryTokenizerCodepointsTest, Basic)
+{
+    for (UChar c = 0; c <= 1000; ++c) {
+        if (isASCIIDigit(c))
+            testToken(c, NumberToken);
+        else if (isASCIIAlpha(c))
+            testToken(c, IdentToken);
+        else if (c == '_')
+            testToken(c, IdentToken);
+        else if (c == '\r' || c == ' ' || c == '\n' || c == '\t' || c == '\f')
+            testToken(c, WhitespaceToken);
+        else if (c == '(')
+            testToken(c, LeftParenthesisToken);
+        else if (c == ')')
+            testToken(c, RightParenthesisToken);
+        else if (c == '.' || c == '+' || c == '-' || c == '/' || c == '\\')
+            testToken(c, DelimiterToken);
+        else if (c == ',')
+            testToken(c, CommaToken);
+        else if (c == ':')
+            testToken(c, ColonToken);
+        else if (c == ';')
+            testToken(c, SemicolonToken);
+        else if (!c)
+            testToken(c, EOFToken);
+        else if (c > SCHAR_MAX)
+            testToken(c, IdentToken);
+        else
+            testToken(c, DelimiterToken);
+    }
+    testToken(USHRT_MAX, IdentToken);
+}
+
 } // namespace
diff --git a/Source/core/css/resolver/AnimatedStyleBuilder.cpp b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
index 50f2f24..7769468 100644
--- a/Source/core/css/resolver/AnimatedStyleBuilder.cpp
+++ b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
@@ -174,7 +174,7 @@
         case CSSPropertyBackgroundImage:
         case CSSPropertyWebkitMaskImage:
             if (layerValue->isImage()) {
-                fillLayer->setImage(toAnimatableImage(layerValue)->toStyleImage());
+                fillLayer->setImage(state.styleImage(property, toAnimatableImage(layerValue)->toCSSValue()));
             } else {
                 ASSERT(toAnimatableUnknown(layerValue)->toCSSValueID() == CSSValueNone);
                 fillLayer->setImage(nullptr);
@@ -297,7 +297,7 @@
         style->setBorderImageSlices(animatableValueToLengthBox(value, state, NonNegativeValues));
         return;
     case CSSPropertyBorderImageSource:
-        style->setBorderImageSource(toAnimatableImage(value)->toStyleImage());
+        style->setBorderImageSource(state.styleImage(property, toAnimatableImage(value)->toCSSValue()));
         return;
     case CSSPropertyBorderImageWidth:
         style->setBorderImageWidth(animatableValueToBorderImageLengthBox(value, state));
@@ -345,8 +345,7 @@
         style->setVisitedLinkColor(toAnimatableColor(value)->visitedLinkColor());
         return;
     case CSSPropertyFillOpacity:
-        // Avoiding a value of 1 forces a layer to be created.
-        style->setFillOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, nextafterf(1, 0)));
+        style->setFillOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
         return;
     case CSSPropertyFill:
         {
@@ -394,7 +393,7 @@
             style->setLineHeight(Length(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0), Percent));
         return;
     case CSSPropertyListStyleImage:
-        style->setListStyleImage(toAnimatableImage(value)->toStyleImage());
+        style->setListStyleImage(state.styleImage(property, toAnimatableImage(value)->toCSSValue()));
         return;
     case CSSPropertyLetterSpacing:
         style->setLetterSpacing(clampTo<float>(toAnimatableDouble(value)->toDouble()));
@@ -537,7 +536,7 @@
         style->setMaskBoxImageSlicesFill(toAnimatableLengthBoxAndBool(value)->flag());
         return;
     case CSSPropertyWebkitMaskBoxImageSource:
-        style->setMaskBoxImageSource(toAnimatableImage(value)->toStyleImage());
+        style->setMaskBoxImageSource(state.styleImage(property, toAnimatableImage(value)->toCSSValue()));
         return;
     case CSSPropertyWebkitMaskBoxImageWidth:
         style->setMaskBoxImageWidth(animatableValueToBorderImageLengthBox(value, state));
@@ -581,8 +580,7 @@
         return;
     case CSSPropertyWebkitTransform: {
         const TransformOperations& operations = toAnimatableTransform(value)->transformOperations();
-        // FIXME: Using identity matrix here when the transform list is empty
-        // forces a layer to be created in the presence of a transform animation.
+        // FIXME: This normalization (handling of 'none') should be performed at input in AnimatableValueFactory.
         style->setTransform(operations.size() ? operations : TransformOperations(true));
         return;
     }
diff --git a/Source/core/css/resolver/ElementResolveContext.cpp b/Source/core/css/resolver/ElementResolveContext.cpp
index 75a1ab1..9d952b4 100644
--- a/Source/core/css/resolver/ElementResolveContext.cpp
+++ b/Source/core/css/resolver/ElementResolveContext.cpp
@@ -33,12 +33,10 @@
     : m_element(&element)
     , m_elementLinkState(element.document().visitedLinkState().determineLinkState(element))
     , m_distributedToInsertionPoint(false)
-    , m_resetStyleInheritance(false)
 {
     NodeRenderingTraversal::ParentDetails parentDetails;
     m_parentNode = NodeRenderingTraversal::parent(&element, &parentDetails);
     m_distributedToInsertionPoint = parentDetails.insertionPoint();
-    m_resetStyleInheritance = parentDetails.resetStyleInheritance();
 
     const Document& document = element.document();
     Node* documentElement = document.documentElement();
diff --git a/Source/core/css/resolver/ElementResolveContext.h b/Source/core/css/resolver/ElementResolveContext.h
index f255e89..04056fe 100644
--- a/Source/core/css/resolver/ElementResolveContext.h
+++ b/Source/core/css/resolver/ElementResolveContext.h
@@ -41,7 +41,6 @@
         , m_rootElementStyle(0)
         , m_elementLinkState(NotInsideLink)
         , m_distributedToInsertionPoint(false)
-        , m_resetStyleInheritance(false)
     {
     }
 
@@ -52,7 +51,6 @@
     const RenderStyle* rootElementStyle() const { return m_rootElementStyle; }
     EInsideLink elementLinkState() const { return m_elementLinkState; }
     bool distributedToInsertionPoint() const { return m_distributedToInsertionPoint; }
-    bool resetStyleInheritance() const { return m_resetStyleInheritance; }
 
 private:
     Element* m_element;
@@ -60,7 +58,6 @@
     RenderStyle* m_rootElementStyle;
     EInsideLink m_elementLinkState;
     bool m_distributedToInsertionPoint;
-    bool m_resetStyleInheritance;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/ElementStyleResources.cpp b/Source/core/css/resolver/ElementStyleResources.cpp
index 2234aac..208468b 100644
--- a/Source/core/css/resolver/ElementStyleResources.cpp
+++ b/Source/core/css/resolver/ElementStyleResources.cpp
@@ -90,6 +90,16 @@
     return image.release();
 }
 
+void ElementStyleResources::clearPendingImageProperties()
+{
+    m_pendingImageProperties.clear();
+}
+
+void ElementStyleResources::clearPendingSVGDocuments()
+{
+    m_pendingSVGDocuments.clear();
+}
+
 void ElementStyleResources::addPendingSVGDocument(FilterOperation* filterOperation, CSSSVGDocumentValue* cssSVGDocumentValue)
 {
     m_pendingSVGDocuments.set(filterOperation, cssSVGDocumentValue);
diff --git a/Source/core/css/resolver/ElementStyleResources.h b/Source/core/css/resolver/ElementStyleResources.h
index b37e6e2..d8bc27a 100644
--- a/Source/core/css/resolver/ElementStyleResources.h
+++ b/Source/core/css/resolver/ElementStyleResources.h
@@ -61,6 +61,9 @@
     const PendingImagePropertyMap& pendingImageProperties() const { return m_pendingImageProperties; }
     const PendingSVGDocumentMap& pendingSVGDocuments() const { return m_pendingSVGDocuments; }
 
+    void clearPendingImageProperties();
+    void clearPendingSVGDocuments();
+
     float deviceScaleFactor() const { return m_deviceScaleFactor; }
     void setDeviceScaleFactor(float deviceScaleFactor) { m_deviceScaleFactor = deviceScaleFactor; }
 
diff --git a/Source/core/css/resolver/FontBuilder.cpp b/Source/core/css/resolver/FontBuilder.cpp
index 7750099..1c03e14 100644
--- a/Source/core/css/resolver/FontBuilder.cpp
+++ b/Source/core/css/resolver/FontBuilder.cpp
@@ -63,6 +63,7 @@
     : m_document(0)
     , m_useSVGZoomRules(false)
     , m_fontSizehasViewportUnits(false)
+    , m_style(0)
     , m_fontDirty(false)
 {
 }
@@ -79,6 +80,21 @@
     m_fontDirty = false;
 }
 
+inline static void setFontFamilyToStandard(FontDescription& fontDescription, const Document* document)
+{
+    if (!document || !document->settings())
+        return;
+
+    fontDescription.setGenericFamily(FontDescription::StandardFamily);
+    const AtomicString& standardFontFamily = document->settings()->genericFontFamilySettings().standard();
+    if (standardFontFamily.isEmpty())
+        return;
+
+    fontDescription.firstFamily().setFamily(standardFontFamily);
+    // FIXME: Why is this needed here?
+    fontDescription.firstFamily().appendFamily(nullptr);
+}
+
 void FontBuilder::setInitial(float effectiveZoom)
 {
     ASSERT(m_document && m_document->settings());
@@ -88,13 +104,8 @@
     FontDescriptionChangeScope scope(this);
 
     scope.reset();
-    scope.fontDescription().setGenericFamily(FontDescription::StandardFamily);
     scope.fontDescription().setUsePrinterFont(m_document->printing());
-    const AtomicString& standardFontFamily = m_document->settings()->genericFontFamilySettings().standard();
-    if (!standardFontFamily.isEmpty()) {
-        scope.fontDescription().firstFamily().setFamily(standardFontFamily);
-        scope.fontDescription().firstFamily().appendFamily(nullptr);
-    }
+    setFontFamilyToStandard(scope.fontDescription(), m_document);
     scope.fontDescription().setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
     setSize(scope.fontDescription(), effectiveZoom, FontSize::fontSizeForKeyword(m_document, CSSValueMedium, false));
 }
@@ -138,14 +149,7 @@
 {
     FontDescriptionChangeScope scope(this);
 
-    FontDescription initialDesc = FontDescription();
-
-    // We need to adjust the size to account for the generic family change from monospace to non-monospace.
-    if (scope.fontDescription().keywordSize() && scope.fontDescription().useFixedDefaultSize())
-        scope.fontDescription().setSpecifiedSize(FontSize::fontSizeForKeyword(m_document, CSSValueXxSmall + scope.fontDescription().keywordSize() - 1, false));
-    scope.fontDescription().setGenericFamily(initialDesc.genericFamily());
-    if (!initialDesc.firstFamily().familyIsEmpty())
-        scope.fontDescription().setFamily(initialDesc.firstFamily());
+    setFontFamilyToStandard(scope.fontDescription(), m_document);
 }
 
 void FontBuilder::setFontFamilyInherit(const FontDescription& parentFontDescription)
@@ -154,7 +158,6 @@
 
     scope.fontDescription().setGenericFamily(parentFontDescription.genericFamily());
     scope.fontDescription().setFamily(parentFontDescription.family());
-    scope.fontDescription().setIsSpecifiedFont(parentFontDescription.isSpecifiedFont());
 }
 
 // FIXME: I am not convinced FontBuilder needs to know anything about CSSValues.
@@ -221,7 +224,6 @@
                 firstFamily.setFamily(face);
                 firstFamily.appendFamily(nullptr); // Remove any inherited family-fallback list.
                 currFamily = &firstFamily;
-                scope.fontDescription().setIsSpecifiedFont(scope.fontDescription().genericFamily() == FontDescription::NoFamily);
             } else {
                 RefPtr<SharedFontFamily> newFamily = SharedFontFamily::create();
                 newFamily->setFamily(face);
@@ -656,21 +658,13 @@
 {
     FontDescription fontDescription = FontDescription();
     fontDescription.setScript(localeToScriptCodeForFontSelection(documentStyle->locale()));
-    if (Settings* settings = m_document->settings()) {
-        fontDescription.setUsePrinterFont(m_document->printing());
-        const AtomicString& standardFont = settings->genericFontFamilySettings().standard(fontDescription.script());
-        if (!standardFont.isEmpty()) {
-            fontDescription.setGenericFamily(FontDescription::StandardFamily);
-            fontDescription.firstFamily().setFamily(standardFont);
-            fontDescription.firstFamily().appendFamily(nullptr);
-        }
-        fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
-        int size = FontSize::fontSizeForKeyword(m_document, CSSValueMedium, false);
-        fontDescription.setSpecifiedSize(size);
-        fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(fontDescription, documentStyle->effectiveZoom(), size));
-    } else {
-        fontDescription.setUsePrinterFont(m_document->printing());
-    }
+    fontDescription.setUsePrinterFont(m_document->printing());
+
+    setFontFamilyToStandard(fontDescription, m_document);
+    fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
+    int size = FontSize::fontSizeForKeyword(m_document, CSSValueMedium, false);
+    fontDescription.setSpecifiedSize(size);
+    fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(fontDescription, documentStyle->effectiveZoom(), size));
 
     FontOrientation fontOrientation;
     NonCJKGlyphOrientation glyphOrientation;
diff --git a/Source/core/css/resolver/FontBuilder.h b/Source/core/css/resolver/FontBuilder.h
index 96f24d2..86d0423 100644
--- a/Source/core/css/resolver/FontBuilder.h
+++ b/Source/core/css/resolver/FontBuilder.h
@@ -90,6 +90,7 @@
     // FIXME: This is only used by an ASSERT in StyleResolver. Remove?
     bool fontDirty() const { return m_fontDirty; }
 
+    static FontDescription::GenericFamilyType initialGenericFamily() { return FontDescription::NoFamily; }
     static TextRenderingMode initialTextRendering() { return AutoTextRendering; }
     static FontVariant initialVariant() { return FontVariantNormal; }
     static FontStyle initialStyle() { return FontStyleNormal; }
@@ -125,6 +126,8 @@
     // is changed, FontBuilder tracks the need to update
     // style->font() with this bool.
     bool m_fontDirty;
+
+    friend class FontBuilderTest;
 };
 
 }
diff --git a/Source/core/css/resolver/FontBuilderTest.cpp b/Source/core/css/resolver/FontBuilderTest.cpp
new file mode 100644
index 0000000..231dc93
--- /dev/null
+++ b/Source/core/css/resolver/FontBuilderTest.cpp
@@ -0,0 +1,26 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/css/resolver/FontBuilder.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+class FontBuilderTest : public ::testing::Test {
+protected:
+    RenderStyle* getStyle(const FontBuilder& builder)
+    {
+        return builder.m_style;
+    }
+};
+
+TEST_F(FontBuilderTest, StylePointerInitialisation)
+{
+    FontBuilder builder;
+    EXPECT_EQ(0, getStyle(builder));
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/resolver/MatchRequest.h b/Source/core/css/resolver/MatchRequest.h
index 652a420..199c906 100644
--- a/Source/core/css/resolver/MatchRequest.h
+++ b/Source/core/css/resolver/MatchRequest.h
@@ -31,6 +31,7 @@
 class ContainerNode;
 
 class MatchRequest {
+    STACK_ALLOCATED();
 public:
     MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0, bool elementApplyAuthorStyles = true, unsigned styleSheetIndex = 0, const CSSStyleSheet* cssSheet = 0)
         : ruleSet(ruleSet)
@@ -45,12 +46,12 @@
         ruleSet->compactRulesIfNeeded();
     }
 
-    const RuleSet* ruleSet;
+    RawPtrWillBeMember<const RuleSet> ruleSet;
     const bool includeEmptyRules;
     const ContainerNode* scope;
     const bool elementApplyAuthorStyles;
     const unsigned styleSheetIndex;
-    const CSSStyleSheet* styleSheet;
+    RawPtrWillBeMember<const CSSStyleSheet> styleSheet;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/ScopedStyleResolver.h b/Source/core/css/resolver/ScopedStyleResolver.h
index 5979088..0c7a88c 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.h
+++ b/Source/core/css/resolver/ScopedStyleResolver.h
@@ -72,7 +72,7 @@
     ContainerNode& m_scopingNode;
     ScopedStyleResolver* m_parent;
 
-    Vector<CSSStyleSheet*> m_authorStyleSheets;
+    WillBePersistentHeapVector<RawPtrWillBeMember<CSSStyleSheet> > m_authorStyleSheets;
 
     typedef WillBePersistentHeapHashMap<const StringImpl*, RefPtrWillBeMember<StyleRuleKeyframes> > KeyframesRuleMap;
     KeyframesRuleMap m_keyframesRuleMap;
diff --git a/Source/core/css/resolver/StyleAdjuster.cpp b/Source/core/css/resolver/StyleAdjuster.cpp
index dae46cd..30abca4 100644
--- a/Source/core/css/resolver/StyleAdjuster.cpp
+++ b/Source/core/css/resolver/StyleAdjuster.cpp
@@ -197,55 +197,8 @@
     style->setOriginalDisplay(style->display());
 
     if (style->display() != NONE) {
-        // If we have a <td> that specifies a float property, in quirks mode we just drop the float
-        // property.
-        // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
-        // these tags to retain their display types.
-        if (m_useQuirksModeStyles && e) {
-            if (e->hasTagName(tdTag)) {
-                style->setDisplay(TABLE_CELL);
-                style->setFloating(NoFloat);
-            } else if (isHTMLTableElement(*e)) {
-                style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
-            }
-        }
-
-        if (e && isHTMLTableCellElement(*e)) {
-            if (style->whiteSpace() == KHTML_NOWRAP) {
-                // Figure out if we are really nowrapping or if we should just
-                // use normal instead. If the width of the cell is fixed, then
-                // we don't actually use NOWRAP.
-                if (style->width().isFixed())
-                    style->setWhiteSpace(NORMAL);
-                else
-                    style->setWhiteSpace(NOWRAP);
-            }
-        }
-
-        // Tables never support the -webkit-* values for text-align and will reset back to the default.
-        if (isHTMLTableElement(e) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
-            style->setTextAlign(TASTART);
-
-        // Frames and framesets never honor position:relative or position:absolute. This is necessary to
-        // fix a crash where a site tries to position these objects. They also never honor display.
-        if (e && (isHTMLFrameElement(*e) || isHTMLFrameSetElement(*e))) {
-            style->setPosition(StaticPosition);
-            style->setDisplay(BLOCK);
-        }
-
-        // Ruby text does not support float or position. This might change with evolution of the specification.
-        if (isHTMLRTElement(e)) {
-            style->setPosition(StaticPosition);
-            style->setFloating(NoFloat);
-        }
-
-        // FIXME: We shouldn't be overriding start/-webkit-auto like this. Do it in html.css instead.
-        // Table headers with a text-align of -webkit-auto will change the text-align to center.
-        if (e && e->hasTagName(thTag) && style->textAlign() == TASTART)
-            style->setTextAlign(CENTER);
-
-        if (isHTMLLegendElement(e))
-            style->setDisplay(BLOCK);
+        if (e)
+            adjustStyleForTagName(style, parentStyle, *e);
 
         // Per the spec, position 'static' and 'relative' in the top layer compute to 'absolute'.
         if (isInTopLayer(e, style) && (style->position() == StaticPosition || style->position() == RelativePosition))
@@ -255,42 +208,7 @@
         if (style->hasOutOfFlowPosition() || style->isFloating() || (e && e->document().documentElement() == e))
             style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), !m_useQuirksModeStyles));
 
-        // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
-        // clear how that should work.
-        if (style->display() == INLINE && style->styleType() == NOPSEUDO && style->writingMode() != parentStyle->writingMode())
-            style->setDisplay(INLINE_BLOCK);
-
-        // After performing the display mutation, check table rows. We do not honor position: relative table rows or cells.
-        // This has been established for position: relative in CSS2.1 (and caused a crash in containingBlock()
-        // on some sites).
-        if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
-            || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW)
-            && style->position() == RelativePosition)
-            style->setPosition(StaticPosition);
-
-        // Cannot support position: sticky for table columns and column groups because current code is only doing
-        // background painting through columns / column groups
-        if ((style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_COLUMN)
-            && style->position() == StickyPosition)
-            style->setPosition(StaticPosition);
-
-        // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
-        // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
-        if (style->display() == TABLE_COLUMN || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_FOOTER_GROUP
-            || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_ROW_GROUP
-            || style->display() == TABLE_CELL)
-            style->setWritingMode(parentStyle->writingMode());
-
-        // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
-        // of block-flow to anything other than TopToBottomWritingMode.
-        // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
-        if (style->writingMode() != TopToBottomWritingMode && (style->display() == BOX || style->display() == INLINE_BOX))
-            style->setWritingMode(TopToBottomWritingMode);
-
-        if (isDisplayFlexibleBox(parentStyle->display()) || isDisplayGridBox(parentStyle->display())) {
-            style->setFloating(NoFloat);
-            style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), !m_useQuirksModeStyles));
-        }
+        adjustStyleForDisplay(style, parentStyle);
     }
 
     // Make sure our z-index value is only applied if the object is positioned.
@@ -323,18 +241,6 @@
         style->setTransform(TransformOperations(makeIdentity));
     }
 
-    // Textarea considers overflow visible as auto.
-    if (isHTMLTextAreaElement(e)) {
-        style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
-        style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
-    }
-
-    // For now, <marquee> requires an overflow clip to work properly.
-    if (isHTMLMarqueeElement(e)) {
-        style->setOverflowX(OHIDDEN);
-        style->setOverflowY(OHIDDEN);
-    }
-
     if (doesNotInheritTextDecoration(style, e))
         style->setTextDecorationsInEffect(style->textDecoration());
     else
@@ -370,21 +276,12 @@
     style->adjustBackgroundLayers();
     style->adjustMaskLayers();
 
-    // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
-    // alter fonts and heights/widths.
-    if (e && e->isFormControlElement() && style->fontSize() >= 11) {
-        // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
-        // so we have to treat all image buttons as though they were explicitly sized.
-        if (!isHTMLInputElement(*e) || !toHTMLInputElement(e)->isImageButton())
-            addIntrinsicMargins(style);
-    }
-
     // Let the theme also have a crack at adjusting the style.
     if (style->hasAppearance())
         RenderTheme::theme().adjustStyle(style, e, m_cachedUAStyle);
 
-    // If we have first-letter pseudo style, do not share this style.
-    if (style->hasPseudoStyle(FIRST_LETTER))
+    // If we have first-letter pseudo style, transitions, or animations, do not share this style.
+    if (style->hasPseudoStyle(FIRST_LETTER) || style->transitions() || style->animations())
         style->setUnique();
 
     // FIXME: when dropping the -webkit prefix on transform-style, we should also have opacity < 1 cause flattening.
@@ -420,4 +317,132 @@
     }
 }
 
+void StyleAdjuster::adjustStyleForTagName(RenderStyle* style, RenderStyle* parentStyle, Element& element)
+{
+    // <div> and <span> are the most common elements on the web, we skip all the work for them.
+    if (isHTMLDivElement(element) || isHTMLSpanElement(element))
+        return;
+
+    if (isHTMLTableCellElement(element)) {
+        // If we have a <td> that specifies a float property, in quirks mode we just drop the float property.
+        // FIXME: Why is this only <td> and not <th>?
+        if (element.hasTagName(tdTag) && m_useQuirksModeStyles) {
+            style->setDisplay(TABLE_CELL);
+            style->setFloating(NoFloat);
+        }
+        // FIXME: We shouldn't be overriding start/-webkit-auto like this. Do it in html.css instead.
+        // Table headers with a text-align of -webkit-auto will change the text-align to center.
+        if (element.hasTagName(thTag) && style->textAlign() == TASTART)
+            style->setTextAlign(CENTER);
+        if (style->whiteSpace() == KHTML_NOWRAP) {
+            // Figure out if we are really nowrapping or if we should just
+            // use normal instead. If the width of the cell is fixed, then
+            // we don't actually use NOWRAP.
+            if (style->width().isFixed())
+                style->setWhiteSpace(NORMAL);
+            else
+                style->setWhiteSpace(NOWRAP);
+        }
+        return;
+    }
+
+    if (isHTMLTableElement(element)) {
+        // Sites commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
+        // these tags to retain their display types.
+        if (m_useQuirksModeStyles)
+            style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
+        // Tables never support the -webkit-* values for text-align and will reset back to the default.
+        if (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT)
+            style->setTextAlign(TASTART);
+        return;
+    }
+
+    if (isHTMLFrameElement(element) || isHTMLFrameSetElement(element)) {
+        // Frames and framesets never honor position:relative or position:absolute. This is necessary to
+        // fix a crash where a site tries to position these objects. They also never honor display.
+        style->setPosition(StaticPosition);
+        style->setDisplay(BLOCK);
+        return;
+    }
+
+    if (isHTMLRTElement(element)) {
+        // Ruby text does not support float or position. This might change with evolution of the specification.
+        style->setPosition(StaticPosition);
+        style->setFloating(NoFloat);
+        return;
+    }
+
+    if (isHTMLLegendElement(element)) {
+        style->setDisplay(BLOCK);
+        return;
+    }
+
+    if (isHTMLMarqueeElement(element)) {
+        // For now, <marquee> requires an overflow clip to work properly.
+        style->setOverflowX(OHIDDEN);
+        style->setOverflowY(OHIDDEN);
+        return;
+    }
+
+    if (element.isFormControlElement()) {
+        if (isHTMLTextAreaElement(element)) {
+            // Textarea considers overflow visible as auto.
+            style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
+            style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
+        }
+
+        // Important: Intrinsic margins get added to controls before the theme has adjusted the style,
+        // since the theme will alter fonts and heights/widths.
+        //
+        // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
+        // so we have to treat all image buttons as though they were explicitly sized.
+        if (style->fontSize() >= 11 && (!isHTMLInputElement(element) || !toHTMLInputElement(element).isImageButton()))
+            addIntrinsicMargins(style);
+        return;
+    }
+}
+
+void StyleAdjuster::adjustStyleForDisplay(RenderStyle* style, RenderStyle* parentStyle)
+{
+    if (style->display() == BLOCK && !style->isFloating())
+        return;
+
+    // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
+    // clear how that should work.
+    if (style->display() == INLINE && style->styleType() == NOPSEUDO && style->writingMode() != parentStyle->writingMode())
+        style->setDisplay(INLINE_BLOCK);
+
+    // After performing the display mutation, check table rows. We do not honor position: relative table rows or cells.
+    // This has been established for position: relative in CSS2.1 (and caused a crash in containingBlock()
+    // on some sites).
+    if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
+        || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW)
+        && style->position() == RelativePosition)
+        style->setPosition(StaticPosition);
+
+    // Cannot support position: sticky for table columns and column groups because current code is only doing
+    // background painting through columns / column groups
+    if ((style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_COLUMN)
+        && style->position() == StickyPosition)
+        style->setPosition(StaticPosition);
+
+    // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
+    // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
+    if (style->display() == TABLE_COLUMN || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_FOOTER_GROUP
+        || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_ROW_GROUP
+        || style->display() == TABLE_CELL)
+        style->setWritingMode(parentStyle->writingMode());
+
+    // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
+    // of block-flow to anything other than TopToBottomWritingMode.
+    // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
+    if (style->writingMode() != TopToBottomWritingMode && (style->display() == BOX || style->display() == INLINE_BOX))
+        style->setWritingMode(TopToBottomWritingMode);
+
+    if (isDisplayFlexibleBox(parentStyle->display()) || isDisplayGridBox(parentStyle->display())) {
+        style->setFloating(NoFloat);
+        style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), !m_useQuirksModeStyles));
+    }
+}
+
 }
diff --git a/Source/core/css/resolver/StyleAdjuster.h b/Source/core/css/resolver/StyleAdjuster.h
index 787beaf..43f31e3 100644
--- a/Source/core/css/resolver/StyleAdjuster.h
+++ b/Source/core/css/resolver/StyleAdjuster.h
@@ -41,6 +41,9 @@
     void adjustRenderStyle(RenderStyle* styleToAdjust, RenderStyle* parentStyle, Element*);
 
 private:
+    void adjustStyleForDisplay(RenderStyle* styleToAdjust, RenderStyle* parentStyle);
+    void adjustStyleForTagName(RenderStyle* styleToAdjust, RenderStyle* parentStyle, Element&);
+
     const CachedUAStyle& m_cachedUAStyle;
     bool m_useQuirksModeStyles;
 };
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index 7e1c31e..140773f 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -629,6 +629,13 @@
         features.addAttributeInASelector(contentAttrValues[i]);
 }
 
+// Start loading resources referenced by this style.
+void StyleResolver::loadPendingResources(StyleResolverState& state)
+{
+    m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
+    document().styleEngine()->fontSelector()->loadPendingFonts();
+}
+
 PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderStyle* defaultParent, StyleSharingBehavior sharingBehavior,
     RuleMatchingBehavior matchingBehavior)
 {
@@ -783,9 +790,7 @@
     // go ahead and update it a second time.
     updateFont(state);
 
-    // Start loading resources referenced by this style.
-    m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
-    document().styleEngine()->fontSelector()->loadPendingFonts();
+    loadPendingResources(state);
 
     didAccess();
 
@@ -794,12 +799,13 @@
 
 // This function is used by the WebAnimations JavaScript API method animate().
 // FIXME: Remove this when animate() switches away from resolution-dependent parsing.
-PassRefPtrWillBeRawPtr<KeyframeEffectModel> StyleResolver::createKeyframeEffectModel(Element& element, const Vector<RefPtr<MutableStylePropertySet> >& propertySetVector, KeyframeEffectModel::KeyframeVector& keyframes)
+PassRefPtrWillBeRawPtr<KeyframeEffectModel> StyleResolver::createKeyframeEffectModel(Element& element, const WillBeHeapVector<RefPtrWillBeMember<MutableStylePropertySet> >& propertySetVector, KeyframeEffectModel::KeyframeVector& keyframes)
 {
     ASSERT(propertySetVector.size() == keyframes.size());
 
     StyleResolverState state(element.document(), &element);
     state.setStyle(RenderStyle::create());
+    state.fontBuilder().initForStyleResolve(state.document(), state.style(), state.useSVGZoomRules());
 
     for (unsigned i = 0; i < propertySetVector.size(); ++i) {
         for (unsigned j = 0; j < propertySetVector[i]->propertyCount(); ++j) {
@@ -808,6 +814,7 @@
             keyframes[i]->setPropertyValue(id, CSSAnimatableValueFactory::create(id, *state.style()).get());
         }
     }
+
     return KeyframeEffectModel::create(keyframes);
 }
 
@@ -827,16 +834,22 @@
         return nullptr;
 
     RenderStyle* parentStyle = parentRenderer->style();
+    if (RenderStyle* cachedStyle = parentStyle->getCachedPseudoStyle(pseudoId)) {
+        if (!pseudoElementRendererIsNeeded(cachedStyle))
+            return nullptr;
+        return PseudoElement::create(&parent, pseudoId);
+    }
+
     StyleResolverState state(document(), &parent, parentStyle);
     if (!pseudoStyleForElementInternal(parent, pseudoId, parentStyle, state))
         return nullptr;
     RefPtr<RenderStyle> style = state.takeStyle();
     ASSERT(style);
+    parentStyle->addCachedPseudoStyle(style);
 
     if (!pseudoElementRendererIsNeeded(style.get()))
         return nullptr;
 
-    parentStyle->addCachedPseudoStyle(style.release());
     RefPtr<PseudoElement> pseudo = PseudoElement::create(&parent, pseudoId);
 
     setAnimationUpdateIfNeeded(state, *pseudo);
@@ -955,9 +968,7 @@
 
     addContentAttrValuesToFeatures(state.contentAttrValues(), m_features);
 
-    // Start loading resources referenced by this style.
-    m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
-    document().styleEngine()->fontSelector()->loadPendingFonts();
+    loadPendingResources(state);
 
     didAccess();
 
@@ -1000,7 +1011,7 @@
 
     NodeRenderingTraversal::ParentDetails parentDetails;
     Node* parentNode = NodeRenderingTraversal::parent(textNode, &parentDetails);
-    if (!parentNode || !parentNode->renderStyle() || parentDetails.resetStyleInheritance())
+    if (!parentNode || !parentNode->renderStyle())
         return defaultStyleForElement();
     return parentNode->renderStyle();
 }
@@ -1072,12 +1083,12 @@
     if (!state.animationUpdate())
         return;
 
-    const AnimationEffect::CompositableValueMap& compositableValuesForAnimations = state.animationUpdate()->compositableValuesForAnimations();
-    const AnimationEffect::CompositableValueMap& compositableValuesForTransitions = state.animationUpdate()->compositableValuesForTransitions();
-    applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForAnimations);
-    applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForTransitions);
-    applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForAnimations);
-    applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForTransitions);
+    const HashMap<CSSPropertyID, RefPtr<Interpolation> >& activeInterpolationsForAnimations = state.animationUpdate()->activeInterpolationsForAnimations();
+    const HashMap<CSSPropertyID, RefPtr<Interpolation> >& activeInterpolationsForTransitions = state.animationUpdate()->activeInterpolationsForTransitions();
+    applyAnimatedProperties<HighPriorityProperties>(state, activeInterpolationsForAnimations);
+    applyAnimatedProperties<HighPriorityProperties>(state, activeInterpolationsForTransitions);
+    applyAnimatedProperties<LowPriorityProperties>(state, activeInterpolationsForAnimations);
+    applyAnimatedProperties<LowPriorityProperties>(state, activeInterpolationsForTransitions);
 
     // If the animations/transitions change opacity or transform, we need to update
     // the style to impose the stacking rules. Note that this is also
@@ -1085,20 +1096,22 @@
     RenderStyle* style = state.style();
     if (style->hasAutoZIndex() && (style->opacity() < 1.0f || style->hasTransform()))
         style->setZIndex(0);
+
+    // Start loading resources used by animations.
+    loadPendingResources(state);
 }
 
 template <StyleResolver::StyleApplicationPass pass>
-void StyleResolver::applyAnimatedProperties(StyleResolverState& state, const AnimationEffect::CompositableValueMap& compositableValues)
+void StyleResolver::applyAnimatedProperties(StyleResolverState& state, const HashMap<CSSPropertyID, RefPtr<Interpolation> >& activeInterpolations)
 {
     ASSERT(pass != AnimationProperties);
 
-    for (AnimationEffect::CompositableValueMap::const_iterator iter = compositableValues.begin(); iter != compositableValues.end(); ++iter) {
+    for (HashMap<CSSPropertyID, RefPtr<Interpolation> >::const_iterator iter = activeInterpolations.begin(); iter != activeInterpolations.end(); ++iter) {
         CSSPropertyID property = iter->key;
         if (!isPropertyForPass<pass>(property))
             continue;
-        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);
-        AnimatedStyleBuilder::applyProperty(property, state, animatableValue.get());
+        const StyleInterpolation *interpolation = toStyleInterpolation(iter->value.get());
+        interpolation->apply(state);
     }
 }
 
@@ -1329,9 +1342,7 @@
     applyMatchedProperties<LowPriorityProperties>(state, matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
     applyMatchedProperties<LowPriorityProperties>(state, matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
 
-    // Start loading resources referenced by this style.
-    m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
-    document().styleEngine()->fontSelector()->loadPendingFonts();
+    loadPendingResources(state);
 
     if (!cachedMatchedProperties && cacheHash && MatchedPropertiesCache::isCacheable(element, state.style(), state.parentStyle())) {
         INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyCacheAdded);
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index a848bb4..51a21ea 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -122,7 +122,7 @@
         RuleMatchingBehavior = MatchAllRules);
 
     PassRefPtr<RenderStyle> styleForKeyframe(Element*, const RenderStyle&, RenderStyle* parentStyle, const StyleKeyframe*, const AtomicString& animationName);
-    static PassRefPtrWillBeRawPtr<KeyframeEffectModel> createKeyframeEffectModel(Element&, const Vector<RefPtr<MutableStylePropertySet> >&, KeyframeEffectModel::KeyframeVector&);
+    static PassRefPtrWillBeRawPtr<KeyframeEffectModel> createKeyframeEffectModel(Element&, const WillBeHeapVector<RefPtrWillBeMember<MutableStylePropertySet> >&, KeyframeEffectModel::KeyframeVector&);
 
     PassRefPtr<RenderStyle> pseudoStyleForElement(Element*, const PseudoStyleRequest&, RenderStyle* parentStyle);
 
@@ -242,6 +242,8 @@
     // FIXME: This should probably go away, folded into FontBuilder.
     void updateFont(StyleResolverState&);
 
+    void loadPendingResources(StyleResolverState&);
+
     void appendCSSStyleSheet(CSSStyleSheet*);
 
     void collectPseudoRulesForElement(Element*, ElementRuleCollector&, PseudoId, unsigned rulesToInclude);
@@ -273,7 +275,7 @@
     template <StyleApplicationPass pass>
     void applyProperties(StyleResolverState&, const StylePropertySet* properties, StyleRule*, bool isImportant, bool inheritedOnly, PropertyWhitelistType = PropertyWhitelistNone);
     template <StyleApplicationPass pass>
-    void applyAnimatedProperties(StyleResolverState&, const AnimationEffect::CompositableValueMap&);
+    void applyAnimatedProperties(StyleResolverState&, const HashMap<CSSPropertyID, RefPtr<Interpolation> >&);
     void matchPageRules(MatchResult&, RuleSet*, bool isLeftPage, bool isFirstPage, const String& pageName);
     void matchPageRulesForList(WillBeHeapVector<RawPtrWillBeMember<StyleRulePage> >& matchedRules, const WillBeHeapVector<RawPtrWillBeMember<StyleRulePage> >&, bool isLeftPage, bool isFirstPage, const String& pageName);
     void collectViewportRules();
@@ -304,8 +306,11 @@
     Document& m_document;
     SelectorFilter m_selectorFilter;
 
-    RefPtr<ViewportStyleResolver> m_viewportStyleResolver;
+    RefPtrWillBePersistent<ViewportStyleResolver> m_viewportStyleResolver;
 
+    // FIXME: Oilpan: This should be a WillBePersistentHeapListHashSet.
+    // This is safe for now, but should be updated when we support
+    // heap allocated ListHashSets.
     ListHashSet<CSSStyleSheet*, 16> m_pendingStyleSheets;
 
     ScopedStyleTree m_styleTree;
diff --git a/Source/core/css/resolver/StyleResolverState.cpp b/Source/core/css/resolver/StyleResolverState.cpp
index 370877c..f729923 100644
--- a/Source/core/css/resolver/StyleResolverState.cpp
+++ b/Source/core/css/resolver/StyleResolverState.cpp
@@ -41,9 +41,7 @@
     , m_styleMap(*this, m_elementStyleResources)
     , m_currentRule(0)
 {
-    if (m_elementContext.resetStyleInheritance())
-        m_parentStyle = nullptr;
-    else if (!parentStyle && m_elementContext.parentNode())
+    if (!parentStyle && m_elementContext.parentNode())
         m_parentStyle = m_elementContext.parentNode()->renderStyle();
 
     // FIXME: Animation unitests will start animations on non-active documents!
diff --git a/Source/core/css/resolver/StyleResolverState.h b/Source/core/css/resolver/StyleResolverState.h
index 4e01e8c..a23f9da 100644
--- a/Source/core/css/resolver/StyleResolverState.h
+++ b/Source/core/css/resolver/StyleResolverState.h
@@ -94,7 +94,14 @@
     void setLineHeightValue(CSSValue* value) { m_lineHeightValue = value; }
     CSSValue* lineHeightValue() { return m_lineHeightValue; }
 
-    void cacheUserAgentBorderAndBackground() { m_cachedUAStyle = CachedUAStyle(style()); }
+    void cacheUserAgentBorderAndBackground()
+    {
+        // RenderTheme only needs the cached style if it has an appearance,
+        // and constructing it is expensive so we avoid it if possible.
+        if (!style()->hasAppearance())
+            return;
+        m_cachedUAStyle = CachedUAStyle(style());
+    }
     const CachedUAStyle& cachedUAStyle() const { return m_cachedUAStyle; }
 
     ElementStyleResources& elementStyleResources() { return m_elementStyleResources; }
diff --git a/Source/core/css/resolver/StyleResourceLoader.cpp b/Source/core/css/resolver/StyleResourceLoader.cpp
index 8319059..3dbc1e8 100644
--- a/Source/core/css/resolver/StyleResourceLoader.cpp
+++ b/Source/core/css/resolver/StyleResourceLoader.cpp
@@ -46,7 +46,7 @@
 {
 }
 
-void StyleResourceLoader::loadPendingSVGDocuments(RenderStyle* renderStyle, const ElementStyleResources& elementStyleResources)
+void StyleResourceLoader::loadPendingSVGDocuments(RenderStyle* renderStyle, ElementStyleResources& elementStyleResources)
 {
     if (!renderStyle->hasFilter() || elementStyleResources.pendingSVGDocuments().isEmpty())
         return;
@@ -68,6 +68,8 @@
             ReferenceFilterBuilder::setDocumentResourceReference(referenceFilter, adoptPtr(new DocumentResourceReference(resource)));
         }
     }
+
+    elementStyleResources.clearPendingSVGDocuments();
 }
 
 static PassRefPtr<StyleImage> doLoadPendingImage(ResourceFetcher* fetcher, StylePendingImage* pendingImage, float deviceScaleFactor, const ResourceLoaderOptions& options)
@@ -112,7 +114,7 @@
     shapeValue->setImage(doLoadPendingImage(m_fetcher, toStylePendingImage(image), deviceScaleFactor, options));
 }
 
-void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementStyleResources& elementStyleResources)
+void StyleResourceLoader::loadPendingImages(RenderStyle* style, ElementStyleResources& elementStyleResources)
 {
     if (elementStyleResources.pendingImageProperties().isEmpty())
         return;
@@ -196,6 +198,8 @@
             ASSERT_NOT_REACHED();
         }
     }
+
+    elementStyleResources.clearPendingImageProperties();
 }
 
 void StyleResourceLoader::loadPendingResources(RenderStyle* renderStyle, ElementStyleResources& elementStyleResources)
diff --git a/Source/core/css/resolver/StyleResourceLoader.h b/Source/core/css/resolver/StyleResourceLoader.h
index 0715a6b..8d3eff1 100644
--- a/Source/core/css/resolver/StyleResourceLoader.h
+++ b/Source/core/css/resolver/StyleResourceLoader.h
@@ -46,10 +46,10 @@
     void loadPendingResources(RenderStyle*, ElementStyleResources&);
 
 private:
-    void loadPendingSVGDocuments(RenderStyle*, const ElementStyleResources&);
+    void loadPendingSVGDocuments(RenderStyle*, ElementStyleResources&);
 
     PassRefPtr<StyleImage> loadPendingImage(StylePendingImage*, float deviceScaleFactor);
-    void loadPendingImages(RenderStyle*, const ElementStyleResources&);
+    void loadPendingImages(RenderStyle*, ElementStyleResources&);
     void loadPendingShapeImage(RenderStyle*, ShapeValue*, float deviceScaleFactor);
 
     ResourceFetcher* m_fetcher;
diff --git a/Source/core/css/resolver/ViewportStyleResolver.cpp b/Source/core/css/resolver/ViewportStyleResolver.cpp
index 372df90..cfc624e 100644
--- a/Source/core/css/resolver/ViewportStyleResolver.cpp
+++ b/Source/core/css/resolver/ViewportStyleResolver.cpp
@@ -42,6 +42,8 @@
 
 namespace WebCore {
 
+DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(ViewportStyleResolver);
+
 ViewportStyleResolver::ViewportStyleResolver(Document* document)
     : m_document(document),
     m_hasAuthorStyle(false)
@@ -49,10 +51,6 @@
     ASSERT(m_document);
 }
 
-ViewportStyleResolver::~ViewportStyleResolver()
-{
-}
-
 void ViewportStyleResolver::collectViewportRules(RuleSet* rules, Origin origin)
 {
     rules->compactRulesIfNeeded();
@@ -206,4 +204,9 @@
     return result;
 }
 
+void ViewportStyleResolver::trace(Visitor* visitor)
+{
+    visitor->trace(m_propertySet);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/resolver/ViewportStyleResolver.h b/Source/core/css/resolver/ViewportStyleResolver.h
index 30b663f..a6c4e01 100644
--- a/Source/core/css/resolver/ViewportStyleResolver.h
+++ b/Source/core/css/resolver/ViewportStyleResolver.h
@@ -42,15 +42,14 @@
 class MutableStylePropertySet;
 class StyleRuleViewport;
 
-class ViewportStyleResolver : public RefCounted<ViewportStyleResolver> {
+class ViewportStyleResolver : public RefCountedWillBeGarbageCollected<ViewportStyleResolver> {
+    DECLARE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(ViewportStyleResolver);
 public:
-    static PassRefPtr<ViewportStyleResolver> create(Document* document)
+    static PassRefPtrWillBeRawPtr<ViewportStyleResolver> create(Document* document)
     {
-        return adoptRef(new ViewportStyleResolver(document));
+        return adoptRefWillBeNoop(new ViewportStyleResolver(document));
     }
 
-    ~ViewportStyleResolver();
-
     enum Origin { UserAgentOrigin, AuthorOrigin };
 
     void collectViewportRules(RuleSet*, Origin);
@@ -58,6 +57,8 @@
     void clearDocument();
     void resolve();
 
+    void trace(Visitor*);
+
 private:
     explicit ViewportStyleResolver(Document*);
 
@@ -67,7 +68,7 @@
     Length viewportLengthValue(CSSPropertyID) const;
 
     Document* m_document;
-    RefPtr<MutableStylePropertySet> m_propertySet;
+    RefPtrWillBeMember<MutableStylePropertySet> m_propertySet;
     bool m_hasAuthorStyle;
 };
 
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index c6454fa..b6ca3b5 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -28,6 +28,7 @@
 #include "core/dom/Element.h"
 #include "core/dom/Text.h"
 #include "core/events/ScopedEventQueue.h"
+#include "core/frame/UseCounter.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -102,7 +103,7 @@
     invalidateNodeListCachesInAncestors(&m_name, m_element);
 }
 
-void Attr::setValue(const AtomicString& value, ExceptionState&)
+void Attr::setValueInternal(const AtomicString& value)
 {
     if (m_element)
         m_element->willModifyAttribute(qualifiedName(), this->value(), value);
@@ -113,11 +114,23 @@
         m_element->didModifyAttribute(qualifiedName(), value);
 }
 
+const AtomicString& Attr::valueForBindings() const
+{
+    UseCounter::count(document(), UseCounter::AttrGetValue);
+    return value();
+}
+
+void Attr::setValueForBindings(const AtomicString& value)
+{
+    UseCounter::count(document(), UseCounter::AttrSetValue);
+    setValueInternal(value);
+}
+
 void Attr::setNodeValue(const String& v)
 {
     // Attr uses AtomicString type for its value to save memory as there
     // is duplication among Elements' attributes values.
-    setValue(AtomicString(v), IGNORE_EXCEPTION);
+    setValueInternal(AtomicString(v));
 }
 
 PassRefPtr<Node> Attr::cloneNode(bool /*deep*/)
diff --git a/Source/core/dom/Attr.h b/Source/core/dom/Attr.h
index 579a5d8..6647ca5 100644
--- a/Source/core/dom/Attr.h
+++ b/Source/core/dom/Attr.h
@@ -49,9 +49,11 @@
     Element* ownerElement() const { return m_element; }
 
     const AtomicString& value() const;
-    void setValue(const AtomicString&, ExceptionState&);
     void setValue(const AtomicString&);
 
+    const AtomicString& valueForBindings() const;
+    void setValueForBindings(const AtomicString&);
+
     const QualifiedName& qualifiedName() const { return m_name; }
 
     void attachToElement(Element*);
@@ -67,6 +69,8 @@
 
     void createTextChild();
 
+    void setValueInternal(const AtomicString&);
+
     virtual String nodeName() const OVERRIDE { return name(); }
     virtual NodeType nodeType() const OVERRIDE { return ATTRIBUTE_NODE; }
 
diff --git a/Source/core/dom/Attr.idl b/Source/core/dom/Attr.idl
index a2fab30..e497d13 100644
--- a/Source/core/dom/Attr.idl
+++ b/Source/core/dom/Attr.idl
@@ -26,7 +26,7 @@
 
     [MeasureAs=AttributeSpecified] readonly attribute boolean specified;
 
-    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter, CustomElementCallbacks] attribute DOMString value;
+    [ImplementedAs=valueForBindings, TreatReturnedNullStringAs=Null, TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString value;
 
     // DOM 4
 
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index 0bf96bf..5f8b1d0 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -236,11 +236,11 @@
     return doc.release();
 }
 
-PassRefPtr<CSSStyleSheet> DOMImplementation::createCSSStyleSheet(const String&, const String& media)
+PassRefPtrWillBeRawPtr<CSSStyleSheet> DOMImplementation::createCSSStyleSheet(const String&, const String& media)
 {
     // FIXME: Title should be set.
     // FIXME: Media could have wrong syntax, in which case we should generate an exception.
-    RefPtr<CSSStyleSheet> sheet = CSSStyleSheet::create(StyleSheetContents::create(strictCSSParserContext()));
+    RefPtrWillBeRawPtr<CSSStyleSheet> sheet = CSSStyleSheet::create(StyleSheetContents::create(strictCSSParserContext()));
     sheet->setMediaQueries(MediaQuerySet::create(media));
     return sheet;
 }
diff --git a/Source/core/dom/DOMImplementation.h b/Source/core/dom/DOMImplementation.h
index 429aa8b..041ca94 100644
--- a/Source/core/dom/DOMImplementation.h
+++ b/Source/core/dom/DOMImplementation.h
@@ -58,7 +58,7 @@
     DOMImplementation* getInterface(const String& feature);
 
     // From the DOMImplementationCSS interface
-    static PassRefPtr<CSSStyleSheet> createCSSStyleSheet(const String& title, const String& media);
+    static PassRefPtrWillBeRawPtr<CSSStyleSheet> createCSSStyleSheet(const String& title, const String& media);
 
     // From the HTMLDOMImplementation interface
     PassRefPtr<HTMLDocument> createHTMLDocument(const String& title);
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index db5f3b0..a45d551 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -815,11 +815,6 @@
     m_import = import;
 }
 
-void Document::didLoadAllImports()
-{
-    executeScriptsWaitingForResourcesIfNeeded();
-}
-
 bool Document::haveImportsLoaded() const
 {
     return !m_import || !m_import->state().shouldBlockScriptExecution();
@@ -2057,6 +2052,7 @@
 
     if (page())
         page()->documentDetached(this);
+    InspectorInstrumentation::documentDetached(this);
 
     if (m_frame->loader().client()->sharedWorkerRepositoryClient())
         m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
@@ -2843,20 +2839,37 @@
     return 0;
 }
 
+void Document::didLoadAllImports()
+{
+    if (!haveStylesheetsLoaded())
+        return;
+
+    didLoadAllScriptBlockingResources();
+}
+
 void Document::didRemoveAllPendingStylesheet()
 {
     m_needsNotifyRemoveAllPendingStylesheet = false;
 
     styleResolverChanged(RecalcStyleDeferred, hasNodesWithPlaceholderStyle() ? FullStyleUpdate : AnalyzedStyleUpdate);
+
+    if (m_import)
+        m_import->didRemoveAllPendingStylesheet();
+    if (!haveImportsLoaded())
+        return;
+
+    didLoadAllScriptBlockingResources();
+}
+
+void Document::didLoadAllScriptBlockingResources()
+{
     executeScriptsWaitingForResourcesIfNeeded();
 
     if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
         view()->scrollToFragment(m_url);
-
-    if (m_import)
-        m_import->didRemoveAllPendingStylesheet();
 }
 
+
 void Document::executeScriptsWaitingForResourcesIfNeeded()
 {
     if (!haveStylesheetsAndImportsLoaded())
@@ -4391,6 +4404,14 @@
     if (!m_documentTiming.domContentLoadedEventEnd)
         m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
 
+    if (frame() && frame()->isMainFrame()) {
+        // Reset the text autosizing multipliers on main frame when DOM is loaded.
+        // This is to allow for a fresh text autosizing pass when the page layout
+        // changes significantly in the end.
+        if (TextAutosizer* textAutosizer = this->textAutosizer())
+            textAutosizer->recalculateMultipliers();
+    }
+
     // The loader's finishedParsing() method may invoke script that causes this object to
     // be dereferenced (when this document is in an iframe and the onload causes the iframe's src to change).
     // Keep it alive until we are done.
@@ -5066,7 +5087,7 @@
 
     LayoutRect visibleContentRect = view()->visibleContentRect();
     for (size_t i = 0; i < quads.size(); ++i) {
-        quads[i].move(-FloatSize(visibleContentRect.x(), visibleContentRect.y()));
+        quads[i].move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
         adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
     }
 }
@@ -5077,7 +5098,7 @@
         return;
 
     LayoutRect visibleContentRect = view()->visibleContentRect();
-    rect.move(-FloatSize(visibleContentRect.x(), visibleContentRect.y()));
+    rect.move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
     adjustFloatRectForAbsoluteZoom(rect, renderer);
 }
 
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index 18e4b8b..7ddecbc 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -993,6 +993,7 @@
 
     ElementDataCache* elementDataCache() { return m_elementDataCache.get(); }
 
+    void didLoadAllScriptBlockingResources();
     void didRemoveAllPendingStylesheet();
     void setNeedsNotifyRemoveAllPendingStylesheet() { m_needsNotifyRemoveAllPendingStylesheet = true; }
     void clearStyleResolver();
@@ -1182,7 +1183,7 @@
     RefPtr<DocumentType> m_docType;
     OwnPtr<DOMImplementation> m_implementation;
 
-    RefPtr<CSSStyleSheet> m_elemSheet;
+    RefPtrWillBePersistent<CSSStyleSheet> m_elemSheet;
 
     bool m_printing;
     bool m_paginatedForScreen;
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index e277d24..c49c6ec 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -39,13 +39,19 @@
 class TreeScope;
 
 class DocumentStyleSheetCollection FINAL : public TreeScopeStyleSheetCollection {
-    WTF_MAKE_NONCOPYABLE(DocumentStyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
+    WTF_MAKE_NONCOPYABLE(DocumentStyleSheetCollection);
+    WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
 public:
     explicit DocumentStyleSheetCollection(TreeScope&);
 
     bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
     void collectStyleSheets(StyleEngine*, DocumentStyleSheetCollector&);
 
+    virtual void trace(Visitor* visitor) OVERRIDE
+    {
+        TreeScopeStyleSheetCollection::trace(visitor);
+    }
+
 private:
     void collectStyleSheetsFromCandidates(StyleEngine*, DocumentStyleSheetCollector&);
 };
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index 1b88ddb..60bd7bf 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -84,6 +84,7 @@
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLFormControlsCollection.h"
+#include "core/html/HTMLFrameElementBase.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLLabelElement.h"
 #include "core/html/HTMLOptionsCollection.h"
@@ -227,6 +228,26 @@
     return static_cast<ElementRareData&>(ensureRareData());
 }
 
+bool Element::hasElementFlagInternal(ElementFlags mask) const
+{
+    ASSERT(hasRareData());
+    return elementRareData()->hasFlag(mask);
+}
+
+void Element::setElementFlag(ElementFlags mask, bool value)
+{
+    if (!hasRareData() && !value)
+        return;
+    ensureElementRareData().setFlag(mask, value);
+}
+
+void Element::clearElementFlag(ElementFlags mask)
+{
+    if (!hasRareData())
+        return;
+    elementRareData()->clearFlag(mask);
+}
+
 void Element::clearTabIndexExplicitlyIfNeeded()
 {
     if (hasRareData())
@@ -238,11 +259,6 @@
     ensureElementRareData().setTabIndexExplicitly(tabIndex);
 }
 
-bool Element::supportsFocus() const
-{
-    return hasRareData() && elementRareData()->tabIndexSetExplicitly();
-}
-
 short Element::tabIndex() const
 {
     return hasRareData() ? elementRareData()->tabIndex() : 0;
@@ -1050,6 +1066,16 @@
         cache->handleAttributeChanged(name, this);
 }
 
+bool Element::hasLegalLinkAttribute(const QualifiedName&) const
+{
+    return false;
+}
+
+const QualifiedName& Element::subResourceAttributeName() const
+{
+    return nullQName();
+}
+
 inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
 {
     if (name == isAttr)
@@ -1383,8 +1409,7 @@
 
     document().removeFromTopLayer(this);
 
-    if (hasRareData())
-        elementRareData()->setIsInCanvasSubtree(false);
+    clearElementFlag(IsInCanvasSubtree);
 }
 
 void Element::attach(const AttachContext& context)
@@ -1425,10 +1450,10 @@
 
     if (hasRareData()) {
         ElementRareData* data = elementRareData();
-        if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
+        if (data->hasFlag(NeedsFocusAppearanceUpdateSoonAfterAttach)) {
             if (isFocusable() && document().focusedElement() == this)
                 document().updateFocusAppearanceSoon(false /* don't restore selection */);
-            data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
+            data->clearFlag(NeedsFocusAppearanceUpdateSoonAfterAttach);
         }
         if (!renderer()) {
             if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
@@ -1740,6 +1765,21 @@
     setAnimationStyleChange(true);
 }
 
+void Element::setCustomElementDefinition(PassRefPtr<CustomElementDefinition> definition)
+{
+    if (!hasRareData() && !definition)
+        return;
+    ASSERT(!customElementDefinition());
+    ensureElementRareData().setCustomElementDefinition(definition);
+}
+
+CustomElementDefinition* Element::customElementDefinition() const
+{
+    if (hasRareData())
+        return elementRareData()->customElementDefinition();
+    return 0;
+}
+
 PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& exceptionState)
 {
     if (alwaysCreateUserAgentShadowRoot())
@@ -1829,14 +1869,16 @@
     if (!style || (needsStyleRecalc() && childrenAffectedByPositionalRules()))
         return;
 
-    // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
+    // Forward positional selectors include nth-child, nth-of-type, first-of-type and only-of-type.
+    // The indirect adjacent selector is the ~ selector.
     // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
-    // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
-    // backward case.
+    // We have to invalidate everything following the insertion point in the forward and indirect adjacent case,
+    // and everything before the insertion point in the backward case.
     // |afterChange| is 0 in the parser callback case, so we won't do any work for the forward case if we don't have to.
     // For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids
     // here. recalcStyle will then force a walk of the children when it sees that this has happened.
-    if ((childrenAffectedByForwardPositionalRules() && afterChange) || (childrenAffectedByBackwardPositionalRules() && beforeChange)) {
+    if (((childrenAffectedByForwardPositionalRules() || childrenAffectedByIndirectAdjacentRules()) && afterChange)
+        || (childrenAffectedByBackwardPositionalRules() && beforeChange)) {
         setNeedsStyleRecalc(SubtreeStyleChange);
         return;
     }
@@ -2167,7 +2209,7 @@
     doc.updateLayoutIgnorePendingStylesheets();
 
     if (!isFocusable()) {
-        ensureElementRareData().setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
+        setElementFlag(NeedsFocusAppearanceUpdateSoonAfterAttach);
         return;
     }
 
@@ -2502,56 +2544,6 @@
     return pseudoElementSpecifier ? rareData.computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : rareData.computedStyle();
 }
 
-void Element::setStyleAffectedByEmpty()
-{
-    ensureElementRareData().setStyleAffectedByEmpty(true);
-}
-
-void Element::setChildrenAffectedByFocus()
-{
-    ensureElementRareData().setChildrenAffectedByFocus(true);
-}
-
-void Element::setChildrenAffectedByHover()
-{
-    ensureElementRareData().setChildrenAffectedByHover(true);
-}
-
-void Element::setChildrenAffectedByActive()
-{
-    ensureElementRareData().setChildrenAffectedByActive(true);
-}
-
-void Element::setChildrenAffectedByDrag()
-{
-    ensureElementRareData().setChildrenAffectedByDrag(true);
-}
-
-void Element::setChildrenAffectedByFirstChildRules()
-{
-    ensureElementRareData().setChildrenAffectedByFirstChildRules(true);
-}
-
-void Element::setChildrenAffectedByLastChildRules()
-{
-    ensureElementRareData().setChildrenAffectedByLastChildRules(true);
-}
-
-void Element::setChildrenAffectedByDirectAdjacentRules()
-{
-    ensureElementRareData().setChildrenAffectedByDirectAdjacentRules(true);
-}
-
-void Element::setChildrenAffectedByForwardPositionalRules()
-{
-    ensureElementRareData().setChildrenAffectedByForwardPositionalRules(true);
-}
-
-void Element::setChildrenAffectedByBackwardPositionalRules()
-{
-    ensureElementRareData().setChildrenAffectedByBackwardPositionalRules(true);
-}
-
 void Element::setChildIndex(unsigned index)
 {
     ElementRareData& rareData = ensureElementRareData();
@@ -2560,97 +2552,12 @@
     rareData.setChildIndex(index);
 }
 
-bool Element::childrenSupportStyleSharing() const
-{
-    if (!hasRareData())
-        return true;
-    return !rareDataChildrenAffectedByFocus()
-        && !rareDataChildrenAffectedByHover()
-        && !rareDataChildrenAffectedByActive()
-        && !rareDataChildrenAffectedByDrag()
-        && !rareDataChildrenAffectedByFirstChildRules()
-        && !rareDataChildrenAffectedByLastChildRules()
-        && !rareDataChildrenAffectedByDirectAdjacentRules()
-        && !rareDataChildrenAffectedByForwardPositionalRules()
-        && !rareDataChildrenAffectedByBackwardPositionalRules();
-}
-
-bool Element::rareDataStyleAffectedByEmpty() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->styleAffectedByEmpty();
-}
-
-bool Element::rareDataChildrenAffectedByFocus() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->childrenAffectedByFocus();
-}
-
-bool Element::rareDataChildrenAffectedByHover() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->childrenAffectedByHover();
-}
-
-bool Element::rareDataChildrenAffectedByActive() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->childrenAffectedByActive();
-}
-
-bool Element::rareDataChildrenAffectedByDrag() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->childrenAffectedByDrag();
-}
-
-bool Element::rareDataChildrenAffectedByFirstChildRules() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->childrenAffectedByFirstChildRules();
-}
-
-bool Element::rareDataChildrenAffectedByLastChildRules() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->childrenAffectedByLastChildRules();
-}
-
-bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->childrenAffectedByDirectAdjacentRules();
-}
-
-bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->childrenAffectedByForwardPositionalRules();
-}
-
-bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
-{
-    ASSERT(hasRareData());
-    return elementRareData()->childrenAffectedByBackwardPositionalRules();
-}
-
 unsigned Element::rareDataChildIndex() const
 {
     ASSERT(hasRareData());
     return elementRareData()->childIndex();
 }
 
-void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
-{
-    ensureElementRareData().setIsInCanvasSubtree(isInCanvasSubtree);
-}
-
-bool Element::isInCanvasSubtree() const
-{
-    return hasRareData() && elementRareData()->isInCanvasSubtree();
-}
-
 AtomicString Element::computeInheritedLanguage() const
 {
     const Node* n = this;
@@ -2684,7 +2591,7 @@
 void Element::cancelFocusAppearanceUpdate()
 {
     if (hasRareData())
-        elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
+        clearElementFlag(NeedsFocusAppearanceUpdateSoonAfterAttach);
     if (document().focusedElement() == this)
         document().cancelFocusAppearanceUpdate();
 }
@@ -2853,14 +2760,9 @@
     FullscreenElementStack::from(document()).requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
 }
 
-bool Element::containsFullScreenElement() const
-{
-    return hasRareData() && elementRareData()->containsFullScreenElement();
-}
-
 void Element::setContainsFullScreenElement(bool flag)
 {
-    ensureElementRareData().setContainsFullScreenElement(flag);
+    setElementFlag(ContainsFullScreenElement, flag);
     setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
@@ -2877,16 +2779,11 @@
         element->setContainsFullScreenElement(flag);
 }
 
-bool Element::isInTopLayer() const
-{
-    return hasRareData() && elementRareData()->isInTopLayer();
-}
-
 void Element::setIsInTopLayer(bool inTopLayer)
 {
     if (isInTopLayer() == inTopLayer)
         return;
-    ensureElementRareData().setIsInTopLayer(inTopLayer);
+    setElementFlag(IsInTopLayer, inTopLayer);
 
     // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
     // top layer position, or in its usual place if not in the top layer.
@@ -3314,21 +3211,6 @@
     return hasRareData() && elementRareData()->hasInputMethodContext();
 }
 
-bool Element::hasPendingResources() const
-{
-    return hasRareData() && elementRareData()->hasPendingResources();
-}
-
-void Element::setHasPendingResources()
-{
-    ensureElementRareData().setHasPendingResources(true);
-}
-
-void Element::clearHasPendingResources()
-{
-    ensureElementRareData().setHasPendingResources(false);
-}
-
 void Element::synchronizeStyleAttributeInternal() const
 {
     ASSERT(isStyledElement());
@@ -3529,8 +3411,7 @@
     // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
     // See comments in RenderObject::setStyle().
     // FIXME: Why does gaining a layer from outside the style system require disabling sharing?
-    if (isHTMLIFrameElement(*this)
-        || isHTMLFrameElement(*this)
+    if (isHTMLFrameElementBase(*this)
         || isHTMLEmbedElement(*this)
         || isHTMLObjectElement(*this)
         || isHTMLAppletElement(*this)
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index ff846f4..af0ff1d 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -43,6 +43,7 @@
 class Attribute;
 class ClientRect;
 class ClientRectList;
+class CustomElementDefinition;
 class DOMStringMap;
 class DOMTokenList;
 class ElementRareData;
@@ -75,6 +76,39 @@
     SpellcheckAttributeDefault
 };
 
+enum ElementFlags {
+    TabIndexWasSetExplicitly = 1 << 0,
+    NeedsFocusAppearanceUpdateSoonAfterAttach = 1 << 1,
+    StyleAffectedByEmpty = 1 << 2,
+    IsInCanvasSubtree = 1 << 3,
+    ContainsFullScreenElement = 1 << 4,
+    IsInTopLayer = 1 << 5,
+    HasPendingResources = 1 << 6,
+    ChildrenAffectedByFocus = 1 << 7,
+    ChildrenAffectedByHover = 1 << 8,
+    ChildrenAffectedByActive = 1 << 9,
+    ChildrenAffectedByDrag = 1 << 10,
+    ChildrenAffectedByFirstChildRules = 1 << 11,
+    ChildrenAffectedByLastChildRules = 1 << 12,
+    ChildrenAffectedByDirectAdjacentRules = 1 << 13,
+    ChildrenAffectedByIndirectAdjacentRules = 1 << 14,
+    ChildrenAffectedByForwardPositionalRules = 1 << 15,
+    ChildrenAffectedByBackwardPositionalRules = 1 << 16,
+
+    // If any of these flags are set we cannot share style.
+    ElementFlagsPreventingStyleSharing =
+        ChildrenAffectedByFocus
+        | ChildrenAffectedByHover
+        | ChildrenAffectedByActive
+        | ChildrenAffectedByDrag
+        | ChildrenAffectedByFirstChildRules
+        | ChildrenAffectedByLastChildRules
+        | ChildrenAffectedByDirectAdjacentRules
+        | ChildrenAffectedByIndirectAdjacentRules
+        | ChildrenAffectedByForwardPositionalRules
+        | ChildrenAffectedByBackwardPositionalRules,
+};
+
 class Element : public ContainerNode {
 public:
     static PassRefPtr<Element> create(const QualifiedName&, Document*);
@@ -278,6 +312,9 @@
     virtual void attributeChanged(const QualifiedName&, const AtomicString&, AttributeModificationReason = ModifiedDirectly);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) { }
 
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const;
+    virtual const QualifiedName& subResourceAttributeName() const;
+
     // Only called by the parser immediately after element construction.
     void parserSetAttributes(const Vector<Attribute>&);
 
@@ -325,35 +362,48 @@
     RenderStyle* computedStyle(PseudoId = NOPSEUDO);
 
     // Methods for indicating the style is affected by dynamic updates (e.g., children changing, our position changing in our sibling list, etc.)
-    bool styleAffectedByEmpty() const { return hasRareData() && rareDataStyleAffectedByEmpty(); }
-    bool childrenAffectedByFocus() const { return hasRareData() && rareDataChildrenAffectedByFocus(); }
-    bool childrenAffectedByHover() const { return hasRareData() && rareDataChildrenAffectedByHover(); }
-    bool childrenAffectedByActive() const { return hasRareData() && rareDataChildrenAffectedByActive(); }
-    bool childrenAffectedByDrag() const { return hasRareData() && rareDataChildrenAffectedByDrag(); }
-    bool childrenAffectedByPositionalRules() const { return hasRareData() && (rareDataChildrenAffectedByForwardPositionalRules() || rareDataChildrenAffectedByBackwardPositionalRules()); }
-    bool childrenAffectedByFirstChildRules() const { return hasRareData() && rareDataChildrenAffectedByFirstChildRules(); }
-    bool childrenAffectedByLastChildRules() const { return hasRareData() && rareDataChildrenAffectedByLastChildRules(); }
-    bool childrenAffectedByDirectAdjacentRules() const { return hasRareData() && rareDataChildrenAffectedByDirectAdjacentRules(); }
-    bool childrenAffectedByForwardPositionalRules() const { return hasRareData() && rareDataChildrenAffectedByForwardPositionalRules(); }
-    bool childrenAffectedByBackwardPositionalRules() const { return hasRareData() && rareDataChildrenAffectedByBackwardPositionalRules(); }
+    bool styleAffectedByEmpty() const { return hasElementFlag(StyleAffectedByEmpty); }
+    void setStyleAffectedByEmpty() { setElementFlag(StyleAffectedByEmpty); }
+
+    bool childrenAffectedByFocus() const { return hasElementFlag(ChildrenAffectedByFocus); }
+    void setChildrenAffectedByFocus() { setElementFlag(ChildrenAffectedByFocus); }
+
+    bool childrenAffectedByHover() const { return hasElementFlag(ChildrenAffectedByHover); }
+    void setChildrenAffectedByHover() { setElementFlag(ChildrenAffectedByHover); }
+
+    bool childrenAffectedByActive() const { return hasElementFlag(ChildrenAffectedByActive); }
+    void setChildrenAffectedByActive() { setElementFlag(ChildrenAffectedByActive); }
+
+    bool childrenAffectedByDrag() const { return hasElementFlag(ChildrenAffectedByDrag); }
+    void setChildrenAffectedByDrag() { setElementFlag(ChildrenAffectedByDrag); }
+
+    bool childrenAffectedByPositionalRules() const { return hasElementFlag(ChildrenAffectedByForwardPositionalRules) || hasElementFlag(ChildrenAffectedByBackwardPositionalRules); }
+
+    bool childrenAffectedByFirstChildRules() const { return hasElementFlag(ChildrenAffectedByFirstChildRules); }
+    void setChildrenAffectedByFirstChildRules() { setElementFlag(ChildrenAffectedByFirstChildRules); }
+
+    bool childrenAffectedByLastChildRules() const { return hasElementFlag(ChildrenAffectedByLastChildRules); }
+    void setChildrenAffectedByLastChildRules() { setElementFlag(ChildrenAffectedByLastChildRules); }
+
+    bool childrenAffectedByDirectAdjacentRules() const { return hasElementFlag(ChildrenAffectedByDirectAdjacentRules); }
+    void setChildrenAffectedByDirectAdjacentRules() { setElementFlag(ChildrenAffectedByDirectAdjacentRules); }
+
+    bool childrenAffectedByIndirectAdjacentRules() const { return hasElementFlag(ChildrenAffectedByIndirectAdjacentRules); }
+    void setChildrenAffectedByIndirectAdjacentRules() { setElementFlag(ChildrenAffectedByIndirectAdjacentRules); }
+
+    bool childrenAffectedByForwardPositionalRules() const { return hasElementFlag(ChildrenAffectedByForwardPositionalRules); }
+    void setChildrenAffectedByForwardPositionalRules() { setElementFlag(ChildrenAffectedByForwardPositionalRules); }
+
+    bool childrenAffectedByBackwardPositionalRules() const { return hasElementFlag(ChildrenAffectedByBackwardPositionalRules); }
+    void setChildrenAffectedByBackwardPositionalRules() { setElementFlag(ChildrenAffectedByBackwardPositionalRules); }
+
+    void setIsInCanvasSubtree(bool value) { setElementFlag(IsInCanvasSubtree, value); }
+    bool isInCanvasSubtree() const { return hasElementFlag(IsInCanvasSubtree); }
+
     unsigned childIndex() const { return hasRareData() ? rareDataChildIndex() : 0; }
-
-    bool childrenSupportStyleSharing() const;
-
-    void setStyleAffectedByEmpty();
-    void setChildrenAffectedByFocus();
-    void setChildrenAffectedByHover();
-    void setChildrenAffectedByActive();
-    void setChildrenAffectedByDrag();
-    void setChildrenAffectedByFirstChildRules();
-    void setChildrenAffectedByLastChildRules();
-    void setChildrenAffectedByDirectAdjacentRules();
-    void setChildrenAffectedByForwardPositionalRules();
-    void setChildrenAffectedByBackwardPositionalRules();
     void setChildIndex(unsigned);
 
-    void setIsInCanvasSubtree(bool);
-    bool isInCanvasSubtree() const;
+    bool childrenSupportStyleSharing() const { return !hasElementFlag(ElementFlagsPreventingStyleSharing); }
 
     bool isUpgradedCustomElement() { return customElementState() == Upgraded; }
     bool isUnresolvedCustomElement() { return customElementState() == WaitingForUpgrade; }
@@ -379,7 +429,7 @@
     // focusable but some elements, such as form controls and links, are. Unlike
     // rendererIsFocusable(), this method may be called when layout is not up to
     // date, so it must not use the renderer to determine focusability.
-    virtual bool supportsFocus() const;
+    virtual bool supportsFocus() const { return hasElementFlag(TabIndexWasSetExplicitly); }
     // Whether the node can actually be focused.
     bool isFocusable() const;
     virtual bool isKeyboardFocusable() const;
@@ -458,7 +508,6 @@
     virtual bool isValidFormControlElement() { return false; }
     virtual bool isInRange() const { return false; }
     virtual bool isOutOfRange() const { return false; }
-    virtual bool isFrameElementBase() const { return false; }
     virtual bool isPasswordGeneratorButtonElement() const { return false; }
     virtual bool isClearButtonElement() const { return false; }
 
@@ -468,25 +517,28 @@
     // to event listeners, and prevents DOMActivate events from being sent at all.
     virtual bool isDisabledFormControl() const { return false; }
 
-    bool hasPendingResources() const;
-    void setHasPendingResources();
-    void clearHasPendingResources();
+    bool hasPendingResources() const { return hasElementFlag(HasPendingResources); }
+    void setHasPendingResources() { setElementFlag(HasPendingResources); }
+    void clearHasPendingResources() { clearElementFlag(HasPendingResources); }
     virtual void buildPendingResource() { };
 
+    void setCustomElementDefinition(PassRefPtr<CustomElementDefinition>);
+    CustomElementDefinition* customElementDefinition() const;
+
     enum {
         ALLOW_KEYBOARD_INPUT = 1 << 0,
         LEGACY_MOZILLA_REQUEST = 1 << 1,
     };
 
     void webkitRequestFullScreen(unsigned short flags);
-    bool containsFullScreenElement() const;
+    bool containsFullScreenElement() const { return hasElementFlag(ContainsFullScreenElement); }
     void setContainsFullScreenElement(bool);
     void setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool);
 
     // W3C API
     void webkitRequestFullscreen();
 
-    bool isInTopLayer() const;
+    bool isInTopLayer() const { return hasElementFlag(IsInTopLayer); }
     void setIsInTopLayer(bool);
 
     void webkitRequestPointerLock();
@@ -563,6 +615,11 @@
     Node* insertAdjacent(const String& where, Node* newChild, ExceptionState&);
 
 private:
+    bool hasElementFlag(ElementFlags mask) const { return hasRareData() && hasElementFlagInternal(mask); }
+    void setElementFlag(ElementFlags, bool value = true);
+    void clearElementFlag(ElementFlags);
+    bool hasElementFlagInternal(ElementFlags) const;
+
     void styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason);
 
     void updatePresentationAttributeStyle();
@@ -635,16 +692,7 @@
     virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren();
 
     QualifiedName m_tagName;
-    bool rareDataStyleAffectedByEmpty() const;
-    bool rareDataChildrenAffectedByFocus() const;
-    bool rareDataChildrenAffectedByHover() const;
-    bool rareDataChildrenAffectedByActive() const;
-    bool rareDataChildrenAffectedByDrag() const;
-    bool rareDataChildrenAffectedByFirstChildRules() const;
-    bool rareDataChildrenAffectedByLastChildRules() const;
-    bool rareDataChildrenAffectedByDirectAdjacentRules() const;
-    bool rareDataChildrenAffectedByForwardPositionalRules() const;
-    bool rareDataChildrenAffectedByBackwardPositionalRules() const;
+
     unsigned rareDataChildIndex() const;
 
     SpellcheckAttributeState spellcheckAttributeState() const;
diff --git a/Source/core/dom/ElementRareData.cpp b/Source/core/dom/ElementRareData.cpp
index 8512151..f87ff42 100644
--- a/Source/core/dom/ElementRareData.cpp
+++ b/Source/core/dom/ElementRareData.cpp
@@ -40,7 +40,7 @@
     unsigned bitfields;
     LayoutSize sizeForResizing;
     IntSize scrollOffset;
-    void* pointers[11];
+    void* pointers[12];
 };
 
 CSSStyleDeclaration& ElementRareData::ensureInlineCSSStyleDeclaration(Element* ownerElement)
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index 40942a5..38d9107 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -27,6 +27,7 @@
 #include "core/dom/NamedNodeMap.h"
 #include "core/dom/NodeRareData.h"
 #include "core/dom/PseudoElement.h"
+#include "core/dom/custom/CustomElementDefinition.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/html/ClassList.h"
 #include "core/html/ime/InputMethodContext.h"
@@ -49,45 +50,24 @@
     void resetStyleState();
     void resetDynamicRestyleObservations();
 
-    short tabIndex() const { return m_tabIndex; }
-    void setTabIndexExplicitly(short index) { m_tabIndex = index; m_tabIndexWasSetExplicitly = true; }
-    bool tabIndexSetExplicitly() const { return m_tabIndexWasSetExplicitly; }
-    void clearTabIndexExplicitly() { m_tabIndex = 0; m_tabIndexWasSetExplicitly = false; }
+    short tabIndex() const { return m_tabindex; }
 
-    bool needsFocusAppearanceUpdateSoonAfterAttach() const { return m_needsFocusAppearanceUpdateSoonAfterAttach; }
-    void setNeedsFocusAppearanceUpdateSoonAfterAttach(bool needs) { m_needsFocusAppearanceUpdateSoonAfterAttach = needs; }
+    void setTabIndexExplicitly(short index)
+    {
+        m_tabindex = index;
+        setFlag(TabIndexWasSetExplicitly, true);
+    }
 
-    bool styleAffectedByEmpty() const { return m_styleAffectedByEmpty; }
-    void setStyleAffectedByEmpty(bool value) { m_styleAffectedByEmpty = value; }
+    void clearTabIndexExplicitly()
+    {
+        m_tabindex = 0;
+        clearFlag(TabIndexWasSetExplicitly);
+    }
 
-    bool isInCanvasSubtree() const { return m_isInCanvasSubtree; }
-    void setIsInCanvasSubtree(bool value) { m_isInCanvasSubtree = value; }
+    bool hasFlag(ElementFlags mask) const { return m_flags & mask; }
+    void setFlag(ElementFlags mask, bool value) { m_flags = (m_flags & ~mask) | (-(int32_t)value & mask); }
+    void clearFlag(ElementFlags mask) { m_flags &= ~mask; }
 
-    bool containsFullScreenElement() { return m_containsFullScreenElement; }
-    void setContainsFullScreenElement(bool value) { m_containsFullScreenElement = value; }
-
-    bool isInTopLayer() const { return m_isInTopLayer; }
-    void setIsInTopLayer(bool value) { m_isInTopLayer = value; }
-
-    bool childrenAffectedByFocus() const { return m_childrenAffectedByFocus; }
-    void setChildrenAffectedByFocus(bool value) { m_childrenAffectedByFocus = value; }
-    bool childrenAffectedByHover() const { return m_childrenAffectedByHover; }
-    void setChildrenAffectedByHover(bool value) { m_childrenAffectedByHover = value; }
-    bool childrenAffectedByActive() const { return m_childrenAffectedByActive; }
-    void setChildrenAffectedByActive(bool value) { m_childrenAffectedByActive = value; }
-    bool childrenAffectedByDrag() const { return m_childrenAffectedByDrag; }
-    void setChildrenAffectedByDrag(bool value) { m_childrenAffectedByDrag = value; }
-
-    bool childrenAffectedByFirstChildRules() const { return m_childrenAffectedByFirstChildRules; }
-    void setChildrenAffectedByFirstChildRules(bool value) { m_childrenAffectedByFirstChildRules = value; }
-    bool childrenAffectedByLastChildRules() const { return m_childrenAffectedByLastChildRules; }
-    void setChildrenAffectedByLastChildRules(bool value) { m_childrenAffectedByLastChildRules = value; }
-    bool childrenAffectedByDirectAdjacentRules() const { return m_childrenAffectedByDirectAdjacentRules; }
-    void setChildrenAffectedByDirectAdjacentRules(bool value) { m_childrenAffectedByDirectAdjacentRules = value; }
-    bool childrenAffectedByForwardPositionalRules() const { return m_childrenAffectedByForwardPositionalRules; }
-    void setChildrenAffectedByForwardPositionalRules(bool value) { m_childrenAffectedByForwardPositionalRules = value; }
-    bool childrenAffectedByBackwardPositionalRules() const { return m_childrenAffectedByBackwardPositionalRules; }
-    void setChildrenAffectedByBackwardPositionalRules(bool value) { m_childrenAffectedByBackwardPositionalRules = value; }
     unsigned childIndex() const { return m_childIndex; }
     void setChildIndex(unsigned index) { m_childIndex = index; }
 
@@ -133,9 +113,6 @@
         m_activeAnimations = activeAnimations;
     }
 
-    bool hasPendingResources() const { return m_hasPendingResources; }
-    void setHasPendingResources(bool has) { m_hasPendingResources = has; }
-
     bool hasInputMethodContext() const { return m_inputMethodContext; }
     InputMethodContext& ensureInputMethodContext(HTMLElement* element)
     {
@@ -147,32 +124,16 @@
     bool hasPseudoElements() const;
     void clearPseudoElements();
 
+    void setCustomElementDefinition(PassRefPtr<CustomElementDefinition> definition) { m_customElementDefinition = definition; }
+    CustomElementDefinition* customElementDefinition() const { return m_customElementDefinition.get(); }
+
 private:
-    short m_tabIndex;
+    short m_tabindex;
     unsigned short m_childIndex;
-    unsigned m_tabIndexWasSetExplicitly : 1;
-    unsigned m_needsFocusAppearanceUpdateSoonAfterAttach : 1;
-    unsigned m_styleAffectedByEmpty : 1;
-    unsigned m_isInCanvasSubtree : 1;
-    unsigned m_containsFullScreenElement : 1;
-    unsigned m_isInTopLayer : 1;
-    unsigned m_hasPendingResources : 1;
-    unsigned m_childrenAffectedByFocus : 1;
-    unsigned m_childrenAffectedByHover : 1;
-    unsigned m_childrenAffectedByActive : 1;
-    unsigned m_childrenAffectedByDrag : 1;
-    // Bits for dynamic child matching.
-    // We optimize for :first-child and :last-child. The other positional child selectors like nth-child or
-    // *-child-of-type, we will just give up and re-evaluate whenever children change at all.
-    unsigned m_childrenAffectedByFirstChildRules : 1;
-    unsigned m_childrenAffectedByLastChildRules : 1;
-    unsigned m_childrenAffectedByDirectAdjacentRules : 1;
-    unsigned m_childrenAffectedByForwardPositionalRules : 1;
-    unsigned m_childrenAffectedByBackwardPositionalRules : 1;
+    unsigned m_flags;
 
     LayoutSize m_minimumSizeForResizing;
     IntSize m_savedLayerScrollOffset;
-    RefPtr<RenderStyle> m_computedStyle;
 
     OwnPtr<DatasetDOMStringMap> m_dataset;
     OwnPtr<ClassList> m_classList;
@@ -182,11 +143,14 @@
     OwnPtr<ActiveAnimations> m_activeAnimations;
     OwnPtr<InlineCSSStyleDeclaration> m_cssomWrapper;
 
+    RefPtr<RenderStyle> m_computedStyle;
+    RefPtr<CustomElementDefinition> m_customElementDefinition;
+
     RefPtr<PseudoElement> m_generatedBefore;
     RefPtr<PseudoElement> m_generatedAfter;
     RefPtr<PseudoElement> m_backdrop;
 
-    ElementRareData(RenderObject*);
+    explicit ElementRareData(RenderObject*);
 };
 
 inline IntSize defaultMinimumSizeForResizing()
@@ -196,24 +160,9 @@
 
 inline ElementRareData::ElementRareData(RenderObject* renderer)
     : NodeRareData(renderer)
-    , m_tabIndex(0)
+    , m_tabindex(0)
     , m_childIndex(0)
-    , m_tabIndexWasSetExplicitly(false)
-    , m_needsFocusAppearanceUpdateSoonAfterAttach(false)
-    , m_styleAffectedByEmpty(false)
-    , m_isInCanvasSubtree(false)
-    , m_containsFullScreenElement(false)
-    , m_isInTopLayer(false)
-    , m_hasPendingResources(false)
-    , m_childrenAffectedByFocus(false)
-    , m_childrenAffectedByHover(false)
-    , m_childrenAffectedByActive(false)
-    , m_childrenAffectedByDrag(false)
-    , m_childrenAffectedByFirstChildRules(false)
-    , m_childrenAffectedByLastChildRules(false)
-    , m_childrenAffectedByDirectAdjacentRules(false)
-    , m_childrenAffectedByForwardPositionalRules(false)
-    , m_childrenAffectedByBackwardPositionalRules(false)
+    , m_flags(0)
     , m_minimumSizeForResizing(defaultMinimumSizeForResizing())
 {
 }
@@ -277,21 +226,22 @@
 
 inline void ElementRareData::resetStyleState()
 {
-    setStyleAffectedByEmpty(false);
+    clearFlag(StyleAffectedByEmpty);
     setChildIndex(0);
 }
 
 inline void ElementRareData::resetDynamicRestyleObservations()
 {
-    setChildrenAffectedByFocus(false);
-    setChildrenAffectedByHover(false);
-    setChildrenAffectedByActive(false);
-    setChildrenAffectedByDrag(false);
-    setChildrenAffectedByFirstChildRules(false);
-    setChildrenAffectedByLastChildRules(false);
-    setChildrenAffectedByDirectAdjacentRules(false);
-    setChildrenAffectedByForwardPositionalRules(false);
-    setChildrenAffectedByBackwardPositionalRules(false);
+    clearFlag(ChildrenAffectedByFocus);
+    clearFlag(ChildrenAffectedByHover);
+    clearFlag(ChildrenAffectedByActive);
+    clearFlag(ChildrenAffectedByDrag);
+    clearFlag(ChildrenAffectedByFirstChildRules);
+    clearFlag(ChildrenAffectedByLastChildRules);
+    clearFlag(ChildrenAffectedByDirectAdjacentRules);
+    clearFlag(ChildrenAffectedByIndirectAdjacentRules);
+    clearFlag(ChildrenAffectedByForwardPositionalRules);
+    clearFlag(ChildrenAffectedByBackwardPositionalRules);
 }
 
 } // namespace
diff --git a/Source/core/dom/IconURL.cpp b/Source/core/dom/IconURL.cpp
index 248835b..b427d1a 100644
--- a/Source/core/dom/IconURL.cpp
+++ b/Source/core/dom/IconURL.cpp
@@ -44,7 +44,7 @@
         url.setPort(documentURL.port());
     url.setPath("/favicon.ico");
 
-    IconURL result(url, emptyString(), emptyString(), Favicon);
+    IconURL result(url, Vector<IntSize>(), emptyString(), Favicon);
     result.m_isDefaultIcon = true;
     return result;
 }
diff --git a/Source/core/dom/IconURL.h b/Source/core/dom/IconURL.h
index d35b360..4a6fa23 100644
--- a/Source/core/dom/IconURL.h
+++ b/Source/core/dom/IconURL.h
@@ -31,6 +31,7 @@
 #ifndef IconURL_h
 #define IconURL_h
 
+#include "platform/geometry/IntSize.h"
 #include "platform/weborigin/KURL.h"
 
 namespace WebCore {
@@ -44,7 +45,7 @@
 
 struct IconURL {
     IconType m_iconType;
-    String m_sizes;
+    Vector<IntSize> m_sizes;
     String m_mimeType;
     KURL m_iconURL;
     bool m_isDefaultIcon;
@@ -55,7 +56,7 @@
     {
     }
 
-    IconURL(const KURL& url, const String& sizes, const String& mimeType, IconType type)
+    IconURL(const KURL& url, const Vector<IntSize>& sizes, const String& mimeType, IconType type)
         : m_iconType(type)
         , m_sizes(sizes)
         , m_mimeType(mimeType)
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index 33d1ff2..cce831a 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -245,7 +245,6 @@
     virtual bool isAttributeNode() const { return false; }
     virtual bool isCharacterDataNode() const { return false; }
     virtual bool isFrameOwnerElement() const { return false; }
-    virtual bool isPluginElement() const { return false; }
 
     // StyledElements allow inline style (style="border: 1px"), presentational attributes (ex. color),
     // class names (ex. class="foo bar") and other non-basic styling features. They and also control
@@ -613,8 +612,8 @@
     virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual ExecutionContext* executionContext() const OVERRIDE;
 
-    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE;
-    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE;
+    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture = false) OVERRIDE;
+    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture = false) OVERRIDE;
     virtual void removeAllEventListeners() OVERRIDE;
 
     // Handlers to do/undo actions on the target node before an event is dispatched to it and after the event
diff --git a/Source/core/dom/NodeRenderingTraversal.cpp b/Source/core/dom/NodeRenderingTraversal.cpp
index 496413e..6cee1a7 100644
--- a/Source/core/dom/NodeRenderingTraversal.cpp
+++ b/Source/core/dom/NodeRenderingTraversal.cpp
@@ -49,15 +49,9 @@
 {
     if (!m_insertionPoint) {
         m_insertionPoint = insertionPoint;
-        m_resetStyleInheritance  = m_resetStyleInheritance || insertionPoint->resetStyleInheritance();
     }
 }
 
-void ParentDetails::didTraverseShadowRoot(const ShadowRoot* root)
-{
-    m_resetStyleInheritance  = m_resetStyleInheritance || root->resetStyleInheritance();
-}
-
 ContainerNode* parent(const Node* node, ParentDetails* details)
 {
     // FIXME: We should probably ASSERT(!node->document().childNeedsDistributionRecalc()) here, but
diff --git a/Source/core/dom/NodeRenderingTraversal.h b/Source/core/dom/NodeRenderingTraversal.h
index 2d96b25..0a0bd9c 100644
--- a/Source/core/dom/NodeRenderingTraversal.h
+++ b/Source/core/dom/NodeRenderingTraversal.h
@@ -40,24 +40,19 @@
 public:
     ParentDetails()
         : m_insertionPoint(0)
-        , m_resetStyleInheritance(false)
     { }
 
     const InsertionPoint* insertionPoint() const { return m_insertionPoint; }
-    bool resetStyleInheritance() const { return m_resetStyleInheritance; }
 
     void didTraverseInsertionPoint(const InsertionPoint*);
-    void didTraverseShadowRoot(const ShadowRoot*);
 
     bool operator==(const ParentDetails& other)
     {
-        return m_insertionPoint == other.m_insertionPoint
-            && m_resetStyleInheritance == other.m_resetStyleInheritance;
+        return m_insertionPoint == other.m_insertionPoint;
     }
 
 private:
     const InsertionPoint* m_insertionPoint;
-    bool m_resetStyleInheritance;
 };
 
 ContainerNode* parent(const Node*);
diff --git a/Source/core/dom/ProcessingInstruction.cpp b/Source/core/dom/ProcessingInstruction.cpp
index ad3d494..e913a25 100644
--- a/Source/core/dom/ProcessingInstruction.cpp
+++ b/Source/core/dom/ProcessingInstruction.cpp
@@ -176,7 +176,7 @@
 
     RefPtrWillBeRawPtr<StyleSheetContents> newSheet = StyleSheetContents::create(href, parserContext);
 
-    RefPtr<CSSStyleSheet> cssSheet = CSSStyleSheet::create(newSheet, this);
+    RefPtrWillBeRawPtr<CSSStyleSheet> cssSheet = CSSStyleSheet::create(newSheet, this);
     cssSheet->setDisabled(m_alternate);
     cssSheet->setTitle(m_title);
     cssSheet->setMediaQueries(MediaQuerySet::create(m_media));
@@ -212,7 +212,7 @@
         toXSLStyleSheet(m_sheet.get())->checkLoaded();
 }
 
-void ProcessingInstruction::setCSSStyleSheet(PassRefPtr<CSSStyleSheet> sheet)
+void ProcessingInstruction::setCSSStyleSheet(PassRefPtrWillBeRawPtr<CSSStyleSheet> sheet)
 {
     ASSERT(!resource());
     ASSERT(!m_loading);
@@ -239,7 +239,7 @@
 
     document().styleEngine()->removeStyleSheetCandidateNode(this);
 
-    RefPtr<StyleSheet> removedSheet = m_sheet;
+    RefPtrWillBeRawPtr<StyleSheet> removedSheet = m_sheet;
 
     if (m_sheet) {
         ASSERT(m_sheet->ownerNode() == this);
diff --git a/Source/core/dom/ProcessingInstruction.h b/Source/core/dom/ProcessingInstruction.h
index 374534f..f8cc63b 100644
--- a/Source/core/dom/ProcessingInstruction.h
+++ b/Source/core/dom/ProcessingInstruction.h
@@ -43,7 +43,7 @@
 
     const String& localHref() const { return m_localHref; }
     StyleSheet* sheet() const { return m_sheet.get(); }
-    void setCSSStyleSheet(PassRefPtr<CSSStyleSheet>);
+    void setCSSStyleSheet(PassRefPtrWillBeRawPtr<CSSStyleSheet>);
 
     bool isCSS() const { return m_isCSS; }
     bool isXSL() const { return m_isXSL; }
@@ -73,7 +73,7 @@
     String m_localHref;
     String m_title;
     String m_media;
-    RefPtr<StyleSheet> m_sheet;
+    RefPtrWillBePersistent<StyleSheet> m_sheet;
     bool m_loading;
     bool m_alternate;
     bool m_createdByParser;
diff --git a/Source/core/dom/RenderTreeBuilder.cpp b/Source/core/dom/RenderTreeBuilder.cpp
index bb52e93..439e784 100644
--- a/Source/core/dom/RenderTreeBuilder.cpp
+++ b/Source/core/dom/RenderTreeBuilder.cpp
@@ -161,10 +161,7 @@
     Text* textNode = toText(m_node);
     RenderObject* parentRenderer = this->parentRenderer();
 
-    if (m_parentDetails.resetStyleInheritance())
-        m_style = textNode->document().ensureStyleResolver().defaultStyleForElement();
-    else
-        m_style = parentRenderer->style();
+    m_style = parentRenderer->style();
 
     if (!textNode->textRendererIsNeeded(*m_style, *parentRenderer))
         return;
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.h b/Source/core/dom/ShadowTreeStyleSheetCollection.h
index 25323d4..4639325 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.h
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.h
@@ -39,12 +39,18 @@
 class StyleEngine;
 
 class ShadowTreeStyleSheetCollection FINAL : public TreeScopeStyleSheetCollection {
-    WTF_MAKE_NONCOPYABLE(ShadowTreeStyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
+    WTF_MAKE_NONCOPYABLE(ShadowTreeStyleSheetCollection);
+    WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
 public:
     explicit ShadowTreeStyleSheetCollection(ShadowRoot&);
 
     bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
 
+    virtual void trace(Visitor* visitor) OVERRIDE
+    {
+        TreeScopeStyleSheetCollection::trace(visitor);
+    }
+
 private:
     void collectStyleSheets(StyleEngine*, StyleSheetCollection&);
 };
diff --git a/Source/core/dom/SiblingRuleHelper.cpp b/Source/core/dom/SiblingRuleHelper.cpp
index 7ebc4ca..baacc0f 100644
--- a/Source/core/dom/SiblingRuleHelper.cpp
+++ b/Source/core/dom/SiblingRuleHelper.cpp
@@ -28,6 +28,14 @@
         toShadowRoot(m_node)->setChildrenAffectedByDirectAdjacentRules();
 }
 
+void SiblingRuleHelper::setChildrenAffectedByIndirectAdjacentRules()
+{
+    if (m_node->isElementNode())
+        toElement(m_node)->setChildrenAffectedByIndirectAdjacentRules();
+    else
+        toShadowRoot(m_node)->setChildrenAffectedByIndirectAdjacentRules();
+}
+
 void SiblingRuleHelper::setChildrenAffectedByForwardPositionalRules()
 {
     if (m_node->isElementNode())
@@ -80,6 +88,11 @@
     return m_node->isElementNode() ? toElement(m_node)->childrenAffectedByDirectAdjacentRules() : toShadowRoot(m_node)->childrenAffectedByDirectAdjacentRules();
 }
 
+bool SiblingRuleHelper::childrenAffectedByIndirectAdjacentRules() const
+{
+    return m_node->isElementNode() ? toElement(m_node)->childrenAffectedByIndirectAdjacentRules() : toShadowRoot(m_node)->childrenAffectedByIndirectAdjacentRules();
+}
+
 bool SiblingRuleHelper::childrenAffectedByForwardPositionalRules() const
 {
     return m_node->isElementNode() ? toElement(m_node)->childrenAffectedByForwardPositionalRules() : toShadowRoot(m_node)->childrenAffectedByForwardPositionalRules();
@@ -93,7 +106,7 @@
 void SiblingRuleHelper::checkForChildrenAdjacentRuleChanges()
 {
     bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
-    bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
+    bool hasIndirectAdjacentRules = childrenAffectedByIndirectAdjacentRules();
 
     if (!hasDirectAdjacentRules && !hasIndirectAdjacentRules)
         return;
diff --git a/Source/core/dom/SiblingRuleHelper.h b/Source/core/dom/SiblingRuleHelper.h
index 1ae2d9c..47436c7 100644
--- a/Source/core/dom/SiblingRuleHelper.h
+++ b/Source/core/dom/SiblingRuleHelper.h
@@ -20,6 +20,7 @@
     void checkForChildrenAdjacentRuleChanges();
 
     void setChildrenAffectedByDirectAdjacentRules();
+    void setChildrenAffectedByIndirectAdjacentRules();
     void setChildrenAffectedByForwardPositionalRules();
     void setChildrenAffectedByBackwardPositionalRules();
     void setChildrenAffectedByFirstChildRules();
@@ -34,6 +35,7 @@
     bool childrenAffectedByFirstChildRules() const;
     bool childrenAffectedByLastChildRules() const;
     bool childrenAffectedByDirectAdjacentRules() const;
+    bool childrenAffectedByIndirectAdjacentRules() const;
     bool childrenAffectedByForwardPositionalRules() const;
     bool childrenAffectedByBackwardPositionalRules() const;
 
diff --git a/Source/core/dom/StyleElement.cpp b/Source/core/dom/StyleElement.cpp
index 5d377b8..1cc8e26 100644
--- a/Source/core/dom/StyleElement.cpp
+++ b/Source/core/dom/StyleElement.cpp
@@ -76,7 +76,7 @@
     ASSERT(element);
     document.styleEngine()->removeStyleSheetCandidateNode(element, scopingNode, treeScope);
 
-    RefPtr<StyleSheet> removedSheet = m_sheet;
+    RefPtrWillBeRawPtr<StyleSheet> removedSheet = m_sheet.get();
 
     if (m_sheet)
         clearSheet(element);
@@ -148,7 +148,7 @@
         if (screenEval.eval(mediaQueries.get()) || printEval.eval(mediaQueries.get())) {
             m_loading = true;
             TextPosition startPosition = m_startPosition == TextPosition::belowRangePosition() ? TextPosition::minimumPosition() : m_startPosition;
-            m_sheet = StyleEngine::createSheet(e, text, startPosition, m_createdByParser);
+            m_sheet = document.styleEngine()->createSheet(e, text, startPosition, m_createdByParser);
             m_sheet->setMediaQueries(mediaQueries.release());
             m_loading = false;
         }
diff --git a/Source/core/dom/StyleElement.h b/Source/core/dom/StyleElement.h
index b10337e..df23445 100644
--- a/Source/core/dom/StyleElement.h
+++ b/Source/core/dom/StyleElement.h
@@ -53,7 +53,7 @@
     void childrenChanged(Element*);
     void finishParsingChildren(Element*);
 
-    RefPtr<CSSStyleSheet> m_sheet;
+    RefPtrWillBePersistent<CSSStyleSheet> m_sheet;
 
 private:
     void createSheet(Element*, const String& text = String());
diff --git a/Source/core/dom/StyleEngine.cpp b/Source/core/dom/StyleEngine.cpp
index 756d3cc..5524bca 100644
--- a/Source/core/dom/StyleEngine.cpp
+++ b/Source/core/dom/StyleEngine.cpp
@@ -54,30 +54,6 @@
 
 using namespace HTMLNames;
 
-static WillBeHeapHashMap<AtomicString, RawPtrWillBeWeakMember<StyleSheetContents> >& textToSheetCache()
-{
-    typedef WillBeHeapHashMap<AtomicString, RawPtrWillBeWeakMember<StyleSheetContents> > TextToSheetCache;
-#if ENABLE(OILPAN)
-    DEFINE_STATIC_LOCAL(Persistent<TextToSheetCache>, cache, (new TextToSheetCache));
-    return *cache;
-#else
-    DEFINE_STATIC_LOCAL(TextToSheetCache, cache, ());
-    return cache;
-#endif
-}
-
-static WillBeHeapHashMap<RawPtrWillBeWeakMember<StyleSheetContents>, AtomicString>& sheetToTextCache()
-{
-    typedef WillBeHeapHashMap<RawPtrWillBeWeakMember<StyleSheetContents>, AtomicString> SheetToTextCache;
-#if ENABLE(OILPAN)
-    DEFINE_STATIC_LOCAL(Persistent<SheetToTextCache>, cache, (new SheetToTextCache));
-    return *cache;
-#else
-    DEFINE_STATIC_LOCAL(SheetToTextCache, cache, ());
-    return cache;
-#endif
-}
-
 StyleEngine::StyleEngine(Document& document)
     : m_document(document)
     , m_isMaster(HTMLImport::isMaster(&document))
@@ -167,9 +143,9 @@
     if (treeScope == m_document)
         return &m_documentStyleSheetCollection;
 
-    HashMap<TreeScope*, OwnPtr<TreeScopeStyleSheetCollection> >::AddResult result = m_styleSheetCollectionMap.add(&treeScope, nullptr);
+    WillBeHeapHashMap<TreeScope*, OwnPtrWillBeMember<ShadowTreeStyleSheetCollection> >::AddResult result = m_styleSheetCollectionMap.add(&treeScope, nullptr);
     if (result.isNewEntry)
-        result.storedValue->value = adoptPtr(new ShadowTreeStyleSheetCollection(toShadowRoot(treeScope)));
+        result.storedValue->value = adoptPtrWillBeNoop(new ShadowTreeStyleSheetCollection(toShadowRoot(treeScope)));
     return result.storedValue->value.get();
 }
 
@@ -178,7 +154,7 @@
     if (treeScope == m_document)
         return &m_documentStyleSheetCollection;
 
-    HashMap<TreeScope*, OwnPtr<TreeScopeStyleSheetCollection> >::iterator it = m_styleSheetCollectionMap.find(&treeScope);
+    WillBeHeapHashMap<TreeScope*, OwnPtrWillBeMember<ShadowTreeStyleSheetCollection> >::iterator it = m_styleSheetCollectionMap.find(&treeScope);
     if (it == m_styleSheetCollectionMap.end())
         return 0;
     return it->value.get();
@@ -586,25 +562,43 @@
         m_document.import()->master()->styleEngine()->markDocumentDirty();
 }
 
-PassRefPtr<CSSStyleSheet> StyleEngine::createSheet(Element* e, const String& text, TextPosition startPosition, bool createdByParser)
+static bool isCacheableForStyleElement(const StyleSheetContents& contents)
 {
-    RefPtr<CSSStyleSheet> styleSheet;
+    // FIXME: Support copying import rules.
+    if (!contents.importRules().isEmpty())
+        return false;
+    // Until import rules are supported in cached sheets it's not possible for loading to fail.
+    ASSERT(!contents.didLoadErrorOccur());
+    // It is not the original sheet anymore.
+    if (contents.isMutable())
+        return false;
+    if (!contents.hasSyntacticallyValidCSSHeader())
+        return false;
+    return true;
+}
+
+PassRefPtrWillBeRawPtr<CSSStyleSheet> StyleEngine::createSheet(Element* e, const String& text, TextPosition startPosition, bool createdByParser)
+{
+    RefPtrWillBeRawPtr<CSSStyleSheet> styleSheet;
 
     e->document().styleEngine()->addPendingSheet();
 
     if (!e->document().inQuirksMode()) {
         AtomicString textContent(text);
 
-        WillBeHeapHashMap<AtomicString, RawPtrWillBeWeakMember<StyleSheetContents> >::iterator it = textToSheetCache().find(textContent);
-        if (it == textToSheetCache().end()) {
+        HashMap<AtomicString, StyleSheetContents*>::AddResult result = m_textToSheetCache.add(textContent, 0);
+        if (result.isNewEntry || !result.storedValue->value) {
             styleSheet = StyleEngine::parseSheet(e, text, startPosition, createdByParser);
-            if (styleSheet->contents()->maybeCacheable()) {
-                textToSheetCache().add(textContent, styleSheet->contents());
-                sheetToTextCache().add(styleSheet->contents(), textContent);
+            if (result.isNewEntry && isCacheableForStyleElement(*styleSheet->contents())) {
+                result.storedValue->value = styleSheet->contents();
+                m_sheetToTextCache.add(styleSheet->contents(), textContent);
             }
         } else {
-            ASSERT(it->value->maybeCacheable());
-            styleSheet = CSSStyleSheet::createInline(it->value, e, startPosition);
+            StyleSheetContents* contents = result.storedValue->value;
+            ASSERT(contents);
+            ASSERT(isCacheableForStyleElement(*contents));
+            ASSERT(contents->singleOwnerDocument() == e->document());
+            styleSheet = CSSStyleSheet::createInline(contents, e, startPosition);
         }
     } else {
         // FIXME: currently we don't cache StyleSheetContents inQuirksMode.
@@ -616,9 +610,9 @@
     return styleSheet;
 }
 
-PassRefPtr<CSSStyleSheet> StyleEngine::parseSheet(Element* e, const String& text, TextPosition startPosition, bool createdByParser)
+PassRefPtrWillBeRawPtr<CSSStyleSheet> StyleEngine::parseSheet(Element* e, const String& text, TextPosition startPosition, bool createdByParser)
 {
-    RefPtr<CSSStyleSheet> styleSheet;
+    RefPtrWillBeRawPtr<CSSStyleSheet> styleSheet;
     styleSheet = CSSStyleSheet::createInline(e, KURL(), startPosition, e->document().inputEncoding());
     styleSheet->contents()->parseStringAtPosition(text, startPosition, createdByParser);
     return styleSheet;
@@ -626,18 +620,20 @@
 
 void StyleEngine::removeSheet(StyleSheetContents* contents)
 {
-    WillBeHeapHashMap<RawPtrWillBeWeakMember<StyleSheetContents>, AtomicString>::iterator it = sheetToTextCache().find(contents);
-    if (it == sheetToTextCache().end())
+    HashMap<StyleSheetContents*, AtomicString>::iterator it = m_sheetToTextCache.find(contents);
+    if (it == m_sheetToTextCache.end())
         return;
 
-    textToSheetCache().remove(it->value);
-    sheetToTextCache().remove(contents);
+    m_textToSheetCache.remove(it->value);
+    m_sheetToTextCache.remove(contents);
 }
 
 void StyleEngine::trace(Visitor* visitor)
 {
     visitor->trace(m_injectedAuthorStyleSheets);
     visitor->trace(m_authorStyleSheets);
+    visitor->trace(m_documentStyleSheetCollection);
+    visitor->trace(m_styleSheetCollectionMap);
 }
 
 }
diff --git a/Source/core/dom/StyleEngine.h b/Source/core/dom/StyleEngine.h
index 57daab1..dc6940a 100644
--- a/Source/core/dom/StyleEngine.h
+++ b/Source/core/dom/StyleEngine.h
@@ -32,6 +32,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/DocumentOrderedList.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
+#include "heap/Handle.h"
 #include "wtf/FastAllocBase.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/RefPtr.h"
@@ -184,8 +185,8 @@
 
     void markDocumentDirty();
 
-    static PassRefPtr<CSSStyleSheet> createSheet(Element*, const String& text, TextPosition startPosition, bool createdByParser);
-    static void removeSheet(StyleSheetContents*);
+    PassRefPtrWillBeRawPtr<CSSStyleSheet> createSheet(Element*, const String& text, TextPosition startPosition, bool createdByParser);
+    void removeSheet(StyleSheetContents*);
 
     void trace(Visitor*);
 
@@ -207,7 +208,7 @@
 
     void createResolver();
 
-    static PassRefPtr<CSSStyleSheet> parseSheet(Element*, const String& text, TextPosition startPosition, bool createdByParser);
+    static PassRefPtrWillBeRawPtr<CSSStyleSheet> parseSheet(Element*, const String& text, TextPosition startPosition, bool createdByParser);
 
     Document& m_document;
     bool m_isMaster;
@@ -224,7 +225,7 @@
     WillBeHeapVector<RefPtrWillBeMember<CSSStyleSheet> > m_authorStyleSheets;
 
     DocumentStyleSheetCollection m_documentStyleSheetCollection;
-    HashMap<TreeScope*, OwnPtr<TreeScopeStyleSheetCollection> > m_styleSheetCollectionMap;
+    WillBeHeapHashMap<TreeScope*, OwnPtrWillBeMember<ShadowTreeStyleSheetCollection> > m_styleSheetCollectionMap;
 
     bool m_documentScopeDirty;
     TreeScopeSet m_dirtyTreeScopes;
@@ -245,6 +246,9 @@
     OwnPtr<StyleResolver> m_resolver;
 
     RefPtr<CSSFontSelector> m_fontSelector;
+
+    HashMap<AtomicString, StyleSheetContents*> m_textToSheetCache;
+    HashMap<StyleSheetContents*, AtomicString> m_sheetToTextCache;
 };
 
 }
diff --git a/Source/core/dom/StyleSheetCollection.cpp b/Source/core/dom/StyleSheetCollection.cpp
index 9187d67..186f1a4 100644
--- a/Source/core/dom/StyleSheetCollection.cpp
+++ b/Source/core/dom/StyleSheetCollection.cpp
@@ -52,7 +52,7 @@
     m_styleSheetsForStyleSheetList.swap(sheets);
 }
 
-void StyleSheetCollection::appendActiveStyleSheets(const WillBePersistentHeapVector<RefPtrWillBeMember<CSSStyleSheet> >& sheets)
+void StyleSheetCollection::appendActiveStyleSheets(const WillBeHeapVector<RefPtrWillBeMember<CSSStyleSheet> >& sheets)
 {
     m_activeAuthorStyleSheets.appendVector(sheets);
 }
@@ -67,4 +67,10 @@
     m_styleSheetsForStyleSheetList.append(sheet);
 }
 
+void StyleSheetCollection::trace(Visitor* visitor)
+{
+    visitor->trace(m_activeAuthorStyleSheets);
+    visitor->trace(m_styleSheetsForStyleSheetList);
+}
+
 }
diff --git a/Source/core/dom/StyleSheetCollection.h b/Source/core/dom/StyleSheetCollection.h
index 7f0da11..231fead 100644
--- a/Source/core/dom/StyleSheetCollection.h
+++ b/Source/core/dom/StyleSheetCollection.h
@@ -38,14 +38,15 @@
 class CSSStyleSheet;
 class StyleSheet;
 
-class StyleSheetCollection {
-    WTF_MAKE_NONCOPYABLE(StyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
+class StyleSheetCollection : public NoBaseWillBeGarbageCollectedFinalized<StyleSheetCollection> {
+    WTF_MAKE_NONCOPYABLE(StyleSheetCollection);
+    WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
 public:
     friend class ActiveDocumentStyleSheetCollector;
     friend class ImportedDocumentStyleSheetCollector;
 
     StyleSheetCollection();
-    ~StyleSheetCollection();
+    virtual ~StyleSheetCollection();
 
     WillBeHeapVector<RefPtrWillBeMember<CSSStyleSheet> >& activeAuthorStyleSheets() { return m_activeAuthorStyleSheets; }
     WillBeHeapVector<RefPtrWillBeMember<StyleSheet> >& styleSheetsForStyleSheetList() { return m_styleSheetsForStyleSheetList; }
@@ -54,13 +55,15 @@
 
     void swap(StyleSheetCollection&);
     void swapSheetsForSheetList(WillBeHeapVector<RefPtrWillBeMember<StyleSheet> >&);
-    void appendActiveStyleSheets(const WillBePersistentHeapVector<RefPtrWillBeMember<CSSStyleSheet> >&);
+    void appendActiveStyleSheets(const WillBeHeapVector<RefPtrWillBeMember<CSSStyleSheet> >&);
     void appendActiveStyleSheet(CSSStyleSheet*);
     void appendSheetForList(StyleSheet*);
 
+    virtual void trace(Visitor*);
+
 protected:
-    WillBePersistentHeapVector<RefPtrWillBeMember<StyleSheet> > m_styleSheetsForStyleSheetList;
-    WillBePersistentHeapVector<RefPtrWillBeMember<CSSStyleSheet> > m_activeAuthorStyleSheets;
+    WillBeHeapVector<RefPtrWillBeMember<StyleSheet> > m_styleSheetsForStyleSheetList;
+    WillBeHeapVector<RefPtrWillBeMember<CSSStyleSheet> > m_activeAuthorStyleSheets;
 };
 
 }
diff --git a/Source/core/dom/TreeScopeStyleSheetCollection.h b/Source/core/dom/TreeScopeStyleSheetCollection.h
index f2141c3..6d7b976 100644
--- a/Source/core/dom/TreeScopeStyleSheetCollection.h
+++ b/Source/core/dom/TreeScopeStyleSheetCollection.h
@@ -56,7 +56,6 @@
     void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode);
     bool hasStyleSheetCandidateNodes() const { return !m_styleSheetCandidateNodes.isEmpty(); }
 
-
     bool usesRemUnits() const { return m_usesRemUnits; }
 
     DocumentOrderedList& styleSheetCandidateNodes() { return m_styleSheetCandidateNodes; }
@@ -65,6 +64,11 @@
 
     void clearMediaQueryRuleSetStyleSheets();
 
+    virtual void trace(Visitor* visitor) OVERRIDE
+    {
+        StyleSheetCollection::trace(visitor);
+    }
+
 protected:
     explicit TreeScopeStyleSheetCollection(TreeScope&);
 
diff --git a/Source/core/dom/custom/CustomElement.cpp b/Source/core/dom/custom/CustomElement.cpp
index 2415e4d..4810925 100644
--- a/Source/core/dom/custom/CustomElement.cpp
+++ b/Source/core/dom/custom/CustomElement.cpp
@@ -97,23 +97,16 @@
         break;
 
     case Element::WaitingForUpgrade:
-        definitions().add(element, definition);
+        element->setCustomElementDefinition(definition);
         CustomElementScheduler::scheduleCreatedCallback(definition->callbacks(), element);
         break;
     }
 }
 
-CustomElementDefinition* CustomElement::definitionFor(Element* element)
-{
-    CustomElementDefinition* definition = definitions().get(element);
-    ASSERT(definition);
-    return definition;
-}
-
 void CustomElement::attributeDidChange(Element* element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
 {
     ASSERT(element->customElementState() == Element::Upgraded);
-    CustomElementScheduler::scheduleAttributeChangedCallback(definitionFor(element)->callbacks(), element, name, oldValue, newValue);
+    CustomElementScheduler::scheduleAttributeChangedCallback(element->customElementDefinition()->callbacks(), element, name, oldValue, newValue);
 }
 
 void CustomElement::didEnterDocument(Element* element, const Document& document)
@@ -121,7 +114,7 @@
     ASSERT(element->customElementState() == Element::Upgraded);
     if (!document.domWindow())
         return;
-    CustomElementScheduler::scheduleAttachedCallback(definitionFor(element)->callbacks(), element);
+    CustomElementScheduler::scheduleAttachedCallback(element->customElementDefinition()->callbacks(), element);
 }
 
 void CustomElement::didLeaveDocument(Element* element, const Document& document)
@@ -129,7 +122,7 @@
     ASSERT(element->customElementState() == Element::Upgraded);
     if (!document.domWindow())
         return;
-    CustomElementScheduler::scheduleDetachedCallback(definitionFor(element)->callbacks(), element);
+    CustomElementScheduler::scheduleDetachedCallback(element->customElementDefinition()->callbacks(), element);
 }
 
 void CustomElement::wasDestroyed(Element* element)
@@ -141,23 +134,9 @@
 
     case Element::WaitingForUpgrade:
     case Element::Upgraded:
-        definitions().remove(element);
         CustomElementObserver::notifyElementWasDestroyed(element);
         break;
     }
 }
 
-void CustomElement::DefinitionMap::add(Element* element, PassRefPtr<CustomElementDefinition> definition)
-{
-    ASSERT(definition.get());
-    DefinitionMap::ElementDefinitionHashMap::AddResult result = m_definitions.add(element, definition);
-    ASSERT_UNUSED(result, result.isNewEntry);
-}
-
-CustomElement::DefinitionMap& CustomElement::definitions()
-{
-    DEFINE_STATIC_LOCAL(DefinitionMap, map, ());
-    return map;
-}
-
 } // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElement.h b/Source/core/dom/custom/CustomElement.h
index 2fb4add..c9504eb 100644
--- a/Source/core/dom/custom/CustomElement.h
+++ b/Source/core/dom/custom/CustomElement.h
@@ -62,9 +62,6 @@
     // API for registration contexts
     static void define(Element*, PassRefPtr<CustomElementDefinition>);
 
-    // API for wrapper creation, which uses a definition as a key
-    static CustomElementDefinition* definitionFor(Element*);
-
     // API for Element to kick off changes
 
     static void attributeDidChange(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
@@ -76,24 +73,6 @@
     CustomElement();
 
     static Vector<AtomicString>& embedderCustomElementNames();
-
-    // Maps resolved elements to their definitions
-
-    class DefinitionMap {
-        WTF_MAKE_NONCOPYABLE(DefinitionMap);
-    public:
-        DefinitionMap() { }
-        ~DefinitionMap() { }
-
-        void add(Element*, PassRefPtr<CustomElementDefinition>);
-        void remove(Element* element) { m_definitions.remove(element); }
-        CustomElementDefinition* get(Element* element) const { return m_definitions.get(element); }
-
-    private:
-        typedef HashMap<Element*, RefPtr<CustomElementDefinition> > ElementDefinitionHashMap;
-        ElementDefinitionHashMap m_definitions;
-    };
-    static DefinitionMap& definitions();
 };
 
 }
diff --git a/Source/core/dom/shadow/ComposedTreeWalker.cpp b/Source/core/dom/shadow/ComposedTreeWalker.cpp
index 55390f6..0ea969d 100644
--- a/Source/core/dom/shadow/ComposedTreeWalker.cpp
+++ b/Source/core/dom/shadow/ComposedTreeWalker.cpp
@@ -139,14 +139,14 @@
             // The node is distributed. But the distribution was stopped at this insertion point.
             if (shadowWhereNodeCanBeDistributed(*insertionPoint))
                 return 0;
-            return traverseParentOrHost(insertionPoint, details);
+            return traverseParentOrHost(insertionPoint);
         }
         return 0;
     }
-    return traverseParentOrHost(node, details);
+    return traverseParentOrHost(node);
 }
 
-inline Node* ComposedTreeWalker::traverseParentOrHost(const Node* node, ParentTraversalDetails* details) const
+inline Node* ComposedTreeWalker::traverseParentOrHost(const Node* node) const
 {
     Node* parent = node->parentNode();
     if (!parent)
@@ -157,8 +157,6 @@
     ASSERT(!shadowRoot->shadowInsertionPointOfYoungerShadowRoot());
     if (!shadowRoot->isYoungest())
         return 0;
-    if (details)
-        details->didTraverseShadowRoot(shadowRoot);
     return shadowRoot->host();
 }
 
diff --git a/Source/core/dom/shadow/ComposedTreeWalker.h b/Source/core/dom/shadow/ComposedTreeWalker.h
index b750e34..9d5ee99 100644
--- a/Source/core/dom/shadow/ComposedTreeWalker.h
+++ b/Source/core/dom/shadow/ComposedTreeWalker.h
@@ -107,7 +107,7 @@
 
     static Node* traverseBackToYoungerShadowRoot(const Node*, TraversalDirection);
 
-    Node* traverseParentOrHost(const Node*, ParentTraversalDetails* = 0) const;
+    Node* traverseParentOrHost(const Node*) const;
 
     const Node* m_node;
 };
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
index 690cb8e..b072066 100644
--- a/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -247,26 +247,6 @@
     HTMLElement::removedFrom(insertionPoint);
 }
 
-void InsertionPoint::parseAttribute(const QualifiedName& name, const AtomicString& value)
-{
-    if (name == reset_style_inheritanceAttr) {
-        if (!inDocument() || !isActive())
-            return;
-        containingShadowRoot()->host()->setNeedsStyleRecalc(SubtreeStyleChange);
-    } else
-        HTMLElement::parseAttribute(name, value);
-}
-
-bool InsertionPoint::resetStyleInheritance() const
-{
-    return fastHasAttribute(reset_style_inheritanceAttr);
-}
-
-void InsertionPoint::setResetStyleInheritance(bool value)
-{
-    setBooleanAttribute(reset_style_inheritanceAttr, value);
-}
-
 const InsertionPoint* resolveReprojection(const Node* projectedNode)
 {
     ASSERT(projectedNode);
diff --git a/Source/core/dom/shadow/InsertionPoint.h b/Source/core/dom/shadow/InsertionPoint.h
index 75cc3c5..76d983f 100644
--- a/Source/core/dom/shadow/InsertionPoint.h
+++ b/Source/core/dom/shadow/InsertionPoint.h
@@ -56,9 +56,6 @@
 
     virtual bool canAffectSelector() const { return false; }
 
-    bool resetStyleInheritance() const;
-    void setResetStyleInheritance(bool);
-
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
 
@@ -77,7 +74,6 @@
     virtual void childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
 
 private:
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index c781db0..736858e 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -57,7 +57,6 @@
     , m_next(0)
     , m_numberOfStyles(0)
     , m_applyAuthorStyles(false)
-    , m_resetStyleInheritance(false)
     , m_type(type)
     , m_registeredWithParentShadowRoot(false)
     , m_descendantInsertionPointsIsValid(false)
@@ -142,11 +141,6 @@
     // ShadowRoot doesn't support custom callbacks.
     ASSERT(!hasCustomStyleCallbacks());
 
-    // If we're propagating an Inherit change and this ShadowRoot resets
-    // inheritance we don't need to look at the children.
-    if (change <= Inherit && resetStyleInheritance() && !needsStyleRecalc() && !childNeedsStyleRecalc())
-        return;
-
     StyleResolver& styleResolver = document().ensureStyleResolver();
     styleResolver.pushParentShadowRoot(*this);
 
@@ -216,21 +210,6 @@
     setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
-void ShadowRoot::setResetStyleInheritance(bool value)
-{
-    if (isOrphan())
-        return;
-
-    if (value == resetStyleInheritance())
-        return;
-
-    m_resetStyleInheritance = value;
-    if (!isActiveForStyling())
-        return;
-
-    setNeedsStyleRecalc(SubtreeStyleChange);
-}
-
 void ShadowRoot::attach(const AttachContext& context)
 {
     StyleResolver& styleResolver = document().ensureStyleResolver();
@@ -411,6 +390,7 @@
     return !m_shadowRootRareData->childrenAffectedByFirstChildRules()
         && !m_shadowRootRareData->childrenAffectedByLastChildRules()
         && !m_shadowRootRareData->childrenAffectedByDirectAdjacentRules()
+        && !m_shadowRootRareData->childrenAffectedByIndirectAdjacentRules()
         && !m_shadowRootRareData->childrenAffectedByForwardPositionalRules()
         && !m_shadowRootRareData->childrenAffectedByBackwardPositionalRules();
 }
@@ -435,6 +415,11 @@
     return m_shadowRootRareData && m_shadowRootRareData->childrenAffectedByDirectAdjacentRules();
 }
 
+bool ShadowRoot::childrenAffectedByIndirectAdjacentRules() const
+{
+    return m_shadowRootRareData && m_shadowRootRareData->childrenAffectedByIndirectAdjacentRules();
+}
+
 bool ShadowRoot::childrenAffectedByForwardPositionalRules() const
 {
     return m_shadowRootRareData && m_shadowRootRareData->childrenAffectedByForwardPositionalRules();
@@ -455,6 +440,11 @@
     ensureShadowRootRareData()->setChildrenAffectedByDirectAdjacentRules(true);
 }
 
+void ShadowRoot::setChildrenAffectedByIndirectAdjacentRules()
+{
+    ensureShadowRootRareData()->setChildrenAffectedByIndirectAdjacentRules(true);
+}
+
 void ShadowRoot::setChildrenAffectedByBackwardPositionalRules()
 {
     ensureShadowRootRareData()->setChildrenAffectedByBackwardPositionalRules(true);
diff --git a/Source/core/dom/shadow/ShadowRoot.h b/Source/core/dom/shadow/ShadowRoot.h
index 43091ff..d11e9ae 100644
--- a/Source/core/dom/shadow/ShadowRoot.h
+++ b/Source/core/dom/shadow/ShadowRoot.h
@@ -113,9 +113,6 @@
     bool applyAuthorStyles() const { return m_applyAuthorStyles; }
     void setApplyAuthorStyles(bool);
 
-    bool resetStyleInheritance() const { return m_resetStyleInheritance; }
-    void setResetStyleInheritance(bool);
-
     ShadowRoot* olderShadowRoot() const { return next(); }
 
     String innerHTML() const;
@@ -132,12 +129,14 @@
     bool childrenAffectedByFirstChildRules() const;
     bool childrenAffectedByLastChildRules() const;
     bool childrenAffectedByDirectAdjacentRules() const;
+    bool childrenAffectedByIndirectAdjacentRules() const;
     bool childrenAffectedByForwardPositionalRules() const;
     bool childrenAffectedByBackwardPositionalRules() const;
 
     void setChildrenAffectedByFirstChildRules();
     void setChildrenAffectedByLastChildRules();
     void setChildrenAffectedByDirectAdjacentRules();
+    void setChildrenAffectedByIndirectAdjacentRules();
     void setChildrenAffectedByForwardPositionalRules();
     void setChildrenAffectedByBackwardPositionalRules();
 
@@ -167,7 +166,6 @@
     OwnPtr<ShadowRootRareData> m_shadowRootRareData;
     unsigned m_numberOfStyles : 27;
     unsigned m_applyAuthorStyles : 1;
-    unsigned m_resetStyleInheritance : 1;
     unsigned m_type : 1;
     unsigned m_registeredWithParentShadowRoot : 1;
     unsigned m_descendantInsertionPointsIsValid : 1;
diff --git a/Source/core/dom/shadow/ShadowRoot.idl b/Source/core/dom/shadow/ShadowRoot.idl
index 241c2f6..ececba5 100644
--- a/Source/core/dom/shadow/ShadowRoot.idl
+++ b/Source/core/dom/shadow/ShadowRoot.idl
@@ -29,7 +29,6 @@
 ] interface ShadowRoot : DocumentFragment {
     readonly attribute Element activeElement;
     [DeprecateAs=ShadowRootApplyAuthorStyles] attribute boolean applyAuthorStyles;
-    attribute boolean resetStyleInheritance;
     [RuntimeEnabled=ShadowDOM, ImplementedAs=olderShadowRootForBindings] readonly attribute ShadowRoot olderShadowRoot;
 
     [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, RaisesException=Setter] attribute DOMString innerHTML;
diff --git a/Source/core/dom/shadow/ShadowRootRareData.h b/Source/core/dom/shadow/ShadowRootRareData.h
index 051579a..cbc85d0 100644
--- a/Source/core/dom/shadow/ShadowRootRareData.h
+++ b/Source/core/dom/shadow/ShadowRootRareData.h
@@ -44,6 +44,7 @@
         , m_descendantContentElementCount(0)
         , m_childShadowRootCount(0)
         , m_childrenAffectedByDirectAdjacentRules(false)
+        , m_childrenAffectedByIndirectAdjacentRules(false)
         , m_childrenAffectedByForwardPositionalRules(false)
         , m_childrenAffectedByBackwardPositionalRules(false)
         , m_childrenAffectedByFirstChildRules(false)
@@ -77,6 +78,10 @@
 
     bool childrenAffectedByDirectAdjacentRules() const { return m_childrenAffectedByDirectAdjacentRules; }
     void setChildrenAffectedByDirectAdjacentRules(bool value) { m_childrenAffectedByDirectAdjacentRules = value; }
+
+    bool childrenAffectedByIndirectAdjacentRules() const { return m_childrenAffectedByIndirectAdjacentRules; }
+    void setChildrenAffectedByIndirectAdjacentRules(bool value) { m_childrenAffectedByIndirectAdjacentRules = value; }
+
     bool childrenAffectedByForwardPositionalRules() const { return m_childrenAffectedByForwardPositionalRules; }
     void setChildrenAffectedByForwardPositionalRules(bool value) { m_childrenAffectedByForwardPositionalRules = value; }
 
@@ -98,6 +103,7 @@
     RefPtrWillBePersistent<StyleSheetList> m_styleSheetList;
 
     unsigned m_childrenAffectedByDirectAdjacentRules : 1;
+    unsigned m_childrenAffectedByIndirectAdjacentRules : 1;
     unsigned m_childrenAffectedByForwardPositionalRules : 1;
     unsigned m_childrenAffectedByBackwardPositionalRules : 1;
     unsigned m_childrenAffectedByFirstChildRules : 1;
diff --git a/Source/core/editing/ApplyStyleCommand.cpp b/Source/core/editing/ApplyStyleCommand.cpp
index 4d70f21..553e54c 100644
--- a/Source/core/editing/ApplyStyleCommand.cpp
+++ b/Source/core/editing/ApplyStyleCommand.cpp
@@ -292,7 +292,7 @@
         updateStartEnd(startRange->startPosition(), endRange->startPosition());
 }
 
-static PassRefPtr<MutableStylePropertySet> copyStyleOrCreateEmpty(const StylePropertySet* style)
+static PassRefPtrWillBeRawPtr<MutableStylePropertySet> copyStyleOrCreateEmpty(const StylePropertySet* style)
 {
     if (!style)
         return MutableStylePropertySet::create();
@@ -401,7 +401,7 @@
         }
         lastStyledNode = node;
 
-        RefPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
+        RefPtrWillBeRawPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
         float currentFontSize = computedFontSize(node);
         float desiredFontSize = max(MinimumFontSize, startingFontSizes.get(node) + style->fontSizeDelta());
         RefPtrWillBeRawPtr<CSSValue> value = inlineStyle->getPropertyCSSValue(CSSPropertyFontSize);
@@ -525,7 +525,7 @@
             // other attributes, like we (should) do with B and I elements.
             removeNodeAttribute(element, dirAttr);
         } else {
-            RefPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
+            RefPtrWillBeRawPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
             inlineStyle->setProperty(CSSPropertyUnicodeBidi, CSSValueNormal);
             inlineStyle->removeProperty(CSSPropertyDirection);
             setNodeAttribute(element, styleAttr, AtomicString(inlineStyle->asText()));
@@ -773,7 +773,7 @@
             next = NodeTraversal::nextSkippingChildren(*node);
             if (!style->style())
                 continue;
-            RefPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
+            RefPtrWillBeRawPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
             inlineStyle->mergeAndOverrideOnConflict(style->style());
             setNodeAttribute(element, styleAttr, AtomicString(inlineStyle->asText()));
             continue;
diff --git a/Source/core/editing/EditingStyle.cpp b/Source/core/editing/EditingStyle.cpp
index 5ab6d5b..55a91b6 100644
--- a/Source/core/editing/EditingStyle.cpp
+++ b/Source/core/editing/EditingStyle.cpp
@@ -122,7 +122,7 @@
 }
 
 template <class StyleDeclarationType>
-static PassRefPtr<MutableStylePropertySet> copyEditingProperties(StyleDeclarationType* style, EditingPropertiesType type = OnlyInheritableEditingProperties)
+static PassRefPtrWillBeRawPtr<MutableStylePropertySet> copyEditingProperties(StyleDeclarationType* style, EditingPropertiesType type = OnlyInheritableEditingProperties)
 {
     if (type == AllEditingProperties)
         return style->copyPropertiesInSet(allEditingProperties());
@@ -134,14 +134,14 @@
     return allEditingProperties().contains(static_cast<CSSPropertyID>(id));
 }
 
-static PassRefPtr<MutableStylePropertySet> editingStyleFromComputedStyle(PassRefPtr<CSSComputedStyleDeclaration> style, EditingPropertiesType type = OnlyInheritableEditingProperties)
+static PassRefPtrWillBeRawPtr<MutableStylePropertySet> editingStyleFromComputedStyle(PassRefPtr<CSSComputedStyleDeclaration> style, EditingPropertiesType type = OnlyInheritableEditingProperties)
 {
     if (!style)
         return MutableStylePropertySet::create();
     return copyEditingProperties(style.get(), type);
 }
 
-static PassRefPtr<MutableStylePropertySet> getPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, CSSStyleDeclaration* baseStyle);
+static PassRefPtrWillBeRawPtr<MutableStylePropertySet> getPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, CSSStyleDeclaration* baseStyle);
 enum LegacyFontSizeMode { AlwaysUseLegacyFontSize, UseLegacyFontSizeOnlyIfPixelValuesMatch };
 static int legacyFontSizeFromCSSValue(Document*, CSSPrimitiveValue*, bool shouldUseFixedFontDefaultSize, LegacyFontSizeMode);
 static bool isTransparentColorValue(CSSValue*);
@@ -294,7 +294,7 @@
     if (value.isNull())
         return nullptr;
 
-    RefPtr<MutableStylePropertySet> dummyStyle;
+    RefPtrWillBeRawPtr<MutableStylePropertySet> dummyStyle;
     dummyStyle = MutableStylePropertySet::create();
     dummyStyle->setProperty(m_propertyID, value);
     return dummyStyle->getPropertyCSSValue(m_propertyID);
@@ -616,8 +616,8 @@
 {
     if (!node || !node->parentNode())
         return;
-    RefPtr<MutableStylePropertySet> parentStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node->parentNode()), AllEditingProperties);
-    RefPtr<MutableStylePropertySet> nodeStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node), AllEditingProperties);
+    RefPtrWillBeRawPtr<MutableStylePropertySet> parentStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node->parentNode()), AllEditingProperties);
+    RefPtrWillBeRawPtr<MutableStylePropertySet> nodeStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node), AllEditingProperties);
     nodeStyle->removeEquivalentProperties(parentStyle.get());
     m_mutableStyle->removeEquivalentProperties(nodeStyle.get());
 }
@@ -627,8 +627,8 @@
     if (!node || !node->parentNode() || !m_mutableStyle)
         return;
 
-    RefPtr<MutableStylePropertySet> parentStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node->parentNode()), AllEditingProperties);
-    RefPtr<MutableStylePropertySet> nodeStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node), AllEditingProperties);
+    RefPtrWillBeRawPtr<MutableStylePropertySet> parentStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node->parentNode()), AllEditingProperties);
+    RefPtrWillBeRawPtr<MutableStylePropertySet> nodeStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node), AllEditingProperties);
     nodeStyle->removeEquivalentProperties(parentStyle.get());
 
     unsigned propertyCount = nodeStyle->propertyCount();
@@ -673,7 +673,7 @@
 
 TriState EditingStyle::triStateOfStyle(CSSStyleDeclaration* styleToCompare, ShouldIgnoreTextOnlyProperties shouldIgnoreTextOnlyProperties) const
 {
-    RefPtr<MutableStylePropertySet> difference = getPropertiesNotIn(m_mutableStyle.get(), styleToCompare);
+    RefPtrWillBeRawPtr<MutableStylePropertySet> difference = getPropertiesNotIn(m_mutableStyle.get(), styleToCompare);
 
     if (shouldIgnoreTextOnlyProperties == IgnoreTextOnlyProperties)
         difference->removePropertiesInSet(textOnlyProperties, WTF_ARRAY_LENGTH(textOnlyProperties));
@@ -1002,7 +1002,7 @@
         && (mode == EditingStyle::OverrideValues || !equivalent->propertyExistsInStyle(style));
 }
 
-static PassRefPtr<MutableStylePropertySet> extractEditingProperties(const StylePropertySet* style, EditingStyle::PropertiesToInclude propertiesToInclude)
+static PassRefPtrWillBeRawPtr<MutableStylePropertySet> extractEditingProperties(const StylePropertySet* style, EditingStyle::PropertiesToInclude propertiesToInclude)
 {
     if (!style)
         return nullptr;
@@ -1115,9 +1115,9 @@
     }
 }
 
-static PassRefPtr<MutableStylePropertySet> styleFromMatchedRulesForElement(Element* element, unsigned rulesToInclude)
+static PassRefPtrWillBeRawPtr<MutableStylePropertySet> styleFromMatchedRulesForElement(Element* element, unsigned rulesToInclude)
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     RefPtr<StyleRuleList> matchedRules = element->document().ensureStyleResolver().styleRulesForElement(element, rulesToInclude);
     if (matchedRules) {
         for (unsigned i = 0; i < matchedRules->m_list.size(); ++i)
@@ -1128,7 +1128,7 @@
 
 void EditingStyle::mergeStyleFromRules(Element* element)
 {
-    RefPtr<MutableStylePropertySet> styleFromMatchedRules = styleFromMatchedRulesForElement(element,
+    RefPtrWillBeRawPtr<MutableStylePropertySet> styleFromMatchedRules = styleFromMatchedRulesForElement(element,
         StyleResolver::AuthorCSSRules | StyleResolver::CrossOriginCSSRules);
     // Styles from the inline style declaration, held in the variable "style", take precedence
     // over those from matched rules.
@@ -1147,7 +1147,7 @@
     // For example: style="height: 1%; overflow: visible;" in quirksmode
     // FIXME: There are others like this, see <rdar://problem/5195123> Slashdot copy/paste fidelity problem
     RefPtr<CSSComputedStyleDeclaration> computedStyleForElement = CSSComputedStyleDeclaration::create(element);
-    RefPtr<MutableStylePropertySet> fromComputedStyle = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> fromComputedStyle = MutableStylePropertySet::create();
     {
         unsigned propertyCount = m_mutableStyle->propertyCount();
         for (unsigned i = 0; i < propertyCount; ++i) {
@@ -1181,7 +1181,7 @@
         return;
 
     // 1. Remove style from matched rules because style remain without repeating it in inline style declaration
-    RefPtr<MutableStylePropertySet> styleFromMatchedRules = styleFromMatchedRulesForElement(element, StyleResolver::AllButEmptyCSSRules);
+    RefPtrWillBeRawPtr<MutableStylePropertySet> styleFromMatchedRules = styleFromMatchedRulesForElement(element, StyleResolver::AllButEmptyCSSRules);
     if (styleFromMatchedRules && !styleFromMatchedRules->isEmpty())
         m_mutableStyle = getPropertiesNotIn(m_mutableStyle.get(), styleFromMatchedRules->ensureCSSStyleDeclaration());
 
@@ -1383,7 +1383,7 @@
 
     RefPtr<CSSComputedStyleDeclaration> computedStyle = position.computedStyle();
     // FIXME: take care of background-color in effect
-    RefPtr<MutableStylePropertySet> mutableStyle = getPropertiesNotIn(style->style(), computedStyle.get());
+    RefPtrWillBeRawPtr<MutableStylePropertySet> mutableStyle = getPropertiesNotIn(style->style(), computedStyle.get());
 
     reconcileTextDecorationProperties(mutableStyle.get());
     if (!document->frame()->editor().shouldStyleWithCSS())
@@ -1530,11 +1530,11 @@
     return value == CSSValueLighter || value == CSSValueBolder;
 }
 
-PassRefPtr<MutableStylePropertySet> getPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, CSSStyleDeclaration* baseStyle)
+PassRefPtrWillBeRawPtr<MutableStylePropertySet> getPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, CSSStyleDeclaration* baseStyle)
 {
     ASSERT(styleWithRedundantProperties);
     ASSERT(baseStyle);
-    RefPtr<MutableStylePropertySet> result = styleWithRedundantProperties->mutableCopy();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> result = styleWithRedundantProperties->mutableCopy();
 
     result->removeEquivalentProperties(baseStyle);
 
diff --git a/Source/core/editing/EditingStyle.h b/Source/core/editing/EditingStyle.h
index 43434ea..80ee79b 100644
--- a/Source/core/editing/EditingStyle.h
+++ b/Source/core/editing/EditingStyle.h
@@ -35,6 +35,7 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "core/editing/WritingDirection.h"
+#include "heap/Handle.h"
 #include "wtf/Forward.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
@@ -155,7 +156,7 @@
     void mergeInlineAndImplicitStyleOfElement(Element*, CSSPropertyOverrideMode, PropertiesToInclude);
     void mergeStyle(const StylePropertySet*, CSSPropertyOverrideMode);
 
-    RefPtr<MutableStylePropertySet> m_mutableStyle;
+    RefPtrWillBePersistent<MutableStylePropertySet> m_mutableStyle;
     bool m_shouldUseFixedDefaultFontSize;
     float m_fontSizeDelta;
 
diff --git a/Source/core/editing/Editor.cpp b/Source/core/editing/Editor.cpp
index 7227783..cfcc2fd 100644
--- a/Source/core/editing/Editor.cpp
+++ b/Source/core/editing/Editor.cpp
@@ -525,7 +525,7 @@
 
 void Editor::notifyComponentsOnChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
 {
-    client().respondToChangedSelection(m_frame.selection().selectionType());
+    client().respondToChangedSelection(&m_frame, m_frame.selection().selectionType());
     setStartNewKillRingSequence(true);
 }
 
@@ -954,17 +954,17 @@
 
 void Editor::setBaseWritingDirection(WritingDirection direction)
 {
-    Node* focusedElement = frame().document()->focusedElement();
-    if (focusedElement && isHTMLTextFormControlElement(*focusedElement)) {
+    Element* focusedElement = frame().document()->focusedElement();
+    if (isHTMLTextFormControlElement(focusedElement)) {
         if (direction == NaturalWritingDirection)
             return;
-        toHTMLElement(focusedElement)->setAttribute(dirAttr, direction == LeftToRightWritingDirection ? "ltr" : "rtl");
+        focusedElement->setAttribute(dirAttr, direction == LeftToRightWritingDirection ? "ltr" : "rtl");
         focusedElement->dispatchInputEvent();
         frame().document()->updateStyleIfNeeded();
         return;
     }
 
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     style->setProperty(CSSPropertyDirection, direction == LeftToRightWritingDirection ? "ltr" : direction == RightToLeftWritingDirection ? "rtl" : "inherit", false);
     applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
 }
@@ -1045,7 +1045,7 @@
     // does not call EditorClient::respondToChangedSelection(), which, on the Mac, sends selection change notifications and
     // starts a new kill ring sequence, but we want to do these things (matches AppKit).
     if (selectionDidNotChangeDOMPosition)
-        client().respondToChangedSelection(m_frame.selection().selectionType());
+        client().respondToChangedSelection(&m_frame, m_frame.selection().selectionType());
 }
 
 IntRect Editor::firstRectForRange(Range* range) const
diff --git a/Source/core/editing/EditorCommand.cpp b/Source/core/editing/EditorCommand.cpp
index ba4a113..46c65f1 100644
--- a/Source/core/editing/EditorCommand.cpp
+++ b/Source/core/editing/EditorCommand.cpp
@@ -118,14 +118,14 @@
 
 static bool executeApplyStyle(LocalFrame& frame, EditorCommandSource source, EditAction action, CSSPropertyID propertyID, const String& propertyValue)
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     style->setProperty(propertyID, propertyValue);
     return applyCommandToFrame(frame, source, action, style.get());
 }
 
 static bool executeApplyStyle(LocalFrame& frame, EditorCommandSource source, EditAction action, CSSPropertyID propertyID, CSSValueID propertyValue)
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     style->setProperty(propertyID, propertyValue);
     return applyCommandToFrame(frame, source, action, style.get());
 }
@@ -152,7 +152,7 @@
         newStyle = value->cssText();
 
     // FIXME: We shouldn't be having to convert new style into text.  We should have setPropertyCSSValue.
-    RefPtr<MutableStylePropertySet> newMutableStyle = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> newMutableStyle = MutableStylePropertySet::create();
     newMutableStyle->setProperty(propertyID, newStyle);
     return applyCommandToFrame(frame, source, action, newMutableStyle.get());
 }
@@ -175,7 +175,7 @@
 
 static bool executeApplyParagraphStyle(LocalFrame& frame, EditorCommandSource source, EditAction action, CSSPropertyID propertyID, const String& propertyValue)
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     style->setProperty(propertyID, propertyValue);
     // FIXME: We don't call shouldApplyStyle when the source is DOM; is there a good reason for that?
     switch (source) {
@@ -596,7 +596,7 @@
 
 static bool executeMakeTextWritingDirectionLeftToRight(LocalFrame& frame, Event*, EditorCommandSource, const String&)
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     style->setProperty(CSSPropertyUnicodeBidi, CSSValueEmbed);
     style->setProperty(CSSPropertyDirection, CSSValueLtr);
     frame.editor().applyStyle(style.get(), EditActionSetWritingDirection);
@@ -605,7 +605,7 @@
 
 static bool executeMakeTextWritingDirectionNatural(LocalFrame& frame, Event*, EditorCommandSource, const String&)
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     style->setProperty(CSSPropertyUnicodeBidi, CSSValueNormal);
     frame.editor().applyStyle(style.get(), EditActionSetWritingDirection);
     return true;
@@ -613,7 +613,7 @@
 
 static bool executeMakeTextWritingDirectionRightToLeft(LocalFrame& frame, Event*, EditorCommandSource, const String&)
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     style->setProperty(CSSPropertyUnicodeBidi, CSSValueEmbed);
     style->setProperty(CSSPropertyDirection, CSSValueRtl);
     frame.editor().applyStyle(style.get(), EditActionSetWritingDirection);
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index 0c6083d..d505320 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -1733,7 +1733,7 @@
         if (HTMLFormElement* owner = element->formOwner())
                 return owner;
 
-        if (isHTMLFrameElement(*element) || isHTMLIFrameElement(*element)) {
+        if (isHTMLFrameElementBase(*element)) {
             Node* childDocument = toHTMLFrameElementBase(*element).contentDocument();
             if (HTMLFormElement* frameResult = scanForForm(childDocument))
                 return frameResult;
diff --git a/Source/core/editing/ReplaceSelectionCommand.cpp b/Source/core/editing/ReplaceSelectionCommand.cpp
index 7428ed7..8ca4e2f 100644
--- a/Source/core/editing/ReplaceSelectionCommand.cpp
+++ b/Source/core/editing/ReplaceSelectionCommand.cpp
@@ -609,7 +609,7 @@
     return elements.contains(name);
 }
 
-void ReplaceSelectionCommand::makeInsertedContentRoundTrippableWithHTMLTreeBuilder(InsertedNodes& insertedNodes)
+void ReplaceSelectionCommand::makeInsertedContentRoundTrippableWithHTMLTreeBuilder(const InsertedNodes& insertedNodes)
 {
     RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
     RefPtr<Node> next;
diff --git a/Source/core/editing/ReplaceSelectionCommand.h b/Source/core/editing/ReplaceSelectionCommand.h
index e4411cc..13f2744 100644
--- a/Source/core/editing/ReplaceSelectionCommand.h
+++ b/Source/core/editing/ReplaceSelectionCommand.h
@@ -88,7 +88,7 @@
     void removeUnrenderedTextNodesAtEnds(InsertedNodes&);
 
     void removeRedundantStylesAndKeepStyleSpanInline(InsertedNodes&);
-    void makeInsertedContentRoundTrippableWithHTMLTreeBuilder(InsertedNodes&);
+    void makeInsertedContentRoundTrippableWithHTMLTreeBuilder(const InsertedNodes&);
     void moveNodeOutOfAncestor(PassRefPtr<Node>, PassRefPtr<Node> ancestor);
     void handleStyleSpans(InsertedNodes&);
 
diff --git a/Source/core/events/EventTarget.h b/Source/core/events/EventTarget.h
index 6323036..f6fa122 100644
--- a/Source/core/events/EventTarget.h
+++ b/Source/core/events/EventTarget.h
@@ -107,8 +107,8 @@
     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 bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture = false);
+    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture = false);
     virtual void removeAllEventListeners();
     virtual bool dispatchEvent(PassRefPtr<Event>);
     bool dispatchEvent(PassRefPtr<Event>, ExceptionState&); // DOM API
diff --git a/Source/core/events/EventTarget.idl b/Source/core/events/EventTarget.idl
index 0cd1b17..7febedf 100644
--- a/Source/core/events/EventTarget.idl
+++ b/Source/core/events/EventTarget.idl
@@ -21,10 +21,10 @@
 [
     Custom=ToV8,
 ] interface EventTarget {
-    void addEventListener(DOMString type,
+    void addEventListener([TreatNullAs=NullString] DOMString type,
                           EventListener listener,
                           optional boolean useCapture);
-    void removeEventListener(DOMString type,
+    void removeEventListener([TreatNullAs=NullString] DOMString type,
                              EventListener listener,
                              optional boolean useCapture);
     [RaisesException] boolean dispatchEvent(Event event);
diff --git a/Source/core/events/PopStateEvent.cpp b/Source/core/events/PopStateEvent.cpp
index c310932..bf22a41 100644
--- a/Source/core/events/PopStateEvent.cpp
+++ b/Source/core/events/PopStateEvent.cpp
@@ -48,7 +48,7 @@
     ScriptWrappable::init(this);
 }
 
-PopStateEvent::PopStateEvent(PassRefPtr<SerializedScriptValue> serializedState, PassRefPtr<History> history)
+PopStateEvent::PopStateEvent(PassRefPtr<SerializedScriptValue> serializedState, PassRefPtrWillBeRawPtr<History> history)
     : Event(EventTypeNames::popstate, false, true)
     , m_serializedState(serializedState)
     , m_history(history)
@@ -65,7 +65,7 @@
     return adoptRef(new PopStateEvent);
 }
 
-PassRefPtr<PopStateEvent> PopStateEvent::create(PassRefPtr<SerializedScriptValue> serializedState, PassRefPtr<History> history)
+PassRefPtr<PopStateEvent> PopStateEvent::create(PassRefPtr<SerializedScriptValue> serializedState, PassRefPtrWillBeRawPtr<History> history)
 {
     return adoptRef(new PopStateEvent(serializedState, history));
 }
diff --git a/Source/core/events/PopStateEvent.h b/Source/core/events/PopStateEvent.h
index 19f5f88..6492ffd 100644
--- a/Source/core/events/PopStateEvent.h
+++ b/Source/core/events/PopStateEvent.h
@@ -28,6 +28,7 @@
 #define PopStateEvent_h
 
 #include "core/events/Event.h"
+#include "heap/Handle.h"
 
 namespace WebCore {
 
@@ -40,7 +41,7 @@
 public:
     virtual ~PopStateEvent();
     static PassRefPtr<PopStateEvent> create();
-    static PassRefPtr<PopStateEvent> create(PassRefPtr<SerializedScriptValue>, PassRefPtr<History>);
+    static PassRefPtr<PopStateEvent> create(PassRefPtr<SerializedScriptValue>, PassRefPtrWillBeRawPtr<History>);
     static PassRefPtr<PopStateEvent> create(const AtomicString&, const PopStateEventInit&);
 
     SerializedScriptValue* serializedState() const { return m_serializedState.get(); }
@@ -58,10 +59,10 @@
 private:
     PopStateEvent();
     PopStateEvent(const AtomicString&, const PopStateEventInit&);
-    explicit PopStateEvent(PassRefPtr<SerializedScriptValue>, PassRefPtr<History>);
+    PopStateEvent(PassRefPtr<SerializedScriptValue>, PassRefPtrWillBeRawPtr<History>);
 
     RefPtr<SerializedScriptValue> m_serializedState;
-    RefPtr<History> m_history;
+    RefPtrWillBePersistent<History> m_history;
 };
 
 } // namespace WebCore
diff --git a/Source/core/fetch/MemoryCache.cpp b/Source/core/fetch/MemoryCache.cpp
index e6d24c9..208ade0 100644
--- a/Source/core/fetch/MemoryCache.cpp
+++ b/Source/core/fetch/MemoryCache.cpp
@@ -327,13 +327,14 @@
 
 void MemoryCache::removeFromLRUList(Resource* resource)
 {
-    // If we've never been accessed, then we're brand new and not in any list.
-    if (!resource->accessCount())
-        return;
-
     MemoryCacheEntry* entry = m_resources.get(resource->url());
     ASSERT(entry->m_resource == resource);
+
     LRUList* list = lruListFor(entry);
+    MemoryCacheEntry* next = entry->m_nextInAllResourcesList;
+    MemoryCacheEntry* previous = entry->m_previousInAllResourcesList;
+    if (!next && !previous && list->m_head != entry)
+        return;
 
 #if !ASSERT_DISABLED
     // Verify that we are in fact in this list.
@@ -347,9 +348,6 @@
     ASSERT(found);
 #endif
 
-    MemoryCacheEntry* next = entry->m_nextInAllResourcesList;
-    MemoryCacheEntry* previous = entry->m_previousInAllResourcesList;
-
     entry->m_nextInAllResourcesList = 0;
     entry->m_previousInAllResourcesList = 0;
 
@@ -372,7 +370,6 @@
     // Make sure we aren't in some list already.
     ASSERT(!entry->m_nextInAllResourcesList && !entry->m_previousInAllResourcesList);
     ASSERT(resource->inCache());
-    ASSERT(resource->accessCount() > 0);
 
     LRUList* list = lruListFor(entry);
 
diff --git a/Source/core/fetch/MemoryCacheTest.cpp b/Source/core/fetch/MemoryCacheTest.cpp
index b59e513..0159bc5 100644
--- a/Source/core/fetch/MemoryCacheTest.cpp
+++ b/Source/core/fetch/MemoryCacheTest.cpp
@@ -366,4 +366,24 @@
     ASSERT_EQ(memoryCache()->deadSize(), 0u);
     ASSERT_EQ(memoryCache()->liveSize(), totalSize - lowPriorityMockDecodeSize - highPriorityMockDecodeSize);
 }
+
+TEST_F(MemoryCacheTest, MultipleReplace)
+{
+    ResourcePtr<FakeResource> resource1 = new FakeResource(ResourceRequest(""), Resource::Raw);
+    memoryCache()->add(resource1.get());
+    EXPECT_EQ(1U, resource1->accessCount());
+
+    ResourcePtr<FakeResource> resource2 = new FakeResource(ResourceRequest(""), Resource::Raw);
+    memoryCache()->replace(resource2.get(), resource1.get());
+    EXPECT_TRUE(resource2->inCache());
+    EXPECT_FALSE(resource1->inCache());
+    EXPECT_EQ(0U, resource2->accessCount());
+
+    ResourcePtr<FakeResource> resource3 = new FakeResource(ResourceRequest(""), Resource::Raw);
+    memoryCache()->replace(resource3.get(), resource2.get());
+    EXPECT_TRUE(resource3->inCache());
+    EXPECT_FALSE(resource2->inCache());
+    EXPECT_EQ(0U, resource3->accessCount());
+}
+
 } // namespace
diff --git a/Source/core/frame/DOMWindow.cpp b/Source/core/frame/DOMWindow.cpp
index f6b928f..a9c7d4d 100644
--- a/Source/core/frame/DOMWindow.cpp
+++ b/Source/core/frame/DOMWindow.cpp
@@ -979,7 +979,7 @@
     if (!host)
         return;
 
-    if (m_frame->loader().documentLoader()->isLoading()) {
+    if (m_frame->loader().provisionalDocumentLoader() || m_frame->loader().documentLoader()->isLoading()) {
         m_shouldPrintWhenFinishedLoading = true;
         return;
     }
@@ -1189,7 +1189,7 @@
 
 const AtomicString& DOMWindow::name() const
 {
-    if (!m_frame)
+    if (!isCurrentlyDisplayedInFrame())
         return nullAtom;
 
     return m_frame->tree().name();
@@ -1197,10 +1197,11 @@
 
 void DOMWindow::setName(const AtomicString& name)
 {
-    if (!m_frame)
+    if (!isCurrentlyDisplayedInFrame())
         return;
 
     m_frame->tree().setName(name);
+    ASSERT(m_frame->loader().client());
     m_frame->loader().client()->didChangeName(name);
 }
 
diff --git a/Source/core/frame/DOMWindow.h b/Source/core/frame/DOMWindow.h
index 37cea69..bdc565e 100644
--- a/Source/core/frame/DOMWindow.h
+++ b/Source/core/frame/DOMWindow.h
@@ -248,8 +248,8 @@
 
         // Events
         // EventTarget API
-        virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE;
-        virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE;
+        virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture = false) OVERRIDE;
+        virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture = false) OVERRIDE;
         virtual void removeAllEventListeners() OVERRIDE;
 
         using EventTarget::dispatchEvent;
@@ -344,7 +344,7 @@
         HashSet<DOMWindowProperty*> m_properties;
 
         mutable RefPtrWillBePersistent<Screen> m_screen;
-        mutable RefPtr<History> m_history;
+        mutable RefPtrWillBePersistent<History> m_history;
         mutable RefPtr<BarProp> m_locationbar;
         mutable RefPtr<BarProp> m_menubar;
         mutable RefPtr<BarProp> m_personalbar;
@@ -352,8 +352,8 @@
         mutable RefPtr<BarProp> m_statusbar;
         mutable RefPtr<BarProp> m_toolbar;
         mutable RefPtr<Console> m_console;
-        mutable RefPtr<Navigator> m_navigator;
-        mutable RefPtr<Location> m_location;
+        mutable RefPtrWillBePersistent<Navigator> m_navigator;
+        mutable RefPtrWillBePersistent<Location> m_location;
         mutable RefPtr<StyleMedia> m_media;
 
         String m_status;
@@ -363,7 +363,7 @@
         mutable RefPtrWillBePersistent<Storage> m_localStorage;
         mutable RefPtr<ApplicationCache> m_applicationCache;
 
-        mutable RefPtr<Performance> m_performance;
+        mutable RefPtrWillBePersistent<Performance> m_performance;
 
         mutable RefPtr<DOMWindowCSS> m_css;
 
diff --git a/Source/core/frame/FrameView.cpp b/Source/core/frame/FrameView.cpp
index 3596a61..c111f2c 100644
--- a/Source/core/frame/FrameView.cpp
+++ b/Source/core/frame/FrameView.cpp
@@ -2335,7 +2335,10 @@
 
 void FrameView::getTickmarks(Vector<IntRect>& tickmarks) const
 {
-    tickmarks = frame().document()->markers().renderedRectsForMarkers(DocumentMarker::TextMatch);
+    if (!m_tickmarks.isEmpty())
+        tickmarks = m_tickmarks;
+    else
+        tickmarks = frame().document()->markers().renderedRectsForMarkers(DocumentMarker::TextMatch);
 }
 
 IntRect FrameView::windowResizerRect() const
@@ -2876,9 +2879,8 @@
         const LayoutRect& documentRect = renderView->documentRect();
         LayoutUnit docLogicalWidth = horizontalWritingMode ? documentRect.width() : documentRect.height();
         if (docLogicalWidth > pageLogicalWidth) {
-            int expectedPageWidth = std::min<float>(documentRect.width(), pageSize.width() * maximumShrinkFactor);
-            int expectedPageHeight = std::min<float>(documentRect.height(), pageSize.height() * maximumShrinkFactor);
-            FloatSize maxPageSize = m_frame->resizePageRectsKeepingRatio(FloatSize(originalPageSize.width(), originalPageSize.height()), FloatSize(expectedPageWidth, expectedPageHeight));
+            FloatSize expectedPageSize(std::min<float>(documentRect.width().toFloat(), pageSize.width() * maximumShrinkFactor), std::min<float>(documentRect.height().toFloat(), pageSize.height() * maximumShrinkFactor));
+            FloatSize maxPageSize = m_frame->resizePageRectsKeepingRatio(FloatSize(originalPageSize.width(), originalPageSize.height()), expectedPageSize);
             pageLogicalWidth = horizontalWritingMode ? maxPageSize.width() : maxPageSize.height();
             pageLogicalHeight = horizontalWritingMode ? maxPageSize.height() : maxPageSize.width();
 
diff --git a/Source/core/frame/FrameView.h b/Source/core/frame/FrameView.h
index 7ce9cf2..07ccb28 100644
--- a/Source/core/frame/FrameView.h
+++ b/Source/core/frame/FrameView.h
@@ -313,6 +313,11 @@
     // false.
     bool isSubtreeLayout() const { return !!m_layoutSubtreeRoot; }
 
+    // Sets the tickmarks for the FrameView, overriding the default behavior
+    // which is to display the tickmarks corresponding to find results.
+    // If |m_tickmarks| is empty, the default behavior is restored.
+    void setTickmarks(const Vector<IntRect>& tickmarks) { m_tickmarks = tickmarks; }
+
     // ScrollableArea interface
     virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&) OVERRIDE;
     virtual void getTickmarks(Vector<IntRect>&) const OVERRIDE;
@@ -507,6 +512,8 @@
     bool m_layoutSizeFixedToFrameSize;
 
     Timer<FrameView> m_didScrollTimer;
+
+    Vector<IntRect> m_tickmarks;
 };
 
 inline void FrameView::incrementVisuallyNonEmptyCharacterCount(unsigned count)
diff --git a/Source/core/frame/History.h b/Source/core/frame/History.h
index e330052..30a1c34 100644
--- a/Source/core/frame/History.h
+++ b/Source/core/frame/History.h
@@ -30,6 +30,7 @@
 #include "bindings/v8/SerializedScriptValue.h"
 #include "core/loader/FrameLoaderTypes.h"
 #include "core/frame/DOMWindowProperty.h"
+#include "heap/Handle.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
@@ -41,9 +42,12 @@
 class ExecutionContext;
 class ExceptionState;
 
-class History FINAL : public ScriptWrappable, public RefCounted<History>, public DOMWindowProperty {
+class History FINAL : public RefCountedWillBeGarbageCollectedFinalized<History>, public ScriptWrappable, public DOMWindowProperty {
 public:
-    static PassRefPtr<History> create(LocalFrame* frame) { return adoptRef(new History(frame)); }
+    static PassRefPtrWillBeRawPtr<History> create(LocalFrame* frame)
+    {
+        return adoptRefWillBeNoop(new History(frame));
+    }
 
     unsigned length() const;
     SerializedScriptValue* state();
@@ -57,6 +61,8 @@
 
     void stateObjectAdded(PassRefPtr<SerializedScriptValue>, const String& title, const String& url, UpdateBackForwardListPolicy, ExceptionState&);
 
+    void trace(Visitor*) { }
+
 private:
     explicit History(LocalFrame*);
 
diff --git a/Source/core/frame/History.idl b/Source/core/frame/History.idl
index 6bd6439..4060604 100644
--- a/Source/core/frame/History.idl
+++ b/Source/core/frame/History.idl
@@ -23,7 +23,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface History {
+[
+    WillBeGarbageCollected,
+] interface History {
     readonly attribute unsigned long length;
     [Custom=Getter] readonly attribute SerializedScriptValue state;
 
diff --git a/Source/core/frame/ImageBitmapTest.cpp b/Source/core/frame/ImageBitmapTest.cpp
index d6981bc..d4633c8 100644
--- a/Source/core/frame/ImageBitmapTest.cpp
+++ b/Source/core/frame/ImageBitmapTest.cpp
@@ -54,12 +54,10 @@
 protected:
     virtual void SetUp()
     {
-        m_bitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
-        m_bitmap.allocPixels();
+        ASSERT_TRUE(m_bitmap.allocN32Pixels(10, 10));
         m_bitmap.eraseColor(0xFFFFFFFF);
 
-        m_bitmap2.setConfig(SkBitmap::kARGB_8888_Config, 5, 5);
-        m_bitmap2.allocPixels();
+        ASSERT_TRUE(m_bitmap2.allocN32Pixels(5, 5));
         m_bitmap2.eraseColor(0xAAAAAAAA);
 
         // Save the global memory cache to restore it upon teardown.
diff --git a/Source/core/frame/LocalFrame.cpp b/Source/core/frame/LocalFrame.cpp
index 2add1aa..1a13ed7 100644
--- a/Source/core/frame/LocalFrame.cpp
+++ b/Source/core/frame/LocalFrame.cpp
@@ -425,11 +425,11 @@
 
 String LocalFrame::layerTreeAsText(unsigned flags) const
 {
-    document()->updateLayout();
-
     if (!contentRenderer())
         return String();
 
+    ASSERT(document()->lifecycle().state() >= DocumentLifecycle::CompositingClean);
+
     return contentRenderer()->compositor()->layerTreeAsText(static_cast<LayerTreeFlags>(flags));
 }
 
diff --git a/Source/core/frame/Location.h b/Source/core/frame/Location.h
index 8930ae2..e8a0d6d 100644
--- a/Source/core/frame/Location.h
+++ b/Source/core/frame/Location.h
@@ -43,9 +43,12 @@
 class LocalFrame;
 class KURL;
 
-class Location FINAL : public ScriptWrappable, public RefCounted<Location>, public DOMWindowProperty {
+class Location FINAL : public RefCountedWillBeGarbageCollectedFinalized<Location>, public ScriptWrappable, public DOMWindowProperty {
 public:
-    static PassRefPtr<Location> create(LocalFrame* frame) { return adoptRef(new Location(frame)); }
+    static PassRefPtrWillBeRawPtr<Location> create(LocalFrame* frame)
+    {
+        return adoptRefWillBeNoop(new Location(frame));
+    }
 
     void setHref(DOMWindow* callingWindow, DOMWindow* enteredWindow, const String&);
     String href() const;
@@ -72,6 +75,8 @@
 
     PassRefPtr<DOMStringList> ancestorOrigins() const;
 
+    void trace(Visitor*) { }
+
 private:
     explicit Location(LocalFrame*);
 
diff --git a/Source/core/frame/Location.idl b/Source/core/frame/Location.idl
index 5ce2990..4e7660c 100644
--- a/Source/core/frame/Location.idl
+++ b/Source/core/frame/Location.idl
@@ -28,6 +28,7 @@
 
 [
     CheckSecurity=Frame,
+    WillBeGarbageCollected,
 ] interface Location {
     // |assign|, |replace|, and *writing* |href| do not require a security
     // check, as they *change* the page, and thus these do not change any
diff --git a/Source/core/frame/Navigator.cpp b/Source/core/frame/Navigator.cpp
index 1660234..7d99341 100644
--- a/Source/core/frame/Navigator.cpp
+++ b/Source/core/frame/Navigator.cpp
@@ -129,4 +129,13 @@
     // FIXME: Remove this method or rename to yieldForStorageUpdates.
 }
 
+void Navigator::trace(Visitor* visitor)
+{
+    visitor->trace(m_plugins);
+    visitor->trace(m_mimeTypes);
+#if ENABLE(OILPAN)
+    HeapSupplementable<Navigator>::trace(visitor);
+#endif
+}
+
 } // namespace WebCore
diff --git a/Source/core/frame/Navigator.h b/Source/core/frame/Navigator.h
index 990c016..3e1b14d 100644
--- a/Source/core/frame/Navigator.h
+++ b/Source/core/frame/Navigator.h
@@ -39,9 +39,14 @@
 
 typedef int ExceptionCode;
 
-class Navigator FINAL : public NavigatorBase, public ScriptWrappable, public RefCounted<Navigator>, public DOMWindowProperty, public Supplementable<Navigator> {
+class Navigator FINAL : public RefCountedWillBeGarbageCollectedFinalized<Navigator>, public NavigatorBase, public ScriptWrappable, public DOMWindowProperty, public WillBeHeapSupplementable<Navigator> {
+    WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(Navigator);
 public:
-    static PassRefPtr<Navigator> create(LocalFrame* frame) { return adoptRef(new Navigator(frame)); }
+    static PassRefPtrWillBeRawPtr<Navigator> create(LocalFrame* frame)
+    {
+        return adoptRefWillBeNoop(new Navigator(frame));
+    }
+
     virtual ~Navigator();
 
     AtomicString language() const;
@@ -59,11 +64,13 @@
     // Relinquishes the storage lock, if one exists.
     void getStorageUpdates();
 
+    virtual void trace(Visitor*);
+
 private:
     explicit Navigator(LocalFrame*);
 
-    mutable RefPtrWillBePersistent<DOMPluginArray> m_plugins;
-    mutable RefPtrWillBePersistent<DOMMimeTypeArray> m_mimeTypes;
+    mutable RefPtrWillBeMember<DOMPluginArray> m_plugins;
+    mutable RefPtrWillBeMember<DOMMimeTypeArray> m_mimeTypes;
 };
 
 }
diff --git a/Source/core/frame/Navigator.idl b/Source/core/frame/Navigator.idl
index 546e3e0..0812269 100644
--- a/Source/core/frame/Navigator.idl
+++ b/Source/core/frame/Navigator.idl
@@ -17,7 +17,9 @@
     Boston, MA 02110-1301, USA.
 */
 
-interface Navigator {
+[
+    WillBeGarbageCollected,
+] interface Navigator {
     readonly attribute DOMString language;
     readonly attribute PluginArray plugins;
     readonly attribute MimeTypeArray mimeTypes;
diff --git a/Source/core/frame/Settings.in b/Source/core/frame/Settings.in
index 43a7f61..3b8bcc0 100644
--- a/Source/core/frame/Settings.in
+++ b/Source/core/frame/Settings.in
@@ -133,7 +133,7 @@
 
 fullScreenEnabled initial=false
 asynchronousSpellCheckingEnabled initial=false
-memoryInfoEnabled initial=false
+preciseMemoryInfoEnabled initial=false
 
 hyperlinkAuditingEnabled initial=false
 allowDisplayOfInsecureContent initial=true
diff --git a/Source/core/frame/UseCounter.h b/Source/core/frame/UseCounter.h
index 5caab36..6681768 100644
--- a/Source/core/frame/UseCounter.h
+++ b/Source/core/frame/UseCounter.h
@@ -309,6 +309,11 @@
         ElementAnimateKeyframeListEffectObjectTiming = 292,
         ElementAnimateKeyframeListEffectDoubleTiming = 293,
         ElementAnimateKeyframeListEffectNoTiming = 294,
+        DocumentXPathCreateExpression = 295,
+        DocumentXPathCreateNSResolver = 296,
+        DocumentXPathEvaluate = 297,
+        AttrGetValue = 298,
+        AttrSetValue = 299,
         // Add new features immediately above this line. Don't change assigned
         // numbers of any item, and don't reuse removed slots.
         NumberOfFeatures, // This enum value must be last.
diff --git a/Source/core/html/HTMLAnchorElement.cpp b/Source/core/html/HTMLAnchorElement.cpp
index 33e6a31..f71f2c8 100644
--- a/Source/core/html/HTMLAnchorElement.cpp
+++ b/Source/core/html/HTMLAnchorElement.cpp
@@ -301,6 +301,11 @@
     return attribute.name().localName() == hrefAttr || HTMLElement::isURLAttribute(attribute);
 }
 
+bool HTMLAnchorElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == hrefAttr || HTMLElement::hasLegalLinkAttribute(name);
+}
+
 bool HTMLAnchorElement::canStartSelection() const
 {
     // FIXME: We probably want this same behavior in SVGAElement too
diff --git a/Source/core/html/HTMLAnchorElement.h b/Source/core/html/HTMLAnchorElement.h
index 821fa34..3f0b3f2 100644
--- a/Source/core/html/HTMLAnchorElement.h
+++ b/Source/core/html/HTMLAnchorElement.h
@@ -97,6 +97,7 @@
     virtual void setActive(bool = true) OVERRIDE FINAL;
     virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE FINAL;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE FINAL;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE FINAL;
     virtual bool canStartSelection() const OVERRIDE FINAL;
     virtual short tabIndex() const OVERRIDE FINAL;
     virtual bool draggable() const OVERRIDE FINAL;
diff --git a/Source/core/html/HTMLAppletElement.cpp b/Source/core/html/HTMLAppletElement.cpp
index 7620bea..713cd1c 100644
--- a/Source/core/html/HTMLAppletElement.cpp
+++ b/Source/core/html/HTMLAppletElement.cpp
@@ -77,6 +77,11 @@
         || HTMLPlugInElement::isURLAttribute(attribute);
 }
 
+bool HTMLAppletElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == codebaseAttr || HTMLPlugInElement::hasLegalLinkAttribute(name);
+}
+
 bool HTMLAppletElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (!fastHasAttribute(codeAttr) && !hasAuthorShadowRoot())
diff --git a/Source/core/html/HTMLAppletElement.h b/Source/core/html/HTMLAppletElement.h
index 41c5193..063b641 100644
--- a/Source/core/html/HTMLAppletElement.h
+++ b/Source/core/html/HTMLAppletElement.h
@@ -41,6 +41,7 @@
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
diff --git a/Source/core/html/HTMLAttributeNames.in b/Source/core/html/HTMLAttributeNames.in
index 4686e8e..88c5fbc 100644
--- a/Source/core/html/HTMLAttributeNames.in
+++ b/Source/core/html/HTMLAttributeNames.in
@@ -292,7 +292,6 @@
 readonly
 rel
 required
-reset-style-inheritance
 results
 rev
 reversed
diff --git a/Source/core/html/HTMLAudioElement.h b/Source/core/html/HTMLAudioElement.h
index d05c907..be7c5fc 100644
--- a/Source/core/html/HTMLAudioElement.h
+++ b/Source/core/html/HTMLAudioElement.h
@@ -40,8 +40,6 @@
 
 private:
     HTMLAudioElement(Document&);
-
-    virtual bool isVideo() const OVERRIDE { return false; }
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLBodyElement.cpp b/Source/core/html/HTMLBodyElement.cpp
index 10882ea..646d4db 100644
--- a/Source/core/html/HTMLBodyElement.cpp
+++ b/Source/core/html/HTMLBodyElement.cpp
@@ -161,12 +161,12 @@
         // and marginheight attribute can magically appear on the <body> of all documents
         // embedded through <iframe> or <frame>.
         Element* ownerElement = document().ownerElement();
-        if (ownerElement && ownerElement->isFrameElementBase()) {
-            HTMLFrameElementBase* ownerFrameElement = toHTMLFrameElementBase(ownerElement);
-            int marginWidth = ownerFrameElement->marginWidth();
+        if (isHTMLFrameElementBase(ownerElement)) {
+            HTMLFrameElementBase& ownerFrameElement = toHTMLFrameElementBase(*ownerElement);
+            int marginWidth = ownerFrameElement.marginWidth();
             if (marginWidth != -1)
                 setIntegralAttribute(marginwidthAttr, marginWidth);
-            int marginHeight = ownerFrameElement->marginHeight();
+            int marginHeight = ownerFrameElement.marginHeight();
             if (marginHeight != -1)
                 setIntegralAttribute(marginheightAttr, marginHeight);
         }
@@ -179,6 +179,16 @@
     return attribute.name() == backgroundAttr || HTMLElement::isURLAttribute(attribute);
 }
 
+bool HTMLBodyElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == backgroundAttr || HTMLElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLBodyElement::subResourceAttributeName() const
+{
+    return backgroundAttr;
+}
+
 bool HTMLBodyElement::supportsFocus() const
 {
     // This override is needed because the inherited method bails if the parent is editable.
diff --git a/Source/core/html/HTMLBodyElement.h b/Source/core/html/HTMLBodyElement.h
index b80c40f..6794c7e 100644
--- a/Source/core/html/HTMLBodyElement.h
+++ b/Source/core/html/HTMLBodyElement.h
@@ -53,6 +53,8 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
 
     virtual bool supportsFocus() const OVERRIDE;
 
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index 4ea2212..f25930e 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -303,7 +303,7 @@
 }
 
 
-void HTMLCanvasElement::paint(GraphicsContext* context, const LayoutRect& r, bool useLowQualityScale)
+void HTMLCanvasElement::paint(GraphicsContext* context, const LayoutRect& r)
 {
     // Clear the dirty rect
     m_dirtyRect = FloatRect();
@@ -322,9 +322,9 @@
         if (imageBuffer) {
             CompositeOperator compositeOperator = !m_context || m_context->hasAlpha() ? CompositeSourceOver : CompositeCopy;
             if (m_presentedImage)
-                context->drawImage(m_presentedImage.get(), pixelSnappedIntRect(r), compositeOperator, DoNotRespectImageOrientation, useLowQualityScale);
+                context->drawImage(m_presentedImage.get(), pixelSnappedIntRect(r), compositeOperator, DoNotRespectImageOrientation);
             else
-                context->drawImageBuffer(imageBuffer, pixelSnappedIntRect(r), compositeOperator, blink::WebBlendModeNormal, useLowQualityScale);
+                context->drawImageBuffer(imageBuffer, pixelSnappedIntRect(r), compositeOperator, blink::WebBlendModeNormal);
         }
     }
 
@@ -482,7 +482,7 @@
     }
 
     m_imageBuffer->context()->setShouldClampToSourceRect(false);
-    m_imageBuffer->context()->setImageInterpolationQuality(DefaultInterpolationQuality);
+    m_imageBuffer->context()->setImageInterpolationQuality(CanvasDefaultInterpolationQuality);
     // Enabling MSAA overrides a request to disable antialiasing. This is true regardless of whether the
     // rendering mode is accelerated or not. For consistency, we don't want to apply AA in accelerated
     // canvases but not in unaccelerated canvases.
diff --git a/Source/core/html/HTMLCanvasElement.h b/Source/core/html/HTMLCanvasElement.h
index 99a1d1c..fa8c45a 100644
--- a/Source/core/html/HTMLCanvasElement.h
+++ b/Source/core/html/HTMLCanvasElement.h
@@ -33,9 +33,10 @@
 #include "platform/geometry/FloatRect.h"
 #include "platform/geometry/IntSize.h"
 #include "platform/graphics/Canvas2DLayerBridge.h"
+#include "platform/graphics/GraphicsTypes.h"
 #include "wtf/Forward.h"
 
-#define DefaultInterpolationQuality InterpolationMedium
+#define CanvasDefaultInterpolationQuality InterpolationLow
 
 namespace WebCore {
 
@@ -100,7 +101,7 @@
     void didDraw(const FloatRect&);
     void notifyObserversCanvasChanged(const FloatRect&);
 
-    void paint(GraphicsContext*, const LayoutRect&, bool useLowQualityScale = false);
+    void paint(GraphicsContext*, const LayoutRect&);
 
     GraphicsContext* drawingContext() const;
     GraphicsContext* existingDrawingContext() const;
diff --git a/Source/core/html/HTMLCollection.cpp b/Source/core/html/HTMLCollection.cpp
index 0ab210b..0b0bce0 100644
--- a/Source/core/html/HTMLCollection.cpp
+++ b/Source/core/html/HTMLCollection.cpp
@@ -309,17 +309,17 @@
 
 inline Element* firstMatchingChildElement(const HTMLCollection& nodeList, const ContainerNode& root)
 {
-    Element* element = ElementTraversal::firstWithin(root);
+    Element* element = ElementTraversal::firstChild(root);
     while (element && !isMatchingElement(nodeList, *element))
-        element = ElementTraversal::nextSkippingChildren(*element, &root);
+        element = ElementTraversal::nextSibling(*element);
     return element;
 }
 
-inline Element* nextMatchingChildElement(const HTMLCollection& nodeList, Element& current, const ContainerNode& root)
+inline Element* nextMatchingChildElement(const HTMLCollection& nodeList, Element& current)
 {
     Element* next = &current;
     do {
-        next = ElementTraversal::nextSkippingChildren(*next, &root);
+        next = ElementTraversal::nextSibling(*next);
     } while (next && !isMatchingElement(nodeList, *next));
     return next;
 }
@@ -345,7 +345,7 @@
     if (overridesItemAfter())
         return virtualItemAfter(&previous);
     if (shouldOnlyIncludeDirectChildren())
-        return nextMatchingChildElement(*this, previous, root);
+        return nextMatchingChildElement(*this, previous);
     return nextMatchingElement(*this, previous, root);
 }
 
@@ -368,7 +368,7 @@
         }
         if (shouldOnlyIncludeDirectChildren()) {
             Element* next = &currentElement;
-            while ((next = nextMatchingChildElement(*this, *next, root))) {
+            while ((next = nextMatchingChildElement(*this, *next))) {
                 if (++currentOffset == offset)
                     return next;
             }
diff --git a/Source/core/html/HTMLContentElement.idl b/Source/core/html/HTMLContentElement.idl
index ab59342..15d63d6 100644
--- a/Source/core/html/HTMLContentElement.idl
+++ b/Source/core/html/HTMLContentElement.idl
@@ -27,6 +27,5 @@
 [
 ] interface HTMLContentElement : HTMLElement {
     [Reflect, TreatNullAs=NullString] attribute DOMString select;
-    attribute boolean resetStyleInheritance;
     NodeList getDistributedNodes();
 };
diff --git a/Source/core/html/HTMLElement.h b/Source/core/html/HTMLElement.h
index 90c3963..09ff972 100644
--- a/Source/core/html/HTMLElement.h
+++ b/Source/core/html/HTMLElement.h
@@ -79,6 +79,7 @@
     TextDirection directionalityIfhasDirAutoAttribute(bool& isAuto) const;
 
     virtual bool isHTMLUnknownElement() const { return false; }
+    virtual bool isPluginElement() const { return false; }
 
     virtual bool isLabelable() const { return false; }
     // http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#interactive-content
@@ -137,6 +138,20 @@
     ScriptWrappable::init(this);
 }
 
+// This requires isHTML*Element(const Element&) and isHTML*Element(const HTMLElement&).
+// When the input element is an HTMLElement, we don't need to check the namespace URI, just the local name.
+#define DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(thisType) \
+    inline bool is##thisType(const thisType* element); \
+    inline bool is##thisType(const thisType& element); \
+    inline bool is##thisType(const HTMLElement* element) { return element && is##thisType(*element); } \
+    inline bool is##thisType(const Element* element) { return element && is##thisType(*element); } \
+    inline bool is##thisType(const Node& node) { return node.isElementNode() ? is##thisType(toElement(node)) : false; } \
+    inline bool is##thisType(const Node* node) { return node && node->isElementNode() ? is##thisType(*toElement(node)) : false; } \
+    template<typename T> inline bool is##thisType(const PassRefPtr<T>& node) { return is##thisType(node.get()); } \
+    template<typename T> inline bool is##thisType(const RefPtr<T>& node) { return is##thisType(node.get()); } \
+    template <> inline bool isElementOfType<const thisType>(const HTMLElement& element) { return is##thisType(element); } \
+    DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(thisType)
+
 } // namespace WebCore
 
 #include "HTMLElementTypeHelpers.h"
diff --git a/Source/core/html/HTMLEmbedElement.cpp b/Source/core/html/HTMLEmbedElement.cpp
index 3d366ee..5c65467 100644
--- a/Source/core/html/HTMLEmbedElement.cpp
+++ b/Source/core/html/HTMLEmbedElement.cpp
@@ -190,6 +190,11 @@
     return attribute.name() == srcAttr || HTMLPlugInElement::isURLAttribute(attribute);
 }
 
+const QualifiedName& HTMLEmbedElement::subResourceAttributeName() const
+{
+    return srcAttr;
+}
+
 const AtomicString HTMLEmbedElement::imageSourceURL() const
 {
     return getAttribute(srcAttr);
diff --git a/Source/core/html/HTMLEmbedElement.h b/Source/core/html/HTMLEmbedElement.h
index 9e3c0af..42b21ef 100644
--- a/Source/core/html/HTMLEmbedElement.h
+++ b/Source/core/html/HTMLEmbedElement.h
@@ -43,6 +43,7 @@
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
     virtual const AtomicString imageSourceURL() const OVERRIDE;
 
     virtual RenderWidget* existingRenderWidget() const OVERRIDE;
diff --git a/Source/core/html/HTMLFormControlElement.h b/Source/core/html/HTMLFormControlElement.h
index 8a89ebc..2dfc001 100644
--- a/Source/core/html/HTMLFormControlElement.h
+++ b/Source/core/html/HTMLFormControlElement.h
@@ -181,12 +181,12 @@
     bool m_wasFocusedByMouse : 1;
 };
 
-inline bool isHTMLFormControlElement(const Node& node)
+inline bool isHTMLFormControlElement(const Element& element)
 {
-    return node.isElementNode() && toElement(node).isFormControlElement();
+    return element.isFormControlElement();
 }
 
-DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLFormControlElement);
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLFormControlElement);
 DEFINE_TYPE_CASTS(HTMLFormControlElement, FormAssociatedElement, control, control->isFormControlElement(), control.isFormControlElement());
 
 } // namespace
diff --git a/Source/core/html/HTMLFormElement.cpp b/Source/core/html/HTMLFormElement.cpp
index 0c96bf0..3af938f 100644
--- a/Source/core/html/HTMLFormElement.cpp
+++ b/Source/core/html/HTMLFormElement.cpp
@@ -512,6 +512,11 @@
     return attribute.name() == actionAttr || HTMLElement::isURLAttribute(attribute);
 }
 
+bool HTMLFormElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == actionAttr || HTMLElement::hasLegalLinkAttribute(name);
+}
+
 void HTMLFormElement::associate(HTMLImageElement& e)
 {
     m_imageElementsAreDirty = true;
diff --git a/Source/core/html/HTMLFormElement.h b/Source/core/html/HTMLFormElement.h
index 758f5fe..aa71694 100644
--- a/Source/core/html/HTMLFormElement.h
+++ b/Source/core/html/HTMLFormElement.h
@@ -127,6 +127,7 @@
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
 
     virtual bool shouldRegisterAsNamedItem() const OVERRIDE { return true; }
 
diff --git a/Source/core/html/HTMLFrameElementBase.cpp b/Source/core/html/HTMLFrameElementBase.cpp
index 23eb76f..f7e2290 100644
--- a/Source/core/html/HTMLFrameElementBase.cpp
+++ b/Source/core/html/HTMLFrameElementBase.cpp
@@ -206,6 +206,11 @@
         || HTMLFrameOwnerElement::isURLAttribute(attribute);
 }
 
+bool HTMLFrameElementBase::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == hrefAttr || HTMLFrameOwnerElement::hasLegalLinkAttribute(name);
+}
+
 bool HTMLFrameElementBase::isHTMLContentAttribute(const Attribute& attribute) const
 {
     return attribute.name() == srcdocAttr || HTMLFrameOwnerElement::isHTMLContentAttribute(attribute);
diff --git a/Source/core/html/HTMLFrameElementBase.h b/Source/core/html/HTMLFrameElementBase.h
index 82c5013..694a523 100644
--- a/Source/core/html/HTMLFrameElementBase.h
+++ b/Source/core/html/HTMLFrameElementBase.h
@@ -59,10 +59,9 @@
     virtual void setFocus(bool) OVERRIDE FINAL;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE FINAL;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE FINAL;
     virtual bool isHTMLContentAttribute(const Attribute&) const OVERRIDE FINAL;
 
-    virtual bool isFrameElementBase() const OVERRIDE FINAL { return true; }
-
     virtual bool areAuthorShadowsAllowed() const OVERRIDE FINAL { return false; }
 
     void setNameAndOpenURL();
@@ -77,12 +76,17 @@
     int m_marginHeight;
 };
 
-inline bool isHTMLFrameElementBase(const Node& node)
+inline bool isHTMLFrameElementBase(const Element& element)
 {
-    return node.isElementNode() && toElement(node).isFrameElementBase();
+    return isHTMLFrameElement(element) || isHTMLIFrameElement(element);
 }
 
-DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLFrameElementBase);
+inline bool isHTMLFrameElementBase(const HTMLElement& element)
+{
+    return isHTMLFrameElement(element) || isHTMLIFrameElement(element);
+}
+
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLFrameElementBase);
 
 } // namespace WebCore
 
diff --git a/Source/core/html/HTMLImageElement.cpp b/Source/core/html/HTMLImageElement.cpp
index df1902a..8509958 100644
--- a/Source/core/html/HTMLImageElement.cpp
+++ b/Source/core/html/HTMLImageElement.cpp
@@ -322,6 +322,16 @@
         || HTMLElement::isURLAttribute(attribute);
 }
 
+bool HTMLImageElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == srcAttr || HTMLElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLImageElement::subResourceAttributeName() const
+{
+    return srcAttr;
+}
+
 const AtomicString& HTMLImageElement::alt() const
 {
     return fastGetAttribute(altAttr);
diff --git a/Source/core/html/HTMLImageElement.h b/Source/core/html/HTMLImageElement.h
index 9a819a7..5f238cd 100644
--- a/Source/core/html/HTMLImageElement.h
+++ b/Source/core/html/HTMLImageElement.h
@@ -109,6 +109,8 @@
     virtual bool canStartSelection() const OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
 
     virtual bool draggable() const OVERRIDE;
 
diff --git a/Source/core/html/HTMLInputElement.cpp b/Source/core/html/HTMLInputElement.cpp
index fade032..53526f2 100644
--- a/Source/core/html/HTMLInputElement.cpp
+++ b/Source/core/html/HTMLInputElement.cpp
@@ -1206,6 +1206,16 @@
     return attribute.name() == srcAttr || attribute.name() == formactionAttr || HTMLTextFormControlElement::isURLAttribute(attribute);
 }
 
+bool HTMLInputElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return m_inputType->hasLegalLinkAttribute(name) || HTMLTextFormControlElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLInputElement::subResourceAttributeName() const
+{
+    return m_inputType->subResourceAttributeName();
+}
+
 const AtomicString& HTMLInputElement::defaultValue() const
 {
     return fastGetAttribute(valueAttr);
diff --git a/Source/core/html/HTMLInputElement.h b/Source/core/html/HTMLInputElement.h
index e6dd216..f94669d 100644
--- a/Source/core/html/HTMLInputElement.h
+++ b/Source/core/html/HTMLInputElement.h
@@ -338,6 +338,8 @@
     virtual void postDispatchEventHandler(Event*, void* dataFromPreDispatch) OVERRIDE FINAL;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE FINAL;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE FINAL;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE FINAL;
     virtual bool isInRange() const OVERRIDE FINAL;
     virtual bool isOutOfRange() const OVERRIDE FINAL;
 
diff --git a/Source/core/html/HTMLLinkElement.cpp b/Source/core/html/HTMLLinkElement.cpp
index b2a8f5b..09d7978 100644
--- a/Source/core/html/HTMLLinkElement.cpp
+++ b/Source/core/html/HTMLLinkElement.cpp
@@ -52,12 +52,84 @@
 
 using namespace HTMLNames;
 
+template <typename CharacterType>
+static void parseSizes(const CharacterType* value, unsigned length, Vector<IntSize>& iconSizes)
+{
+    enum State {
+        ParseStart,
+        ParseWidth,
+        ParseHeight
+    };
+    int width = 0;
+    unsigned start = 0;
+    unsigned i = 0;
+    State state = ParseStart;
+    bool invalid = false;
+    for (; i < length; ++i) {
+        if (state == ParseWidth) {
+            if (value[i] == 'x' || value[i] == 'X') {
+                if (i == start) {
+                    invalid = true;
+                    break;
+                }
+                width = charactersToInt(value + start, i - start);
+                start = i + 1;
+                state = ParseHeight;
+            } else if (value[i] < '0' || value[i] > '9') {
+                invalid = true;
+                break;
+            }
+        } else if (state == ParseHeight) {
+            if (value[i] == ' ') {
+                if (i == start) {
+                    invalid = true;
+                    break;
+                }
+                int height = charactersToInt(value + start, i - start);
+                iconSizes.append(IntSize(width, height));
+                start = i + 1;
+                state = ParseStart;
+            } else if (value[i] < '0' || value[i] > '9') {
+                invalid = true;
+                break;
+            }
+        } else if (state == ParseStart) {
+            if (value[i] >= '0' && value[i] <= '9') {
+                start = i;
+                state = ParseWidth;
+            } else if (value[i] != ' ') {
+                invalid = true;
+                break;
+            }
+        }
+    }
+    if (invalid || state == ParseWidth || (state == ParseHeight && start == i)) {
+        iconSizes.clear();
+        return;
+    }
+    if (state == ParseHeight && i > start) {
+        int height = charactersToInt(value + start, i - start);
+        iconSizes.append(IntSize(width, height));
+    }
+}
+
 static LinkEventSender& linkLoadEventSender()
 {
     DEFINE_STATIC_LOCAL(LinkEventSender, sharedLoadEventSender, (EventTypeNames::load));
     return sharedLoadEventSender;
 }
 
+void HTMLLinkElement::parseSizesAttribute(const AtomicString& value, Vector<IntSize>& iconSizes)
+{
+    ASSERT(iconSizes.isEmpty());
+    if (value.isEmpty())
+        return;
+    if (value.is8Bit())
+        parseSizes(value.characters8(), value.length(), iconSizes);
+    else
+        parseSizes(value.characters16(), value.length(), iconSizes);
+}
+
 inline HTMLLinkElement::HTMLLinkElement(Document& document, bool createdByParser)
     : HTMLElement(linkTag, document)
     , m_linkLoader(this)
@@ -96,6 +168,7 @@
         process();
     } else if (name == sizesAttr) {
         m_sizes->setValue(value);
+        parseSizesAttribute(value, m_iconSizes);
         process();
     } else if (name == mediaAttr) {
         m_media = value.string().lower();
@@ -230,7 +303,7 @@
     }
     document().styleEngine()->removeStyleSheetCandidateNode(this);
 
-    RefPtr<StyleSheet> removedSheet = sheet();
+    RefPtrWillBeRawPtr<StyleSheet> removedSheet = sheet();
 
     if (m_link)
         m_link->ownerRemoved();
@@ -327,6 +400,22 @@
     return attribute.name().localName() == hrefAttr || HTMLElement::isURLAttribute(attribute);
 }
 
+bool HTMLLinkElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == hrefAttr || HTMLElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLLinkElement::subResourceAttributeName() const
+{
+    // If the link element is not css, ignore it.
+    if (equalIgnoringCase(getAttribute(typeAttr), "text/css")) {
+        // FIXME: Add support for extracting links of sub-resources which
+        // are inside style-sheet such as @import, @font-face, url(), etc.
+        return hrefAttr;
+    }
+    return HTMLElement::subResourceAttributeName();
+}
+
 KURL HTMLLinkElement::href() const
 {
     return document().completeURL(getAttribute(hrefAttr));
@@ -352,9 +441,9 @@
     return m_relAttribute.iconType();
 }
 
-const AtomicString& HTMLLinkElement::iconSizes() const
+const Vector<IntSize>& HTMLLinkElement::iconSizes() const
 {
-    return m_sizes->toString();
+    return m_iconSizes;
 }
 
 DOMSettableTokenList* HTMLLinkElement::sizes() const
@@ -616,7 +705,7 @@
         }
     } else if (m_sheet) {
         // we no longer contain a stylesheet, e.g. perhaps rel or type was changed
-        RefPtr<StyleSheet> removedSheet = m_sheet;
+        RefPtrWillBeRawPtr<StyleSheet> removedSheet = m_sheet.get();
         clearSheet();
         document().removedStyleSheet(removedSheet.get());
     }
diff --git a/Source/core/html/HTMLLinkElement.h b/Source/core/html/HTMLLinkElement.h
index 8508abd..142fe17 100644
--- a/Source/core/html/HTMLLinkElement.h
+++ b/Source/core/html/HTMLLinkElement.h
@@ -109,7 +109,7 @@
     void removePendingSheet(RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
     Document& document();
 
-    RefPtr<CSSStyleSheet> m_sheet;
+    RefPtrWillBePersistent<CSSStyleSheet> m_sheet;
     DisabledState m_disabledState;
     PendingSheetType m_pendingSheetType;
     bool m_loading;
@@ -133,8 +133,8 @@
 
     IconType iconType() const;
 
-    // the icon size string as parsed from the HTML attribute
-    const AtomicString& iconSizes() const;
+    // the icon sizes as parsed from the HTML attribute
+    const Vector<IntSize>& iconSizes() const;
 
     bool async() const;
 
@@ -163,6 +163,10 @@
     bool shouldProcessStyle() { return linkResourceToProcess() && linkStyle(); }
     bool isCreatedByParser() const { return m_createdByParser; }
 
+    // Parse the icon size attribute into |iconSizes|, make this method public
+    // visible for testing purpose.
+    static void parseSizesAttribute(const AtomicString& value, Vector<IntSize>& iconSizes);
+
 private:
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
@@ -177,6 +181,8 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
     virtual bool sheetLoaded() OVERRIDE;
     virtual void notifyLoadedSheetAndAllCriticalSubresources(bool errorOccurred) OVERRIDE;
     virtual void startLoadingDynamicSheet() OVERRIDE;
@@ -199,6 +205,7 @@
     String m_type;
     String m_media;
     RefPtr<DOMSettableTokenList> m_sizes;
+    Vector<IntSize> m_iconSizes;
     LinkRelAttribute m_relAttribute;
 
     bool m_createdByParser;
diff --git a/Source/core/html/HTMLLinkElementSizesAttributeTest.cpp b/Source/core/html/HTMLLinkElementSizesAttributeTest.cpp
new file mode 100644
index 0000000..62cce28
--- /dev/null
+++ b/Source/core/html/HTMLLinkElementSizesAttributeTest.cpp
@@ -0,0 +1,77 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/html/HTMLLinkElement.h"
+
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+class HTMLLinkElementSizesAttributeTest : public testing::Test {
+};
+
+TEST(HTMLLinkElementSizesAttributeTest, parseSizes)
+{
+    AtomicString sizesAttribute = "32x33";
+    Vector<IntSize> sizes;
+    HTMLLinkElement::parseSizesAttribute(sizesAttribute, sizes);
+    ASSERT_EQ(1U, sizes.size());
+    EXPECT_EQ(32, sizes[0].width());
+    EXPECT_EQ(33, sizes[0].height());
+
+    UChar attribute[] = {'3', '2', 'x', '3', '3', 0};
+    sizesAttribute = attribute;
+    sizes.clear();
+    HTMLLinkElement::parseSizesAttribute(sizesAttribute, sizes);
+    ASSERT_EQ(1U, sizes.size());
+    EXPECT_EQ(32, sizes[0].width());
+    EXPECT_EQ(33, sizes[0].height());
+
+
+    sizesAttribute = "   32x33   16X17    128x129   ";
+    sizes.clear();
+    HTMLLinkElement::parseSizesAttribute(sizesAttribute, sizes);
+    ASSERT_EQ(3U, sizes.size());
+    EXPECT_EQ(32, sizes[0].width());
+    EXPECT_EQ(33, sizes[0].height());
+    EXPECT_EQ(16, sizes[1].width());
+    EXPECT_EQ(17, sizes[1].height());
+    EXPECT_EQ(128, sizes[2].width());
+    EXPECT_EQ(129, sizes[2].height());
+
+    sizesAttribute = "any";
+    sizes.clear();
+    HTMLLinkElement::parseSizesAttribute(sizesAttribute, sizes);
+    ASSERT_EQ(0U, sizes.size());
+
+    sizesAttribute = "32x33 32";
+    sizes.clear();
+    HTMLLinkElement::parseSizesAttribute(sizesAttribute, sizes);
+    ASSERT_EQ(0U, sizes.size());
+
+    sizesAttribute = "32x33 32x";
+    sizes.clear();
+    HTMLLinkElement::parseSizesAttribute(sizesAttribute, sizes);
+    ASSERT_EQ(0U, sizes.size());
+
+    sizesAttribute = "32x33 x32";
+    sizes.clear();
+    HTMLLinkElement::parseSizesAttribute(sizesAttribute, sizes);
+    ASSERT_EQ(0U, sizes.size());
+
+    sizesAttribute = "32x33 any";
+    sizes.clear();
+    HTMLLinkElement::parseSizesAttribute(sizesAttribute, sizes);
+    ASSERT_EQ(0U, sizes.size());
+
+    sizesAttribute = "32x33, 64x64";
+    sizes.clear();
+    HTMLLinkElement::parseSizesAttribute(sizesAttribute, sizes);
+    ASSERT_EQ(0U, sizes.size());
+}
+
+} //  namespace
diff --git a/Source/core/html/HTMLMediaElement.cpp b/Source/core/html/HTMLMediaElement.cpp
index fe5779b..22612f5 100644
--- a/Source/core/html/HTMLMediaElement.cpp
+++ b/Source/core/html/HTMLMediaElement.cpp
@@ -1568,7 +1568,7 @@
     if (m_readyState >= HAVE_METADATA && oldState < HAVE_METADATA) {
         prepareMediaFragmentURI();
         scheduleEvent(EventTypeNames::durationchange);
-        if (isVideo())
+        if (isHTMLVideoElement(*this))
             scheduleEvent(EventTypeNames::resize);
         scheduleEvent(EventTypeNames::loadedmetadata);
         if (hasMediaControls())
@@ -2853,7 +2853,7 @@
     WTF_LOG(Media, "HTMLMediaElement::mediaPlayerSizeChanged");
 
     ASSERT(hasVideo()); // "resize" makes no sense absent video.
-    if (m_readyState > HAVE_NOTHING && isVideo())
+    if (m_readyState > HAVE_NOTHING && isHTMLVideoElement(*this))
         scheduleEvent(EventTypeNames::resize);
 
     if (renderer())
@@ -3180,7 +3180,7 @@
 {
     if (hasMediaControls())
         mediaControls()->enteredFullscreen();
-    if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && isVideo())
+    if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && isHTMLVideoElement(*this))
         document().renderView()->compositor()->setCompositingLayersNeedRebuild();
 }
 
@@ -3188,7 +3188,7 @@
 {
     if (hasMediaControls())
         mediaControls()->exitedFullscreen();
-    if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && isVideo())
+    if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && isHTMLVideoElement(*this))
         document().renderView()->compositor()->setCompositingLayersNeedRebuild();
 }
 
diff --git a/Source/core/html/HTMLMediaElement.h b/Source/core/html/HTMLMediaElement.h
index 695bf5f..df5b8bf 100644
--- a/Source/core/html/HTMLMediaElement.h
+++ b/Source/core/html/HTMLMediaElement.h
@@ -84,8 +84,7 @@
     MediaPlayer* player() const { return m_player.get(); }
     blink::WebMediaPlayer* webMediaPlayer() const { return m_player ? m_player->webMediaPlayer() : 0; }
 
-    virtual bool isVideo() const = 0;
-    virtual bool hasVideo() const OVERRIDE { return false; }
+    virtual bool hasVideo() const { return false; }
     virtual bool hasAudio() const OVERRIDE FINAL;
 
     bool supportsSave() const;
@@ -234,11 +233,11 @@
     bool hasSingleSecurityOrigin() const { return !m_player || m_player->hasSingleSecurityOrigin(); }
 
     bool isFullscreen() const;
-    virtual void enterFullscreen() OVERRIDE FINAL;
+    void enterFullscreen();
 
-    virtual bool hasClosedCaptions() const OVERRIDE FINAL;
-    virtual bool closedCaptionsVisible() const OVERRIDE FINAL;
-    virtual void setClosedCaptionsVisible(bool) OVERRIDE FINAL;
+    bool hasClosedCaptions() const;
+    bool closedCaptionsVisible() const;
+    void setClosedCaptionsVisible(bool);
 
     MediaControls* mediaControls() const;
 
@@ -541,17 +540,17 @@
 };
 #endif
 
-inline bool isHTMLMediaElement(const Node& node)
+inline bool isHTMLMediaElement(const Element& element)
 {
-    return isHTMLAudioElement(node) || isHTMLVideoElement(node);
+    return isHTMLAudioElement(element) || isHTMLVideoElement(element);
 }
 
-inline bool isHTMLMediaElement(const Node* node)
+inline bool isHTMLMediaElement(const HTMLElement& element)
 {
-    return node && isHTMLMediaElement(*node);
+    return isHTMLAudioElement(element) || isHTMLVideoElement(element);
 }
 
-DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLMediaElement);
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLMediaElement);
 
 } //namespace
 
diff --git a/Source/core/html/HTMLMediaSource.h b/Source/core/html/HTMLMediaSource.h
index f40206c..14baccb 100644
--- a/Source/core/html/HTMLMediaSource.h
+++ b/Source/core/html/HTMLMediaSource.h
@@ -31,7 +31,6 @@
 #ifndef HTMLMediaSource_h
 #define HTMLMediaSource_h
 
-#include "core/html/HTMLMediaElement.h"
 #include "core/html/URLRegistry.h"
 #include "wtf/Forward.h"
 
@@ -41,6 +40,7 @@
 
 namespace WebCore {
 
+class HTMLMediaElement;
 class TimeRanges;
 
 class HTMLMediaSource : public URLRegistrable {
diff --git a/Source/core/html/HTMLModElement.cpp b/Source/core/html/HTMLModElement.cpp
index e609ef5..2d99964 100644
--- a/Source/core/html/HTMLModElement.cpp
+++ b/Source/core/html/HTMLModElement.cpp
@@ -45,4 +45,14 @@
     return attribute.name() == citeAttr || HTMLElement::isURLAttribute(attribute);
 }
 
+bool HTMLModElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == citeAttr || HTMLElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLModElement::subResourceAttributeName() const
+{
+    return citeAttr;
+}
+
 }
diff --git a/Source/core/html/HTMLModElement.h b/Source/core/html/HTMLModElement.h
index 7fcc7c9..41a46dd 100644
--- a/Source/core/html/HTMLModElement.h
+++ b/Source/core/html/HTMLModElement.h
@@ -36,6 +36,8 @@
     HTMLModElement(const QualifiedName&, Document&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLOListElement.cpp b/Source/core/html/HTMLOListElement.cpp
index 0367551..f13880c 100644
--- a/Source/core/html/HTMLOListElement.cpp
+++ b/Source/core/html/HTMLOListElement.cpp
@@ -100,6 +100,9 @@
 
 void HTMLOListElement::updateItemValues()
 {
+    if (!renderer())
+        return;
+    document().updateDistributionForNodeIfNeeded(this);
     RenderListItem::updateItemValuesForOrderedList(this);
 }
 
diff --git a/Source/core/html/HTMLObjectElement.cpp b/Source/core/html/HTMLObjectElement.cpp
index 5e0fb91..a42afa3 100644
--- a/Source/core/html/HTMLObjectElement.cpp
+++ b/Source/core/html/HTMLObjectElement.cpp
@@ -370,6 +370,16 @@
         || HTMLPlugInElement::isURLAttribute(attribute);
 }
 
+bool HTMLObjectElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == classidAttr || name == dataAttr || name == codebaseAttr || HTMLPlugInElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLObjectElement::subResourceAttributeName() const
+{
+    return dataAttr;
+}
+
 const AtomicString HTMLObjectElement::imageSourceURL() const
 {
     return getAttribute(dataAttr);
@@ -430,7 +440,7 @@
     if (MIMETypeRegistry::isJavaAppletMIMEType(getAttribute(typeAttr)))
         return true;
 
-    for (HTMLElement* child = Traversal<HTMLElement>::firstWithin(*this); child; child = Traversal<HTMLElement>::nextSkippingChildren(*child, this)) {
+    for (HTMLElement* child = Traversal<HTMLElement>::firstChild(*this); child; child = Traversal<HTMLElement>::nextSibling(*child)) {
         if (isHTMLParamElement(*child)
                 && equalIgnoringCase(child->getNameAttribute(), "type")
                 && MIMETypeRegistry::isJavaAppletMIMEType(child->getAttribute(valueAttr).string()))
diff --git a/Source/core/html/HTMLObjectElement.h b/Source/core/html/HTMLObjectElement.h
index 1ca9fd8..6a917ad 100644
--- a/Source/core/html/HTMLObjectElement.h
+++ b/Source/core/html/HTMLObjectElement.h
@@ -81,6 +81,8 @@
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
     virtual const AtomicString imageSourceURL() const OVERRIDE;
 
     virtual RenderWidget* existingRenderWidget() const OVERRIDE;
diff --git a/Source/core/html/HTMLPlugInElement.h b/Source/core/html/HTMLPlugInElement.h
index 74e7a0c..92ed0f2 100644
--- a/Source/core/html/HTMLPlugInElement.h
+++ b/Source/core/html/HTMLPlugInElement.h
@@ -98,7 +98,6 @@
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
     virtual void finishParsingChildren() OVERRIDE FINAL;
-    virtual bool isPluginElement() const OVERRIDE FINAL;
 
     // Element functions:
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
@@ -111,6 +110,7 @@
 
     // HTMLElement function:
     virtual bool hasCustomFocusLogic() const OVERRIDE;
+    virtual bool isPluginElement() const OVERRIDE FINAL;
 
     // Return any existing RenderWidget without triggering relayout, or 0 if it
     // doesn't yet exist.
@@ -138,7 +138,17 @@
     DisplayState m_displayState;
 };
 
-DEFINE_ELEMENT_TYPE_CASTS(HTMLPlugInElement, isPluginElement());
+inline bool isHTMLPlugInElement(const Element& element)
+{
+    return element.isHTMLElement() && toHTMLElement(element).isPluginElement();
+}
+
+inline bool isHTMLPlugInElement(const HTMLElement& element)
+{
+    return element.isPluginElement();
+}
+
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLPlugInElement);
 
 } // namespace WebCore
 
diff --git a/Source/core/html/HTMLQuoteElement.cpp b/Source/core/html/HTMLQuoteElement.cpp
index ff18c60..f690991 100644
--- a/Source/core/html/HTMLQuoteElement.cpp
+++ b/Source/core/html/HTMLQuoteElement.cpp
@@ -48,4 +48,14 @@
     return attribute.name() == citeAttr || HTMLElement::isURLAttribute(attribute);
 }
 
+bool HTMLQuoteElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == citeAttr || HTMLElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLQuoteElement::subResourceAttributeName() const
+{
+    return citeAttr;
+}
+
 }
diff --git a/Source/core/html/HTMLQuoteElement.h b/Source/core/html/HTMLQuoteElement.h
index bfdc9ee..09ec799 100644
--- a/Source/core/html/HTMLQuoteElement.h
+++ b/Source/core/html/HTMLQuoteElement.h
@@ -37,6 +37,8 @@
     HTMLQuoteElement(const QualifiedName&, Document&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLScriptElement.cpp b/Source/core/html/HTMLScriptElement.cpp
index 50afbd1..46a6892 100644
--- a/Source/core/html/HTMLScriptElement.cpp
+++ b/Source/core/html/HTMLScriptElement.cpp
@@ -54,6 +54,16 @@
     return attribute.name() == srcAttr || HTMLElement::isURLAttribute(attribute);
 }
 
+bool HTMLScriptElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == srcAttr || HTMLElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLScriptElement::subResourceAttributeName() const
+{
+    return srcAttr;
+}
+
 void HTMLScriptElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
     HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
diff --git a/Source/core/html/HTMLScriptElement.h b/Source/core/html/HTMLScriptElement.h
index adc0362..e60718f 100644
--- a/Source/core/html/HTMLScriptElement.h
+++ b/Source/core/html/HTMLScriptElement.h
@@ -54,6 +54,8 @@
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
 
     virtual String sourceAttributeValue() const OVERRIDE;
     virtual String charsetAttributeValue() const OVERRIDE;
diff --git a/Source/core/html/HTMLSelectElement.cpp b/Source/core/html/HTMLSelectElement.cpp
index 535b803..ed9942c 100644
--- a/Source/core/html/HTMLSelectElement.cpp
+++ b/Source/core/html/HTMLSelectElement.cpp
@@ -73,6 +73,7 @@
     , m_multiple(false)
     , m_activeSelectionState(false)
     , m_shouldRecalcListItems(false)
+    , m_suggestedIndex(-1)
 {
     ScriptWrappable::init(this);
 }
@@ -203,7 +204,7 @@
     // Make sure the element is ref'd and deref'd so we don't leak it.
     RefPtr<HTMLElement> protectNewChild(element);
 
-    if (!element || !(element->hasLocalName(optionTag) || element->hasLocalName(hrTag)))
+    if (!element || !(isHTMLOptionElement(element) || isHTMLHRElement(element)))
         return;
 
     insertBefore(element, before, exceptionState);
@@ -223,7 +224,7 @@
 {
     const Vector<HTMLElement*>& items = listItems();
     for (unsigned i = 0; i < items.size(); i++) {
-        if (items[i]->hasLocalName(optionTag) && toHTMLOptionElement(items[i])->selected())
+        if (isHTMLOptionElement(items[i]) && toHTMLOptionElement(items[i])->selected())
             return toHTMLOptionElement(items[i])->value();
     }
     return "";
@@ -241,7 +242,7 @@
     const Vector<HTMLElement*>& items = listItems();
     unsigned optionIndex = 0;
     for (unsigned i = 0; i < items.size(); i++) {
-        if (items[i]->hasLocalName(optionTag)) {
+        if (isHTMLOptionElement(items[i])) {
             if (toHTMLOptionElement(items[i])->value() == value) {
                 setSelectedIndex(optionIndex);
                 return;
@@ -253,6 +254,40 @@
     setSelectedIndex(-1);
 }
 
+String HTMLSelectElement::suggestedValue() const
+{
+    const Vector<HTMLElement*>& items = listItems();
+    for (unsigned i = 0; i < items.size(); ++i) {
+        if (isHTMLOptionElement(items[i]) && m_suggestedIndex >= 0) {
+            if (i == static_cast<unsigned>(m_suggestedIndex))
+                return toHTMLOptionElement(items[i])->value();
+        }
+    }
+    return "";
+}
+
+void HTMLSelectElement::setSuggestedValue(const String& value)
+{
+    if (value.isNull()) {
+        setSuggestedIndex(-1);
+        return;
+    }
+
+    const Vector<HTMLElement*>& items = listItems();
+    unsigned optionIndex = 0;
+    for (unsigned i = 0; i < items.size(); ++i) {
+        if (isHTMLOptionElement(items[i])) {
+            if (toHTMLOptionElement(items[i])->value() == value) {
+                setSuggestedIndex(optionIndex);
+                return;
+            }
+            optionIndex++;
+        }
+    }
+
+    setSuggestedIndex(-1);
+}
+
 bool HTMLSelectElement::isPresentationAttribute(const QualifiedName& name) const
 {
     if (name == alignAttr) {
@@ -441,7 +476,7 @@
         size_t optionIndex = 0;
         for (size_t i = 0; i < items.size(); ++i) {
             Element* item = items[i];
-            if (item->hasLocalName(optionTag) && optionIndex++ >= newLen) {
+            if (isHTMLOptionElement(items[i]) && optionIndex++ >= newLen) {
                 ASSERT(item->parentNode());
                 itemsToRemove.append(item);
             }
@@ -797,6 +832,22 @@
     selectOption(index, DeselectOtherOptions);
 }
 
+int HTMLSelectElement::suggestedIndex() const
+{
+    return m_suggestedIndex;
+}
+
+void HTMLSelectElement::setSuggestedIndex(int suggestedIndex)
+{
+    m_suggestedIndex = suggestedIndex;
+
+    if (RenderObject* renderer = this->renderer())  {
+        renderer->updateFromElement();
+        if (renderer->isListBox())
+            toRenderListBox(renderer)->scrollToRevealElementAtListIndex(suggestedIndex);
+    }
+}
+
 void HTMLSelectElement::optionSelectionStateChanged(HTMLOptionElement* option, bool optionIsSelected)
 {
     ASSERT(option->ownerSelectElement() == this);
@@ -939,7 +990,7 @@
     const Vector<HTMLElement*>& items = listItems();
     size_t loopEndIndex = std::min(items.size(), listIndexEnd);
     for (size_t i = listIndexStart; i < loopEndIndex; ++i) {
-        if (!items[i]->hasLocalName(optionTag))
+        if (!isHTMLOptionElement(items[i]))
             continue;
         if (toHTMLOptionElement(items[i])->value() == value)
             return i;
@@ -957,7 +1008,7 @@
         return;
 
     for (size_t i = 0; i < itemsSize; ++i) {
-        if (!items[i]->hasLocalName(optionTag))
+        if (!isHTMLOptionElement(items[i]))
             continue;
         toHTMLOptionElement(items[i])->setSelectedState(false);
     }
diff --git a/Source/core/html/HTMLSelectElement.h b/Source/core/html/HTMLSelectElement.h
index 2f1f0e2..8268cc1 100644
--- a/Source/core/html/HTMLSelectElement.h
+++ b/Source/core/html/HTMLSelectElement.h
@@ -44,6 +44,8 @@
 
     int selectedIndex() const;
     void setSelectedIndex(int);
+    int suggestedIndex() const;
+    void setSuggestedIndex(int);
 
     void optionSelectedByUser(int index, bool dispatchChangeEvent, bool allowMultipleSelection = false);
 
@@ -67,6 +69,8 @@
 
     String value() const;
     void setValue(const String&);
+    String suggestedValue() const;
+    void setSuggestedValue(const String&);
 
     PassRefPtr<HTMLOptionsCollection> options();
     PassRefPtr<HTMLCollection> selectedOptions();
@@ -204,6 +208,7 @@
     bool m_multiple;
     bool m_activeSelectionState;
     mutable bool m_shouldRecalcListItems;
+    int m_suggestedIndex;
 };
 
 } // namespace
diff --git a/Source/core/html/HTMLShadowElement.idl b/Source/core/html/HTMLShadowElement.idl
index 44bc357..32c8340 100644
--- a/Source/core/html/HTMLShadowElement.idl
+++ b/Source/core/html/HTMLShadowElement.idl
@@ -29,6 +29,5 @@
  */
 
 interface HTMLShadowElement : HTMLElement {
-    attribute boolean resetStyleInheritance;
     [RuntimeEnabled=ShadowDOM] NodeList getDistributedNodes();
 };
diff --git a/Source/core/html/HTMLStyleElement.cpp b/Source/core/html/HTMLStyleElement.cpp
index c7f9ec6..76f96d2 100644
--- a/Source/core/html/HTMLStyleElement.cpp
+++ b/Source/core/html/HTMLStyleElement.cpp
@@ -76,8 +76,7 @@
         scopedAttributeChanged(!value.isNull());
     } else if (name == mediaAttr && inDocument() && document().isActive() && m_sheet) {
         m_sheet->setMediaQueries(MediaQuerySet::create(value));
-        // FIXME: This shold be RecalcStyleDeferred.
-        document().modifiedStyleSheet(m_sheet.get(), RecalcStyleImmediately);
+        document().modifiedStyleSheet(m_sheet.get(), RecalcStyleDeferred);
     } else {
         HTMLElement::parseAttribute(name, value);
     }
diff --git a/Source/core/html/HTMLTableCellElement.cpp b/Source/core/html/HTMLTableCellElement.cpp
index 9e0b4f1..a68ba17 100644
--- a/Source/core/html/HTMLTableCellElement.cpp
+++ b/Source/core/html/HTMLTableCellElement.cpp
@@ -128,6 +128,16 @@
     return attribute.name() == backgroundAttr || HTMLTablePartElement::isURLAttribute(attribute);
 }
 
+bool HTMLTableCellElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return (hasLocalName(tdTag) && name == backgroundAttr) || HTMLTablePartElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLTableCellElement::subResourceAttributeName() const
+{
+    return hasLocalName(tdTag) ? backgroundAttr : HTMLTablePartElement::subResourceAttributeName();
+}
+
 const AtomicString& HTMLTableCellElement::abbr() const
 {
     return fastGetAttribute(abbrAttr);
diff --git a/Source/core/html/HTMLTableCellElement.h b/Source/core/html/HTMLTableCellElement.h
index 19ea012..d90552b 100644
--- a/Source/core/html/HTMLTableCellElement.h
+++ b/Source/core/html/HTMLTableCellElement.h
@@ -59,14 +59,21 @@
     virtual const StylePropertySet* additionalPresentationAttributeStyle() OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
 };
 
-inline bool isHTMLTableCellElement(const Node& node)
+inline bool isHTMLTableCellElement(const Element& element)
 {
-    return node.hasTagName(HTMLNames::tdTag) || node.hasTagName(HTMLNames::thTag);
+    return element.hasTagName(HTMLNames::tdTag) || element.hasTagName(HTMLNames::thTag);
 }
 
-DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTableCellElement);
+inline bool isHTMLTableCellElement(const HTMLElement& element)
+{
+    return element.hasLocalName(HTMLNames::tdTag) || element.hasLocalName(HTMLNames::thTag);
+}
+
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTableCellElement);
 
 } // namespace
 
diff --git a/Source/core/html/HTMLTableColElement.h b/Source/core/html/HTMLTableColElement.h
index be4069e..9c24f5b 100644
--- a/Source/core/html/HTMLTableColElement.h
+++ b/Source/core/html/HTMLTableColElement.h
@@ -50,12 +50,17 @@
     int m_span;
 };
 
-inline bool isHTMLTableColElement(const Node& node)
+inline bool isHTMLTableColElement(const Element& element)
 {
-    return node.hasTagName(HTMLNames::colTag) || node.hasTagName(HTMLNames::colgroupTag);
+    return element.hasTagName(HTMLNames::colTag) || element.hasTagName(HTMLNames::colgroupTag);
 }
 
-DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTableColElement);
+inline bool isHTMLTableColElement(const HTMLElement& element)
+{
+    return element.hasLocalName(HTMLNames::colTag) || element.hasLocalName(HTMLNames::colgroupTag);
+}
+
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTableColElement);
 
 } // namespace WebCore
 
diff --git a/Source/core/html/HTMLTableElement.cpp b/Source/core/html/HTMLTableElement.cpp
index 49c56e9..70503c2 100644
--- a/Source/core/html/HTMLTableElement.cpp
+++ b/Source/core/html/HTMLTableElement.cpp
@@ -400,7 +400,7 @@
 
 static PassRefPtr<StylePropertySet> createBorderStyle(CSSValueID value)
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     style->setProperty(CSSPropertyBorderTopStyle, value);
     style->setProperty(CSSPropertyBorderBottomStyle, value);
     style->setProperty(CSSPropertyBorderLeftStyle, value);
@@ -456,7 +456,7 @@
 
 PassRefPtr<StylePropertySet> HTMLTableElement::createSharedCellStyle()
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
 
     switch (cellBorders()) {
     case SolidBordersColsOnly:
@@ -503,7 +503,7 @@
 
 static PassRefPtr<StylePropertySet> createGroupBorderStyle(int rows)
 {
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
     if (rows) {
         style->setProperty(CSSPropertyBorderTopWidth, CSSValueThin);
         style->setProperty(CSSPropertyBorderBottomWidth, CSSValueThin);
@@ -536,6 +536,16 @@
     return attribute.name() == backgroundAttr || HTMLElement::isURLAttribute(attribute);
 }
 
+bool HTMLTableElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == backgroundAttr || HTMLElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLTableElement::subResourceAttributeName() const
+{
+    return backgroundAttr;
+}
+
 PassRefPtr<HTMLCollection> HTMLTableElement::rows()
 {
     return ensureCachedHTMLCollection(TableRows);
diff --git a/Source/core/html/HTMLTableElement.h b/Source/core/html/HTMLTableElement.h
index 71f8154..ad3b774 100644
--- a/Source/core/html/HTMLTableElement.h
+++ b/Source/core/html/HTMLTableElement.h
@@ -75,6 +75,8 @@
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
 
     // Used to obtain either a solid or outset border decl and to deal with the frame and rules attributes.
     virtual const StylePropertySet* additionalPresentationAttributeStyle() OVERRIDE;
diff --git a/Source/core/html/HTMLTableRowElement.cpp b/Source/core/html/HTMLTableRowElement.cpp
index 2938abb..d6fd9ce 100644
--- a/Source/core/html/HTMLTableRowElement.cpp
+++ b/Source/core/html/HTMLTableRowElement.cpp
@@ -44,6 +44,16 @@
     ScriptWrappable::init(this);
 }
 
+bool HTMLTableRowElement::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == backgroundAttr || HTMLTablePartElement::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& HTMLTableRowElement::subResourceAttributeName() const
+{
+    return backgroundAttr;
+}
+
 PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(Document& document)
 {
     return adoptRef(new HTMLTableRowElement(document));
diff --git a/Source/core/html/HTMLTableRowElement.h b/Source/core/html/HTMLTableRowElement.h
index 3dac5e2..a5a7e14 100644
--- a/Source/core/html/HTMLTableRowElement.h
+++ b/Source/core/html/HTMLTableRowElement.h
@@ -47,6 +47,9 @@
 
 private:
     explicit HTMLTableRowElement(Document&);
+
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
 };
 
 } // namespace
diff --git a/Source/core/html/HTMLTableSectionElement.h b/Source/core/html/HTMLTableSectionElement.h
index 4ab3b0b..53cc913 100644
--- a/Source/core/html/HTMLTableSectionElement.h
+++ b/Source/core/html/HTMLTableSectionElement.h
@@ -49,12 +49,17 @@
     virtual const StylePropertySet* additionalPresentationAttributeStyle() OVERRIDE;
 };
 
-inline bool isHTMLTableSectionElement(const Node& node)
+inline bool isHTMLTableSectionElement(const Element& element)
 {
-    return node.hasTagName(HTMLNames::tbodyTag) || node.hasTagName(HTMLNames::tfootTag) || node.hasTagName(HTMLNames::theadTag);
+    return element.hasTagName(HTMLNames::tbodyTag) || element.hasTagName(HTMLNames::tfootTag) || element.hasTagName(HTMLNames::theadTag);
 }
 
-DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTableSectionElement);
+inline bool isHTMLTableSectionElement(const HTMLElement& element)
+{
+    return element.hasLocalName(HTMLNames::tbodyTag) || element.hasLocalName(HTMLNames::tfootTag) || element.hasLocalName(HTMLNames::theadTag);
+}
+
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTableSectionElement);
 
 } //namespace
 
diff --git a/Source/core/html/HTMLTextFormControlElement.h b/Source/core/html/HTMLTextFormControlElement.h
index d64d1fc..5484262 100644
--- a/Source/core/html/HTMLTextFormControlElement.h
+++ b/Source/core/html/HTMLTextFormControlElement.h
@@ -135,12 +135,12 @@
     TextFieldSelectionDirection m_cachedSelectionDirection;
 };
 
-inline bool isHTMLTextFormControlElement(const Node& node)
+inline bool isHTMLTextFormControlElement(const Element& element)
 {
-    return node.isElementNode() && toElement(node).isTextFormControl();
+    return element.isTextFormControl();
 }
 
-DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTextFormControlElement);
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTextFormControlElement);
 
 HTMLTextFormControlElement* enclosingTextFormControl(const Position&);
 
diff --git a/Source/core/html/HTMLUnknownElement.h b/Source/core/html/HTMLUnknownElement.h
index d35aa71..f3c5397 100644
--- a/Source/core/html/HTMLUnknownElement.h
+++ b/Source/core/html/HTMLUnknownElement.h
@@ -51,12 +51,17 @@
     }
 };
 
-inline bool isHTMLUnknownElement(const Node& node)
+inline bool isHTMLUnknownElement(const Element& element)
 {
-    return node.isElementNode() && toHTMLElement(node).isHTMLUnknownElement();
+    return element.isHTMLElement() && toHTMLElement(element).isHTMLUnknownElement();
 }
 
-DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLUnknownElement);
+inline bool isHTMLUnknownElement(const HTMLElement& element)
+{
+    return element.isHTMLUnknownElement();
+}
+
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLUnknownElement);
 
 } // namespace
 
diff --git a/Source/core/html/HTMLVideoElement.h b/Source/core/html/HTMLVideoElement.h
index 02e82e1..b4d92d1 100644
--- a/Source/core/html/HTMLVideoElement.h
+++ b/Source/core/html/HTMLVideoElement.h
@@ -78,7 +78,6 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
-    virtual bool isVideo() const OVERRIDE { return true; }
     virtual bool hasVideo() const OVERRIDE { return player() && player()->hasVideo(); }
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
     virtual const AtomicString imageSourceURL() const OVERRIDE;
diff --git a/Source/core/html/ImageDocument.cpp b/Source/core/html/ImageDocument.cpp
index 193cbab..2782a6d 100644
--- a/Source/core/html/ImageDocument.cpp
+++ b/Source/core/html/ImageDocument.cpp
@@ -227,8 +227,8 @@
     LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), pageZoomFactor(this));
     LayoutSize windowSize = LayoutSize(view->width(), view->height());
 
-    float widthScale = (float)windowSize.width() / imageSize.width();
-    float heightScale = (float)windowSize.height() / imageSize.height();
+    float widthScale = windowSize.width().toFloat() / imageSize.width().toFloat();
+    float heightScale = windowSize.height().toFloat() / imageSize.height().toFloat();
 
     return min(widthScale, heightScale);
 }
diff --git a/Source/core/html/LabelableElement.h b/Source/core/html/LabelableElement.h
index 4497557..18f4408 100644
--- a/Source/core/html/LabelableElement.h
+++ b/Source/core/html/LabelableElement.h
@@ -50,12 +50,17 @@
     virtual bool isLabelable() const OVERRIDE FINAL { return true; }
 };
 
-inline bool isLabelableElement(const Node& node)
+inline bool isLabelableElement(const Element& element)
 {
-    return node.isHTMLElement() && toHTMLElement(node).isLabelable();
+    return element.isHTMLElement() && toHTMLElement(element).isLabelable();
 }
 
-DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(LabelableElement);
+inline bool isLabelableElement(const HTMLElement& element)
+{
+    return element.isLabelable();
+}
+
+DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(LabelableElement);
 
 } // namespace WebCore
 
diff --git a/Source/core/html/MediaController.cpp b/Source/core/html/MediaController.cpp
index c7fb6b5..4494b08 100644
--- a/Source/core/html/MediaController.cpp
+++ b/Source/core/html/MediaController.cpp
@@ -55,7 +55,6 @@
     , m_playbackState(WAITING)
     , m_asyncEventTimer(this, &MediaController::asyncEventTimerFired)
     , m_clearPositionTimer(this, &MediaController::clearPositionTimerFired)
-    , m_closedCaptionsVisible(false)
     , m_clock(Clock::create())
     , m_executionContext(context)
     , m_timeupdateTimer(this, &MediaController::timeupdateTimerFired)
@@ -566,31 +565,6 @@
     return false;
 }
 
-bool MediaController::hasVideo() const
-{
-    for (size_t index = 0; index < m_mediaElements.size(); ++index) {
-        if (m_mediaElements[index]->hasVideo())
-            return true;
-    }
-    return false;
-}
-
-bool MediaController::hasClosedCaptions() const
-{
-    for (size_t index = 0; index < m_mediaElements.size(); ++index) {
-        if (m_mediaElements[index]->hasClosedCaptions())
-            return true;
-    }
-    return false;
-}
-
-void MediaController::setClosedCaptionsVisible(bool visible)
-{
-    m_closedCaptionsVisible = visible;
-    for (size_t index = 0; index < m_mediaElements.size(); ++index)
-        m_mediaElements[index]->setClosedCaptionsVisible(visible);
-}
-
 void MediaController::beginScrubbing()
 {
     for (size_t index = 0; index < m_mediaElements.size(); ++index)
diff --git a/Source/core/html/MediaController.h b/Source/core/html/MediaController.h
index deee58c..1505b2d 100644
--- a/Source/core/html/MediaController.h
+++ b/Source/core/html/MediaController.h
@@ -41,7 +41,6 @@
 class Clock;
 class Event;
 class ExceptionState;
-class HTMLMediaElement;
 class ExecutionContext;
 
 class MediaController FINAL : public RefCounted<MediaController>, public ScriptWrappable, public MediaControllerInterface, public EventTargetWithInlineData {
@@ -85,13 +84,7 @@
     enum PlaybackState { WAITING, PLAYING, ENDED };
     const AtomicString& playbackState() const;
 
-    virtual void enterFullscreen() OVERRIDE { }
-
     virtual bool hasAudio() const OVERRIDE;
-    virtual bool hasVideo() const OVERRIDE;
-    virtual bool hasClosedCaptions() const OVERRIDE;
-    virtual void setClosedCaptionsVisible(bool) OVERRIDE;
-    virtual bool closedCaptionsVisible() const OVERRIDE { return m_closedCaptionsVisible; }
 
     virtual void beginScrubbing() OVERRIDE;
     virtual void endScrubbing() OVERRIDE;
@@ -134,7 +127,6 @@
     Vector<RefPtr<Event> > m_pendingEvents;
     Timer<MediaController> m_asyncEventTimer;
     mutable Timer<MediaController> m_clearPositionTimer;
-    bool m_closedCaptionsVisible;
     OwnPtr<Clock> m_clock;
     ExecutionContext* m_executionContext;
     Timer<MediaController> m_timeupdateTimer;
diff --git a/Source/core/html/MediaControllerInterface.h b/Source/core/html/MediaControllerInterface.h
index 481d6bd..d7f116c 100644
--- a/Source/core/html/MediaControllerInterface.h
+++ b/Source/core/html/MediaControllerInterface.h
@@ -49,13 +49,7 @@
     virtual bool muted() const = 0;
     virtual void setMuted(bool) = 0;
 
-    virtual void enterFullscreen() = 0;
-
     virtual bool hasAudio() const = 0;
-    virtual bool hasVideo() const = 0;
-    virtual bool hasClosedCaptions() const = 0;
-    virtual void setClosedCaptionsVisible(bool) = 0;
-    virtual bool closedCaptionsVisible() const = 0;
 
     virtual void beginScrubbing() = 0;
     virtual void endScrubbing() = 0;
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index ef14b3f..c7aee8f 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -1869,7 +1869,7 @@
         return;
 
     MutableStylePropertyMap::iterator i = m_fetchedFonts.find(newFont);
-    RefPtr<MutableStylePropertySet> parsedStyle = i != m_fetchedFonts.end() ? i->value : nullptr;
+    RefPtrWillBeRawPtr<MutableStylePropertySet> parsedStyle = i != m_fetchedFonts.end() ? i->value : nullptr;
 
     if (!parsedStyle) {
         parsedStyle = MutableStylePropertySet::create();
@@ -2197,7 +2197,7 @@
     modifiableState().m_imageSmoothingEnabled = enabled;
     GraphicsContext* c = drawingContext();
     if (c)
-        c->setImageInterpolationQuality(enabled ? DefaultInterpolationQuality : InterpolationNone);
+        c->setImageInterpolationQuality(enabled ? CanvasDefaultInterpolationQuality : InterpolationNone);
 }
 
 PassRefPtr<Canvas2DContextAttributes> CanvasRenderingContext2D::getContextAttributes() const
@@ -2238,7 +2238,7 @@
         return false;
     if (path.isEmpty())
         return false;
-    if (!element->isDescendantOf(canvas()))
+    if (!element || !element->isDescendantOf(canvas()))
         return false;
 
     return true;
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.h b/Source/core/html/canvas/CanvasRenderingContext2D.h
index bb9d9df..022b9cf 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.h
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.h
@@ -63,7 +63,7 @@
 class ImageData;
 class TextMetrics;
 
-typedef HashMap<String, RefPtr<MutableStylePropertySet> > MutableStylePropertyMap;
+typedef WillBePersistentHeapHashMap<String, RefPtrWillBeMember<MutableStylePropertySet> > MutableStylePropertyMap;
 
 class CanvasRenderingContext2D FINAL: public ScriptWrappable, public CanvasRenderingContext, public CanvasPathMethods {
 public:
diff --git a/Source/core/html/canvas/WebGLContextAttributes.cpp b/Source/core/html/canvas/WebGLContextAttributes.cpp
index 4d63bb6..3857206 100644
--- a/Source/core/html/canvas/WebGLContextAttributes.cpp
+++ b/Source/core/html/canvas/WebGLContextAttributes.cpp
@@ -159,7 +159,7 @@
     attrs.failIfMajorPerformanceCaveat = m_failIfMajorPerformanceCaveat;
 
     attrs.noExtensions = true;
-    attrs.shareResources = true;
+    attrs.shareResources = false;
     attrs.preferDiscreteGPU = true;
 
     attrs.topDocumentURL = topDocumentURL;
diff --git a/Source/core/html/canvas/WebGLRenderingContext.cpp b/Source/core/html/canvas/WebGLRenderingContext.cpp
index 619a418..02e36e9 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -80,7 +80,7 @@
         attrs = defaultAttrs.get();
     }
     blink::WebGraphicsContext3D::Attributes attributes = attrs->attributes(document.topDocument().url().string(), settings);
-    OwnPtr<blink::WebGraphicsContext3D> context = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(attributes));
+    OwnPtr<blink::WebGraphicsContext3D> context = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(attributes, 0));
     if (!context || !context->makeContextCurrent()) {
         canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Could not create a WebGL context."));
         return nullptr;
diff --git a/Source/core/html/canvas/WebGLRenderingContextBase.cpp b/Source/core/html/canvas/WebGLRenderingContextBase.cpp
index 7a058de..3c70156 100644
--- a/Source/core/html/canvas/WebGLRenderingContextBase.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContextBase.cpp
@@ -455,6 +455,22 @@
     }
 } // namespace anonymous
 
+class ScopedTexture2DRestorer {
+public:
+    ScopedTexture2DRestorer(WebGLRenderingContextBase* context)
+        : m_context(context)
+    {
+    }
+
+    ~ScopedTexture2DRestorer()
+    {
+        m_context->restoreCurrentTexture2D();
+    }
+
+private:
+    WebGLRenderingContextBase* m_context;
+};
+
 class WebGLRenderingContextLostCallback : public blink::WebGraphicsContext3D::WebGraphicsContextLostCallback {
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -831,6 +847,8 @@
     canvas()->clearCopiedImage();
     m_markedCanvasDirty = false;
 
+    ScopedTexture2DRestorer restorer(this);
+
     m_drawingBuffer->commit();
     if (!(canvas()->buffer())->copyRenderingResultsFromDrawingBuffer(m_drawingBuffer.get())) {
         canvas()->ensureUnacceleratedImageBuffer();
@@ -3406,9 +3424,12 @@
         return;
 
     WebGLTexture* texture = validateTextureBinding("texImage2D", target, true);
+
     // If possible, copy from the canvas element directly to the texture
     // via the GPU, without a read-back to system memory.
     if (GL_TEXTURE_2D == target && texture) {
+        ScopedTexture2DRestorer restorer(this);
+
         if (!canvas->is3D()) {
             ImageBuffer* buffer = canvas->buffer();
             if (buffer && buffer->copyToPlatformTexture(m_context.get(), texture->object(), internalformat, type,
@@ -3418,6 +3439,7 @@
             }
         } else {
             WebGLRenderingContextBase* gl = toWebGLRenderingContextBase(canvas->renderingContext());
+            ScopedTexture2DRestorer restorer(gl);
             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);
@@ -5338,7 +5360,7 @@
         return;
 
     blink::WebGraphicsContext3D::Attributes attributes = m_requestedAttributes->attributes(canvas()->document().topDocument().url().string(), settings);
-    OwnPtr<blink::WebGraphicsContext3D> context = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(attributes));
+    OwnPtr<blink::WebGraphicsContext3D> context = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(attributes, 0));
     if (!context) {
         if (m_contextLostMode == RealLostContext) {
             m_restoreTimer.startOneShot(secondsBetweenRestoreAttempts, FROM_HERE);
diff --git a/Source/core/html/canvas/WebGLRenderingContextBase.h b/Source/core/html/canvas/WebGLRenderingContextBase.h
index 41b1d69..3914fc5 100644
--- a/Source/core/html/canvas/WebGLRenderingContextBase.h
+++ b/Source/core/html/canvas/WebGLRenderingContextBase.h
@@ -356,6 +356,7 @@
     friend class WebGLCompressedTextureS3TC;
     friend class WebGLRenderingContextErrorMessageCallback;
     friend class WebGLVertexArrayObjectOES;
+    friend class ScopedTexture2DRestorer;
 
     WebGLRenderingContextBase(HTMLCanvasElement*, PassOwnPtr<blink::WebGraphicsContext3D>, WebGLContextAttributes*);
     void initializeNewContext();
diff --git a/Source/core/html/forms/ImageInputType.cpp b/Source/core/html/forms/ImageInputType.cpp
index a8a8d51..7c0d195 100644
--- a/Source/core/html/forms/ImageInputType.cpp
+++ b/Source/core/html/forms/ImageInputType.cpp
@@ -235,4 +235,14 @@
     return box ? adjustForAbsoluteZoom(box->contentWidth(), box) : 0;
 }
 
+bool ImageInputType::hasLegalLinkAttribute(const QualifiedName& name) const
+{
+    return name == srcAttr || BaseButtonInputType::hasLegalLinkAttribute(name);
+}
+
+const QualifiedName& ImageInputType::subResourceAttributeName() const
+{
+    return srcAttr;
+}
+
 } // namespace WebCore
diff --git a/Source/core/html/forms/ImageInputType.h b/Source/core/html/forms/ImageInputType.h
index c871974..d3a1ffa 100644
--- a/Source/core/html/forms/ImageInputType.h
+++ b/Source/core/html/forms/ImageInputType.h
@@ -61,6 +61,8 @@
     virtual bool shouldRespectHeightAndWidthAttributes() OVERRIDE;
     virtual unsigned height() const OVERRIDE;
     virtual unsigned width() const OVERRIDE;
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const OVERRIDE;
+    virtual const QualifiedName& subResourceAttributeName() const OVERRIDE;
 
     IntPoint m_clickLocation; // Valid only during HTMLFormElement::prepareForSubmission().
 };
diff --git a/Source/core/html/forms/InputType.cpp b/Source/core/html/forms/InputType.cpp
index 58dfc09..8e9c4d5 100644
--- a/Source/core/html/forms/InputType.cpp
+++ b/Source/core/html/forms/InputType.cpp
@@ -758,6 +758,16 @@
 {
 }
 
+bool InputType::hasLegalLinkAttribute(const QualifiedName&) const
+{
+    return false;
+}
+
+const QualifiedName& InputType::subResourceAttributeName() const
+{
+    return nullQName();
+}
+
 bool InputType::supportsIndeterminateAppearance() const
 {
     return false;
diff --git a/Source/core/html/forms/InputType.h b/Source/core/html/forms/InputType.h
index e636319..88a9f0a 100644
--- a/Source/core/html/forms/InputType.h
+++ b/Source/core/html/forms/InputType.h
@@ -191,6 +191,8 @@
     virtual String defaultToolTip() const;
     virtual Decimal findClosestTickMarkValue(const Decimal&);
     virtual void handleDOMActivateEvent(Event*);
+    virtual bool hasLegalLinkAttribute(const QualifiedName&) const;
+    virtual const QualifiedName& subResourceAttributeName() const;
 
     // Parses the specified string for the type, and return
     // the Decimal value for the parsing result if the parsing
diff --git a/Source/core/html/imports/HTMLImportsController.cpp b/Source/core/html/imports/HTMLImportsController.cpp
index b7d0f26..5120efa 100644
--- a/Source/core/html/imports/HTMLImportsController.cpp
+++ b/Source/core/html/imports/HTMLImportsController.cpp
@@ -148,7 +148,7 @@
 
 bool HTMLImportsController::isDone() const
 {
-    return !m_master->parsing();
+    return !m_master->parsing() && m_master->haveStylesheetsLoaded();
 }
 
 void HTMLImportsController::stateDidChange()
diff --git a/Source/core/html/parser/HTMLConstructionSite.cpp b/Source/core/html/parser/HTMLConstructionSite.cpp
index 79feebf..e5e2efe 100644
--- a/Source/core/html/parser/HTMLConstructionSite.cpp
+++ b/Source/core/html/parser/HTMLConstructionSite.cpp
@@ -38,6 +38,7 @@
 #include "core/frame/LocalFrame.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLHtmlElement.h"
+#include "core/html/HTMLPlugInElement.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/HTMLTemplateElement.h"
 #include "core/html/parser/AtomicHTMLToken.h"
@@ -274,7 +275,7 @@
 void HTMLConstructionSite::attachLater(ContainerNode* parent, PassRefPtr<Node> prpChild, bool selfClosing)
 {
     ASSERT(scriptingContentIsAllowed(m_parserContentPolicy) || !prpChild.get()->isElementNode() || !toScriptLoaderIfPossible(toElement(prpChild.get())));
-    ASSERT(pluginContentIsAllowed(m_parserContentPolicy) || !prpChild->isPluginElement());
+    ASSERT(pluginContentIsAllowed(m_parserContentPolicy) || !isHTMLPlugInElement(prpChild));
 
     HTMLConstructionSiteTask task(HTMLConstructionSiteTask::Insert);
     task.parent = parent;
diff --git a/Source/core/html/parser/HTMLEntityParser.cpp b/Source/core/html/parser/HTMLEntityParser.cpp
index 7c1cdde..9866313 100644
--- a/Source/core/html/parser/HTMLEntityParser.cpp
+++ b/Source/core/html/parser/HTMLEntityParser.cpp
@@ -115,7 +115,7 @@
     }
     notEnoughCharacters = source.isEmpty();
     if (notEnoughCharacters) {
-        // We can't an entity because there might be a longer entity
+        // We can't decide on an entity because there might be a longer entity
         // that we could match if we had more data.
         unconsumeCharacters(source, consumedCharacters);
         return false;
@@ -130,11 +130,12 @@
         // actual entity.
         unconsumeCharacters(source, consumedCharacters);
         consumedCharacters.clear();
-        const int length = entitySearch.mostRecentMatch()->length;
-        const LChar* reference = entitySearch.mostRecentMatch()->entity;
+        const HTMLEntityTableEntry* mostRecent = entitySearch.mostRecentMatch();
+        const int length = mostRecent->length;
+        const LChar* reference = HTMLEntityTable::entityString(*mostRecent);
         for (int i = 0; i < length; ++i) {
             cc = source.currentChar();
-            ASSERT_UNUSED(reference, cc == *reference++);
+            ASSERT_UNUSED(reference, cc == static_cast<UChar>(*reference++));
             consumedCharacters.append(cc);
             source.advanceAndASSERT(cc);
             ASSERT(!source.isEmpty());
diff --git a/Source/core/html/parser/HTMLEntitySearch.cpp b/Source/core/html/parser/HTMLEntitySearch.cpp
index c4ef2b0..fe847e4 100644
--- a/Source/core/html/parser/HTMLEntitySearch.cpp
+++ b/Source/core/html/parser/HTMLEntitySearch.cpp
@@ -47,7 +47,8 @@
 {
     if (entry->length < m_currentLength + 1)
         return Before;
-    UChar entryNextCharacter = entry->entity[m_currentLength];
+    const LChar* entityString = HTMLEntityTable::entityString(*entry);
+    UChar entryNextCharacter = entityString[m_currentLength];
     if (entryNextCharacter == nextCharacter)
         return Prefix;
     return entryNextCharacter < nextCharacter ? Before : After;
diff --git a/Source/core/html/parser/HTMLEntityTable.h b/Source/core/html/parser/HTMLEntityTable.h
index b5cd6c4..1e46504 100644
--- a/Source/core/html/parser/HTMLEntityTable.h
+++ b/Source/core/html/parser/HTMLEntityTable.h
@@ -30,13 +30,14 @@
 
 namespace WebCore {
 
+// Member order to optimize packing. There will be thousands of these objects.
 struct HTMLEntityTableEntry {
-    LChar lastCharacter() const { return entity[length - 1]; }
+    LChar lastCharacter() const;
 
-    const LChar* entity;
-    int length;
     UChar32 firstValue;
-    UChar32 secondValue;
+    UChar secondValue; // UChar since double char sequences only use BMP chars.
+    short entityOffset;
+    short length;
 };
 
 class HTMLEntityTable {
@@ -46,6 +47,8 @@
 
     static const HTMLEntityTableEntry* firstEntryStartingWith(UChar);
     static const HTMLEntityTableEntry* lastEntryStartingWith(UChar);
+
+    static const LChar* entityString(const HTMLEntityTableEntry&);
 };
 
 }
diff --git a/Source/core/html/parser/HTMLScriptRunner.cpp b/Source/core/html/parser/HTMLScriptRunner.cpp
index c16d06a..3e3a7d0 100644
--- a/Source/core/html/parser/HTMLScriptRunner.cpp
+++ b/Source/core/html/parser/HTMLScriptRunner.cpp
@@ -125,8 +125,12 @@
     if (pendingScript.resource() && pendingScript.watchingForLoad())
         stopWatchingForLoad(pendingScript);
 
-    if (!isExecutingScript())
+    if (!isExecutingScript()) {
         Microtask::performCheckpoint();
+        m_hasScriptsWaitingForResources = !m_document->haveStylesheetsAndImportsLoaded();
+        if (m_hasScriptsWaitingForResources)
+            return;
+    }
 
     // Clear the pending script before possible rentrancy from executeScript()
     RefPtr<Element> element = pendingScript.releaseElementAndClear();
diff --git a/Source/core/html/parser/HTMLToken.h b/Source/core/html/parser/HTMLToken.h
index 64f3044..01592a5 100644
--- a/Source/core/html/parser/HTMLToken.h
+++ b/Source/core/html/parser/HTMLToken.h
@@ -27,7 +27,6 @@
 #define HTMLToken_h
 
 #include "core/dom/Attribute.h"
-#include "core/html/parser/HTMLToken.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/html/parser/create-html-entity-table b/Source/core/html/parser/create-html-entity-table
index 3b9ca45..587e8a8 100755
--- a/Source/core/html/parser/create-html-entity-table
+++ b/Source/core/html/parser/create-html-entity-table
@@ -27,6 +27,11 @@
 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
+"""This python script creates the raw data that is our entity
+database. The representation is one string database containing all
+strings we could need, and then a mapping from offset+length -> entity
+data. That is compact, easy to use and efficient."""
+
 import csv
 import os.path
 import string
@@ -35,13 +40,6 @@
 ENTITY = 0
 VALUE = 1
 
-def convert_entity_to_cpp_name(entity):
-    postfix = "EntityName"
-    if entity[-1] == ";":
-        return "%sSemicolon%s" % (entity[:-1], postfix)
-    return "%s%s" % (entity, postfix)
-
-
 def convert_value_to_int(value):
     if not value:
         return "0";
@@ -63,9 +61,8 @@
 output_path = sys.argv[2]
 input_path = sys.argv[3]
 
-html_entity_names_file = open(input_path)
-entries = list(csv.reader(html_entity_names_file))
-html_entity_names_file.close()
+with open(input_path) as html_entity_names_file:
+    entries = list(csv.reader(html_entity_names_file))
 
 entries.sort(key = lambda entry: entry[ENTITY])
 entity_count = len(entries)
@@ -97,7 +94,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-// THIS FILE IS GENERATED BY WebCore/html/parser/create-html-entity-table
+// THIS FILE IS GENERATED BY core/html/parser/create-html-entity-table
 // DO NOT EDIT (unless you are a ninja)!
 
 #include "config.h"
@@ -108,60 +105,126 @@
 namespace {
 """)
 
+assert len(entries) > 0, "Code assumes a non-empty entity array."
+def check_ascii(entity_string):
+    for c in entity_string:
+        code = ord(c)
+        assert 0 <= code <= 127, (c + " is not ASCII. Need to change type " +
+                                  "of storage from LChar to UChar to support " +
+                                  "this entity.")
+
+output_file.write("static const LChar staticEntityStringStorage[] = {\n")
+output_file.write("'")
+all_data = ""
+entity_offset = 0
+first_output = True
+saved_by_reusing = 0
 for entry in entries:
-    output_file.write("static const LChar %s[] = \"%s\";\n" % (convert_entity_to_cpp_name(entry[ENTITY]), entry[ENTITY]))
+    check_ascii(entry[ENTITY])
+    # Reuse substrings from earlier entries. This saves 1-2000
+    # characters, but it's O(n^2) and not very smart. The optimal
+    # solution has to solve the "Shortest Common Superstring" problem
+    # and that is NP-Complete or worse.
+    #
+    # This would be even more efficient if we didn't store the
+    # semi-colon in the array but as a bit in the entry.
+    entity = entry[ENTITY]
+    already_existing_offset = all_data.find(entity)
+    if already_existing_offset != -1:
+        # Reusing space.
+        this_offset = already_existing_offset
+        saved_by_reusing += len(entity)
+    else:
+        if not first_output:
+            output_file.write(",\n'")
+        first_output = False
+
+        # Try the end of the string and see if we can reuse that to
+        # fit the start of the new entity.
+        data_to_add = entity
+        this_offset = entity_offset
+        for truncated_len in range(len(entity) - 1, 0, -1):
+            if all_data.endswith(entity[:truncated_len]):
+                data_to_add = entity[truncated_len:]
+                this_offset = entity_offset - truncated_len
+                saved_by_reusing += truncated_len
+                break
+
+        output_file.write("', '".join(data_to_add))
+        all_data += data_to_add
+        output_file.write("'")
+        entity_offset += len(data_to_add)
+    assert len(entry) == 2, "We will use slot [2] in the list for the offset."
+    assert this_offset < 32768 # Stored in a 16 bit short.
+    entry.append(this_offset)
+
+output_file.write("};\n")
+
+index = {}
+for offset, entry in enumerate(entries):
+    starting_letter = entry[ENTITY][0]
+    if starting_letter not in index:
+        index[starting_letter] = offset
 
 output_file.write("""
 static const HTMLEntityTableEntry staticEntityTable[%s] = {\n""" % entity_count)
 
-index = {}
-offset = 0
 for entry in entries:
-    letter = entry[ENTITY][0]
-    if letter not in index:
-        index[letter] = offset
     values = entry[VALUE].split(' ')
     assert len(values) <= 2, values
-    output_file.write('    { %s, %s, %s, %s },\n' % (
-        convert_entity_to_cpp_name(entry[ENTITY]),
-        len(entry[ENTITY]),
+    output_file.write('    { %s, %s, %s, %s }, // &%s\n' % (
         convert_value_to_int(values[0]),
-        convert_value_to_int(values[1] if len(values) >= 2 else "")))
-    offset += 1
+        convert_value_to_int(values[1] if len(values) >= 2 else ""),
+        entry[2],
+        len(entry[ENTITY]),
+        entry[ENTITY],
+        ))
 
 output_file.write("""};
 
 """)
 
-output_file.write("static const HTMLEntityTableEntry* uppercaseOffset[] = {\n")
+output_file.write("""
+}
+""")
+
+output_file.write("static const short uppercaseOffset[] = {\n")
 for letter in string.ascii_uppercase:
-    output_file.write("%s\n" % offset_table_entry(index[letter]))
-output_file.write("%s\n" % offset_table_entry(index['a']))
+    output_file.write("%d,\n" % index[letter])
+output_file.write("%d\n" % index['a'])
 output_file.write("""};
 
-static const HTMLEntityTableEntry* lowercaseOffset[] = {\n""")
+static const short lowercaseOffset[] = {\n""")
 for letter in string.ascii_lowercase:
-    output_file.write("%s\n" % offset_table_entry(index[letter]))
-output_file.write("%s\n" % offset_table_entry(entity_count))
+    output_file.write("%d,\n" % index[letter])
+output_file.write("%d\n" % entity_count)
 output_file.write("""};
 
+const LChar* HTMLEntityTable::entityString(const HTMLEntityTableEntry& entry)
+{
+    return staticEntityStringStorage + entry.entityOffset;
+}
+
+LChar HTMLEntityTableEntry::lastCharacter() const
+{
+    return HTMLEntityTable::entityString(*this)[length - 1];
 }
 
 const HTMLEntityTableEntry* HTMLEntityTable::firstEntryStartingWith(UChar c)
 {
     if (c >= 'A' && c <= 'Z')
-        return uppercaseOffset[c - 'A'];
+        return &staticEntityTable[uppercaseOffset[c - 'A']];
     if (c >= 'a' && c <= 'z')
-        return lowercaseOffset[c - 'a'];
+        return &staticEntityTable[lowercaseOffset[c - 'a']];
     return 0;
 }
 
 const HTMLEntityTableEntry* HTMLEntityTable::lastEntryStartingWith(UChar c)
 {
     if (c >= 'A' && c <= 'Z')
-        return uppercaseOffset[c - 'A' + 1] - 1;
+        return &staticEntityTable[uppercaseOffset[c - 'A' + 1]] - 1;
     if (c >= 'a' && c <= 'z')
-        return lowercaseOffset[c - 'a' + 1] - 1;
+        return &staticEntityTable[lowercaseOffset[c - 'a' + 1]] - 1;
     return 0;
 }
 
diff --git a/Source/core/html/shadow/MediaControlElements.cpp b/Source/core/html/shadow/MediaControlElements.cpp
index 5e04376..e07cb3f 100644
--- a/Source/core/html/shadow/MediaControlElements.cpp
+++ b/Source/core/html/shadow/MediaControlElements.cpp
@@ -38,7 +38,6 @@
 #include "core/events/MouseEvent.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/frame/LocalFrame.h"
-#include "core/frame/Settings.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/shadow/MediaControls.h"
 #include "core/html/track/TextTrack.h"
@@ -61,8 +60,6 @@
 
 MediaControlPanelElement::MediaControlPanelElement(MediaControls& mediaControls)
     : MediaControlDivElement(mediaControls, MediaControlsPanel)
-    , m_canBeDragged(false)
-    , m_isBeingDragged(false)
     , m_isDisplayed(false)
     , m_opaque(true)
     , m_transitionTimer(this, &MediaControlPanelElement::transitionTimerFired)
@@ -80,54 +77,6 @@
     return id;
 }
 
-void MediaControlPanelElement::startDrag(const LayoutPoint& eventLocation)
-{
-    if (!m_canBeDragged)
-        return;
-
-    if (m_isBeingDragged)
-        return;
-
-    RenderObject* renderer = this->renderer();
-    if (!renderer || !renderer->isBox())
-        return;
-
-    LocalFrame* frame = document().frame();
-    if (!frame)
-        return;
-
-    m_lastDragEventLocation = eventLocation;
-
-    frame->eventHandler().setCapturingMouseEventsNode(this);
-
-    m_isBeingDragged = true;
-}
-
-void MediaControlPanelElement::continueDrag(const LayoutPoint& eventLocation)
-{
-    if (!m_isBeingDragged)
-        return;
-
-    LayoutSize distanceDragged = eventLocation - m_lastDragEventLocation;
-    m_cumulativeDragOffset.move(distanceDragged);
-    m_lastDragEventLocation = eventLocation;
-    setPosition(m_cumulativeDragOffset);
-}
-
-void MediaControlPanelElement::endDrag()
-{
-    if (!m_isBeingDragged)
-        return;
-
-    m_isBeingDragged = false;
-
-    LocalFrame* frame = document().frame();
-    if (!frame)
-        return;
-
-    frame->eventHandler().setCapturingMouseEventsNode(nullptr);
-}
-
 void MediaControlPanelElement::startTimer()
 {
     stopTimer();
@@ -153,35 +102,6 @@
     stopTimer();
 }
 
-void MediaControlPanelElement::setPosition(const LayoutPoint& position)
-{
-    // FIXME: Do we really want to up-convert these to doubles and not round? crbug.com/350474
-    double left = position.x().toFloat();
-    double top = position.y().toFloat();
-
-    // Set the left and top to control the panel's position; this depends on it being absolute positioned.
-    // Set the margin to zero since the position passed in will already include the effect of the margin.
-    setInlineStyleProperty(CSSPropertyLeft, left, CSSPrimitiveValue::CSS_PX);
-    setInlineStyleProperty(CSSPropertyTop, top, CSSPrimitiveValue::CSS_PX);
-    setInlineStyleProperty(CSSPropertyMarginLeft, 0.0, CSSPrimitiveValue::CSS_PX);
-    setInlineStyleProperty(CSSPropertyMarginTop, 0.0, CSSPrimitiveValue::CSS_PX);
-
-    classList().add("dragged", IGNORE_EXCEPTION);
-}
-
-void MediaControlPanelElement::resetPosition()
-{
-    removeInlineStyleProperty(CSSPropertyLeft);
-    removeInlineStyleProperty(CSSPropertyTop);
-    removeInlineStyleProperty(CSSPropertyMarginLeft);
-    removeInlineStyleProperty(CSSPropertyMarginTop);
-
-    classList().remove("dragged", IGNORE_EXCEPTION);
-
-    m_cumulativeDragOffset.setX(0);
-    m_cumulativeDragOffset.setY(0);
-}
-
 void MediaControlPanelElement::makeOpaque()
 {
     if (m_opaque)
@@ -210,36 +130,6 @@
     startTimer();
 }
 
-void MediaControlPanelElement::defaultEventHandler(Event* event)
-{
-    MediaControlDivElement::defaultEventHandler(event);
-
-    if (event->isMouseEvent()) {
-        LayoutPoint location = toMouseEvent(event)->absoluteLocation();
-        if (event->type() == EventTypeNames::mousedown && event->target() == this) {
-            startDrag(location);
-            event->setDefaultHandled();
-        } else if (event->type() == EventTypeNames::mousemove && m_isBeingDragged)
-            continueDrag(location);
-        else if (event->type() == EventTypeNames::mouseup && m_isBeingDragged) {
-            continueDrag(location);
-            endDrag();
-            event->setDefaultHandled();
-        }
-    }
-}
-
-void MediaControlPanelElement::setCanBeDragged(bool canBeDragged)
-{
-    if (m_canBeDragged == canBeDragged)
-        return;
-
-    m_canBeDragged = canBeDragged;
-
-    if (!canBeDragged)
-        endDrag();
-}
-
 void MediaControlPanelElement::setIsDisplayed(bool isDisplayed)
 {
     m_isDisplayed = isDisplayed;
@@ -416,7 +306,7 @@
 
 void MediaControlToggleClosedCaptionsButtonElement::updateDisplayType()
 {
-    bool captionsVisible = mediaControllerInterface().closedCaptionsVisible();
+    bool captionsVisible = mediaElement().closedCaptionsVisible();
     setDisplayType(captionsVisible ? MediaHideClosedCaptionsButton : MediaShowClosedCaptionsButton);
     setChecked(captionsVisible);
 }
@@ -424,8 +314,8 @@
 void MediaControlToggleClosedCaptionsButtonElement::defaultEventHandler(Event* event)
 {
     if (event->type() == EventTypeNames::click) {
-        mediaControllerInterface().setClosedCaptionsVisible(!mediaControllerInterface().closedCaptionsVisible());
-        setChecked(mediaControllerInterface().closedCaptionsVisible());
+        mediaElement().setClosedCaptionsVisible(!mediaElement().closedCaptionsVisible());
+        setChecked(mediaElement().closedCaptionsVisible());
         updateDisplayType();
         event->setDefaultHandled();
     }
@@ -588,19 +478,10 @@
 void MediaControlFullscreenButtonElement::defaultEventHandler(Event* event)
 {
     if (event->type() == EventTypeNames::click) {
-        // Only use the new full screen API if the fullScreenEnabled setting has
-        // been explicitly enabled. Otherwise, use the old fullscreen API. This
-        // allows apps which embed a WebView to retain the existing full screen
-        // video implementation without requiring them to implement their own full
-        // screen behavior.
-        if (document().settings() && document().settings()->fullScreenEnabled()) {
-            if (FullscreenElementStack::isActiveFullScreenElement(&mediaElement()))
-                FullscreenElementStack::from(document()).webkitCancelFullScreen();
-            else
-                FullscreenElementStack::from(document()).requestFullScreenForElement(&mediaElement(), 0, FullscreenElementStack::ExemptIFrameAllowFullScreenRequirement);
-        } else {
-            mediaControllerInterface().enterFullscreen();
-        }
+        if (FullscreenElementStack::isActiveFullScreenElement(&mediaElement()))
+            FullscreenElementStack::from(document()).webkitCancelFullScreen();
+        else
+            FullscreenElementStack::from(document()).requestFullScreenForElement(&mediaElement(), 0, FullscreenElementStack::ExemptIFrameAllowFullScreenRequirement);
         event->setDefaultHandled();
     }
     HTMLInputElement::defaultEventHandler(event);
@@ -696,7 +577,7 @@
 
 void MediaControlTextTrackContainerElement::updateDisplay()
 {
-    if (!mediaControllerInterface().closedCaptionsVisible()) {
+    if (!mediaElement().closedCaptionsVisible()) {
         removeChildren();
         return;
     }
@@ -704,7 +585,7 @@
     // 1. If the media element is an audio element, or is another playback
     // mechanism with no rendering area, abort these steps. There is nothing to
     // render.
-    if (!mediaElement().isVideo())
+    if (isHTMLAudioElement(mediaElement()))
         return;
 
     // 2. Let video be the media element or other playback mechanism.
diff --git a/Source/core/html/shadow/MediaControlElements.h b/Source/core/html/shadow/MediaControlElements.h
index 4b1a3fd..9194097 100644
--- a/Source/core/html/shadow/MediaControlElements.h
+++ b/Source/core/html/shadow/MediaControlElements.h
@@ -40,38 +40,22 @@
 public:
     static PassRefPtr<MediaControlPanelElement> create(MediaControls&);
 
-    void setCanBeDragged(bool);
     void setIsDisplayed(bool);
 
-    void resetPosition();
     void makeOpaque();
     void makeTransparent();
 
-    virtual bool willRespondToMouseMoveEvents() OVERRIDE { return true; }
-    virtual bool willRespondToMouseClickEvents() OVERRIDE { return true; }
-
 private:
     explicit MediaControlPanelElement(MediaControls&);
 
     virtual const AtomicString& shadowPseudoId() const OVERRIDE;
-    virtual void defaultEventHandler(Event*) OVERRIDE;
-
-    void startDrag(const LayoutPoint& eventLocation);
-    void continueDrag(const LayoutPoint& eventLocation);
-    void endDrag();
 
     void startTimer();
     void stopTimer();
     void transitionTimerFired(Timer<MediaControlPanelElement>*);
 
-    void setPosition(const LayoutPoint&);
-
-    bool m_canBeDragged;
-    bool m_isBeingDragged;
     bool m_isDisplayed;
     bool m_opaque;
-    LayoutPoint m_lastDragEventLocation;
-    LayoutPoint m_cumulativeDragOffset;
 
     Timer<MediaControlPanelElement> m_transitionTimer;
 };
diff --git a/Source/core/html/shadow/MediaControls.cpp b/Source/core/html/shadow/MediaControls.cpp
index 2af3e93..59d1a76 100644
--- a/Source/core/html/shadow/MediaControls.cpp
+++ b/Source/core/html/shadow/MediaControls.cpp
@@ -29,6 +29,7 @@
 
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/events/MouseEvent.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLMediaElement.h"
 #include "core/html/MediaController.h"
 #include "core/rendering/RenderTheme.h"
@@ -191,7 +192,7 @@
 
     refreshClosedCaptionsButtonVisibility();
 
-    if (mediaControllerInterface().hasVideo())
+    if (mediaElement().hasVideo() && document().settings() && document().settings()->fullScreenEnabled())
         m_fullScreenButton->show();
     else
         m_fullScreenButton->hide();
@@ -247,7 +248,7 @@
     m_timeline->setPosition(mediaControllerInterface().currentTime());
     updateCurrentTimeDisplay();
 
-    if (!m_isMouseOverControls && mediaControllerInterface().hasVideo())
+    if (!m_isMouseOverControls && mediaElement().hasVideo())
         makeTransparent();
 }
 
@@ -303,7 +304,7 @@
 
 void MediaControls::refreshClosedCaptionsButtonVisibility()
 {
-    if (mediaControllerInterface().hasClosedCaptions())
+    if (mediaElement().hasClosedCaptions())
         m_toggleClosedCaptionsButton->show();
     else
         m_toggleClosedCaptionsButton->hide();
diff --git a/Source/core/inspector/InspectorBaseAgent.cpp b/Source/core/inspector/InspectorBaseAgent.cpp
index 5d93086..e1b4e8a 100644
--- a/Source/core/inspector/InspectorBaseAgent.cpp
+++ b/Source/core/inspector/InspectorBaseAgent.cpp
@@ -94,5 +94,11 @@
         m_agents[i]->discardAgent();
 }
 
+void InspectorAgentRegistry::flushPendingFrontendMessages()
+{
+    for (size_t i = 0; i < m_agents.size(); i++)
+        m_agents[i]->flushPendingFrontendMessages();
+}
+
 } // namespace WebCore
 
diff --git a/Source/core/inspector/InspectorBaseAgent.h b/Source/core/inspector/InspectorBaseAgent.h
index af1c670..eae8210 100644
--- a/Source/core/inspector/InspectorBaseAgent.h
+++ b/Source/core/inspector/InspectorBaseAgent.h
@@ -55,6 +55,7 @@
     virtual void registerInDispatcher(InspectorBackendDispatcher*) = 0;
     virtual void discardAgent() { }
     virtual void didCommitLoadForMainFrame() { }
+    virtual void flushPendingFrontendMessages() { }
 
     String name() { return m_name; }
     void appended(InstrumentingAgents*, InspectorState*);
@@ -77,6 +78,7 @@
     void restore();
     void registerInDispatcher(InspectorBackendDispatcher*);
     void discardAgents();
+    void flushPendingFrontendMessages();
 
 private:
     InstrumentingAgents* m_instrumentingAgents;
diff --git a/Source/core/inspector/InspectorCSSAgent.cpp b/Source/core/inspector/InspectorCSSAgent.cpp
index 82645d6..69aa436 100644
--- a/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/Source/core/inspector/InspectorCSSAgent.cpp
@@ -121,14 +121,10 @@
 class InspectorCSSAgent::StyleSheetAction : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(StyleSheetAction);
 public:
-    StyleSheetAction(const String& name, InspectorStyleSheet* styleSheet)
+    StyleSheetAction(const String& name)
         : InspectorHistory::Action(name)
-        , m_styleSheet(styleSheet)
     {
     }
-
-protected:
-    RefPtr<InspectorStyleSheet> m_styleSheet;
 };
 
 class InspectorCSSAgent::EnableResourceClient FINAL : public StyleSheetResourceClient {
@@ -175,8 +171,9 @@
 class InspectorCSSAgent::SetStyleSheetTextAction FINAL : public InspectorCSSAgent::StyleSheetAction {
     WTF_MAKE_NONCOPYABLE(SetStyleSheetTextAction);
 public:
-    SetStyleSheetTextAction(InspectorStyleSheet* styleSheet, const String& text)
-        : InspectorCSSAgent::StyleSheetAction("SetStyleSheetText", styleSheet)
+    SetStyleSheetTextAction(InspectorStyleSheetBase* styleSheet, const String& text)
+        : InspectorCSSAgent::StyleSheetAction("SetStyleSheetText")
+        , m_styleSheet(styleSheet)
         , m_text(text)
     {
     }
@@ -190,20 +187,12 @@
 
     virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
-        if (m_styleSheet->setText(m_oldText, exceptionState)) {
-            m_styleSheet->reparseStyleSheet(m_oldText);
-            return true;
-        }
-        return false;
+        return m_styleSheet->setText(m_oldText, exceptionState);
     }
 
     virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
-        if (m_styleSheet->setText(m_text, exceptionState)) {
-            m_styleSheet->reparseStyleSheet(m_text);
-            return true;
-        }
-        return false;
+        return m_styleSheet->setText(m_text, exceptionState);
     }
 
     virtual String mergeId() OVERRIDE
@@ -220,6 +209,7 @@
     }
 
 private:
+    RefPtr<InspectorStyleSheetBase> m_styleSheet;
     String m_text;
     String m_oldText;
 };
@@ -227,8 +217,9 @@
 class InspectorCSSAgent::SetPropertyTextAction FINAL : public InspectorCSSAgent::StyleSheetAction {
     WTF_MAKE_NONCOPYABLE(SetPropertyTextAction);
 public:
-    SetPropertyTextAction(InspectorStyleSheet* styleSheet, const InspectorCSSId& cssId, unsigned propertyIndex, const String& text, bool overwrite)
-        : InspectorCSSAgent::StyleSheetAction("SetPropertyText", styleSheet)
+    SetPropertyTextAction(InspectorStyleSheetBase* styleSheet, const InspectorCSSId& cssId, unsigned propertyIndex, const String& text, bool overwrite)
+        : InspectorCSSAgent::StyleSheetAction("SetPropertyText")
+        , m_styleSheet(styleSheet)
         , m_cssId(cssId)
         , m_propertyIndex(propertyIndex)
         , m_text(text)
@@ -274,6 +265,7 @@
     }
 
 private:
+    RefPtr<InspectorStyleSheetBase> m_styleSheet;
     InspectorCSSId m_cssId;
     unsigned m_propertyIndex;
     String m_text;
@@ -285,7 +277,8 @@
     WTF_MAKE_NONCOPYABLE(SetRuleSelectorAction);
 public:
     SetRuleSelectorAction(InspectorStyleSheet* styleSheet, const InspectorCSSId& cssId, const String& selector)
-        : InspectorCSSAgent::StyleSheetAction("SetRuleSelector", styleSheet)
+        : InspectorCSSAgent::StyleSheetAction("SetRuleSelector")
+        , m_styleSheet(styleSheet)
         , m_cssId(cssId)
         , m_selector(selector)
     {
@@ -310,6 +303,7 @@
     }
 
 private:
+    RefPtr<InspectorStyleSheet> m_styleSheet;
     InspectorCSSId m_cssId;
     String m_selector;
     String m_oldSelector;
@@ -319,7 +313,8 @@
     WTF_MAKE_NONCOPYABLE(AddRuleAction);
 public:
     AddRuleAction(InspectorStyleSheet* styleSheet, const String& selector)
-        : InspectorCSSAgent::StyleSheetAction("AddRule", styleSheet)
+        : InspectorCSSAgent::StyleSheetAction("AddRule")
+        , m_styleSheet(styleSheet)
         , m_selector(selector)
     {
     }
@@ -346,6 +341,7 @@
     InspectorCSSId newRuleId() { return m_newId; }
 
 private:
+    RefPtr<InspectorStyleSheet> m_styleSheet;
     InspectorCSSId m_newId;
     String m_selector;
     String m_oldSelector;
@@ -431,11 +427,23 @@
         wasEnabled(nullptr);
 }
 
+void InspectorCSSAgent::flushPendingFrontendMessages()
+{
+    if (!m_invalidatedDocuments.size())
+        return;
+    HashSet<Document*> invalidatedDocuments;
+    m_invalidatedDocuments.swap(&invalidatedDocuments);
+    for (HashSet<Document*>::iterator it = invalidatedDocuments.begin(); it != invalidatedDocuments.end(); ++it)
+        updateActiveStyleSheets(*it, ExistingFrontendRefresh);
+}
+
 void InspectorCSSAgent::reset()
 {
     m_idToInspectorStyleSheet.clear();
+    m_idToInspectorStyleSheetForInlineStyle.clear();
     m_cssStyleSheetToInspectorStyleSheet.clear();
-    m_frameToCSSStyleSheets.clear();
+    m_documentToCSSStyleSheets.clear();
+    m_invalidatedDocuments.clear();
     m_nodeToInspectorStyleSheet.clear();
     m_documentToViaInspectorStyleSheet.clear();
     resetNonPersistentData();
@@ -490,10 +498,8 @@
 
     m_instrumentingAgents->setInspectorCSSAgent(this);
     Vector<Document*> documents = m_domAgent->documents();
-    for (Vector<Document*>::iterator it = documents.begin(); it != documents.end(); ++it) {
-        Document* document = *it;
-        updateActiveStyleSheetsForDocument(document, InitialFrontendLoad);
-    }
+    for (Vector<Document*>::iterator it = documents.begin(); it != documents.end(); ++it)
+        updateActiveStyleSheets(*it, InitialFrontendLoad);
 
     if (callback)
         callback->sendSuccess();
@@ -505,20 +511,15 @@
     m_state->setBoolean(CSSAgentState::cssAgentEnabled, false);
 }
 
-void InspectorCSSAgent::didCommitLoad(LocalFrame* frame, DocumentLoader* loader)
+void InspectorCSSAgent::didCommitLoadForMainFrame()
 {
-    if (loader->frame() == frame->page()->mainFrame()) {
-        reset();
-        return;
-    }
-
-    updateActiveStyleSheets(frame, Vector<CSSStyleSheet*>(), ExistingFrontendRefresh);
+    reset();
 }
 
 void InspectorCSSAgent::mediaQueryResultChanged()
 {
-    if (m_frontend)
-        m_frontend->mediaQueryResultChanged();
+    flushPendingFrontendMessages();
+    m_frontend->mediaQueryResultChanged();
 }
 
 void InspectorCSSAgent::willMutateRules()
@@ -559,33 +560,30 @@
 {
     if (styleSheetEditInProgress())
         return;
-    updateActiveStyleSheetsForDocument(document, ExistingFrontendRefresh);
+    m_invalidatedDocuments.add(document);
+    if (m_creatingViaInspectorStyleSheet)
+        flushPendingFrontendMessages();
 }
 
-void InspectorCSSAgent::updateActiveStyleSheetsForDocument(Document* document, StyleSheetsUpdateType styleSheetsUpdateType)
+void InspectorCSSAgent::updateActiveStyleSheets(Document* document, StyleSheetsUpdateType styleSheetsUpdateType)
 {
-    LocalFrame* frame = document->frame();
-    if (!frame)
-        return;
     Vector<CSSStyleSheet*> newSheetsVector;
     collectAllDocumentStyleSheets(document, newSheetsVector);
-    updateActiveStyleSheets(frame, newSheetsVector, styleSheetsUpdateType);
+    setActiveStyleSheets(document, newSheetsVector, styleSheetsUpdateType);
 }
 
-void InspectorCSSAgent::updateActiveStyleSheets(LocalFrame* frame, const Vector<CSSStyleSheet*>& allSheetsVector, StyleSheetsUpdateType styleSheetsUpdateType)
+void InspectorCSSAgent::setActiveStyleSheets(Document* document, const Vector<CSSStyleSheet*>& allSheetsVector, StyleSheetsUpdateType styleSheetsUpdateType)
 {
     bool isInitialFrontendLoad = styleSheetsUpdateType == InitialFrontendLoad;
 
-    HashSet<CSSStyleSheet*>* frameCSSStyleSheets = m_frameToCSSStyleSheets.get(frame);
-    if (!frameCSSStyleSheets) {
-        frameCSSStyleSheets = new HashSet<CSSStyleSheet*>();
-        OwnPtr<HashSet<CSSStyleSheet*> > frameCSSStyleSheetsPtr = adoptPtr(frameCSSStyleSheets);
-        m_frameToCSSStyleSheets.set(frame, frameCSSStyleSheetsPtr.release());
+    HashSet<CSSStyleSheet*>* documentCSSStyleSheets = m_documentToCSSStyleSheets.get(document);
+    if (!documentCSSStyleSheets) {
+        documentCSSStyleSheets = new HashSet<CSSStyleSheet*>();
+        OwnPtr<HashSet<CSSStyleSheet*> > documentCSSStyleSheetsPtr = adoptPtr(documentCSSStyleSheets);
+        m_documentToCSSStyleSheets.set(document, documentCSSStyleSheetsPtr.release());
     }
 
-    HashSet<CSSStyleSheet*> removedSheets;
-    for (HashSet<CSSStyleSheet*>::iterator it = frameCSSStyleSheets->begin(); it != frameCSSStyleSheets->end(); ++it)
-        removedSheets.add(*it);
+    HashSet<CSSStyleSheet*> removedSheets(*documentCSSStyleSheets);
 
     HashSet<CSSStyleSheet*> addedSheets;
     for (Vector<CSSStyleSheet*>::const_iterator it = allSheetsVector.begin(); it != allSheetsVector.end(); ++it) {
@@ -604,9 +602,9 @@
         RefPtr<InspectorStyleSheet> inspectorStyleSheet = m_cssStyleSheetToInspectorStyleSheet.get(cssStyleSheet);
         ASSERT(inspectorStyleSheet);
 
+        documentCSSStyleSheets->remove(cssStyleSheet);
         if (m_idToInspectorStyleSheet.contains(inspectorStyleSheet->id())) {
             String id = unbindStyleSheet(inspectorStyleSheet.get());
-            frameCSSStyleSheets->remove(cssStyleSheet);
             if (m_frontend && !isInitialFrontendLoad)
                 m_frontend->styleSheetRemoved(id);
         }
@@ -617,19 +615,20 @@
         bool isNew = isInitialFrontendLoad || !m_cssStyleSheetToInspectorStyleSheet.contains(cssStyleSheet);
         if (isNew) {
             InspectorStyleSheet* newStyleSheet = bindStyleSheet(cssStyleSheet);
-            frameCSSStyleSheets->add(cssStyleSheet);
+            documentCSSStyleSheets->add(cssStyleSheet);
             if (m_frontend)
                 m_frontend->styleSheetAdded(newStyleSheet->buildObjectForStyleSheetInfo());
         }
     }
 
-    if (frameCSSStyleSheets->isEmpty())
-        m_frameToCSSStyleSheets.remove(frame);
+    if (documentCSSStyleSheets->isEmpty())
+        m_documentToCSSStyleSheets.remove(document);
 }
 
-void InspectorCSSAgent::frameDetachedFromParent(LocalFrame* frame)
+void InspectorCSSAgent::documentDetached(Document* document)
 {
-    updateActiveStyleSheets(frame, Vector<CSSStyleSheet*>(), ExistingFrontendRefresh);
+    m_invalidatedDocuments.remove(document);
+    setActiveStyleSheets(document, Vector<CSSStyleSheet*>(), ExistingFrontendRefresh);
 }
 
 bool InspectorCSSAgent::forcePseudoState(Element* element, CSSSelector::PseudoType pseudoType)
@@ -817,7 +816,7 @@
 
 void InspectorCSSAgent::getStyleSheetText(ErrorString* errorString, const String& styleSheetId, String* result)
 {
-    InspectorStyleSheet* inspectorStyleSheet = assertStyleSheetForId(errorString, styleSheetId);
+    InspectorStyleSheetBase* inspectorStyleSheet = assertStyleSheetForId(errorString, styleSheetId);
     if (!inspectorStyleSheet)
         return;
 
@@ -826,7 +825,7 @@
 
 void InspectorCSSAgent::setStyleSheetText(ErrorString* errorString, const String& styleSheetId, const String& text)
 {
-    InspectorStyleSheet* inspectorStyleSheet = assertStyleSheetForId(errorString, styleSheetId);
+    InspectorStyleSheetBase* inspectorStyleSheet = assertStyleSheetForId(errorString, styleSheetId);
     if (!inspectorStyleSheet) {
         *errorString = "Style sheet with id " + styleSheetId + " not found.";
         return;
@@ -842,7 +841,7 @@
     InspectorCSSId compoundId(fullStyleId);
     ASSERT(!compoundId.isEmpty());
 
-    InspectorStyleSheet* inspectorStyleSheet = assertStyleSheetForId(errorString, compoundId.styleSheetId());
+    InspectorStyleSheetBase* inspectorStyleSheet = assertStyleSheetForId(errorString, compoundId.styleSheetId());
     if (!inspectorStyleSheet)
         return;
 
@@ -858,7 +857,7 @@
     InspectorCSSId compoundId(fullRuleId);
     ASSERT(!compoundId.isEmpty());
 
-    InspectorStyleSheet* inspectorStyleSheet = assertStyleSheetForId(errorString, compoundId.styleSheetId());
+    InspectorStyleSheet* inspectorStyleSheet = assertInspectorStyleSheetForId(errorString, compoundId.styleSheetId());
     if (!inspectorStyleSheet)
         return;
 
@@ -892,12 +891,14 @@
         return;
     }
 
+    updateActiveStyleSheets(document, ExistingFrontendRefresh);
+
     *outStyleSheetId = inspectorStyleSheet->id();
 }
 
 void InspectorCSSAgent::addRule(ErrorString* errorString, const String& styleSheetId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result)
 {
-    InspectorStyleSheet* inspectorStyleSheet = assertStyleSheetForId(errorString, styleSheetId);
+    InspectorStyleSheet* inspectorStyleSheet = assertInspectorStyleSheetForId(errorString, styleSheetId);
     if (!inspectorStyleSheet)
         return;
 
@@ -1052,8 +1053,8 @@
         return 0;
 
     String newStyleSheetId = String::number(m_lastStyleSheetId++);
-    RefPtr<InspectorStyleSheetForInlineStyle> inspectorStyleSheet = InspectorStyleSheetForInlineStyle::create(m_pageAgent, m_resourceAgent, newStyleSheetId, element, this);
-    m_idToInspectorStyleSheet.set(newStyleSheetId, inspectorStyleSheet);
+    RefPtr<InspectorStyleSheetForInlineStyle> inspectorStyleSheet = InspectorStyleSheetForInlineStyle::create(newStyleSheetId, element, this);
+    m_idToInspectorStyleSheetForInlineStyle.set(newStyleSheetId, inspectorStyleSheet);
     m_nodeToInspectorStyleSheet.set(element, inspectorStyleSheet);
     return inspectorStyleSheet.get();
 }
@@ -1170,7 +1171,7 @@
     return m_documentToViaInspectorStyleSheet.get(document);
 }
 
-InspectorStyleSheet* InspectorCSSAgent::assertStyleSheetForId(ErrorString* errorString, const String& styleSheetId)
+InspectorStyleSheet* InspectorCSSAgent::assertInspectorStyleSheetForId(ErrorString* errorString, const String& styleSheetId)
 {
     IdToInspectorStyleSheet::iterator it = m_idToInspectorStyleSheet.find(styleSheetId);
     if (it == m_idToInspectorStyleSheet.end()) {
@@ -1180,6 +1181,20 @@
     return it->value.get();
 }
 
+InspectorStyleSheetBase* InspectorCSSAgent::assertStyleSheetForId(ErrorString* errorString, const String& styleSheetId)
+{
+    String placeholder;
+    InspectorStyleSheetBase* result = assertInspectorStyleSheetForId(&placeholder, styleSheetId);
+    if (result)
+        return result;
+    IdToInspectorStyleSheetForInlineStyle::iterator it = m_idToInspectorStyleSheetForInlineStyle.find(styleSheetId);
+    if (it == m_idToInspectorStyleSheetForInlineStyle.end()) {
+        *errorString = "No style sheet with given id found";
+        return 0;
+    }
+    return it->value.get();
+}
+
 TypeBuilder::CSS::StyleSheetOrigin::Enum InspectorCSSAgent::detectOrigin(CSSStyleSheet* pageStyleSheet, Document* ownerDocument)
 {
     if (m_creatingViaInspectorStyleSheet)
@@ -1294,7 +1309,7 @@
     if (it == m_nodeToInspectorStyleSheet.end())
         return;
 
-    m_idToInspectorStyleSheet.remove(it->value->id());
+    m_idToInspectorStyleSheetForInlineStyle.remove(it->value->id());
     m_nodeToInspectorStyleSheet.remove(node);
 }
 
@@ -1310,10 +1325,10 @@
     it->value->didModifyElementAttribute();
 }
 
-void InspectorCSSAgent::styleSheetChanged(InspectorStyleSheet* styleSheet)
+void InspectorCSSAgent::styleSheetChanged(InspectorStyleSheetBase* styleSheet)
 {
-    if (m_frontend)
-        m_frontend->styleSheetChanged(styleSheet->id());
+    flushPendingFrontendMessages();
+    m_frontend->styleSheetChanged(styleSheet->id());
 }
 
 void InspectorCSSAgent::willReparseStyleSheet()
diff --git a/Source/core/inspector/InspectorCSSAgent.h b/Source/core/inspector/InspectorCSSAgent.h
index d104358..4e4b097 100644
--- a/Source/core/inspector/InspectorCSSAgent.h
+++ b/Source/core/inspector/InspectorCSSAgent.h
@@ -63,7 +63,7 @@
     : public InspectorBaseAgent<InspectorCSSAgent>
     , public InspectorDOMAgent::DOMListener
     , public InspectorBackendDispatcher::CSSCommandHandler
-    , public InspectorStyleSheet::Listener {
+    , public InspectorStyleSheetBase::Listener {
     WTF_MAKE_NONCOPYABLE(InspectorCSSAgent);
 public:
     enum MediaListSource {
@@ -107,20 +107,20 @@
     virtual void setFrontend(InspectorFrontend*) OVERRIDE;
     virtual void clearFrontend() OVERRIDE;
     virtual void discardAgent() OVERRIDE;
+    virtual void didCommitLoadForMainFrame() OVERRIDE;
     virtual void restore() OVERRIDE;
+    virtual void flushPendingFrontendMessages() OVERRIDE;
     virtual void enable(ErrorString*, PassRefPtr<EnableCallback>) OVERRIDE;
     virtual void disable(ErrorString*) OVERRIDE;
     void reset();
-    void didCommitLoad(LocalFrame*, DocumentLoader*);
     void mediaQueryResultChanged();
     void willMutateRules();
     void didMutateRules(CSSStyleSheet*);
     void willMutateStyle();
     void didMutateStyle(CSSStyleDeclaration*, bool);
 
-public:
     void activeStyleSheetsUpdated(Document*);
-    void frameDetachedFromParent(LocalFrame*);
+    void documentDetached(Document*);
 
     virtual void getComputedStyleForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSComputedStyleProperty> >&) OVERRIDE;
     virtual void getPlatformFontsForNode(ErrorString*, int nodeId, String* cssFamilyName, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PlatformFontUsage> >&) OVERRIDE;
@@ -148,6 +148,7 @@
     InspectorCSSAgent(InspectorDOMAgent*, InspectorPageAgent*, InspectorResourceAgent*);
 
     typedef HashMap<String, RefPtr<InspectorStyleSheet> > IdToInspectorStyleSheet;
+    typedef HashMap<String, RefPtr<InspectorStyleSheetForInlineStyle> > IdToInspectorStyleSheetForInlineStyle;
     typedef HashMap<Node*, RefPtr<InspectorStyleSheetForInlineStyle> > NodeToInspectorStyleSheet; // bogus "stylesheets" with elements' inline styles
     typedef HashMap<int, unsigned> NodeIdToForcedPseudoState;
 
@@ -159,15 +160,16 @@
     void collectAllDocumentStyleSheets(Document*, Vector<CSSStyleSheet*>&);
     void collectStyleSheets(CSSStyleSheet*, Vector<CSSStyleSheet*>&);
 
-    void updateActiveStyleSheetsForDocument(Document*, StyleSheetsUpdateType);
-    void updateActiveStyleSheets(LocalFrame*, const Vector<CSSStyleSheet*>&, StyleSheetsUpdateType);
+    void updateActiveStyleSheets(Document*, StyleSheetsUpdateType);
+    void setActiveStyleSheets(Document*, const Vector<CSSStyleSheet*>&, StyleSheetsUpdateType);
 
     void collectPlatformFontsForRenderer(RenderText*, HashCountedSet<String>*);
 
     InspectorStyleSheet* bindStyleSheet(CSSStyleSheet*);
     String unbindStyleSheet(InspectorStyleSheet*);
     InspectorStyleSheet* viaInspectorStyleSheet(Document*, bool createIfAbsent);
-    InspectorStyleSheet* assertStyleSheetForId(ErrorString*, const String&);
+    InspectorStyleSheet* assertInspectorStyleSheetForId(ErrorString*, const String&);
+    InspectorStyleSheetBase* assertStyleSheetForId(ErrorString*, const String&);
     TypeBuilder::CSS::StyleSheetOrigin::Enum detectOrigin(CSSStyleSheet* pageStyleSheet, Document* ownerDocument);
     bool styleSheetEditInProgress() const { return m_styleSheetsPendingMutation || m_styleDeclarationPendingMutation || m_isSettingStyleSheetText; }
 
@@ -181,7 +183,7 @@
     virtual void didModifyDOMAttr(Element*) OVERRIDE;
 
     // InspectorStyleSheet::Listener implementation
-    virtual void styleSheetChanged(InspectorStyleSheet*) OVERRIDE;
+    virtual void styleSheetChanged(InspectorStyleSheetBase*) OVERRIDE;
     virtual void willReparseStyleSheet() OVERRIDE;
     virtual void didReparseStyleSheet() OVERRIDE;
 
@@ -193,14 +195,17 @@
     InspectorResourceAgent* m_resourceAgent;
 
     IdToInspectorStyleSheet m_idToInspectorStyleSheet;
+    IdToInspectorStyleSheetForInlineStyle m_idToInspectorStyleSheetForInlineStyle;
     HashMap<CSSStyleSheet*, RefPtr<InspectorStyleSheet> > m_cssStyleSheetToInspectorStyleSheet;
-    HashMap<LocalFrame*, OwnPtr<HashSet<CSSStyleSheet*> > > m_frameToCSSStyleSheets;
+    typedef HashMap<Document*, OwnPtr<HashSet<CSSStyleSheet*> > > DocumentStyleSheets;
+    DocumentStyleSheets m_documentToCSSStyleSheets;
+    HashSet<Document*> m_invalidatedDocuments;
 
     NodeToInspectorStyleSheet m_nodeToInspectorStyleSheet;
     HashMap<RefPtr<Document>, RefPtr<InspectorStyleSheet> > m_documentToViaInspectorStyleSheet; // "via inspector" stylesheets
     NodeIdToForcedPseudoState m_nodeIdToForcedPseudoState;
 
-    RefPtr<CSSStyleSheet> m_inspectorUserAgentStyleSheet;
+    RefPtrWillBePersistent<CSSStyleSheet> m_inspectorUserAgentStyleSheet;
 
     int m_lastStyleSheetId;
     int m_styleSheetsPendingMutation;
diff --git a/Source/core/inspector/InspectorController.cpp b/Source/core/inspector/InspectorController.cpp
index f3f7838..64e6f3f 100644
--- a/Source/core/inspector/InspectorController.cpp
+++ b/Source/core/inspector/InspectorController.cpp
@@ -428,6 +428,11 @@
         domDebuggerAgent->didProcessTask();
 }
 
+void InspectorController::flushPendingFrontendMessages()
+{
+    m_agents.flushPendingFrontendMessages();
+}
+
 void InspectorController::didCommitLoadForMainFrame()
 {
     Vector<InspectorAgent*> agents = m_moduleAgents;
diff --git a/Source/core/inspector/InspectorController.h b/Source/core/inspector/InspectorController.h
index 701e883..0c85ea5 100644
--- a/Source/core/inspector/InspectorController.h
+++ b/Source/core/inspector/InspectorController.h
@@ -121,6 +121,7 @@
 
     void willProcessTask();
     void didProcessTask();
+    void flushPendingFrontendMessages();
 
     void didCommitLoadForMainFrame();
     void didBeginFrame(int frameId);
@@ -134,6 +135,7 @@
 
     void willAddPageOverlay(const GraphicsLayer*);
     void didRemovePageOverlay(const GraphicsLayer*);
+
 private:
     InspectorController(Page*, InspectorClient*);
 
diff --git a/Source/core/inspector/InspectorDOMAgent.cpp b/Source/core/inspector/InspectorDOMAgent.cpp
index cb1d0af..17ad00b 100644
--- a/Source/core/inspector/InspectorDOMAgent.cpp
+++ b/Source/core/inspector/InspectorDOMAgent.cpp
@@ -423,6 +423,20 @@
     return toElement(node);
 }
 
+static ShadowRoot* userAgentShadowRoot(Node* node)
+{
+    if (!node || !node->isInShadowTree())
+        return 0;
+
+    Node* candidate = node;
+    while (candidate && !candidate->isShadowRoot())
+        candidate = candidate->parentOrShadowHostNode();
+    ASSERT(candidate);
+    ShadowRoot* shadowRoot = toShadowRoot(candidate);
+
+    return shadowRoot->type() == ShadowRoot::UserAgentShadowRoot ? shadowRoot : 0;
+}
+
 Node* InspectorDOMAgent::assertEditableNode(ErrorString* errorString, int nodeId)
 {
     Node* node = assertNode(errorString, nodeId);
@@ -434,10 +448,7 @@
             *errorString = "Cannot edit shadow roots";
             return 0;
         }
-        Node* candidate = node;
-        while (candidate && !candidate->isShadowRoot())
-            candidate = candidate->parentElementOrShadowRoot();
-        if (!candidate || (candidate->isShadowRoot() && toShadowRoot(candidate)->type() == ShadowRoot::UserAgentShadowRoot)) {
+        if (userAgentShadowRoot(node)) {
             *errorString = "Cannot edit nodes from user-agent shadow trees";
             return 0;
         }
@@ -1127,8 +1138,11 @@
         return;
 
     Node* node = inspectedNode;
-    if (node->nodeType() != Node::ELEMENT_NODE && node->nodeType() != Node::DOCUMENT_NODE)
-        node = node->parentNode();
+    while (node && node->nodeType() != Node::ELEMENT_NODE && node->nodeType() != Node::DOCUMENT_NODE && node->nodeType() != Node::DOCUMENT_FRAGMENT_NODE)
+        node = node->parentOrShadowHostNode();
+
+    if (!node)
+        return;
 
     int nodeId = pushNodePathToFrontend(node);
     if (nodeId)
@@ -1144,9 +1158,20 @@
         return;
     Node* node = hoveredNodeForEvent(frame, event, event.shiftKey());
 
-    while (m_searchingForNode != SearchingForShadow && node && node->isInShadowTree())
+    // Do not highlight within UA shadow root unless requested.
+    if (m_searchingForNode != SearchingForUAShadow) {
+        ShadowRoot* uaShadowRoot = userAgentShadowRoot(node);
+        if (uaShadowRoot)
+            node = uaShadowRoot->host();
+    }
+
+    // Shadow roots don't have boxes - use host element instead.
+    if (node && node->isShadowRoot())
         node = node->parentOrShadowHostNode();
 
+    if (!node)
+        return;
+
     Node* eventTarget = event.shiftKey() ? hoveredNodeForEvent(frame, event, false) : 0;
     if (eventTarget == node)
         eventTarget = 0;
@@ -1193,11 +1218,11 @@
     return highlightConfig.release();
 }
 
-void InspectorDOMAgent::setInspectModeEnabled(ErrorString* errorString, bool enabled, const bool* inspectShadowDOM, const RefPtr<JSONObject>* highlightConfig)
+void InspectorDOMAgent::setInspectModeEnabled(ErrorString* errorString, bool enabled, const bool* inspectUAShadowDOM, const RefPtr<JSONObject>* highlightConfig)
 {
     if (enabled && !pushDocumentUponHandlelessOperation(errorString))
         return;
-    SearchMode searchMode = enabled ? (inspectShadowDOM && *inspectShadowDOM ? SearchingForShadow : SearchingForNormal) : NotSearching;
+    SearchMode searchMode = enabled ? (inspectUAShadowDOM && *inspectUAShadowDOM ? SearchingForUAShadow : SearchingForNormal) : NotSearching;
     setSearchingForNode(errorString, searchMode, highlightConfig ? highlightConfig->get() : 0);
 }
 
diff --git a/Source/core/inspector/InspectorDOMAgent.h b/Source/core/inspector/InspectorDOMAgent.h
index 9f726ba..3777cf4 100644
--- a/Source/core/inspector/InspectorDOMAgent.h
+++ b/Source/core/inspector/InspectorDOMAgent.h
@@ -131,7 +131,7 @@
     virtual void discardSearchResults(ErrorString*, const String& searchId) OVERRIDE;
     virtual void resolveNode(ErrorString*, int nodeId, const String* objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& result) OVERRIDE;
     virtual void getAttributes(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<String> >& result) OVERRIDE;
-    virtual void setInspectModeEnabled(ErrorString*, bool enabled, const bool* inspectShadowDOM, const RefPtr<JSONObject>* highlightConfig) OVERRIDE;
+    virtual void setInspectModeEnabled(ErrorString*, bool enabled, const bool* inspectUAShadowDOM, const RefPtr<JSONObject>* highlightConfig) OVERRIDE;
     virtual void requestNode(ErrorString*, const String& objectId, int* nodeId) OVERRIDE;
     virtual void pushNodeByPathToFrontend(ErrorString*, const String& path, int* nodeId) OVERRIDE;
     virtual void pushNodesByBackendIdsToFrontend(ErrorString*, const RefPtr<JSONArray>& nodeIds, RefPtr<TypeBuilder::Array<int> >&) OVERRIDE;
@@ -205,7 +205,7 @@
     Document* assertDocument(ErrorString*, int nodeId);
 
 private:
-    enum SearchMode { NotSearching, SearchingForNormal, SearchingForShadow };
+    enum SearchMode { NotSearching, SearchingForNormal, SearchingForUAShadow };
 
     InspectorDOMAgent(InspectorPageAgent*, InjectedScriptManager*, InspectorOverlay*);
 
diff --git a/Source/core/inspector/InspectorDebuggerAgent.cpp b/Source/core/inspector/InspectorDebuggerAgent.cpp
index 625d84b..d18518d 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -1208,7 +1208,6 @@
     }
 
     m_frontend->paused(currentCallFrames(), m_breakReason, m_breakAuxData, hitBreakpointIds, currentAsyncStackTrace());
-    m_frontend->flush();
     m_javaScriptPauseScheduled = false;
 
     if (!m_continueToLocationBreakpointId.isEmpty()) {
diff --git a/Source/core/inspector/InspectorInstrumentation.idl b/Source/core/inspector/InspectorInstrumentation.idl
index 899f15e..d614345 100644
--- a/Source/core/inspector/InspectorInstrumentation.idl
+++ b/Source/core/inspector/InspectorInstrumentation.idl
@@ -91,6 +91,9 @@
     [DOM, DOMDebugger, Inline=FastReturn]
     void didInvalidateStyleAttr([Keep] Node*);
 
+    [CSS]
+    void documentDetached([Keep] Document*);
+
     [CSS, Inline=FastReturn]
     void willMutateRules(CSSStyleSheet*);
 
@@ -337,10 +340,10 @@
     [Page]
     void frameAttachedToParent([Keep] LocalFrame*);
 
-    [Canvas, Page, CSS]
+    [Canvas, Page]
     void frameDetachedFromParent([Keep] LocalFrame*);
 
-    [Console, Resource, CSS, DOM, Inspector, Canvas, Page, PageDebugger]
+    [Console, Resource, DOM, Inspector, Canvas, Page, PageDebugger]
     void didCommitLoad([Keep] LocalFrame*, DocumentLoader*);
 
     [DOM, Inline=FastReturn]
diff --git a/Source/core/inspector/InspectorStyleSheet.cpp b/Source/core/inspector/InspectorStyleSheet.cpp
index 8e9081b..e159795 100644
--- a/Source/core/inspector/InspectorStyleSheet.cpp
+++ b/Source/core/inspector/InspectorStyleSheet.cpp
@@ -340,7 +340,7 @@
     // FIXME: Use another subclass of BisonCSSParser::SourceDataHandler and assert that
     // no comments are encountered (will not need m_document and m_styleSheetContents).
     StyleSheetHandler handler(commentText, m_document, m_styleSheetContents, &sourceData);
-    RefPtr<MutableStylePropertySet> tempMutableStyle = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> tempMutableStyle = MutableStylePropertySet::create();
     m_commentParser->parseDeclaration(tempMutableStyle.get(), commentText, &handler, m_styleSheetContents);
     Vector<CSSPropertySourceData>& commentPropertyData = sourceData.first()->styleSourceData->propertyData;
     if (commentPropertyData.size() != 1)
@@ -375,7 +375,7 @@
     String m_text;
     bool m_hasText;
     OwnPtr<RuleSourceDataList> m_sourceData;
-    RefPtr<CSSStyleSheet> m_pageStyleSheet;
+    RefPtrWillBePersistent<CSSStyleSheet> m_pageStyleSheet;
 };
 
 ParsedStyleSheet::ParsedStyleSheet(CSSStyleSheet* pageStyleSheet)
@@ -504,12 +504,12 @@
     return nullptr;
 }
 
-PassRefPtr<InspectorStyle> InspectorStyle::create(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheet* parentStyleSheet)
+PassRefPtr<InspectorStyle> InspectorStyle::create(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheetBase* parentStyleSheet)
 {
     return adoptRef(new InspectorStyle(styleId, style, parentStyleSheet));
 }
 
-InspectorStyle::InspectorStyle(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheet* parentStyleSheet)
+InspectorStyle::InspectorStyle(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheetBase* parentStyleSheet)
     : m_styleId(styleId)
     , m_style(style)
     , m_parentStyleSheet(parentStyleSheet)
@@ -551,7 +551,7 @@
 bool InspectorStyle::verifyPropertyText(const String& propertyText, bool canOmitSemicolon)
 {
     DEFINE_STATIC_LOCAL(String, bogusPropertyName, ("-webkit-boguz-propertee"));
-    RefPtr<MutableStylePropertySet> tempMutableStyle = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> tempMutableStyle = MutableStylePropertySet::create();
     RuleSourceDataList sourceData;
     RefPtrWillBeRawPtr<StyleSheetContents> styleSheetContents = StyleSheetContents::create(strictCSSParserContext());
     String declarationText = propertyText + (canOmitSemicolon ? ";" : " ") + bogusPropertyName + ": none";
@@ -830,22 +830,84 @@
 
 Document* InspectorStyle::ownerDocument() const
 {
-    return m_parentStyleSheet->pageStyleSheet() ? m_parentStyleSheet->pageStyleSheet()->ownerDocument() : 0;
+    return m_parentStyleSheet->ownerDocument();
 }
 
-PassRefPtr<InspectorStyleSheet> InspectorStyleSheet::create(InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent, const String& id, PassRefPtr<CSSStyleSheet> pageStyleSheet, TypeBuilder::CSS::StyleSheetOrigin::Enum origin, const String& documentURL, Listener* listener)
+InspectorStyleSheetBase::InspectorStyleSheetBase(const String& id, Listener* listener)
+    : m_id(id)
+    , m_listener(listener)
+{
+}
+
+bool InspectorStyleSheetBase::setPropertyText(const InspectorCSSId& id, unsigned propertyIndex, const String& text, bool overwrite, String* oldText, ExceptionState& exceptionState)
+{
+    RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
+    if (!inspectorStyle) {
+        exceptionState.throwDOMException(NotFoundError, "No property could be found for the given ID.");
+        return false;
+    }
+
+    bool success = inspectorStyle->setPropertyText(propertyIndex, text, overwrite, oldText, exceptionState);
+    if (success)
+        fireStyleSheetChanged();
+    return success;
+}
+
+void InspectorStyleSheetBase::fireStyleSheetChanged()
+{
+    if (listener())
+        listener()->styleSheetChanged(this);
+}
+
+PassRefPtr<TypeBuilder::CSS::CSSStyle> InspectorStyleSheetBase::buildObjectForStyle(CSSStyleDeclaration* style)
+{
+    RefPtr<CSSRuleSourceData> sourceData;
+    if (ensureParsedDataReady())
+        sourceData = ruleSourceDataFor(style);
+
+    InspectorCSSId id = styleId(style);
+    if (id.isEmpty()) {
+        // Any rule coming from User Agent and not from DefaultStyleSheet will not have id.
+        // See InspectorCSSAgent::buildObjectForRule for details.
+        RefPtr<InspectorStyle> inspectorStyle = InspectorStyle::create(id, style, this);
+        return inspectorStyle->buildObjectForStyle();
+    }
+    RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
+    RefPtr<TypeBuilder::CSS::CSSStyle> result = inspectorStyle->buildObjectForStyle();
+
+    // Style text cannot be retrieved without stylesheet, so set cssText here.
+    if (sourceData) {
+        String sheetText;
+        bool success = getText(&sheetText);
+        if (success) {
+            const SourceRange& bodyRange = sourceData->ruleBodyRange;
+            result->setCssText(sheetText.substring(bodyRange.start, bodyRange.end - bodyRange.start));
+        }
+    }
+
+    return result.release();
+}
+
+PassOwnPtr<Vector<unsigned> > InspectorStyleSheetBase::lineEndings()
+{
+    String text;
+    if (!getText(&text))
+        return PassOwnPtr<Vector<unsigned> >();
+    return WTF::lineEndings(text);
+}
+
+PassRefPtr<InspectorStyleSheet> InspectorStyleSheet::create(InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent, const String& id, PassRefPtrWillBeRawPtr<CSSStyleSheet> pageStyleSheet, TypeBuilder::CSS::StyleSheetOrigin::Enum origin, const String& documentURL, Listener* listener)
 {
     return adoptRef(new InspectorStyleSheet(pageAgent, resourceAgent, id, pageStyleSheet, origin, documentURL, listener));
 }
 
-InspectorStyleSheet::InspectorStyleSheet(InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent, const String& id, PassRefPtr<CSSStyleSheet> pageStyleSheet, TypeBuilder::CSS::StyleSheetOrigin::Enum origin, const String& documentURL, Listener* listener)
-    : m_pageAgent(pageAgent)
+InspectorStyleSheet::InspectorStyleSheet(InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent, const String& id, PassRefPtrWillBeRawPtr<CSSStyleSheet> pageStyleSheet, TypeBuilder::CSS::StyleSheetOrigin::Enum origin, const String& documentURL, Listener* listener)
+    : InspectorStyleSheetBase(id, listener)
+    , m_pageAgent(pageAgent)
     , m_resourceAgent(resourceAgent)
-    , m_id(id)
     , m_pageStyleSheet(pageStyleSheet)
     , m_origin(origin)
     , m_documentURL(documentURL)
-    , m_listener(listener)
 {
     m_parsedStyleSheet = adoptPtr(new ParsedStyleSheet(m_pageStyleSheet.get()));
 }
@@ -867,10 +929,13 @@
     return url.isEmpty() ? m_documentURL : url;
 }
 
-void InspectorStyleSheet::reparseStyleSheet(const String& text)
+bool InspectorStyleSheet::setText(const String& text, ExceptionState& exceptionState)
 {
-    if (m_listener)
-        m_listener->willReparseStyleSheet();
+    m_parsedStyleSheet->setText(text);
+    m_flatRules.clear();
+
+    if (listener())
+        listener()->willReparseStyleSheet();
 
     {
         // Have a separate scope for clearRules() (bug 95324).
@@ -883,22 +948,10 @@
         m_pageStyleSheet->contents()->parseString(text);
     }
 
-    if (m_listener)
-        m_listener->didReparseStyleSheet();
+    if (listener())
+        listener()->didReparseStyleSheet();
     fireStyleSheetChanged();
     m_pageStyleSheet->ownerDocument()->styleResolverChanged(RecalcStyleImmediately, FullStyleUpdate);
-}
-
-bool InspectorStyleSheet::setText(const String& text, ExceptionState& exceptionState)
-{
-    if (!checkPageStyleSheet(exceptionState))
-        return false;
-    if (!m_parsedStyleSheet)
-        return false;
-
-    m_parsedStyleSheet->setText(text);
-    m_flatRules.clear();
-
     return true;
 }
 
@@ -914,8 +967,6 @@
 
 bool InspectorStyleSheet::setRuleSelector(const InspectorCSSId& id, const String& selector, ExceptionState& exceptionState)
 {
-    if (!checkPageStyleSheet(exceptionState))
-        return false;
     CSSStyleRule* rule = ruleForId(id);
     if (!rule) {
         exceptionState.throwDOMException(NotFoundError, "No rule was found for the given ID.");
@@ -950,8 +1001,6 @@
 
 CSSStyleRule* InspectorStyleSheet::addRule(const String& selector, ExceptionState& exceptionState)
 {
-    if (!checkPageStyleSheet(exceptionState))
-        return 0;
     if (!checkStyleRuleSelector(m_pageStyleSheet->ownerDocument(), selector)) {
         exceptionState.throwDOMException(SyntaxError, "The selector '" + selector + "' could not be added.");
         return 0;
@@ -988,8 +1037,8 @@
 
     styleSheetText.append(selector);
     styleSheetText.appendLiteral(" {}");
-    // Using setText() as this operation changes the style sheet rule set.
-    setText(styleSheetText.toString(), ASSERT_NO_EXCEPTION);
+    m_parsedStyleSheet->setText(styleSheetText.toString());
+    m_flatRules.clear();
 
     fireStyleSheetChanged();
 
@@ -998,8 +1047,6 @@
 
 bool InspectorStyleSheet::deleteRule(const InspectorCSSId& id, ExceptionState& exceptionState)
 {
-    if (!checkPageStyleSheet(exceptionState))
-        return false;
     RefPtrWillBeRawPtr<CSSStyleRule> rule = ruleForId(id);
     if (!rule) {
         exceptionState.throwDOMException(NotFoundError, "No style rule could be found for the provided ID.");
@@ -1025,7 +1072,8 @@
 
     String sheetText = m_parsedStyleSheet->text();
     sheetText.remove(sourceData->ruleHeaderRange.start, sourceData->ruleBodyRange.end - sourceData->ruleHeaderRange.start + 1);
-    setText(sheetText, ASSERT_NO_EXCEPTION);
+    m_parsedStyleSheet->setText(sheetText);
+    m_flatRules.clear();
     fireStyleSheetChanged();
     return true;
 }
@@ -1066,7 +1114,7 @@
     return result.release();
 }
 
-PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::Selector> > InspectorStyleSheet::selectorsFromSource(const CSSRuleSourceData* sourceData, const String& sheetText) const
+PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::Selector> > InspectorStyleSheet::selectorsFromSource(const CSSRuleSourceData* sourceData, const String& sheetText)
 {
     ScriptRegexp comment("/\\*[^]*?\\*/", TextCaseSensitive, MultilineEnabled);
     RefPtr<TypeBuilder::Array<TypeBuilder::CSS::Selector> > result = TypeBuilder::Array<TypeBuilder::CSS::Selector>::create();
@@ -1146,49 +1194,6 @@
     return result.release();
 }
 
-PassRefPtr<TypeBuilder::CSS::CSSStyle> InspectorStyleSheet::buildObjectForStyle(CSSStyleDeclaration* style)
-{
-    RefPtr<CSSRuleSourceData> sourceData;
-    if (ensureParsedDataReady())
-        sourceData = ruleSourceDataFor(style);
-
-    InspectorCSSId id = ruleIdByStyle(style);
-    if (id.isEmpty()) {
-        // Any rule coming from User Agent and not from DefaultStyleSheet will not have id.
-        // See InspectorCSSAgent::buildObjectForRule for details.
-        RefPtr<InspectorStyle> inspectorStyle = InspectorStyle::create(id, style, this);
-        return inspectorStyle->buildObjectForStyle();
-    }
-    RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
-    RefPtr<TypeBuilder::CSS::CSSStyle> result = inspectorStyle->buildObjectForStyle();
-
-    // Style text cannot be retrieved without stylesheet, so set cssText here.
-    if (sourceData) {
-        String sheetText;
-        bool success = getText(&sheetText);
-        if (success) {
-            const SourceRange& bodyRange = sourceData->ruleBodyRange;
-            result->setCssText(sheetText.substring(bodyRange.start, bodyRange.end - bodyRange.start));
-        }
-    }
-
-    return result.release();
-}
-
-bool InspectorStyleSheet::setPropertyText(const InspectorCSSId& id, unsigned propertyIndex, const String& text, bool overwrite, String* oldText, ExceptionState& exceptionState)
-{
-    RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
-    if (!inspectorStyle) {
-        exceptionState.throwDOMException(NotFoundError, "No property could be found for the given ID.");
-        return false;
-    }
-
-    bool success = inspectorStyle->setPropertyText(propertyIndex, text, overwrite, oldText, exceptionState);
-    if (success)
-        fireStyleSheetChanged();
-    return success;
-}
-
 bool InspectorStyleSheet::getText(String* result) const
 {
     if (!ensureText())
@@ -1206,20 +1211,16 @@
     return rule->style();
 }
 
-void InspectorStyleSheet::fireStyleSheetChanged()
-{
-    if (m_listener)
-        m_listener->styleSheetChanged(this);
-}
-
 PassRefPtr<TypeBuilder::CSS::SourceRange> InspectorStyleSheet::ruleHeaderSourceRange(const CSSRule* rule)
 {
     if (!ensureParsedDataReady())
         return nullptr;
 
-    RefPtr<CSSRuleSourceData> sourceData = m_parsedStyleSheet->ruleSourceDataAt(ruleIndexByRule(rule));
-    if (!sourceData)
+    ensureFlatRules();
+    size_t index = m_flatRules.find(rule);
+    if (index == kNotFound)
         return nullptr;
+    RefPtr<CSSRuleSourceData> sourceData = m_parsedStyleSheet->ruleSourceDataAt(static_cast<unsigned>(index));
     return buildSourceRangeObject(sourceData->ruleHeaderRange, lineEndings().get());
 }
 
@@ -1307,7 +1308,7 @@
     return m_pageAgent->resourceSourceMapURL(finalURL());
 }
 
-InspectorCSSId InspectorStyleSheet::ruleIdByStyle(CSSStyleDeclaration* style) const
+InspectorCSSId InspectorStyleSheet::styleId(CSSStyleDeclaration* style) const
 {
     unsigned index = ruleIndexByStyle(style);
     if (index != UINT_MAX)
@@ -1325,13 +1326,6 @@
     return m_parsedStyleSheet->ruleSourceDataAt(ruleIndexByStyle(style));
 }
 
-PassOwnPtr<Vector<unsigned> > InspectorStyleSheet::lineEndings() const
-{
-    if (!m_parsedStyleSheet->hasText())
-        return PassOwnPtr<Vector<unsigned> >();
-    return WTF::lineEndings(m_parsedStyleSheet->text());
-}
-
 unsigned InspectorStyleSheet::ruleIndexByStyle(CSSStyleDeclaration* pageStyle) const
 {
     ensureFlatRules();
@@ -1343,22 +1337,6 @@
     return UINT_MAX;
 }
 
-unsigned InspectorStyleSheet::ruleIndexByRule(const CSSRule* rule) const
-{
-    ensureFlatRules();
-    size_t index = m_flatRules.find(rule);
-    return index == kNotFound ? UINT_MAX : static_cast<unsigned>(index);
-}
-
-bool InspectorStyleSheet::checkPageStyleSheet(ExceptionState& exceptionState) const
-{
-    if (!m_pageStyleSheet) {
-        exceptionState.throwDOMException(NotSupportedError, "No stylesheet is available.");
-        return false;
-    }
-    return true;
-}
-
 bool InspectorStyleSheet::ensureParsedDataReady()
 {
     return ensureText() && m_parsedStyleSheet->ensureSourceData();
@@ -1366,8 +1344,6 @@
 
 bool InspectorStyleSheet::ensureText() const
 {
-    if (!m_parsedStyleSheet)
-        return false;
     if (m_parsedStyleSheet->hasText())
         return true;
 
@@ -1415,8 +1391,6 @@
 
 bool InspectorStyleSheet::setStyleText(CSSStyleDeclaration* style, const String& text)
 {
-    if (!m_pageStyleSheet)
-        return false;
     if (!ensureParsedDataReady())
         return false;
 
@@ -1425,7 +1399,7 @@
     if (!success)
         return false;
 
-    InspectorCSSId id = ruleIdByStyle(style);
+    InspectorCSSId id = styleId(style);
     if (id.isEmpty())
         return false;
 
@@ -1460,7 +1434,7 @@
 
 InspectorCSSId InspectorStyleSheet::ruleId(CSSStyleRule* rule) const
 {
-    return ruleIdByStyle(rule->style());
+    return styleId(rule->style());
 }
 
 bool InspectorStyleSheet::originalStyleSheetText(String* result) const
@@ -1476,7 +1450,7 @@
     if (m_origin == TypeBuilder::CSS::StyleSheetOrigin::User || m_origin == TypeBuilder::CSS::StyleSheetOrigin::User_agent)
         return false;
 
-    if (!m_pageStyleSheet || !ownerDocument() || !ownerDocument()->frame())
+    if (!ownerDocument() || !ownerDocument()->frame())
         return false;
 
     bool base64Encoded;
@@ -1486,9 +1460,6 @@
 
 bool InspectorStyleSheet::inlineStyleSheetText(String* result) const
 {
-    if (!m_pageStyleSheet)
-        return false;
-
     Node* ownerNode = m_pageStyleSheet->ownerNode();
     if (!ownerNode || ownerNode->nodeType() != Node::ELEMENT_NODE)
         return false;
@@ -1500,13 +1471,13 @@
     return true;
 }
 
-PassRefPtr<InspectorStyleSheetForInlineStyle> InspectorStyleSheetForInlineStyle::create(InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent, const String& id, PassRefPtr<Element> element, Listener* listener)
+PassRefPtr<InspectorStyleSheetForInlineStyle> InspectorStyleSheetForInlineStyle::create(const String& id, PassRefPtr<Element> element, Listener* listener)
 {
-    return adoptRef(new InspectorStyleSheetForInlineStyle(pageAgent, resourceAgent, id, element, listener));
+    return adoptRef(new InspectorStyleSheetForInlineStyle(id, element, listener));
 }
 
-InspectorStyleSheetForInlineStyle::InspectorStyleSheetForInlineStyle(InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent, const String& id, PassRefPtr<Element> element, Listener* listener)
-    : InspectorStyleSheet(pageAgent, resourceAgent, id, nullptr, TypeBuilder::CSS::StyleSheetOrigin::Regular, "", listener)
+InspectorStyleSheetForInlineStyle::InspectorStyleSheetForInlineStyle(const String& id, PassRefPtr<Element> element, Listener* listener)
+    : InspectorStyleSheetBase(id, listener)
     , m_element(element)
     , m_ruleSourceData(nullptr)
     , m_isStyleTextValid(false)
@@ -1524,16 +1495,13 @@
     m_ruleSourceData.clear();
 }
 
-void InspectorStyleSheetForInlineStyle::reparseStyleSheet(const String& text)
-{
-    fireStyleSheetChanged();
-}
-
 bool InspectorStyleSheetForInlineStyle::setText(const String& text, ExceptionState& exceptionState)
 {
     bool success = setStyleText(inlineStyle(), text);
     if (!success)
         exceptionState.throwDOMException(SyntaxError, "Style sheet text is invalid.");
+    else
+        fireStyleSheetChanged();
     return success;
 }
 
@@ -1563,11 +1531,6 @@
     return !exceptionState.hadException();
 }
 
-PassOwnPtr<Vector<unsigned> > InspectorStyleSheetForInlineStyle::lineEndings() const
-{
-    return WTF::lineEndings(elementStyleText());
-}
-
 Document* InspectorStyleSheetForInlineStyle::ownerDocument() const
 {
     return &m_element->document();
@@ -1625,7 +1588,7 @@
         return result.release();
     }
 
-    RefPtr<MutableStylePropertySet> tempDeclaration = MutableStylePropertySet::create();
+    RefPtrWillBeRawPtr<MutableStylePropertySet> tempDeclaration = MutableStylePropertySet::create();
     RuleSourceDataList ruleSourceDataResult;
     StyleSheetHandler handler(m_styleText, &m_element->document(), m_element->document().elementSheet().contents(), &ruleSourceDataResult);
     createCSSParser(&m_element->document())->parseDeclaration(tempDeclaration.get(), m_styleText, &handler, m_element->document().elementSheet().contents());
diff --git a/Source/core/inspector/InspectorStyleSheet.h b/Source/core/inspector/InspectorStyleSheet.h
index 15c218f..4954732 100644
--- a/Source/core/inspector/InspectorStyleSheet.h
+++ b/Source/core/inspector/InspectorStyleSheet.h
@@ -50,7 +50,7 @@
 class ExceptionState;
 class InspectorPageAgent;
 class InspectorResourceAgent;
-class InspectorStyleSheet;
+class InspectorStyleSheetBase;
 
 typedef WillBePersistentHeapVector<RefPtrWillBeMember<CSSRule> > CSSRuleVector;
 typedef String ErrorString;
@@ -132,7 +132,7 @@
 
 class InspectorStyle FINAL : public RefCounted<InspectorStyle> {
 public:
-    static PassRefPtr<InspectorStyle> create(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheet* parentStyleSheet);
+    static PassRefPtr<InspectorStyle> create(const InspectorCSSId&, PassRefPtr<CSSStyleDeclaration>, InspectorStyleSheetBase* parentStyleSheet);
 
     CSSStyleDeclaration* cssStyle() const { return m_style.get(); }
     PassRefPtr<TypeBuilder::CSS::CSSStyle> buildObjectForStyle() const;
@@ -141,7 +141,7 @@
     bool styleText(String* result) const;
 
 private:
-    InspectorStyle(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheet* parentStyleSheet);
+    InspectorStyle(const InspectorCSSId&, PassRefPtr<CSSStyleDeclaration>, InspectorStyleSheetBase* parentStyleSheet);
 
     bool verifyPropertyText(const String& propertyText, bool canOmitSemicolon);
     void populateAllProperties(Vector<InspectorStyleProperty>& result) const;
@@ -154,78 +154,105 @@
 
     InspectorCSSId m_styleId;
     RefPtr<CSSStyleDeclaration> m_style;
-    InspectorStyleSheet* m_parentStyleSheet;
+    InspectorStyleSheetBase* m_parentStyleSheet;
     mutable std::pair<String, String> m_format;
     mutable bool m_formatAcquired;
 };
 
-class InspectorStyleSheet : public RefCounted<InspectorStyleSheet> {
+class InspectorStyleSheetBase : public RefCounted<InspectorStyleSheetBase> {
 public:
     class Listener {
     public:
         Listener() { }
         virtual ~Listener() { }
-        virtual void styleSheetChanged(InspectorStyleSheet*) = 0;
+        virtual void styleSheetChanged(InspectorStyleSheetBase*) = 0;
         virtual void willReparseStyleSheet() = 0;
         virtual void didReparseStyleSheet() = 0;
     };
-
-    static PassRefPtr<InspectorStyleSheet> create(InspectorPageAgent*, InspectorResourceAgent*, const String& id, PassRefPtr<CSSStyleSheet> pageStyleSheet, TypeBuilder::CSS::StyleSheetOrigin::Enum, const String& documentURL, Listener*);
-
-    virtual ~InspectorStyleSheet();
+    virtual ~InspectorStyleSheetBase() { }
 
     String id() const { return m_id; }
-    String finalURL() const;
-    virtual Document* ownerDocument() const;
-    CSSStyleSheet* pageStyleSheet() const { return m_pageStyleSheet.get(); }
-    virtual void reparseStyleSheet(const String&);
-    virtual bool setText(const String&, ExceptionState&);
-    virtual bool getText(String* result) const;
-    String ruleSelector(const InspectorCSSId&, ExceptionState&);
-    bool setRuleSelector(const InspectorCSSId&, const String& selector, ExceptionState&);
-    CSSStyleRule* addRule(const String& selector, ExceptionState&);
-    bool deleteRule(const InspectorCSSId&, ExceptionState&);
+
+    virtual Document* ownerDocument() const = 0;
+    virtual bool setText(const String&, ExceptionState&) = 0;
+    virtual bool getText(String* result) const = 0;
     bool setPropertyText(const InspectorCSSId&, unsigned propertyIndex, const String& text, bool overwrite, String* oldPropertyText, ExceptionState&);
 
-    PassRefPtr<TypeBuilder::CSS::CSSStyleSheetHeader> buildObjectForStyleSheetInfo() const;
-    PassRefPtr<TypeBuilder::CSS::CSSRule> buildObjectForRule(CSSStyleRule*, PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSMedia> >);
+    virtual CSSStyleDeclaration* styleForId(const InspectorCSSId&) const = 0;
+    virtual InspectorCSSId styleId(CSSStyleDeclaration*) const = 0;
+
     PassRefPtr<TypeBuilder::CSS::CSSStyle> buildObjectForStyle(CSSStyleDeclaration*);
 
-    PassRefPtr<TypeBuilder::CSS::SourceRange> ruleHeaderSourceRange(const CSSRule*);
-
-    InspectorCSSId ruleId(CSSStyleRule*) const;
-    InspectorCSSId styleId(CSSStyleDeclaration* style) const { return ruleIdByStyle(style); }
-    virtual CSSStyleRule* ruleForId(const InspectorCSSId&) const;
-    virtual CSSStyleDeclaration* styleForId(const InspectorCSSId&) const;
-
 protected:
-    InspectorStyleSheet(InspectorPageAgent*, InspectorResourceAgent*, const String& id, PassRefPtr<CSSStyleSheet> pageStyleSheet, TypeBuilder::CSS::StyleSheetOrigin::Enum, const String& documentURL, Listener*);
+    InspectorStyleSheetBase(const String& id, Listener*);
 
+    Listener* listener() const { return m_listener; }
     void fireStyleSheetChanged();
-    virtual PassRefPtr<CSSRuleSourceData> ruleSourceDataFor(CSSStyleDeclaration*) const;
-    virtual unsigned ruleIndexByStyle(CSSStyleDeclaration*) const;
-    virtual unsigned ruleIndexByRule(const CSSRule*) const;
-    virtual bool ensureParsedDataReady();
-    virtual PassRefPtr<InspectorStyle> inspectorStyleForId(const InspectorCSSId&);
-    virtual String sourceMapURL() const;
-    virtual String sourceURL() const;
+    PassOwnPtr<Vector<unsigned> > lineEndings();
+
+    virtual PassRefPtr<InspectorStyle> inspectorStyleForId(const InspectorCSSId&) = 0;
 
     // Also accessed by friend class InspectorStyle.
-    virtual bool setStyleText(CSSStyleDeclaration*, const String&);
-    virtual PassOwnPtr<Vector<unsigned> > lineEndings() const;
+    virtual PassRefPtr<CSSRuleSourceData> ruleSourceDataFor(CSSStyleDeclaration*) const = 0;
+    virtual bool setStyleText(CSSStyleDeclaration*, const String&) = 0;
+    virtual bool ensureParsedDataReady() = 0;
 
 private:
     friend class InspectorStyle;
 
-    InspectorCSSId ruleIdByStyle(CSSStyleDeclaration*) const;
-    bool checkPageStyleSheet(ExceptionState&) const;
+    String m_id;
+    Listener* m_listener;
+};
+
+class InspectorStyleSheet : public InspectorStyleSheetBase {
+public:
+    static PassRefPtr<InspectorStyleSheet> create(InspectorPageAgent*, InspectorResourceAgent*, const String& id, PassRefPtrWillBeRawPtr<CSSStyleSheet> pageStyleSheet, TypeBuilder::CSS::StyleSheetOrigin::Enum, const String& documentURL, Listener*);
+
+    virtual ~InspectorStyleSheet();
+
+    String finalURL() const;
+    virtual Document* ownerDocument() const OVERRIDE;
+    virtual bool setText(const String&, ExceptionState&) OVERRIDE;
+    virtual bool getText(String* result) const OVERRIDE;
+    String ruleSelector(const InspectorCSSId&, ExceptionState&);
+    bool setRuleSelector(const InspectorCSSId&, const String& selector, ExceptionState&);
+    CSSStyleRule* addRule(const String& selector, ExceptionState&);
+    bool deleteRule(const InspectorCSSId&, ExceptionState&);
+
+    CSSStyleSheet* pageStyleSheet() const { return m_pageStyleSheet.get(); }
+
+    PassRefPtr<TypeBuilder::CSS::CSSStyleSheetHeader> buildObjectForStyleSheetInfo() const;
+    PassRefPtr<TypeBuilder::CSS::CSSRule> buildObjectForRule(CSSStyleRule*, PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSMedia> >);
+
+    PassRefPtr<TypeBuilder::CSS::SourceRange> ruleHeaderSourceRange(const CSSRule*);
+
+    InspectorCSSId ruleId(CSSStyleRule*) const;
+    CSSStyleRule* ruleForId(const InspectorCSSId&) const;
+
+    virtual InspectorCSSId styleId(CSSStyleDeclaration*) const OVERRIDE;
+    virtual CSSStyleDeclaration* styleForId(const InspectorCSSId&) const OVERRIDE;
+
+protected:
+    virtual PassRefPtr<InspectorStyle> inspectorStyleForId(const InspectorCSSId&) OVERRIDE;
+
+    // Also accessed by friend class InspectorStyle.
+    virtual PassRefPtr<CSSRuleSourceData> ruleSourceDataFor(CSSStyleDeclaration*) const OVERRIDE;
+    virtual bool setStyleText(CSSStyleDeclaration*, const String&) OVERRIDE;
+    virtual bool ensureParsedDataReady() OVERRIDE;
+
+private:
+    InspectorStyleSheet(InspectorPageAgent*, InspectorResourceAgent*, const String& id, PassRefPtrWillBeRawPtr<CSSStyleSheet> pageStyleSheet, TypeBuilder::CSS::StyleSheetOrigin::Enum, const String& documentURL, Listener*);
+
+    unsigned ruleIndexByStyle(CSSStyleDeclaration*) const;
+    String sourceMapURL() const;
+    String sourceURL() const;
     bool ensureText() const;
     void ensureFlatRules() const;
     bool styleSheetTextWithChangedStyle(CSSStyleDeclaration*, const String& newStyleText, String* result);
     bool originalStyleSheetText(String* result) const;
     bool resourceStyleSheetText(String* result) const;
     bool inlineStyleSheetText(String* result) const;
-    PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::Selector> > selectorsFromSource(const CSSRuleSourceData*, const String&) const;
+    PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::Selector> > selectorsFromSource(const CSSRuleSourceData*, const String&);
     PassRefPtr<TypeBuilder::CSS::SelectorList> buildObjectForSelectorList(CSSStyleRule*);
     String url() const;
     bool hasSourceURL() const;
@@ -233,43 +260,36 @@
 
     InspectorPageAgent* m_pageAgent;
     InspectorResourceAgent* m_resourceAgent;
-    String m_id;
-    RefPtr<CSSStyleSheet> m_pageStyleSheet;
+    RefPtrWillBePersistent<CSSStyleSheet> m_pageStyleSheet;
     TypeBuilder::CSS::StyleSheetOrigin::Enum m_origin;
     String m_documentURL;
     OwnPtr<ParsedStyleSheet> m_parsedStyleSheet;
     mutable CSSRuleVector m_flatRules;
-    Listener* m_listener;
     mutable String m_sourceURL;
 };
 
-class InspectorStyleSheetForInlineStyle FINAL : public InspectorStyleSheet {
+class InspectorStyleSheetForInlineStyle FINAL : public InspectorStyleSheetBase {
 public:
-    static PassRefPtr<InspectorStyleSheetForInlineStyle> create(InspectorPageAgent*, InspectorResourceAgent*, const String& id, PassRefPtr<Element>, Listener*);
+    static PassRefPtr<InspectorStyleSheetForInlineStyle> create(const String& id, PassRefPtr<Element>, Listener*);
 
     void didModifyElementAttribute();
     virtual Document* ownerDocument() const OVERRIDE;
-    virtual void reparseStyleSheet(const String&) OVERRIDE;
     virtual bool setText(const String&, ExceptionState&) OVERRIDE;
     virtual bool getText(String* result) const OVERRIDE;
-    virtual CSSStyleRule* ruleForId(const InspectorCSSId&) const OVERRIDE { return 0; }
+
     virtual CSSStyleDeclaration* styleForId(const InspectorCSSId& id) const OVERRIDE { ASSERT_UNUSED(id, !id.ordinal()); return inlineStyle(); }
+    virtual InspectorCSSId styleId(CSSStyleDeclaration* style) const OVERRIDE { return InspectorCSSId(id(), 0); }
 
 protected:
-    InspectorStyleSheetForInlineStyle(InspectorPageAgent*, InspectorResourceAgent*, const String& id, PassRefPtr<Element>, Listener*);
-
-    virtual PassRefPtr<CSSRuleSourceData> ruleSourceDataFor(CSSStyleDeclaration* style) const OVERRIDE { ASSERT_UNUSED(style, style == inlineStyle()); return m_ruleSourceData; }
-    virtual unsigned ruleIndexByStyle(CSSStyleDeclaration*) const OVERRIDE { return 0; }
-    virtual bool ensureParsedDataReady() OVERRIDE;
     virtual PassRefPtr<InspectorStyle> inspectorStyleForId(const InspectorCSSId&) OVERRIDE;
-    virtual String sourceMapURL() const OVERRIDE { return String(); }
-    virtual String sourceURL() const OVERRIDE { return String(); }
 
     // Also accessed by friend class InspectorStyle.
+    virtual bool ensureParsedDataReady() OVERRIDE;
+    virtual PassRefPtr<CSSRuleSourceData> ruleSourceDataFor(CSSStyleDeclaration* style) const OVERRIDE { ASSERT_UNUSED(style, style == inlineStyle()); return m_ruleSourceData; }
     virtual bool setStyleText(CSSStyleDeclaration*, const String&) OVERRIDE;
-    virtual PassOwnPtr<Vector<unsigned> > lineEndings() const OVERRIDE;
 
 private:
+    InspectorStyleSheetForInlineStyle(const String& id, PassRefPtr<Element>, Listener*);
     CSSStyleDeclaration* inlineStyle() const;
     const String& elementStyleText() const;
     PassRefPtr<CSSRuleSourceData> getStyleAttributeData() const;
diff --git a/Source/core/inspector/ScriptProfile.cpp b/Source/core/inspector/ScriptProfile.cpp
index 7313538..09539ea 100644
--- a/Source/core/inspector/ScriptProfile.cpp
+++ b/Source/core/inspector/ScriptProfile.cpp
@@ -40,7 +40,7 @@
 
 ScriptProfile::~ScriptProfile()
 {
-    const_cast<v8::CpuProfile*>(m_profile)->Delete();
+    m_profile->Delete();
 }
 
 String ScriptProfile::title() const
diff --git a/Source/core/inspector/ScriptProfile.h b/Source/core/inspector/ScriptProfile.h
index 162c0b8..91ce25f 100644
--- a/Source/core/inspector/ScriptProfile.h
+++ b/Source/core/inspector/ScriptProfile.h
@@ -43,7 +43,7 @@
 
 class ScriptProfile FINAL : public RefCounted<ScriptProfile> {
 public:
-    static PassRefPtr<ScriptProfile> create(const v8::CpuProfile* profile, double idleTime)
+    static PassRefPtr<ScriptProfile> create(v8::CpuProfile* profile, double idleTime)
     {
         return adoptRef(new ScriptProfile(profile, idleTime));
     }
@@ -59,13 +59,13 @@
     PassRefPtr<TypeBuilder::Array<int> > buildInspectorObjectForSamples() const;
 
 private:
-    ScriptProfile(const v8::CpuProfile* profile, double idleTime)
+    ScriptProfile(v8::CpuProfile* profile, double idleTime)
         : m_profile(profile)
         , m_idleTime(idleTime)
     {
     }
 
-    const v8::CpuProfile* m_profile;
+    v8::CpuProfile* m_profile;
     double m_idleTime;
 };
 
diff --git a/Source/core/inspector/TraceEventDispatcher.cpp b/Source/core/inspector/TraceEventDispatcher.cpp
index 8351b81..dec9a8e 100644
--- a/Source/core/inspector/TraceEventDispatcher.cpp
+++ b/Source/core/inspector/TraceEventDispatcher.cpp
@@ -100,7 +100,7 @@
 
 void TraceEventDispatcher::innerAddListener(const char* name, char phase, TraceEventTargetBase* instance, TraceEventHandlerMethod method, InspectorClient* client)
 {
-    static const char CategoryFilter[] = "devtools,webkit";
+    static const char CategoryFilter[] = "devtools";
 
     ASSERT(isMainThread());
     MutexLocker locker(m_mutex);
diff --git a/Source/core/loader/DocumentLoader.cpp b/Source/core/loader/DocumentLoader.cpp
index f8af711..9c2f4ae 100644
--- a/Source/core/loader/DocumentLoader.cpp
+++ b/Source/core/loader/DocumentLoader.cpp
@@ -589,6 +589,10 @@
 
 bool DocumentLoader::maybeCreateArchive()
 {
+    // Only the top-frame can load MHTML.
+    if (m_frame->tree().parent())
+        return false;
+
     // Give the archive machinery a crack at this document. If the MIME type is not an archive type, it will return 0.
     if (!isArchiveMIMEType(m_response.mimeType()))
         return false;
@@ -608,6 +612,9 @@
     // relative URLs are resolved properly.
     ensureWriter(mainResource->mimeType(), m_archive->mainResource()->url());
 
+    // The Document has now been created.
+    document()->enforceSandboxFlags(SandboxAll);
+
     commitData(mainResource->data()->data(), mainResource->data()->size());
     return true;
 }
diff --git a/Source/core/loader/EmptyClients.h b/Source/core/loader/EmptyClients.h
index 39d0a99..9e7a7f2 100644
--- a/Source/core/loader/EmptyClients.h
+++ b/Source/core/loader/EmptyClients.h
@@ -289,7 +289,7 @@
     virtual ~EmptyEditorClient() { }
 
     virtual void respondToChangedContents() OVERRIDE { }
-    virtual void respondToChangedSelection(SelectionType) OVERRIDE { }
+    virtual void respondToChangedSelection(LocalFrame*, SelectionType) OVERRIDE { }
 
     virtual bool canCopyCut(LocalFrame*, bool defaultValue) const OVERRIDE { return defaultValue; }
     virtual bool canPaste(LocalFrame*, bool defaultValue) const OVERRIDE { return defaultValue; }
diff --git a/Source/core/loader/FrameLoader.cpp b/Source/core/loader/FrameLoader.cpp
index 2f3d4e2..ac66761 100644
--- a/Source/core/loader/FrameLoader.cpp
+++ b/Source/core/loader/FrameLoader.cpp
@@ -544,15 +544,15 @@
 
 LocalFrame* FrameLoader::opener()
 {
-    ASSERT(m_client);
     // FIXME: Temporary hack to stage converting locations that really should be Frame.
-    return toLocalFrame(m_client->opener());
+    return m_client ? toLocalFrame(m_client->opener()) : 0;
 }
 
 void FrameLoader::setOpener(LocalFrame* opener)
 {
-    ASSERT(m_client);
-    m_client->setOpener(opener);
+    // If the frame is already detached, the opener has already been cleared.
+    if (m_client)
+        m_client->setOpener(opener);
 }
 
 bool FrameLoader::allowPlugins(ReasonForCallingAllowPlugins reason)
diff --git a/Source/core/make_core_generated.target.darwin-arm.mk b/Source/core/make_core_generated.target.darwin-arm.mk
index 0625545..1620f19 100644
--- a/Source/core/make_core_generated.target.darwin-arm.mk
+++ b/Source/core/make_core_generated.target.darwin-arm.mk
@@ -233,9 +233,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -497,7 +497,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -583,7 +582,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
diff --git a/Source/core/make_core_generated.target.darwin-mips.mk b/Source/core/make_core_generated.target.darwin-mips.mk
index 160d32e..f0bbc0f 100644
--- a/Source/core/make_core_generated.target.darwin-mips.mk
+++ b/Source/core/make_core_generated.target.darwin-mips.mk
@@ -233,9 +233,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -496,7 +496,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -581,7 +580,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
diff --git a/Source/core/make_core_generated.target.darwin-x86.mk b/Source/core/make_core_generated.target.darwin-x86.mk
index ecf03e2..cee18c9 100644
--- a/Source/core/make_core_generated.target.darwin-x86.mk
+++ b/Source/core/make_core_generated.target.darwin-x86.mk
@@ -233,9 +233,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -498,7 +498,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -584,7 +583,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
diff --git a/Source/core/make_core_generated.target.linux-arm.mk b/Source/core/make_core_generated.target.linux-arm.mk
index 0625545..1620f19 100644
--- a/Source/core/make_core_generated.target.linux-arm.mk
+++ b/Source/core/make_core_generated.target.linux-arm.mk
@@ -233,9 +233,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -497,7 +497,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -583,7 +582,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
diff --git a/Source/core/make_core_generated.target.linux-mips.mk b/Source/core/make_core_generated.target.linux-mips.mk
index 160d32e..f0bbc0f 100644
--- a/Source/core/make_core_generated.target.linux-mips.mk
+++ b/Source/core/make_core_generated.target.linux-mips.mk
@@ -233,9 +233,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -496,7 +496,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -581,7 +580,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
diff --git a/Source/core/make_core_generated.target.linux-x86.mk b/Source/core/make_core_generated.target.linux-x86.mk
index ecf03e2..cee18c9 100644
--- a/Source/core/make_core_generated.target.linux-x86.mk
+++ b/Source/core/make_core_generated.target.linux-x86.mk
@@ -233,9 +233,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeMac.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeMac.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -498,7 +498,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -584,7 +583,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
diff --git a/Source/core/page/DragController.cpp b/Source/core/page/DragController.cpp
index a254211..c245660 100644
--- a/Source/core/page/DragController.cpp
+++ b/Source/core/page/DragController.cpp
@@ -554,7 +554,7 @@
     if (dragData->containsFiles() && asFileInput(result.innerNonSharedNode()))
         return true;
 
-    if (result.innerNonSharedNode()->isPluginElement()) {
+    if (isHTMLPlugInElement(*result.innerNonSharedNode())) {
         HTMLPlugInElement* plugin = toHTMLPlugInElement(result.innerNonSharedNode());
         if (!plugin->canProcessDrag() && !result.innerNonSharedNode()->rendererIsEditable())
             return false;
diff --git a/Source/core/page/EditorClient.h b/Source/core/page/EditorClient.h
index 7d7e4fd..d8b69cf 100644
--- a/Source/core/page/EditorClient.h
+++ b/Source/core/page/EditorClient.h
@@ -41,7 +41,7 @@
     virtual ~EditorClient() { }
 
     virtual void respondToChangedContents() = 0;
-    virtual void respondToChangedSelection(SelectionType) = 0;
+    virtual void respondToChangedSelection(LocalFrame*, SelectionType) = 0;
 
     virtual bool canCopyCut(LocalFrame*, bool defaultValue) const = 0;
     virtual bool canPaste(LocalFrame*, bool defaultValue) const = 0;
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index 5a64465..e0301a0 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -1745,10 +1745,7 @@
 
 static bool targetIsFrame(Node* target, LocalFrame*& frame)
 {
-    if (!target)
-        return false;
-
-    if (!isHTMLFrameElement(*target) && !isHTMLIFrameElement(*target))
+    if (!isHTMLFrameElementBase(target))
         return false;
 
     frame = toHTMLFrameElementBase(target)->contentFrame();
diff --git a/Source/core/page/FocusController.cpp b/Source/core/page/FocusController.cpp
index 4e3fe53..a5d573e 100644
--- a/Source/core/page/FocusController.cpp
+++ b/Source/core/page/FocusController.cpp
@@ -47,6 +47,7 @@
 #include "core/frame/LocalFrame.h"
 #include "core/html/HTMLAreaElement.h"
 #include "core/html/HTMLImageElement.h"
+#include "core/html/HTMLPlugInElement.h"
 #include "core/html/HTMLShadowElement.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
@@ -382,7 +383,7 @@
         return false;
 
     Element* element = toElement(node);
-    if (element->isFrameOwnerElement() && (!element->isPluginElement() || !element->isKeyboardFocusable())) {
+    if (element->isFrameOwnerElement() && (!isHTMLPlugInElement(*element) || !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.
         HTMLFrameOwnerElement* owner = toHTMLFrameOwnerElement(element);
diff --git a/Source/core/page/PageSerializer.cpp b/Source/core/page/PageSerializer.cpp
index e0d3342..9143fdd 100644
--- a/Source/core/page/PageSerializer.cpp
+++ b/Source/core/page/PageSerializer.cpp
@@ -314,7 +314,7 @@
     if (!shouldAddURL(url))
         return;
 
-    if (!image || image->image() == Image::nullImage())
+    if (!image || image->image() == Image::nullImage() || image->errorOccurred())
         return;
 
     RefPtr<SharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
diff --git a/Source/core/page/SpatialNavigation.cpp b/Source/core/page/SpatialNavigation.cpp
index 77606dd..8e5a04e 100644
--- a/Source/core/page/SpatialNavigation.cpp
+++ b/Source/core/page/SpatialNavigation.cpp
@@ -662,8 +662,8 @@
         return;
     }
 
-    float x = (entryPoint.x() - exitPoint.x()) * (entryPoint.x() - exitPoint.x());
-    float y = (entryPoint.y() - exitPoint.y()) * (entryPoint.y() - exitPoint.y());
+    float x = ((entryPoint.x() - exitPoint.x()) * (entryPoint.x() - exitPoint.x())).toFloat();
+    float y = ((entryPoint.y() - exitPoint.y()) * (entryPoint.y() - exitPoint.y())).toFloat();
 
     float euclidianDistance = sqrt(x + y);
 
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.cpp b/Source/core/page/scrolling/ScrollingCoordinator.cpp
index c09c01c..6147b12 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -29,13 +29,19 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/Document.h"
+#include "core/dom/FullscreenElementStack.h"
 #include "core/dom/Node.h"
 #include "core/dom/WheelController.h"
 #include "core/html/HTMLElement.h"
 #include "core/frame/FrameView.h"
 #include "core/frame/LocalFrame.h"
-#include "core/page/Page.h"
 #include "core/frame/Settings.h"
+#include "core/page/Page.h"
+#include "core/plugins/PluginView.h"
+#include "core/rendering/RenderGeometryMap.h"
+#include "core/rendering/RenderView.h"
+#include "core/rendering/compositing/CompositedLayerMapping.h"
+#include "core/rendering/compositing/RenderLayerCompositor.h"
 #include "platform/TraceEvent.h"
 #include "platform/exported/WebScrollbarImpl.h"
 #include "platform/exported/WebScrollbarThemeGeometryNative.h"
@@ -47,11 +53,6 @@
 #endif
 #include "platform/scroll/ScrollAnimator.h"
 #include "platform/scroll/ScrollbarTheme.h"
-#include "core/plugins/PluginView.h"
-#include "core/rendering/RenderGeometryMap.h"
-#include "core/rendering/RenderView.h"
-#include "core/rendering/compositing/CompositedLayerMapping.h"
-#include "core/rendering/compositing/RenderLayerCompositor.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebCompositorSupport.h"
 #include "public/platform/WebLayerPositionConstraint.h"
@@ -160,8 +161,15 @@
 
     // The mainFrame view doesn't get included in the FrameTree below, so we
     // update its size separately.
-    if (WebLayer* scrollingWebLayer = frameView ? toWebLayer(frameView->layerForScrolling()) : 0)
+    if (WebLayer* scrollingWebLayer = frameView ? toWebLayer(frameView->layerForScrolling()) : 0) {
         scrollingWebLayer->setBounds(frameView->contentsSize());
+        // If there is a fullscreen element, set the scroll clip layer to 0 so main frame won't scroll.
+        Element* fullscreenElement = FullscreenElementStack::fullscreenElementFrom(*(m_page->mainFrame()->document()));
+        if (fullscreenElement)
+            scrollingWebLayer->setScrollClipLayer(0);
+        else
+            scrollingWebLayer->setScrollClipLayer(toWebLayer(frameView->layerForContainer()));
+    }
 
     const FrameTree& tree = m_page->mainFrame()->tree();
     for (const LocalFrame* child = tree.firstChild(); child; child = child->tree().nextSibling()) {
diff --git a/Source/core/rendering/FastTextAutosizer.cpp b/Source/core/rendering/FastTextAutosizer.cpp
index 2888f16..5cbbf1b 100644
--- a/Source/core/rendering/FastTextAutosizer.cpp
+++ b/Source/core/rendering/FastTextAutosizer.cpp
@@ -51,7 +51,6 @@
 {
     // At style recalc, the renderer's parent may not be attached,
     // so we need to obtain this from the DOM tree.
-
     const Node* node = renderer->node();
     if (!node)
         return 0;
@@ -63,22 +62,21 @@
     return 0;
 }
 
-static const Vector<QualifiedName>& formInputTags()
+static bool isFormInput(const Element* element)
 {
-    // Returns the tags for the form input elements.
     DEFINE_STATIC_LOCAL(Vector<QualifiedName>, formInputTags, ());
     if (formInputTags.isEmpty()) {
         formInputTags.append(HTMLNames::inputTag);
         formInputTags.append(HTMLNames::buttonTag);
         formInputTags.append(HTMLNames::selectTag);
     }
-    return formInputTags;
+    return formInputTags.contains(element->tagQName());
 }
 
-static bool isAutosizingContainer(const RenderObject* renderer)
+static bool isPotentialClusterRoot(const RenderObject* renderer)
 {
-    // "Autosizing containers" are the smallest unit for which we can
-    // enable/disable Text Autosizing.
+    // "Potential cluster roots" are the smallest unit for which we can
+    // enable/disable text autosizing.
     // - Must not be inline, as different multipliers on one line looks terrible.
     //   Exceptions are inline-block and alike elements (inline-table, -webkit-inline-*),
     //   as they often contain entire multi-line columns of text.
@@ -86,50 +84,26 @@
     // - Must not be normal list items, as items in the same list should look
     //   consistent, unless they are floating or position:absolute/fixed.
     Node* node = renderer->generatingNode();
-    if ((node && !node->hasChildren())
-        || !renderer->isRenderBlock()
-        || (renderer->isInline() && !renderer->style()->isDisplayReplacedType()))
+    if (node && !node->hasChildren())
+        return false;
+    if (!renderer->isRenderBlock())
+        return false;
+    if (renderer->isInline() && !renderer->style()->isDisplayReplacedType())
         return false;
     if (renderer->isListItem())
-        return renderer->isFloating() || renderer->isOutOfFlowPositioned();
+        return (renderer->isFloating() || renderer->isOutOfFlowPositioned());
     // Avoid creating containers for text within text controls, buttons, or <select> buttons.
     Node* parentNode = renderer->parent() ? renderer->parent()->generatingNode() : 0;
-    if (parentNode && parentNode->isElementNode() && formInputTags().contains(toElement(parentNode)->tagQName()))
+    if (parentNode && parentNode->isElementNode() && isFormInput(toElement(parentNode)))
         return false;
 
     return true;
 }
 
-static RenderObject* nextInPreOrderSkippingDescendantsOfContainers(const RenderObject* current, const RenderObject* stayWithin)
-{
-    if (current == stayWithin || !isAutosizingContainer(current))
-        return current->nextInPreOrder(stayWithin);
-    return current->nextInPreOrderAfterChildren(stayWithin);
-}
-
 static bool isIndependentDescendant(const RenderBlock* renderer)
 {
-    ASSERT(isAutosizingContainer(renderer));
+    ASSERT(isPotentialClusterRoot(renderer));
 
-    // "Autosizing clusters" are special autosizing containers within which we
-    // want to enforce a uniform text size multiplier, in the hopes of making
-    // the major sections of the page look internally consistent.
-    // All their descendants (including other autosizing containers) must share
-    // the same multiplier, except for subtrees which are themselves clusters,
-    // and some of their descendant containers might not be autosized at all
-    // (for example if their height is constrained).
-    // Additionally, clusterShouldBeAutosized requires each cluster to contain a
-    // minimum amount of text, without which it won't be autosized.
-    //
-    // Clusters are chosen using very similar criteria to CSS flow roots, aka
-    // block formatting contexts (http://w3.org/TR/css3-box/#flow-root), since
-    // flow roots correspond to box containers that behave somewhat
-    // independently from their parent (for example they don't overlap floats).
-    // The definition of a flow root also conveniently includes most of the
-    // ways that a box and its children can have significantly different width
-    // from the box's parent (we want to avoid having significantly different
-    // width blocks within a cluster, since the narrower blocks would end up
-    // larger than would otherwise be necessary).
     RenderBlock* containingBlock = renderer->containingBlock();
     return renderer->isRenderView()
         || renderer->isFloating()
@@ -147,96 +121,112 @@
     // containers, and probably flexboxes...
 }
 
-static bool containerIsRowOfLinks(const RenderObject* container)
+static bool blockIsRowOfLinks(const RenderBlock* block)
 {
-    // A "row of links" is a container for which holds:
-    //  1. it should not contain non-link text elements longer than 3 characters
-    //  2. it should contain min. 3 inline links and all links should
-    //     have the same specified font size
-    //  3. it should not contain <br> elements
-    //  4. it should contain only inline elements unless they are containers,
+    // A "row of links" is a block for which:
+    //  1. It does not contain non-link text elements longer than 3 characters
+    //  2. It contains a minimum of 3 inline links and all links should
+    //     have the same specified font size.
+    //  3. It should not contain <br> elements.
+    //  4. It should contain only inline elements unless they are containers,
     //     children of link elements or children of sub-containers.
     int linkCount = 0;
-    RenderObject* renderer = container->nextInPreOrder(container);
+    RenderObject* renderer = block->nextInPreOrder(block);
     float matchingFontSize = -1;
 
     while (renderer) {
-        if (!isAutosizingContainer(renderer)) {
+        if (!isPotentialClusterRoot(renderer)) {
             if (renderer->isText() && toRenderText(renderer)->text().impl()->stripWhiteSpace()->length() > 3)
                 return false;
-            if (!renderer->isInline())
-                return false;
-            if (renderer->isBR())
+            if (!renderer->isInline() || renderer->isBR())
                 return false;
         }
         if (renderer->style()->isLink()) {
-            if (matchingFontSize < 0) {
-                matchingFontSize = renderer->style()->specifiedFontSize();
-            } else {
-                if (matchingFontSize != renderer->style()->specifiedFontSize())
-                    return false;
-            }
-
             linkCount++;
+            if (matchingFontSize < 0)
+                matchingFontSize = renderer->style()->specifiedFontSize();
+            else if (matchingFontSize != renderer->style()->specifiedFontSize())
+                return false;
+
             // Skip traversing descendants of the link.
-            renderer = renderer->nextInPreOrderAfterChildren(container);
-        } else {
-            renderer = nextInPreOrderSkippingDescendantsOfContainers(renderer, container);
+            renderer = renderer->nextInPreOrderAfterChildren(block);
+            continue;
         }
+        renderer = renderer->nextInPreOrder(block);
     }
 
     return (linkCount >= 3);
 }
 
-static bool contentHeightIsConstrained(const RenderBlock* container)
+static bool blockHeightConstrained(const RenderBlock* block)
 {
     // FIXME: Propagate constrainedness down the tree, to avoid inefficiently walking back up from each box.
     // FIXME: This code needs to take into account vertical writing modes.
     // FIXME: Consider additional heuristics, such as ignoring fixed heights if the content is already overflowing before autosizing kicks in.
-    for (; container; container = container->containingBlock()) {
-        RenderStyle* style = container->style();
+    for (; block; block = block->containingBlock()) {
+        RenderStyle* style = block->style();
         if (style->overflowY() >= OSCROLL)
             return false;
-        if (style->height().isSpecified() || style->maxHeight().isSpecified() || container->isOutOfFlowPositioned()) {
+        if (style->height().isSpecified() || style->maxHeight().isSpecified() || block->isOutOfFlowPositioned()) {
             // Some sites (e.g. wikipedia) set their html and/or body elements to height:100%,
             // without intending to constrain the height of the content within them.
-            return !container->isRoot() && !container->isBody();
+            return !block->isRoot() && !block->isBody();
         }
-        if (container->isFloating())
+        if (block->isFloating())
             return false;
     }
     return false;
 }
 
-static bool containerContainsOneOfTags(const RenderBlock* container, const Vector<QualifiedName>& tags)
+static bool blockContainsFormInput(const RenderBlock* block)
 {
-    const RenderObject* renderer = container;
+    const RenderObject* renderer = block;
     while (renderer) {
-        const Node* rendererNode = renderer->node();
-        if (rendererNode && rendererNode->isElementNode()) {
-            if (tags.contains(toElement(rendererNode)->tagQName()))
-                return true;
-        }
-        renderer = nextInPreOrderSkippingDescendantsOfContainers(renderer, container);
+        const Node* node = renderer->node();
+        if (node && node->isElementNode() && isFormInput(toElement(node)))
+            return true;
+        if (renderer == block)
+            renderer = renderer->nextInPreOrder(block);
+        else
+            renderer = renderer->nextInPreOrderAfterChildren(block);
     }
 
     return false;
 }
 
-static bool containerShouldBeAutosized(const RenderBlock* container)
+// Some blocks are not autosized even if their parent cluster wants them to.
+static bool blockSuppressesAutosizing(const RenderBlock* block)
 {
-    if (containerContainsOneOfTags(container, formInputTags()))
-        return false;
+    if (blockContainsFormInput(block))
+        return true;
 
-    if (containerIsRowOfLinks(container))
-        return false;
+    if (blockIsRowOfLinks(block))
+        return true;
 
     // Don't autosize block-level text that can't wrap (as it's likely to
     // expand sideways and break the page's layout).
-    if (!container->style()->autoWrap())
-        return false;
+    if (!block->style()->autoWrap())
+        return true;
 
-    return !contentHeightIsConstrained(container);
+    if (blockHeightConstrained(block))
+        return true;
+
+    return false;
+}
+
+static bool mightBeWiderOrNarrowerDescendant(const RenderBlock* block)
+{
+    // FIXME: This heuristic may need to be expanded to other ways a block can be wider or narrower
+    //        than its parent containing block.
+    return block->style() && block->style()->width().isSpecified();
+}
+
+// Before a block enters layout we don't know for sure if it will become a cluster.
+// Note: clusters are also created for blocks that do become autosizing clusters!
+static bool blockMightBecomeAutosizingCluster(const RenderBlock* block)
+{
+    ASSERT(isPotentialClusterRoot(block));
+    return isIndependentDescendant(block) || mightBeWiderOrNarrowerDescendant(block) || block->isTable();
 }
 
 FastTextAutosizer::FastTextAutosizer(const Document* document)
@@ -263,7 +253,10 @@
 
     ASSERT(!m_blocksThatHaveBegunLayout.contains(block));
 
-    if (!isFingerprintingCandidate(block))
+    if (!isPotentialClusterRoot(block))
+        return;
+
+    if (!blockMightBecomeAutosizingCluster(block))
         return;
 
     if (Fingerprint fingerprint = computeFingerprint(block))
@@ -364,7 +357,7 @@
                 RenderTableCell* renderTableCell = toRenderTableCell(cell);
 
                 bool shouldAutosize;
-                if (!containerShouldBeAutosized(renderTableCell))
+                if (blockSuppressesAutosizing(renderTableCell))
                     shouldAutosize = false;
                 else if (Supercluster* supercluster = getSupercluster(renderTableCell))
                     shouldAutosize = anyClusterHasEnoughTextToAutosize(supercluster->m_roots, table);
@@ -405,7 +398,13 @@
 {
     Cluster* cluster = currentCluster();
     float multiplier = 0;
-    for (RenderObject* descendant = nextChildSkippingChildrenOfBlocks(block, block); descendant; descendant = nextChildSkippingChildrenOfBlocks(descendant, block)) {
+    RenderObject* descendant = block->nextInPreOrder();
+    while (descendant) {
+        // Skip block descendants because they will be inflate()'d on their own.
+        if (descendant->isRenderBlock()) {
+            descendant = descendant->nextInPreOrderAfterChildren(block);
+            continue;
+        }
         if (descendant->isText()) {
             // We only calculate this multiplier on-demand to ensure the parent block of this text
             // has entered layout.
@@ -414,6 +413,7 @@
             applyMultiplier(descendant, multiplier);
             applyMultiplier(descendant->parent(), multiplier); // Parent handles line spacing.
         }
+        descendant = descendant->nextInPreOrder(block);
     }
 }
 
@@ -456,15 +456,6 @@
 #endif
 }
 
-bool FastTextAutosizer::isFingerprintingCandidate(const RenderBlock* block)
-{
-    // FIXME: move the logic out of TextAutosizer.cpp into this class.
-    return block->isRenderView()
-        || (isAutosizingContainer(block)
-            && (isIndependentDescendant(block)
-                || mightBeWiderOrNarrowerDescendant(block)));
-}
-
 bool FastTextAutosizer::clusterWouldHaveEnoughTextToAutosize(const RenderBlock* root, const RenderBlock* widthProvider)
 {
     Cluster hypotheticalCluster(root, true, 0);
@@ -486,7 +477,7 @@
         return true;
     }
 
-    if (!containerShouldBeAutosized(root)) {
+    if (blockSuppressesAutosizing(root)) {
         cluster->m_hasEnoughTextToAutosize = NotEnoughText;
         return false;
     }
@@ -499,12 +490,12 @@
     while (descendant) {
         if (descendant->isRenderBlock()) {
             RenderBlock* block = toRenderBlock(descendant);
-            if (isAutosizingContainer(block)) {
-                // Note: Ideally we would check isWiderOrNarrowerDescendant here but we only know that
-                //       after the block has entered layout, which may not be the case.
+
+            // Note: Ideally we would check isWiderOrNarrowerDescendant here but we only know that
+            //       after the block has entered layout, which may not be the case.
+            if (isPotentialClusterRoot(block)) {
                 bool isAutosizingClusterRoot = isIndependentDescendant(block) || block->isTable();
-                if ((isAutosizingClusterRoot && !block->isTableCell())
-                    || !containerShouldBeAutosized(block)) {
+                if ((isAutosizingClusterRoot && !block->isTableCell()) || blockSuppressesAutosizing(block)) {
                     descendant = descendant->nextInPreOrderAfterChildren(root);
                     continue;
                 }
@@ -580,25 +571,21 @@
 
 FastTextAutosizer::Cluster* FastTextAutosizer::maybeCreateCluster(const RenderBlock* block)
 {
-    if (!isAutosizingContainer(block))
+    if (!isPotentialClusterRoot(block))
         return 0;
 
     Cluster* parentCluster = m_clusterStack.isEmpty() ? 0 : currentCluster();
     ASSERT(parentCluster || block->isRenderView());
 
-    // Create clusters to suppress / unsuppress autosizing based on containerShouldBeAutosized.
-    bool containerCanAutosize = containerShouldBeAutosized(block);
-    bool parentClusterCanAutosize = parentCluster && parentCluster->m_autosize;
-    bool createClusterThatMightAutosize = block->isRenderView()
-        || mightBeWiderOrNarrowerDescendant(block)
-        || isIndependentDescendant(block)
-        || block->isTable();
+    bool mightAutosize = blockMightBecomeAutosizingCluster(block);
+    bool suppressesAutosizing = blockSuppressesAutosizing(block);
 
-    // If the container would not alter the m_autosize bit, it doesn't need to be a cluster.
-    if (!createClusterThatMightAutosize && containerCanAutosize == parentClusterCanAutosize)
+    // If the block would not alter the m_autosize bit, it doesn't need to be a cluster.
+    bool parentSuppressesAutosizing = parentCluster && !parentCluster->m_autosize;
+    if (!mightAutosize && suppressesAutosizing == parentSuppressesAutosizing)
         return 0;
 
-    return new Cluster(block, containerCanAutosize, parentCluster, getSupercluster(block));
+    return new Cluster(block, !suppressesAutosizing, parentCluster, getSupercluster(block));
 }
 
 FastTextAutosizer::Supercluster* FastTextAutosizer::getSupercluster(const RenderBlock* block)
@@ -796,7 +783,7 @@
     while (child) {
         // Note: At this point clusters may not have been created for these blocks so we cannot rely
         //       on m_clusters. Instead, we use a best-guess about whether the block will become a cluster.
-        if (!isAutosizingContainer(child) || !isIndependentDescendant(toRenderBlock(child))) {
+        if (!isPotentialClusterRoot(child) || !isIndependentDescendant(toRenderBlock(child))) {
             const RenderObject* leaf = findTextLeaf(child, depth, firstOrLast);
             if (leaf)
                 return leaf;
@@ -822,13 +809,6 @@
     renderer->setStyleInternal(style.release());
 }
 
-bool FastTextAutosizer::mightBeWiderOrNarrowerDescendant(const RenderBlock* block)
-{
-    // FIXME: This heuristic may need to be expanded to other ways a block can be wider or narrower
-    //        than its parent containing block.
-    return block->style() && block->style()->width().isSpecified();
-}
-
 bool FastTextAutosizer::isWiderOrNarrowerDescendant(Cluster* cluster)
 {
     if (!cluster->m_parent || !mightBeWiderOrNarrowerDescendant(cluster->m_root))
@@ -930,13 +910,6 @@
     return *m_blocksForFingerprint.get(fingerprint);
 }
 
-RenderObject* FastTextAutosizer::nextChildSkippingChildrenOfBlocks(const RenderObject* current, const RenderObject* stayWithin)
-{
-    if (current == stayWithin || !current->isRenderBlock())
-        return current->nextInPreOrder(stayWithin);
-    return current->nextInPreOrderAfterChildren(stayWithin);
-}
-
 FastTextAutosizer::LayoutScope::LayoutScope(RenderBlock* block)
     : m_textAutosizer(block->document().fastTextAutosizer())
     , m_block(block)
diff --git a/Source/core/rendering/FastTextAutosizer.h b/Source/core/rendering/FastTextAutosizer.h
index 37a5447..df7b04c 100644
--- a/Source/core/rendering/FastTextAutosizer.h
+++ b/Source/core/rendering/FastTextAutosizer.h
@@ -212,7 +212,6 @@
     float widthFromBlock(const RenderBlock*);
     float multiplierFromBlock(const RenderBlock*);
     void applyMultiplier(RenderObject*, float);
-    bool mightBeWiderOrNarrowerDescendant(const RenderBlock*);
     bool isWiderOrNarrowerDescendant(Cluster*);
     bool isLayoutRoot(const RenderBlock*) const;
 
diff --git a/Source/core/rendering/ImageQualityController.cpp b/Source/core/rendering/ImageQualityController.cpp
index c9bdae7..e69b1cf 100644
--- a/Source/core/rendering/ImageQualityController.cpp
+++ b/Source/core/rendering/ImageQualityController.cpp
@@ -60,6 +60,21 @@
     }
 }
 
+InterpolationQuality ImageQualityController::chooseInterpolationQuality(GraphicsContext* context, RenderObject* object, Image* image, const void* layer, const LayoutSize& layoutSize)
+{
+    if (InterpolationDefault == InterpolationLow)
+        return InterpolationLow;
+
+    if (shouldPaintAtLowQuality(context, object, image, layer, layoutSize))
+        return InterpolationLow;
+
+    // For images that are potentially animated we paint them at medium quality.
+    if (image && image->maybeAnimated())
+        return InterpolationMedium;
+
+    return InterpolationDefault;
+}
+
 ImageQualityController::~ImageQualityController()
 {
     // This will catch users of ImageQualityController that forget to call cleanUp.
@@ -137,10 +152,6 @@
     if (object->style()->imageRendering() == ImageRenderingOptimizeContrast)
         return true;
 
-    // For images that are potentially animated we paint them at low quality.
-    if (image->maybeAnimated())
-        return true;
-
     // Look ourselves up in the hashtables.
     ObjectLayerSizeMap::iterator i = m_objectLayerSizeMap.find(object);
     LayerSizeMap* innerMap = i != m_objectLayerSizeMap.end() ? &i->value : 0;
diff --git a/Source/core/rendering/ImageQualityController.h b/Source/core/rendering/ImageQualityController.h
index a9e8b10..7154428 100644
--- a/Source/core/rendering/ImageQualityController.h
+++ b/Source/core/rendering/ImageQualityController.h
@@ -53,11 +53,12 @@
 
     static void remove(RenderObject*);
 
-    bool shouldPaintAtLowQuality(GraphicsContext*, RenderObject*, Image*, const void* layer, const LayoutSize&);
+    InterpolationQuality chooseInterpolationQuality(GraphicsContext*, RenderObject*, Image*, const void* layer, const LayoutSize&);
 
 private:
     ImageQualityController();
 
+    bool shouldPaintAtLowQuality(GraphicsContext*, RenderObject*, Image*, const void* layer, const LayoutSize&);
     void removeLayer(RenderObject*, LayerSizeMap* innerMap, const void* layer);
     void set(RenderObject*, LayerSizeMap* innerMap, const void* layer, const LayoutSize&);
     void objectDestroyed(RenderObject*);
diff --git a/Source/core/rendering/RenderBlock.cpp b/Source/core/rendering/RenderBlock.cpp
index 5a02765..f5ad896 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -4027,9 +4027,9 @@
         || charCategory == Punctuation_Other;
 }
 
-static inline bool shouldSkipForFirstLetter(UChar c)
+static inline bool isSpaceForFirstLetter(UChar c)
 {
-    return isSpaceOrNewline(c) || c == noBreakSpace || isPunctuationForFirstLetter(c);
+    return isSpaceOrNewline(c) || c == noBreakSpace;
 }
 
 static inline RenderObject* findFirstLetterBlock(RenderBlock* start)
@@ -4108,31 +4108,34 @@
 static inline unsigned firstLetterLength(const String& text)
 {
     unsigned length = 0;
+    unsigned textLength = text.length();
 
-    // Account for leading spaces and punctuation.
-    while (length < text.length() && shouldSkipForFirstLetter((text)[length]))
+    // Account for leading spaces first.
+    while (length < textLength && isSpaceForFirstLetter(text[length]))
         length++;
 
-    // Bail if we didn't find a letter
-    if (text.length() && length == text.length())
+    // Now account for leading punctuation.
+    while (length < textLength && isPunctuationForFirstLetter(text[length]))
+        length++;
+
+    // Bail if we didn't find a letter before the end of the text or before a space.
+    if (isSpaceForFirstLetter(text[length]) || (textLength && length == textLength))
         return 0;
 
-    // Account for first letter.
+    // Account the next character for first letter.
     length++;
 
-    // Keep looking for whitespace and allowed punctuation, but avoid
-    // accumulating just whitespace into the :first-letter.
-    for (unsigned scanLength = length; scanLength < text.length(); ++scanLength) {
-        UChar c = (text)[scanLength];
+    // Keep looking allowed punctuation for the :first-letter.
+    for (unsigned scanLength = length; scanLength < textLength; ++scanLength) {
+        UChar c = text[scanLength];
 
-        if (!shouldSkipForFirstLetter(c))
+        if (!isPunctuationForFirstLetter(c))
             break;
 
-        if (isPunctuationForFirstLetter(c))
-            length = scanLength + 1;
+        length = scanLength + 1;
     }
 
-    // FIXME: If text.length() is 0, length may still be 1!
+    // FIXME: If textLength is 0, length may still be 1!
     return length;
 }
 
diff --git a/Source/core/rendering/RenderBlock.h b/Source/core/rendering/RenderBlock.h
index b11db74..86ff13e 100644
--- a/Source/core/rendering/RenderBlock.h
+++ b/Source/core/rendering/RenderBlock.h
@@ -120,12 +120,18 @@
 
     void addPercentHeightDescendant(RenderBox*);
     static void removePercentHeightDescendant(RenderBox*);
-    TrackedRendererListHashSet* percentHeightDescendants() const;
     static bool hasPercentHeightContainerMap();
     static bool hasPercentHeightDescendant(RenderBox*);
     static void clearPercentHeightDescendantsFrom(RenderBox*);
     static void removePercentHeightDescendantIfNeeded(RenderBox*);
 
+    TrackedRendererListHashSet* percentHeightDescendants() const;
+    bool hasPercentHeightDescendants() const
+    {
+        TrackedRendererListHashSet* descendants = percentHeightDescendants();
+        return descendants && !descendants->isEmpty();
+    }
+
     void setHasMarkupTruncation(bool b) { m_hasMarkupTruncation = b; }
     bool hasMarkupTruncation() const { return m_hasMarkupTruncation; }
 
diff --git a/Source/core/rendering/RenderBlockFlow.cpp b/Source/core/rendering/RenderBlockFlow.cpp
index 2ae2cbd..08ca3ee 100644
--- a/Source/core/rendering/RenderBlockFlow.cpp
+++ b/Source/core/rendering/RenderBlockFlow.cpp
@@ -251,7 +251,7 @@
         }
     } else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
         // Now that we know the intrinsic height of the columns, we have to rebalance them.
-        columnHeight = max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf((float)layoutOverflowLogicalBottom / desiredColumnCount));
+        columnHeight = max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf(layoutOverflowLogicalBottom.toFloat() / desiredColumnCount));
     }
 
     if (columnHeight && columnHeight != pageLogicalHeight) {
@@ -386,7 +386,7 @@
             return false;
         }
 
-        setColumnCountAndHeight(ceilf((float)layoutOverflowLogicalBottom / pageLogicalHeight), pageLogicalHeight);
+        setColumnCountAndHeight(ceilf(layoutOverflowLogicalBottom.toFloat() / pageLogicalHeight.toFloat()), pageLogicalHeight.toFloat());
     }
 
     if (shouldBreakAtLineToAvoidWidow()) {
@@ -1326,7 +1326,7 @@
     // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
     // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
     // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
-    if ((document().inQuirksMode() && hasMarginBeforeQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
+    if ((document().inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
         return;
 
     // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
@@ -2708,12 +2708,6 @@
     return logicalRight;
 }
 
-/*template <typename CharacterType>
-static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
-{
-    return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
-}*/
-
 template <typename CharacterType>
 static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
 {
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index 4b2f02d..859507d 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -353,30 +353,8 @@
 
 bool RenderBox::canDetermineWidthWithoutLayout() const
 {
-    // FIXME: This optimization is incorrect as written.
-    // We need to be able to opt-in to this behavior only when
-    // it's guarentted correct.
-    // Until then disabling this optimization to be safe.
+    // FIXME: Remove function and callers.
     return false;
-
-    // FIXME: There are likely many subclasses of RenderBlockFlow which
-    // cannot determine their layout just from style!
-    // Perhaps we should create a "PlainRenderBlockFlow"
-    // and move this optimization there?
-    if (!isRenderBlockFlow()
-        // Flexbox items can be expanded beyond their width.
-        || isFlexItemIncludingDeprecated()
-        // Table Layout controls cell size and can expand beyond width.
-        || isTableCell())
-        return false;
-
-    RenderStyle* style = this->style();
-    return style->width().isFixed()
-        && style->minWidth().isFixed()
-        && (style->maxWidth().isUndefined() || style->maxWidth().isFixed())
-        && style->paddingLeft().isFixed()
-        && style->paddingRight().isFixed()
-        && style->boxSizing() == CONTENT_BOX;
 }
 
 LayoutUnit RenderBox::fixedOffsetWidth() const
@@ -2714,8 +2692,8 @@
         skippedAutoHeightContainingBlock = true;
         containingBlockChild = cb;
         cb = cb->containingBlock();
-        cb->addPercentHeightDescendant(const_cast<RenderBox*>(this));
     }
+    cb->addPercentHeightDescendant(const_cast<RenderBox*>(this));
 
     RenderStyle* cbstyle = cb->style();
 
@@ -2867,10 +2845,10 @@
         case Calculated:
         {
             RenderObject* cb = isOutOfFlowPositioned() ? container() : containingBlock();
-            while (cb->isAnonymous()) {
+            while (cb->isAnonymous())
                 cb = cb->containingBlock();
+            if (cb->isRenderBlock())
                 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
-            }
 
             // FIXME: This calculation is not patched for block-flow yet.
             // https://bugs.webkit.org/show_bug.cgi?id=46500
diff --git a/Source/core/rendering/RenderBox.h b/Source/core/rendering/RenderBox.h
index 39c943a..399e3cf 100644
--- a/Source/core/rendering/RenderBox.h
+++ b/Source/core/rendering/RenderBox.h
@@ -23,6 +23,7 @@
 #ifndef RenderBox_h
 #define RenderBox_h
 
+#include "core/animation/ActiveAnimations.h"
 #include "core/rendering/RenderBoxModelObject.h"
 #include "core/rendering/RenderOverflow.h"
 #include "core/rendering/shapes/ShapeOutsideInfo.h"
@@ -71,7 +72,7 @@
     // position:static elements that are not flex-items get their z-index coerced to auto.
     virtual LayerType layerTypeRequired() const OVERRIDE
     {
-        if (isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns() || !style()->hasAutoZIndex() || style()->hasWillChangeCompositingHint() || style()->hasWillChangeGpuRasterizationHint())
+        if (isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns() || !style()->hasAutoZIndex() || style()->hasWillChangeCompositingHint() || style()->hasWillChangeGpuRasterizationHint() || shouldCompositeForActiveAnimations(*this))
             return NormalLayer;
         if (hasOverflowClip())
             return OverflowClipLayer;
diff --git a/Source/core/rendering/RenderBoxModelObject.cpp b/Source/core/rendering/RenderBoxModelObject.cpp
index dfa132b..22b207c 100644
--- a/Source/core/rendering/RenderBoxModelObject.cpp
+++ b/Source/core/rendering/RenderBoxModelObject.cpp
@@ -100,9 +100,9 @@
     return view()->compositor()->hasAcceleratedCompositing();
 }
 
-bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
+InterpolationQuality RenderBoxModelObject::chooseInterpolationQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
 {
-    return ImageQualityController::imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
+    return ImageQualityController::imageQualityController()->chooseInterpolationQuality(context, this, image, layer, size);
 }
 
 RenderBoxModelObject::RenderBoxModelObject(ContainerNode* node)
@@ -702,11 +702,14 @@
             CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op;
             RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
             RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
-            bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
+            InterpolationQuality interpolationQuality = chooseInterpolationQuality(context, image.get(), bgLayer, geometry.tileSize());
             if (bgLayer->maskSourceType() == MaskLuminance)
                 context->setColorFilter(ColorFilterLuminanceToAlpha);
+            InterpolationQuality previousInterpolationQuality = context->imageInterpolationQuality();
+            context->setImageInterpolationQuality(interpolationQuality);
             context->drawTiledImage(image.get(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(),
-                compositeOp, useLowQualityScaling, bgLayer->blendMode(), geometry.spaceSize());
+                compositeOp, bgLayer->blendMode(), geometry.spaceSize());
+            context->setImageInterpolationQuality(previousInterpolationQuality);
         }
     }
 
@@ -2031,7 +2034,7 @@
     const LayoutRect& outerRect = outerBorder.rect();
     const LayoutRect& innerRect = innerBorder.rect();
 
-    FloatPoint centerPoint(innerRect.location().x() + static_cast<float>(innerRect.width()) / 2, innerRect.location().y() + static_cast<float>(innerRect.height()) / 2);
+    FloatPoint centerPoint(innerRect.location().x().toFloat() + innerRect.width().toFloat() / 2, innerRect.location().y().toFloat() + innerRect.height().toFloat() / 2);
 
     // For each side, create a quad that encompasses all parts of that side that may draw,
     // including areas inside the innerBorder.
diff --git a/Source/core/rendering/RenderBoxModelObject.h b/Source/core/rendering/RenderBoxModelObject.h
index 9eb4384..6a94808 100644
--- a/Source/core/rendering/RenderBoxModelObject.h
+++ b/Source/core/rendering/RenderBoxModelObject.h
@@ -24,6 +24,7 @@
 #ifndef RenderBoxModelObject_h
 #define RenderBoxModelObject_h
 
+#include "core/animation/ActiveAnimations.h"
 #include "core/rendering/RenderLayerModelObject.h"
 #include "core/rendering/style/ShadowData.h"
 #include "platform/geometry/LayoutRect.h"
@@ -89,7 +90,7 @@
 
     virtual LayerType layerTypeRequired() const OVERRIDE
     {
-        if (isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns() || style()->hasWillChangeCompositingHint() || style()->hasWillChangeGpuRasterizationHint())
+        if (isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns() || style()->hasWillChangeCompositingHint() || style()->hasWillChangeGpuRasterizationHint() || shouldCompositeForActiveAnimations(*this))
             return NormalLayer;
 
         return NoLayer;
@@ -259,7 +260,7 @@
     RoundedRect backgroundRoundedRectAdjustedForBleedAvoidance(GraphicsContext*, const LayoutRect&, BackgroundBleedAvoidance, InlineFlowBox*, const LayoutSize&, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const;
     LayoutRect borderInnerRectAdjustedForBleedAvoidance(GraphicsContext*, const LayoutRect&, BackgroundBleedAvoidance) const;
 
-    bool shouldPaintAtLowQuality(GraphicsContext*, Image*, const void*, const LayoutSize&);
+    InterpolationQuality chooseInterpolationQuality(GraphicsContext*, Image*, const void*, const LayoutSize&);
 
     RenderBoxModelObject* continuation() const;
     void setContinuation(RenderBoxModelObject*);
diff --git a/Source/core/rendering/RenderEmbeddedObject.cpp b/Source/core/rendering/RenderEmbeddedObject.cpp
index ff57118..2db078f 100644
--- a/Source/core/rendering/RenderEmbeddedObject.cpp
+++ b/Source/core/rendering/RenderEmbeddedObject.cpp
@@ -28,6 +28,7 @@
 #include "HTMLNames.h"
 #include "core/frame/LocalFrame.h"
 #include "core/html/HTMLIFrameElement.h"
+#include "core/html/HTMLPlugInElement.h"
 #include "core/page/Page.h"
 #include "core/frame/Settings.h"
 #include "core/plugins/PluginView.h"
@@ -109,7 +110,7 @@
 void RenderEmbeddedObject::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     Element* element = toElement(node());
-    if (!element || !element->isPluginElement())
+    if (!isHTMLPlugInElement(element))
         return;
 
     RenderPart::paintContents(paintInfo, paintOffset);
diff --git a/Source/core/rendering/RenderHTMLCanvas.cpp b/Source/core/rendering/RenderHTMLCanvas.cpp
index f2b67c7..8e5ad0b 100644
--- a/Source/core/rendering/RenderHTMLCanvas.cpp
+++ b/Source/core/rendering/RenderHTMLCanvas.cpp
@@ -73,8 +73,13 @@
         paintInfo.context->clip(pixelSnappedIntRect(contentRect));
     }
 
-    bool useLowQualityScale = style()->imageRendering() == ImageRenderingOptimizeContrast;
-    toHTMLCanvasElement(node())->paint(context, paintRect, useLowQualityScale);
+    // FIXME: InterpolationNone should be used if ImageRenderingOptimizeContrast is set.
+    // See bug for more details: crbug.com/353716.
+    InterpolationQuality interpolationQuality = style()->imageRendering() == ImageRenderingOptimizeContrast ? InterpolationLow : CanvasDefaultInterpolationQuality;
+    InterpolationQuality previousInterpolationQuality = context->imageInterpolationQuality();
+    context->setImageInterpolationQuality(interpolationQuality);
+    toHTMLCanvasElement(node())->paint(context, paintRect);
+    context->setImageInterpolationQuality(previousInterpolationQuality);
 
     if (clip)
         context->restore();
diff --git a/Source/core/rendering/RenderImage.cpp b/Source/core/rendering/RenderImage.cpp
index 0730452..02bed7a 100644
--- a/Source/core/rendering/RenderImage.cpp
+++ b/Source/core/rendering/RenderImage.cpp
@@ -467,10 +467,13 @@
     HTMLImageElement* imageElt = isHTMLImageElement(node()) ? toHTMLImageElement(node()) : 0;
     CompositeOperator compositeOperator = imageElt ? imageElt->compositeOperator() : CompositeSourceOver;
     Image* image = m_imageResource->image().get();
-    bool useLowQualityScaling = shouldPaintAtLowQuality(context, image, image, alignedRect.size());
+    InterpolationQuality interpolationQuality = chooseInterpolationQuality(context, image, image, alignedRect.size());
 
     InspectorInstrumentation::willPaintImage(this);
-    context->drawImage(m_imageResource->image(alignedRect.width(), alignedRect.height()).get(), alignedRect, compositeOperator, shouldRespectImageOrientation(), useLowQualityScaling);
+    InterpolationQuality previousInterpolationQuality = context->imageInterpolationQuality();
+    context->setImageInterpolationQuality(interpolationQuality);
+    context->drawImage(m_imageResource->image(alignedRect.width(), alignedRect.height()).get(), alignedRect, compositeOperator, shouldRespectImageOrientation());
+    context->setImageInterpolationQuality(previousInterpolationQuality);
     InspectorInstrumentation::didPaintImage(this);
 }
 
diff --git a/Source/core/rendering/RenderInline.h b/Source/core/rendering/RenderInline.h
index 947492e..3c5a1a0 100644
--- a/Source/core/rendering/RenderInline.h
+++ b/Source/core/rendering/RenderInline.h
@@ -23,6 +23,7 @@
 #ifndef RenderInline_h
 #define RenderInline_h
 
+#include "core/animation/ActiveAnimations.h"
 #include "core/rendering/InlineFlowBox.h"
 #include "core/rendering/RenderBoxModelObject.h"
 #include "core/rendering/RenderLineBoxList.h"
@@ -135,7 +136,7 @@
 
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE FINAL;
 
-    virtual LayerType layerTypeRequired() const OVERRIDE { return isInFlowPositioned() || createsGroup() || hasClipPath() ? NormalLayer : NoLayer; }
+    virtual LayerType layerTypeRequired() const OVERRIDE { return isInFlowPositioned() || createsGroup() || hasClipPath() || shouldCompositeForActiveAnimations(*this) ? NormalLayer : NoLayer; }
 
     virtual LayoutUnit offsetLeft() const OVERRIDE FINAL;
     virtual LayoutUnit offsetTop() const OVERRIDE FINAL;
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index ebda58d..ef40889 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -165,6 +165,7 @@
     removeFilterInfoIfNeeded();
 
     if (groupedMapping()) {
+        DisableCompositingQueryAsserts disabler;
         groupedMapping()->removeRenderLayerFromSquashingGraphicsLayer(this);
         setGroupedMapping(0);
     }
@@ -1062,8 +1063,7 @@
     const LayoutRect borderBox = toRenderBox(renderer())->borderBoxRect();
     RenderStyle* style = renderer()->style();
 
-    return FloatPoint(floatValueForLength(style->perspectiveOriginX(), borderBox.width()),
-                      floatValueForLength(style->perspectiveOriginY(), borderBox.height()));
+    return FloatPoint(floatValueForLength(style->perspectiveOriginX(), borderBox.width().toFloat()), floatValueForLength(style->perspectiveOriginY(), borderBox.height().toFloat()));
 }
 
 static inline bool isFixedPositionedContainer(RenderLayer* layer)
diff --git a/Source/core/rendering/RenderLayerRepainter.cpp b/Source/core/rendering/RenderLayerRepainter.cpp
index 7381c8e..141d303 100644
--- a/Source/core/rendering/RenderLayerRepainter.cpp
+++ b/Source/core/rendering/RenderLayerRepainter.cpp
@@ -74,6 +74,7 @@
         LayoutRect oldRepaintRect = m_repaintRect;
         LayoutRect oldOutlineBox = m_outlineBox;
         computeRepaintRects(repaintContainer, geometryMap);
+        shouldCheckForRepaint &= shouldRepaintLayer();
 
         // FIXME: Should ASSERT that value calculated for m_outlineBox using the cached offset is the same
         // as the value not using the cached offset, but we can't due to https://bugs.webkit.org/show_bug.cgi?id=37048
@@ -83,7 +84,7 @@
                     m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldRepaintRect));
                     if (m_repaintRect != oldRepaintRect)
                         m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_repaintRect));
-                } else if (shouldRepaintAfterLayout()) {
+                } else {
                     m_renderer->repaintAfterLayoutIfNeeded(repaintContainer, m_renderer->selfNeedsLayout(), oldRepaintRect, oldOutlineBox, &m_repaintRect, &m_outlineBox);
                 }
             }
@@ -121,14 +122,13 @@
         layer->repainter().computeRepaintRectsIncludingDescendants();
 }
 
-inline bool RenderLayerRepainter::shouldRepaintAfterLayout() const
+inline bool RenderLayerRepainter::shouldRepaintLayer() const
 {
-    if (m_repaintStatus == NeedsNormalRepaint)
+    if (m_repaintStatus != NeedsFullRepaintForPositionedMovementLayout)
         return true;
 
     // Composited layers that were moved during a positioned movement only
     // layout, don't need to be repainted. They just need to be recomposited.
-    ASSERT(m_repaintStatus == NeedsFullRepaintForPositionedMovementLayout);
     return m_renderer->compositingState() != PaintsIntoOwnBacking;
 }
 
diff --git a/Source/core/rendering/RenderLayerRepainter.h b/Source/core/rendering/RenderLayerRepainter.h
index ffc08ee..172e170 100644
--- a/Source/core/rendering/RenderLayerRepainter.h
+++ b/Source/core/rendering/RenderLayerRepainter.h
@@ -53,7 +53,7 @@
 enum RepaintStatus {
     NeedsNormalRepaint = 0,
     NeedsFullRepaint = 1 << 0,
-    NeedsFullRepaintForPositionedMovementLayout = 1 << 1
+    NeedsFullRepaintForPositionedMovementLayout = NeedsFullRepaint | 1 << 1
 };
 
 class RenderGeometryMap;
@@ -86,7 +86,7 @@
     void setFilterBackendNeedsRepaintingInRect(const LayoutRect&);
 
 private:
-    bool shouldRepaintAfterLayout() const;
+    bool shouldRepaintLayer() const;
 
     void clearRepaintRects();
 
diff --git a/Source/core/rendering/RenderListBox.cpp b/Source/core/rendering/RenderListBox.cpp
index 8918b0a..62ea8e3 100644
--- a/Source/core/rendering/RenderListBox.cpp
+++ b/Source/core/rendering/RenderListBox.cpp
@@ -426,7 +426,7 @@
     applyTextTransform(style(), itemText, ' ');
 
     Color textColor = element->renderStyle() ? resolveColor(element->renderStyle(), CSSPropertyColor) : resolveColor(CSSPropertyColor);
-    if (isOptionElement && toHTMLOptionElement(*element).selected()) {
+    if (isOptionElement && ((toHTMLOptionElement(*element).selected() && select->suggestedIndex() < 0) || listIndex == select->suggestedIndex())) {
         if (frame()->selection().isFocusedAndActive() && document().focusedElement() == node())
             textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor();
         // Honor the foreground color for disabled items
@@ -460,7 +460,7 @@
     HTMLElement* element = listItems[listIndex];
 
     Color backColor;
-    if (isHTMLOptionElement(*element) && toHTMLOptionElement(*element).selected()) {
+    if (isHTMLOptionElement(*element) && ((toHTMLOptionElement(*element).selected() && selectElement()->suggestedIndex() < 0) || listIndex == selectElement()->suggestedIndex())) {
         if (frame()->selection().isFocusedAndActive() && document().focusedElement() == node())
             backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor();
         else
@@ -631,13 +631,6 @@
     return ScrollableArea::scroll(direction, granularity, multiplier);
 }
 
-void RenderListBox::valueChanged(unsigned listIndex)
-{
-    HTMLSelectElement* element = selectElement();
-    element->setSelectedIndex(element->listToOptionIndex(listIndex));
-    element->dispatchFormControlChangeEvent();
-}
-
 int RenderListBox::scrollSize(ScrollbarOrientation orientation) const
 {
     return orientation == VerticalScrollbar ? (numItems() - numVisibleItems()) : 0;
diff --git a/Source/core/rendering/RenderListBox.h b/Source/core/rendering/RenderListBox.h
index c824b7c..efc47aa 100644
--- a/Source/core/rendering/RenderListBox.h
+++ b/Source/core/rendering/RenderListBox.h
@@ -138,7 +138,6 @@
     void destroyScrollbar();
 
     LayoutUnit itemHeight() const;
-    void valueChanged(unsigned listIndex);
     int numVisibleItems() const;
     int numItems() const;
     LayoutUnit listHeight() const;
diff --git a/Source/core/rendering/RenderMenuList.cpp b/Source/core/rendering/RenderMenuList.cpp
index 5b28b71..5d7457a 100644
--- a/Source/core/rendering/RenderMenuList.cpp
+++ b/Source/core/rendering/RenderMenuList.cpp
@@ -201,10 +201,14 @@
         m_optionsChanged = false;
     }
 
-    if (m_popupIsVisible)
+    if (m_popupIsVisible) {
         m_popup->updateFromElement();
-    else
-        setTextFromOption(selectElement()->selectedIndex());
+    } else {
+        if (selectElement()->suggestedIndex() >= 0)
+            setTextFromOption(selectElement()->suggestedIndex());
+        else
+            setTextFromOption(selectElement()->selectedIndex());
+    }
 }
 
 void RenderMenuList::setTextFromOption(int optionIndex)
diff --git a/Source/core/rendering/RenderMultiColumnSet.cpp b/Source/core/rendering/RenderMultiColumnSet.cpp
index 9b1394b..697fab4 100644
--- a/Source/core/rendering/RenderMultiColumnSet.cpp
+++ b/Source/core/rendering/RenderMultiColumnSet.cpp
@@ -292,7 +292,7 @@
     if (!logicalHeightInColumns)
         return 1;
 
-    unsigned count = ceil(static_cast<float>(logicalHeightInColumns) / computedColumnHeight());
+    unsigned count = ceil(logicalHeightInColumns.toFloat() / computedColumnHeight().toFloat());
     ASSERT(count >= 1);
     return count;
 }
@@ -331,7 +331,7 @@
     }
 
     // Just divide by the column height to determine the correct column.
-    return static_cast<float>(offset - flowThreadLogicalTop) / computedColumnHeight();
+    return (offset - flowThreadLogicalTop).toFloat() / computedColumnHeight().toFloat();
 }
 
 LayoutRect RenderMultiColumnSet::flowThreadPortionRectAt(unsigned index) const
diff --git a/Source/core/rendering/RenderMultiColumnSet.h b/Source/core/rendering/RenderMultiColumnSet.h
index da7a783..d858b23 100644
--- a/Source/core/rendering/RenderMultiColumnSet.h
+++ b/Source/core/rendering/RenderMultiColumnSet.h
@@ -161,7 +161,7 @@
 
         // Return the column height that this content run would require, considering the implicit
         // breaks assumed so far.
-        LayoutUnit columnLogicalHeight(LayoutUnit startOffset) const { return ceilf(float(m_breakOffset - startOffset) / float(m_assumedImplicitBreaks + 1)); }
+        LayoutUnit columnLogicalHeight(LayoutUnit startOffset) const { return ceilf((m_breakOffset - startOffset).toFloat() / float(m_assumedImplicitBreaks + 1)); }
 
     private:
         LayoutUnit m_breakOffset; // Flow thread offset where this run ends.
diff --git a/Source/core/rendering/RenderTableCol.cpp b/Source/core/rendering/RenderTableCol.cpp
index 60d548e..1a9d9d7 100644
--- a/Source/core/rendering/RenderTableCol.cpp
+++ b/Source/core/rendering/RenderTableCol.cpp
@@ -60,7 +60,7 @@
 {
     unsigned oldSpan = m_span;
     Node* n = node();
-    if (n && isHTMLTableColElement(*n)) {
+    if (isHTMLTableColElement(n)) {
         HTMLTableColElement& tc = toHTMLTableColElement(*n);
         m_span = tc.span();
     } else
diff --git a/Source/core/rendering/RenderTableRow.h b/Source/core/rendering/RenderTableRow.h
index 126502a..4cf834b 100644
--- a/Source/core/rendering/RenderTableRow.h
+++ b/Source/core/rendering/RenderTableRow.h
@@ -105,7 +105,7 @@
 
     virtual LayerType layerTypeRequired() const OVERRIDE
     {
-        if (hasTransform() || hasHiddenBackface() || hasClipPath() || createsGroup() || isStickyPositioned() || style()->hasWillChangeCompositingHint() || style()->hasWillChangeGpuRasterizationHint())
+        if (hasTransform() || hasHiddenBackface() || hasClipPath() || createsGroup() || isStickyPositioned() || style()->hasWillChangeCompositingHint() || style()->hasWillChangeGpuRasterizationHint() || shouldCompositeForActiveAnimations(*this))
             return NormalLayer;
 
         if (hasOverflowClip())
diff --git a/Source/core/rendering/RenderText.cpp b/Source/core/rendering/RenderText.cpp
index 8d6c379..7348910 100644
--- a/Source/core/rendering/RenderText.cpp
+++ b/Source/core/rendering/RenderText.cpp
@@ -930,37 +930,43 @@
     int lastWordBoundary = 0;
     float cachedWordTrailingSpaceWidth[2] = { 0, 0 }; // LTR, RTL
 
-    // 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 firstGlyphLeftOverflow = -1;
 
     bool breakAll = (styleToUse->wordBreak() == BreakAllWordBreak || styleToUse->wordBreak() == BreakWordBreak) && styleToUse->autoWrap();
 
     TextRun textRun(text());
     BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver;
-    BidiStatus status(LTR, false);
-    status.last = status.lastStrong = WTF::Unicode::OtherNeutral;
-    bidiResolver.setStatus(status);
-    bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&textRun, 0));
-    bool hardLineBreak = false;
-    bool reorderRuns = false;
-    bidiResolver.createBidiRunsForLine(TextRunIterator(&textRun, textRun.length()), NoVisualOverride, hardLineBreak, reorderRuns);
 
-    BidiRunList<BidiCharacterRun>& bidiRuns = bidiResolver.runs();
-    BidiCharacterRun* run = bidiRuns.firstRun();
+    BidiCharacterRun* run;
+    TextDirection textDirection = styleToUse->direction();
+    if (isOverride(styleToUse->unicodeBidi())) {
+        run = 0;
+    } else {
+        BidiStatus status(LTR, false);
+        status.last = status.lastStrong = WTF::Unicode::OtherNeutral;
+        bidiResolver.setStatus(status);
+        bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&textRun, 0));
+        bool hardLineBreak = false;
+        bool reorderRuns = false;
+        bidiResolver.createBidiRunsForLine(TextRunIterator(&textRun, textRun.length()), NoVisualOverride, hardLineBreak, reorderRuns);
+        BidiRunList<BidiCharacterRun>& bidiRuns = bidiResolver.runs();
+        run = bidiRuns.firstRun();
+    }
+
     for (int i = 0; i < len; i++) {
         UChar c = uncheckedCharacterAt(i);
 
-        // Treat adjacent runs with the same resolved directionality
-        // (TextDirection as opposed to WTF::Unicode::Direction) as belonging
-        // to the same run to avoid breaking unnecessarily.
-        while (i > run->stop() || (run->next() && run->next()->direction() == run->direction()))
-            run = run->next();
+        if (run) {
+            // Treat adjacent runs with the same resolved directionality
+            // (TextDirection as opposed to WTF::Unicode::Direction) as belonging
+            // to the same run to avoid breaking unnecessarily.
+            while (i > run->stop() || (run->next() && run->next()->direction() == run->direction()))
+                run = run->next();
 
-        ASSERT(run);
-        ASSERT(i <= run->stop());
-        TextDirection textDirection = run->direction();
+            ASSERT(run);
+            ASSERT(i <= run->stop());
+            textDirection = run->direction();
+        }
 
         bool previousCharacterIsSpace = isSpace;
         bool isNewline = false;
@@ -1024,7 +1030,8 @@
         }
 
         // Terminate word boundary at bidi run boundary.
-        j = min(j, run->stop() + 1);
+        if (run)
+            j = min(j, run->stop() + 1);
         int wordLen = j - i;
         if (wordLen) {
             bool isSpace = (j < len) && c == ' ';
@@ -1048,8 +1055,6 @@
                     currMinWidth += hyphenWidth(this, f, textDirection);
             }
 
-            maxWordWidth = max(maxWordWidth, w);
-
             if (firstGlyphLeftOverflow < 0)
                 firstGlyphLeftOverflow = glyphOverflow.left;
             currMinWidth += w;
@@ -1122,7 +1127,8 @@
             lastWordBoundary++;
         }
     }
-    bidiRuns.deleteRuns();
+    if (run)
+        bidiResolver.runs().deleteRuns();
 
     if (firstGlyphLeftOverflow > 0)
         glyphOverflow.left = firstGlyphLeftOverflow;
diff --git a/Source/core/rendering/TextAutosizer.cpp b/Source/core/rendering/TextAutosizer.cpp
index 1b836df..7e1b350 100644
--- a/Source/core/rendering/TextAutosizer.cpp
+++ b/Source/core/rendering/TextAutosizer.cpp
@@ -169,8 +169,20 @@
     return combinedHashValue;
 }
 
+bool TextAutosizer::isApplicable() const
+{
+    return m_document->settings()
+        && m_document->settings()->textAutosizingEnabled()
+        && m_document->page()
+        && m_document->page()->mainFrame()
+        && m_document->page()->mainFrame()->loader().stateMachine()->committedFirstRealDocumentLoad();
+}
+
 void TextAutosizer::recalculateMultipliers()
 {
+    if (!isApplicable())
+        return;
+
     RenderObject* renderer = m_document->renderer();
     while (renderer) {
         if (renderer->style() && renderer->style()->textAutosizingMultiplier() != 1)
@@ -182,20 +194,13 @@
 bool TextAutosizer::processSubtree(RenderObject* layoutRoot)
 {
     TRACE_EVENT0("webkit", "TextAutosizer: check if needed");
-    if (!m_document->settings() || layoutRoot->view()->document().printing() || !m_document->page())
-        return false;
 
-    bool textAutosizingEnabled = m_document->settings()->textAutosizingEnabled();
-    if (!textAutosizingEnabled)
+    if (!isApplicable() || layoutRoot->view()->document().printing())
         return false;
 
     LocalFrame* mainFrame = m_document->page()->mainFrame();
     TextAutosizingWindowInfo windowInfo;
 
-    if (!mainFrame->loader().stateMachine()->committedFirstRealDocumentLoad())
-        return false;
-
-
     // Window area, in logical (density-independent) pixels.
     windowInfo.windowSize = m_document->settings()->textAutosizingWindowSizeOverride();
     if (windowInfo.windowSize.isEmpty())
diff --git a/Source/core/rendering/TextAutosizer.h b/Source/core/rendering/TextAutosizer.h
index 8b8b51a..0f69e25 100644
--- a/Source/core/rendering/TextAutosizer.h
+++ b/Source/core/rendering/TextAutosizer.h
@@ -83,6 +83,7 @@
 
     explicit TextAutosizer(Document*);
 
+    bool isApplicable() const;
     float clusterMultiplier(WritingMode, const TextAutosizingWindowInfo&, float textWidth) const;
 
     void processClusterInternal(TextAutosizingClusterInfo&, RenderBlock* container, RenderObject* subtreeRoot, const TextAutosizingWindowInfo&, float multiplier);
diff --git a/Source/core/rendering/compositing/CompositedLayerMapping.cpp b/Source/core/rendering/compositing/CompositedLayerMapping.cpp
index 56406ad..2ff29ae 100644
--- a/Source/core/rendering/compositing/CompositedLayerMapping.cpp
+++ b/Source/core/rendering/compositing/CompositedLayerMapping.cpp
@@ -561,11 +561,19 @@
     return pixelSnappedIntRect(result);
 }
 
+static LayoutPoint computeOffsetFromCompositedAncestor(const RenderLayer* layer, const RenderLayer* compositedAncestor)
+{
+    LayoutPoint offset;
+    layer->convertToLayerCoords(compositedAncestor, offset);
+    if (compositedAncestor)
+        offset.move(compositedAncestor->compositedLayerMapping()->subpixelAccumulation());
+    return offset;
+}
+
 void CompositedLayerMapping::adjustBoundsForSubPixelAccumulation(const RenderLayer* compositedAncestor, IntRect& localBounds, IntRect& relativeBounds, IntPoint& delta)
 {
     LayoutRect localRawCompositingBounds = compositedBounds();
-    LayoutPoint rawDelta;
-    m_owningLayer.convertToLayerCoords(compositedAncestor, rawDelta);
+    LayoutPoint rawDelta = computeOffsetFromCompositedAncestor(&m_owningLayer, compositedAncestor);
     delta = flooredIntPoint(rawDelta);
     m_subpixelAccumulation = toLayoutSize(rawDelta).fraction();
     RELEASE_ASSERT(m_subpixelAccumulation.width() < 1 && m_subpixelAccumulation.height() < 1);
@@ -598,13 +606,16 @@
 
     // The totalSquashBounds is positioned with respect to m_owningLayer of this CompositedLayerMapping.
     // But the squashingLayer needs to be positioned with respect to the ancestor CompositedLayerMapping.
-    // The conversion between m_owningLayer and the ancestor CLM is already computed in the caller as |delta|.
-    // FIXME: probably not the right place to round from LayoutPoint to IntPoint?
-    IntPoint squashLayerPosition = pixelSnappedIntRect(totalSquashBounds).location();
-    squashLayerPosition.moveBy(delta);
+    // The conversion between m_owningLayer and the ancestor CLM is already computed in the caller as
+    // |delta| + |m_subpixelAccumulation|.
+    LayoutPoint rawDelta = delta + m_subpixelAccumulation;
+    totalSquashBounds.moveBy(rawDelta);
+    IntRect squashLayerBounds = enclosingIntRect(totalSquashBounds);
+    IntPoint squashLayerOrigin = squashLayerBounds.location();
+    LayoutPoint squashLayerOriginInOwningLayerSpace = LayoutPoint(squashLayerOrigin - rawDelta);
 
-    m_squashingLayer->setPosition(squashLayerPosition);
-    m_squashingLayer->setSize(totalSquashBounds.size());
+    m_squashingLayer->setPosition(squashLayerBounds.location());
+    m_squashingLayer->setSize(squashLayerBounds.size());
 
     // Now that the squashing bounds are known, we can convert the RenderLayer painting offsets
     // from CLM owning layer space to the squashing layer space.
@@ -613,11 +624,15 @@
     // the squashed RenderLayer described w.r.t. m_squashingLayer's origin. For this purpose we already cached
     // offsetFromSquashingCLM before, which describes where the squashed RenderLayer is located w.r.t.
     // m_owningLayer. So we just need to convert that point from m_owningLayer space to m_squashingLayer
-    // space. This is simply done by subtracing totalSquashBounds... but then the offset overall needs to be
-    // negated because that's the direction that the painting code expects the offset to be.
+    // space. This is simply done by subtracing squashLayerOriginInOwningLayerSpace, but then the offset
+    // overall needs to be negated because that's the direction that the painting code expects the
+    // offset to be.
     for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
-        m_squashedLayers[i].offsetFromRenderer = IntSize(-m_squashedLayers[i].offsetFromSquashingCLM.width() + totalSquashBounds.x(),
-            -m_squashedLayers[i].offsetFromSquashingCLM.height() + totalSquashBounds.y());
+        LayoutSize offsetFromSquashLayerOrigin = LayoutPoint(m_squashedLayers[i].offsetFromSquashingCLM) - squashLayerOriginInOwningLayerSpace;
+        m_squashedLayers[i].offsetFromRenderer = -flooredIntSize(offsetFromSquashLayerOrigin);
+        m_squashedLayers[i].subpixelAccumulation = offsetFromSquashLayerOrigin.fraction();
+        ASSERT(m_squashedLayers[i].subpixelAccumulation ==
+            toLayoutSize(computeOffsetFromCompositedAncestor(m_squashedLayers[i].renderLayer, m_squashedLayers[i].renderLayer->ancestorCompositingLayer())).fraction());
 
         // FIXME: find a better design to avoid this redundant value - most likely it will make
         // sense to move the paint task info into RenderLayer's m_compositingProperties.
@@ -668,7 +683,7 @@
     IntRect ancestorCompositingBounds;
     if (compAncestor) {
         ASSERT(compAncestor->hasCompositedLayerMapping());
-        ancestorCompositingBounds = pixelSnappedIntRect(compAncestor->compositedLayerMapping()->compositedBounds());
+        ancestorCompositingBounds = compAncestor->compositedLayerMapping()->pixelSnappedCompositedBounds();
     }
 
     IntRect localCompositingBounds;
@@ -744,13 +759,14 @@
     }
 
     if (m_owningLayer.hasTransform()) {
-        const IntRect borderBox = toRenderBox(renderer())->pixelSnappedBorderBoxRect();
+        const LayoutRect borderBox = toRenderBox(renderer())->borderBoxRect();
 
         // Get layout bounds in the coords of compAncestor to match relativeCompositingBounds.
-        IntRect layerBounds(delta + roundedIntSize(m_subpixelAccumulation), borderBox.size());
+        IntRect layerBounds = pixelSnappedIntRect(toLayoutPoint(m_subpixelAccumulation), borderBox.size());
+        layerBounds.moveBy(delta);
 
         // Update properties that depend on layer dimensions
-        FloatPoint3D transformOrigin = computeTransformOrigin(borderBox);
+        FloatPoint3D transformOrigin = computeTransformOrigin(IntRect(IntPoint(), layerBounds.size()));
         // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
         FloatPoint3D anchor(
             relativeCompositingBounds.width() ? (layerBounds.x() - relativeCompositingBounds.x() + transformOrigin.x()) / relativeCompositingBounds.width()  : 0.5f,
@@ -1900,10 +1916,10 @@
 
     if (!(paintInfo.paintingPhase & GraphicsLayerPaintOverflowContents)) {
         LayoutRect bounds = paintInfo.compositedBounds;
-        bounds.move(m_subpixelAccumulation);
+        bounds.move(paintInfo.subpixelAccumulation);
         dirtyRect.intersect(pixelSnappedIntRect(bounds));
     } else {
-        dirtyRect.move(roundedIntSize(m_subpixelAccumulation));
+        dirtyRect.move(roundedIntSize(paintInfo.subpixelAccumulation));
     }
 
 #ifndef NDEBUG
@@ -1912,7 +1928,7 @@
 
     if (paintInfo.renderLayer->compositingState() != PaintsIntoGroupedBacking) {
         // FIXME: GraphicsLayers need a way to split for RenderRegions.
-        LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, m_subpixelAccumulation);
+        LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, paintInfo.subpixelAccumulation);
         paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags);
 
         ASSERT(!paintInfo.isBackgroundLayer || paintFlags & PaintLayerPaintingRootBackgroundOnly);
@@ -1921,7 +1937,7 @@
             paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags | PaintLayerPaintingOverlayScrollbars);
     } else {
         ASSERT(compositor()->layerSquashingEnabled());
-        LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, LayoutSize());
+        LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, paintInfo.subpixelAccumulation);
         paintInfo.renderLayer->paintLayer(context, paintingInfo, paintFlags);
     }
 
@@ -1970,6 +1986,7 @@
         paintInfo.offsetFromRenderer = graphicsLayer->offsetFromRenderer();
         paintInfo.paintingPhase = paintingPhase;
         paintInfo.isBackgroundLayer = (graphicsLayer == m_backgroundLayer);
+        paintInfo.subpixelAccumulation = m_subpixelAccumulation;
 
         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
         doPaintTask(paintInfo, &context, clip);
@@ -2029,9 +2046,11 @@
     renderer()->node()->document().cssPendingAnimations().notifyCompositorAnimationStarted(monotonicTime);
 }
 
-LayoutRect CompositedLayerMapping::compositedBounds() const
+IntRect CompositedLayerMapping::pixelSnappedCompositedBounds() const
 {
-    return m_compositedBounds;
+    LayoutRect bounds = m_compositedBounds;
+    bounds.move(m_subpixelAccumulation);
+    return pixelSnappedIntRect(bounds);
 }
 
 void CompositedLayerMapping::setCompositedBounds(const LayoutRect& bounds)
@@ -2039,7 +2058,7 @@
     m_compositedBounds = bounds;
 }
 
-bool CompositedLayerMapping::updateSquashingLayerAssignment(RenderLayer* layer, IntSize offsetFromSquashingCLM, size_t nextSquashedLayerIndex)
+bool CompositedLayerMapping::updateSquashingLayerAssignment(RenderLayer* layer, LayoutSize offsetFromSquashingCLM, size_t nextSquashedLayerIndex)
 {
     ASSERT(compositor()->layerSquashingEnabled());
 
diff --git a/Source/core/rendering/compositing/CompositedLayerMapping.h b/Source/core/rendering/compositing/CompositedLayerMapping.h
index a22b28b..dd17905 100644
--- a/Source/core/rendering/compositing/CompositedLayerMapping.h
+++ b/Source/core/rendering/compositing/CompositedLayerMapping.h
@@ -49,10 +49,11 @@
     // an intermediate offset for a squashed RenderLayer, described with respect to the CompositedLayerMapping's
     // owning layer that would eventually have the m_squashingLayer. Once the shared GraphicsLayer's bounds are
     // known, then we can trivially convert this offset to m_squashingLayer's space.
-    IntSize offsetFromSquashingCLM;
+    LayoutSize offsetFromSquashingCLM;
 
     // Offset describing where this squashed RenderLayer paints into the shared GraphicsLayer backing.
     IntSize offsetFromRenderer;
+    LayoutSize subpixelAccumulation;
 
     GraphicsLayerPaintingPhase paintingPhase;
 
@@ -157,7 +158,8 @@
     // Notification from the renderer that its content changed.
     void contentChanged(ContentChangeType);
 
-    LayoutRect compositedBounds() const;
+    LayoutRect compositedBounds() const { return m_compositedBounds; }
+    IntRect pixelSnappedCompositedBounds() const;
     void setCompositedBounds(const LayoutRect&);
     void updateCompositedBounds();
 
@@ -166,7 +168,7 @@
     bool hasUnpositionedOverflowControlsLayers() const;
 
     // Returns true if the assignment actually changed the assigned squashing layer.
-    bool updateSquashingLayerAssignment(RenderLayer*, IntSize offsetFromSquashingCLM, size_t nextSquashedLayerIndex);
+    bool updateSquashingLayerAssignment(RenderLayer*, LayoutSize offsetFromSquashingCLM, size_t nextSquashedLayerIndex);
     void removeRenderLayerFromSquashingGraphicsLayer(const RenderLayer*);
 
     void finishAccumulatingSquashingLayers(size_t nextSquashedLayerIndex);
diff --git a/Source/core/rendering/compositing/RenderLayerCompositor.cpp b/Source/core/rendering/compositing/RenderLayerCompositor.cpp
index ba9ca58..32563e5 100644
--- a/Source/core/rendering/compositing/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/compositing/RenderLayerCompositor.cpp
@@ -648,12 +648,12 @@
     return compositedLayerMappingChanged || nonCompositedReasonChanged;
 }
 
-static IntPoint computeOffsetFromAbsolute(RenderLayer* layer)
+static LayoutPoint computeOffsetFromAbsolute(RenderLayer* layer)
 {
     TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
     layer->renderer()->mapLocalToContainer(0, transformState, ApplyContainerFlip);
     transformState.flatten();
-    return roundedIntPoint(transformState.lastPlanarPoint());
+    return LayoutPoint(transformState.lastPlanarPoint());
 }
 
 bool RenderLayerCompositor::updateSquashingAssignment(RenderLayer* layer, SquashingState& squashingState, const CompositingStateTransitionType compositedLayerUpdate)
@@ -668,9 +668,9 @@
         ASSERT(!layer->hasCompositedLayerMapping());
         ASSERT(squashingState.hasMostRecentMapping);
 
-        IntPoint offsetFromAbsoluteForSquashedLayer = computeOffsetFromAbsolute(layer);
+        LayoutPoint offsetFromAbsoluteForSquashedLayer = computeOffsetFromAbsolute(layer);
 
-        IntSize offsetFromSquashingCLM(offsetFromAbsoluteForSquashedLayer.x() - squashingState.offsetFromAbsoluteForSquashingCLM.x(),
+        LayoutSize offsetFromSquashingCLM(offsetFromAbsoluteForSquashedLayer.x() - squashingState.offsetFromAbsoluteForSquashingCLM.x(),
             offsetFromAbsoluteForSquashedLayer.y() - squashingState.offsetFromAbsoluteForSquashingCLM.y());
 
         bool changedSquashingLayer =
@@ -727,7 +727,14 @@
 bool RenderLayerCompositor::canSquashIntoCurrentSquashingOwner(const RenderLayer* layer, const RenderLayerCompositor::SquashingState& squashingState, const RenderLayer* clippingAncestor)
 {
     ASSERT(clippingAncestor);
-    return clippingAncestor == squashingState.clippingAncestorForMostRecentMapping;
+    if (clippingAncestor != squashingState.clippingAncestorForMostRecentMapping)
+        return false;
+
+    ASSERT(squashingState.hasMostRecentMapping);
+    if (layer->scrollsWithRespectTo(&squashingState.mostRecentMapping->owningLayer()))
+        return false;
+
+    return true;
 }
 
 RenderLayerCompositor::CompositingStateTransitionType RenderLayerCompositor::computeCompositedLayerUpdate(RenderLayer* layer)
@@ -947,15 +954,6 @@
 
     reasonsToComposite |= overlapCompositingReason;
 
-    // If the layer is squashable, but would scroll differently than the
-    // most recent backing that it would squash onto, then don't squash it.
-    // Note that this happens before we know all possible compositing reasons
-    // for this layer, but it's OK because we're just forcing the layer conservatively
-    // to be separately composited rather than squashed, anyway.
-    if (currentRecursionData.m_mostRecentCompositedLayer && requiresSquashing(reasonsToComposite)
-        && layer->scrollsWithRespectTo(currentRecursionData.m_mostRecentCompositedLayer))
-        reasonsToComposite |= CompositingReasonOverlapsWithoutSquashingTarget;
-
     // The children of this layer don't need to composite, unless there is
     // a compositing layer among them, so start by inheriting the compositing
     // ancestor with m_subtreeIsCompositing set to false.
@@ -1140,7 +1138,7 @@
         overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
 }
 
-void RenderLayerCompositor::SquashingState::updateSquashingStateForNewMapping(CompositedLayerMappingPtr newCompositedLayerMapping, bool hasNewCompositedLayerMapping, IntPoint newOffsetFromAbsoluteForSquashingCLM, RenderLayer* newClippingAncestorForMostRecentMapping)
+void RenderLayerCompositor::SquashingState::updateSquashingStateForNewMapping(CompositedLayerMappingPtr newCompositedLayerMapping, bool hasNewCompositedLayerMapping, LayoutPoint newOffsetFromAbsoluteForSquashingCLM, RenderLayer* newClippingAncestorForMostRecentMapping)
 {
     // The most recent backing is done accumulating any more squashing layers.
     if (hasMostRecentMapping)
@@ -1179,7 +1177,7 @@
         clippingAncestor = layer;
 
     if (layerSquashingEnabled() && requiresSquashing(layer->compositingReasons()) && !canSquashIntoCurrentSquashingOwner(layer, squashingState, clippingAncestor))
-        layer->setCompositingReasons(layer->compositingReasons() | CompositingReasonOverlapsWithoutSquashingTarget);
+        layer->setCompositingReasons(layer->compositingReasons() | CompositingReasonNoSquashingTargetFound);
 
     CompositingStateTransitionType compositedLayerUpdate = computeCompositedLayerUpdate(layer);
 
@@ -1207,7 +1205,7 @@
         // At this point, if the layer is to be "separately" composited, then its backing becomes the most recent in paint-order.
         if (layer->compositingState() == PaintsIntoOwnBacking || layer->compositingState() == HasOwnBackingButPaintsIntoAncestor) {
             ASSERT(!requiresSquashing(layer->compositingReasons()));
-            IntPoint offsetFromAbsoluteForSquashingCLM = computeOffsetFromAbsolute(layer);
+            LayoutPoint offsetFromAbsoluteForSquashingCLM = computeOffsetFromAbsolute(layer);
             squashingState.updateSquashingStateForNewMapping(layer->compositedLayerMapping(), layer->hasCompositedLayerMapping(), offsetFromAbsoluteForSquashingCLM, clippingAncestor);
         }
     }
@@ -1340,8 +1338,7 @@
 
 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
 {
-    // Before dumping the layer tree, finish any pending compositing update.
-    updateCompositingLayers();
+    ASSERT(m_renderView.document().lifecycle().state() >= DocumentLifecycle::CompositingClean);
 
     if (!m_rootContentLayer)
         return String();
diff --git a/Source/core/rendering/compositing/RenderLayerCompositor.h b/Source/core/rendering/compositing/RenderLayerCompositor.h
index 00cfd63..e04c4b2 100644
--- a/Source/core/rendering/compositing/RenderLayerCompositor.h
+++ b/Source/core/rendering/compositing/RenderLayerCompositor.h
@@ -217,7 +217,7 @@
             , nextSquashedLayerIndex(0)
             , clippingAncestorForMostRecentMapping(0) { }
 
-        void updateSquashingStateForNewMapping(CompositedLayerMappingPtr, bool hasNewCompositedLayerMapping, IntPoint newOffsetFromAbsoluteForSquashingCLM, RenderLayer* clippingAncestorForMostRecentMapping);
+        void updateSquashingStateForNewMapping(CompositedLayerMappingPtr, bool hasNewCompositedLayerMapping, LayoutPoint newOffsetFromAbsoluteForSquashingCLM, RenderLayer* clippingAncestorForMostRecentMapping);
 
         // The most recent composited backing that the layer should squash onto if needed.
         CompositedLayerMappingPtr mostRecentMapping;
@@ -225,7 +225,7 @@
 
         // Absolute coordinates of the compositedLayerMapping's owning layer. This is used for computing the correct
         // positions of renderlayers when they paint into the squashing layer.
-        IntPoint offsetFromAbsoluteForSquashingCLM;
+        LayoutPoint offsetFromAbsoluteForSquashingCLM;
 
         // Counter that tracks what index the next RenderLayer would be if it gets squashed to the current squashing layer.
         size_t nextSquashedLayerIndex;
diff --git a/Source/core/rendering/shapes/BoxShape.cpp b/Source/core/rendering/shapes/BoxShape.cpp
index 5638140..5211a57 100644
--- a/Source/core/rendering/shapes/BoxShape.cpp
+++ b/Source/core/rendering/shapes/BoxShape.cpp
@@ -76,8 +76,8 @@
     if (marginBounds.isEmpty() || !lineOverlapsShapeMarginBounds(logicalTop, logicalHeight))
         return;
 
-    float y1 = logicalTop;
-    float y2 = logicalTop + logicalHeight;
+    float y1 = logicalTop.toFloat();
+    float y2 = (logicalTop + logicalHeight).toFloat();
     const FloatRect& rect = marginBounds.rect();
 
     if (!marginBounds.isRounded()) {
@@ -118,8 +118,8 @@
     if (paddingBounds.isEmpty())
         return;
 
-    float y1 = logicalTop;
-    float y2 = logicalTop + logicalHeight;
+    float y1 = logicalTop.toFloat();
+    float y2 = (logicalTop + logicalHeight).toFloat();
     const FloatRect& rect = paddingBounds.rect();
 
     if (y1 < rect.y() || y2 > rect.maxY())
diff --git a/Source/core/rendering/shapes/PolygonShape.cpp b/Source/core/rendering/shapes/PolygonShape.cpp
index 512ae14..2e69638 100644
--- a/Source/core/rendering/shapes/PolygonShape.cpp
+++ b/Source/core/rendering/shapes/PolygonShape.cpp
@@ -368,8 +368,8 @@
     if (polygon.isEmpty())
         return;
 
-    float y1 = logicalTop;
-    float y2 = logicalTop + logicalHeight;
+    float y1 = logicalTop.toFloat();
+    float y2 = (logicalTop + logicalHeight).toFloat();
 
     FloatShapeIntervals y1XIntervals, y2XIntervals;
     computeXIntersections(polygon, y1, true, y1XIntervals);
@@ -396,8 +396,8 @@
     if (polygon.isEmpty())
         return;
 
-    float y1 = logicalTop;
-    float y2 = logicalTop + logicalHeight;
+    float y1 = logicalTop.toFloat();
+    float y2 = (logicalTop + logicalHeight).toFloat();
 
     FloatShapeIntervals y1XIntervals, y2XIntervals;
     computeXIntersections(polygon, y1, true, y1XIntervals);
@@ -444,7 +444,7 @@
 
 bool PolygonShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize& minLogicalIntervalSize, LayoutUnit& result) const
 {
-    float minIntervalTop = minLogicalIntervalTop;
+    float minIntervalTop = minLogicalIntervalTop.toFloat();
     float minIntervalHeight = minLogicalIntervalSize.height();
     float minIntervalWidth = minLogicalIntervalSize.width();
 
diff --git a/Source/core/rendering/shapes/Shape.cpp b/Source/core/rendering/shapes/Shape.cpp
index 27a5593..ce8bd1f 100644
--- a/Source/core/rendering/shapes/Shape.cpp
+++ b/Source/core/rendering/shapes/Shape.cpp
@@ -116,8 +116,8 @@
     ASSERT(basicShape);
 
     bool horizontalWritingMode = isHorizontalWritingMode(writingMode);
-    float boxWidth = horizontalWritingMode ? logicalBoxSize.width() : logicalBoxSize.height();
-    float boxHeight = horizontalWritingMode ? logicalBoxSize.height() : logicalBoxSize.width();
+    float boxWidth = horizontalWritingMode ? logicalBoxSize.width().toFloat() : logicalBoxSize.height().toFloat();
+    float boxHeight = horizontalWritingMode ? logicalBoxSize.height().toFloat() : logicalBoxSize.width().toFloat();
     OwnPtr<Shape> shape;
 
     switch (basicShape->type()) {
@@ -133,7 +133,7 @@
             floatValueForLength(rectangle->cornerRadiusX(), boxWidth),
             floatValueForLength(rectangle->cornerRadiusY(), boxHeight));
         ensureRadiiDoNotOverlap(bounds, cornerRadii);
-        FloatRect logicalBounds = physicalRectToLogical(bounds, logicalBoxSize.height(), writingMode);
+        FloatRect logicalBounds = physicalRectToLogical(bounds, logicalBoxSize.height().toFloat(), writingMode);
 
         shape = createRectangleShape(logicalBounds, physicalSizeToLogical(cornerRadii, writingMode));
         break;
@@ -148,7 +148,7 @@
         // off of the diagonal of the box and ensures that if the box is
         // square, the radius is equal to half the diagonal.
         float radius = floatValueForLength(circle->radius(), sqrtf((boxWidth * boxWidth + boxHeight * boxHeight) / 2));
-        FloatPoint logicalCenter = physicalPointToLogical(FloatPoint(centerX, centerY), logicalBoxSize.height(), writingMode);
+        FloatPoint logicalCenter = physicalPointToLogical(FloatPoint(centerX, centerY), logicalBoxSize.height().toFloat(), writingMode);
 
         shape = createCircleShape(logicalCenter, radius);
         break;
@@ -158,7 +158,7 @@
         const BasicShapeCircle* circle = static_cast<const BasicShapeCircle*>(basicShape);
         FloatPoint center = floatPointForCenterCoordinate(circle->centerX(), circle->centerY(), FloatSize(boxWidth, boxHeight));
         float radius = circle->floatValueForRadiusInBox(FloatSize(boxWidth, boxHeight));
-        FloatPoint logicalCenter = physicalPointToLogical(center, logicalBoxSize.height(), writingMode);
+        FloatPoint logicalCenter = physicalPointToLogical(center, logicalBoxSize.height().toFloat(), writingMode);
 
         shape = createCircleShape(logicalCenter, radius);
         break;
@@ -170,7 +170,7 @@
         float centerY = floatValueForLength(ellipse->centerY(), boxHeight);
         float radiusX = floatValueForLength(ellipse->radiusX(), boxWidth);
         float radiusY = floatValueForLength(ellipse->radiusY(), boxHeight);
-        FloatPoint logicalCenter = physicalPointToLogical(FloatPoint(centerX, centerY), logicalBoxSize.height(), writingMode);
+        FloatPoint logicalCenter = physicalPointToLogical(FloatPoint(centerX, centerY), logicalBoxSize.height().toFloat(), writingMode);
         FloatSize logicalRadii = physicalSizeToLogical(FloatSize(radiusX, radiusY), writingMode);
 
         shape = createEllipseShape(logicalCenter, logicalRadii);
@@ -182,7 +182,7 @@
         FloatPoint center = floatPointForCenterCoordinate(ellipse->centerX(), ellipse->centerY(), FloatSize(boxWidth, boxHeight));
         float radiusX = ellipse->floatValueForRadiusInBox(ellipse->radiusX(), center.x(), boxWidth);
         float radiusY = ellipse->floatValueForRadiusInBox(ellipse->radiusY(), center.y(), boxHeight);
-        FloatPoint logicalCenter = physicalPointToLogical(center, logicalBoxSize.height(), writingMode);
+        FloatPoint logicalCenter = physicalPointToLogical(center, logicalBoxSize.height().toFloat(), writingMode);
 
         shape = createEllipseShape(logicalCenter, FloatSize(radiusX, radiusY));
         break;
@@ -198,7 +198,7 @@
             FloatPoint vertex(
                 floatValueForLength(values.at(i), boxWidth),
                 floatValueForLength(values.at(i + 1), boxHeight));
-            (*vertices)[i / 2] = physicalPointToLogical(vertex, logicalBoxSize.height(), writingMode);
+            (*vertices)[i / 2] = physicalPointToLogical(vertex, logicalBoxSize.height().toFloat(), writingMode);
         }
         shape = createPolygonShape(vertices.release(), polygon->windRule());
         break;
@@ -219,7 +219,7 @@
             floatValueForLength(rectangle->cornerRadiusX(), boxWidth),
             floatValueForLength(rectangle->cornerRadiusY(), boxHeight));
         ensureRadiiDoNotOverlap(bounds, cornerRadii);
-        FloatRect logicalBounds = physicalRectToLogical(bounds, logicalBoxSize.height(), writingMode);
+        FloatRect logicalBounds = physicalRectToLogical(bounds, logicalBoxSize.height().toFloat(), writingMode);
 
         shape = createRectangleShape(logicalBounds, physicalSizeToLogical(cornerRadii, writingMode));
         break;
@@ -232,7 +232,7 @@
         float right = floatValueForLength(inset.right(), boxWidth);
         float bottom = floatValueForLength(inset.bottom(), boxHeight);
         FloatRect rect(left, top, std::max<float>(boxWidth - left - right, 0), std::max<float>(boxHeight - top - bottom, 0));
-        FloatRect logicalRect = physicalRectToLogical(rect, logicalBoxSize.height(), writingMode);
+        FloatRect logicalRect = physicalRectToLogical(rect, logicalBoxSize.height().toFloat(), writingMode);
 
         FloatSize boxSize(boxWidth, boxHeight);
         FloatSize topLeftRadius = physicalSizeToLogical(floatSizeForLengthSize(inset.topLeftRadius(), boxSize), writingMode);
diff --git a/Source/core/rendering/style/CachedUAStyle.h b/Source/core/rendering/style/CachedUAStyle.h
index 2b98e51..a3d7446 100644
--- a/Source/core/rendering/style/CachedUAStyle.h
+++ b/Source/core/rendering/style/CachedUAStyle.h
@@ -39,15 +39,11 @@
     { }
 
     explicit CachedUAStyle(const RenderStyle* style)
-        : hasAppearance(style->hasAppearance())
+        : hasAppearance(true)
         , backgroundLayers(BackgroundFillLayer)
         , backgroundColor(StyleColor::currentColor())
     {
-        // RenderTheme::adjustStyle is the only consumer of this data.
-        // It only cares about the styles if appearance is set,
-        // so we cheat and don't bother to copy them when !hasAppearance.
-        if (!hasAppearance)
-            return;
+        ASSERT(style->hasAppearance());
         border = style->border();
         backgroundLayers = *style->backgroundLayers();
         backgroundColor = style->backgroundColor();
diff --git a/Source/core/rendering/style/RenderStyle.h b/Source/core/rendering/style/RenderStyle.h
index 0ef9eb2..75d996f 100644
--- a/Source/core/rendering/style/RenderStyle.h
+++ b/Source/core/rendering/style/RenderStyle.h
@@ -1849,8 +1849,6 @@
         return false;
     if (hasUniquePseudoStyle())
         return false;
-    if (transitions() || animations())
-        return false;
     return true;
 }
 
diff --git a/Source/core/rendering/style/SVGRenderStyle.h b/Source/core/rendering/style/SVGRenderStyle.h
index 2f94d94..5d0c969 100644
--- a/Source/core/rendering/style/SVGRenderStyle.h
+++ b/Source/core/rendering/style/SVGRenderStyle.h
@@ -89,9 +89,9 @@
     static const AtomicString& initialClipperResource() { return nullAtom; }
     static const AtomicString& initialFilterResource() { return nullAtom; }
     static const AtomicString& initialMaskerResource() { return nullAtom; }
-    static String initialMarkerStartResource() { return String(); }
-    static String initialMarkerMidResource() { return String(); }
-    static String initialMarkerEndResource() { return String(); }
+    static const AtomicString& initialMarkerStartResource() { return nullAtom; }
+    static const AtomicString& initialMarkerMidResource() { return nullAtom; }
+    static const AtomicString& initialMarkerEndResource() { return nullAtom; }
     static EMaskType initialMaskType() { return MT_LUMINANCE; }
     static EPaintOrder initialPaintOrder() { return PO_NORMAL; }
 
@@ -282,19 +282,19 @@
     }
 
     // Setters for inherited resources
-    void setMarkerStartResource(const String& obj)
+    void setMarkerStartResource(const AtomicString& obj)
     {
         if (!(inheritedResources->markerStart == obj))
             inheritedResources.access()->markerStart = obj;
     }
 
-    void setMarkerMidResource(const String& obj)
+    void setMarkerMidResource(const AtomicString& obj)
     {
         if (!(inheritedResources->markerMid == obj))
             inheritedResources.access()->markerMid = obj;
     }
 
-    void setMarkerEndResource(const String& obj)
+    void setMarkerEndResource(const AtomicString& obj)
     {
         if (!(inheritedResources->markerEnd == obj))
             inheritedResources.access()->markerEnd = obj;
@@ -340,9 +340,9 @@
     const AtomicString& clipperResource() const { return resources->clipper; }
     const AtomicString& filterResource() const { return resources->filter; }
     const AtomicString& maskerResource() const { return resources->masker; }
-    String markerStartResource() const { return inheritedResources->markerStart; }
-    String markerMidResource() const { return inheritedResources->markerMid; }
-    String markerEndResource() const { return inheritedResources->markerEnd; }
+    const AtomicString& markerStartResource() const { return inheritedResources->markerStart; }
+    const AtomicString& markerMidResource() const { return inheritedResources->markerMid; }
+    const AtomicString& markerEndResource() const { return inheritedResources->markerEnd; }
     EMaskType maskType() const { return (EMaskType) svg_noninherited_flags.f.maskType; }
     EPaintOrder paintOrder() const { return (EPaintOrder) svg_inherited_flags._paintOrder; }
     EPaintOrderType paintOrderType(unsigned index) const;
diff --git a/Source/core/rendering/style/SVGRenderStyleDefs.h b/Source/core/rendering/style/SVGRenderStyleDefs.h
index e25a8b2..b624dc7 100644
--- a/Source/core/rendering/style/SVGRenderStyleDefs.h
+++ b/Source/core/rendering/style/SVGRenderStyleDefs.h
@@ -257,9 +257,9 @@
             return !(*this == other);
         }
 
-        String markerStart;
-        String markerMid;
-        String markerEnd;
+        AtomicString markerStart;
+        AtomicString markerMid;
+        AtomicString markerEnd;
 
     private:
         StyleInheritedResourceData();
diff --git a/Source/core/rendering/style/StyleFetchedImage.cpp b/Source/core/rendering/style/StyleFetchedImage.cpp
index 59566a9..867736e 100644
--- a/Source/core/rendering/style/StyleFetchedImage.cpp
+++ b/Source/core/rendering/style/StyleFetchedImage.cpp
@@ -24,6 +24,7 @@
 #include "config.h"
 #include "core/rendering/style/StyleFetchedImage.h"
 
+#include "core/css/CSSImageValue.h"
 #include "core/fetch/ImageResource.h"
 #include "core/rendering/RenderObject.h"
 
@@ -43,7 +44,7 @@
 
 PassRefPtrWillBeRawPtr<CSSValue> StyleFetchedImage::cssValue() const
 {
-    return CSSPrimitiveValue::create(m_image->url().string(), CSSPrimitiveValue::CSS_URI);
+    return CSSImageValue::create(m_image->url(), const_cast<StyleFetchedImage*>(this));
 }
 
 bool StyleFetchedImage::canRender(const RenderObject* renderer, float multiplier) const
diff --git a/Source/core/rendering/svg/RenderSVGImage.cpp b/Source/core/rendering/svg/RenderSVGImage.cpp
index 584bacb..9f82cc6 100644
--- a/Source/core/rendering/svg/RenderSVGImage.cpp
+++ b/Source/core/rendering/svg/RenderSVGImage.cpp
@@ -168,11 +168,14 @@
     SVGImageElement* imageElement = toSVGImageElement(element());
     imageElement->preserveAspectRatio()->currentValue()->transformRect(destRect, srcRect);
 
-    bool useLowQualityScaling = false;
+    InterpolationQuality interpolationQuality = InterpolationDefault;
     if (style()->svgStyle()->bufferedRendering() != BR_STATIC)
-        useLowQualityScaling = ImageQualityController::imageQualityController()->shouldPaintAtLowQuality(paintInfo.context, this, image.get(), image.get(), LayoutSize(destRect.size()));
+        interpolationQuality = ImageQualityController::imageQualityController()->chooseInterpolationQuality(paintInfo.context, this, image.get(), image.get(), LayoutSize(destRect.size()));
 
-    paintInfo.context->drawImage(image.get(), destRect, srcRect, CompositeSourceOver, DoNotRespectImageOrientation, useLowQualityScaling);
+    InterpolationQuality previousInterpolationQuality = paintInfo.context->imageInterpolationQuality();
+    paintInfo.context->setImageInterpolationQuality(interpolationQuality);
+    paintInfo.context->drawImage(image.get(), destRect, srcRect, CompositeSourceOver);
+    paintInfo.context->setImageInterpolationQuality(previousInterpolationQuality);
 }
 
 void RenderSVGImage::invalidateBufferedForeground()
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
index f62c653..927212d 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
@@ -171,7 +171,7 @@
 
     // Determine absolute transformation matrix for filter.
     AffineTransform absoluteTransform;
-    SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(object, absoluteTransform);
+    SVGRenderingContext::calculateDeviceSpaceTransformation(object, absoluteTransform);
     if (!absoluteTransform.isInvertible())
         return false;
 
diff --git a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
index d6f93ef..cf6889d 100644
--- a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
@@ -85,7 +85,7 @@
         return 0;
 
     AffineTransform absoluteTransformIgnoringRotation;
-    SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(object, absoluteTransformIgnoringRotation);
+    SVGRenderingContext::calculateDeviceSpaceTransformation(object, absoluteTransformIgnoringRotation);
 
     // Ignore 2D rotation, as it doesn't affect the size of the tile.
     SVGRenderingContext::clear2DRotation(absoluteTransformIgnoringRotation);
diff --git a/Source/core/rendering/svg/RenderSVGRoot.cpp b/Source/core/rendering/svg/RenderSVGRoot.cpp
index 4c81c67..0e181b4 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.cpp
+++ b/Source/core/rendering/svg/RenderSVGRoot.cpp
@@ -147,7 +147,7 @@
         return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
 
     if (svg->widthAttributeEstablishesViewport())
-        return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth());
+        return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth().toFloat());
 
     // SVG embedded through object/embed/iframe.
     if (isEmbeddedThroughFrameContainingSVGDocument())
@@ -174,14 +174,13 @@
         if (height.isPercent()) {
             RenderBlock* cb = containingBlock();
             ASSERT(cb);
-            while (cb->isAnonymous()) {
+            while (cb->isAnonymous())
                 cb = cb->containingBlock();
-                cb->addPercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
-            }
+            cb->addPercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
         } else
             RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
 
-        return resolveLengthAttributeForSVG(height, style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding));
+        return resolveLengthAttributeForSVG(height, style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding).toFloat());
     }
 
     // SVG embedded through object/embed/iframe.
@@ -394,7 +393,7 @@
 {
     SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_repaintBoundingBox);
     SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
-    m_repaintBoundingBox.inflate(borderAndPaddingWidth());
+    m_repaintBoundingBox.inflate(borderAndPaddingWidth().toFloat());
 }
 
 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
diff --git a/Source/core/rendering/svg/RenderSVGShape.cpp b/Source/core/rendering/svg/RenderSVGShape.cpp
index b5c9528..fd362d6 100644
--- a/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -196,7 +196,7 @@
     if (!style()->svgStyle()->hasMarkers())
         return false;
 
-    if (!toSVGGraphicsElement(element())->supportsMarkers())
+    if (!SVGResources::supportsMarkers(*toSVGGraphicsElement(element())))
         return false;
 
     SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
diff --git a/Source/core/rendering/svg/SVGRenderingContext.cpp b/Source/core/rendering/svg/SVGRenderingContext.cpp
index 7928a7c..6329cf0 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.cpp
+++ b/Source/core/rendering/svg/SVGRenderingContext.cpp
@@ -203,12 +203,17 @@
     ASSERT(renderer);
 
     AffineTransform ctm;
-    calculateTransformationToOutermostCoordinateSystem(renderer, ctm);
+    // FIXME: calculateDeviceSpaceTransformation() queries layer compositing state - which is not
+    // supported during layout. Hence, the result may not include all CSS transforms.
+    calculateDeviceSpaceTransformation(renderer, ctm);
     return narrowPrecisionToFloat(sqrt((pow(ctm.xScale(), 2) + pow(ctm.yScale(), 2)) / 2));
 }
 
-void SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(const RenderObject* renderer, AffineTransform& absoluteTransform)
+void SVGRenderingContext::calculateDeviceSpaceTransformation(const RenderObject* renderer, AffineTransform& absoluteTransform)
 {
+    // FIXME: trying to compute a device space transform at record time is wrong. All clients
+    // should be updated to avoid relying on this information, and the method should be removed.
+
     ASSERT(renderer);
     // We're about to possibly clear renderer, so save the deviceScaleFactor now.
     float deviceScaleFactor = renderer->document().frameHost()->deviceScaleFactor();
@@ -224,18 +229,18 @@
 
     // Continue walking up the layer tree, accumulating CSS transforms.
     RenderLayer* layer = renderer ? renderer->enclosingLayer() : 0;
-    while (layer) {
-        if (TransformationMatrix* layerTransform = layer->transform())
-            absoluteTransform = layerTransform->toAffineTransform() * absoluteTransform;
-
+    while (layer && layer->isAllowedToQueryCompositingState()) {
         // We can stop at compositing layers, to match the backing resolution.
         // FIXME: should we be computing the transform to the nearest composited layer,
         // or the nearest composited layer that does not paint into its ancestor?
         // I think this is the nearest composited ancestor since we will inherit its
         // transforms in the composited layer tree.
-        if (layer->hasCompositedLayerMapping())
+        if (layer->compositingState() != NotComposited)
             break;
 
+        if (TransformationMatrix* layerTransform = layer->transform())
+            absoluteTransform = layerTransform->toAffineTransform() * absoluteTransform;
+
         layer = layer->parent();
     }
 
diff --git a/Source/core/rendering/svg/SVGRenderingContext.h b/Source/core/rendering/svg/SVGRenderingContext.h
index 742e0a0..3fcda0a 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.h
+++ b/Source/core/rendering/svg/SVGRenderingContext.h
@@ -79,7 +79,7 @@
     static void renderSubtree(GraphicsContext*, RenderObject*, const AffineTransform&);
 
     static float calculateScreenFontSizeScalingFactor(const RenderObject*);
-    static void calculateTransformationToOutermostCoordinateSystem(const RenderObject*, AffineTransform& absoluteTransform);
+    static void calculateDeviceSpaceTransformation(const RenderObject*, AffineTransform& absoluteTransform);
     static FloatRect clampedAbsoluteTargetRect(const FloatRect& absoluteTargetRect);
     static void clear2DRotation(AffineTransform&);
 
diff --git a/Source/core/rendering/svg/SVGResources.cpp b/Source/core/rendering/svg/SVGResources.cpp
index f59ad85..fa086a2 100644
--- a/Source/core/rendering/svg/SVGResources.cpp
+++ b/Source/core/rendering/svg/SVGResources.cpp
@@ -91,7 +91,7 @@
     return s_tagList;
 }
 
-static HashSet<AtomicString>& markerTags()
+bool SVGResources::supportsMarkers(const SVGElement& element)
 {
     DEFINE_STATIC_LOCAL(HashSet<AtomicString>, s_tagList, ());
     if (s_tagList.isEmpty()) {
@@ -101,7 +101,7 @@
         s_tagList.add(SVGNames::polylineTag.localName());
     }
 
-    return s_tagList;
+    return s_tagList.contains(element.localName());
 }
 
 static HashSet<AtomicString>& fillAndStrokeTags()
@@ -250,17 +250,17 @@
         }
     }
 
-    if (markerTags().contains(tagName) && style->hasMarkers()) {
-        AtomicString markerStartId(style->markerStartResource());
+    if (style->hasMarkers() && supportsMarkers(*element)) {
+        const AtomicString& markerStartId = style->markerStartResource();
         if (!ensureResources(resources)->setMarkerStart(getRenderSVGResourceById<RenderSVGResourceMarker>(document, markerStartId)))
             registerPendingResource(extensions, markerStartId, element);
 
-        AtomicString markerMidId(style->markerMidResource());
+        const AtomicString& markerMidId = style->markerMidResource();
         if (!ensureResources(resources)->setMarkerMid(getRenderSVGResourceById<RenderSVGResourceMarker>(document, markerMidId)))
             registerPendingResource(extensions, markerMidId, element);
 
-        AtomicString markerEndId(style->markerEndResource());
-        if (!ensureResources(resources)->setMarkerEnd(getRenderSVGResourceById<RenderSVGResourceMarker>(document, markerEndId)))
+        const AtomicString& markerEndId = style->markerEndResource();
+        if (!ensureResources(resources)->setMarkerEnd(getRenderSVGResourceById<RenderSVGResourceMarker>(document, style->markerEndResource())))
             registerPendingResource(extensions, markerEndId, element);
     }
 
diff --git a/Source/core/rendering/svg/SVGResources.h b/Source/core/rendering/svg/SVGResources.h
index 5f3a8d4..03f9c33 100644
--- a/Source/core/rendering/svg/SVGResources.h
+++ b/Source/core/rendering/svg/SVGResources.h
@@ -35,6 +35,7 @@
 class RenderSVGResourceFilter;
 class RenderSVGResourceMarker;
 class RenderSVGResourceMasker;
+class SVGElement;
 class SVGRenderStyle;
 
 // Holds a set of resources associated with a RenderObject
@@ -46,6 +47,8 @@
     static PassOwnPtr<SVGResources> buildResources(const RenderObject*, const SVGRenderStyle*);
     void layoutIfNeeded();
 
+    static bool supportsMarkers(const SVGElement&);
+
     // Ordinary resources
     RenderSVGResourceClipper* clipper() const { return m_clipperFilterMaskerData ? m_clipperFilterMaskerData->clipper : 0; }
     RenderSVGResourceMarker* markerStart() const { return m_markerData ? m_markerData->markerStart : 0; }
diff --git a/Source/core/svg/SVGElement.cpp b/Source/core/svg/SVGElement.cpp
index ca015d3..c3211ee 100644
--- a/Source/core/svg/SVGElement.cpp
+++ b/Source/core/svg/SVGElement.cpp
@@ -270,7 +270,7 @@
     if (!attr)
         return nullptr;
 
-    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create(SVGAttributeMode);
+    RefPtrWillBeRawPtr<MutableStylePropertySet> style = MutableStylePropertySet::create(SVGAttributeMode);
     CSSPropertyID propertyID = SVGElement::cssPropertyIdForSVGAttributeName(attr->name());
     style->setProperty(propertyID, attr->value());
     RefPtrWillBeRawPtr<CSSValue> cssValue = style->getPropertyCSSValue(propertyID);
@@ -753,11 +753,9 @@
 
 bool SVGElement::haveLoadedRequiredResources()
 {
-    Node* child = firstChild();
-    while (child) {
-        if (child->isSVGElement() && !toSVGElement(child)->haveLoadedRequiredResources())
+    for (SVGElement* child = Traversal<SVGElement>::firstChild(*this); child; child = Traversal<SVGElement>::nextSibling(*child)) {
+        if (!child->haveLoadedRequiredResources())
             return false;
-        child = child->nextSibling();
     }
     return true;
 }
diff --git a/Source/core/svg/SVGElement.h b/Source/core/svg/SVGElement.h
index 020e091..ebdf634 100644
--- a/Source/core/svg/SVGElement.h
+++ b/Source/core/svg/SVGElement.h
@@ -55,7 +55,6 @@
 
     virtual String title() const OVERRIDE;
     bool hasRelativeLengths() const { return !m_elementsWithRelativeLengths.isEmpty(); }
-    virtual bool supportsMarkers() const { return false; }
     PassRefPtrWillBeRawPtr<CSSValue> getPresentationAttribute(const AtomicString& name);
     static bool isAnimatableCSSProperty(const QualifiedName&);
     enum CTMScope {
@@ -136,8 +135,8 @@
 
     virtual bool haveLoadedRequiredResources();
 
-    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE FINAL;
-    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE FINAL;
+    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture = false) OVERRIDE FINAL;
+    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture = false) OVERRIDE FINAL;
 
     void invalidateRelativeLengthClients(SubtreeLayoutScope* = 0);
 
diff --git a/Source/core/svg/SVGElementInstance.h b/Source/core/svg/SVGElementInstance.h
index 5161d15..ec1f925 100644
--- a/Source/core/svg/SVGElementInstance.h
+++ b/Source/core/svg/SVGElementInstance.h
@@ -50,8 +50,8 @@
     virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual ExecutionContext* executionContext() const OVERRIDE;
 
-    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE;
-    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE;
+    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture = false) OVERRIDE;
+    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture = false) OVERRIDE;
     virtual void removeAllEventListeners() OVERRIDE;
 
     using EventTarget::dispatchEvent;
diff --git a/Source/core/svg/SVGElementRareData.h b/Source/core/svg/SVGElementRareData.h
index 91a69d9..776af3c 100644
--- a/Source/core/svg/SVGElementRareData.h
+++ b/Source/core/svg/SVGElementRareData.h
@@ -113,7 +113,7 @@
     bool m_instancesUpdatesBlocked : 1;
     bool m_useOverrideComputedStyle : 1;
     bool m_needsOverrideComputedStyleUpdate : 1;
-    RefPtr<MutableStylePropertySet> m_animatedSMILStyleProperties;
+    RefPtrWillBePersistent<MutableStylePropertySet> m_animatedSMILStyleProperties;
     RefPtr<RenderStyle> m_overrideComputedStyle;
 };
 
diff --git a/Source/core/svg/SVGFontFaceElement.cpp b/Source/core/svg/SVGFontFaceElement.cpp
index 5430c48..b539322 100644
--- a/Source/core/svg/SVGFontFaceElement.cpp
+++ b/Source/core/svg/SVGFontFaceElement.cpp
@@ -52,7 +52,7 @@
     , m_fontElement(0)
 {
     ScriptWrappable::init(this);
-    RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create(HTMLStandardMode);
+    RefPtrWillBeRawPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create(HTMLStandardMode);
     m_fontFaceRule->setProperties(styleDeclaration.release());
 }
 
diff --git a/Source/core/svg/SVGLineElement.h b/Source/core/svg/SVGLineElement.h
index e90c432..59ee1c7 100644
--- a/Source/core/svg/SVGLineElement.h
+++ b/Source/core/svg/SVGLineElement.h
@@ -46,8 +46,6 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual bool supportsMarkers() const OVERRIDE { return true; }
-
     virtual bool selfHasRelativeLengths() const OVERRIDE;
 
     RefPtr<SVGAnimatedLength> m_x1;
diff --git a/Source/core/svg/SVGPathElement.h b/Source/core/svg/SVGPathElement.h
index 7f01e4e..0847d8b 100644
--- a/Source/core/svg/SVGPathElement.h
+++ b/Source/core/svg/SVGPathElement.h
@@ -103,7 +103,6 @@
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
-    virtual bool supportsMarkers() const OVERRIDE { return true; }
 
     virtual Node::InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
diff --git a/Source/core/svg/SVGPolyElement.h b/Source/core/svg/SVGPolyElement.h
index c830f0d..aac0184 100644
--- a/Source/core/svg/SVGPolyElement.h
+++ b/Source/core/svg/SVGPolyElement.h
@@ -45,8 +45,6 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE FINAL;
     virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE FINAL;
 
-    virtual bool supportsMarkers() const OVERRIDE FINAL { return true; }
-
 private:
     RefPtr<SVGAnimatedPointList> m_points;
 
diff --git a/Source/core/svg/SVGSVGElement.cpp b/Source/core/svg/SVGSVGElement.cpp
index dbe9c07..fa325ca 100644
--- a/Source/core/svg/SVGSVGElement.cpp
+++ b/Source/core/svg/SVGSVGElement.cpp
@@ -30,7 +30,6 @@
 #include "core/css/CSSHelper.h"
 #include "core/dom/Document.h"
 #include "core/dom/ElementTraversal.h"
-#include "core/dom/NodeTraversal.h"
 #include "core/dom/StaticNodeList.h"
 #include "core/editing/FrameSelection.h"
 #include "core/events/EventListener.h"
@@ -825,11 +824,7 @@
 
     // Fall back to traversing our subtree. Duplicate ids are allowed, the first found will
     // be returned.
-    for (Node* node = firstChild(); node; node = NodeTraversal::next(*node, this)) {
-        if (!node->isElementNode())
-            continue;
-
-        Element* element = toElement(node);
+    for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::next(*element, this)) {
         if (element->getIdAttribute() == id)
             return element;
     }
diff --git a/Source/core/svg/SVGUseElement.cpp b/Source/core/svg/SVGUseElement.cpp
index 6135db1..108d478 100644
--- a/Source/core/svg/SVGUseElement.cpp
+++ b/Source/core/svg/SVGUseElement.cpp
@@ -580,13 +580,9 @@
     // is the SVGGElement object for the 'g', and then two child SVGElementInstance objects, each of which has
     // its correspondingElement that is an SVGRectElement object.
 
-    for (Node* node = target->firstChild(); node; node = node->nextSibling()) {
-        SVGElement* element = 0;
-        if (node->isSVGElement())
-            element = toSVGElement(node);
-
-        // Skip any non-svg nodes or any disallowed element.
-        if (!element || isDisallowedElement(element))
+    for (SVGElement* element = Traversal<SVGElement>::firstChild(*target); element; element = Traversal<SVGElement>::nextSibling(*element)) {
+        // Skip any disallowed element.
+        if (isDisallowedElement(element))
             continue;
 
         // Create SVGElementInstance object, for both container/non-container nodes.
@@ -820,17 +816,10 @@
     targetInstance->setShadowTreeElement(element);
     element->setCorrespondingElement(originalElement);
 
-    Node* node = target->firstChild();
-    for (SVGElementInstance* instance = targetInstance->firstChild(); node && instance; instance = instance->nextSibling()) {
-        // Skip any non-svg elements in shadow tree
-        while (node && !node->isSVGElement())
-           node = node->nextSibling();
-
-        if (!node)
-            break;
-
-        associateInstancesWithShadowTreeElements(node, instance);
-        node = node->nextSibling();
+    SVGElement* child = Traversal<SVGElement>::firstChild(*target);
+    for (SVGElementInstance* instance = targetInstance->firstChild(); child && instance; instance = instance->nextSibling()) {
+        associateInstancesWithShadowTreeElements(child, instance);
+        child = Traversal<SVGElement>::nextSibling(*child);
     }
 }
 
diff --git a/Source/core/testing/Internals.cpp b/Source/core/testing/Internals.cpp
index 35e8ee2..c00c6a9 100644
--- a/Source/core/testing/Internals.cpp
+++ b/Source/core/testing/Internals.cpp
@@ -42,6 +42,7 @@
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ScriptFunction.h"
 #include "bindings/v8/ScriptPromise.h"
+#include "bindings/v8/ScriptPromiseResolver.h"
 #include "bindings/v8/SerializedScriptValue.h"
 #include "bindings/v8/V8ThrowException.h"
 #include "core/animation/DocumentTimeline.h"
@@ -85,7 +86,6 @@
 #include "core/html/HTMLContentElement.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLMediaElement.h"
 #include "core/html/HTMLSelectElement.h"
 #include "core/html/HTMLTextAreaElement.h"
 #include "core/html/forms/FormController.h"
@@ -1014,6 +1014,10 @@
 
     if (isHTMLTextAreaElement(*element))
         suggestedValue = toHTMLTextAreaElement(*element).suggestedValue();
+
+    if (isHTMLSelectElement(*element))
+        suggestedValue = toHTMLSelectElement(*element).suggestedValue();
+
     return suggestedValue;
 }
 
@@ -1034,6 +1038,9 @@
 
     if (isHTMLTextAreaElement(*element))
         toHTMLTextAreaElement(*element).setSuggestedValue(value);
+
+    if (isHTMLSelectElement(*element))
+        toHTMLSelectElement(*element).setSuggestedValue(value);
 }
 
 void Internals::setEditingValue(Element* element, const String& value, ExceptionState& exceptionState)
@@ -1647,7 +1654,9 @@
 
 String Internals::elementLayerTreeAsText(Element* element, ExceptionState& exceptionState) const
 {
-    DisableCompositingQueryAsserts disabler;
+    FrameView* frameView = element->document().view();
+    frameView->updateLayoutAndStyleForPainting();
+
     return elementLayerTreeAsText(element, 0, exceptionState);
 }
 
@@ -1772,6 +1781,8 @@
         return String();
     }
 
+    document->view()->updateLayoutAndStyleForPainting();
+
     return document->frame()->layerTreeAsText(flags);
 }
 
@@ -2381,6 +2392,27 @@
 
 } // namespace
 
+ScriptPromise Internals::createPromise(ExecutionContext* context)
+{
+    return ScriptPromiseResolver::create(context)->promise();
+}
+
+ScriptPromise Internals::createResolvedPromise(ExecutionContext* context, ScriptValue value)
+{
+    RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context);
+    ScriptPromise promise = resolver->promise();
+    resolver->resolve(value);
+    return promise;
+}
+
+ScriptPromise Internals::createRejectedPromise(ExecutionContext* context, ScriptValue value)
+{
+    RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context);
+    ScriptPromise promise = resolver->promise();
+    resolver->reject(value);
+    return promise;
+}
+
 ScriptPromise Internals::addOneToPromise(ExecutionContext* context, ScriptPromise promise)
 {
     return promise.then(AddOneFunction::create(context));
diff --git a/Source/core/testing/Internals.h b/Source/core/testing/Internals.h
index 3865517..7e96617 100644
--- a/Source/core/testing/Internals.h
+++ b/Source/core/testing/Internals.h
@@ -310,6 +310,9 @@
 
     void setShouldRevealPassword(Element*, bool, ExceptionState&);
 
+    ScriptPromise createPromise(ExecutionContext*);
+    ScriptPromise createResolvedPromise(ExecutionContext*, ScriptValue);
+    ScriptPromise createRejectedPromise(ExecutionContext*, ScriptValue);
     ScriptPromise addOneToPromise(ExecutionContext*, ScriptPromise);
 
     void trace(Visitor*);
diff --git a/Source/core/testing/Internals.idl b/Source/core/testing/Internals.idl
index b3da863..90111ea 100644
--- a/Source/core/testing/Internals.idl
+++ b/Source/core/testing/Internals.idl
@@ -278,6 +278,9 @@
 
     [RaisesException] void setShouldRevealPassword(Element element, boolean reveal);
 
+    [CallWith=ExecutionContext] Promise createPromise();
+    [CallWith=ExecutionContext] Promise createResolvedPromise(any value);
+    [CallWith=ExecutionContext] Promise createRejectedPromise(any reason);
     [CallWith=ExecutionContext] Promise addOneToPromise(Promise promise);
 
     void startSpeechInput(Element element);
diff --git a/Source/core/timing/MemoryInfo.cpp b/Source/core/timing/MemoryInfo.cpp
index 945e284..65b2fdc 100644
--- a/Source/core/timing/MemoryInfo.cpp
+++ b/Source/core/timing/MemoryInfo.cpp
@@ -137,7 +137,7 @@
     if (!frame || !frame->settings())
         return;
 
-    if (frame->settings()->memoryInfoEnabled()) {
+    if (frame->settings()->preciseMemoryInfoEnabled()) {
         ScriptGCEvent::getHeapSize(m_info);
     } else {
         DEFINE_STATIC_LOCAL(HeapSizeCache, heapSizeCache, ());
diff --git a/Source/core/timing/Performance.cpp b/Source/core/timing/Performance.cpp
index f3decc4..20dabe3 100644
--- a/Source/core/timing/Performance.cpp
+++ b/Source/core/timing/Performance.cpp
@@ -48,7 +48,7 @@
 Performance::Performance(LocalFrame* frame)
     : DOMWindowProperty(frame)
     , m_resourceTimingBufferSize(defaultResourceTimingBufferSize)
-    , m_referenceTime(frame->host() ? frame->document()->loader()->timing()->referenceMonotonicTime() : 0.0)
+    , m_referenceTime(frame && frame->host() ? frame->document()->loader()->timing()->referenceMonotonicTime() : 0.0)
     , m_userTiming(nullptr)
 {
     ScriptWrappable::init(this);
diff --git a/Source/core/webcore_dom.target.darwin-arm.mk b/Source/core/webcore_dom.target.darwin-arm.mk
index 9a49bcf..51da6f4 100644
--- a/Source/core/webcore_dom.target.darwin-arm.mk
+++ b/Source/core/webcore_dom.target.darwin-arm.mk
@@ -250,7 +250,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -277,6 +276,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -403,7 +403,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -430,6 +429,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_dom.target.darwin-mips.mk b/Source/core/webcore_dom.target.darwin-mips.mk
index b3c1d94..9623482 100644
--- a/Source/core/webcore_dom.target.darwin-mips.mk
+++ b/Source/core/webcore_dom.target.darwin-mips.mk
@@ -249,7 +249,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -276,6 +275,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -401,7 +401,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -428,6 +427,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_dom.target.darwin-x86.mk b/Source/core/webcore_dom.target.darwin-x86.mk
index 696d525..565ccab 100644
--- a/Source/core/webcore_dom.target.darwin-x86.mk
+++ b/Source/core/webcore_dom.target.darwin-x86.mk
@@ -251,7 +251,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -278,6 +277,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -404,7 +404,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -431,6 +430,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_dom.target.linux-arm.mk b/Source/core/webcore_dom.target.linux-arm.mk
index 9a49bcf..51da6f4 100644
--- a/Source/core/webcore_dom.target.linux-arm.mk
+++ b/Source/core/webcore_dom.target.linux-arm.mk
@@ -250,7 +250,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -277,6 +276,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -403,7 +403,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -430,6 +429,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_dom.target.linux-mips.mk b/Source/core/webcore_dom.target.linux-mips.mk
index b3c1d94..9623482 100644
--- a/Source/core/webcore_dom.target.linux-mips.mk
+++ b/Source/core/webcore_dom.target.linux-mips.mk
@@ -249,7 +249,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -276,6 +275,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -401,7 +401,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -428,6 +427,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_dom.target.linux-x86.mk b/Source/core/webcore_dom.target.linux-x86.mk
index 696d525..565ccab 100644
--- a/Source/core/webcore_dom.target.linux-x86.mk
+++ b/Source/core/webcore_dom.target.linux-x86.mk
@@ -251,7 +251,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -278,6 +277,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -404,7 +404,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -431,6 +430,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_generated.target.darwin-arm.mk b/Source/core/webcore_generated.target.darwin-arm.mk
index 3000330..32abe45 100644
--- a/Source/core/webcore_generated.target.darwin-arm.mk
+++ b/Source/core/webcore_generated.target.darwin-arm.mk
@@ -386,7 +386,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -413,6 +412,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -544,7 +544,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -571,6 +570,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_generated.target.darwin-mips.mk b/Source/core/webcore_generated.target.darwin-mips.mk
index 9f6d09b..98602fc 100644
--- a/Source/core/webcore_generated.target.darwin-mips.mk
+++ b/Source/core/webcore_generated.target.darwin-mips.mk
@@ -385,7 +385,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -412,6 +411,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -542,7 +542,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -569,6 +568,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_generated.target.darwin-x86.mk b/Source/core/webcore_generated.target.darwin-x86.mk
index 2a41c96..1d9f8c3 100644
--- a/Source/core/webcore_generated.target.darwin-x86.mk
+++ b/Source/core/webcore_generated.target.darwin-x86.mk
@@ -387,7 +387,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -414,6 +413,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -545,7 +545,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -572,6 +571,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_generated.target.linux-arm.mk b/Source/core/webcore_generated.target.linux-arm.mk
index 3000330..32abe45 100644
--- a/Source/core/webcore_generated.target.linux-arm.mk
+++ b/Source/core/webcore_generated.target.linux-arm.mk
@@ -386,7 +386,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -413,6 +412,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -544,7 +544,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -571,6 +570,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_generated.target.linux-mips.mk b/Source/core/webcore_generated.target.linux-mips.mk
index 9f6d09b..98602fc 100644
--- a/Source/core/webcore_generated.target.linux-mips.mk
+++ b/Source/core/webcore_generated.target.linux-mips.mk
@@ -385,7 +385,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -412,6 +411,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -542,7 +542,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -569,6 +568,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_generated.target.linux-x86.mk b/Source/core/webcore_generated.target.linux-x86.mk
index 2a41c96..1d9f8c3 100644
--- a/Source/core/webcore_generated.target.linux-x86.mk
+++ b/Source/core/webcore_generated.target.linux-x86.mk
@@ -387,7 +387,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -414,6 +413,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -545,7 +545,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -572,6 +571,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_html.target.darwin-arm.mk b/Source/core/webcore_html.target.darwin-arm.mk
index 147d980..127fa93 100644
--- a/Source/core/webcore_html.target.darwin-arm.mk
+++ b/Source/core/webcore_html.target.darwin-arm.mk
@@ -337,7 +337,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -364,6 +363,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -490,7 +490,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -517,6 +516,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_html.target.darwin-mips.mk b/Source/core/webcore_html.target.darwin-mips.mk
index 944576f..8750f6a 100644
--- a/Source/core/webcore_html.target.darwin-mips.mk
+++ b/Source/core/webcore_html.target.darwin-mips.mk
@@ -336,7 +336,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -363,6 +362,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -488,7 +488,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -515,6 +514,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_html.target.darwin-x86.mk b/Source/core/webcore_html.target.darwin-x86.mk
index 80e6a3d..194bdda 100644
--- a/Source/core/webcore_html.target.darwin-x86.mk
+++ b/Source/core/webcore_html.target.darwin-x86.mk
@@ -338,7 +338,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -365,6 +364,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -491,7 +491,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -518,6 +517,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_html.target.linux-arm.mk b/Source/core/webcore_html.target.linux-arm.mk
index 147d980..127fa93 100644
--- a/Source/core/webcore_html.target.linux-arm.mk
+++ b/Source/core/webcore_html.target.linux-arm.mk
@@ -337,7 +337,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -364,6 +363,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -490,7 +490,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -517,6 +516,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_html.target.linux-mips.mk b/Source/core/webcore_html.target.linux-mips.mk
index 944576f..8750f6a 100644
--- a/Source/core/webcore_html.target.linux-mips.mk
+++ b/Source/core/webcore_html.target.linux-mips.mk
@@ -336,7 +336,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -363,6 +362,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -488,7 +488,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -515,6 +514,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_html.target.linux-x86.mk b/Source/core/webcore_html.target.linux-x86.mk
index 80e6a3d..194bdda 100644
--- a/Source/core/webcore_html.target.linux-x86.mk
+++ b/Source/core/webcore_html.target.linux-x86.mk
@@ -338,7 +338,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -365,6 +364,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -491,7 +491,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -518,6 +517,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_remaining.target.darwin-arm.mk b/Source/core/webcore_remaining.target.darwin-arm.mk
index 5acc2ee..7a62113 100644
--- a/Source/core/webcore_remaining.target.darwin-arm.mk
+++ b/Source/core/webcore_remaining.target.darwin-arm.mk
@@ -605,7 +605,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -632,6 +631,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -759,7 +759,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -786,6 +785,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_remaining.target.darwin-mips.mk b/Source/core/webcore_remaining.target.darwin-mips.mk
index a335096..9a2dbbc 100644
--- a/Source/core/webcore_remaining.target.darwin-mips.mk
+++ b/Source/core/webcore_remaining.target.darwin-mips.mk
@@ -604,7 +604,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -631,6 +630,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -757,7 +757,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -784,6 +783,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_remaining.target.darwin-x86.mk b/Source/core/webcore_remaining.target.darwin-x86.mk
index a44acd1..1c2b30e 100644
--- a/Source/core/webcore_remaining.target.darwin-x86.mk
+++ b/Source/core/webcore_remaining.target.darwin-x86.mk
@@ -606,7 +606,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -633,6 +632,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -760,7 +760,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -787,6 +786,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_remaining.target.linux-arm.mk b/Source/core/webcore_remaining.target.linux-arm.mk
index 5acc2ee..7a62113 100644
--- a/Source/core/webcore_remaining.target.linux-arm.mk
+++ b/Source/core/webcore_remaining.target.linux-arm.mk
@@ -605,7 +605,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -632,6 +631,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -759,7 +759,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -786,6 +785,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_remaining.target.linux-mips.mk b/Source/core/webcore_remaining.target.linux-mips.mk
index a335096..9a2dbbc 100644
--- a/Source/core/webcore_remaining.target.linux-mips.mk
+++ b/Source/core/webcore_remaining.target.linux-mips.mk
@@ -604,7 +604,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -631,6 +630,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -757,7 +757,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -784,6 +783,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_remaining.target.linux-x86.mk b/Source/core/webcore_remaining.target.linux-x86.mk
index a44acd1..1c2b30e 100644
--- a/Source/core/webcore_remaining.target.linux-x86.mk
+++ b/Source/core/webcore_remaining.target.linux-x86.mk
@@ -606,7 +606,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -633,6 +632,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -760,7 +760,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -787,6 +786,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_rendering.target.darwin-arm.mk b/Source/core/webcore_rendering.target.darwin-arm.mk
index 1d161ed..9e6e7e4 100644
--- a/Source/core/webcore_rendering.target.darwin-arm.mk
+++ b/Source/core/webcore_rendering.target.darwin-arm.mk
@@ -236,7 +236,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -263,6 +262,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -389,7 +389,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -416,6 +415,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_rendering.target.darwin-mips.mk b/Source/core/webcore_rendering.target.darwin-mips.mk
index 4109803..1fceb1d 100644
--- a/Source/core/webcore_rendering.target.darwin-mips.mk
+++ b/Source/core/webcore_rendering.target.darwin-mips.mk
@@ -235,7 +235,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -262,6 +261,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -387,7 +387,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -414,6 +413,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_rendering.target.darwin-x86.mk b/Source/core/webcore_rendering.target.darwin-x86.mk
index 3af5bba..12ff5ae 100644
--- a/Source/core/webcore_rendering.target.darwin-x86.mk
+++ b/Source/core/webcore_rendering.target.darwin-x86.mk
@@ -238,7 +238,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -265,6 +264,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -392,7 +392,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -419,6 +418,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_rendering.target.linux-arm.mk b/Source/core/webcore_rendering.target.linux-arm.mk
index 1d161ed..9e6e7e4 100644
--- a/Source/core/webcore_rendering.target.linux-arm.mk
+++ b/Source/core/webcore_rendering.target.linux-arm.mk
@@ -236,7 +236,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -263,6 +262,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -389,7 +389,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -416,6 +415,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_rendering.target.linux-mips.mk b/Source/core/webcore_rendering.target.linux-mips.mk
index 4109803..1fceb1d 100644
--- a/Source/core/webcore_rendering.target.linux-mips.mk
+++ b/Source/core/webcore_rendering.target.linux-mips.mk
@@ -235,7 +235,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -262,6 +261,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -387,7 +387,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -414,6 +413,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_rendering.target.linux-x86.mk b/Source/core/webcore_rendering.target.linux-x86.mk
index 3af5bba..12ff5ae 100644
--- a/Source/core/webcore_rendering.target.linux-x86.mk
+++ b/Source/core/webcore_rendering.target.linux-x86.mk
@@ -238,7 +238,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -265,6 +264,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -392,7 +392,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -419,6 +418,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_svg.target.darwin-arm.mk b/Source/core/webcore_svg.target.darwin-arm.mk
index 139c8ea..3493e40 100644
--- a/Source/core/webcore_svg.target.darwin-arm.mk
+++ b/Source/core/webcore_svg.target.darwin-arm.mk
@@ -301,7 +301,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -328,6 +327,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -454,7 +454,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -481,6 +480,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_svg.target.darwin-mips.mk b/Source/core/webcore_svg.target.darwin-mips.mk
index 57675eb..9865c72 100644
--- a/Source/core/webcore_svg.target.darwin-mips.mk
+++ b/Source/core/webcore_svg.target.darwin-mips.mk
@@ -300,7 +300,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -327,6 +326,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -452,7 +452,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -479,6 +478,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_svg.target.darwin-x86.mk b/Source/core/webcore_svg.target.darwin-x86.mk
index 39a1c8d..fc4c338 100644
--- a/Source/core/webcore_svg.target.darwin-x86.mk
+++ b/Source/core/webcore_svg.target.darwin-x86.mk
@@ -302,7 +302,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -329,6 +328,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -455,7 +455,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -482,6 +481,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_svg.target.linux-arm.mk b/Source/core/webcore_svg.target.linux-arm.mk
index 139c8ea..3493e40 100644
--- a/Source/core/webcore_svg.target.linux-arm.mk
+++ b/Source/core/webcore_svg.target.linux-arm.mk
@@ -301,7 +301,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -328,6 +327,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -454,7 +454,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -481,6 +480,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_svg.target.linux-mips.mk b/Source/core/webcore_svg.target.linux-mips.mk
index 57675eb..9865c72 100644
--- a/Source/core/webcore_svg.target.linux-mips.mk
+++ b/Source/core/webcore_svg.target.linux-mips.mk
@@ -300,7 +300,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -327,6 +326,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -452,7 +452,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -479,6 +478,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/webcore_svg.target.linux-x86.mk b/Source/core/webcore_svg.target.linux-x86.mk
index 39a1c8d..fc4c338 100644
--- a/Source/core/webcore_svg.target.linux-x86.mk
+++ b/Source/core/webcore_svg.target.linux-x86.mk
@@ -302,7 +302,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -329,6 +328,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
@@ -455,7 +455,6 @@
 	'-DUSE_LIBJPEG_TURBO=1' \
 	'-DUSE_PROPRIETARY_CODECS' \
 	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DENABLE_NEW_GAMEPAD_API=1' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
 	'-DENABLE_EGLIMAGE=1' \
@@ -482,6 +481,7 @@
 	'-DSK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT' \
 	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
 	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
+	'-DSK_SUPPORT_LEGACY_READPIXELSCONFIG' \
 	'-DSK_SUPPORT_LEGACY_GETCLIPTYPE' \
 	'-DSK_SUPPORT_LEGACY_GETTOTALCLIP' \
 	'-DSK_SUPPORT_LEGACY_GETTOPDEVICE' \
diff --git a/Source/core/workers/WorkerGlobalScope.cpp b/Source/core/workers/WorkerGlobalScope.cpp
index 1699766..7078128 100644
--- a/Source/core/workers/WorkerGlobalScope.cpp
+++ b/Source/core/workers/WorkerGlobalScope.cpp
@@ -196,18 +196,16 @@
 {
     ASSERT(thread()->isCurrentThread());
 
-    // Notify proxy that we are going away. This can free the WorkerThread object, so do not access it after this.
-    thread()->workerReportingProxy().workerGlobalScopeDestroyed();
-
     clearScript();
     clearInspector();
     setClient(0);
 
-    // The thread reference isn't currently cleared, as the execution
-    // context's thread is accessed by GCed lifetime objects when
-    // they're finalized.
-    // FIXME: oilpan: avoid by explicitly removing the WorkerGlobalScope
-    // as an observable context right here.
+    // We do not clear the thread field of the
+    // WorkerGlobalScope. Other objects keep the worker global scope
+    // alive because they need its thread field to check that work is
+    // being carried out on the right thread. We therefore cannot clear
+    // the thread field before all references to the worker global
+    // scope are gone.
 }
 
 void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& exceptionState)
diff --git a/Source/core/workers/WorkerThread.cpp b/Source/core/workers/WorkerThread.cpp
index c605115..a956a82 100644
--- a/Source/core/workers/WorkerThread.cpp
+++ b/Source/core/workers/WorkerThread.cpp
@@ -145,8 +145,20 @@
 #endif
     m_workerGlobalScope = nullptr;
 
+    // Detach the ThreadState, cleaning out the thread's heap by
+    // performing a final GC. The cleanup operation will at the end
+    // assert that the heap is empty. If the heap does not become
+    // empty, there are still pointers into the heap and those
+    // pointers will be dangling after thread termination because we
+    // are destroying the heap. It is important to detach while the
+    // thread is still valid. In particular, finalizers for objects in
+    // the heap for this thread will need to access thread local data.
     ThreadState::detach();
 
+    // Notify the proxy that the WorkerGlobalScope has been disposed of.
+    // This can free this thread object, hence it must not be touched afterwards.
+    workerReportingProxy().workerGlobalScopeDestroyed();
+
     // Clean up PlatformThreadData before WTF::WTFThreadData goes away!
     PlatformThreadData::current().destroy();
 
diff --git a/Source/core/xml/DocumentXPathEvaluator.idl b/Source/core/xml/DocumentXPathEvaluator.idl
index 3ef7c2d..8380ad0 100644
--- a/Source/core/xml/DocumentXPathEvaluator.idl
+++ b/Source/core/xml/DocumentXPathEvaluator.idl
@@ -19,10 +19,10 @@
 
 partial interface Document {
     // DOM Level 3 XPath (XPathEvaluator interface)
-    [RaisesException] XPathExpression createExpression([Default=Undefined] optional DOMString expression,
+    [MeasureAs=DocumentXPathCreateExpression, RaisesException] XPathExpression createExpression([Default=Undefined] optional DOMString expression,
                                                        [Default=Undefined] optional XPathNSResolver resolver);
-    XPathNSResolver    createNSResolver(Node nodeResolver);
-    [Custom, RaisesException] XPathResult evaluate([Default=Undefined] optional DOMString expression,
+    [MeasureAs=DocumentXPathCreateNSResolver] XPathNSResolver    createNSResolver(Node nodeResolver);
+    [Custom, MeasureAs=DocumentXPathEvaluate, RaisesException] XPathResult evaluate([Default=Undefined] optional DOMString expression,
                                                    [Default=Undefined] optional Node contextNode,
                                                    [Default=Undefined] optional XPathNSResolver resolver,
                                                    [Default=Undefined] optional unsigned short type,
diff --git a/Source/core/xml/XSLImportRule.h b/Source/core/xml/XSLImportRule.h
index 4d9a77a..3521e69 100644
--- a/Source/core/xml/XSLImportRule.h
+++ b/Source/core/xml/XSLImportRule.h
@@ -58,9 +58,12 @@
 
     virtual void setXSLStyleSheet(const String& href, const KURL& baseURL, const String& sheet) OVERRIDE;
 
+    // FIXME: Oilpan: This raw pointer is safe and has to be kept raw at this
+    // point to avoid cycles. When XSLImportRule is moved to the oilpan heap
+    // it should be a Member and be traced.
     XSLStyleSheet* m_parentStyleSheet;
     String m_strHref;
-    RefPtr<XSLStyleSheet> m_styleSheet;
+    RefPtrWillBePersistent<XSLStyleSheet> m_styleSheet;
     ResourcePtr<XSLStyleSheetResource> m_resource;
     bool m_loading;
 };
diff --git a/Source/core/xml/XSLStyleSheet.h b/Source/core/xml/XSLStyleSheet.h
index a2064f3..fb80c6a 100644
--- a/Source/core/xml/XSLStyleSheet.h
+++ b/Source/core/xml/XSLStyleSheet.h
@@ -41,17 +41,17 @@
     static PassRefPtrWillBeRawPtr<XSLStyleSheet> create(XSLImportRule* parentImport, const String& originalURL, const KURL& finalURL)
     {
         ASSERT(RuntimeEnabledFeatures::xsltEnabled());
-        return adoptRefWillBeRefCountedGarbageCollected(new XSLStyleSheet(parentImport, originalURL, finalURL));
+        return adoptRefWillBeNoop(new XSLStyleSheet(parentImport, originalURL, finalURL));
     }
     static PassRefPtrWillBeRawPtr<XSLStyleSheet> create(ProcessingInstruction* parentNode, const String& originalURL, const KURL& finalURL)
     {
         ASSERT(RuntimeEnabledFeatures::xsltEnabled());
-        return adoptRefWillBeRefCountedGarbageCollected(new XSLStyleSheet(parentNode, originalURL, finalURL, false));
+        return adoptRefWillBeNoop(new XSLStyleSheet(parentNode, originalURL, finalURL, false));
     }
     static PassRefPtrWillBeRawPtr<XSLStyleSheet> createEmbedded(ProcessingInstruction* parentNode, const KURL& finalURL)
     {
         ASSERT(RuntimeEnabledFeatures::xsltEnabled());
-        return adoptRefWillBeRefCountedGarbageCollected(new XSLStyleSheet(parentNode, finalURL.string(), finalURL, true));
+        return adoptRefWillBeNoop(new XSLStyleSheet(parentNode, finalURL.string(), finalURL, true));
     }
 
     // Taking an arbitrary node is unsafe, because owner node pointer can become stale.
@@ -59,7 +59,7 @@
     static PassRefPtrWillBeRawPtr<XSLStyleSheet> createForXSLTProcessor(Node* parentNode, const String& originalURL, const KURL& finalURL)
     {
         ASSERT(RuntimeEnabledFeatures::xsltEnabled());
-        return adoptRefWillBeRefCountedGarbageCollected(new XSLStyleSheet(parentNode, originalURL, finalURL, false));
+        return adoptRefWillBeNoop(new XSLStyleSheet(parentNode, originalURL, finalURL, false));
     }
 
     virtual ~XSLStyleSheet();
@@ -119,7 +119,7 @@
     bool m_stylesheetDocTaken;
     bool m_compilationFailed;
 
-    XSLStyleSheet* m_parentStyleSheet;
+    RawPtrWillBeMember<XSLStyleSheet> m_parentStyleSheet;
 };
 
 DEFINE_TYPE_CASTS(XSLStyleSheet, StyleSheet, sheet, !sheet->isCSSStyleSheet(), !sheet.isCSSStyleSheet());
diff --git a/Source/core/xml/XSLStyleSheetLibxslt.cpp b/Source/core/xml/XSLStyleSheetLibxslt.cpp
index 215d922..e765eea 100644
--- a/Source/core/xml/XSLStyleSheetLibxslt.cpp
+++ b/Source/core/xml/XSLStyleSheetLibxslt.cpp
@@ -62,7 +62,7 @@
     , m_stylesheetDoc(0)
     , m_stylesheetDocTaken(false)
     , m_compilationFailed(false)
-    , m_parentStyleSheet(0)
+    , m_parentStyleSheet(nullptr)
 {
 }
 
@@ -303,8 +303,9 @@
     m_stylesheetDocTaken = true;
 }
 
-void XSLStyleSheet::trace(Visitor*)
+void XSLStyleSheet::trace(Visitor* visitor)
 {
+    visitor->trace(m_parentStyleSheet);
 }
 
 } // namespace WebCore
diff --git a/Source/core/xml/XSLTProcessor.cpp b/Source/core/xml/XSLTProcessor.cpp
index a2061fa..b6408db 100644
--- a/Source/core/xml/XSLTProcessor.cpp
+++ b/Source/core/xml/XSLTProcessor.cpp
@@ -54,8 +54,10 @@
 
 XSLTProcessor::~XSLTProcessor()
 {
+#if !ENABLE(OILPAN)
     // Stylesheet shouldn't outlive its root node.
     ASSERT(!m_stylesheetRootNode || !m_stylesheet || m_stylesheet->hasOneRef());
+#endif
 }
 
 PassRefPtr<Document> XSLTProcessor::createDocumentFromSource(const String& sourceString,
@@ -157,4 +159,9 @@
     m_parameters.clear();
 }
 
+void XSLTProcessor::trace(Visitor* visitor)
+{
+    visitor->trace(m_stylesheet);
+}
+
 } // namespace WebCore
diff --git a/Source/core/xml/XSLTProcessor.h b/Source/core/xml/XSLTProcessor.h
index 22fb56b..f66a16a 100644
--- a/Source/core/xml/XSLTProcessor.h
+++ b/Source/core/xml/XSLTProcessor.h
@@ -48,7 +48,7 @@
     }
     ~XSLTProcessor();
 
-    void setXSLStyleSheet(PassRefPtr<XSLStyleSheet> styleSheet) { m_stylesheet = styleSheet; }
+    void setXSLStyleSheet(PassRefPtrWillBeRawPtr<XSLStyleSheet> styleSheet) { m_stylesheet = styleSheet; }
     bool transformToString(Node* source, String& resultMIMEType, String& resultString, String& resultEncoding);
     PassRefPtr<Document> createDocumentFromSource(const String& source, const String& sourceEncoding, const String& sourceMIMEType, Node* sourceNode, LocalFrame* frame);
 
@@ -76,7 +76,7 @@
 
     typedef HashMap<String, String> ParameterMap;
 
-    void trace(Visitor*) { }
+    void trace(Visitor*);
 
 private:
     XSLTProcessor()
@@ -84,7 +84,7 @@
         ScriptWrappable::init(this);
     }
 
-    RefPtr<XSLStyleSheet> m_stylesheet;
+    RefPtrWillBeMember<XSLStyleSheet> m_stylesheet;
     RefPtr<Node> m_stylesheetRootNode;
     ParameterMap m_parameters;
 };
diff --git a/Source/core/xml/XSLTProcessorLibxslt.cpp b/Source/core/xml/XSLTProcessorLibxslt.cpp
index 278fe21..197b223 100644
--- a/Source/core/xml/XSLTProcessorLibxslt.cpp
+++ b/Source/core/xml/XSLTProcessorLibxslt.cpp
@@ -219,7 +219,7 @@
     fastFree(params);
 }
 
-static xsltStylesheetPtr xsltStylesheetPointer(RefPtr<XSLStyleSheet>& cachedStylesheet, Node* stylesheetRootNode)
+static xsltStylesheetPtr xsltStylesheetPointer(RefPtrWillBeMember<XSLStyleSheet>& cachedStylesheet, Node* stylesheetRootNode)
 {
     if (!cachedStylesheet && stylesheetRootNode) {
         cachedStylesheet = XSLStyleSheet::createForXSLTProcessor(stylesheetRootNode->parentNode() ? stylesheetRootNode->parentNode() : stylesheetRootNode,