Merge from Chromium at DEPS revision 240154

This commit was generated by merge_to_master.py.

Change-Id: Idca0efe87ed6b721349fbeab55bfdc919cc4941d
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index 1ebc4bb..b67b281 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -24,7 +24,6 @@
 #include "core/dom/Attr.h"
 
 #include "XMLNSNames.h"
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Element.h"
@@ -100,12 +99,12 @@
         return;
 
     if (prefix == xmlnsAtom && namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
-        exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + xmlnsAtom + "' may not be used on the namespace '" + namespaceURI() + "'."));
+        exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlnsAtom + "' may not be used on the namespace '" + namespaceURI() + "'.");
         return;
     }
 
     if (this->qualifiedName() == xmlnsAtom) {
-        exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + prefix + "' may not be used as a namespace prefix for attributes whose qualified name is '" + xmlnsAtom + "'."));
+        exceptionState.throwDOMException(NamespaceError, "The prefix '" + prefix + "' may not be used as a namespace prefix for attributes whose qualified name is '" + xmlnsAtom + "'.");
         return;
     }
 
diff --git a/Source/core/dom/CharacterData.cpp b/Source/core/dom/CharacterData.cpp
index d7f818a..d0344f2 100644
--- a/Source/core/dom/CharacterData.cpp
+++ b/Source/core/dom/CharacterData.cpp
@@ -22,7 +22,6 @@
 #include "config.h"
 #include "core/dom/CharacterData.h"
 
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
@@ -61,7 +60,7 @@
 String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& exceptionState)
 {
     if (offset > length()) {
-        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("substringData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+        exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ").");
         return String();
     }
 
@@ -95,7 +94,7 @@
 void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& exceptionState, RecalcStyleBehavior recalcStyleBehavior)
 {
     if (offset > length()) {
-        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+        exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ").");
         return;
     }
 
@@ -110,7 +109,7 @@
 void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& exceptionState, RecalcStyleBehavior recalcStyleBehavior)
 {
     if (offset > length()) {
-        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+        exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ").");
         return;
     }
 
@@ -131,7 +130,7 @@
 void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& exceptionState)
 {
     if (offset > length()) {
-        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("replaceData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+        exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ").");
         return;
     }
 
diff --git a/Source/core/dom/ChildListMutationScope.cpp b/Source/core/dom/ChildListMutationScope.cpp
index 47e296e..1d00364 100644
--- a/Source/core/dom/ChildListMutationScope.cpp
+++ b/Source/core/dom/ChildListMutationScope.cpp
@@ -33,10 +33,8 @@
 
 #include "core/dom/MutationObserverInterestGroup.h"
 #include "core/dom/MutationRecord.h"
-#include "core/dom/Node.h"
 #include "core/dom/StaticNodeList.h"
 #include "wtf/HashMap.h"
-#include "wtf/OwnPtr.h"
 #include "wtf/StdLibExtras.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/Comment.cpp b/Source/core/dom/Comment.cpp
index 186008a..90fb91b 100644
--- a/Source/core/dom/Comment.cpp
+++ b/Source/core/dom/Comment.cpp
@@ -39,7 +39,7 @@
 
 String Comment::nodeName() const
 {
-    return commentAtom.string();
+    return "#comment";
 }
 
 Node::NodeType Comment::nodeType() const
diff --git a/Source/core/dom/Comment.idl b/Source/core/dom/Comment.idl
index 0503d63..0297e95 100644
--- a/Source/core/dom/Comment.idl
+++ b/Source/core/dom/Comment.idl
@@ -19,7 +19,7 @@
 
 [
     Constructor([Default=NullString] optional DOMString data),
-    ConstructorCallWith=Document
+    ConstructorCallWith=Document,
 ] interface Comment : CharacterData {
 };
 
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index a352dce..3f8352c 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -23,9 +23,7 @@
 #include "config.h"
 #include "core/dom/ContainerNode.h"
 
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ChildListMutationScope.h"
 #include "core/dom/ContainerNodeAlgorithms.h"
 #include "core/dom/ElementTraversal.h"
@@ -43,7 +41,6 @@
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
-#include "wtf/Vector.h"
 
 using namespace std;
 
@@ -58,10 +55,6 @@
 unsigned NoEventDispatchAssertion::s_count = 0;
 #endif
 
-static const char appendChildMethodName[] = "appendChild";
-static const char insertBeforeMethodName[] = "insertBefore";
-static const char replaceChildMethodName[] = "replaceChild";
-
 static void collectChildrenAndRemoveFromOldParent(Node& node, NodeVector& nodes, ExceptionState& exceptionState)
 {
     if (!node.isDocumentFragment()) {
@@ -118,11 +111,11 @@
     return newChild.contains(this);
 }
 
-bool ContainerNode::checkAcceptChild(const Node* newChild, const Node* oldChild, const char* method, ExceptionState& exceptionState) const
+bool ContainerNode::checkAcceptChild(const Node* newChild, const Node* oldChild, ExceptionState& exceptionState) const
 {
     // Not mentioned in spec: throw NotFoundError if newChild is null
     if (!newChild) {
-        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(method, "Node", "The new child element is null."));
+        exceptionState.throwDOMException(NotFoundError, "The new child element is null.");
         return false;
     }
 
@@ -130,7 +123,7 @@
     if ((newChild->isElementNode() || newChild->isTextNode()) && isElementNode()) {
         ASSERT(isChildTypeAllowed(*newChild));
         if (containsConsideringHostElements(*newChild)) {
-            exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element contains the parent."));
+            exceptionState.throwDOMException(HierarchyRequestError, "The new child element contains the parent.");
             return false;
         }
         return true;
@@ -139,34 +132,34 @@
     // This should never happen, but also protect release builds from tree corruption.
     ASSERT(!newChild->isPseudoElement());
     if (newChild->isPseudoElement()) {
-        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element is a pseudo-element."));
+        exceptionState.throwDOMException(HierarchyRequestError, "The new child element is a pseudo-element.");
         return false;
     }
 
     if (containsConsideringHostElements(*newChild)) {
-        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element contains the parent."));
+        exceptionState.throwDOMException(HierarchyRequestError, "The new child element contains the parent.");
         return false;
     }
 
     if (oldChild && isDocumentNode()) {
         if (!toDocument(this)->canReplaceChild(*newChild, *oldChild)) {
             // FIXME: Adjust 'Document::canReplaceChild' to return some additional detail (or an error message).
-            exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "ContainerNode"));
+            exceptionState.throwDOMException(HierarchyRequestError, "Failed to replace child.");
             return false;
         }
     } else if (!isChildTypeAllowed(*newChild)) {
-        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "Nodes of type '" + newChild->nodeName() + "' may not be inserted inside nodes of type '" + nodeName() + "'."));
+        exceptionState.throwDOMException(HierarchyRequestError, "Nodes of type '" + newChild->nodeName() + "' may not be inserted inside nodes of type '" + nodeName() + "'.");
         return false;
     }
 
     return true;
 }
 
-bool ContainerNode::checkAcceptChildGuaranteedNodeTypes(const Node& newChild, const char* method, ExceptionState& exceptionState) const
+bool ContainerNode::checkAcceptChildGuaranteedNodeTypes(const Node& newChild, ExceptionState& exceptionState) const
 {
     ASSERT(isChildTypeAllowed(newChild));
     if (newChild.contains(this)) {
-        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute(method, "Node", "The new child element contains the parent."));
+        exceptionState.throwDOMException(HierarchyRequestError, "The new child element contains the parent.");
         return false;
     }
     return true;
@@ -187,13 +180,13 @@
     }
 
     // Make sure adding the new child is OK.
-    if (!checkAcceptChild(newChild.get(), 0, insertBeforeMethodName, exceptionState))
+    if (!checkAcceptChild(newChild.get(), 0, exceptionState))
         return;
     ASSERT(newChild);
 
     // NotFoundError: Raised if refChild is not a child of this node
     if (refChild->parentNode() != this) {
-        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(insertBeforeMethodName, "Node", "The node before which the new node is to be inserted is not a child of this node."));
+        exceptionState.throwDOMException(NotFoundError, "The node before which the new node is to be inserted is not a child of this node.");
         return;
     }
 
@@ -210,7 +203,7 @@
         return;
 
     // We need this extra check because collectChildrenAndRemoveFromOldParent() can fire mutation events.
-    if (!checkAcceptChildGuaranteedNodeTypes(*newChild, insertBeforeMethodName, exceptionState))
+    if (!checkAcceptChildGuaranteedNodeTypes(*newChild, exceptionState))
         return;
 
     InspectorInstrumentation::willInsertDOMNode(this);
@@ -300,17 +293,17 @@
         return;
 
     if (!oldChild) {
-        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(replaceChildMethodName, "Node", "The node to be replaced is null."));
+        exceptionState.throwDOMException(NotFoundError, "The node to be replaced is null.");
         return;
     }
 
     // Make sure replacing the old child with the new is ok
-    if (!checkAcceptChild(newChild.get(), oldChild, replaceChildMethodName, exceptionState))
+    if (!checkAcceptChild(newChild.get(), oldChild, exceptionState))
         return;
 
     // NotFoundError: Raised if oldChild is not a child of this node.
     if (oldChild->parentNode() != this) {
-        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute(replaceChildMethodName, "Node", "The node to be replaced is not a child of this node."));
+        exceptionState.throwDOMException(NotFoundError, "The node to be replaced is not a child of this node.");
         return;
     }
 
@@ -328,7 +321,7 @@
         return;
 
     // Does this one more time because removeChild() fires a MutationEvent.
-    if (!checkAcceptChild(newChild.get(), oldChild, replaceChildMethodName, exceptionState))
+    if (!checkAcceptChild(newChild.get(), oldChild, exceptionState))
         return;
 
     NodeVector targets;
@@ -337,7 +330,7 @@
         return;
 
     // Does this yet another check because collectChildrenAndRemoveFromOldParent() fires a MutationEvent.
-    if (!checkAcceptChild(newChild.get(), oldChild, replaceChildMethodName, exceptionState))
+    if (!checkAcceptChild(newChild.get(), oldChild, exceptionState))
         return;
 
     InspectorInstrumentation::willInsertDOMNode(this);
@@ -415,7 +408,7 @@
 
     // NotFoundError: Raised if oldChild is not a child of this node.
     if (!oldChild || oldChild->parentNode() != this) {
-        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "The node to be removed is not a child of this node."));
+        exceptionState.throwDOMException(NotFoundError, "The node to be removed is not a child of this node.");
         return;
     }
 
@@ -429,7 +422,7 @@
     // Events fired when blurring currently focused node might have moved this
     // child into a different parent.
     if (child->parentNode() != this) {
-        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "The node to be removed is no longer a child of this node. Perhaps it was moved in a 'blur' event handler?"));
+        exceptionState.throwDOMException(NotFoundError, "The node to be removed is no longer a child of this node. Perhaps it was moved in a 'blur' event handler?");
         return;
     }
 
@@ -437,7 +430,7 @@
 
     // Mutation events might have moved this child into a different parent.
     if (child->parentNode() != this) {
-        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "The node to be removed is no longer a child of this node. Perhaps it was moved in response to a mutation?"));
+        exceptionState.throwDOMException(NotFoundError, "The node to be removed is no longer a child of this node. Perhaps it was moved in response to a mutation?");
         return;
     }
 
@@ -560,7 +553,7 @@
     ASSERT(refCount() || parentOrShadowHostNode());
 
     // Make sure adding the new child is ok
-    if (!checkAcceptChild(newChild.get(), 0, appendChildMethodName, exceptionState))
+    if (!checkAcceptChild(newChild.get(), 0, exceptionState))
         return;
     ASSERT(newChild);
 
@@ -576,7 +569,7 @@
         return;
 
     // We need this extra check because collectChildrenAndRemoveFromOldParent() can fire mutation events.
-    if (!checkAcceptChildGuaranteedNodeTypes(*newChild, appendChildMethodName, exceptionState))
+    if (!checkAcceptChildGuaranteedNodeTypes(*newChild, exceptionState))
         return;
 
     InspectorInstrumentation::willInsertDOMNode(this);
@@ -813,6 +806,7 @@
         setNeedsStyleRecalc();
     if (renderer() && renderer()->style()->hasAppearance())
         RenderTheme::theme().stateChanged(renderer(), FocusState);
+    InspectorInstrumentation::pseudoStateChanged(this);
 }
 
 void ContainerNode::setFocus(bool received)
@@ -841,6 +835,7 @@
             setNeedsStyleRecalc();
         if (renderStyle()->hasAppearance())
             RenderTheme::theme().stateChanged(renderer(), PressedState);
+        InspectorInstrumentation::pseudoStateChanged(this);
     }
 }
 
@@ -855,6 +850,7 @@
     if (!renderer()) {
         if (!over)
             setNeedsStyleRecalc();
+        InspectorInstrumentation::pseudoStateChanged(this);
         return;
     }
 
@@ -863,6 +859,7 @@
             setNeedsStyleRecalc();
         if (renderer() && renderer()->style()->hasAppearance())
             RenderTheme::theme().stateChanged(renderer(), HoverState);
+        InspectorInstrumentation::pseudoStateChanged(this);
     }
 }
 
diff --git a/Source/core/dom/ContainerNode.h b/Source/core/dom/ContainerNode.h
index 3b55990..d64d782 100644
--- a/Source/core/dom/ContainerNode.h
+++ b/Source/core/dom/ContainerNode.h
@@ -152,8 +152,8 @@
     void willRemoveChildren();
     void willRemoveChild(Node& child);
 
-    inline bool checkAcceptChildGuaranteedNodeTypes(const Node& newChild, const char* method, ExceptionState&) const;
-    inline bool checkAcceptChild(const Node* newChild, const Node* oldChild, const char* method, ExceptionState&) const;
+    inline bool checkAcceptChildGuaranteedNodeTypes(const Node& newChild, ExceptionState&) const;
+    inline bool checkAcceptChild(const Node* newChild, const Node* oldChild, ExceptionState&) const;
     inline bool containsConsideringHostElements(const Node&) const;
     inline bool isChildTypeAllowed(const Node& child) const;
 
diff --git a/Source/core/dom/ContainerNodeAlgorithms.cpp b/Source/core/dom/ContainerNodeAlgorithms.cpp
index 1caa683..4c55b46 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.cpp
+++ b/Source/core/dom/ContainerNodeAlgorithms.cpp
@@ -29,7 +29,6 @@
 #include "core/dom/Element.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/html/HTMLFrameOwnerElement.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ContextFeatures.h b/Source/core/dom/ContextFeatures.h
index b3f309f..109b781 100644
--- a/Source/core/dom/ContextFeatures.h
+++ b/Source/core/dom/ContextFeatures.h
@@ -102,9 +102,14 @@
 
 inline void ContextFeatures::urlDidChange(Document* document)
 {
-    if (m_client)
-        return;
-    m_client->urlDidChange(document);
+    // FIXME: The original code, commented out below, is obviously
+    // wrong, but the seemingly correct fix of negating the test to
+    // the more logical 'if (!m_client)' crashes the renderer.
+    // See issue 294180
+    //
+    // if (m_client)
+    //     return;
+    // m_client->urlDidChange(document);
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DOMError.cpp b/Source/core/dom/DOMError.cpp
index e77d271..3d41a04 100644
--- a/Source/core/dom/DOMError.cpp
+++ b/Source/core/dom/DOMError.cpp
@@ -26,7 +26,6 @@
 #include "config.h"
 #include "core/dom/DOMError.h"
 
-#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index 83885b3..ff898a5 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -47,10 +47,10 @@
 #include "core/loader/FrameLoader.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/platform/graphics/Image.h"
 #include "core/svg/SVGDocument.h"
 #include "platform/ContentType.h"
 #include "platform/MIMETypeRegistry.h"
+#include "platform/graphics/Image.h"
 #include "platform/graphics/media/MediaPlayer.h"
 #include "platform/plugins/PluginData.h"
 #include "platform/weborigin/SecurityOrigin.h"
@@ -178,10 +178,10 @@
     return true;
 }
 
-PassRefPtr<DocumentType> DOMImplementation::createDocumentType(const String& qualifiedName,
+PassRefPtr<DocumentType> DOMImplementation::createDocumentType(const AtomicString& qualifiedName,
     const String& publicId, const String& systemId, ExceptionState& exceptionState)
 {
-    String prefix, localName;
+    AtomicString prefix, localName;
     if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return 0;
 
@@ -193,8 +193,8 @@
     return 0;
 }
 
-PassRefPtr<Document> DOMImplementation::createDocument(const String& namespaceURI,
-    const String& qualifiedName, DocumentType* doctype, ExceptionState& exceptionState)
+PassRefPtr<Document> DOMImplementation::createDocument(const AtomicString& namespaceURI,
+    const AtomicString& qualifiedName, DocumentType* doctype, ExceptionState& exceptionState)
 {
     RefPtr<Document> doc;
     DocumentInit init = DocumentInit::fromContext(m_document.contextDocument());
diff --git a/Source/core/dom/DOMImplementation.h b/Source/core/dom/DOMImplementation.h
index 76852d3..b710d2a 100644
--- a/Source/core/dom/DOMImplementation.h
+++ b/Source/core/dom/DOMImplementation.h
@@ -50,8 +50,8 @@
 
     // DOM methods & attributes for DOMImplementation
     static bool hasFeature(const String& feature, const String& version);
-    PassRefPtr<DocumentType> createDocumentType(const String& qualifiedName, const String& publicId, const String& systemId, ExceptionState&);
-    PassRefPtr<Document> createDocument(const String& namespaceURI, const String& qualifiedName, DocumentType*, ExceptionState&);
+    PassRefPtr<DocumentType> createDocumentType(const AtomicString& qualifiedName, const String& publicId, const String& systemId, ExceptionState&);
+    PassRefPtr<Document> createDocument(const AtomicString& namespaceURI, const AtomicString& qualifiedName, DocumentType*, ExceptionState&);
 
     DOMImplementation* getInterface(const String& feature);
 
diff --git a/Source/core/dom/DOMImplementation.idl b/Source/core/dom/DOMImplementation.idl
index 9c42ec0..7630c5e 100644
--- a/Source/core/dom/DOMImplementation.idl
+++ b/Source/core/dom/DOMImplementation.idl
@@ -24,25 +24,24 @@
 
     // DOM Level 1
 
-     boolean hasFeature([Default=Undefined] optional DOMString feature,
-                                      [TreatNullAs=NullString,Default=Undefined] optional DOMString version);
+    boolean hasFeature(DOMString feature, [TreatNullAs=NullString] DOMString version);
 
     // DOM Level 2
 
-     [RaisesException] DocumentType createDocumentType([TreatNullAs=NullString] DOMString qualifiedName,
-                                                       [TreatNullAs=NullString] DOMString publicId,
-                                                       [TreatNullAs=NullString] DOMString systemId);
-     [RaisesException] Document createDocument([TreatNullAs=NullString] DOMString namespaceURI,
-                                               [TreatNullAs=NullString] DOMString qualifiedName,
-                                               [Default=Undefined] optional DocumentType doctype);
+    [RaisesException] DocumentType createDocumentType(DOMString qualifiedName,
+                                                      DOMString publicId,
+                                                      DOMString systemId);
+    [RaisesException] Document createDocument([TreatNullAs=NullString] DOMString namespaceURI,
+                                              [TreatNullAs=NullString] DOMString qualifiedName,
+                                              [Default=Undefined] optional DocumentType doctype);
 
     // DOMImplementationCSS interface from DOM Level 2 CSS
 
-     CSSStyleSheet createCSSStyleSheet([Default=Undefined] optional DOMString title,
-                                       [Default=Undefined] optional DOMString media);
+    [MeasureAs=DOMImplementationCreateCSSStyleSheet]
+    CSSStyleSheet createCSSStyleSheet([Default=Undefined] optional DOMString title,
+                                      [Default=Undefined] optional DOMString media);
 
     // HTMLDOMImplementation interface from DOM Level 2 HTML
 
     HTMLDocument createHTMLDocument([Default=NullString] optional DOMString title);
 };
-
diff --git a/Source/core/dom/DOMNamedFlowCollection.cpp b/Source/core/dom/DOMNamedFlowCollection.cpp
index 695bbbc..9fbf981 100644
--- a/Source/core/dom/DOMNamedFlowCollection.cpp
+++ b/Source/core/dom/DOMNamedFlowCollection.cpp
@@ -31,7 +31,6 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/NamedFlow.h"
-#include "core/dom/NamedFlowCollection.h"
 #include "wtf/text/StringHash.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/DOMTokenList.cpp b/Source/core/dom/DOMTokenList.cpp
index fc815ee..41255b2 100644
--- a/Source/core/dom/DOMTokenList.cpp
+++ b/Source/core/dom/DOMTokenList.cpp
@@ -25,7 +25,6 @@
 #include "config.h"
 #include "core/dom/DOMTokenList.h"
 
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/html/parser/HTMLParserIdioms.h"
@@ -33,17 +32,17 @@
 
 namespace WebCore {
 
-bool DOMTokenList::validateToken(const AtomicString& token, const char* method, ExceptionState& exceptionState)
+bool DOMTokenList::validateToken(const AtomicString& token, ExceptionState& exceptionState)
 {
     if (token.isEmpty()) {
-        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute(method, "DOMTokenList", "The token provided must not be empty."));
+        exceptionState.throwDOMException(SyntaxError, "The token provided must not be empty.");
         return false;
     }
 
     unsigned length = token.length();
     for (unsigned i = 0; i < length; ++i) {
         if (isHTMLSpace<UChar>(token[i])) {
-            exceptionState.throwDOMException(InvalidCharacterError, ExceptionMessages::failedToExecute(method, "DOMTokenList", "The token provided ('" + token + "') contains HTML space characters, which are not valid in tokens."));
+            exceptionState.throwDOMException(InvalidCharacterError, "The token provided ('" + token + "') contains HTML space characters, which are not valid in tokens.");
             return false;
         }
     }
@@ -51,10 +50,10 @@
     return true;
 }
 
-bool DOMTokenList::validateTokens(const Vector<String>& tokens, const char* method, ExceptionState& exceptionState)
+bool DOMTokenList::validateTokens(const Vector<String>& tokens, ExceptionState& exceptionState)
 {
     for (size_t i = 0; i < tokens.size(); ++i) {
-        if (!validateToken(tokens[i], method, exceptionState))
+        if (!validateToken(tokens[i], exceptionState))
             return false;
     }
 
@@ -63,7 +62,7 @@
 
 bool DOMTokenList::contains(const AtomicString& token, ExceptionState& exceptionState) const
 {
-    if (!validateToken(token, "contains", exceptionState))
+    if (!validateToken(token, exceptionState))
         return false;
     return containsInternal(token);
 }
@@ -80,7 +79,7 @@
     Vector<String> filteredTokens;
     filteredTokens.reserveCapacity(tokens.size());
     for (size_t i = 0; i < tokens.size(); ++i) {
-        if (!validateToken(tokens[i], "add", exceptionState))
+        if (!validateToken(tokens[i], exceptionState))
             return;
         if (containsInternal(tokens[i]))
             continue;
@@ -104,7 +103,7 @@
 
 void DOMTokenList::remove(const Vector<String>& tokens, ExceptionState& exceptionState)
 {
-    if (!validateTokens(tokens, "remove", exceptionState))
+    if (!validateTokens(tokens, exceptionState))
         return;
 
     // Check using containsInternal first since it is a lot faster than going
@@ -123,7 +122,7 @@
 
 bool DOMTokenList::toggle(const AtomicString& token, ExceptionState& exceptionState)
 {
-    if (!validateToken(token, "toggle", exceptionState))
+    if (!validateToken(token, exceptionState))
         return false;
 
     if (containsInternal(token)) {
@@ -136,7 +135,7 @@
 
 bool DOMTokenList::toggle(const AtomicString& token, bool force, ExceptionState& exceptionState)
 {
-    if (!validateToken(token, "toggle", exceptionState))
+    if (!validateToken(token, exceptionState))
         return false;
 
     if (force)
diff --git a/Source/core/dom/DOMTokenList.h b/Source/core/dom/DOMTokenList.h
index 1b1957e..d758214 100644
--- a/Source/core/dom/DOMTokenList.h
+++ b/Source/core/dom/DOMTokenList.h
@@ -69,8 +69,8 @@
     virtual bool containsInternal(const AtomicString&) const = 0;
     virtual void removeInternal(const AtomicString&);
 
-    static bool validateToken(const AtomicString&, const char* method, ExceptionState&);
-    static bool validateTokens(const Vector<String>&, const char* method, ExceptionState&);
+    static bool validateToken(const AtomicString&, ExceptionState&);
+    static bool validateTokens(const Vector<String>&, ExceptionState&);
     static String addToken(const AtomicString&, const AtomicString&);
     static String addTokens(const AtomicString&, const Vector<String>&);
     static String removeToken(const AtomicString&, const AtomicString&);
diff --git a/Source/core/dom/DOMURL.cpp b/Source/core/dom/DOMURL.cpp
index a61485e..8881223 100644
--- a/Source/core/dom/DOMURL.cpp
+++ b/Source/core/dom/DOMURL.cpp
@@ -44,11 +44,11 @@
 {
     ScriptWrappable::init(this);
     if (!base.isValid())
-        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToConstruct("URL", "Invalid base URL"));
+        exceptionState.throwDOMException(SyntaxError, "Invalid base URL");
 
     m_url = KURL(base, url);
     if (!m_url.isValid())
-        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToConstruct("URL", "Invalid URL"));
+        exceptionState.throwDOMException(SyntaxError, "Invalid URL");
 }
 
 void DOMURL::setInput(const String& value)
diff --git a/Source/core/dom/DataTransferItem.cpp b/Source/core/dom/DataTransferItem.cpp
index 8d2d976..369b7f1 100644
--- a/Source/core/dom/DataTransferItem.cpp
+++ b/Source/core/dom/DataTransferItem.cpp
@@ -64,7 +64,7 @@
     return m_item->type();
 }
 
-void DataTransferItem::getAsString(ExecutionContext* context, PassRefPtr<StringCallback> callback) const
+void DataTransferItem::getAsString(ExecutionContext* context, PassOwnPtr<StringCallback> callback) const
 {
     if (!m_clipboard->canReadData())
         return;
diff --git a/Source/core/dom/DataTransferItem.h b/Source/core/dom/DataTransferItem.h
index d06256e..03dd377 100644
--- a/Source/core/dom/DataTransferItem.h
+++ b/Source/core/dom/DataTransferItem.h
@@ -56,7 +56,7 @@
     String kind() const;
     String type() const;
 
-    void getAsString(ExecutionContext*, PassRefPtr<StringCallback>) const;
+    void getAsString(ExecutionContext*, PassOwnPtr<StringCallback>) const;
     PassRefPtr<Blob> getAsFile() const;
 
     Clipboard* clipboard() { return m_clipboard.get(); }
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index 26e2db8..2e9ebcf 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -86,7 +86,6 @@
 #include "core/dom/NodeWithIndex.h"
 #include "core/dom/PostAttachCallbacks.h"
 #include "core/dom/ProcessingInstruction.h"
-#include "core/dom/QualifiedName.h"
 #include "core/dom/RequestAnimationFrameCallback.h"
 #include "core/dom/ScriptRunner.h"
 #include "core/dom/ScriptedAnimationController.h"
@@ -95,7 +94,6 @@
 #include "core/dom/TouchList.h"
 #include "core/dom/TransformSource.h"
 #include "core/dom/TreeWalker.h"
-#include "core/dom/UserActionElementSet.h"
 #include "core/dom/VisitedLinkState.h"
 #include "core/dom/custom/CustomElementRegistrationContext.h"
 #include "core/dom/shadow/ElementShadow.h"
@@ -161,21 +159,21 @@
 #include "core/page/PointerLockController.h"
 #include "core/page/Settings.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/rendering/HitTestRequest.h"
+#include "core/rendering/FastTextAutosizer.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
 #include "core/rendering/TextAutosizer.h"
 #include "core/svg/SVGDocumentExtensions.h"
+#include "core/svg/SVGFontFaceElement.h"
 #include "core/svg/SVGStyleElement.h"
 #include "core/xml/XSLTProcessor.h"
 #include "core/xml/parser/XMLDocumentParser.h"
 #include "platform/DateComponents.h"
 #include "platform/Language.h"
-#include "platform/Timer.h"
 #include "platform/TraceEvent.h"
 #include "platform/network/HTTPParsers.h"
+#include "platform/scroll/ScrollbarTheme.h"
 #include "platform/text/PlatformLocale.h"
 #include "platform/text/SegmentedString.h"
 #include "platform/weborigin/OriginAccessEntry.h"
@@ -184,10 +182,8 @@
 #include "wtf/CurrentTime.h"
 #include "wtf/HashFunctions.h"
 #include "wtf/MainThread.h"
-#include "wtf/PassRefPtr.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/TemporaryChange.h"
-#include "wtf/UnusedParam.h"
 #include "wtf/text/StringBuffer.h"
 #include "wtf/text/TextEncodingRegistry.h"
 
@@ -396,7 +392,6 @@
     , m_domTreeVersion(++s_globalTreeVersion)
     , m_listenerTypes(0)
     , m_mutationObserverTypes(0)
-    , m_styleEngine(StyleEngine::create(*this))
     , m_visitedLinkState(VisitedLinkState::create(*this))
     , m_visuallyOrdered(false)
     , m_readyState(Complete)
@@ -443,7 +438,6 @@
     , m_writeRecursionDepth(0)
     , m_lastHandledUserGestureTimestamp(0)
     , m_taskRunner(MainThreadTaskRunner::create(this))
-    , m_textAutosizer(TextAutosizer::create(this))
     , m_registrationContext(initializer.registrationContext(this))
     , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
 #ifndef NDEBUG
@@ -485,6 +479,11 @@
     InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
 
     m_lifecyle.advanceTo(DocumentLifecycle::Inactive);
+
+    // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
+    // CSSFontSelector, need to initialize m_styleEngine after initializing
+    // m_fetcher.
+    m_styleEngine = StyleEngine::create(*this);
 }
 
 Document::~Document()
@@ -714,9 +713,9 @@
     return element;
 }
 
-PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
+PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
 {
-    String prefix, localName;
+    AtomicString prefix, localName;
     if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return 0;
 
@@ -792,7 +791,7 @@
         exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
         return 0;
     }
-    if (data.find("]]>") != WTF::kNotFound) {
+    if (data.contains("]]>")) {
         exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
         return 0;
     }
@@ -802,11 +801,11 @@
 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
 {
     if (!isValidName(target)) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
         return 0;
     }
-    if (isHTMLDocument()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+    if (data.contains("?>")) {
+        exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
         return 0;
     }
     return ProcessingInstruction::create(*this, target, data);
@@ -1024,9 +1023,9 @@
     return m_namedFlows.get();
 }
 
-PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& exceptionState)
+PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
 {
-    String prefix, localName;
+    AtomicString prefix, localName;
     if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return 0;
 
@@ -1067,7 +1066,7 @@
     case Loading:
         if (!m_documentTiming.domLoading) {
             m_documentTiming.domLoading = monotonicallyIncreasingTime();
-            if (RuntimeEnabledFeatures::webAnimationsEnabled())
+            if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
                 m_timeline->setZeroTime(m_documentTiming.domLoading);
         }
         break;
@@ -1090,7 +1089,7 @@
     return m_readyState == Complete;
 }
 
-String Document::encodingName() const
+AtomicString Document::encodingName() const
 {
     // TextEncoding::name() returns a char*, no need to allocate a new
     // String for it each time.
@@ -1118,7 +1117,7 @@
     setEncodingData(newEncodingData);
 }
 
-void Document::setContentLanguage(const String& language)
+void Document::setContentLanguage(const AtomicString& language)
 {
     if (m_contentLanguage == language)
         return;
@@ -1467,17 +1466,6 @@
     return NodeIterator::create(root, whatToShow, filter);
 }
 
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& exceptionState)
-{
-    if (!root) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-    // FIXME: Warn if |expandEntityReferences| is specified. This optional argument is deprecated in DOM4.
-    UNUSED_PARAM(expandEntityReferences);
-    return NodeIterator::create(root, whatToShow, filter);
-}
-
 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
 {
     if (!root) {
@@ -1505,16 +1493,6 @@
     return TreeWalker::create(root, whatToShow, filter);
 }
 
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& exceptionState)
-{
-    UNUSED_PARAM(expandEntityReferences);
-    if (!root) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-    return TreeWalker::create(root, whatToShow, filter);
-}
-
 void Document::scheduleStyleRecalc()
 {
     if (shouldDisplaySeamlesslyWithParent()) {
@@ -1605,7 +1583,7 @@
 
     RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
     if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
-        documentElementStyle = styleResolver()->styleForElement(documentElement());
+        documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
 
     WritingMode rootWritingMode = documentElementStyle->writingMode();
     TextDirection rootDirection = documentElementStyle->direction();
@@ -1614,7 +1592,7 @@
     if (body) {
         RefPtr<RenderStyle> bodyStyle = body->renderStyle();
         if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
-            bodyStyle = styleResolver()->styleForElement(body, documentElementStyle.get());
+            bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
         if (!writingModeSetOnDocumentElement())
             rootWritingMode = bodyStyle->writingMode();
         if (!directionSetOnDocumentElement())
@@ -1689,7 +1667,7 @@
         if (styleChangeType() >= SubtreeStyleChange)
             change = Force;
 
-        // FIXME: Cannot access the styleResolver() before calling styleForDocument below because
+        // FIXME: Cannot access the ensureStyleResolver() before calling styleForDocument below because
         // apparently the StyleResolver's constructor has side effects. We should fix it.
         // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
         // mac when accessing the resolver by what appears to be a viewport size difference.
@@ -1708,9 +1686,9 @@
         // Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
         // entire DOM (where collecting them is very slow).
         // FIXME: Expose this as a runtime flag.
-        // styleResolver()->enableStats(/*StyleResolver::ReportSlowStats*/);
+        // ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
 
-        if (StyleResolverStats* stats = styleResolver()->stats())
+        if (StyleResolverStats* stats = ensureStyleResolver().stats())
             stats->reset();
 
         if (Element* documentElement = this->documentElement()) {
@@ -1719,7 +1697,7 @@
                 documentElement->recalcStyle(change);
         }
 
-        styleResolver()->printStats();
+        ensureStyleResolver().printStats();
 
         view()->updateCompositingLayersAfterStyleChange();
 
@@ -1733,8 +1711,9 @@
 
         if (m_styleEngine->hasResolver()) {
             // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
-            m_styleEngine->resetCSSFeatureFlags(m_styleEngine->resolver()->ensureRuleFeatureSet());
-            m_styleEngine->resolver()->clearStyleSharingList();
+            StyleResolver& resolver = m_styleEngine->ensureResolver();
+            m_styleEngine->resetCSSFeatureFlags(resolver.ensureRuleFeatureSet());
+            resolver.clearStyleSharingList();
         }
     }
 
@@ -1776,7 +1755,7 @@
 {
     ASSERT(isMainThread());
 
-    FrameView* frameView = view();
+    RefPtr<FrameView> frameView = view();
     if (frameView && frameView->isInLayout()) {
         // View layout should not be re-entrant.
         ASSERT_NOT_REACHED();
@@ -1789,10 +1768,10 @@
     updateStyleIfNeeded();
 
     // Only do a layout if changes have occurred that make it necessary.
-    if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
+    if (isActive() && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
         frameView->layout();
 
-    if (frameView)
+    if (isActive() && frameView)
         frameView->partialLayout().reset();
 
     setNeedsFocusedElementCheck();
@@ -1884,12 +1863,12 @@
 {
     ASSERT_ARG(element, element->document() == this);
     StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
-    return styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
+    return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
 }
 
 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
 {
-    return styleResolver()->styleForPage(pageIndex);
+    return ensureStyleResolver().styleForPage(pageIndex);
 }
 
 bool Document::isPageBoxVisible(int pageIndex)
@@ -1946,16 +1925,16 @@
     didUpdateSecurityOrigin();
 }
 
-StyleResolver* Document::styleResolverIfExists() const
-{
-    return m_styleEngine->resolverIfExists();
-}
-
 StyleResolver* Document::styleResolver() const
 {
     return m_styleEngine->resolver();
 }
 
+StyleResolver& Document::ensureStyleResolver() const
+{
+    return m_styleEngine->ensureResolver();
+}
+
 void Document::clearStyleResolver()
 {
     m_styleEngine->clearResolver();
@@ -2155,7 +2134,6 @@
         setURL(ownerDocument->url());
         m_cookieURL = ownerDocument->cookieURL();
         setSecurityOrigin(ownerDocument->securityOrigin());
-        InspectorInstrumentation::childDocumentOpened(this);
     }
 
     if (m_frame) {
@@ -2824,7 +2802,7 @@
     return m_elemSheet.get();
 }
 
-void Document::processHttpEquiv(const String& equiv, const String& content)
+void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content)
 {
     ASSERT(!equiv.isNull() && !content.isNull());
 
@@ -2847,7 +2825,7 @@
         processHttpEquivContentSecurityPolicy(equiv, content);
 }
 
-void Document::processHttpEquivContentSecurityPolicy(const String& equiv, const String& content)
+void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
 {
     if (equalIgnoringCase(equiv, "content-security-policy"))
         contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
@@ -2862,7 +2840,7 @@
         ASSERT_NOT_REACHED();
 }
 
-void Document::processHttpEquivDefaultStyle(const String& content)
+void Document::processHttpEquivDefaultStyle(const AtomicString& content)
 {
     // The preferred style set has been overridden as per section
     // 14.3.2 of the HTML4.0 specification. We need to update the
@@ -2875,7 +2853,7 @@
     styleResolverChanged(RecalcStyleDeferred);
 }
 
-void Document::processHttpEquivRefresh(const String& content)
+void Document::processHttpEquivRefresh(const AtomicString& content)
 {
     maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
 }
@@ -2908,7 +2886,7 @@
     m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
 }
 
-void Document::processHttpEquivSetCookie(const String& content)
+void Document::processHttpEquivSetCookie(const AtomicString& content)
 {
     // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
     if (!isHTMLDocument())
@@ -2918,7 +2896,7 @@
     toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
 }
 
-void Document::processHttpEquivXFrameOptions(const String& content)
+void Document::processHttpEquivXFrameOptions(const AtomicString& content)
 {
     Frame* frame = this->frame();
     if (!frame)
@@ -3176,8 +3154,12 @@
 
 void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
 {
-    StyleResolverChange change = m_styleEngine->resolverChanged(updateMode);
+    // styleResolverChanged() can be invoked during Document destruction.
+    // We just skip that case.
+    if (!m_styleEngine)
+        return;
 
+    StyleResolverChange change = m_styleEngine->resolverChanged(updateTime, updateMode);
     if (change.needsRepaint()) {
         // We need to manually repaint because we avoid doing all repaints in layout or style
         // recalc while sheets are still loading to avoid FOUC.
@@ -3504,10 +3486,8 @@
             (*it)->nodeWillBeRemoved(*n);
     }
 
-    Frame* frame = this->frame();
-    for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
-        m_markers->nodeWillBeRemoved(*n);
-        if (frame) {
+    if (Frame* frame = this->frame()) {
+        for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
             frame->eventHandler().nodeWillBeRemoved(*n);
             frame->selection().nodeWillBeRemoved(*n);
             frame->page()->dragCaretController().nodeWillBeRemoved(*n);
@@ -3532,8 +3512,6 @@
         frame->selection().nodeWillBeRemoved(n);
         frame->page()->dragCaretController().nodeWillBeRemoved(n);
     }
-
-    m_markers->nodeWillBeRemoved(n);
 }
 
 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
@@ -3670,6 +3648,7 @@
         UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
         addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
     } else if (eventType == EventTypeNames::overflowchanged) {
+        UseCounter::count(*this, UseCounter::OverflowChangedEvent);
         addListenerType(OVERFLOWCHANGED_LISTENER);
     } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
         addListenerType(ANIMATIONSTART_LISTENER);
@@ -3688,6 +3667,8 @@
         addListenerType(BEFORELOAD_LISTENER);
     } else if (eventType == EventTypeNames::scroll) {
         addListenerType(SCROLL_LISTENER);
+    } else if (eventType == EventTypeNames::DOMFocusIn || eventType == EventTypeNames::DOMFocusOut) {
+        UseCounter::count(*this, UseCounter::DOMFocusInOutEvent);
     }
 }
 
@@ -3713,13 +3694,12 @@
     // browsing context.
 
     if (!securityOrigin()->canAccessCookies()) {
-        String accessDeniedMessage = "Access to 'cookie' is denied for this document.";
         if (isSandboxed(SandboxOrigin))
-            exceptionState.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
+            exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
         else if (url().protocolIs("data"))
-            exceptionState.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+            exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
         else
-            exceptionState.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError("Access is denied for this document.");
         return String();
     }
 
@@ -3740,13 +3720,12 @@
     // browsing context.
 
     if (!securityOrigin()->canAccessCookies()) {
-        String accessDeniedMessage = "Access to 'cookie' is denied for this document.";
         if (isSandboxed(SandboxOrigin))
-            exceptionState.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
+            exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
         else if (url().protocolIs("data"))
-            exceptionState.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+            exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
         else
-            exceptionState.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError("Access is denied for this document.");
         return;
     }
 
@@ -3757,11 +3736,11 @@
     setCookies(this, cookieURL, value);
 }
 
-String Document::referrer() const
+const AtomicString& Document::referrer() const
 {
     if (loader())
         return loader()->request().httpReferrer();
-    return String();
+    return nullAtom;
 }
 
 String Document::domain() const
@@ -3771,14 +3750,18 @@
 
 void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
 {
+    if (isSandboxed(SandboxDocumentDomain)) {
+        exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
+        return;
+    }
+
     if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
-        exceptionState.throwSecurityError(ExceptionMessages::failedToSet("domain", "Document", "assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme."));
+        exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
         return;
     }
 
     if (newDomain.isEmpty()) {
-        String exceptionMessage = ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is an empty domain.");
-        exceptionState.throwSecurityError(exceptionMessage);
+        exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
         return;
     }
 
@@ -3786,14 +3769,12 @@
     OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
     OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
     if (result == OriginAccessEntry::DoesNotMatchOrigin) {
-        String exceptionMessage = ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is not a suffix of '" + domain() + "'.");
-        exceptionState.throwSecurityError(exceptionMessage);
+        exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
         return;
     }
 
     if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
-        String exceptionMessage = ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is a top-level domain.");
-        exceptionState.throwSecurityError(exceptionMessage);
+        exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
         return;
     }
 
@@ -3808,12 +3789,12 @@
     DateComponents date;
     bool foundDate = false;
     if (m_frame) {
-        String httpLastModified;
-        if (DocumentLoader* documentLoader = loader())
-            httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
-        if (!httpLastModified.isEmpty()) {
-            date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
-            foundDate = true;
+        if (DocumentLoader* documentLoader = loader()) {
+            const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
+            if (!httpLastModified.isEmpty()) {
+                date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
+                foundDate = true;
+            }
         }
     }
     // FIXME: If this document came from the file system, the HTML5
@@ -3900,7 +3881,7 @@
 }
 
 template<typename CharType>
-static bool parseQualifiedNameInternal(const String& qualifiedName, const CharType* characters, unsigned length, String& prefix, String& localName, ExceptionState& exceptionState)
+static bool parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
 {
     bool nameStart = true;
     bool sawColon = false;
@@ -3932,15 +3913,16 @@
     }
 
     if (!sawColon) {
-        prefix = String();
+        prefix = nullAtom;
         localName = qualifiedName;
     } else {
-        prefix = qualifiedName.substring(0, colonPos);
+        prefix = AtomicString(characters, colonPos);
         if (prefix.isEmpty()) {
             exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
             return false;
         }
-        localName = qualifiedName.substring(colonPos + 1);
+        int prefixStart = colonPos + 1;
+        localName = AtomicString(characters + prefixStart, length - prefixStart);
     }
 
     if (localName.isEmpty()) {
@@ -3951,7 +3933,7 @@
     return true;
 }
 
-bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionState& exceptionState)
+bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
 {
     unsigned length = qualifiedName.length();
 
@@ -3982,7 +3964,7 @@
         CString originalBytes = m_titleElement->textContent().latin1();
         OwnPtr<TextCodec> codec = newTextCodec(newData.encoding);
         String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), true);
-        m_titleElement->setTextContent(correctlyDecodedTitle, IGNORE_EXCEPTION);
+        m_titleElement->setTextContent(correctlyDecodedTitle);
     }
 
     m_encodingData = newData;
@@ -3995,7 +3977,12 @@
     // See also [CSS]StyleSheet::completeURL(const String&)
     if (url.isNull())
         return KURL();
-    const KURL& baseURL = ((baseURLOverride.isEmpty() || baseURLOverride == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : baseURLOverride;
+    const KURL* baseURLFromParent = 0;
+    if (baseURLOverride.isEmpty() || baseURLOverride == blankURL()) {
+        if (Document* parent = parentDocument())
+            baseURLFromParent = &parent->baseURL();
+    }
+    const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
     if (!encoding().isValid())
         return KURL(baseURL, url);
     return KURL(baseURL, url, encoding());
@@ -4163,14 +4150,14 @@
     return WeakPtr<Document>(0);
 }
 
-PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionState& exceptionState)
+PassRefPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
 {
-    return createAttributeNS(String(), name, exceptionState, true);
+    return createAttributeNS(nullAtom, name, exceptionState, true);
 }
 
-PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
+PassRefPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
 {
-    String prefix, localName;
+    AtomicString prefix, localName;
     if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return 0;
 
@@ -4772,7 +4759,7 @@
     return *m_scriptedAnimationController;
 }
 
-int Document::requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
+int Document::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
 {
     return ensureScriptedAnimationController().registerCallback(callback);
 }
@@ -4984,6 +4971,9 @@
 {
     ASSERT(!request.readOnly());
 
+    if (request.active() && m_frame)
+        m_frame->eventHandler().notifyElementActivated();
+
     Element* innerElementInDocument = innerElement;
     while (innerElementInDocument && innerElementInDocument->document() != this) {
         innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
@@ -5198,20 +5188,36 @@
 
 void Document::removedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
 {
-    if (!isActive())
-        return;
-
-    styleEngine()->modifiedStyleSheet(sheet);
+    // If we're in document teardown, then we don't need this notification of our sheet's removal.
+    // styleResolverChanged() is needed even when the document is inactive so that
+    // imported docuements (which is inactive) notifies the change to the master document.
+    if (isActive())
+        styleEngine()->modifiedStyleSheet(sheet);
     styleResolverChanged(when, updateMode);
 }
 
 void Document::modifiedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
 {
-    if (!isActive())
-        return;
-
-    styleEngine()->modifiedStyleSheet(sheet);
+    // If we're in document teardown, then we don't need this notification of our sheet's removal.
+    // styleResolverChanged() is needed even when the document is inactive so that
+    // imported docuements (which is inactive) notifies the change to the master document.
+    if (isActive())
+        styleEngine()->modifiedStyleSheet(sheet);
     styleResolverChanged(when, updateMode);
 }
 
+TextAutosizer* Document::textAutosizer()
+{
+    if (!m_textAutosizer && !RuntimeEnabledFeatures::fastTextAutosizingEnabled())
+        m_textAutosizer = TextAutosizer::create(this);
+    return m_textAutosizer.get();
+}
+
+FastTextAutosizer* Document::fastTextAutosizer()
+{
+    if (!m_fastTextAutosizer && RuntimeEnabledFeatures::fastTextAutosizingEnabled())
+        m_fastTextAutosizer = FastTextAutosizer::create(this);
+    return m_fastTextAutosizer.get();
+}
+
 } // namespace WebCore
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index 65ea92a..a9a6446 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -64,6 +64,7 @@
 class AnimationClock;
 class Attr;
 class CDATASection;
+class CSSFontSelector;
 class CSSStyleDeclaration;
 class CSSStyleSheet;
 class CSSStyleSheetResource;
@@ -96,6 +97,7 @@
 class EventListener;
 class ExceptionState;
 class MainThreadTaskRunner;
+class FastTextAutosizer;
 class FloatQuad;
 class FloatRect;
 class FormController;
@@ -289,11 +291,11 @@
     PassRefPtr<Comment> createComment(const String& data);
     PassRefPtr<CDATASection> createCDATASection(const String& data, ExceptionState&);
     PassRefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionState&);
-    PassRefPtr<Attr> createAttribute(const String& name, ExceptionState&);
-    PassRefPtr<Attr> createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionState&, bool shouldIgnoreNamespaceChecks = false);
+    PassRefPtr<Attr> createAttribute(const AtomicString& name, ExceptionState&);
+    PassRefPtr<Attr> createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&, bool shouldIgnoreNamespaceChecks = false);
     PassRefPtr<Node> importNode(Node* importedNode, ExceptionState& ec) { return importNode(importedNode, true, ec); }
     PassRefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionState&);
-    PassRefPtr<Element> createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionState&);
+    PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&);
     PassRefPtr<Element> createElement(const QualifiedName&, bool createdByParser);
 
     PassRefPtr<DOMNamedFlowCollection> webkitGetNamedFlows();
@@ -323,11 +325,11 @@
 
     String defaultCharset() const;
 
-    String inputEncoding() const { return Document::encodingName(); }
-    String charset() const { return Document::encodingName(); }
-    String characterSet() const { return Document::encodingName(); }
+    AtomicString inputEncoding() const { return Document::encodingName(); }
+    AtomicString charset() const { return Document::encodingName(); }
+    AtomicString characterSet() const { return Document::encodingName(); }
 
-    String encodingName() const;
+    AtomicString encodingName() const;
 
     void setCharset(const String&);
 
@@ -335,8 +337,8 @@
 
     String suggestedMIMEType() const;
 
-    String contentLanguage() const { return m_contentLanguage; }
-    void setContentLanguage(const String&);
+    const AtomicString& contentLanguage() const { return m_contentLanguage; }
+    void setContentLanguage(const AtomicString&);
 
     String xmlEncoding() const { return m_xmlEncoding; }
     String xmlVersion() const { return m_xmlVersion; }
@@ -389,8 +391,8 @@
     bool isSrcdocDocument() const { return m_isSrcdocDocument; }
     bool isMobileDocument() const { return m_isMobileDocument; }
 
-    StyleResolver* styleResolverIfExists() const;
     StyleResolver* styleResolver() const;
+    StyleResolver& ensureStyleResolver() const;
 
     bool isViewSource() const { return m_isViewSource; }
     void setIsViewSource(bool);
@@ -439,12 +441,10 @@
     PassRefPtr<NodeIterator> createNodeIterator(Node* root, ExceptionState&);
     PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, ExceptionState&);
     PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
-    PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionState&);
 
     PassRefPtr<TreeWalker> createTreeWalker(Node* root, ExceptionState&);
     PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, ExceptionState&);
     PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
-    PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionState&);
 
     // Special support for editing
     PassRefPtr<CSSStyleDeclaration> createCSSStyleDeclaration();
@@ -703,7 +703,7 @@
      * @param equiv The http header name (value of the meta tag's "equiv" attribute)
      * @param content The header value (value of the meta tag's "content" attribute)
      */
-    void processHttpEquiv(const String& equiv, const String& content);
+    void processHttpEquiv(const AtomicString& equiv, const AtomicString& content);
     void processViewport(const String& features, ViewportDescription::Type origin);
     void updateViewportDescription();
     void processReferrerPolicy(const String& policy);
@@ -725,7 +725,7 @@
     String cookie(ExceptionState&) const;
     void setCookie(const String&, ExceptionState&);
 
-    String referrer() const;
+    const AtomicString& referrer() const;
 
     String domain() const;
     void setDomain(const String& newDomain, ExceptionState&);
@@ -755,7 +755,7 @@
     // The following breaks a qualified name into a prefix and a local name.
     // It also does a validity check, and returns false if the qualified name
     // is invalid.  It also sets ExceptionCode when name is invalid.
-    static bool parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionState&);
+    static bool parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState&);
 
     // Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
     static bool hasValidNamespaceForElements(const QualifiedName&);
@@ -914,7 +914,7 @@
 
     const DocumentTiming* timing() const { return &m_documentTiming; }
 
-    int requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>);
+    int requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback>);
     void cancelAnimationFrame(int id);
     void serviceScriptedAnimations(double monotonicAnimationStartTime);
 
@@ -939,10 +939,13 @@
 
     IntSize initialViewportSize() const;
 
-    TextAutosizer* textAutosizer() { return m_textAutosizer.get(); }
+    // There are currently two parallel autosizing implementations: TextAutosizer and FastTextAutosizer.
+    // See http://tinyurl.com/chromium-fast-autosizer for more details.
+    TextAutosizer* textAutosizer();
+    FastTextAutosizer* fastTextAutosizer();
 
     PassRefPtr<Element> createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState&);
-    PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionState&);
+    PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState&);
     ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, ExceptionState&);
     ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionState&, CustomElement::NameSet validNames = CustomElement::StandardNames);
     CustomElementRegistrationContext* registrationContext() { return m_registrationContext.get(); }
@@ -1084,11 +1087,11 @@
     void didAssociateFormControlsTimerFired(Timer<Document>*);
     void styleResolverThrowawayTimerFired(Timer<Document>*);
 
-    void processHttpEquivDefaultStyle(const String& content);
-    void processHttpEquivRefresh(const String& content);
-    void processHttpEquivSetCookie(const String& content);
-    void processHttpEquivXFrameOptions(const String& content);
-    void processHttpEquivContentSecurityPolicy(const String& equiv, const String& content);
+    void processHttpEquivDefaultStyle(const AtomicString& content);
+    void processHttpEquivRefresh(const AtomicString& content);
+    void processHttpEquivSetCookie(const AtomicString& content);
+    void processHttpEquivXFrameOptions(const AtomicString& content);
+    void processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content);
 
     DocumentLifecycle m_lifecyle;
 
@@ -1211,7 +1214,7 @@
     unsigned m_xmlStandalone : 2;
     unsigned m_hasXMLDeclaration : 1;
 
-    String m_contentLanguage;
+    AtomicString m_contentLanguage;
 
     DocumentEncodingData m_encodingData;
 
@@ -1275,6 +1278,7 @@
     RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
     OwnPtr<MainThreadTaskRunner> m_taskRunner;
     OwnPtr<TextAutosizer> m_textAutosizer;
+    OwnPtr<FastTextAutosizer> m_fastTextAutosizer;
 
     RefPtr<CustomElementRegistrationContext> m_registrationContext;
 
@@ -1343,6 +1347,9 @@
 
 DEFINE_NODE_TYPE_CASTS(Document, isDocumentNode());
 
+#define DEFINE_DOCUMENT_TYPE_CASTS(thisType) \
+    DEFINE_TYPE_CASTS(thisType, Document, document, document->is##thisType(), document.is##thisType())
+
 // All these varations are needed to avoid ambiguous overloads with the Node and TreeScope versions.
 inline bool operator==(const Document& a, const Document& b) { return &a == &b; }
 inline bool operator==(const Document& a, const Document* b) { return &a == b; }
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index f5f0b83..772a3ad 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -29,27 +29,23 @@
     readonly attribute DOMImplementation implementation;
     readonly attribute Element documentElement;
 
-    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElement([TreatNullAs=NullString,Default=Undefined] optional DOMString tagName);
-    DocumentFragment   createDocumentFragment();
-    [PerWorldBindings] Text createTextNode([Default=Undefined] optional DOMString data);
-    Comment createComment([Default=Undefined] optional DOMString data);
+    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElement(DOMString tagName);
+    DocumentFragment createDocumentFragment();
+    [PerWorldBindings] Text createTextNode(DOMString data);
+    Comment createComment(DOMString data);
     [RaisesException, MeasureAs=DocumentCreateCDATASection] CDATASection createCDATASection([Default=Undefined] optional DOMString data); // Removed from DOM4.
-    [RaisesException] ProcessingInstruction createProcessingInstruction([Default=Undefined] optional DOMString target,
-                                                                                 [Default=Undefined] optional DOMString data);
+    [RaisesException] ProcessingInstruction createProcessingInstruction(DOMString target, DOMString data);
     [RaisesException, MeasureAs=DocumentCreateAttribute] Attr createAttribute([Default=Undefined] optional DOMString name); // Removed from DOM4.
-    [PerWorldBindings] NodeList           getElementsByTagName([Default=Undefined] optional DOMString tagname);
+    [PerWorldBindings] NodeList getElementsByTagName(DOMString localName);
 
     // Introduced in DOM Level 2:
 
-    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node importNode([Default=Undefined] optional Node importedNode,
-                    optional boolean deep);
-    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                            [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName);
+    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node importNode(Node node, optional boolean deep);
+    [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName);
     [RaisesException, MeasureAs=DocumentCreateAttributeNS] Attr createAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                                                                   [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName); // Removed from DOM4.
-     NodeList getElementsByTagNameNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                                                   [Default=Undefined] optional DOMString localName);
-    [PerWorldBindings] Element            getElementById([Default=Undefined] optional DOMString elementId);
+    NodeList getElementsByTagNameNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
+    [PerWorldBindings] Element getElementById(DOMString elementId);
 
     // DOM Level 3 Core
 
@@ -59,30 +55,26 @@
     [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter, MeasureAs=DocumentXMLVersion] attribute DOMString xmlVersion; // Removed from DOM4.
     [RaisesException=Setter, MeasureAs=DocumentXMLStandalone] attribute boolean xmlStandalone; // Removed from DOM4.
 
-    [RaisesException, CustomElementCallbacks] Node               adoptNode([Default=Undefined] optional Node source);
+    [RaisesException, CustomElementCallbacks] Node adoptNode(Node node);
 
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString documentURI;
 
     // DOM Level 2 Events (DocumentEvents interface)
 
-    [RaisesException] Event              createEvent([Default=Undefined] optional DOMString eventType);
+    [RaisesException] Event createEvent(DOMString eventType);
 
     // DOM Level 2 Traversal and Range (DocumentRange interface)
 
-    Range              createRange();
+    Range createRange();
 
     // DOM Level 2 Traversal and Range (DocumentTraversal interface)
-    // In DOM4, the fourth argument |expandEntityReferences| is removed.
-    // Historically, this argument was never implemented and has been ignored.
-    // We still receive the argument to keep compatibility, but don't do anything if it's specified.
+
     [RaisesException] NodeIterator createNodeIterator(Node root,
                                                       optional unsigned long whatToShow,
-                                                      optional NodeFilter filter,
-                                                      optional boolean expandEntityReferences);
+                                                      optional NodeFilter filter);
     [RaisesException] TreeWalker createTreeWalker(Node root,
                                                   optional unsigned long whatToShow,
-                                                  optional NodeFilter filter,
-                                                  optional boolean expandEntityReferences);
+                                                  optional NodeFilter filter);
 
     // DOM Level 2 Abstract Views (DocumentView interface)
 
@@ -154,7 +146,7 @@
     CanvasRenderingContext getCSSCanvasContext(DOMString contextId, DOMString name, long width, long height);
 
     // HTML 5
-    NodeList getElementsByClassName([Default=Undefined] optional DOMString tagname);
+    NodeList getElementsByClassName(DOMString classNames);
 
     readonly attribute DOMString compatMode;
 
diff --git a/Source/core/dom/DocumentEncodingData.h b/Source/core/dom/DocumentEncodingData.h
index d41c078..5a696af 100644
--- a/Source/core/dom/DocumentEncodingData.h
+++ b/Source/core/dom/DocumentEncodingData.h
@@ -31,6 +31,8 @@
 #ifndef DocumentEncodingData_h
 #define DocumentEncodingData_h
 
+#include "wtf/text/TextEncoding.h"
+
 namespace WebCore {
 
 struct DocumentEncodingData {
diff --git a/Source/core/dom/DocumentFragment.idl b/Source/core/dom/DocumentFragment.idl
index 942f021..4f1ecf9 100644
--- a/Source/core/dom/DocumentFragment.idl
+++ b/Source/core/dom/DocumentFragment.idl
@@ -19,7 +19,7 @@
 
 [
     Constructor,
-    ConstructorCallWith=Document
+    ConstructorCallWith=Document,
 ] interface DocumentFragment : Node {
     // NodeSelector - Selector API
     [RaisesException] Element querySelector(DOMString selectors);
@@ -27,4 +27,3 @@
 };
 
 DocumentFragment implements ParentNode;
-
diff --git a/Source/core/dom/DocumentMarkerController.cpp b/Source/core/dom/DocumentMarkerController.cpp
index be763b1..ef4fa82 100644
--- a/Source/core/dom/DocumentMarkerController.cpp
+++ b/Source/core/dom/DocumentMarkerController.cpp
@@ -140,15 +140,6 @@
     }
 }
 
-void DocumentMarkerController::nodeWillBeRemoved(const Node& node)
-{
-    if (!possiblyHasMarkers(DocumentMarker::AllMarkers()))
-        return;
-    m_markers.remove(&node);
-    if (m_markers.isEmpty())
-        m_possiblyExistingMarkerTypes = 0;
-}
-
 void DocumentMarkerController::prepareForDestruction()
 {
     clear();
diff --git a/Source/core/dom/DocumentMarkerController.h b/Source/core/dom/DocumentMarkerController.h
index bae5e11..a3b023f 100644
--- a/Source/core/dom/DocumentMarkerController.h
+++ b/Source/core/dom/DocumentMarkerController.h
@@ -34,6 +34,7 @@
 
 namespace WebCore {
 
+class ContainerNode;
 class LayoutPoint;
 class LayoutRect;
 class Node;
@@ -58,7 +59,6 @@
     void copyMarkers(Node* srcNode, unsigned startOffset, int length, Node* dstNode, int delta);
     bool hasMarkers(Range*, DocumentMarker::MarkerTypes = DocumentMarker::AllMarkers());
 
-    void nodeWillBeRemoved(const Node&);
     void prepareForDestruction();
     // When a marker partially overlaps with range, if removePartiallyOverlappingMarkers is true, we completely
     // remove the marker. If the argument is false, we will adjust the span of the marker so that it retains
diff --git a/Source/core/dom/DocumentMarkerControllerTest.cpp b/Source/core/dom/DocumentMarkerControllerTest.cpp
new file mode 100644
index 0000000..f7132ed
--- /dev/null
+++ b/Source/core/dom/DocumentMarkerControllerTest.cpp
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/DocumentMarkerController.h"
+
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/Document.h"
+#include "core/dom/Range.h"
+#include "core/dom/Text.h"
+#include "core/html/HTMLElement.h"
+#include "core/testing/DummyPageHolder.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/testing/WTFTestHelpers.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+class DocumentMarkerControllerTest : public ::testing::Test {
+protected:
+    virtual void SetUp() OVERRIDE;
+
+    Document& document() const { return *m_document; }
+    DocumentMarkerController& markerController() const { return *m_document->markers(); }
+
+    PassRefPtr<Text> createTextNode(const char*);
+    void markNodeContents(PassRefPtr<Node>);
+    void setBodyInnerHTML(const char*);
+
+private:
+    OwnPtr<DummyPageHolder> m_dummyPageHolder;
+    Document* m_document;
+};
+
+void DocumentMarkerControllerTest::SetUp()
+{
+    m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600));
+    m_document = &m_dummyPageHolder->document();
+    ASSERT(m_document);
+}
+
+PassRefPtr<Text> DocumentMarkerControllerTest::createTextNode(const char* textContents)
+{
+    return document().createTextNode(String::fromUTF8(textContents));
+}
+
+void DocumentMarkerControllerTest::markNodeContents(PassRefPtr<Node> node)
+{
+    // Force renderers to be created; TextIterator, which is used in
+    // DocumentMarkerControllerTest::addMarker(), needs them.
+    document().updateLayout();
+    RefPtr<Range> range = rangeOfContents(node.get());
+    markerController().addMarker(range.get(), DocumentMarker::Spelling);
+}
+
+void DocumentMarkerControllerTest::setBodyInnerHTML(const char* bodyContent)
+{
+    document().body()->setInnerHTML(String::fromUTF8(bodyContent), ASSERT_NO_EXCEPTION);
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByNormalize)
+{
+    setBodyInnerHTML("<b><i>foo</i></b>");
+    {
+        RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+        parent->appendChild(createTextNode("bar").get());
+        markNodeContents(parent.get());
+        EXPECT_EQ(2u, markerController().markers().size());
+        parent->normalize();
+    }
+    // No more reference to marked node.
+    EXPECT_EQ(1u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveChildren)
+{
+    setBodyInnerHTML("<b><i>foo</i></b>");
+    RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+    markNodeContents(parent.get());
+    EXPECT_EQ(1u, markerController().markers().size());
+    parent->removeChildren();
+    // No more reference to marked node.
+    EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedByRemoveMarked)
+{
+    setBodyInnerHTML("<b><i>foo</i></b>");
+    {
+        RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+        markNodeContents(parent);
+        EXPECT_EQ(1u, markerController().markers().size());
+        parent->removeChild(parent->firstChild());
+    }
+    // No more reference to marked node.
+    EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveAncestor)
+{
+    setBodyInnerHTML("<b><i>foo</i></b>");
+    {
+        RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+        markNodeContents(parent);
+        EXPECT_EQ(1u, markerController().markers().size());
+        parent->parentNode()->parentNode()->removeChild(parent->parentNode());
+    }
+    // No more reference to marked node.
+    EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveParent)
+{
+    setBodyInnerHTML("<b><i>foo</i></b>");
+    {
+        RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+        markNodeContents(parent);
+        EXPECT_EQ(1u, markerController().markers().size());
+        parent->parentNode()->removeChild(parent.get());
+    }
+    // No more reference to marked node.
+    EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByReplaceChild)
+{
+    setBodyInnerHTML("<b><i>foo</i></b>");
+    {
+        RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+        markNodeContents(parent.get());
+        EXPECT_EQ(1u, markerController().markers().size());
+        parent->replaceChild(createTextNode("bar").get(), parent->firstChild());
+    }
+    // No more reference to marked node.
+    EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedBySetInnerHTML)
+{
+    setBodyInnerHTML("<b><i>foo</i></b>");
+    {
+        RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+        markNodeContents(parent);
+        EXPECT_EQ(1u, markerController().markers().size());
+        setBodyInnerHTML("");
+    }
+    // No more reference to marked node.
+    EXPECT_EQ(0u, markerController().markers().size());
+}
+
+}
diff --git a/Source/core/dom/DocumentStyleSheetCollection.cpp b/Source/core/dom/DocumentStyleSheetCollection.cpp
index 87a308c..5d4736f 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -52,7 +52,7 @@
     ASSERT(treeScope.rootNode() == treeScope.rootNode()->document());
 }
 
-void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* engine, StyleSheetCollectionBase& collection)
+void DocumentStyleSheetCollection::collectStyleSheetsFromCandidates(StyleEngine* engine, StyleSheetCollectionBase& collection, DocumentStyleSheetCollection::CollectFor collectFor)
 {
     DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin();
     DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end();
@@ -130,7 +130,7 @@
                 activeSheet = 0;
         }
 
-        if (sheet)
+        if (sheet && collectFor == CollectForList)
             collection.appendSheetForList(sheet);
         if (activeSheet)
             collection.appendActiveStyleSheet(activeSheet);
@@ -145,20 +145,27 @@
     collection.appendActiveStyleSheets(seamlessParentIFrame->document().styleEngine()->activeAuthorStyleSheets());
 }
 
-bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleEngine* engine, StyleResolverUpdateMode updateMode)
+void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* engine, StyleSheetCollectionBase& collection, DocumentStyleSheetCollection::CollectFor colletFor)
 {
-    StyleSheetCollectionBase collection;
+    ASSERT(document()->styleEngine() == engine);
     collection.appendActiveStyleSheets(engine->injectedAuthorStyleSheets());
     collection.appendActiveStyleSheets(engine->documentAuthorStyleSheets());
     collectActiveCSSStyleSheetsFromSeamlessParents(collection, document());
-    collectStyleSheets(engine, collection);
+    collectStyleSheetsFromCandidates(engine, collection, colletFor);
+}
+
+bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleEngine* engine, StyleResolverUpdateMode updateMode)
+{
+    StyleSheetCollectionBase collection;
+    engine->collectDocumentActiveStyleSheets(collection);
 
     StyleSheetChange change;
     analyzeStyleSheetChange(updateMode, collection, change);
 
     if (change.styleResolverUpdateType == Reconstruct) {
-        engine->clearResolver();
-    } else if (StyleResolver* styleResolver = engine->resolverIfExists()) {
+        engine->clearMasterResolver();
+        engine->resetFontSelector();
+    } else if (StyleResolver* styleResolver = engine->resolver()) {
         // FIXME: We might have already had styles in child treescope. In this case, we cannot use buildScopedStyleTreeInDocumentOrder.
         // Need to change "false" to some valid condition.
         styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
@@ -166,12 +173,14 @@
             ASSERT(change.styleResolverUpdateType == Reset || change.styleResolverUpdateType == ResetStyleResolverAndFontSelector);
             resetAllRuleSetsInTreeScope(styleResolver);
             if (change.styleResolverUpdateType == ResetStyleResolverAndFontSelector)
-                styleResolver->resetFontSelector();
+                engine->resetFontSelector();
             styleResolver->removePendingAuthorStyleSheets(m_activeAuthorStyleSheets);
             styleResolver->lazyAppendAuthorStyleSheets(0, collection.activeAuthorStyleSheets());
         } else {
             styleResolver->lazyAppendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), collection.activeAuthorStyleSheets());
         }
+    } else if (change.styleResolverUpdateType == ResetStyleResolverAndFontSelector) {
+        engine->resetFontSelector();
     }
     m_scopingNodesForStyleScoped.didRemoveScopingNodes();
     collection.swap(*this);
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index cefe7da..9920ad8 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -43,10 +43,16 @@
 public:
     explicit DocumentStyleSheetCollection(TreeScope&);
 
+    enum CollectFor {
+        CollectForList,
+        DontCollectForList
+    };
+
     bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
+    void collectStyleSheets(StyleEngine*, StyleSheetCollectionBase&, CollectFor);
 
 private:
-    void collectStyleSheets(StyleEngine*, StyleSheetCollectionBase&);
+    void collectStyleSheetsFromCandidates(StyleEngine*, StyleSheetCollectionBase&, CollectFor);
 };
 
 }
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index 893d1dc..369bf39 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -26,9 +26,7 @@
 #include "config.h"
 #include "core/dom/Element.h"
 
-#include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
-#include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "XMLNames.h"
@@ -43,12 +41,10 @@
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Attr.h"
-#include "core/dom/Attribute.h"
 #include "core/dom/CSSSelectorWatch.h"
 #include "core/dom/ClientRect.h"
 #include "core/dom/ClientRectList.h"
 #include "core/dom/DatasetDOMStringMap.h"
-#include "core/dom/Document.h"
 #include "core/dom/DocumentSharedObjectPool.h"
 #include "core/dom/ElementRareData.h"
 #include "core/dom/ExceptionCode.h"
@@ -119,7 +115,7 @@
     {
         if (m_pushedStyleResolver)
             return;
-        m_pushedStyleResolver = m_parent.document().styleResolver();
+        m_pushedStyleResolver = &m_parent.document().ensureStyleResolver();
         m_pushedStyleResolver->pushParentElement(m_parent);
     }
     ~StyleResolverParentPusher()
@@ -394,7 +390,7 @@
 
 bool Element::hasActiveAnimations() const
 {
-    if (!RuntimeEnabledFeatures::webAnimationsEnabled())
+    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
         return false;
 
     if (!hasRareData())
@@ -443,7 +439,7 @@
     }
 }
 
-inline void Element::synchronizeAttribute(const AtomicString& localName) const
+void Element::synchronizeAttribute(const AtomicString& localName) const
 {
     // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
     // e.g when called from DOM API.
@@ -515,8 +511,7 @@
         direction = ScrollUp;
         units = -units;
     }
-    Node* stopNode = this;
-    toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode);
+    toRenderBox(renderer())->scroll(direction, granularity, units);
 }
 
 void Element::scrollByLines(int lines)
@@ -976,7 +971,7 @@
 
     document().incDOMTreeVersion();
 
-    StyleResolver* styleResolver = document().styleResolverIfExists();
+    StyleResolver* styleResolver = document().styleResolver();
     bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
     bool shouldInvalidateStyle = false;
 
@@ -1098,7 +1093,7 @@
 
 void Element::classAttributeChanged(const AtomicString& newClassString)
 {
-    StyleResolver* styleResolver = document().styleResolverIfExists();
+    StyleResolver* styleResolver = document().styleResolver();
     bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
     bool shouldInvalidateStyle = false;
 
@@ -1495,17 +1490,32 @@
 
 PassRefPtr<RenderStyle> Element::styleForRenderer()
 {
-    if (hasCustomStyleCallbacks()) {
-        if (RefPtr<RenderStyle> style = customStyleForRenderer())
-            return style.release();
-    }
+    ASSERT(document().inStyleRecalc());
 
-    return originalStyleForRenderer();
+    RefPtr<RenderStyle> style;
+
+    // FIXME: Instead of clearing updates that may have been added from calls to styleForElement
+    // outside recalcStyle, we should just never set them if we're not inside recalcStyle.
+    if (ActiveAnimations* activeAnimations = this->activeAnimations())
+        activeAnimations->cssAnimations().setPendingUpdate(nullptr);
+
+    if (hasCustomStyleCallbacks())
+        style = customStyleForRenderer();
+    if (!style)
+        style = originalStyleForRenderer();
+
+    // styleForElement() might add active animations so we need to get it again.
+    if (ActiveAnimations* activeAnimations = this->activeAnimations())
+        activeAnimations->cssAnimations().maybeApplyPendingUpdate(this);
+
+    ASSERT(style);
+    return style.release();
 }
 
 PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
 {
-    return document().styleResolver()->styleForElement(this);
+    ASSERT(document().inStyleRecalc());
+    return document().ensureStyleResolver().styleForElement(this);
 }
 
 void Element::recalcStyle(StyleRecalcChange change, Text* nextTextSibling)
@@ -1521,6 +1531,11 @@
             ElementRareData* data = elementRareData();
             data->resetStyleState();
             data->clearComputedStyle();
+
+            if (change >= Inherit) {
+                if (ActiveAnimations* activeAnimations = data->activeAnimations())
+                    activeAnimations->setAnimationStyleChange(false);
+            }
         }
         if (parentRenderStyle())
             change = recalcOwnStyle(change);
@@ -1547,11 +1562,7 @@
     ASSERT(parentRenderStyle());
 
     RefPtr<RenderStyle> oldStyle = renderStyle();
-    RefPtr<RenderStyle> newStyle;
-    {
-        CSSAnimationUpdateScope cssAnimationUpdateScope(this);
-        newStyle = styleForRenderer();
-    }
+    RefPtr<RenderStyle> newStyle = styleForRenderer();
     StyleRecalcChange localChange = RenderStyle::compare(oldStyle.get(), newStyle.get());
 
     ASSERT(newStyle);
@@ -1586,7 +1597,7 @@
     // all the way down the tree. This is simpler than having to maintain a cache of objects (and such font size changes should be rare anyway).
     if (document().styleEngine()->usesRemUnits() && document().documentElement() == this && oldStyle->fontSize() != newStyle->fontSize()) {
         // Cached RenderStyles may depend on the re units.
-        document().styleResolver()->invalidateMatchedPropertiesCache();
+        document().ensureStyleResolver().invalidateMatchedPropertiesCache();
         return Force;
     }
 
@@ -1621,7 +1632,7 @@
     // a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
     // child and work our way back means in the common case, we'll find the insertion point in O(1) time.
     // See crbug.com/288225
-    StyleResolver& styleResolver = *document().styleResolver();
+    StyleResolver& styleResolver = document().ensureStyleResolver();
     Text* lastTextNode = 0;
     for (Node* child = lastChild(); child; child = child->previousSibling()) {
         if (child->isTextNode()) {
@@ -1714,6 +1725,21 @@
         elementShadow->didAffectSelector(mask);
 }
 
+void Element::setAnimationStyleChange(bool animationStyleChange)
+{
+    if (ActiveAnimations* activeAnimations = elementRareData()->activeAnimations())
+        activeAnimations->setAnimationStyleChange(animationStyleChange);
+}
+
+void Element::setNeedsAnimationStyleRecalc()
+{
+    if (styleChangeType() != NoStyleChange)
+        return;
+
+    setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+    setAnimationStyleChange(true);
+}
+
 PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& exceptionState)
 {
     if (alwaysCreateUserAgentShadowRoot())
@@ -2001,7 +2027,7 @@
 
 bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
 {
-    String prefix, localName;
+    AtomicString prefix, localName;
     if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
         return false;
     ASSERT(!exceptionState.hadException());
@@ -2277,6 +2303,69 @@
         mergeWithNextTextNode(prev.release(), exceptionState);
 }
 
+Node* Element::insertAdjacent(const String& where, Node* newChild, ExceptionState& exceptionState)
+{
+    if (equalIgnoringCase(where, "beforeBegin")) {
+        if (ContainerNode* parent = this->parentNode()) {
+            parent->insertBefore(newChild, this, exceptionState);
+            if (!exceptionState.hadException())
+                return newChild;
+        }
+        return 0;
+    }
+
+    if (equalIgnoringCase(where, "afterBegin")) {
+        insertBefore(newChild, firstChild(), exceptionState);
+        return exceptionState.hadException() ? 0 : newChild;
+    }
+
+    if (equalIgnoringCase(where, "beforeEnd")) {
+        appendChild(newChild, exceptionState);
+        return exceptionState.hadException() ? 0 : newChild;
+    }
+
+    if (equalIgnoringCase(where, "afterEnd")) {
+        if (ContainerNode* parent = this->parentNode()) {
+            parent->insertBefore(newChild, nextSibling(), exceptionState);
+            if (!exceptionState.hadException())
+                return newChild;
+        }
+        return 0;
+    }
+
+    exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
+    return 0;
+}
+
+// Step 1 of http://domparsing.spec.whatwg.org/#insertadjacenthtml()
+static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& exceptionState)
+{
+    if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
+        ContainerNode* parent = element->parentNode();
+        if (!parent || !parent->isElementNode()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
+            return 0;
+        }
+        return toElement(parent);
+    }
+    if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
+        return element;
+    exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
+    return 0;
+}
+
+void Element::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& exceptionState)
+{
+    RefPtr<Element> contextElement = contextElementForInsertion(where, this, exceptionState);
+    if (!contextElement)
+        return;
+
+    RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement.get(), AllowScriptingContent, "insertAdjacentHTML", exceptionState);
+    if (!fragment)
+        return;
+    insertAdjacent(where, fragment.get(), exceptionState);
+}
+
 String Element::innerText()
 {
     // We need to update layout, since plainText uses line boxes in the render tree.
@@ -3017,7 +3106,7 @@
 
 static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
 {
-    return document->styleResolver() && document->styleResolver()->ensureRuleFeatureSet().hasSelectorForAttribute(localName);
+    return document->ensureStyleResolver().ensureRuleFeatureSet().hasSelectorForAttribute(localName);
 }
 
 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
@@ -3501,7 +3590,7 @@
     if (isSVGElement() && toSVGElement(this)->animatedSMILStyleProperties())
         return false;
     // Ids stop style sharing if they show up in the stylesheets.
-    if (hasID() && document().styleResolver()->hasRulesForId(idForStyleResolution()))
+    if (hasID() && document().ensureStyleResolver().hasRulesForId(idForStyleResolution()))
         return false;
     // Active and hovered elements always make a chain towards the document node
     // and no siblings or cousins will have the same state.
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index dd870be..eca5712 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -82,11 +82,6 @@
     static PassRefPtr<Element> create(const QualifiedName&, Document*);
     virtual ~Element();
 
-    String innerHTML() const;
-    String outerHTML() const;
-    void setInnerHTML(const String&, ExceptionState&);
-    void setOuterHTML(const String&, ExceptionState&);
-
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
@@ -306,6 +301,8 @@
     virtual bool rendererIsNeeded(const RenderStyle&);
     void recalcStyle(StyleRecalcChange, Text* nextTextSibling = 0);
     void didAffectSelector(AffectedSelectorMask);
+    void setAnimationStyleChange(bool);
+    void setNeedsAnimationStyleRecalc();
 
     bool supportsStyleSharing() const;
 
@@ -398,6 +395,11 @@
 
     String innerText();
     String outerText();
+    String innerHTML() const;
+    String outerHTML() const;
+    void setInnerHTML(const String&, ExceptionState&);
+    void setOuterHTML(const String&, ExceptionState&);
+    void insertAdjacentHTML(const String& where, const String& html, ExceptionState&);
 
     String textFromChildren();
 
@@ -494,8 +496,8 @@
 
     bool isSpellCheckingEnabled() const;
 
+    // FIXME: public for NodeRenderingContext, we shouldn't expose this though.
     PassRefPtr<RenderStyle> styleForRenderer();
-    PassRefPtr<RenderStyle> originalStyleForRenderer();
 
     RenderRegion* renderRegion() const;
     virtual bool shouldMoveToFlowThread(RenderStyle*) const;
@@ -518,6 +520,8 @@
 
     virtual void setPrefix(const AtomicString&, ExceptionState&) OVERRIDE FINAL;
 
+    void synchronizeAttribute(const AtomicString& localName) const;
+
 protected:
     Element(const QualifiedName& tagName, Document* document, ConstructionType type)
         : ContainerNode(document, type)
@@ -561,6 +565,10 @@
     // svgAttributeChanged (called when element.className.baseValue is set)
     void classAttributeChanged(const AtomicString& newClassString);
 
+    PassRefPtr<RenderStyle> originalStyleForRenderer();
+
+    Node* insertAdjacent(const String& where, Node* newChild, ExceptionState&);
+
 private:
     void styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason);
 
@@ -602,7 +610,6 @@
     void didRemoveAttribute(const QualifiedName&);
 
     void synchronizeAttribute(const QualifiedName&) const;
-    void synchronizeAttribute(const AtomicString& localName) const;
 
     void updateId(const AtomicString& oldId, const AtomicString& newId);
     void updateId(TreeScope&, const AtomicString& oldId, const AtomicString& newId);
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index d85e326..b839383 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -49,7 +49,7 @@
                                     [Default=Undefined] optional DOMString localName);
     [MeasureAs=ElementGetAttributeNodeNS] Attr getAttributeNodeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                                                   [Default=Undefined] optional DOMString localName); // Removed from DOM4.
-    [RaisesException, CustomElementCallbacks] Attr setAttributeNodeNS([Default=Undefined, StrictTypeChecking] optional Attr newAttr);
+    [RaisesException, CustomElementCallbacks, MeasureAs=ElementSetAttributeNodeNS] Attr setAttributeNodeNS([Default=Undefined, StrictTypeChecking] optional Attr newAttr); // Removed from DOM4.
     boolean hasAttribute(DOMString name);
     boolean hasAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                            [Default=Undefined] optional DOMString localName);
@@ -57,9 +57,7 @@
     [PerWorldBindings] readonly attribute CSSStyleDeclaration style;
 
     // DOM4
-    // iht.com relies on id returning the empty string when no id is present.
-    // Other browsers do this as well. So we don't convert null to JS null.
-    [Reflect, TreatNullAs=NullString] attribute DOMString id;
+    [Reflect] attribute DOMString id;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString namespaceURI;
     [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter] attribute DOMString prefix;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString localName;
@@ -94,8 +92,9 @@
     NodeList getElementsByClassName([Default=Undefined] optional DOMString name);
     [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, RaisesException=Setter] attribute DOMString innerHTML;
     [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter] attribute DOMString outerHTML;
+    [CustomElementCallbacks, RaisesException] void insertAdjacentHTML(DOMString where, DOMString html);
 
-    [Reflect=class, TreatNullAs=NullString, PerWorldBindings] attribute DOMString className;
+    [Reflect=class, PerWorldBindings] attribute DOMString className;
     [PerWorldBindings] readonly attribute DOMTokenList classList;
 
     [PerWorldBindings] readonly attribute DOMStringMap dataset;
@@ -104,8 +103,8 @@
     [RaisesException] Element querySelector(DOMString selectors);
     [RaisesException] NodeList querySelectorAll(DOMString selectors);
 
-    // WebKit extension, pending specification.
-    [RaisesException] boolean webkitMatchesSelector([Default=Undefined] optional DOMString selectors);
+    // WebKit extension
+    [RaisesException, MeasureAs=ElementPrefixedMatchesSelector] boolean webkitMatchesSelector([Default=Undefined] optional DOMString selectors);
 
     // Shadow DOM API
     [RuntimeEnabled=ShadowDOM, Reflect, TreatNullAs=NullString, PerWorldBindings] attribute DOMString pseudo;
diff --git a/Source/core/dom/ElementData.cpp b/Source/core/dom/ElementData.cpp
index 73d0c39..2ce4aa0 100644
--- a/Source/core/dom/ElementData.cpp
+++ b/Source/core/dom/ElementData.cpp
@@ -35,7 +35,6 @@
 #include "core/dom/Attr.h"
 #include "core/dom/QualifiedName.h"
 #include "wtf/Vector.h"
-#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
@@ -130,6 +129,8 @@
     // Continue to checking case-insensitively and/or full namespaced names if necessary:
     for (unsigned i = 0; i < length(); ++i) {
         const Attribute* attribute = attributeItem(i);
+        // FIXME: Why check the prefix? Namespace is all that should matter
+        // and all HTML/SVG attributes have a null namespace!
         if (!attribute->name().hasPrefix()) {
             if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
                 return i;
diff --git a/Source/core/dom/ElementData.h b/Source/core/dom/ElementData.h
index b7c36f0..2426667 100644
--- a/Source/core/dom/ElementData.h
+++ b/Source/core/dom/ElementData.h
@@ -185,7 +185,9 @@
 inline size_t ElementData::getAttributeItemIndex(const QualifiedName& name, bool shouldIgnoreCase) const
 {
     const Attribute* begin = attributeBase();
-    for (unsigned i = 0; i < length(); ++i) {
+    // Cache length for performance as ElementData::length() contains a conditional branch.
+    unsigned len = length();
+    for (unsigned i = 0; i < len; ++i) {
         const Attribute& attribute = begin[i];
         if (attribute.name().matchesPossiblyIgnoringCase(name, shouldIgnoreCase))
             return i;
@@ -197,6 +199,7 @@
 // can tune the behavior (hasAttribute is case sensitive whereas getAttribute is not).
 inline size_t ElementData::getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const
 {
+    // Cache length for performance as ElementData::length() contains a conditional branch.
     unsigned len = length();
     bool doSlowCheck = shouldIgnoreAttributeCase;
 
@@ -204,6 +207,8 @@
     const Attribute* begin = attributeBase();
     for (unsigned i = 0; i < len; ++i) {
         const Attribute& attribute = begin[i];
+        // FIXME: Why check the prefix? Namespaces should be all that matter.
+        // Most attributes (all of HTML and CSS) have no namespace.
         if (!attribute.name().hasPrefix()) {
             if (name == attribute.localName())
                 return i;
diff --git a/Source/core/dom/ExecutionContext.cpp b/Source/core/dom/ExecutionContext.cpp
index 8481a1e..1f62b74 100644
--- a/Source/core/dom/ExecutionContext.cpp
+++ b/Source/core/dom/ExecutionContext.cpp
@@ -31,9 +31,7 @@
 #include "core/dom/AddConsoleMessageTask.h"
 #include "core/dom/ContextLifecycleNotifier.h"
 #include "core/dom/ExecutionContextTask.h"
-#include "core/events/ErrorEvent.h"
 #include "core/events/EventTarget.h"
-#include "core/frame/DOMTimer.h"
 #include "core/html/PublicURLManager.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/inspector/ScriptCallStack.h"
diff --git a/Source/core/dom/FullscreenElementStack.cpp b/Source/core/dom/FullscreenElementStack.cpp
index 1cb4b79..ea6d058 100644
--- a/Source/core/dom/FullscreenElementStack.cpp
+++ b/Source/core/dom/FullscreenElementStack.cpp
@@ -30,7 +30,6 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/dom/Element.h"
 #include "core/events/Event.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/page/Chrome.h"
diff --git a/Source/core/dom/LiveNodeList.cpp b/Source/core/dom/LiveNodeList.cpp
index fea8b8a..5343cb9 100644
--- a/Source/core/dom/LiveNodeList.cpp
+++ b/Source/core/dom/LiveNodeList.cpp
@@ -23,7 +23,6 @@
 #include "config.h"
 #include "core/dom/LiveNodeList.h"
 
-#include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/html/HTMLCollection.h"
 
diff --git a/Source/core/dom/MessagePort.cpp b/Source/core/dom/MessagePort.cpp
index f827ccf..85254e4 100644
--- a/Source/core/dom/MessagePort.cpp
+++ b/Source/core/dom/MessagePort.cpp
@@ -27,7 +27,6 @@
 #include "config.h"
 #include "core/dom/MessagePort.h"
 
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "bindings/v8/SerializedScriptValue.h"
@@ -38,7 +37,6 @@
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/frame/DOMWindow.h"
 #include "core/workers/WorkerGlobalScope.h"
-#include "public/platform/WebMessagePortChannel.h"
 #include "public/platform/WebString.h"
 #include "wtf/Functional.h"
 #include "wtf/text/AtomicString.h"
@@ -79,7 +77,7 @@
         for (unsigned int i = 0; i < ports->size(); ++i) {
             MessagePort* dataPort = (*ports)[i].get();
             if (dataPort == this) {
-                exceptionState.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("postMessage", "MessagePort", "Item #" + String::number(i) + " in the array of ports contains the source port."));
+                exceptionState.throwDOMException(DataCloneError, "Item #" + String::number(i) + " in the array of ports contains the source port.");
                 return;
             }
         }
@@ -214,7 +212,7 @@
                 type = "already neutered";
             else
                 type = "a duplicate";
-            exceptionState.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("disentanglePorts", "MessagePort", "Item #"  + String::number(i) + " in the array of ports is " + type + "."));
+            exceptionState.throwDOMException(DataCloneError, "Item #"  + String::number(i) + " in the array of ports is " + type + ".");
             return nullptr;
         }
         portSet.add(port);
diff --git a/Source/core/dom/MutationCallback.h b/Source/core/dom/MutationCallback.h
index 5e15169..88f230b 100644
--- a/Source/core/dom/MutationCallback.h
+++ b/Source/core/dom/MutationCallback.h
@@ -31,7 +31,6 @@
 #ifndef MutationCallback_h
 #define MutationCallback_h
 
-#include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
 
@@ -40,7 +39,7 @@
 class MutationRecord;
 class MutationObserver;
 
-class MutationCallback : public RefCounted<MutationCallback> {
+class MutationCallback {
 public:
     virtual ~MutationCallback() { }
 
diff --git a/Source/core/dom/MutationObserver.cpp b/Source/core/dom/MutationObserver.cpp
index ebe5639..06e610a 100644
--- a/Source/core/dom/MutationObserver.cpp
+++ b/Source/core/dom/MutationObserver.cpp
@@ -33,7 +33,6 @@
 
 #include <algorithm>
 #include "bindings/v8/Dictionary.h"
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
@@ -41,9 +40,7 @@
 #include "core/dom/MutationObserverRegistration.h"
 #include "core/dom/MutationRecord.h"
 #include "core/dom/Node.h"
-#include "wtf/HashSet.h"
 #include "wtf/MainThread.h"
-#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -56,13 +53,13 @@
     }
 };
 
-PassRefPtr<MutationObserver> MutationObserver::create(PassRefPtr<MutationCallback> callback)
+PassRefPtr<MutationObserver> MutationObserver::create(PassOwnPtr<MutationCallback> callback)
 {
     ASSERT(isMainThread());
     return adoptRef(new MutationObserver(callback));
 }
 
-MutationObserver::MutationObserver(PassRefPtr<MutationCallback> callback)
+MutationObserver::MutationObserver(PassOwnPtr<MutationCallback> callback)
     : m_callback(callback)
     , m_priority(s_observerPriority++)
 {
@@ -77,7 +74,7 @@
 void MutationObserver::observe(Node* node, const Dictionary& optionsDictionary, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The provided node was null."));
+        exceptionState.throwDOMException(NotFoundError, "The provided node was null.");
         return;
     }
 
@@ -118,21 +115,21 @@
 
     if (!(options & Attributes)) {
         if (options & AttributeOldValue) {
-            exceptionState.throwDOMException(TypeError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object may only set 'attributeOldValue' to true when 'attributes' is true or not present."));
+            exceptionState.throwDOMException(TypeError, "The options object may only set 'attributeOldValue' to true when 'attributes' is true or not present.");
             return;
         }
         if (options & AttributeFilter) {
-            exceptionState.throwDOMException(TypeError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object may only set 'attributeFilter' when 'attributes' is true or not present."));
+            exceptionState.throwDOMException(TypeError, "The options object may only set 'attributeFilter' when 'attributes' is true or not present.");
             return;
         }
     }
     if (!((options & CharacterData) || !(options & CharacterDataOldValue))) {
-        exceptionState.throwDOMException(TypeError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object may only set 'characterDataOldValue' to true when 'characterData' is true or not present."));
+        exceptionState.throwDOMException(TypeError, "The options object may only set 'characterDataOldValue' to true when 'characterData' is true or not present.");
         return;
     }
 
     if (!(options & (Attributes | CharacterData | ChildList))) {
-        exceptionState.throwDOMException(TypeError, ExceptionMessages::failedToExecute("observe", "MutationObserver", "The options object must set at least one of 'attributes', 'characterData', or 'childList' to true."));
+        exceptionState.throwDOMException(TypeError, "The options object must set at least one of 'attributes', 'characterData', or 'childList' to true.");
         return;
     }
 
diff --git a/Source/core/dom/MutationObserver.h b/Source/core/dom/MutationObserver.h
index ff3c442..062d01e 100644
--- a/Source/core/dom/MutationObserver.h
+++ b/Source/core/dom/MutationObserver.h
@@ -70,7 +70,7 @@
         CharacterDataOldValue = 1 << 6,
     };
 
-    static PassRefPtr<MutationObserver> create(PassRefPtr<MutationCallback>);
+    static PassRefPtr<MutationObserver> create(PassOwnPtr<MutationCallback>);
     static void deliverAllMutations();
 
     ~MutationObserver();
@@ -89,10 +89,10 @@
 private:
     struct ObserverLessThan;
 
-    explicit MutationObserver(PassRefPtr<MutationCallback>);
+    explicit MutationObserver(PassOwnPtr<MutationCallback>);
     void deliver();
 
-    RefPtr<MutationCallback> m_callback;
+    OwnPtr<MutationCallback> m_callback;
     Vector<RefPtr<MutationRecord> > m_records;
     HashSet<MutationObserverRegistration*> m_registrations;
     unsigned m_priority;
diff --git a/Source/core/dom/MutationObserverInterestGroup.cpp b/Source/core/dom/MutationObserverInterestGroup.cpp
index 48cd761..e9e839b 100644
--- a/Source/core/dom/MutationObserverInterestGroup.cpp
+++ b/Source/core/dom/MutationObserverInterestGroup.cpp
@@ -33,8 +33,6 @@
 #include "core/dom/MutationObserverInterestGroup.h"
 
 #include "core/dom/MutationRecord.h"
-#include "core/dom/Node.h"
-#include "core/dom/QualifiedName.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/MutationRecord.cpp b/Source/core/dom/MutationRecord.cpp
index 5d86f3e..77c6f39 100644
--- a/Source/core/dom/MutationRecord.cpp
+++ b/Source/core/dom/MutationRecord.cpp
@@ -168,22 +168,22 @@
 
 PassRefPtr<MutationRecord> MutationRecord::createChildList(PassRefPtr<Node> target, PassRefPtr<NodeList> added, PassRefPtr<NodeList> removed, PassRefPtr<Node> previousSibling, PassRefPtr<Node> nextSibling)
 {
-    return adoptRef(static_cast<MutationRecord*>(new ChildListRecord(target, added, removed, previousSibling, nextSibling)));
+    return adoptRef(new ChildListRecord(target, added, removed, previousSibling, nextSibling));
 }
 
 PassRefPtr<MutationRecord> MutationRecord::createAttributes(PassRefPtr<Node> target, const QualifiedName& name, const AtomicString& oldValue)
 {
-    return adoptRef(static_cast<MutationRecord*>(new AttributesRecord(target, name, oldValue)));
+    return adoptRef(new AttributesRecord(target, name, oldValue));
 }
 
 PassRefPtr<MutationRecord> MutationRecord::createCharacterData(PassRefPtr<Node> target, const String& oldValue)
 {
-    return adoptRef(static_cast<MutationRecord*>(new CharacterDataRecord(target, oldValue)));
+    return adoptRef(new CharacterDataRecord(target, oldValue));
 }
 
 PassRefPtr<MutationRecord> MutationRecord::createWithNullOldValue(PassRefPtr<MutationRecord> record)
 {
-    return adoptRef(static_cast<MutationRecord*>(new MutationRecordWithNullOldValue(record)));
+    return adoptRef(new MutationRecordWithNullOldValue(record));
 }
 
 MutationRecord::~MutationRecord()
diff --git a/Source/core/dom/NamedFlowCollection.cpp b/Source/core/dom/NamedFlowCollection.cpp
index 538a88c..2b48c7b 100644
--- a/Source/core/dom/NamedFlowCollection.cpp
+++ b/Source/core/dom/NamedFlowCollection.cpp
@@ -33,7 +33,6 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/DOMNamedFlowCollection.h"
 #include "core/dom/Document.h"
-#include "core/dom/NamedFlow.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "wtf/text/StringHash.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 2cd8dde..c9fae12 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -27,9 +27,7 @@
 
 #include "HTMLNames.h"
 #include "XMLNames.h"
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/Attr.h"
 #include "core/dom/Attribute.h"
@@ -39,6 +37,7 @@
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
+#include "core/dom/DocumentMarkerController.h"
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
 #include "core/dom/ElementRareData.h"
@@ -79,7 +78,6 @@
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLStyleElement.h"
 #include "core/html/RadioNodeList.h"
-#include "core/inspector/InspectorCounters.h"
 #include "core/page/ContextMenuController.h"
 #include "core/page/EventHandler.h"
 #include "core/frame/Frame.h"
@@ -92,7 +90,6 @@
 #include "wtf/HashSet.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefCountedLeakCounter.h"
-#include "wtf/UnusedParam.h"
 #include "wtf/Vector.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
@@ -319,6 +316,8 @@
 
     if (AXObjectCache* cache = document->existingAXObjectCache())
         cache->remove(this);
+
+    document->markers()->removeMarkers(this);
 }
 
 NodeRareData* Node::rareData() const
@@ -453,7 +452,7 @@
     if (isContainerNode())
         toContainerNode(this)->insertBefore(newChild, refChild, exceptionState);
     else
-        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("insertBefore", "Node", "This node type does not support this method."));
+        exceptionState.throwDOMException(HierarchyRequestError, "This node type does not support this method.");
 }
 
 void Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& exceptionState)
@@ -461,7 +460,7 @@
     if (isContainerNode())
         toContainerNode(this)->replaceChild(newChild, oldChild, exceptionState);
     else
-        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("replaceChild", "Node", "This node type does not support this method."));
+        exceptionState.throwDOMException(HierarchyRequestError,  "This node type does not support this method.");
 }
 
 void Node::removeChild(Node* oldChild, ExceptionState& exceptionState)
@@ -469,7 +468,7 @@
     if (isContainerNode())
         toContainerNode(this)->removeChild(oldChild, exceptionState);
     else
-        exceptionState.throwDOMException(NotFoundError, ExceptionMessages::failedToExecute("removeChild", "Node", "This node type does not support this method."));
+        exceptionState.throwDOMException(NotFoundError, "This node type does not support this method.");
 }
 
 void Node::appendChild(PassRefPtr<Node> newChild, ExceptionState& exceptionState)
@@ -477,7 +476,7 @@
     if (isContainerNode())
         toContainerNode(this)->appendChild(newChild, exceptionState);
     else
-        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("appendChild", "Node", "This node type does not support this method."));
+        exceptionState.throwDOMException(HierarchyRequestError, "This node type does not support this method.");
 }
 
 void Node::remove(ExceptionState& exceptionState)
@@ -520,7 +519,7 @@
     // The spec says that for nodes other than elements and attributes, prefix is always null.
     // It does not say what to do when the user tries to set the prefix on another type of
     // node, however Mozilla throws a NamespaceError exception.
-    exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "Prefixes are only supported on element and attribute nodes."));
+    exceptionState.throwDOMException(NamespaceError, "Prefixes are only supported on element and attribute nodes.");
 }
 
 const AtomicString& Node::localName() const
@@ -727,6 +726,18 @@
 
     if (existingChangeType == NoStyleChange)
         markAncestorsWithChildNeedsStyleRecalc();
+
+    if (isElementNode() && hasRareData())
+        toElement(*this).setAnimationStyleChange(false);
+}
+
+void Node::clearNeedsStyleRecalc()
+{
+    m_nodeFlags &= ~StyleChangeMask;
+    clearFlag(NotifyRendererWithIdenticalStyles);
+
+    if (isElementNode() && hasRareData())
+        toElement(*this).setAnimationStyleChange(false);
 }
 
 bool Node::inActiveDocument() const
@@ -837,7 +848,7 @@
     // Element::setPrefix() and Attr::setPrefix()
 
     if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
-        exceptionState.throwDOMException(InvalidCharacterError, ExceptionMessages::failedToSet("prefix", "Node", "The prefix '" + prefix + "' is not a valid name."));
+        exceptionState.throwDOMException(InvalidCharacterError, "The prefix '" + prefix + "' is not a valid name.");
         return;
     }
 
@@ -845,12 +856,12 @@
 
     const AtomicString& nodeNamespaceURI = namespaceURI();
     if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
-        exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "No namespace is set, so a namespace prefix may not be set."));
+        exceptionState.throwDOMException(NamespaceError, "No namespace is set, so a namespace prefix may not be set.");
         return;
     }
 
     if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
-        exceptionState.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'."));
+        exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'.");
         return;
     }
     // Attribute-specific checks are in Attr::setPrefix().
@@ -1154,7 +1165,7 @@
     while (root) {
         if (root->isShadowRoot())
             return root;
-        Node* parent = root->parentNodeGuaranteedHostFree();
+        Node* parent = root->parentOrShadowHostNode();
         if (parent && parent->isShadowRoot())
             return root;
         root = parent;
@@ -1286,7 +1297,7 @@
 PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionState& exceptionState)
 {
     if (selectors.isEmpty()) {
-        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("querySelector", "Node", "The provided selector is empty."));
+        exceptionState.throwDOMException(SyntaxError,  "The provided selector is empty.");
         return 0;
     }
 
@@ -1299,7 +1310,7 @@
 PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionState& exceptionState)
 {
     if (selectors.isEmpty()) {
-        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("querySelectorAll", "Node", "The provided selector is empty."));
+        exceptionState.throwDOMException(SyntaxError, "The provided selector is empty.");
         return 0;
     }
 
@@ -1427,13 +1438,13 @@
     }
 }
 
-String Node::lookupPrefix(const AtomicString &namespaceURI) const
+const AtomicString& Node::lookupPrefix(const AtomicString& namespaceURI) const
 {
     // Implemented according to
     // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
 
     if (namespaceURI.isEmpty())
-        return String();
+        return nullAtom;
 
     switch (nodeType()) {
         case ELEMENT_NODE:
@@ -1441,32 +1452,32 @@
         case DOCUMENT_NODE:
             if (Element* de = toDocument(this)->documentElement())
                 return de->lookupPrefix(namespaceURI);
-            return String();
+            return nullAtom;
         case ENTITY_NODE:
         case NOTATION_NODE:
         case DOCUMENT_FRAGMENT_NODE:
         case DOCUMENT_TYPE_NODE:
-            return String();
+            return nullAtom;
         case ATTRIBUTE_NODE: {
             const Attr *attr = static_cast<const Attr *>(this);
             if (attr->ownerElement())
                 return attr->ownerElement()->lookupPrefix(namespaceURI);
-            return String();
+            return nullAtom;
         }
         default:
             if (Element* ancestor = ancestorElement())
                 return ancestor->lookupPrefix(namespaceURI);
-            return String();
+            return nullAtom;
     }
 }
 
-String Node::lookupNamespaceURI(const String &prefix) const
+const AtomicString& Node::lookupNamespaceURI(const String& prefix) const
 {
     // Implemented according to
     // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
 
     if (!prefix.isNull() && prefix.isEmpty())
-        return String();
+        return nullAtom;
 
     switch (nodeType()) {
         case ELEMENT_NODE: {
@@ -1483,47 +1494,47 @@
                         if (!attr->value().isEmpty())
                             return attr->value();
 
-                        return String();
+                        return nullAtom;
                     } else if (attr->localName() == xmlnsAtom && prefix.isNull()) {
                         if (!attr->value().isEmpty())
                             return attr->value();
 
-                        return String();
+                        return nullAtom;
                     }
                 }
             }
             if (Element* ancestor = ancestorElement())
                 return ancestor->lookupNamespaceURI(prefix);
-            return String();
+            return nullAtom;
         }
         case DOCUMENT_NODE:
             if (Element* de = toDocument(this)->documentElement())
                 return de->lookupNamespaceURI(prefix);
-            return String();
+            return nullAtom;
         case ENTITY_NODE:
         case NOTATION_NODE:
         case DOCUMENT_TYPE_NODE:
         case DOCUMENT_FRAGMENT_NODE:
-            return String();
+            return nullAtom;
         case ATTRIBUTE_NODE: {
             const Attr *attr = static_cast<const Attr *>(this);
 
             if (attr->ownerElement())
                 return attr->ownerElement()->lookupNamespaceURI(prefix);
             else
-                return String();
+                return nullAtom;
         }
         default:
             if (Element* ancestor = ancestorElement())
                 return ancestor->lookupNamespaceURI(prefix);
-            return String();
+            return nullAtom;
     }
 }
 
-String Node::lookupNamespacePrefix(const AtomicString &_namespaceURI, const Element *originalElement) const
+const AtomicString& Node::lookupNamespacePrefix(const AtomicString& _namespaceURI, const Element* originalElement) const
 {
     if (_namespaceURI.isNull())
-        return String();
+        return nullAtom;
 
     if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
         return prefix();
@@ -1542,7 +1553,7 @@
 
     if (Element* ancestor = ancestorElement())
         return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
-    return String();
+    return nullAtom;
 }
 
 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
@@ -1594,7 +1605,7 @@
     return isNullString ? String() : content.toString();
 }
 
-void Node::setTextContent(const String& text, ExceptionState& exceptionState)
+void Node::setTextContent(const String& text)
 {
     switch (nodeType()) {
         case TEXT_NODE:
@@ -1611,7 +1622,7 @@
             ChildListMutationScope mutation(*this);
             container->removeChildren();
             if (!text.isEmpty())
-                container->appendChild(document().createTextNode(text), exceptionState);
+                container->appendChild(document().createTextNode(text), ASSERT_NO_EXCEPTION);
             return;
         }
         case DOCUMENT_NODE:
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index a139faf..382652d 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -210,12 +210,12 @@
     bool isSameNode(Node* other) const { return this == other; }
     bool isEqualNode(Node*) const;
     bool isDefaultNamespace(const AtomicString& namespaceURI) const;
-    String lookupPrefix(const AtomicString& namespaceURI) const;
-    String lookupNamespaceURI(const String& prefix) const;
-    String lookupNamespacePrefix(const AtomicString& namespaceURI, const Element* originalElement) const;
+    const AtomicString& lookupPrefix(const AtomicString& namespaceURI) const;
+    const AtomicString& lookupNamespaceURI(const String& prefix) const;
+    const AtomicString& lookupNamespacePrefix(const AtomicString& namespaceURI, const Element* originalElement) const;
 
     String textContent(bool convertBRsToNewlines = false) const;
-    void setTextContent(const String&, ExceptionState&);
+    void setTextContent(const String&);
 
     Node& lastDescendant() const;
 
@@ -298,8 +298,6 @@
     // Knows about all kinds of hosts.
     ContainerNode* parentOrShadowHostOrTemplateHostNode() const;
 
-    // Use when it's guaranteed to that shadowHost is 0.
-    ContainerNode* parentNodeGuaranteedHostFree() const;
     // Returns the parent node, but 0 if the parent node is a ShadowRoot.
     ContainerNode* nonShadowBoundaryParentNode() const;
 
@@ -380,11 +378,7 @@
     void clearChildNeedsStyleRecalc() { clearFlag(ChildNeedsStyleRecalcFlag); }
 
     void setNeedsStyleRecalc(StyleChangeType = SubtreeStyleChange, StyleChangeSource = StyleChangeFromCSS);
-    void clearNeedsStyleRecalc()
-    {
-        m_nodeFlags &= ~StyleChangeMask;
-        clearFlag(NotifyRendererWithIdenticalStyles);
-    }
+    void clearNeedsStyleRecalc();
 
     bool childNeedsDistributionRecalc() const { return getFlag(ChildNeedsDistributionRecalc); }
     void setChildNeedsDistributionRecalc()  { setFlag(ChildNeedsDistributionRecalc); }
@@ -525,6 +519,7 @@
     // Integration with rendering tree
 
     // As renderer() includes a branch you should avoid calling it repeatedly in hot code paths.
+    // Note that if a Node has a renderer, it's parentNode is guaranteed to have one as well.
     RenderObject* renderer() const { return hasRareData() ? m_data.m_rareData->renderer() : m_data.m_renderer; };
     void setRenderer(RenderObject* renderer)
     {
@@ -893,12 +888,6 @@
     return isShadowRoot() ? 0 : parentOrShadowHostNode();
 }
 
-inline ContainerNode* Node::parentNodeGuaranteedHostFree() const
-{
-    ASSERT(!isShadowRoot());
-    return parentOrShadowHostNode();
-}
-
 inline void Node::lazyReattachIfAttached()
 {
     if (styleChangeType() == NeedsReattachStyleChange)
diff --git a/Source/core/dom/Node.idl b/Source/core/dom/Node.idl
index b066000..c67bbeb 100644
--- a/Source/core/dom/Node.idl
+++ b/Source/core/dom/Node.idl
@@ -19,8 +19,8 @@
  */
 
 [
-    CustomWrap,
-    DependentLifetime
+    Custom=Wrap,
+    DependentLifetime,
 ] interface Node : EventTarget {
     // NodeType
     const unsigned short      ELEMENT_NODE                   = 1;
@@ -36,9 +36,8 @@
     const unsigned short      DOCUMENT_FRAGMENT_NODE         = 11;
     const unsigned short      NOTATION_NODE                  = 12;
 
-    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString        nodeName;
+    [PerWorldBindings] readonly attribute DOMString nodeName;
 
-             // FIXME: the spec says this can also raise on retrieval.
     [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, CustomElementCallbacks] attribute DOMString nodeValue;
 
     [PerWorldBindings] readonly attribute unsigned short   nodeType;
@@ -69,16 +68,15 @@
     [TreatReturnedNullStringAs=Null, PerWorldBindings, MeasureAs=NodeLocalName] readonly attribute DOMString localName; // Moved to Element and Attr in DOM4.
 
     // Introduced in DOM Level 3:
-    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString       baseURI;
+    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString baseURI;
 
-             // FIXME: the spec says this can also raise on retrieval.
-             [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter, CustomElementCallbacks] attribute DOMString       textContent;
+    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, CustomElementCallbacks] attribute DOMString textContent;
 
     [MeasureAs=NodeIsSameNode] boolean isSameNode([Default=Undefined] optional Node other); // Removed in DOM4.
-    boolean            isEqualNode([Default=Undefined] optional Node other);
-    [TreatReturnedNullStringAs=Null] DOMString          lookupPrefix([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI);
-    boolean            isDefaultNamespace([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI);
-    [TreatReturnedNullStringAs=Null] DOMString          lookupNamespaceURI([TreatNullAs=NullString,Default=Undefined] optional DOMString prefix);
+    boolean isEqualNode(Node other);
+    [TreatReturnedNullStringAs=Null] DOMString lookupPrefix([TreatNullAs=NullString] DOMString namespaceURI);
+    boolean isDefaultNamespace([TreatNullAs=NullString] DOMString namespaceURI);
+    [TreatReturnedNullStringAs=Null] DOMString lookupNamespaceURI([TreatNullAs=NullString] DOMString prefix);
 
     // DocumentPosition
     const unsigned short      DOCUMENT_POSITION_DISCONNECTED = 0x01;
@@ -88,11 +86,11 @@
     const unsigned short      DOCUMENT_POSITION_CONTAINED_BY = 0x10;
     const unsigned short      DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20;
 
-    unsigned short     compareDocumentPosition([Default=Undefined] optional Node other);
+    unsigned short compareDocumentPosition(Node other);
 
     // Introduced in DOM4
-    [ImplementedAs=bindingsContains] boolean contains([Default=Undefined] optional Node other);
+    [ImplementedAs=bindingsContains] boolean contains(Node other);
 
     // IE extensions
-    [PerWorldBindings] readonly attribute Element          parentElement;
+    [PerWorldBindings] readonly attribute Element parentElement;
 };
diff --git a/Source/core/dom/NodeIterator.cpp b/Source/core/dom/NodeIterator.cpp
index 2643139..35c912f 100644
--- a/Source/core/dom/NodeIterator.cpp
+++ b/Source/core/dom/NodeIterator.cpp
@@ -25,12 +25,10 @@
 #include "config.h"
 #include "core/dom/NodeIterator.h"
 
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ScriptState.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/dom/NodeFilter.h"
 #include "core/dom/NodeTraversal.h"
 
 namespace WebCore {
@@ -91,7 +89,7 @@
 PassRefPtr<Node> NodeIterator::nextNode(ScriptState* state, ExceptionState& exceptionState)
 {
     if (m_detached) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("nextNode", "NodeIterator", "The iterator is detached."));
+        exceptionState.throwDOMException(InvalidStateError, "The iterator is detached.");
         return 0;
     }
 
@@ -120,7 +118,7 @@
 PassRefPtr<Node> NodeIterator::previousNode(ScriptState* state, ExceptionState& exceptionState)
 {
     if (m_detached) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("previousNode", "NodeIterator", "The iterator is detached."));
+        exceptionState.throwDOMException(InvalidStateError, "The iterator is detached.");
         return 0;
     }
 
diff --git a/Source/core/dom/NodeList.idl b/Source/core/dom/NodeList.idl
index 2e48078..19ccec6 100644
--- a/Source/core/dom/NodeList.idl
+++ b/Source/core/dom/NodeList.idl
@@ -19,8 +19,8 @@
  */
 
 [
-    CustomVisitDOMWrapper,
-    DependentLifetime
+    Custom=VisitDOMWrapper,
+    DependentLifetime,
 ] interface NodeList {
 
     getter Node item(unsigned long index);
diff --git a/Source/core/dom/NodeRenderingContext.cpp b/Source/core/dom/NodeRenderingContext.cpp
index f94665c..2d2b4a4 100644
--- a/Source/core/dom/NodeRenderingContext.cpp
+++ b/Source/core/dom/NodeRenderingContext.cpp
@@ -27,7 +27,6 @@
 #include "core/dom/NodeRenderingContext.h"
 
 #include "RuntimeEnabledFeatures.h"
-#include "core/animation/css/CSSAnimations.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ContainerNode.h"
 #include "core/dom/FullscreenElementStack.h"
@@ -206,11 +205,8 @@
     if (!shouldCreateRenderer() && !elementInsideRegionNeedsRenderer())
         return;
 
-    if (!m_style) {
-        CSSAnimationUpdateScope cssAnimationUpdateScope(element);
+    if (!m_style)
         m_style = element->styleForRenderer();
-    }
-    ASSERT(m_style);
 
     moveToFlowThreadIfNeeded();
 
@@ -258,7 +254,7 @@
     RenderObject* parentRenderer = this->parentRenderer();
 
     if (m_parentDetails.resetStyleInheritance())
-        m_style = textNode->document().styleResolver()->defaultStyleForElement();
+        m_style = textNode->document().ensureStyleResolver().defaultStyleForElement();
     else
         m_style = parentRenderer->style();
 
diff --git a/Source/core/dom/Position.cpp b/Source/core/dom/Position.cpp
index 4ceb136..1ce44d8 100644
--- a/Source/core/dom/Position.cpp
+++ b/Source/core/dom/Position.cpp
@@ -1016,13 +1016,13 @@
     InlineBox* b2;
     pos.getInlineBoxAndOffset(DOWNSTREAM, b2, ignoredCaretOffset);
 
-    LOG(Editing, "renderer:               %p [%p]\n", renderer, b1);
-    LOG(Editing, "thisRenderedOffset:         %d\n", thisRenderedOffset);
-    LOG(Editing, "posRenderer:            %p [%p]\n", posRenderer, b2);
-    LOG(Editing, "posRenderedOffset:      %d\n", posRenderedOffset);
-    LOG(Editing, "node min/max:           %d:%d\n", caretMinOffset(deprecatedNode()), caretMaxOffset(deprecatedNode()));
-    LOG(Editing, "pos node min/max:       %d:%d\n", caretMinOffset(pos.deprecatedNode()), caretMaxOffset(pos.deprecatedNode()));
-    LOG(Editing, "----------------------------------------------------------------------\n");
+    WTF_LOG(Editing, "renderer:               %p [%p]\n", renderer, b1);
+    WTF_LOG(Editing, "thisRenderedOffset:         %d\n", thisRenderedOffset);
+    WTF_LOG(Editing, "posRenderer:            %p [%p]\n", posRenderer, b2);
+    WTF_LOG(Editing, "posRenderedOffset:      %d\n", posRenderedOffset);
+    WTF_LOG(Editing, "node min/max:           %d:%d\n", caretMinOffset(deprecatedNode()), caretMaxOffset(deprecatedNode()));
+    WTF_LOG(Editing, "pos node min/max:       %d:%d\n", caretMinOffset(pos.deprecatedNode()), caretMaxOffset(pos.deprecatedNode()));
+    WTF_LOG(Editing, "----------------------------------------------------------------------\n");
 
     if (!b1 || !b2) {
         return false;
diff --git a/Source/core/dom/PositionIterator.cpp b/Source/core/dom/PositionIterator.cpp
index 5cc76b1..f94c0ae 100644
--- a/Source/core/dom/PositionIterator.cpp
+++ b/Source/core/dom/PositionIterator.cpp
@@ -27,7 +27,6 @@
 #include "core/dom/PositionIterator.h"
 
 #include "HTMLNames.h"
-#include "core/dom/Node.h"
 #include "core/editing/htmlediting.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/rendering/RenderBlock.h"
diff --git a/Source/core/dom/QualifiedName.cpp b/Source/core/dom/QualifiedName.cpp
index 21e97ae..1912986 100644
--- a/Source/core/dom/QualifiedName.cpp
+++ b/Source/core/dom/QualifiedName.cpp
@@ -69,7 +69,7 @@
     }
     static void translate(QualifiedName::QualifiedNameImpl*& location, const QualifiedNameComponents& components, unsigned)
     {
-        location = QualifiedName::QualifiedNameImpl::create(components.m_prefix, components.m_localName, components.m_namespace).leakRef();
+        location = QualifiedName::QualifiedNameImpl::create(AtomicString(components.m_prefix), AtomicString(components.m_localName), AtomicString(components.m_namespace)).leakRef();
     }
 };
 
diff --git a/Source/core/dom/Range.cpp b/Source/core/dom/Range.cpp
index e8355a0..5b75ea2 100644
--- a/Source/core/dom/Range.cpp
+++ b/Source/core/dom/Range.cpp
@@ -27,7 +27,6 @@
 
 #include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ClientRect.h"
 #include "core/dom/ClientRectList.h"
 #include "core/dom/DocumentFragment.h"
@@ -47,7 +46,6 @@
 #include "core/rendering/RenderText.h"
 #include "platform/geometry/FloatQuad.h"
 #include "wtf/RefCountedLeakCounter.h"
-#include "wtf/Vector.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
 #ifndef NDEBUG
@@ -131,7 +129,7 @@
 Node* Range::startContainer(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("startContainer", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -141,7 +139,7 @@
 int Range::startOffset(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("startOffset", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -151,7 +149,7 @@
 Node* Range::endContainer(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("endContainer", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -161,7 +159,7 @@
 int Range::endOffset(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("endOffset", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -171,7 +169,7 @@
 Node* Range::commonAncestorContainer(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("commonAncestorContainer", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -192,7 +190,7 @@
 bool Range::collapsed(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapsed", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -214,7 +212,7 @@
 void Range::setStart(PassRefPtr<Node> refNode, int offset, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setStart", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
@@ -242,7 +240,7 @@
 void Range::setEnd(PassRefPtr<Node> refNode, int offset, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setEnd", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
@@ -282,7 +280,7 @@
 void Range::collapse(bool toStart, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapse", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
@@ -295,7 +293,7 @@
 bool Range::isPointInRange(Node* refNode, int offset, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("isPointInRange", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return false;
     }
 
@@ -323,7 +321,7 @@
     // refNode node and an offset within the node is before, same as, or after the range respectively.
 
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("comparePoint", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -406,7 +404,7 @@
 short Range::compareBoundaryPoints(CompareHow how, const Range* sourceRange, ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("compareBoundaryPoints", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -559,7 +557,7 @@
 
 void Range::deleteContents(ExceptionState& exceptionState)
 {
-    checkDeleteExtract("deleteContents", exceptionState);
+    checkDeleteExtract(exceptionState);
     if (exceptionState.hadException())
         return;
 
@@ -573,7 +571,7 @@
 
     // Throw exception if the range is already detached.
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("intersectsNode", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return false;
     }
     if (!refNode) {
@@ -928,7 +926,7 @@
 
 PassRefPtr<DocumentFragment> Range::extractContents(ExceptionState& exceptionState)
 {
-    checkDeleteExtract("extractContents", exceptionState);
+    checkDeleteExtract(exceptionState);
     if (exceptionState.hadException())
         return 0;
 
@@ -938,7 +936,7 @@
 PassRefPtr<DocumentFragment> Range::cloneContents(ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("cloneContents", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -950,7 +948,7 @@
     RefPtr<Node> newNode = prpNewNode;
 
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("insertNode", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
@@ -1062,7 +1060,7 @@
 String Range::toString(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("toString", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return String();
     }
 
@@ -1102,13 +1100,13 @@
 PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
     Node* element = m_start.container()->isElementNode() ? m_start.container() : m_start.container()->parentNode();
     if (!element || !element->isHTMLElement()) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("createContextualFragment", "Range", "The range's container must be an HTML element."));
+        exceptionState.throwDOMException(NotSupportedError, "The range's container must be an HTML element.");
         return 0;
     }
 
@@ -1124,7 +1122,7 @@
 {
     // Check first to see if we've already detached:
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("detach", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
@@ -1169,10 +1167,10 @@
     return 0;
 }
 
-void Range::checkNodeBA(Node* n, const String& methodName, ExceptionState& exceptionState) const
+void Range::checkNodeBA(Node* n, ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute(methodName, "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
@@ -1186,7 +1184,7 @@
     // or if refNode is a Document, DocumentFragment, ShadowRoot, Attr, Entity, or Notation node.
 
     if (!n->parentNode()) {
-        exceptionState.throwDOMException(InvalidNodeTypeError, ExceptionMessages::failedToExecute(methodName, "Range", "the given Node has no parent."));
+        exceptionState.throwDOMException(InvalidNodeTypeError, "the given Node has no parent.");
         return;
     }
 
@@ -1234,7 +1232,7 @@
 PassRefPtr<Range> Range::cloneRange(ExceptionState& exceptionState) const
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("cloneRange", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return 0;
     }
 
@@ -1243,7 +1241,7 @@
 
 void Range::setStartAfter(Node* refNode, ExceptionState& exceptionState)
 {
-    checkNodeBA(refNode, "setStartAfter", exceptionState);
+    checkNodeBA(refNode, exceptionState);
     if (exceptionState.hadException())
         return;
 
@@ -1252,7 +1250,7 @@
 
 void Range::setEndBefore(Node* refNode, ExceptionState& exceptionState)
 {
-    checkNodeBA(refNode, "setEndBefore", exceptionState);
+    checkNodeBA(refNode, exceptionState);
     if (exceptionState.hadException())
         return;
 
@@ -1261,7 +1259,7 @@
 
 void Range::setEndAfter(Node* refNode, ExceptionState& exceptionState)
 {
-    checkNodeBA(refNode, "setEndAfter", exceptionState);
+    checkNodeBA(refNode, exceptionState);
     if (exceptionState.hadException())
         return;
 
@@ -1271,7 +1269,7 @@
 void Range::selectNode(Node* refNode, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("selectNode", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
@@ -1281,7 +1279,7 @@
     }
 
     if (!refNode->parentNode()) {
-        exceptionState.throwDOMException(InvalidNodeTypeError, ExceptionMessages::failedToExecute("selectNode", "Range", "the given Node has no parent."));
+        exceptionState.throwDOMException(InvalidNodeTypeError, "the given Node has no parent.");
         return;
     }
 
@@ -1336,7 +1334,7 @@
 void Range::selectNodeContents(Node* refNode, ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("selectNodeContents", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
@@ -1379,7 +1377,7 @@
     RefPtr<Node> newParent = passNewParent;
 
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("surroundContents", "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
@@ -1460,17 +1458,17 @@
 
 void Range::setStartBefore(Node* refNode, ExceptionState& exceptionState)
 {
-    checkNodeBA(refNode, "setStartBefore", exceptionState);
+    checkNodeBA(refNode, exceptionState);
     if (exceptionState.hadException())
         return;
 
     setStart(refNode->parentNode(), refNode->nodeIndex(), exceptionState);
 }
 
-void Range::checkDeleteExtract(const String& methodName, ExceptionState& exceptionState)
+void Range::checkDeleteExtract(ExceptionState& exceptionState)
 {
     if (!m_start.container()) {
-        exceptionState.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute(methodName, "Range", "The range has no container. Perhaps 'detatch()' has been invoked on this object?"));
+        exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
         return;
     }
 
diff --git a/Source/core/dom/Range.h b/Source/core/dom/Range.h
index ab77a96..3a662f1 100644
--- a/Source/core/dom/Range.h
+++ b/Source/core/dom/Range.h
@@ -156,8 +156,8 @@
     void setDocument(Document&);
 
     Node* checkNodeWOffset(Node*, int offset, ExceptionState&) const;
-    void checkNodeBA(Node*, const String& methodName, ExceptionState&) const;
-    void checkDeleteExtract(const String& methodName, ExceptionState&);
+    void checkNodeBA(Node*, ExceptionState&) const;
+    void checkDeleteExtract(ExceptionState&);
     int maxStartOffset() const;
     int maxEndOffset() const;
 
diff --git a/Source/core/dom/Range.idl b/Source/core/dom/Range.idl
index 4b8a5ee..d3dd1eb 100644
--- a/Source/core/dom/Range.idl
+++ b/Source/core/dom/Range.idl
@@ -21,7 +21,7 @@
 // Introduced in DOM Level 2:
 [
     Constructor,
-    ConstructorCallWith=Document
+    ConstructorCallWith=Document,
 ] interface Range {
 
     [RaisesException=Getter] readonly attribute Node startContainer;
@@ -31,17 +31,15 @@
     [RaisesException=Getter] readonly attribute boolean collapsed;
     [RaisesException=Getter] readonly attribute Node commonAncestorContainer;
 
-     [RaisesException] void setStart([Default=Undefined] optional Node refNode,
-                                 [Default=Undefined] optional long offset);
-     [RaisesException] void setEnd([Default=Undefined] optional Node refNode,
-                               [Default=Undefined] optional long offset);
-    [RaisesException] void setStartBefore([Default=Undefined] optional Node refNode);
-    [RaisesException] void setStartAfter([Default=Undefined] optional Node refNode);
-    [RaisesException] void setEndBefore([Default=Undefined] optional Node refNode);
-    [RaisesException] void setEndAfter([Default=Undefined] optional Node refNode);
+    [RaisesException] void setStart(Node refNode, long offset);
+    [RaisesException] void setEnd(Node refNode, long offset);
+    [RaisesException] void setStartBefore(Node refNode);
+    [RaisesException] void setStartAfter(Node refNode);
+    [RaisesException] void setEndBefore(Node refNode);
+    [RaisesException] void setEndAfter(Node refNode);
     [RaisesException] void collapse([Default=Undefined] optional boolean toStart);
-    [RaisesException] void selectNode([Default=Undefined] optional Node refNode);
-    [RaisesException] void selectNodeContents([Default=Undefined] optional Node refNode);
+    [RaisesException] void selectNode(Node refNode);
+    [RaisesException] void selectNodeContents(Node refNode);
 
     // CompareHow
     const unsigned short START_TO_START = 0;
@@ -49,46 +47,41 @@
     const unsigned short END_TO_END     = 2;
     const unsigned short END_TO_START   = 3;
 
-     [RaisesException] short compareBoundaryPoints([Default=Undefined] optional CompareHow how,
-                                               [Default=Undefined] optional Range sourceRange);
+    [RaisesException] short compareBoundaryPoints(CompareHow how, Range sourceRange);
 
     [RaisesException, CustomElementCallbacks] void deleteContents();
     [RaisesException, CustomElementCallbacks] DocumentFragment extractContents();
     [RaisesException, CustomElementCallbacks] DocumentFragment cloneContents();
-    [RaisesException, CustomElementCallbacks] void insertNode([Default=Undefined] optional Node newNode);
-    [RaisesException, CustomElementCallbacks] void surroundContents([Default=Undefined] optional Node newParent);
+    [RaisesException, CustomElementCallbacks] void insertNode(Node newNode);
+    [RaisesException, CustomElementCallbacks] void surroundContents(Node newParent);
     [RaisesException] Range cloneRange();
     [RaisesException] DOMString toString();
 
     [RaisesException] void detach();
 
+    [RaisesException] boolean isPointInRange(Node refNode, long offset);
+    [RaisesException] short comparePoint(Node refNode, long offset);
+
+    [RaisesException] boolean intersectsNode(Node refNode);
+
     // CSSOM View Module API extensions
 
     ClientRectList getClientRects();
     ClientRect getBoundingClientRect();
 
-    // extensions
+    // DOM Parsing and Serialization
 
-    [RaisesException, CustomElementCallbacks] DocumentFragment createContextualFragment([Default=Undefined] optional DOMString html);
+    [RaisesException, CustomElementCallbacks] DocumentFragment createContextualFragment(DOMString html);
 
     // WebKit extensions
 
-    [RaisesException] boolean intersectsNode([Default=Undefined] optional Node refNode);
-
-    [RaisesException] short compareNode([Default=Undefined] optional Node refNode);
-
     // CompareResults
     const unsigned short NODE_BEFORE           = 0;
     const unsigned short NODE_AFTER            = 1;
     const unsigned short NODE_BEFORE_AND_AFTER = 2;
     const unsigned short NODE_INSIDE           = 3;
 
-    [RaisesException] short comparePoint([Default=Undefined] optional Node refNode,
-                       [Default=Undefined] optional long offset);
-
-    [RaisesException] boolean isPointInRange([Default=Undefined] optional Node refNode,
-                           [Default=Undefined] optional long offset);
+    [RaisesException] short compareNode([Default=Undefined] optional Node refNode);
 
     [RaisesException] void expand([Default=Undefined] optional DOMString unit);
 };
-
diff --git a/Source/core/dom/RequestAnimationFrameCallback.h b/Source/core/dom/RequestAnimationFrameCallback.h
index 768e4a1..d2b212b 100644
--- a/Source/core/dom/RequestAnimationFrameCallback.h
+++ b/Source/core/dom/RequestAnimationFrameCallback.h
@@ -31,17 +31,15 @@
 #ifndef RequestAnimationFrameCallback_h
 #define RequestAnimationFrameCallback_h
 
-#include "wtf/RefCounted.h"
-
 namespace WebCore {
 
-class RequestAnimationFrameCallback : public RefCounted<RequestAnimationFrameCallback> {
+class RequestAnimationFrameCallback {
 public:
     virtual ~RequestAnimationFrameCallback() { }
     virtual bool handleEvent(double highResTimeMs) = 0;
 
     int m_id;
-    bool m_firedOrCancelled;
+    bool m_cancelled;
     bool m_useLegacyTimeBase;
 };
 
diff --git a/Source/core/dom/SandboxFlags.h b/Source/core/dom/SandboxFlags.h
index 460f1f1..fa072d1 100644
--- a/Source/core/dom/SandboxFlags.h
+++ b/Source/core/dom/SandboxFlags.h
@@ -44,6 +44,7 @@
     SandboxAutomaticFeatures = 1 << 7,
     SandboxSeamlessIframes = 1 << 8,
     SandboxPointerLock = 1 << 9,
+    SandboxDocumentDomain = 1 << 10,
     SandboxAll = -1 // Mask with all bits set to 1.
 };
 
diff --git a/Source/core/dom/ScriptLoader.cpp b/Source/core/dom/ScriptLoader.cpp
index 68e9302..eaa0e45 100644
--- a/Source/core/dom/ScriptLoader.cpp
+++ b/Source/core/dom/ScriptLoader.cpp
@@ -49,7 +49,6 @@
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/StringBuilder.h"
 #include "wtf/text/StringHash.h"
-#include "wtf/text/TextPosition.h"
 
 namespace WebCore {
 
@@ -395,6 +394,7 @@
     CORSEnabled corsEnabled = isPotentiallyCORSEnabled() ? PotentiallyCORSEnabled : NotCORSEnabled;
     if (!elementDocument->fetcher()->canAccess(m_resource.get(), corsEnabled)) {
         dispatchErrorEvent();
+        contextDocument->scriptRunner()->notifyScriptLoadError(this, m_willExecuteInOrder ? ScriptRunner::IN_ORDER_EXECUTION : ScriptRunner::ASYNC_EXECUTION);
         return;
     }
 
diff --git a/Source/core/dom/ScriptRunner.cpp b/Source/core/dom/ScriptRunner.cpp
index 6cf96ae..2fbf959 100644
--- a/Source/core/dom/ScriptRunner.cpp
+++ b/Source/core/dom/ScriptRunner.cpp
@@ -99,6 +99,21 @@
     m_timer.startOneShot(0);
 }
 
+void ScriptRunner::notifyScriptLoadError(ScriptLoader* scriptLoader, ExecutionType executionType)
+{
+    switch (executionType) {
+    case ASYNC_EXECUTION:
+        ASSERT(m_pendingAsyncScripts.contains(scriptLoader));
+        m_pendingAsyncScripts.remove(scriptLoader);
+        m_document->decrementLoadEventDelayCount();
+        break;
+
+    case IN_ORDER_EXECUTION:
+        ASSERT(!m_scriptsToExecuteInOrder.isEmpty());
+        break;
+    }
+}
+
 void ScriptRunner::timerFired(Timer<ScriptRunner>* timer)
 {
     ASSERT_UNUSED(timer, timer == &m_timer);
diff --git a/Source/core/dom/ScriptRunner.h b/Source/core/dom/ScriptRunner.h
index 91164d0..b47139c 100644
--- a/Source/core/dom/ScriptRunner.h
+++ b/Source/core/dom/ScriptRunner.h
@@ -52,6 +52,7 @@
     void suspend();
     void resume();
     void notifyScriptReady(ScriptLoader*, ExecutionType);
+    void notifyScriptLoadError(ScriptLoader*, ExecutionType);
 
 private:
     explicit ScriptRunner(Document*);
diff --git a/Source/core/dom/ScriptedAnimationController.cpp b/Source/core/dom/ScriptedAnimationController.cpp
index 33446c8..27a7f6b 100644
--- a/Source/core/dom/ScriptedAnimationController.cpp
+++ b/Source/core/dom/ScriptedAnimationController.cpp
@@ -66,10 +66,10 @@
     scheduleAnimationIfNeeded();
 }
 
-ScriptedAnimationController::CallbackId ScriptedAnimationController::registerCallback(PassRefPtr<RequestAnimationFrameCallback> callback)
+ScriptedAnimationController::CallbackId ScriptedAnimationController::registerCallback(PassOwnPtr<RequestAnimationFrameCallback> callback)
 {
     ScriptedAnimationController::CallbackId id = ++m_nextCallbackId;
-    callback->m_firedOrCancelled = false;
+    callback->m_cancelled = false;
     callback->m_id = id;
     m_callbacks.append(callback);
     scheduleAnimationIfNeeded();
@@ -83,12 +83,19 @@
 {
     for (size_t i = 0; i < m_callbacks.size(); ++i) {
         if (m_callbacks[i]->m_id == id) {
-            m_callbacks[i]->m_firedOrCancelled = true;
             InspectorInstrumentation::didCancelAnimationFrame(m_document, id);
             m_callbacks.remove(i);
             return;
         }
     }
+    for (size_t i = 0; i < m_callbacksToInvoke.size(); ++i) {
+        if (m_callbacksToInvoke[i]->m_id == id) {
+            InspectorInstrumentation::didCancelAnimationFrame(m_document, id);
+            m_callbacksToInvoke[i]->m_cancelled = true;
+            // will be removed at the end of executeCallbacks()
+            return;
+        }
+    }
 }
 
 void ScriptedAnimationController::dispatchEvents()
@@ -120,12 +127,12 @@
 
     // First, generate a list of callbacks to consider.  Callbacks registered from this point
     // on are considered only for the "next" frame, not this one.
-    CallbackList callbacks(m_callbacks);
+    ASSERT(m_callbacksToInvoke.isEmpty());
+    m_callbacksToInvoke.swap(m_callbacks);
 
-    for (size_t i = 0; i < callbacks.size(); ++i) {
-        RequestAnimationFrameCallback* callback = callbacks[i].get();
-        if (!callback->m_firedOrCancelled) {
-            callback->m_firedOrCancelled = true;
+    for (size_t i = 0; i < m_callbacksToInvoke.size(); ++i) {
+        RequestAnimationFrameCallback* callback = m_callbacksToInvoke[i].get();
+        if (!callback->m_cancelled) {
             InspectorInstrumentationCookie cookie = InspectorInstrumentation::willFireAnimationFrame(m_document, callback->m_id);
             if (callback->m_useLegacyTimeBase)
                 callback->handleEvent(legacyHighResNowMs);
@@ -135,13 +142,7 @@
         }
     }
 
-    // Remove any callbacks we fired from the list of pending callbacks.
-    for (size_t i = 0; i < m_callbacks.size();) {
-        if (m_callbacks[i]->m_firedOrCancelled)
-            m_callbacks.remove(i);
-        else
-            ++i;
-    }
+    m_callbacksToInvoke.clear();
 }
 
 void ScriptedAnimationController::serviceScriptedAnimations(double monotonicTimeNow)
diff --git a/Source/core/dom/ScriptedAnimationController.h b/Source/core/dom/ScriptedAnimationController.h
index 7c83094..5f7efb8 100644
--- a/Source/core/dom/ScriptedAnimationController.h
+++ b/Source/core/dom/ScriptedAnimationController.h
@@ -50,7 +50,7 @@
 
     typedef int CallbackId;
 
-    int registerCallback(PassRefPtr<RequestAnimationFrameCallback>);
+    int registerCallback(PassOwnPtr<RequestAnimationFrameCallback>);
     void cancelCallback(CallbackId);
     void serviceScriptedAnimations(double monotonicTimeNow);
 
@@ -68,8 +68,9 @@
     void dispatchEvents();
     void executeCallbacks(double monotonicTimeNow);
 
-    typedef Vector<RefPtr<RequestAnimationFrameCallback> > CallbackList;
+    typedef Vector<OwnPtr<RequestAnimationFrameCallback> > CallbackList;
     CallbackList m_callbacks;
+    CallbackList m_callbacksToInvoke; // only non-empty while inside executeCallbacks
 
     Document* m_document;
     CallbackId m_nextCallbackId;
diff --git a/Source/core/dom/SelectorQuery.cpp b/Source/core/dom/SelectorQuery.cpp
index 50113c5..5fcf2ac 100644
--- a/Source/core/dom/SelectorQuery.cpp
+++ b/Source/core/dom/SelectorQuery.cpp
@@ -28,7 +28,6 @@
 
 #include "bindings/v8/ExceptionState.h"
 #include "core/css/CSSParser.h"
-#include "core/css/CSSSelectorList.h"
 #include "core/css/SelectorChecker.h"
 #include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/SiblingTraversalStrategies.h"
@@ -153,8 +152,7 @@
     SelectorChecker::SelectorCheckingContext selectorCheckingContext(selectorData.selector, &element, SelectorChecker::VisitedMatchDisabled);
     selectorCheckingContext.behaviorAtBoundary = SelectorChecker::StaysWithinTreeScope;
     selectorCheckingContext.scope = !rootNode.isDocumentNode() && rootNode.isContainerNode() ? &toContainerNode(rootNode) : 0;
-    PseudoId ignoreDynamicPseudo = NOPSEUDO;
-    return selectorChecker.match(selectorCheckingContext, ignoreDynamicPseudo, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches;
+    return selectorChecker.match(selectorCheckingContext, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches;
 }
 
 bool SelectorDataList::matches(Element& targetElement) const
@@ -502,13 +500,13 @@
     parser.parseSelector(selectors, selectorList);
 
     if (!selectorList.first()) {
-        exceptionState.throwDOMException(SyntaxError, "Failed to execute query: '" + selectors + "' is not a valid selector.");
+        exceptionState.throwDOMException(SyntaxError, "'" + selectors + "' is not a valid selector.");
         return 0;
     }
 
     // throw a NamespaceError if the selector includes any namespace prefixes.
     if (selectorList.selectorsNeedNamespaceResolution()) {
-        exceptionState.throwDOMException(NamespaceError, "Failed to execute query: '" + selectors + "' contains namespaces, which are not supported.");
+        exceptionState.throwDOMException(NamespaceError, "'" + selectors + "' contains namespaces, which are not supported.");
         return 0;
     }
 
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
index d0ae20a..f682a4f 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
@@ -98,7 +98,7 @@
     StyleSheetChange change;
     analyzeStyleSheetChange(updateMode, collection, change);
 
-    if (StyleResolver* styleResolver = engine->resolverIfExists()) {
+    if (StyleResolver* styleResolver = engine->resolver()) {
         // FIXME: We might have already had styles in child treescope. In this case, we cannot use buildScopedStyleTreeInDocumentOrder.
         // Need to change "false" to some valid condition.
         styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
diff --git a/Source/core/dom/StringCallback.cpp b/Source/core/dom/StringCallback.cpp
index 048dda5..1a1a5fc 100644
--- a/Source/core/dom/StringCallback.cpp
+++ b/Source/core/dom/StringCallback.cpp
@@ -41,7 +41,7 @@
 
 class DispatchCallbackTask : public ExecutionContextTask {
 public:
-    static PassOwnPtr<DispatchCallbackTask> create(PassRefPtr<StringCallback> callback, const String& data)
+    static PassOwnPtr<DispatchCallbackTask> create(PassOwnPtr<StringCallback> callback, const String& data)
     {
         return adoptPtr(new DispatchCallbackTask(callback, data));
     }
@@ -52,21 +52,21 @@
     }
 
 private:
-    DispatchCallbackTask(PassRefPtr<StringCallback> callback, const String& data)
+    DispatchCallbackTask(PassOwnPtr<StringCallback> callback, const String& data)
         : m_callback(callback)
         , m_data(data)
     {
     }
 
-    RefPtr<StringCallback> m_callback;
+    OwnPtr<StringCallback> m_callback;
     const String m_data;
 };
 
 } // namespace
 
-void StringCallback::scheduleCallback(ExecutionContext* context, const String& data)
+void StringCallback::scheduleCallback(PassOwnPtr<StringCallback> callback, ExecutionContext* context, const String& data)
 {
-    context->postTask(DispatchCallbackTask::create(this, data));
+    context->postTask(DispatchCallbackTask::create(callback, data));
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/StringCallback.h b/Source/core/dom/StringCallback.h
index fed4477..0e5b4c9 100644
--- a/Source/core/dom/StringCallback.h
+++ b/Source/core/dom/StringCallback.h
@@ -32,19 +32,18 @@
 #define StringCallback_h
 
 #include "wtf/Forward.h"
-#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
 class ExecutionContext;
 
-class StringCallback : public RefCounted<StringCallback> {
+class StringCallback {
 public:
     virtual ~StringCallback() { }
     virtual bool handleEvent(const String& data) = 0;
 
     // Helper to post callback task.
-    void scheduleCallback(ExecutionContext*, const String& data);
+    static void scheduleCallback(PassOwnPtr<StringCallback>, ExecutionContext*, const String& data);
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/StyleElement.cpp b/Source/core/dom/StyleElement.cpp
index 6a6037c..8233785 100644
--- a/Source/core/dom/StyleElement.cpp
+++ b/Source/core/dom/StyleElement.cpp
@@ -31,7 +31,6 @@
 #include "core/html/HTMLStyleElement.h"
 #include "core/frame/ContentSecurityPolicy.h"
 #include "wtf/text/StringBuilder.h"
-#include "wtf/text/TextPosition.h"
 
 namespace WebCore {
 
@@ -75,9 +74,7 @@
     if (m_sheet)
         clearSheet();
 
-    // If we're in document teardown, then we don't need to do any notification of our sheet's removal.
-    if (document.isActive())
-        document.removedStyleSheet(removedSheet.get(), RecalcStyleDeferred, AnalyzedStyleUpdate);
+    document.removedStyleSheet(removedSheet.get(), RecalcStyleDeferred, AnalyzedStyleUpdate);
 }
 
 void StyleElement::clearDocumentData(Document& document, Element* element)
diff --git a/Source/core/dom/StyleEngine.cpp b/Source/core/dom/StyleEngine.cpp
index 8a1d0c8..0c8385f 100644
--- a/Source/core/dom/StyleEngine.cpp
+++ b/Source/core/dom/StyleEngine.cpp
@@ -30,15 +30,16 @@
 
 #include "HTMLNames.h"
 #include "SVGNames.h"
+#include "core/css/CSSFontSelector.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/StyleInvalidationAnalysis.h"
 #include "core/css/StyleSheetContents.h"
-#include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/ShadowTreeStyleSheetCollection.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLIFrameElement.h"
+#include "core/html/HTMLImport.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLStyleElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
@@ -54,6 +55,7 @@
 
 StyleEngine::StyleEngine(Document& document)
     : m_document(document)
+    , m_isMaster(HTMLImport::isMaster(&document))
     , m_pendingStylesheets(0)
     , m_injectedStyleSheetCacheValid(false)
     , m_needsUpdateActiveStylesheetsOnStyleRecalc(false)
@@ -69,6 +71,9 @@
     , m_didCalculateResolver(false)
     , m_lastResolverAccessCount(0)
     , m_resolverThrowawayTimer(this, &StyleEngine::resolverThrowawayTimerFired)
+    // We don't need to create CSSFontSelector for imported document or
+    // HTMLTemplateElement's document, because those documents have no frame.
+    , m_fontSelector(document.frame() ? CSSFontSelector::create(&document) : 0)
 {
 }
 
@@ -80,6 +85,16 @@
         m_authorStyleSheets[i]->clearOwnerNode();
 }
 
+inline Document* StyleEngine::master()
+{
+    if (isMaster())
+        return &m_document;
+    HTMLImport* import = m_document.import();
+    if (!import) // Document::import() can return null while executing its destructor.
+        return 0;
+    return import->master();
+}
+
 void StyleEngine::insertTreeScopeInDocumentOrder(TreeScopeSet& treeScopes, TreeScope* treeScope)
 {
     if (treeScopes.isEmpty()) {
@@ -217,18 +232,32 @@
     m_dirtyTreeScopes.markDocument();
 }
 
+void StyleEngine::addPendingSheet()
+{
+    master()->styleEngine()->notifyPendingStyleSheetAdded();
+}
+
 // This method is called whenever a top-level stylesheet has finished loading.
 void StyleEngine::removePendingSheet(Node* styleSheetCandidateNode, RemovePendingSheetNotificationType notification)
 {
+    TreeScope* treeScope = isHTMLStyleElement(styleSheetCandidateNode) ? &styleSheetCandidateNode->treeScope() : &m_document;
+    m_dirtyTreeScopes.mark(*treeScope);
+    master()->styleEngine()->notifyPendingStyleSheetRemoved(notification);
+}
+
+void StyleEngine::notifyPendingStyleSheetAdded()
+{
+    ASSERT(isMaster());
+    m_pendingStylesheets++;
+}
+
+void StyleEngine::notifyPendingStyleSheetRemoved(RemovePendingSheetNotificationType notification)
+{
+    ASSERT(isMaster());
     // Make sure we knew this sheet was pending, and that our count isn't out of sync.
     ASSERT(m_pendingStylesheets > 0);
 
     m_pendingStylesheets--;
-
-    TreeScope* treeScope = isHTMLStyleElement(styleSheetCandidateNode) ? &styleSheetCandidateNode->treeScope() : &m_document;
-
-    m_dirtyTreeScopes.mark(*treeScope);
-
     if (m_pendingStylesheets)
         return;
 
@@ -321,8 +350,29 @@
     clearMediaQueryRuleSetOnTreeScopeStyleSheets(m_dirtyTreeScopes.subscope());
 }
 
+void StyleEngine::collectDocumentActiveStyleSheets(StyleSheetCollectionBase& collection)
+{
+    ASSERT(isMaster());
+
+    if (HTMLImport* rootImport = m_document.import()) {
+        for (HTMLImport* import = traverseFirstPostOrder(rootImport); import; import = traverseNextPostOrder(import)) {
+            Document* document = import->document();
+            if (!document)
+                continue;
+            StyleEngine* engine = document->styleEngine();
+            DocumentStyleSheetCollection::CollectFor collectFor = document == &m_document ?
+                DocumentStyleSheetCollection::CollectForList : DocumentStyleSheetCollection::DontCollectForList;
+            engine->m_documentStyleSheetCollection.collectStyleSheets(engine, collection, collectFor);
+        }
+    } else {
+        m_documentStyleSheetCollection.collectStyleSheets(this, collection, DocumentStyleSheetCollection::CollectForList);
+    }
+}
+
 bool StyleEngine::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
 {
+    ASSERT(isMaster());
+
     if (m_document.inStyleRecalc()) {
         // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
         // https://bugs.webkit.org/show_bug.cgi?id=54344
@@ -395,23 +445,23 @@
     m_styleSheetCollectionMap.remove(shadowRoot);
 }
 
-void StyleEngine::appendActiveAuthorStyleSheets(StyleResolver* styleResolver)
+void StyleEngine::appendActiveAuthorStyleSheets()
 {
-    ASSERT(styleResolver);
+    ASSERT(isMaster());
 
-    styleResolver->setBuildScopedStyleTreeInDocumentOrder(true);
-    styleResolver->appendAuthorStyleSheets(0, m_documentStyleSheetCollection.activeAuthorStyleSheets());
+    m_resolver->setBuildScopedStyleTreeInDocumentOrder(true);
+    m_resolver->appendAuthorStyleSheets(0, m_documentStyleSheetCollection.activeAuthorStyleSheets());
 
     TreeScopeSet::iterator begin = m_activeTreeScopes.begin();
     TreeScopeSet::iterator end = m_activeTreeScopes.end();
     for (TreeScopeSet::iterator it = begin; it != end; ++it) {
         if (StyleSheetCollection* collection = m_styleSheetCollectionMap.get(*it)) {
-            styleResolver->setBuildScopedStyleTreeInDocumentOrder(!collection->scopingNodesForStyleScoped());
-            styleResolver->appendAuthorStyleSheets(0, collection->activeAuthorStyleSheets());
+            m_resolver->setBuildScopedStyleTreeInDocumentOrder(!collection->scopingNodesForStyleScoped());
+            m_resolver->appendAuthorStyleSheets(0, collection->activeAuthorStyleSheets());
         }
     }
-    styleResolver->finishAppendAuthorStyleSheets();
-    styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
+    m_resolver->finishAppendAuthorStyleSheets();
+    m_resolver->setBuildScopedStyleTreeInDocumentOrder(false);
 }
 
 void StyleEngine::createResolver()
@@ -421,17 +471,30 @@
     // Document::isActive() before calling into code which could get here.
 
     ASSERT(m_document.frame());
+    ASSERT(m_fontSelector);
 
     m_resolver = adoptPtr(new StyleResolver(m_document));
+    appendActiveAuthorStyleSheets();
+    m_fontSelector->registerForInvalidationCallbacks(m_resolver.get());
     combineCSSFeatureFlags(m_resolver->ensureRuleFeatureSet());
 }
 
 void StyleEngine::clearResolver()
 {
     ASSERT(!m_document.inStyleRecalc());
+    ASSERT(isMaster() || !m_resolver);
+    ASSERT(m_fontSelector || !m_resolver);
+    if (m_resolver)
+        m_fontSelector->unregisterForInvalidationCallbacks(m_resolver.get());
     m_resolver.clear();
 }
 
+void StyleEngine::clearMasterResolver()
+{
+    if (Document* master = this->master())
+        master->styleEngine()->clearResolver();
+}
+
 unsigned StyleEngine::resolverAccessCount() const
 {
     return m_resolver ? m_resolver->accessCount() : 0;
@@ -444,11 +507,6 @@
     m_lastResolverAccessCount = resolverAccessCount();
 }
 
-CSSFontSelector* StyleEngine::fontSelector()
-{
-    return m_resolver ? m_resolver->fontSelector() : 0;
-}
-
 void StyleEngine::didAttach()
 {
     m_resolverThrowawayTimer.startRepeating(60);
@@ -465,10 +523,16 @@
     return !m_didCalculateResolver && !haveStylesheetsLoaded();
 }
 
-StyleResolverChange StyleEngine::resolverChanged(StyleResolverUpdateMode mode)
+StyleResolverChange StyleEngine::resolverChanged(RecalcStyleTime time, StyleResolverUpdateMode mode)
 {
     StyleResolverChange change;
 
+    if (!isMaster()) {
+        if (Document* master = this->master())
+            master->styleResolverChanged(time, mode);
+        return change;
+    }
+
     // Don't bother updating, since we haven't loaded all our style info yet
     // and haven't calculated the style selector for the first time.
     if (!m_document.isActive() || shouldClearResolver()) {
@@ -486,4 +550,26 @@
     return change;
 }
 
+void StyleEngine::resetFontSelector()
+{
+    if (!m_fontSelector)
+        return;
+
+    m_fontSelector->clearDocument();
+    if (m_resolver) {
+        m_fontSelector->unregisterForInvalidationCallbacks(m_resolver.get());
+        m_resolver->invalidateMatchedPropertiesCache();
+    }
+
+    // If the document has been already detached, we don't need to recreate
+    // CSSFontSelector.
+    if (m_document.isActive()) {
+        m_fontSelector = CSSFontSelector::create(&m_document);
+        if (m_resolver)
+            m_fontSelector->registerForInvalidationCallbacks(m_resolver.get());
+    } else {
+        m_fontSelector = 0;
+    }
+}
+
 }
diff --git a/Source/core/dom/StyleEngine.h b/Source/core/dom/StyleEngine.h
index 1c1b6fc..36c4b9d 100644
--- a/Source/core/dom/StyleEngine.h
+++ b/Source/core/dom/StyleEngine.h
@@ -115,7 +115,7 @@
     void setPreferredStylesheetSetName(const String& name) { m_preferredStylesheetSetName = name; }
     void setSelectedStylesheetSetName(const String& name) { m_selectedStylesheetSetName = name; }
 
-    void addPendingSheet() { m_pendingStylesheets++; }
+    void addPendingSheet();
     enum RemovePendingSheetNotificationType {
         RemovePendingSheetNotifyImmediately,
         RemovePendingSheetNotifyLater
@@ -141,34 +141,40 @@
 
     void didModifySeamlessParentStyleSheet() { m_dirtyTreeScopes.markDocument(); }
     void didRemoveShadowRoot(ShadowRoot*);
-    void appendActiveAuthorStyleSheets(StyleResolver*);
+    void appendActiveAuthorStyleSheets();
     void getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const;
 
-    StyleResolver* resolverIfExists() const
+    StyleResolver* resolver() const
     {
         return m_resolver.get();
     }
 
-    StyleResolver* resolver()
+    StyleResolver& ensureResolver()
     {
         if (!m_resolver) {
             createResolver();
         } else if (m_resolver->hasPendingAuthorStyleSheets()) {
             m_resolver->appendPendingAuthorStyleSheets();
         }
-        return m_resolver.get();
+        return *m_resolver.get();
     }
 
     bool hasResolver() const { return m_resolver.get(); }
     void clearResolver();
+    void clearMasterResolver();
 
-    CSSFontSelector* fontSelector();
+    CSSFontSelector* fontSelector() { return m_fontSelector.get(); }
+    void resetFontSelector();
+
     void didAttach();
     void didDetach();
     bool shouldClearResolver() const;
-    StyleResolverChange resolverChanged(StyleResolverUpdateMode);
+    StyleResolverChange resolverChanged(RecalcStyleTime, StyleResolverUpdateMode);
     unsigned resolverAccessCount() const;
 
+    void collectDocumentActiveStyleSheets(StyleSheetCollectionBase&);
+    void markDocumentDirty() { m_dirtyTreeScopes.markDocument(); }
+
 private:
     StyleEngine(Document&);
 
@@ -178,13 +184,20 @@
     bool shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode);
     void resolverThrowawayTimerFired(Timer<StyleEngine>*);
 
+    bool isMaster() const { return m_isMaster; }
+    Document* master();
+
     typedef ListHashSet<TreeScope*, 16> TreeScopeSet;
     static void insertTreeScopeInDocumentOrder(TreeScopeSet&, TreeScope*);
     void clearMediaQueryRuleSetOnTreeScopeStyleSheets(TreeScopeSet treeScopes);
 
     void createResolver();
 
+    void notifyPendingStyleSheetAdded();
+    void notifyPendingStyleSheetRemoved(RemovePendingSheetNotificationType);
+
     Document& m_document;
+    bool m_isMaster;
 
     // Track the number of currently loading top-level stylesheets needed for rendering.
     // Sheets loaded using the @import directive are not included in this count.
@@ -220,6 +233,8 @@
     unsigned m_lastResolverAccessCount;
     Timer<StyleEngine> m_resolverThrowawayTimer;
     OwnPtr<StyleResolver> m_resolver;
+
+    RefPtr<CSSFontSelector> m_fontSelector;
 };
 
 }
diff --git a/Source/core/dom/StyleSheetCollection.cpp b/Source/core/dom/StyleSheetCollection.cpp
index e2f3f3f..df49206 100644
--- a/Source/core/dom/StyleSheetCollection.cpp
+++ b/Source/core/dom/StyleSheetCollection.cpp
@@ -32,7 +32,6 @@
 #include "core/css/StyleRuleImport.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h"
-#include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/StyleEngine.h"
 #include "core/html/HTMLStyleElement.h"
@@ -175,10 +174,6 @@
 
 void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const StyleSheetCollectionBase& newCollection, StyleSheetChange& change)
 {
-    // No point in doing the analysis work if we're just going to recalc the whole document anyways.
-    if (document()->hasPendingForcedStyleRecalc())
-        return;
-
     if (activeLoadingStyleSheetLoaded(newCollection.activeAuthorStyleSheets()))
         return;
 
@@ -213,6 +208,12 @@
     // we need to recalc the whole document. It's wrong to use StyleInvalidationAnalysis since
     // it only looks at the addedSheets.
 
+    // No point in doing the analysis work if we're just going to recalc the whole document anyways.
+    // This needs to be done after the compareStyleSheets calls above to ensure we don't throw away
+    // the StyleResolver if we don't need to.
+    if (document()->hasPendingForcedStyleRecalc())
+        return;
+
     // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
     if (!document()->body() || document()->hasNodesWithPlaceholderStyle())
         return;
diff --git a/Source/core/dom/StyleTreeScopeTracker.cpp b/Source/core/dom/StyleTreeScopeTracker.cpp
index 87f56ac..9cbedc2 100644
--- a/Source/core/dom/StyleTreeScopeTracker.cpp
+++ b/Source/core/dom/StyleTreeScopeTracker.cpp
@@ -28,6 +28,8 @@
 #include "core/dom/StyleTreeScopeTracker.h"
 
 #include "core/dom/Document.h"
+#include "core/dom/StyleEngine.h" // FIXME: This dependency is unfortuante. Probably we should flatten this class again to StyleEngine.
+#include "core/html/HTMLImport.h"
 
 namespace WebCore {
 
@@ -37,6 +39,13 @@
 {
 }
 
+void StyleTreeScopeTracker::markDocument()
+{
+    m_isDocumentMarked = true;
+    if (!HTMLImport::isMaster(&m_document))
+        m_document.import()->master()->styleEngine()->markDocumentDirty();
+}
+
 void StyleTreeScopeTracker::mark(TreeScope& scope)
 {
     if (scope == m_document) {
diff --git a/Source/core/dom/StyleTreeScopeTracker.h b/Source/core/dom/StyleTreeScopeTracker.h
index 7dbd886..998226a 100644
--- a/Source/core/dom/StyleTreeScopeTracker.h
+++ b/Source/core/dom/StyleTreeScopeTracker.h
@@ -41,7 +41,7 @@
     explicit StyleTreeScopeTracker(Document&);
 
     void mark(TreeScope&);
-    void markDocument() { m_isDocumentMarked = true; }
+    void markDocument();
     bool isSubscopeMarked() const { return m_set.isEmpty(); }
     bool isDocumentMarked() const { return m_isDocumentMarked; }
     void clear();
diff --git a/Source/core/dom/TagNodeList.cpp b/Source/core/dom/TagNodeList.cpp
index b0e34f6..3944634 100644
--- a/Source/core/dom/TagNodeList.cpp
+++ b/Source/core/dom/TagNodeList.cpp
@@ -24,7 +24,6 @@
 #include "config.h"
 #include "core/dom/TagNodeList.h"
 
-#include "core/dom/Element.h"
 #include "core/dom/NodeRareData.h"
 #include "wtf/Assertions.h"
 
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index 6cbbeba..f43f6ec 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -23,7 +23,6 @@
 #include "core/dom/Text.h"
 
 #include "SVGNames.h"
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/css/resolver/StyleResolver.h"
@@ -108,7 +107,7 @@
     // IndexSizeError: Raised if the specified offset is negative or greater than
     // the number of 16-bit units in data.
     if (offset > length()) {
-        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("splitText", "Text", "The offset " + String::number(offset) + " is larger than the Text node's length."));
+        exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is larger than the Text node's length.");
         return 0;
     }
 
@@ -227,7 +226,7 @@
 
 String Text::nodeName() const
 {
-    return textAtom.string();
+    return "#text";
 }
 
 Node::NodeType Text::nodeType() const
@@ -315,7 +314,7 @@
 {
     if (RenderText* renderer = toRenderText(this->renderer())) {
         if (change != NoChange || needsStyleRecalc())
-            renderer->setStyle(document().styleResolver()->styleForText(this));
+            renderer->setStyle(document().ensureStyleResolver().styleForText(this));
         if (needsStyleRecalc())
             renderer->setText(dataImpl());
         clearNeedsStyleRecalc();
diff --git a/Source/core/dom/Text.h b/Source/core/dom/Text.h
index 603a018..79540c0 100644
--- a/Source/core/dom/Text.h
+++ b/Source/core/dom/Text.h
@@ -50,7 +50,7 @@
 
     void recalcTextStyle(StyleRecalcChange, Text* nextTextSibling);
     bool textRendererIsNeeded(const NodeRenderingContext&);
-    virtual RenderText* createTextRenderer(RenderStyle*);
+    RenderText* createTextRenderer(RenderStyle*);
     void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, RecalcStyleBehavior = DoNotRecalcStyle);
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
diff --git a/Source/core/dom/Text.idl b/Source/core/dom/Text.idl
index d6e2f18..57e6dc0 100644
--- a/Source/core/dom/Text.idl
+++ b/Source/core/dom/Text.idl
@@ -19,7 +19,7 @@
 [
     Constructor([Default=NullString] optional DOMString data),
     ConstructorCallWith=Document,
-    CustomWrap,
+    Custom=Wrap,
 ] interface Text : CharacterData {
 
     // DOM Level 1
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index c624f9d..3e0494c 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -49,7 +49,6 @@
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderView.h"
 #include "wtf/Vector.h"
-#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/TreeWalker.cpp b/Source/core/dom/TreeWalker.cpp
index 2d58281..fa09981 100644
--- a/Source/core/dom/TreeWalker.cpp
+++ b/Source/core/dom/TreeWalker.cpp
@@ -25,14 +25,11 @@
 #include "config.h"
 #include "core/dom/TreeWalker.h"
 
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ScriptState.h"
 #include "core/dom/ContainerNode.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/dom/NodeFilter.h"
 #include "core/dom/NodeTraversal.h"
-#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
@@ -46,7 +43,7 @@
 void TreeWalker::setCurrentNode(PassRefPtr<Node> node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("setCurrentNode", "TreeWalker", "The Node provided is invalid."));
+        exceptionState.throwDOMException(NotSupportedError, "The Node provided is invalid.");
         return;
     }
     m_current = node;
diff --git a/Source/core/dom/URL.idl b/Source/core/dom/URL.idl
index ff323dd..30c96c6 100644
--- a/Source/core/dom/URL.idl
+++ b/Source/core/dom/URL.idl
@@ -36,5 +36,5 @@
     [CallWith=ExecutionContext] static void revokeObjectURL(DOMString url);
 };
 
-// Force rebuild: crbug.com/307023
+// force rebuild: crbug.com/307023
 URL implements URLUtils;
diff --git a/Source/core/dom/URLUtils.idl b/Source/core/dom/URLUtils.idl
index b4c3e67..9cb7b48 100644
--- a/Source/core/dom/URLUtils.idl
+++ b/Source/core/dom/URLUtils.idl
@@ -27,9 +27,7 @@
     NoInterfaceObject,
     ImplementedAs=DOMURLUtils
 ] interface URLUtils {
-    // Special case null for backwards compat with HTMLAnchorElement href.
-    // https://code.google.com/p/chromium/issues/detail?id=304959
-    [TreatNullAs=NullString] attribute DOMString href;
+    attribute DOMString href;
 
     [NotEnumerable, ImplementedAs=href] DOMString toString();
 
diff --git a/Source/core/dom/custom/CustomElementCallbackScheduler.cpp b/Source/core/dom/custom/CustomElementCallbackScheduler.cpp
index 0b77e75..2d36478 100644
--- a/Source/core/dom/custom/CustomElementCallbackScheduler.cpp
+++ b/Source/core/dom/custom/CustomElementCallbackScheduler.cpp
@@ -33,7 +33,6 @@
 
 #include "core/dom/Element.h"
 #include "core/dom/custom/CustomElementCallbackDispatcher.h"
-#include "core/dom/custom/CustomElementCallbackQueue.h"
 #include "core/dom/custom/CustomElementLifecycleCallbacks.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/custom/CustomElementException.cpp b/Source/core/dom/custom/CustomElementException.cpp
index 78a01f1..331548a 100644
--- a/Source/core/dom/custom/CustomElementException.cpp
+++ b/Source/core/dom/custom/CustomElementException.cpp
@@ -38,22 +38,22 @@
 
 String CustomElementException::preamble(const AtomicString& type)
 {
-    return "Failed to call 'register' on 'Document' for type '" + type + "': ";
+    return "Registration failed for type '" + type + "'. ";
 }
 
 void CustomElementException::throwException(Reason reason, const AtomicString& type, ExceptionState& exceptionState)
 {
     switch (reason) {
     case CannotRegisterFromExtension:
-        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "elements cannot be registered from extensions.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "Elements cannot be registered from extensions.");
         return;
 
     case ConstructorPropertyNotConfigurable:
-        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "prototype constructor property is not configurable.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "Prototype constructor property is not configurable.");
         return;
 
     case ContextDestroyedCheckingPrototype:
-        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "the context is no longer valid.");
+        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "The context is no longer valid.");
         return;
 
     case ContextDestroyedCreatingCallbacks:
@@ -65,27 +65,27 @@
         return;
 
     case ExtendsIsInvalidName:
-        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is not a valid tag name.");
+        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + "The tag name specified in 'extends' is not a valid tag name.");
         return;
 
     case ExtendsIsCustomElementName:
-        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is a custom element name. Use inheritance instead.");
+        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + "The tag name specified in 'extends' is a custom element name. Use inheritance instead.");
         return;
 
     case InvalidName:
-        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + ": '" + type + "' is not a valid name.");
+        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + "The type name is invalid.");
         return;
 
     case PrototypeInUse:
-        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "prototype is already in-use as an interface prototype object.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "The prototype is already in-use as an interface prototype object.");
         return;
 
     case PrototypeNotAnObject:
-        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "the prototype option is not an object.");
+        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "The prototype option is not an object.");
         return;
 
     case TypeAlreadyRegistered:
-        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "a type with that name is already registered.");
+        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "A type with that name is already registered.");
         return;
     }
 
diff --git a/Source/core/dom/custom/CustomElementRegistry.cpp b/Source/core/dom/custom/CustomElementRegistry.cpp
index cbbbf64..b4bd666 100644
--- a/Source/core/dom/custom/CustomElementRegistry.cpp
+++ b/Source/core/dom/custom/CustomElementRegistry.cpp
@@ -35,8 +35,6 @@
 #include "SVGNames.h"
 #include "bindings/v8/CustomElementConstructorBuilder.h"
 #include "core/dom/DocumentLifecycleObserver.h"
-#include "core/dom/custom/CustomElement.h"
-#include "core/dom/custom/CustomElementDefinition.h"
 #include "core/dom/custom/CustomElementException.h"
 #include "core/dom/custom/CustomElementRegistrationContext.h"
 
diff --git a/Source/core/dom/shadow/ComposedTreeWalker.cpp b/Source/core/dom/shadow/ComposedTreeWalker.cpp
index 0b9dc04..2a15612 100644
--- a/Source/core/dom/shadow/ComposedTreeWalker.cpp
+++ b/Source/core/dom/shadow/ComposedTreeWalker.cpp
@@ -30,7 +30,6 @@
 
 #include "core/dom/Element.h"
 #include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/InsertionPoint.h"
 #include "core/html/shadow/HTMLContentElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 
diff --git a/Source/core/dom/shadow/ComposedTreeWalker.h b/Source/core/dom/shadow/ComposedTreeWalker.h
index 0b1b4f0..b750e34 100644
--- a/Source/core/dom/shadow/ComposedTreeWalker.h
+++ b/Source/core/dom/shadow/ComposedTreeWalker.h
@@ -115,7 +115,6 @@
 inline ComposedTreeWalker::ComposedTreeWalker(const Node* node, StartPolicy startPolicy)
     : m_node(node)
 {
-    UNUSED_PARAM(startPolicy);
 #ifndef NDEBUG
     if (m_node && startPolicy == CannotStartFromShadowBoundary)
         assertPrecondition();
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index c4c7a68..913bb93 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -31,8 +31,6 @@
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/shadow/ContentDistribution.h"
-#include "core/dom/shadow/InsertionPoint.h"
-#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/shadow/HTMLContentElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
index f671b91..e3c5d4d 100644
--- a/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -36,7 +36,6 @@
 #include "core/dom/QualifiedName.h"
 #include "core/dom/StaticNodeList.h"
 #include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/shadow/HTMLContentElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index 58d6823..c9f7909 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -27,7 +27,6 @@
 #include "config.h"
 #include "core/dom/shadow/ShadowRoot.h"
 
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/css/StyleSheetList.h"
 #include "core/css/resolver/StyleResolver.h"
@@ -128,7 +127,7 @@
 
 PassRefPtr<Node> ShadowRoot::cloneNode(bool, ExceptionState& exceptionState)
 {
-    exceptionState.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("cloneNode", "ShadowRoot", "ShadowRoot nodes are not clonable."));
+    exceptionState.throwDOMException(DataCloneError, "ShadowRoot nodes are not clonable.");
     return 0;
 }
 
@@ -140,7 +139,7 @@
 void ShadowRoot::setInnerHTML(const String& markup, ExceptionState& exceptionState)
 {
     if (isOrphan()) {
-        exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("setInnerHTML", "ShadowRoot", "The ShadowRoot does not have a host."));
+        exceptionState.throwDOMException(InvalidAccessError, "The ShadowRoot does not have a host.");
         return;
     }
 
@@ -167,8 +166,8 @@
     // ShadowRoot doesn't support custom callbacks.
     ASSERT(!hasCustomStyleCallbacks());
 
-    StyleResolver* styleResolver = document().styleResolver();
-    styleResolver->pushParentShadowRoot(*this);
+    StyleResolver& styleResolver = document().ensureStyleResolver();
+    styleResolver.pushParentShadowRoot(*this);
 
     if (styleChangeType() >= SubtreeStyleChange)
         change = Force;
@@ -190,7 +189,7 @@
         }
     }
 
-    styleResolver->popParentShadowRoot(*this);
+    styleResolver.popParentShadowRoot(*this);
 
     clearChildNeedsStyleRecalc();
 }
@@ -246,10 +245,10 @@
 
 void ShadowRoot::attach(const AttachContext& context)
 {
-    StyleResolver* styleResolver = document().styleResolver();
-    styleResolver->pushParentShadowRoot(*this);
+    StyleResolver& styleResolver = document().ensureStyleResolver();
+    styleResolver.pushParentShadowRoot(*this);
     DocumentFragment::attach(context);
-    styleResolver->popParentShadowRoot(*this);
+    styleResolver.popParentShadowRoot(*this);
 }
 
 Node::InsertionNotificationRequest ShadowRoot::insertedInto(ContainerNode* insertionPoint)