Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / dom / Document.cpp
index ddbf569..be81d14 100644 (file)
 #include "config.h"
 #include "core/dom/Document.h"
 
-#include "HTMLElementFactory.h"
-#include "HTMLNames.h"
-#include "RuntimeEnabledFeatures.h"
-#include "SVGElementFactory.h"
-#include "SVGNames.h"
-#include "XMLNSNames.h"
-#include "XMLNames.h"
-#include "bindings/v8/CustomElementConstructorBuilder.h"
-#include "bindings/v8/Dictionary.h"
-#include "bindings/v8/ExceptionMessages.h"
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "bindings/v8/ScriptController.h"
+#include "bindings/core/v8/CustomElementConstructorBuilder.h"
+#include "bindings/core/v8/DOMDataStore.h"
+#include "bindings/core/v8/Dictionary.h"
+#include "bindings/core/v8/ExceptionMessages.h"
+#include "bindings/core/v8/ExceptionState.h"
+#include "bindings/core/v8/ExceptionStatePlaceholder.h"
+#include "bindings/core/v8/ScriptController.h"
+#include "bindings/core/v8/V8DOMWrapper.h"
+#include "bindings/core/v8/WindowProxy.h"
+#include "core/HTMLElementFactory.h"
+#include "core/HTMLNames.h"
+#include "core/SVGElementFactory.h"
+#include "core/SVGNames.h"
+#include "core/XMLNSNames.h"
+#include "core/XMLNames.h"
 #include "core/accessibility/AXObjectCache.h"
-#include "core/animation/AnimationClock.h"
-#include "core/animation/DocumentTimeline.h"
-#include "core/animation/css/TransitionTimeline.h"
-#include "core/css/CSSDefaultStyleSheets.h"
+#include "core/animation/AnimationTimeline.h"
+#include "core/animation/DocumentAnimations.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSStyleDeclaration.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/StyleSheetList.h"
+#include "core/css/invalidation/StyleInvalidator.h"
+#include "core/css/parser/CSSParser.h"
 #include "core/css/resolver/FontBuilder.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/css/resolver/StyleResolverStats.h"
 #include "core/dom/AddConsoleMessageTask.h"
 #include "core/dom/Attr.h"
 #include "core/dom/CDATASection.h"
 #include "core/dom/Comment.h"
 #include "core/dom/ContextFeatures.h"
 #include "core/dom/DOMImplementation.h"
-#include "core/dom/DOMNamedFlowCollection.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/DocumentLifecycleNotifier.h"
 #include "core/dom/DocumentLifecycleObserver.h"
 #include "core/dom/DocumentMarkerController.h"
-#include "core/dom/DocumentSharedObjectPool.h"
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementDataCache.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExecutionContextTask.h"
-#include "core/dom/NamedFlowCollection.h"
+#include "core/dom/MainThreadTaskRunner.h"
+#include "core/dom/MutationObserver.h"
 #include "core/dom/NodeChildRemovalTracker.h"
 #include "core/dom/NodeFilter.h"
 #include "core/dom/NodeIterator.h"
 #include "core/dom/NodeRenderingTraversal.h"
 #include "core/dom/NodeTraversal.h"
 #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"
 #include "core/dom/SelectorQuery.h"
+#include "core/dom/StaticNodeList.h"
 #include "core/dom/StyleEngine.h"
 #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/XMLDocument.h"
+#include "core/dom/custom/CustomElementMicrotaskRunQueue.h"
 #include "core/dom/custom/CustomElementRegistrationContext.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
+#include "core/editing/SpellChecker.h"
+#include "core/editing/markup.h"
 #include "core/events/BeforeUnloadEvent.h"
 #include "core/events/Event.h"
 #include "core/events/EventFactory.h"
 #include "core/events/HashChangeEvent.h"
 #include "core/events/PageTransitionEvent.h"
 #include "core/events/ScopedEventQueue.h"
-#include "core/events/ThreadLocalEventNames.h"
 #include "core/fetch/ResourceFetcher.h"
-#include "core/fetch/TextResourceDecoder.h"
-#include "core/frame/ContentSecurityPolicy.h"
-#include "core/frame/DOMSecurityPolicy.h"
-#include "core/frame/DOMWindow.h"
-#include "core/frame/Frame.h"
+#include "core/frame/EventHandlerRegistry.h"
+#include "core/frame/FrameConsole.h"
+#include "core/frame/FrameHost.h"
 #include "core/frame/FrameView.h"
 #include "core/frame/History.h"
-#include "core/frame/animation/AnimationController.h"
+#include "core/frame/LocalDOMWindow.h"
+#include "core/frame/LocalFrame.h"
+#include "core/frame/Settings.h"
+#include "core/frame/csp/ContentSecurityPolicy.h"
+#include "core/html/DocumentNameCollection.h"
 #include "core/html/HTMLAllCollection.h"
 #include "core/html/HTMLAnchorElement.h"
+#include "core/html/HTMLBaseElement.h"
 #include "core/html/HTMLCanvasElement.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLDialogElement.h"
 #include "core/html/HTMLHeadElement.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLIFrameElement.h"
-#include "core/html/HTMLImport.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLLinkElement.h"
-#include "core/html/HTMLNameCollection.h"
+#include "core/html/HTMLMetaElement.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/HTMLStyleElement.h"
+#include "core/html/HTMLTemplateElement.h"
 #include "core/html/HTMLTitleElement.h"
 #include "core/html/PluginDocument.h"
+#include "core/html/WindowNameCollection.h"
+#include "core/html/canvas/CanvasRenderingContext.h"
+#include "core/html/canvas/CanvasRenderingContext2D.h"
+#include "core/html/canvas/WebGLRenderingContext.h"
 #include "core/html/forms/FormController.h"
+#include "core/html/imports/HTMLImportLoader.h"
+#include "core/html/imports/HTMLImportsController.h"
 #include "core/html/parser/HTMLDocumentParser.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/NestingLevelIncrementer.h"
+#include "core/html/parser/TextResourceDecoder.h"
+#include "core/inspector/ConsoleMessage.h"
 #include "core/inspector/InspectorCounters.h"
 #include "core/inspector/InspectorInstrumentation.h"
+#include "core/inspector/InspectorTraceEvents.h"
 #include "core/inspector/ScriptCallStack.h"
 #include "core/loader/CookieJar.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/EventHandler.h"
+#include "core/page/EventWithHitTestResults.h"
+#include "core/page/FocusController.h"
 #include "core/page/FrameTree.h"
-#include "core/page/MouseEventWithHitTestResults.h"
 #include "core/page/Page.h"
-#include "core/page/PageConsole.h"
 #include "core/page/PointerLockController.h"
-#include "core/page/Settings.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
 #include "core/rendering/TextAutosizer.h"
+#include "core/rendering/compositing/RenderLayerCompositor.h"
 #include "core/svg/SVGDocumentExtensions.h"
-#include "core/svg/SVGStyleElement.h"
+#include "core/svg/SVGFontFaceElement.h"
+#include "core/svg/SVGTitleElement.h"
+#include "core/svg/SVGUseElement.h"
+#include "core/workers/SharedWorkerRepositoryClient.h"
 #include "core/xml/XSLTProcessor.h"
 #include "core/xml/parser/XMLDocumentParser.h"
 #include "platform/DateComponents.h"
+#include "platform/EventDispatchForbiddenScope.h"
 #include "platform/Language.h"
-#include "platform/Timer.h"
+#include "platform/Logging.h"
+#include "platform/RuntimeEnabledFeatures.h"
+#include "platform/ScriptForbiddenScope.h"
 #include "platform/TraceEvent.h"
+#include "platform/network/ContentSecurityPolicyParsers.h"
 #include "platform/network/HTTPParsers.h"
+#include "platform/scroll/ScrollbarTheme.h"
 #include "platform/text/PlatformLocale.h"
 #include "platform/text/SegmentedString.h"
-#include "weborigin/OriginAccessEntry.h"
-#include "weborigin/SchemeRegistry.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/OriginAccessEntry.h"
+#include "platform/weborigin/SchemeRegistry.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "public/platform/Platform.h"
 #include "wtf/CurrentTime.h"
+#include "wtf/DateMath.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"
 
-using namespace std;
 using namespace WTF;
 using namespace Unicode;
 
-namespace WebCore {
+namespace blink {
 
 using namespace HTMLNames;
 
@@ -285,7 +306,7 @@ static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
     // Note: We generalize this to all "blank" URLs and invalid URLs because we
     // treat all of these URLs as about:blank.
     //
-    return url.isEmpty() || url.isBlankURL();
+    return url.isEmpty() || url.protocolIsAbout();
 }
 
 static Widget* widgetForElement(const Element& focusedElement)
@@ -298,12 +319,12 @@ static Widget* widgetForElement(const Element& focusedElement)
 
 static bool acceptsEditingFocus(const Element& element)
 {
-    ASSERT(element.rendererIsEditable());
+    ASSERT(element.hasEditableStyle());
 
     return element.document().frame() && element.rootEditableElement();
 }
 
-static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame* targetFrame)
+static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, const Frame* targetFrame)
 {
     // targetFrame can be 0 when we're trying to navigate a top-level frame
     // that has a 0 opener.
@@ -311,8 +332,13 @@ static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame*
         return false;
 
     const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
-    for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
-        Document* ancestorDocument = ancestorFrame->document();
+    for (const Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
+        // FIXME: SecurityOrigins need to be refactored to work with out-of-process iframes.
+        // For now we prevent navigation between cross-process frames.
+        if (!ancestorFrame->isLocalFrame())
+            return false;
+
+        Document* ancestorDocument = toLocalFrame(ancestorFrame)->document();
         // FIXME: Should be an ASSERT? Frames should alway have documents.
         if (!ancestorDocument)
             return true;
@@ -331,7 +357,7 @@ static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame*
     return false;
 }
 
-static void printNavigationErrorMessage(const Frame& frame, const KURL& activeURL, const char* reason)
+static void printNavigationErrorMessage(const LocalFrame& frame, const KURL& activeURL, const char* reason)
 {
     String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
 
@@ -341,51 +367,85 @@ static void printNavigationErrorMessage(const Frame& frame, const KURL& activeUR
 
 uint64_t Document::s_globalTreeVersion = 0;
 
-// This class should be passed only to Document::postTask.
-class CheckFocusedElementTask FINAL : public ExecutionContextTask {
+#ifndef NDEBUG
+typedef WillBeHeapHashSet<RawPtrWillBeWeakMember<Document> > WeakDocumentSet;
+static WeakDocumentSet& liveDocumentSet()
+{
+    DEFINE_STATIC_LOCAL(OwnPtrWillBePersistent<WeakDocumentSet>, set, (adoptPtrWillBeNoop(new WeakDocumentSet())));
+    return *set;
+}
+#endif
+
+// This class doesn't work with non-Document ExecutionContext.
+class AutofocusTask FINAL : public ExecutionContextTask {
 public:
-    static PassOwnPtr<CheckFocusedElementTask> create()
+    static PassOwnPtr<AutofocusTask> create()
     {
-        return adoptPtr(new CheckFocusedElementTask());
+        return adoptPtr(new AutofocusTask());
     }
-    virtual ~CheckFocusedElementTask() { }
+    virtual ~AutofocusTask() { }
 
 private:
-    CheckFocusedElementTask() { }
+    AutofocusTask() { }
     virtual void performTask(ExecutionContext* context) OVERRIDE
     {
-        ASSERT(context->isDocument());
         Document* document = toDocument(context);
-        document->didRunCheckFocusedElementTask();
-        Element* element = document->focusedElement();
-        if (!element)
-            return;
-        if (document->childNeedsStyleRecalc()) {
-            document->setNeedsFocusedElementCheck();
-            return;
+        if (RefPtrWillBeRawPtr<Element> element = document->autofocusElement()) {
+            document->setAutofocusElement(0);
+            element->focus();
         }
-        if (element->renderer() && element->renderer()->needsLayout())
-            return;
-        if (!element->isFocusable())
-            document->setFocusedElement(0);
     }
 };
 
+DocumentVisibilityObserver::DocumentVisibilityObserver(Document& document)
+    : m_document(nullptr)
+{
+    registerObserver(document);
+}
+
+DocumentVisibilityObserver::~DocumentVisibilityObserver()
+{
+#if !ENABLE(OILPAN)
+    unregisterObserver();
+#endif
+}
+
+void DocumentVisibilityObserver::trace(Visitor* visitor)
+{
+    visitor->trace(m_document);
+}
+
+void DocumentVisibilityObserver::unregisterObserver()
+{
+    if (m_document) {
+        m_document->unregisterVisibilityObserver(this);
+        m_document = nullptr;
+    }
+}
+
+void DocumentVisibilityObserver::registerObserver(Document& document)
+{
+    ASSERT(!m_document);
+    m_document = &document;
+    if (m_document)
+        m_document->registerVisibilityObserver(this);
+}
+
+void DocumentVisibilityObserver::setObservedDocument(Document& document)
+{
+    unregisterObserver();
+    registerObserver(document);
+}
+
 Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
     : ContainerNode(0, CreateDocument)
-    , TreeScope(this)
-    , m_styleResolverThrowawayTimer(this, &Document::styleResolverThrowawayTimerFired)
-    , m_styleResolverAccessCount(0)
-    , m_lastStyleResolverAccessCount(0)
-    , m_didCalculateStyleResolver(false)
+    , TreeScope(*this)
     , m_hasNodesWithPlaceholderStyle(false)
-    , m_needsNotifyRemoveAllPendingStylesheet(false)
-    , m_ignorePendingStylesheets(false)
     , m_evaluateMediaQueriesOnStyleRecalc(false)
     , m_pendingSheetLayout(NoLayoutWithPendingSheets)
     , m_frame(initializer.frame())
     , m_domWindow(m_frame ? m_frame->domWindow() : 0)
-    , m_import(initializer.import())
+    , m_importsController(initializer.importsController())
     , m_activeParserCount(0)
     , m_contextFeatures(ContextFeatures::defaultSwitch())
     , m_wellFormed(false)
@@ -393,29 +453,26 @@ Document::Document(const DocumentInit& initializer, DocumentClassFlags documentC
     , m_paginatedForScreen(false)
     , m_compatibilityMode(NoQuirksMode)
     , m_compatibilityModeLocked(false)
-    , m_didPostCheckFocusedElementTask(false)
+    , m_executeScriptsWaitingForResourcesTimer(this, &Document::executeScriptsWaitingForResourcesTimerFired)
+    , m_hasAutofocused(false)
+    , m_clearFocusedElementTimer(this, &Document::clearFocusedElementTimerFired)
     , 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)
-    , m_bParsing(false)
-    , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
-    , m_inStyleRecalc(false)
+    , m_isParsing(false)
     , m_gotoAnchorNeededAfterStylesheetsLoad(false)
     , m_containsValidityStyleRules(false)
     , m_updateFocusAppearanceRestoresSelection(false)
     , m_containsPlugins(false)
     , m_ignoreDestructiveWriteCount(0)
-    , m_titleSetExplicitly(false)
-    , m_markers(adoptPtr(new DocumentMarkerController))
+    , m_markers(adoptPtrWillBeNoop(new DocumentMarkerController))
     , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
-    , m_cssTarget(0)
+    , m_cssTarget(nullptr)
     , m_loadEventProgress(LoadEventNotRun)
     , m_startTime(currentTime())
-    , m_overMinimumLayoutThreshold(false)
     , m_scriptRunner(ScriptRunner::create(this))
     , m_xmlVersion("1.0")
     , m_xmlStandalone(StandaloneUnspecified)
@@ -429,41 +486,36 @@ Document::Document(const DocumentInit& initializer, DocumentClassFlags documentC
     , m_sawElementsInKnownNamespaces(false)
     , m_isSrcdocDocument(false)
     , m_isMobileDocument(false)
-    , m_mayDisplaySeamlesslyWithParent(false)
+    , m_isTransitionDocument(false)
     , m_renderView(0)
+#if !ENABLE(OILPAN)
     , m_weakFactory(this)
+#endif
     , m_contextDocument(initializer.contextDocument())
-    , m_idAttributeName(idAttr)
-    , m_hasFullscreenElementStack(false)
+    , m_hasFullscreenSupplement(false)
     , m_loadEventDelayCount(0)
     , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
+    , m_pluginLoadingTimer(this, &Document::pluginLoadingTimerFired)
+    , m_didSetReferrerPolicy(false)
     , m_referrerPolicy(ReferrerPolicyDefault)
     , m_directionSetOnDocumentElement(false)
     , m_writingModeSetOnDocumentElement(false)
     , m_writeRecursionIsTooDeep(false)
     , m_writeRecursionDepth(0)
-    , m_lastHandledUserGestureTimestamp(0)
-    , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
-    , m_textAutosizer(TextAutosizer::create(this))
+    , m_taskRunner(MainThreadTaskRunner::create(this))
     , m_registrationContext(initializer.registrationContext(this))
-    , m_scheduledTasksAreSuspended(false)
-    , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
-#ifndef NDEBUG
-    , m_didDispatchViewportPropertiesChanged(false)
-#endif
-    , m_animationClock(AnimationClock::create())
-    , m_timeline(DocumentTimeline::create(this))
-    , m_transitionTimeline(TransitionTimeline::create(this))
-    , m_templateDocumentHost(0)
+    , m_elementDataCacheClearTimer(this, &Document::elementDataCacheClearTimerFired)
+    , m_timeline(AnimationTimeline::create(this))
+    , m_templateDocumentHost(nullptr)
     , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
+    , m_hasViewportUnits(false)
+    , m_styleRecalcElementCounter(0)
 {
-    setClient(this);
-    ScriptWrappable::init(this);
-
     if (m_frame) {
-        provideContextFeaturesToDocumentFrom(this, m_frame->page());
+        ASSERT(m_frame->page());
+        provideContextFeaturesToDocumentFrom(*this, *m_frame->page());
 
-        m_fetcher = m_frame->loader().activeDocumentLoader()->fetcher();
+        m_fetcher = m_frame->loader().documentLoader()->fetcher();
     }
 
     if (!m_fetcher)
@@ -481,30 +533,48 @@ Document::Document(const DocumentInit& initializer, DocumentClassFlags documentC
     initSecurityContext(initializer);
     initDNSPrefetch();
 
-    for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
+#if !ENABLE(OILPAN)
+    for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); ++i)
         m_nodeListCounts[i] = 0;
+#endif
 
     InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
 
-    m_lifecyle.advanceTo(DocumentLifecycle::Inactive);
+    m_lifecycle.advanceTo(DocumentLifecycle::Inactive);
+
+    // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
+    // CSSFontSelector, need to initialize m_styleEngine after initializing
+    // m_fetcher.
+    m_styleEngine = StyleEngine::create(*this);
+
+#ifndef NDEBUG
+    liveDocumentSet().add(this);
+#endif
 }
 
 Document::~Document()
 {
     ASSERT(!renderView());
+    ASSERT(!parentTreeScope());
+#if !ENABLE(OILPAN)
     ASSERT(m_ranges.isEmpty());
-    ASSERT(!m_parentTreeScope);
     ASSERT(!hasGuardRefCount());
+    // With Oilpan, either the document outlives the visibility observers
+    // or the visibility observers and the document die in the same GC round.
+    // When they die in the same GC round, the list of visibility observers
+    // will not be empty on Document destruction.
+    ASSERT(m_visibilityObservers.isEmpty());
 
     if (m_templateDocument)
-        m_templateDocument->setTemplateDocumentHost(0); // balanced in templateDocument().
-
-    if (Document* ownerDocument = this->ownerDocument())
-        ownerDocument->didRemoveEventTargetNode(this);
+        m_templateDocument->m_templateDocumentHost = nullptr; // balanced in ensureTemplateDocument().
 
     m_scriptRunner.clear();
 
-    removeAllEventListeners();
+    // FIXME: Oilpan: Not removing event listeners here also means that we do
+    // not notify the inspector instrumentation that the event listeners are
+    // gone. The Document and all the nodes in the document are gone, so maybe
+    // that is OK?
+    removeAllEventListenersRecursively();
 
     // Currently we believe that Document can never outlive the parser.
     // Although the Document may be replaced synchronously, DocumentParsers
@@ -514,31 +584,31 @@ Document::~Document()
     // if the DocumentParser outlives the Document it won't cause badness.
     ASSERT(!m_parser || m_parser->refCount() == 1);
     detachParser();
+#endif
 
-    if (this == topDocument())
+    if (this == &axObjectCacheOwner())
         clearAXObjectCache();
 
-    setDecoder(PassRefPtr<TextResourceDecoder>());
-
+#if !ENABLE(OILPAN)
     if (m_styleSheetList)
         m_styleSheetList->detachFromDocument();
 
-    if (m_import) {
-        m_import->wasDetachedFromDocument();
-        m_import = 0;
-    }
+    if (m_importsController)
+        HTMLImportsController::removeFrom(*this);
 
-    m_styleEngine.clear();
+    m_timeline->detachFromDocument();
+
+    // We need to destroy CSSFontSelector before destroying m_fetcher.
+    if (m_styleEngine)
+        m_styleEngine->detachFromDocument();
 
     if (m_elemSheet)
         m_elemSheet->clearOwnerNode();
 
-    clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_fetcher.
-
     // It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
     // load the initial empty document and the SVGDocument with the same DocumentLoader).
     if (m_fetcher->document() == this)
-        m_fetcher->setDocument(0);
+        m_fetcher->setDocument(nullptr);
     m_fetcher.clear();
 
     // We must call clearRareData() here since a Document class inherits TreeScope
@@ -546,28 +616,32 @@ Document::~Document()
     if (hasRareData())
         clearRareData();
 
-    ASSERT(!m_listsInvalidatedAtDocument.size());
+    ASSERT(m_listsInvalidatedAtDocument.isEmpty());
 
-    for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
+    for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); ++i)
         ASSERT(!m_nodeListCounts[i]);
 
-    clearDocumentScope();
-    setClient(0);
+#ifndef NDEBUG
+    liveDocumentSet().remove(this);
+#endif
+#endif
 
     InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
 }
 
+#if !ENABLE(OILPAN)
 void Document::dispose()
 {
     ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
+
     // We must make sure not to be retaining any of our children through
     // these extra pointers or we will create a reference cycle.
-    m_docType = 0;
-    m_focusedElement = 0;
-    m_hoverNode = 0;
-    m_activeElement = 0;
-    m_titleElement = 0;
-    m_documentElement = 0;
+    m_docType = nullptr;
+    m_focusedElement = nullptr;
+    m_hoverNode = nullptr;
+    m_activeHoverElement = nullptr;
+    m_titleElement = nullptr;
+    m_documentElement = nullptr;
     m_contextFeatures = ContextFeatures::defaultSwitch();
     m_userActionElements.documentDidRemoveLastRef();
     m_associatedFormControls.clear();
@@ -576,19 +650,19 @@ void Document::dispose()
 
     m_registrationContext.clear();
 
-    if (m_import) {
-        m_import->wasDetachedFromDocument();
-        m_import = 0;
-    }
+    if (m_importsController)
+        HTMLImportsController::removeFrom(*this);
 
     // removeDetachedChildren() doesn't always unregister IDs,
     // so tear down scope information upfront to avoid having stale references in the map.
     destroyTreeScopeData();
+
     removeDetachedChildren();
+
     // removeDetachedChildren() can access FormController.
     m_formController.clear();
 
-    m_markers->detach();
+    m_markers->clear();
 
     m_cssCanvasElements.clear();
 
@@ -598,11 +672,12 @@ void Document::dispose()
     m_scriptedAnimationController.clear();
 
     if (svgExtensions())
-        accessSVGExtensions()->pauseAnimations();
+        accessSVGExtensions().pauseAnimations();
 
-    m_lifecyle.advanceTo(DocumentLifecycle::Disposed);
+    m_lifecycle.advanceTo(DocumentLifecycle::Disposed);
     lifecycleNotifier().notifyDocumentWasDisposed();
 }
+#endif
 
 SelectorQueryCache& Document::selectorQueryCache()
 {
@@ -614,10 +689,16 @@ SelectorQueryCache& Document::selectorQueryCache()
 MediaQueryMatcher& Document::mediaQueryMatcher()
 {
     if (!m_mediaQueryMatcher)
-        m_mediaQueryMatcher = MediaQueryMatcher::create(this);
+        m_mediaQueryMatcher = MediaQueryMatcher::create(*this);
     return *m_mediaQueryMatcher;
 }
 
+void Document::mediaQueryAffectingValueChanged()
+{
+    m_evaluateMediaQueriesOnStyleRecalc = true;
+    styleEngine()->clearMediaQueryRuleSetStyleSheets();
+}
+
 void Document::setCompatibilityMode(CompatibilityMode mode)
 {
     if (m_compatibilityModeLocked || mode == m_compatibilityMode)
@@ -626,9 +707,8 @@ void Document::setCompatibilityMode(CompatibilityMode mode)
     m_compatibilityMode = mode;
     selectorQueryCache().invalidate();
     if (inQuirksMode() != wasInQuirksMode) {
-        // All user stylesheets have to reparse using the different mode.
-        m_styleEngine->clearPageUserSheet();
-        m_styleEngine->invalidateInjectedStyleSheetCache();
+        // All injected stylesheets have to reparse using the different mode.
+        m_styleEngine->compatibilityModeChanged();
     }
 }
 
@@ -637,7 +717,7 @@ String Document::compatMode() const
     return inQuirksMode() ? "BackCompat" : "CSS1Compat";
 }
 
-void Document::setDoctype(PassRefPtr<DocumentType> docType)
+void Document::setDoctype(PassRefPtrWillBeRawPtr<DocumentType> docType)
 {
     // This should never be called more than once.
     ASSERT(!m_docType || !docType);
@@ -651,16 +731,16 @@ void Document::setDoctype(PassRefPtr<DocumentType> docType)
     clearStyleResolver();
 }
 
-DOMImplementation* Document::implementation()
+DOMImplementation& Document::implementation()
 {
     if (!m_implementation)
-        m_implementation = DOMImplementation::create(this);
-    return m_implementation.get();
+        m_implementation = DOMImplementation::create(*this);
+    return *m_implementation;
 }
 
-bool Document::hasManifest() const
+bool Document::hasAppCacheManifest() const
 {
-    return documentElement() && isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
+    return isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
 }
 
 Location* Document::location() const
@@ -668,280 +748,314 @@ Location* Document::location() const
     if (!frame())
         return 0;
 
-    return domWindow()->location();
+    return &domWindow()->location();
 }
 
-void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
+void Document::childrenChanged(const ChildrenChange& change)
 {
-    ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
+    ContainerNode::childrenChanged(change);
+    m_documentElement = ElementTraversal::firstWithin(*this);
+}
 
-    Element* newDocumentElement = ElementTraversal::firstWithin(this);
-    if (newDocumentElement == m_documentElement)
-        return;
-    m_documentElement = newDocumentElement;
-    // The root style used for media query matching depends on the document element.
-    clearStyleResolver();
+AtomicString Document::convertLocalName(const AtomicString& name)
+{
+    return isHTMLDocument() ? name.lower() : name;
 }
 
-PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& es)
+PassRefPtrWillBeRawPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
 {
     if (!isValidName(name)) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
-        return 0;
+        exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
+        return nullptr;
     }
 
     if (isXHTMLDocument() || isHTMLDocument())
-        return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, isHTMLDocument() ? name.lower() : name, xhtmlNamespaceURI), this, 0, false);
+        return HTMLElementFactory::createHTMLElement(convertLocalName(name), *this, 0, false);
 
-    return createElement(QualifiedName(nullAtom, name, nullAtom), false);
+    return Element::create(QualifiedName(nullAtom, name, nullAtom), this);
 }
 
-PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& es)
+PassRefPtrWillBeRawPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
 {
     if (!isValidName(localName)) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
-        return 0;
+        exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + localName + "') is not a valid name.");
+        return nullptr;
     }
 
-    RefPtr<Element> element;
+    RefPtrWillBeRawPtr<Element> element;
 
-    if (RuntimeEnabledFeatures::customElementsEnabled() && CustomElement::isValidName(localName) && registrationContext())
-        element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
-    else
-        element = createElement(localName, es);
+    if (CustomElement::isValidName(localName) && registrationContext()) {
+        element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, convertLocalName(localName), xhtmlNamespaceURI));
+    } else {
+        element = createElement(localName, exceptionState);
+        if (exceptionState.hadException())
+            return nullptr;
+    }
 
-    if (RuntimeEnabledFeatures::customElementsEnabled() && !typeExtension.isNull() && !typeExtension.isEmpty())
+    if (!typeExtension.isEmpty())
         CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
 
-    return element;
+    return element.release();
 }
 
-PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionState& es)
+static inline QualifiedName createQualifiedName(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
 {
-    String prefix, localName;
-    if (!parseQualifiedName(qualifiedName, prefix, localName, es))
-        return 0;
+    AtomicString prefix, localName;
+    if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
+        return QualifiedName::null();
 
     QualifiedName qName(prefix, localName, namespaceURI);
-    if (!hasValidNamespaceForElements(qName)) {
-        es.throwUninformativeAndGenericDOMException(NamespaceError);
-        return 0;
+    if (!Document::hasValidNamespaceForElements(qName)) {
+        exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
+        return QualifiedName::null();
     }
 
-    RefPtr<Element> element;
+    return qName;
+}
+
+PassRefPtrWillBeRawPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
+{
+    QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
+    if (qName == QualifiedName::null())
+        return nullptr;
+
+    return createElement(qName, false);
+}
+
+PassRefPtrWillBeRawPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
+{
+    QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
+    if (qName == QualifiedName::null())
+        return nullptr;
+
+    RefPtrWillBeRawPtr<Element> element;
     if (CustomElement::isValidName(qName.localName()) && registrationContext())
         element = registrationContext()->createCustomTagElement(*this, qName);
     else
-        element = createElementNS(namespaceURI, qualifiedName, es);
+        element = createElement(qName, false);
 
-    if (!typeExtension.isNull() && !typeExtension.isEmpty())
+    if (!typeExtension.isEmpty())
         CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
 
-    return element;
+    return element.release();
 }
 
-ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, ExceptionState& es)
+ScriptValue Document::registerElement(ScriptState* scriptState, const AtomicString& name, ExceptionState& exceptionState)
 {
-    return registerElement(state, name, Dictionary(), es);
+    return registerElement(scriptState, name, Dictionary(), exceptionState);
 }
 
-ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& es, CustomElement::NameSet validNames)
+ScriptValue Document::registerElement(ScriptState* scriptState, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
 {
     if (!registrationContext()) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "No element registration context is available.");
         return ScriptValue();
     }
 
-    CustomElementConstructorBuilder constructorBuilder(state, &options);
-    registrationContext()->registerElement(this, &constructorBuilder, name, validNames, es);
+    CustomElementConstructorBuilder constructorBuilder(scriptState, &options);
+    registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
     return constructorBuilder.bindingsReturnValue();
 }
 
-void Document::setImport(HTMLImport* import)
+CustomElementMicrotaskRunQueue* Document::customElementMicrotaskRunQueue()
 {
-    ASSERT(!m_import || !import);
-    m_import = import;
+    if (!m_customElementMicrotaskRunQueue)
+        m_customElementMicrotaskRunQueue = CustomElementMicrotaskRunQueue::create();
+    return m_customElementMicrotaskRunQueue.get();
 }
 
-void Document::didLoadAllImports()
+void Document::setImportsController(HTMLImportsController* controller)
 {
-    executeScriptsWaitingForResourcesIfNeeded();
+    ASSERT(!m_importsController || !controller);
+    m_importsController = controller;
+}
+
+HTMLImportLoader* Document::importLoader() const
+{
+    if (!m_importsController)
+        return 0;
+    return m_importsController->loaderFor(*this);
 }
 
 bool Document::haveImportsLoaded() const
 {
-    return !m_import || !m_import->isBlocked();
+    if (!m_importsController)
+        return true;
+    return !m_importsController->shouldBlockScriptExecution(*this);
+}
+
+LocalDOMWindow* Document::executingWindow()
+{
+    if (LocalDOMWindow* owningWindow = domWindow())
+        return owningWindow;
+    if (HTMLImportsController* import = this->importsController())
+        return import->master()->domWindow();
+    return 0;
+}
+
+LocalFrame* Document::executingFrame()
+{
+    LocalDOMWindow* window = executingWindow();
+    if (!window)
+        return 0;
+    return window->frame();
 }
 
-PassRefPtr<DocumentFragment> Document::createDocumentFragment()
+PassRefPtrWillBeRawPtr<DocumentFragment> Document::createDocumentFragment()
 {
-    return DocumentFragment::create(document());
+    return DocumentFragment::create(*this);
 }
 
-PassRefPtr<Text> Document::createTextNode(const String& data)
+PassRefPtrWillBeRawPtr<Text> Document::createTextNode(const String& data)
 {
     return Text::create(*this, data);
 }
 
-PassRefPtr<Comment> Document::createComment(const String& data)
+PassRefPtrWillBeRawPtr<Comment> Document::createComment(const String& data)
 {
     return Comment::create(*this, data);
 }
 
-PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& es)
+PassRefPtrWillBeRawPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
 {
     if (isHTMLDocument()) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
+        exceptionState.throwDOMException(NotSupportedError, "This operation is not supported for HTML documents.");
+        return nullptr;
     }
-    if (data.find("]]>") != WTF::kNotFound) {
-        es.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
-        return 0;
+    if (data.contains("]]>")) {
+        exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
+        return nullptr;
     }
     return CDATASection::create(*this, data);
 }
 
-PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& es)
+PassRefPtrWillBeRawPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
 {
     if (!isValidName(target)) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
-        return 0;
+        exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
+        return nullptr;
     }
-    if (isHTMLDocument()) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
+    if (data.contains("?>")) {
+        exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
+        return nullptr;
     }
     return ProcessingInstruction::create(*this, target, data);
 }
 
-PassRefPtr<Text> Document::createEditingTextNode(const String& text)
+PassRefPtrWillBeRawPtr<Text> Document::createEditingTextNode(const String& text)
 {
     return Text::createEditingText(*this, text);
 }
 
-PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
+bool Document::importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtrWillBeRawPtr<ContainerNode> newContainerNode, ExceptionState& exceptionState)
 {
-    return MutableStylePropertySet::create()->ensureCSSStyleDeclaration();
+    for (Node* oldChild = oldContainerNode->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
+        RefPtrWillBeRawPtr<Node> newChild = importNode(oldChild, true, exceptionState);
+        if (exceptionState.hadException())
+            return false;
+        newContainerNode->appendChild(newChild.release(), exceptionState);
+        if (exceptionState.hadException())
+            return false;
+    }
+
+    return true;
 }
 
-PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& es)
+PassRefPtrWillBeRawPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
 {
-    if (!importedNode) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-
     switch (importedNode->nodeType()) {
     case TEXT_NODE:
         return createTextNode(importedNode->nodeValue());
     case CDATA_SECTION_NODE:
-        return createCDATASection(importedNode->nodeValue(), es);
+        return CDATASection::create(*this, importedNode->nodeValue());
     case PROCESSING_INSTRUCTION_NODE:
-        return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), es);
+        return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
     case COMMENT_NODE:
         return createComment(importedNode->nodeValue());
+    case DOCUMENT_TYPE_NODE: {
+        DocumentType* doctype = toDocumentType(importedNode);
+        return DocumentType::create(this, doctype->name(), doctype->publicId(), doctype->systemId());
+    }
     case ELEMENT_NODE: {
         Element* oldElement = toElement(importedNode);
         // FIXME: The following check might be unnecessary. Is it possible that
         // oldElement has mismatched prefix/namespace?
         if (!hasValidNamespaceForElements(oldElement->tagQName())) {
-            es.throwUninformativeAndGenericDOMException(NamespaceError);
-            return 0;
+            exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
+            return nullptr;
         }
-        RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
+        RefPtrWillBeRawPtr<Element> newElement = createElement(oldElement->tagQName(), false);
 
         newElement->cloneDataFromElement(*oldElement);
 
         if (deep) {
-            for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
-                RefPtr<Node> newChild = importNode(oldChild, true, es);
-                if (es.hadException())
-                    return 0;
-                newElement->appendChild(newChild.release(), es);
-                if (es.hadException())
-                    return 0;
-            }
+            if (!importContainerNodeChildren(oldElement, newElement, exceptionState))
+                return nullptr;
+            if (isHTMLTemplateElement(*oldElement)
+                && !importContainerNodeChildren(toHTMLTemplateElement(oldElement)->content(), toHTMLTemplateElement(newElement)->content(), exceptionState))
+                return nullptr;
         }
 
         return newElement.release();
     }
     case ATTRIBUTE_NODE:
-        return Attr::create(*this, QualifiedName(nullAtom, toAttr(importedNode)->name(), nullAtom), toAttr(importedNode)->value());
+        return Attr::create(*this, QualifiedName(nullAtom, AtomicString(toAttr(importedNode)->name()), nullAtom), toAttr(importedNode)->value());
     case DOCUMENT_FRAGMENT_NODE: {
         if (importedNode->isShadowRoot()) {
             // ShadowRoot nodes should not be explicitly importable.
             // Either they are imported along with their host node, or created implicitly.
-            break;
+            exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
+            return nullptr;
         }
         DocumentFragment* oldFragment = toDocumentFragment(importedNode);
-        RefPtr<DocumentFragment> newFragment = createDocumentFragment();
-        if (deep) {
-            for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
-                RefPtr<Node> newChild = importNode(oldChild, true, es);
-                if (es.hadException())
-                    return 0;
-                newFragment->appendChild(newChild.release(), es);
-                if (es.hadException())
-                    return 0;
-            }
-        }
+        RefPtrWillBeRawPtr<DocumentFragment> newFragment = createDocumentFragment();
+        if (deep && !importContainerNodeChildren(oldFragment, newFragment, exceptionState))
+            return nullptr;
 
         return newFragment.release();
     }
-    case ENTITY_NODE:
-    case NOTATION_NODE:
-        // FIXME: It should be possible to import these node types, however in DOM3 the DocumentType is readonly, so there isn't much sense in doing that.
-        // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
     case DOCUMENT_NODE:
-    case DOCUMENT_TYPE_NODE:
-    case XPATH_NAMESPACE_NODE:
-        break;
+        exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
+        return nullptr;
     }
-    es.throwUninformativeAndGenericDOMException(NotSupportedError);
-    return 0;
+
+    ASSERT_NOT_REACHED();
+    return nullptr;
 }
 
-PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& es)
+PassRefPtrWillBeRawPtr<Node> Document::adoptNode(PassRefPtrWillBeRawPtr<Node> source, ExceptionState& exceptionState)
 {
-    if (!source) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-
     EventQueueScope scope;
 
     switch (source->nodeType()) {
-    case ENTITY_NODE:
-    case NOTATION_NODE:
     case DOCUMENT_NODE:
-    case DOCUMENT_TYPE_NODE:
-    case XPATH_NAMESPACE_NODE:
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
+        exceptionState.throwDOMException(NotSupportedError, "The node provided is of type '" + source->nodeName() + "', which may not be adopted.");
+        return nullptr;
     case ATTRIBUTE_NODE: {
         Attr* attr = toAttr(source.get());
-        if (attr->ownerElement())
-            attr->ownerElement()->removeAttributeNode(attr, es);
+        if (RefPtrWillBeRawPtr<Element> ownerElement = attr->ownerElement())
+            ownerElement->removeAttributeNode(attr, exceptionState);
         break;
     }
     default:
         if (source->isShadowRoot()) {
             // ShadowRoot cannot disconnect itself from the host node.
-            es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
-            return 0;
+            exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
+            return nullptr;
         }
 
         if (source->isFrameOwnerElement()) {
             HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
-            if (frame() && frame()->tree().isDescendantOf(frameOwnerElement->contentFrame())) {
-                es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
-                return 0;
+            // FIXME(kenrb): the downcast can be removed when the FrameTree supports RemoteFrames.
+            if (frame() && frame()->tree().isDescendantOf(toLocalFrameTemporary(frameOwnerElement->contentFrame()))) {
+                exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
+                return nullptr;
             }
         }
         if (source->parentNode()) {
-            source->parentNode()->removeChild(source.get(), es);
-            if (es.hadException())
-                return 0;
+            source->parentNode()->removeChild(source.get(), exceptionState);
+            if (exceptionState.hadException())
+                return nullptr;
         }
     }
 
@@ -961,42 +1075,37 @@ bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
 
     // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
     // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
-    // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
-    if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
-        return false;
-
-    return true;
+    // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
+    if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
+        return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
+    return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
 }
 
 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
 {
-    // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS
-    if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
-        // Note: The case of an "xmlns" qualified name with a namespace of
-        // xmlnsNamespaceURI is specifically allowed (See <http://www.w3.org/2000/xmlns/>).
-        return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
-    }
     return hasValidNamespaceForElements(qName);
 }
 
 // FIXME: This should really be in a possible ElementFactory class
-PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
+PassRefPtrWillBeRawPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
 {
-    RefPtr<Element> e;
+    RefPtrWillBeRawPtr<Element> e = nullptr;
 
     // FIXME: Use registered namespaces and look up in a hash to find the right factory.
     if (qName.namespaceURI() == xhtmlNamespaceURI)
-        e = HTMLElementFactory::createHTMLElement(qNamethis, 0, createdByParser);
+        e = HTMLElementFactory::createHTMLElement(qName.localName(), *this, 0, createdByParser);
     else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
-        e = SVGElementFactory::createSVGElement(qNamethis, createdByParser);
+        e = SVGElementFactory::createSVGElement(qName.localName(), *this, createdByParser);
 
     if (e)
         m_sawElementsInKnownNamespaces = true;
     else
-        e = Element::create(qName, &document());
+        e = Element::create(qName, this);
+
+    if (e->prefix() != qName.prefix())
+        e->setTagNameForCreateElementNS(qName);
 
-    // <image> uses imgTag so we need a special rule.
-    ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
+    ASSERT(qName == e->tagQName());
 
     return e.release();
 }
@@ -1006,44 +1115,6 @@ bool Document::regionBasedColumnsEnabled() const
     return settings() && settings()->regionBasedColumnsEnabled();
 }
 
-bool Document::cssCompositingEnabled() const
-{
-    return RuntimeEnabledFeatures::cssCompositingEnabled();
-}
-
-PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
-{
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !isActive())
-        return 0;
-
-    updateStyleIfNeeded();
-
-    return namedFlows()->createCSSOMSnapshot();
-}
-
-NamedFlowCollection* Document::namedFlows()
-{
-    if (!m_namedFlows)
-        m_namedFlows = NamedFlowCollection::create(this);
-
-    return m_namedFlows.get();
-}
-
-PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& es)
-{
-    String prefix, localName;
-    if (!parseQualifiedName(qualifiedName, prefix, localName, es))
-        return 0;
-
-    QualifiedName qName(prefix, localName, namespaceURI);
-    if (!hasValidNamespaceForElements(qName)) {
-        es.throwUninformativeAndGenericDOMException(NamespaceError);
-        return 0;
-    }
-
-    return createElement(qName, false);
-}
-
 String Document::readyState() const
 {
     DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
@@ -1072,8 +1143,6 @@ void Document::setReadyState(ReadyState readyState)
     case Loading:
         if (!m_documentTiming.domLoading) {
             m_documentTiming.domLoading = monotonicallyIncreasingTime();
-            if (RuntimeEnabledFeatures::webAnimationsEnabled())
-                m_timeline->setZeroTime(m_documentTiming.domLoading);
         }
         break;
     case Interactive:
@@ -1095,12 +1164,12 @@ bool Document::isLoadCompleted()
     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.
     // FIXME: We should fix TextEncoding to speak AtomicString anyway.
-    return AtomicString(m_encoding.name());
+    return AtomicString(encoding().name());
 }
 
 String Document::defaultCharset() const
@@ -1112,44 +1181,40 @@ String Document::defaultCharset() const
 
 void Document::setCharset(const String& charset)
 {
-    if (!decoder())
+    UseCounter::count(*this, UseCounter::DocumentSetCharset);
+    if (DocumentLoader* documentLoader = loader())
+        documentLoader->setUserChosenEncoding(charset);
+    WTF::TextEncoding encoding(charset);
+    // In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
+    if (!encoding.isValid())
         return;
-    decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
-    setEncoding(m_decoder->encoding());
+    DocumentEncodingData newEncodingData = m_encodingData;
+    newEncodingData.setEncoding(encoding);
+    setEncodingData(newEncodingData);
 }
 
-void Document::setContentLanguage(const String& language)
+void Document::setContentLanguage(const AtomicString& language)
 {
     if (m_contentLanguage == language)
         return;
     m_contentLanguage = language;
 
     // Document's style depends on the content language.
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
-void Document::setXMLVersion(const String& version, ExceptionState& es)
+void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
 {
-    if (!implementation()->hasFeature("XML", String())) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return;
-    }
-
     if (!XMLDocumentParser::supportsXMLVersion(version)) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "This document does not support the XML version '" + version + "'.");
         return;
     }
 
     m_xmlVersion = version;
 }
 
-void Document::setXMLStandalone(bool standalone, ExceptionState& es)
+void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
 {
-    if (!implementation()->hasFeature("XML", String())) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return;
-    }
-
     m_xmlStandalone = standalone ? Standalone : NotStandalone;
 }
 
@@ -1172,10 +1237,13 @@ void Document::setContent(const String& content)
 
 String Document::suggestedMIMEType() const
 {
-    if (isXHTMLDocument())
-        return "application/xhtml+xml";
-    if (isSVGDocument())
-        return "image/svg+xml";
+    if (isXMLDocument()) {
+        if (isXHTMLDocument())
+            return "application/xhtml+xml";
+        if (isSVGDocument())
+            return "image/svg+xml";
+        return "application/xml";
+    }
     if (xmlStandalone())
         return "text/xml";
     if (isHTMLDocument())
@@ -1186,22 +1254,42 @@ String Document::suggestedMIMEType() const
     return String();
 }
 
+void Document::setMimeType(const AtomicString& mimeType)
+{
+    m_mimeType = mimeType;
+}
+
+AtomicString Document::contentType() const
+{
+    if (!m_mimeType.isEmpty())
+        return m_mimeType;
+
+    if (DocumentLoader* documentLoader = loader())
+        return documentLoader->mimeType();
+
+    String mimeType = suggestedMIMEType();
+    if (!mimeType.isEmpty())
+        return AtomicString(mimeType);
+
+    return AtomicString("application/xml");
+}
+
 Element* Document::elementFromPoint(int x, int y) const
 {
-    if (!isActive())
+    if (!renderView())
         return 0;
 
     return TreeScope::elementFromPoint(x, y);
 }
 
-PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
+PassRefPtrWillBeRawPtr<Range> Document::caretRangeFromPoint(int x, int y)
 {
-    if (!isActive())
-        return 0;
-    LayoutPoint localPoint;
-    RenderObject* renderer = rendererFromPoint(this, x, y, &localPoint);
+    if (!renderView())
+        return nullptr;
+    HitTestResult result = hitTestInDocument(this, x, y);
+    RenderObject* renderer = result.renderer();
     if (!renderer)
-        return 0;
+        return nullptr;
 
     Node* node = renderer->node();
     Node* shadowAncestorNode = ancestorInThisScope(node);
@@ -1211,9 +1299,9 @@ PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
         return Range::create(*this, container, offset, container, offset);
     }
 
-    PositionWithAffinity positionWithAffinity = renderer->positionForPoint(localPoint);
+    PositionWithAffinity positionWithAffinity = result.position();
     if (positionWithAffinity.position().isNull())
-        return 0;
+        return nullptr;
 
     Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent();
     return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
@@ -1228,49 +1316,28 @@ PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
 template <typename CharacterType>
 static inline String canonicalizedTitle(Document* document, const String& title)
 {
-    const CharacterType* characters = title.getCharacters<CharacterType>();
     unsigned length = title.length();
-    unsigned i;
-
-    StringBuffer<CharacterType> buffer(length);
     unsigned builderIndex = 0;
+    const CharacterType* characters = title.getCharacters<CharacterType>();
 
-    // Skip leading spaces and leading characters that would convert to spaces
-    for (i = 0; i < length; ++i) {
-        CharacterType c = characters[i];
-        if (!(c <= 0x20 || c == 0x7F))
-            break;
-    }
-
-    if (i == length)
-        return String();
+    StringBuffer<CharacterType> buffer(length);
 
-    // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
-    bool previousCharWasWS = false;
-    for (; i < length; ++i) {
-        CharacterType c = characters[i];
+    // Replace control characters with spaces and collapse whitespace.
+    bool pendingWhitespace = false;
+    for (unsigned i = 0; i < length; ++i) {
+        UChar32 c = characters[i];
         if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
-            if (previousCharWasWS)
-                continue;
-            buffer[builderIndex++] = ' ';
-            previousCharWasWS = true;
+            if (builderIndex != 0)
+                pendingWhitespace = true;
         } else {
+            if (pendingWhitespace) {
+                buffer[builderIndex++] = ' ';
+                pendingWhitespace = false;
+            }
             buffer[builderIndex++] = c;
-            previousCharWasWS = false;
         }
     }
-
-    // Strip trailing spaces
-    while (builderIndex > 0) {
-        --builderIndex;
-        if (buffer[builderIndex] != ' ')
-            break;
-    }
-
-    if (!builderIndex && buffer[builderIndex] == ' ')
-        return String();
-
-    buffer.shrink(builderIndex + 1);
+    buffer.shrink(builderIndex);
 
     return String::adopt(buffer);
 }
@@ -1298,32 +1365,39 @@ void Document::updateTitle(const String& title)
 void Document::setTitle(const String& title)
 {
     // Title set by JavaScript -- overrides any title elements.
-    m_titleSetExplicitly = true;
     if (!isHTMLDocument() && !isXHTMLDocument())
-        m_titleElement = 0;
+        m_titleElement = nullptr;
     else if (!m_titleElement) {
-        if (HTMLElement* headElement = head()) {
-            m_titleElement = createElement(titleTag, false);
-            headElement->appendChild(m_titleElement);
-        }
+        HTMLElement* headElement = head();
+        if (!headElement)
+            return;
+        m_titleElement = HTMLTitleElement::create(*this);
+        headElement->appendChild(m_titleElement.get());
     }
 
-    updateTitle(title);
-
-    if (m_titleElement && isHTMLTitleElement(m_titleElement.get()))
+    if (isHTMLTitleElement(m_titleElement))
         toHTMLTitleElement(m_titleElement)->setText(title);
+    else
+        updateTitle(title);
 }
 
-void Document::setTitleElement(const String& title, Element* titleElement)
+void Document::setTitleElement(Element* titleElement)
 {
-    if (titleElement != m_titleElement) {
-        if (m_titleElement || m_titleSetExplicitly)
-            // Only allow the first title element to change the title -- others have no effect.
-            return;
+    // Only allow the first title element to change the title -- others have no effect.
+    if (m_titleElement && m_titleElement != titleElement) {
+        if (isHTMLDocument() || isXHTMLDocument()) {
+            m_titleElement = Traversal<HTMLTitleElement>::firstWithin(*this);
+        } else if (isSVGDocument()) {
+            m_titleElement = Traversal<SVGTitleElement>::firstWithin(*this);
+        }
+    } else {
         m_titleElement = titleElement;
     }
 
-    updateTitle(title);
+    if (isHTMLTitleElement(m_titleElement))
+        updateTitle(toHTMLTitleElement(m_titleElement)->text());
+    else if (isSVGTitleElement(m_titleElement))
+        updateTitle(toSVGTitleElement(m_titleElement)->textContent());
 }
 
 void Document::removeTitle(Element* titleElement)
@@ -1331,26 +1405,37 @@ void Document::removeTitle(Element* titleElement)
     if (m_titleElement != titleElement)
         return;
 
-    m_titleElement = 0;
-    m_titleSetExplicitly = false;
-
-    // FIXME: This is broken for SVG.
-    // Update title based on first title element in the head, if one exists.
-    if (HTMLElement* headElement = head()) {
-        for (Element* element = headElement->firstElementChild(); element; element = element->nextElementSibling()) {
-            if (!isHTMLTitleElement(element))
-                continue;
-            HTMLTitleElement* title = toHTMLTitleElement(element);
-            setTitleElement(title->text(), title);
-            break;
-        }
+    m_titleElement = nullptr;
+
+    // Update title based on first title element in the document, if one exists.
+    if (isHTMLDocument() || isXHTMLDocument()) {
+        if (HTMLTitleElement* title = Traversal<HTMLTitleElement>::firstWithin(*this))
+            setTitleElement(title);
+    } else if (isSVGDocument()) {
+        if (SVGTitleElement* title = Traversal<SVGTitleElement>::firstWithin(*this))
+            setTitleElement(title);
     }
 
     if (!m_titleElement)
         updateTitle(String());
 }
 
-PageVisibilityState Document::visibilityState() const
+const AtomicString& Document::dir()
+{
+    Element* rootElement = documentElement();
+    if (isHTMLHtmlElement(rootElement))
+        return toHTMLHtmlElement(rootElement)->dir();
+    return nullAtom;
+}
+
+void Document::setDir(const AtomicString& value)
+{
+    Element* rootElement = documentElement();
+    if (isHTMLHtmlElement(rootElement))
+        toHTMLHtmlElement(rootElement)->setDir(value);
+}
+
+PageVisibilityState Document::pageVisibilityState() const
 {
     // The visibility of the document is inherited from the visibility of the
     // page. If there is no page associated with the document, we will assume
@@ -1361,26 +1446,38 @@ PageVisibilityState Document::visibilityState() const
     return m_frame->page()->visibilityState();
 }
 
-String Document::webkitVisibilityState() const
+String Document::visibilityState() const
 {
-    return pageVisibilityStateString(visibilityState());
+    return pageVisibilityStateString(pageVisibilityState());
 }
 
-bool Document::webkitHidden() const
+bool Document::hidden() const
 {
-    return visibilityState() != PageVisibilityStateVisible;
+    return pageVisibilityState() != PageVisibilityStateVisible;
 }
 
-void Document::dispatchVisibilityStateChangeEvent()
+void Document::didChangeVisibilityState()
 {
+    dispatchEvent(Event::create(EventTypeNames::visibilitychange));
+    // Also send out the deprecated version until it can be removed.
     dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
+
+    PageVisibilityState state = pageVisibilityState();
+    DocumentVisibilityObserverSet::const_iterator observerEnd = m_visibilityObservers.end();
+    for (DocumentVisibilityObserverSet::const_iterator it = m_visibilityObservers.begin(); it != observerEnd; ++it)
+        (*it)->didChangeVisibilityState(state);
 }
 
-DOMSecurityPolicy* Document::securityPolicy()
+void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
 {
-    if (!m_domSecurityPolicy)
-        m_domSecurityPolicy = DOMSecurityPolicy::create(this);
-    return m_domSecurityPolicy.get();
+    ASSERT(!m_visibilityObservers.contains(observer));
+    m_visibilityObservers.add(observer);
+}
+
+void Document::unregisterVisibilityObserver(DocumentVisibilityObserver* observer)
+{
+    ASSERT(m_visibilityObservers.contains(observer));
+    m_visibilityObservers.remove(observer);
 }
 
 String Document::nodeName() const
@@ -1393,17 +1490,20 @@ Node::NodeType Document::nodeType() const
     return DOCUMENT_NODE;
 }
 
-FormController* Document::formController()
+FormController& Document::formController()
 {
-    if (!m_formController)
+    if (!m_formController) {
         m_formController = FormController::create();
-    return m_formController.get();
+        if (m_frame && m_frame->loader().currentItem() && m_frame->loader().currentItem()->isCurrentDocument(this))
+            m_frame->loader().currentItem()->setDocumentState(m_formController->formElementsState());
+    }
+    return *m_formController;
 }
 
-Vector<String> Document::formElementsState() const
+DocumentState* Document::formElementsState() const
 {
     if (!m_formController)
-        return Vector<String>();
+        return 0;
     return m_formController->formElementsState();
 }
 
@@ -1411,7 +1511,7 @@ void Document::setStateForNewFormElements(const Vector<String>& stateVector)
 {
     if (!stateVector.size() && !m_formController)
         return;
-    formController()->setStateForNewFormElements(stateVector);
+    formController().setStateForNewFormElements(stateVector);
 }
 
 FrameView* Document::view() const
@@ -1424,145 +1524,128 @@ Page* Document::page() const
     return m_frame ? m_frame->page() : 0;
 }
 
-Settings* Document::settings() const
+FrameHost* Document::frameHost() const
 {
-    return m_frame ? m_frame->settings() : 0;
+    return m_frame ? m_frame->host() : 0;
 }
 
-PassRefPtr<Range> Document::createRange()
+Settings* Document::settings() const
 {
-    return Range::create(*this);
+    return m_frame ? m_frame->settings() : 0;
 }
 
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& es)
+PassRefPtrWillBeRawPtr<Range> Document::createRange()
 {
-    // FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
-    if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-    return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
+    return Range::create(*this);
 }
 
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& es)
+PassRefPtrWillBeRawPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter, ExceptionState& exceptionState)
 {
-    if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
     // FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
     // NodeFilter.
-    return NodeIterator::create(root, whatToShow, PassRefPtr<NodeFilter>());
-}
-
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& es)
-{
-    if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-    // FIXME: Ditto.
-    return NodeIterator::create(root, whatToShow, filter);
-}
-
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& es)
-{
-    if (!root) {
-        es.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& es)
+PassRefPtrWillBeRawPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter, ExceptionState& exceptionState)
 {
-    if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-    return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
+    return TreeWalker::create(root, whatToShow, filter);
 }
 
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& es)
+bool Document::needsRenderTreeUpdate() const
 {
-    if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-    return TreeWalker::create(root, whatToShow, PassRefPtr<NodeFilter>());
+    if (!isActive() || !view())
+        return false;
+    if (needsFullRenderTreeUpdate())
+        return true;
+    if (childNeedsStyleRecalc())
+        return true;
+    if (childNeedsStyleInvalidation())
+        return true;
+    return false;
 }
 
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& es)
+bool Document::needsFullRenderTreeUpdate() const
 {
-    if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-    return TreeWalker::create(root, whatToShow, filter);
+    if (!isActive() || !view())
+        return false;
+    if (!m_useElementsNeedingUpdate.isEmpty())
+        return true;
+    if (!m_layerUpdateSVGFilterElements.isEmpty())
+        return true;
+    if (needsStyleRecalc())
+        return true;
+    if (needsStyleInvalidation())
+        return true;
+    // FIXME: The childNeedsDistributionRecalc bit means either self or children, we should fix that.
+    if (childNeedsDistributionRecalc())
+        return true;
+    if (DocumentAnimations::needsOutdatedAnimationPlayerUpdate(*this))
+        return true;
+    return false;
 }
 
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& es)
+bool Document::shouldScheduleRenderTreeUpdate() const
 {
-    UNUSED_PARAM(expandEntityReferences);
-    if (!root) {
-        es.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
-    return TreeWalker::create(root, whatToShow, filter);
+    if (!isActive())
+        return false;
+    if (inStyleRecalc())
+        return false;
+    // InPreLayout will recalc style itself. There's no reason to schedule another recalc.
+    if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
+        return false;
+    if (!shouldScheduleLayout())
+        return false;
+    return true;
 }
 
-void Document::scheduleStyleRecalc()
+void Document::scheduleRenderTreeUpdate()
 {
-    if (shouldDisplaySeamlesslyWithParent()) {
-        // When we're seamless, our parent document manages our style recalcs.
-        ownerElement()->setNeedsStyleRecalc();
-        ownerElement()->document().scheduleStyleRecalc();
-        return;
-    }
-
-    if (m_styleRecalcTimer.isActive())
-        return;
-
-    ASSERT(needsStyleRecalc() || childNeedsStyleRecalc() || childNeedsDistributionRecalc());
+    ASSERT(!hasPendingStyleRecalc());
+    ASSERT(shouldScheduleRenderTreeUpdate());
+    ASSERT(needsRenderTreeUpdate());
 
-    m_styleRecalcTimer.startOneShot(0);
+    page()->animator().scheduleVisualUpdate();
+    m_lifecycle.ensureStateAtMost(DocumentLifecycle::VisualUpdatePending);
 
+    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScheduleStyleRecalculation", "frame", frame());
+    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
+    // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
     InspectorInstrumentation::didScheduleStyleRecalculation(this);
 }
 
-void Document::unscheduleStyleRecalc()
+bool Document::hasPendingForcedStyleRecalc() const
 {
-    ASSERT(!isActive() || (!needsStyleRecalc() && !childNeedsStyleRecalc()));
-    m_styleRecalcTimer.stop();
+    return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
 }
 
-bool Document::hasPendingStyleRecalc() const
+void Document::updateDistributionIfNeeded()
 {
-    return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
-}
+    ScriptForbiddenScope forbidScript;
 
-bool Document::hasPendingForcedStyleRecalc() const
-{
-    return hasPendingStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
+    if (!childNeedsDistributionRecalc())
+        return;
+    TRACE_EVENT0("blink", "Document::updateDistributionIfNeeded");
+    recalcDistribution();
 }
 
-void Document::styleRecalcTimerFired(Timer<Document>*)
+void Document::updateStyleInvalidationIfNeeded()
 {
-    updateStyleIfNeeded();
-}
+    ScriptForbiddenScope forbidScript;
 
-void Document::updateDistributionIfNeeded()
-{
-    if (!childNeedsDistributionRecalc())
+    if (!isActive())
         return;
-    TRACE_EVENT0("webkit", "Document::recalcDistribution");
-    recalcDistribution();
+    if (!childNeedsStyleInvalidation())
+        return;
+    TRACE_EVENT0("blink", "Document::updateStyleInvalidationIfNeeded");
+    ASSERT(styleResolver());
+
+    styleResolver()->ruleFeatureSet().styleInvalidator().invalidate(*this);
 }
 
 void Document::updateDistributionForNodeIfNeeded(Node* node)
 {
+    ScriptForbiddenScope forbidScript;
+
     if (node->inDocument()) {
         updateDistributionIfNeeded();
         return;
@@ -1576,232 +1659,313 @@ void Document::updateDistributionForNodeIfNeeded(Node* node)
         root->recalcDistribution();
 }
 
-void Document::setStyleDependentState(RenderStyle* documentStyle)
+void Document::setupFontBuilder(RenderStyle* documentStyle)
 {
-    const Pagination& pagination = view()->pagination();
-    if (pagination.mode != Pagination::Unpaginated) {
-        Pagination::setStylesForPaginationMode(pagination.mode, documentStyle);
-        documentStyle->setColumnGap(pagination.gap);
-        if (renderView()->hasColumns())
-            renderView()->updateColumnInfoFromStyle(documentStyle);
-    }
-
-    // Seamless iframes want to inherit their font from their parent iframe, so early return before setting the font.
-    if (shouldDisplaySeamlesslyWithParent())
-        return;
-
     FontBuilder fontBuilder;
-    fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
-    RefPtr<CSSFontSelector> selector = m_styleResolver ? m_styleResolver->fontSelector() : 0;
+    fontBuilder.initForStyleResolve(*this, documentStyle);
+    RefPtrWillBeRawPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
     fontBuilder.createFontForDocument(selector, documentStyle);
 }
 
 void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
 {
-    RenderView* renderView = this->renderView();
-
-    if (!documentElement() || !frame() || !view())
-        return;
+    ASSERT(inStyleRecalc());
+    ASSERT(documentElement());
 
     RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
     if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
-        documentElementStyle = styleResolver()->styleForElement(documentElement());
-
-    RefPtr<RenderStyle> bodyStyle = 0;
-    if (body()) {
-        bodyStyle = body()->renderStyle();
-        if (!bodyStyle || body()->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
-            bodyStyle = styleResolver()->styleForElement(body(), documentElementStyle.get());
-    }
+        documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
 
     WritingMode rootWritingMode = documentElementStyle->writingMode();
     TextDirection rootDirection = documentElementStyle->direction();
 
-    if (!writingModeSetOnDocumentElement() && body()) {
-        rootWritingMode = bodyStyle->writingMode();
+    HTMLElement* body = this->body();
+    RefPtr<RenderStyle> bodyStyle;
+    if (body) {
+        bodyStyle = body->renderStyle();
+        if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
+            bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
+        if (!writingModeSetOnDocumentElement())
+            rootWritingMode = bodyStyle->writingMode();
+        if (!directionSetOnDocumentElement())
+            rootDirection = bodyStyle->direction();
+    }
+
+    RefPtr<RenderStyle> overflowStyle;
+    if (Element* element = viewportDefiningElement(documentElementStyle.get())) {
+        if (element == body) {
+            overflowStyle = bodyStyle;
+        } else {
+            ASSERT(element == documentElement());
+            overflowStyle = documentElementStyle;
+        }
     }
 
-    if (!directionSetOnDocumentElement() && body())
-        rootDirection = bodyStyle->direction();
-
-    RefPtr<RenderStyle> documentStyle = renderView->style();
-    if (documentStyle->writingMode() != rootWritingMode || documentStyle->direction() != rootDirection) {
+    // Resolved rem units are stored in the matched properties cache so we need to make sure to
+    // invalidate the cache if the documentElement needed to reattach or the font size changed
+    // and then trigger a full document recalc. We also need to clear it here since the
+    // call to styleForElement on the body above can cache bad values for rem units if the
+    // documentElement's style was dirty. We could keep track of which elements depend on
+    // rem units like we do for viewport styles, but we assume root font size changes are
+    // rare and just invalidate the cache for now.
+    if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
+        ensureStyleResolver().invalidateMatchedPropertiesCache();
+        documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
+    }
+
+    EOverflow overflowX = OAUTO;
+    EOverflow overflowY = OAUTO;
+    float columnGap = 0;
+    if (overflowStyle) {
+        overflowX = overflowStyle->overflowX();
+        overflowY = overflowStyle->overflowY();
+        // Visible overflow on the viewport is meaningless, and the spec says to treat it as 'auto':
+        if (overflowX == OVISIBLE)
+            overflowX = OAUTO;
+        if (overflowY == OVISIBLE)
+            overflowY = OAUTO;
+        // Column-gap is (ab)used by the current paged overflow implementation (in lack of other
+        // ways to specify gaps between pages), so we have to propagate it too.
+        columnGap = overflowStyle->columnGap();
+    }
+
+    RefPtr<RenderStyle> documentStyle = renderView()->style();
+    if (documentStyle->writingMode() != rootWritingMode
+        || documentStyle->direction() != rootDirection
+        || documentStyle->overflowX() != overflowX
+        || documentStyle->overflowY() != overflowY
+        || documentStyle->columnGap() != columnGap) {
         RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
         newStyle->setWritingMode(rootWritingMode);
         newStyle->setDirection(rootDirection);
-        renderView->setStyle(newStyle);
-        setStyleDependentState(newStyle.get());
+        newStyle->setColumnGap(columnGap);
+        newStyle->setOverflowX(overflowX);
+        newStyle->setOverflowY(overflowY);
+        renderView()->setStyle(newStyle);
+        setupFontBuilder(newStyle.get());
     }
 
-    if (body()) {
-        if (RenderStyle* style = body()->renderStyle()) {
+    if (body) {
+        if (RenderStyle* style = body->renderStyle()) {
             if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
-                body()->setNeedsStyleRecalc();
+                body->setNeedsStyleRecalc(SubtreeStyleChange);
         }
     }
 
     if (RenderStyle* style = documentElement()->renderStyle()) {
         if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
-            documentElement()->setNeedsStyleRecalc();
+            documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
     }
 }
 
-void Document::recalcStyle(StyleRecalcChange change)
+void Document::updateRenderTree(StyleRecalcChange change)
 {
-    // we should not enter style recalc while painting
-    RELEASE_ASSERT(!view() || !view()->isPainting());
+    ASSERT(isMainThread());
 
-    // FIXME: We should never enter here without a FrameView or with an inactive document.
-    if (!isActive() || !view())
-        return;
+    ScriptForbiddenScope forbidScript;
 
-    if (m_inStyleRecalc)
+    if (!view() || !isActive())
         return;
 
-    TRACE_EVENT0("webkit", "Document::recalcStyle");
-    TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "RecalcStyle");
+    if (change != Force && !needsRenderTreeUpdate())
+        return;
 
-    updateDistributionIfNeeded();
+    if (inStyleRecalc())
+        return;
 
+    // Entering here from inside layout or paint would be catastrophic since recalcStyle can
+    // tear down the render tree or (unfortunately) run script. Kill the whole renderer if
+    // someone managed to get into here from inside layout or paint.
+    RELEASE_ASSERT(!view()->isInPerformLayout());
+    RELEASE_ASSERT(!view()->isPainting());
+
+    // Script can run below in WidgetUpdates, so protect the LocalFrame.
+    // FIXME: Can this still happen? How does script run inside
+    // UpdateSuspendScope::performDeferredWidgetTreeOperations() ?
+    RefPtrWillBeRawPtr<LocalFrame> protect(m_frame.get());
+
+    TRACE_EVENT_BEGIN0("blink", "Document::updateRenderTree");
+    TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "UpdateRenderTree");
+
+    // FIXME: Remove m_styleRecalcElementCounter, we should just use the accessCount() on the resolver.
+    m_styleRecalcElementCounter = 0;
+    TRACE_EVENT_BEGIN1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "frame", frame());
+    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
+    // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
 
-    if (m_evaluateMediaQueriesOnStyleRecalc) {
-        m_evaluateMediaQueriesOnStyleRecalc = false;
-        evaluateMediaQueryList();
-    }
+    DocumentAnimations::updateOutdatedAnimationPlayersIfNeeded(*this);
+    evaluateMediaQueryListIfNeeded();
+    updateUseShadowTreesIfNeeded();
+    updateDistributionIfNeeded();
+    updateStyleInvalidationIfNeeded();
 
-    // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
-    // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
-    // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
+    // FIXME: We should update style on our ancestor chain before proceeding
+    // however doing so currently causes several tests to crash, as LocalFrame::setDocument calls Document::attach
+    // before setting the LocalDOMWindow on the LocalFrame, or the SecurityOrigin on the document. The attach, in turn
     // resolves style (here) and then when we resolve style on the parent chain, we may end up
     // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
     // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
 
-    if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
-        m_styleEngine->updateActiveStyleSheets(FullStyleUpdate);
-
     if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
         m_styleEngine->setUsesRemUnit(true);
 
-    {
-        PostAttachCallbacks::SuspendScope suspendPostAttachCallbacks;
-        RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
-        FrameView::DeferredRepaintScope deferRepaints(*view());
-        TemporaryChange<bool> changeInStyleRecalc(m_inStyleRecalc, true);
-
-        if (styleChangeType() >= SubtreeStyleChange)
-            change = Force;
-
-        if (change == Force || (change >= Inherit && shouldDisplaySeamlesslyWithParent())) {
-            m_hasNodesWithPlaceholderStyle = false;
-            RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
-            StyleRecalcChange localChange = RenderStyle::compare(documentStyle.get(), renderView()->style());
-            if (localChange != NoChange)
-                renderView()->setStyle(documentStyle.release());
-        }
+    updateStyle(change);
 
-        inheritHtmlAndBodyElementStyles(change);
+    // As a result of the style recalculation, the currently hovered element might have been
+    // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
+    // to check if any other elements ended up under the mouse pointer due to re-layout.
+    if (hoverNode() && !hoverNode()->renderer() && frame())
+        frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
 
-        if (Element* documentElement = this->documentElement()) {
-            if (shouldRecalcStyle(change, documentElement))
-                documentElement->recalcStyle(change);
-        }
+    if (m_focusedElement && !m_focusedElement->isFocusable())
+        clearFocusedElementSoon();
 
-        view()->updateCompositingLayersAfterStyleChange();
+#if ENABLE(SVG_FONTS)
+    if (svgExtensions())
+        accessSVGExtensions().removePendingSVGFontFaceElementsForRemoval();
+#endif
 
-        clearNeedsStyleRecalc();
-        clearChildNeedsStyleRecalc();
-        unscheduleStyleRecalc();
+    ASSERT(!m_timeline->hasOutdatedAnimationPlayer());
 
-        // FIXME: SVG <use> element can schedule a recalc in the middle of an already running one.
-        // See StyleEngine::updateActiveStyleSheets.
-        if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
-            setNeedsStyleRecalc();
+    TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "elementCount", m_styleRecalcElementCounter);
+    TRACE_EVENT_END1("blink", "Document::updateRenderTree", "elementCount", m_styleRecalcElementCounter);
+    // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
+    InspectorInstrumentation::didRecalculateStyle(cookie, m_styleRecalcElementCounter);
+}
 
-        if (m_styleResolver) {
-            // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
-            m_styleEngine->resetCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
-            m_styleResolver->clearStyleSharingList();
-        }
+void Document::updateStyle(StyleRecalcChange change)
+{
+    TRACE_EVENT0("blink", "Document::updateStyle");
+
+    HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates;
+    m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
+
+    if (styleChangeType() >= SubtreeStyleChange)
+        change = Force;
+
+    // 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.
+
+    if (change == Force) {
+        m_hasNodesWithPlaceholderStyle = false;
+        RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this);
+        StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(documentStyle.get(), renderView()->style());
+        if (localChange != NoChange)
+            renderView()->setStyle(documentStyle.release());
     }
 
-    STYLE_STATS_PRINT();
-    STYLE_STATS_CLEAR();
+    clearNeedsStyleRecalc();
 
-    InspectorInstrumentation::didRecalculateStyle(cookie);
+    // Uncomment to enable printing of statistics about style sharing and the matched property cache.
+    // 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.
+    // ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
 
-    // As a result of the style recalculation, the currently hovered element might have been
-    // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
-    // to check if any other elements ended up under the mouse pointer due to re-layout.
-    if (hoverNode() && !hoverNode()->renderer() && frame())
-        frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
-}
+    if (StyleResolverStats* stats = ensureStyleResolver().stats())
+        stats->reset();
 
-void Document::updateStyleIfNeeded()
-{
-    ASSERT(isMainThread());
-    ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
+    if (Element* documentElement = this->documentElement()) {
+        inheritHtmlAndBodyElementStyles(change);
+        dirtyElementsForLayerUpdate();
+        if (documentElement->shouldCallRecalcStyle(change))
+            documentElement->recalcStyle(change);
+        while (dirtyElementsForLayerUpdate())
+            documentElement->recalcStyle(NoChange);
+    }
 
-    if (!needsStyleRecalc() && !childNeedsStyleRecalc() && !childNeedsDistributionRecalc())
-        return;
+    ensureStyleResolver().printStats();
 
-    AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : 0);
-    recalcStyle(NoChange);
-    m_animationClock->unfreeze();
+    view()->recalcOverflowAfterStyleChange();
+
+    clearChildNeedsStyleRecalc();
+
+    if (m_styleEngine->hasResolver()) {
+        // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
+        StyleResolver& resolver = m_styleEngine->ensureResolver();
+        m_styleEngine->resetCSSFeatureFlags(resolver.ensureUpdatedRuleFeatureSet());
+        resolver.clearStyleSharingList();
+    }
+
+    ASSERT(!needsStyleRecalc());
+    ASSERT(!childNeedsStyleRecalc());
+    ASSERT(inStyleRecalc());
+    m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
 }
 
-void Document::updateStyleForNodeIfNeeded(Node* node)
+void Document::updateRenderTreeForNodeIfNeeded(Node* node)
 {
-    if (!hasPendingForcedStyleRecalc() && !childNeedsStyleRecalc() && !needsStyleRecalc())
-        return;
+    bool needsRecalc = needsFullRenderTreeUpdate();
+
+    for (const Node* ancestor = node; ancestor && !needsRecalc; ancestor = NodeRenderingTraversal::parent(ancestor))
+        needsRecalc = ancestor->needsStyleRecalc() || ancestor->needsStyleInvalidation();
 
-    bool needsStyleRecalc = hasPendingForcedStyleRecalc();
-    for (Node* ancestor = node; ancestor && !needsStyleRecalc; ancestor = ancestor->parentOrShadowHostNode())
-        needsStyleRecalc = ancestor->needsStyleRecalc();
-    if (needsStyleRecalc)
-        updateStyleIfNeeded();
+    if (needsRecalc)
+        updateRenderTreeIfNeeded();
 }
 
 void Document::updateLayout()
 {
     ASSERT(isMainThread());
 
-    FrameView* frameView = view();
-    if (frameView && frameView->isInLayout()) {
+    ScriptForbiddenScope forbidScript;
+
+    RefPtr<FrameView> frameView = view();
+    if (frameView && frameView->isInPerformLayout()) {
         // View layout should not be re-entrant.
         ASSERT_NOT_REACHED();
         return;
     }
 
-    if (Element* oe = ownerElement())
-        oe->document().updateLayout();
+    if (HTMLFrameOwnerElement* owner = ownerElement())
+        owner->document().updateLayout();
 
-    updateStyleIfNeeded();
+    updateRenderTreeIfNeeded();
 
-    // Only do a layout if changes have occurred that make it necessary.
-    if (frameView && isActive() && (frameView->layoutPending() || renderView()->needsLayout()))
-        frameView->layout();
+    if (!isActive())
+        return;
 
-    if (frameView)
-        frameView->partialLayout().reset();
+    if (frameView->needsLayout())
+        frameView->layout();
 
-    setNeedsFocusedElementCheck();
+    if (lifecycle().state() < DocumentLifecycle::LayoutClean)
+        lifecycle().advanceTo(DocumentLifecycle::LayoutClean);
 }
 
 void Document::setNeedsFocusedElementCheck()
 {
-    // FIXME: Using a Task doesn't look a good idea.
-    if (!m_focusedElement || m_didPostCheckFocusedElementTask)
-        return;
-    postTask(CheckFocusedElementTask::create());
-    m_didPostCheckFocusedElementTask = true;
+    setNeedsStyleRecalc(LocalStyleChange);
+}
+
+void Document::clearFocusedElementSoon()
+{
+    if (!m_clearFocusedElementTimer.isActive())
+        m_clearFocusedElementTimer.startOneShot(0, FROM_HERE);
 }
 
-void Document::recalcStyleForLayoutIgnoringPendingStylesheets()
+void Document::clearFocusedElementTimerFired(Timer<Document>*)
 {
-    TemporaryChange<bool> ignorePendingStylesheets(m_ignorePendingStylesheets, m_ignorePendingStylesheets);
-    if (!haveStylesheetsLoaded()) {
-        m_ignorePendingStylesheets = true;
+    updateRenderTreeIfNeeded();
+    m_clearFocusedElementTimer.stop();
+
+    if (m_focusedElement && !m_focusedElement->isFocusable())
+        m_focusedElement->blur();
+}
+
+// FIXME: This is a bad idea and needs to be removed eventually.
+// Other browsers load stylesheets before they continue parsing the web page.
+// Since we don't, we can run JavaScript code that needs answers before the
+// stylesheets are loaded. Doing a layout ignoring the pending stylesheets
+// lets us get reasonable answers. The long term solution to this problem is
+// to instead suspend JavaScript execution.
+void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
+{
+    StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
+
+    if (m_styleEngine->hasPendingSheets()) {
         // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
         // Our assumption is that it would be dangerous to try to stop it a second time, after page
         // content has already been loaded and displayed with accurate style information. (Our
@@ -1812,70 +1976,32 @@ void Document::recalcStyleForLayoutIgnoringPendingStylesheets()
         HTMLElement* bodyElement = body();
         if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
             m_pendingSheetLayout = DidLayoutWithPendingSheets;
-            styleResolverChanged(RecalcStyleImmediately);
+            styleResolverChanged();
         } else if (m_hasNodesWithPlaceholderStyle) {
             // If new nodes have been added or style recalc has been done with style sheets still
             // pending, some nodes may not have had their real style calculated yet. Normally this
             // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
-            recalcStyle(Force);
+            updateRenderTree(Force);
         }
     }
-}
-
-// FIXME: This is a bad idea and needs to be removed eventually.
-// Other browsers load stylesheets before they continue parsing the web page.
-// Since we don't, we can run JavaScript code that needs answers before the
-// stylesheets are loaded. Doing a layout ignoring the pending stylesheets
-// lets us get reasonable answers. The long term solution to this problem is
-// to instead suspend JavaScript execution.
-void Document::updateLayoutIgnorePendingStylesheets()
-{
-    recalcStyleForLayoutIgnoringPendingStylesheets();
-    updateLayout();
-}
-
-void Document::partialUpdateLayoutIgnorePendingStylesheets(Node* stopLayoutAtNode)
-{
-    // Non-overlay scrollbars can cause a second layout that is dependent
-    // on a first layout. This is disabled for partial layout for now.
-    if (!RuntimeEnabledFeatures::partialLayoutEnabled() || !ScrollbarTheme::theme()->usesOverlayScrollbars()) {
-        updateLayoutIgnorePendingStylesheets();
-        return;
-    }
-
-    TemporaryChange<bool> ignorePendingStylesheets(m_ignorePendingStylesheets, m_ignorePendingStylesheets);
-    recalcStyleForLayoutIgnoringPendingStylesheets();
-
-    if (stopLayoutAtNode) {
-        RenderObject* renderer = stopLayoutAtNode->renderer();
-        bool canPartialLayout = renderer;
-        while (renderer) {
-            if (!renderer->supportsPartialLayout()) {
-                canPartialLayout = false;
-                break;
-            }
-            renderer = renderer->parent();
-        }
-        if (canPartialLayout && view())
-            view()->partialLayout().setStopAtRenderer(stopLayoutAtNode->renderer());
-    }
 
     updateLayout();
 
-    if (view())
-        view()->partialLayout().reset();
+    if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
+        view()->flushAnyPendingPostLayoutTasks();
 }
 
 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
 {
     ASSERT_ARG(element, element->document() == this);
-    TemporaryChange<bool> ignoreStyleSheets(m_ignorePendingStylesheets, true);
-    return styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
+    StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
+    return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
 }
 
 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
 {
-    return styleResolver()->styleForPage(pageIndex);
+    updateDistributionIfNeeded();
+    return ensureStyleResolver().styleForPage(pageIndex);
 }
 
 bool Document::isPageBoxVisible(int pageIndex)
@@ -1886,7 +2012,6 @@ bool Document::isPageBoxVisible(int pageIndex)
 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
 {
     RefPtr<RenderStyle> style = styleForPage(pageIndex);
-    RenderView* view = renderView();
 
     int width = pageSize.width();
     int height = pageSize.height();
@@ -1905,8 +2030,8 @@ void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int&
         LengthSize size = style->pageSize();
         ASSERT(size.width().isFixed());
         ASSERT(size.height().isFixed());
-        width = valueForLength(size.width(), 0, view);
-        height = valueForLength(size.height(), 0, view);
+        width = valueForLength(size.width(), 0);
+        height = valueForLength(size.height(), 0);
         break;
     }
     default:
@@ -1914,66 +2039,125 @@ void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int&
     }
     pageSize = IntSize(width, height);
 
-    // The percentage is calculated with respect to the width even for margin top and bottom.
-    // http://www.w3.org/TR/CSS2/box.html#margin-properties
-    marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
-    marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
-    marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
-    marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
+    // The percentage is calculated with respect to the width even for margin top and bottom.
+    // http://www.w3.org/TR/CSS2/box.html#margin-properties
+    marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
+    marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
+    marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
+    marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
+}
+
+void Document::setIsViewSource(bool isViewSource)
+{
+    m_isViewSource = isViewSource;
+    if (!m_isViewSource)
+        return;
+
+    setSecurityOrigin(SecurityOrigin::createUnique());
+    didUpdateSecurityOrigin();
+}
+
+bool Document::dirtyElementsForLayerUpdate()
+{
+    if (m_layerUpdateSVGFilterElements.isEmpty())
+        return false;
+
+    for (WillBeHeapHashSet<RawPtrWillBeMember<Element> >::iterator it = m_layerUpdateSVGFilterElements.begin(), end = m_layerUpdateSVGFilterElements.end(); it != end; ++it)
+        (*it)->setNeedsStyleRecalc(LocalStyleChange);
+    m_layerUpdateSVGFilterElements.clear();
+    return true;
+}
+
+void Document::scheduleSVGFilterLayerUpdateHack(Element& element)
+{
+    if (element.styleChangeType() == NeedsReattachStyleChange)
+        return;
+    element.setSVGFilterNeedsLayerUpdate();
+    m_layerUpdateSVGFilterElements.add(&element);
+    scheduleRenderTreeUpdateIfNeeded();
+}
+
+void Document::unscheduleSVGFilterLayerUpdateHack(Element& element)
+{
+    element.clearSVGFilterNeedsLayerUpdate();
+    m_layerUpdateSVGFilterElements.remove(&element);
+}
+
+void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
+{
+    m_useElementsNeedingUpdate.add(&element);
+    scheduleRenderTreeUpdateIfNeeded();
+}
+
+void Document::unscheduleUseShadowTreeUpdate(SVGUseElement& element)
+{
+    m_useElementsNeedingUpdate.remove(&element);
 }
 
-void Document::setIsViewSource(bool isViewSource)
+void Document::updateUseShadowTreesIfNeeded()
 {
-    m_isViewSource = isViewSource;
-    if (!m_isViewSource)
+    ScriptForbiddenScope forbidScript;
+
+    if (m_useElementsNeedingUpdate.isEmpty())
         return;
 
-    setSecurityOrigin(SecurityOrigin::createUnique());
-    didUpdateSecurityOrigin();
+    WillBeHeapVector<RawPtrWillBeMember<SVGUseElement> > elements;
+    copyToVector(m_useElementsNeedingUpdate, elements);
+    m_useElementsNeedingUpdate.clear();
+
+    for (WillBeHeapVector<RawPtrWillBeMember<SVGUseElement> >::iterator it = elements.begin(), end = elements.end(); it != end; ++it)
+        (*it)->buildPendingResource();
+}
+
+StyleResolver* Document::styleResolver() const
+{
+    return m_styleEngine->resolver();
 }
 
-void Document::createStyleResolver()
+StyleResolver& Document::ensureStyleResolver() const
 {
-    bool matchAuthorAndUserStyles = true;
-    if (Settings* docSettings = settings())
-        matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
-    m_styleResolver = adoptPtr(new StyleResolver(*this, matchAuthorAndUserStyles));
-    m_styleEngine->combineCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
+    return m_styleEngine->ensureResolver();
 }
 
 void Document::clearStyleResolver()
 {
-    m_styleResolver.clear();
+    m_styleEngine->clearResolver();
 }
 
 void Document::attach(const AttachContext& context)
 {
-    ASSERT(m_lifecyle.state() == DocumentLifecycle::Inactive);
-    ASSERT(!m_axObjectCache || this != topDocument());
+    ASSERT(m_lifecycle.state() == DocumentLifecycle::Inactive);
+    ASSERT(!m_axObjectCache || this != &axObjectCacheOwner());
 
     m_renderView = new RenderView(this);
     setRenderer(m_renderView);
 
     m_renderView->setIsInWindow(true);
     m_renderView->setStyle(StyleResolver::styleForDocument(*this));
-    view()->updateCompositingLayersAfterStyleChange();
-
-    m_styleResolverThrowawayTimer.startRepeating(60);
+    m_renderView->compositor()->setNeedsCompositingUpdate(CompositingUpdateAfterCompositingInputChange);
 
     ContainerNode::attach(context);
 
-    m_lifecyle.advanceTo(DocumentLifecycle::Active);
+    // The TextAutosizer can't update render view info while the Document is detached, so update now in case anything changed.
+    if (TextAutosizer* autosizer = textAutosizer())
+        autosizer->updatePageInfo();
+
+    m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
 }
 
 void Document::detach(const AttachContext& context)
 {
     ASSERT(isActive());
-    m_lifecyle.advanceTo(DocumentLifecycle::Stopping);
+    m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
 
     if (page())
         page()->documentDetached(this);
+    InspectorInstrumentation::documentDetached(this);
+
+    if (m_frame->loader().client()->sharedWorkerRepositoryClient())
+        m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
 
-    if (this == topDocument())
+    if (this == &axObjectCacheOwner())
         clearAXObjectCache();
 
     stopActiveDOMObjects();
@@ -1984,71 +2168,87 @@ void Document::detach(const AttachContext& context)
     m_scriptedAnimationController.clear();
 
     if (svgExtensions())
-        accessSVGExtensions()->pauseAnimations();
+        accessSVGExtensions().pauseAnimations();
 
-    m_renderView->setIsInWindow(false);
+    // FIXME: This shouldn't be needed once LocalDOMWindow becomes ExecutionContext.
+    if (m_domWindow)
+        m_domWindow->clearEventQueue();
+
+    if (m_renderView)
+        m_renderView->setIsInWindow(false);
 
-    // FIXME: How can the frame be null here?
     if (m_frame) {
-        if (FrameView* view = m_frame->view())
+        FrameView* view = m_frame->view();
+        if (view)
             view->detachCustomScrollbars();
     }
 
-    m_hoverNode = 0;
-    m_focusedElement = 0;
-    m_activeElement = 0;
-
-    m_styleResolverThrowawayTimer.stop();
+    m_hoverNode = nullptr;
+    m_focusedElement = nullptr;
+    m_activeHoverElement = nullptr;
+    m_autofocusElement = nullptr;
 
+    m_renderView = 0;
     ContainerNode::detach(context);
 
-    unscheduleStyleRecalc();
-
-    clearStyleResolver();
+    m_styleEngine->didDetach();
 
-    if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
-        parentDocument()->didRemoveEventTargetNode(this);
+    frameHost()->eventHandlerRegistry().documentDetached(*this);
 
-    // This is required, as our Frame might delete itself as soon as it detaches
+    // This is required, as our LocalFrame might delete itself as soon as it detaches
     // us. However, this violates Node::detach() semantics, as it's never
     // possible to re-attach. Eventually Document::detach() should be renamed,
     // or this setting of the frame to 0 could be made explicit in each of the
     // callers of Document::detach().
-    m_frame = 0;
+    m_frame = nullptr;
 
     if (m_mediaQueryMatcher)
-        m_mediaQueryMatcher->documentDestroyed();
+        m_mediaQueryMatcher->documentDetached();
 
     lifecycleNotifier().notifyDocumentWasDetached();
-    m_lifecyle.advanceTo(DocumentLifecycle::Stopped);
+    m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
+#if ENABLE(OILPAN)
+    // Done with the window, explicitly clear to hasten its
+    // destruction.
+    clearDOMWindow();
+#endif
 }
 
 void Document::prepareForDestruction()
 {
+    m_markers->prepareForDestruction();
     disconnectDescendantFrames();
 
     // The process of disconnecting descendant frames could have already detached us.
     if (!isActive())
         return;
 
-    if (DOMWindow* window = this->domWindow())
+    if (LocalDOMWindow* window = this->domWindow())
         window->willDetachDocumentFromFrame();
     detach();
 }
 
 void Document::removeAllEventListeners()
 {
-    EventTarget::removeAllEventListeners();
+    ContainerNode::removeAllEventListeners();
 
-    if (DOMWindow* domWindow = this->domWindow())
+    if (LocalDOMWindow* domWindow = this->domWindow())
         domWindow->removeAllEventListeners();
-    for (Node* node = firstChild(); node; node = NodeTraversal::next(node))
-        node->removeAllEventListeners();
+}
+
+Document& Document::axObjectCacheOwner() const
+{
+    Document& top = topDocument();
+    if (top.frame() && top.frame()->pagePopupOwner()) {
+        ASSERT(!top.m_axObjectCache);
+        return top.frame()->pagePopupOwner()->document().axObjectCacheOwner();
+    }
+    return top;
 }
 
 void Document::clearAXObjectCache()
 {
-    ASSERT(topDocument() == this);
+    ASSERT(&axObjectCacheOwner() == this);
     // Clear the cache member variable before calling delete because attempts
     // are made to access it during destruction.
     m_axObjectCache.clear();
@@ -2056,63 +2256,51 @@ void Document::clearAXObjectCache()
 
 AXObjectCache* Document::existingAXObjectCache() const
 {
-    if (!AXObjectCache::accessibilityEnabled())
-        return 0;
-
     // If the renderer is gone then we are in the process of destruction.
-    // This method will be called before m_frame = 0.
-    if (!topDocument()->isActive())
+    // This method will be called before m_frame = nullptr.
+    if (!axObjectCacheOwner().renderView())
         return 0;
 
-    return topDocument()->m_axObjectCache.get();
+    return axObjectCacheOwner().m_axObjectCache.get();
 }
 
 AXObjectCache* Document::axObjectCache() const
 {
-    if (!AXObjectCache::accessibilityEnabled())
+    Settings* settings = this->settings();
+    if (!settings || !settings->accessibilityEnabled())
         return 0;
 
     // The only document that actually has a AXObjectCache is the top-level
     // document.  This is because we need to be able to get from any WebCoreAXObject
     // to any other WebCoreAXObject on the same page.  Using a single cache allows
     // lookups across nested webareas (i.e. multiple documents).
-    Document* topDocument = this->topDocument();
+    Document& cacheOwner = this->axObjectCacheOwner();
 
     // If the document has already been detached, do not make a new axObjectCache.
-    if (!topDocument->isActive())
+    if (!cacheOwner.renderView())
         return 0;
 
-    ASSERT(topDocument == this || !m_axObjectCache);
-    if (!topDocument->m_axObjectCache)
-        topDocument->m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
-    return topDocument->m_axObjectCache.get();
+    ASSERT(&cacheOwner == this || !m_axObjectCache);
+    if (!cacheOwner.m_axObjectCache)
+        cacheOwner.m_axObjectCache = adoptPtr(new AXObjectCache(cacheOwner));
+    return cacheOwner.m_axObjectCache.get();
 }
 
-void Document::setVisuallyOrdered()
-{
-    m_visuallyOrdered = true;
-    // FIXME: How is possible to not have a renderer here?
-    if (renderView())
-        renderView()->style()->setRTLOrdering(VisualOrder);
-    setNeedsStyleRecalc();
-}
-
-PassRefPtr<DocumentParser> Document::createParser()
+PassRefPtrWillBeRawPtr<DocumentParser> Document::createParser()
 {
     if (isHTMLDocument()) {
-        bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(this->page());
-        return HTMLDocumentParser::create(toHTMLDocument(this), reportErrors);
+        bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(page());
+        return HTMLDocumentParser::create(toHTMLDocument(*this), reportErrors);
     }
     // FIXME: this should probably pass the frame instead
-    return XMLDocumentParser::create(this, view());
+    return XMLDocumentParser::create(*this, view());
 }
 
 bool Document::isFrameSet() const
 {
     if (!isHTMLDocument())
         return false;
-    HTMLElement* bodyElement = body();
-    return bodyElement && bodyElement->hasTagName(framesetTag);
+    return isHTMLFrameSetElement(body());
 }
 
 ScriptableDocumentParser* Document::scriptableDocumentParser() const
@@ -2120,13 +2308,17 @@ ScriptableDocumentParser* Document::scriptableDocumentParser() const
     return parser() ? parser()->asScriptableDocumentParser() : 0;
 }
 
-void Document::open(Document* ownerDocument)
+void Document::open(Document* ownerDocument, ExceptionState& exceptionState)
 {
+    if (importLoader()) {
+        exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support open().");
+        return;
+    }
+
     if (ownerDocument) {
         setURL(ownerDocument->url());
         m_cookieURL = ownerDocument->cookieURL();
         setSecurityOrigin(ownerDocument->securityOrigin());
-        InspectorInstrumentation::childDocumentOpened(this);
     }
 
     if (m_frame) {
@@ -2145,7 +2337,7 @@ void Document::open(Document* ownerDocument)
             m_frame->loader().stopAllLoaders();
     }
 
-    removeAllEventListeners();
+    removeAllEventListenersRecursively();
     implicitOpen();
     if (ScriptableDocumentParser* parser = scriptableDocumentParser())
         parser->setWasCreatedByScript(true);
@@ -2177,7 +2369,7 @@ void Document::cancelParsing()
     explicitClose();
 }
 
-PassRefPtr<DocumentParser> Document::implicitOpen()
+PassRefPtrWillBeRawPtr<DocumentParser> Document::implicitOpen()
 {
     cancelParsing();
 
@@ -2186,12 +2378,6 @@ PassRefPtr<DocumentParser> Document::implicitOpen()
 
     setCompatibilityMode(NoQuirksMode);
 
-    // Documents rendered seamlessly should start out requiring a stylesheet
-    // collection update in order to ensure they inherit all the relevant data
-    // from their parent.
-    if (shouldDisplaySeamlesslyWithParent())
-        styleResolverChanged(RecalcStyleDeferred);
-
     m_parser = createParser();
     setParsing(true);
     setReadyState(Loading);
@@ -2204,25 +2390,29 @@ HTMLElement* Document::body() const
     if (!documentElement())
         return 0;
 
-    for (Node* child = documentElement()->firstChild(); child; child = child->nextSibling()) {
-        if (child->hasTagName(framesetTag) || child->hasTagName(bodyTag))
-            return toHTMLElement(child);
+    for (HTMLElement* child = Traversal<HTMLElement>::firstChild(*documentElement()); child; child = Traversal<HTMLElement>::nextSibling(*child)) {
+        if (isHTMLFrameSetElement(*child) || isHTMLBodyElement(*child))
+            return child;
     }
 
     return 0;
 }
 
-void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& es)
+void Document::setBody(PassRefPtrWillBeRawPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
 {
-    RefPtr<HTMLElement> newBody = prpNewBody;
+    RefPtrWillBeRawPtr<HTMLElement> newBody = prpNewBody;
 
-    if (!newBody || !documentElement()) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+    if (!newBody) {
+        exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::argumentNullOrIncorrectType(1, "HTMLElement"));
+        return;
+    }
+    if (!documentElement()) {
+        exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
         return;
     }
 
-    if (!newBody->hasTagName(bodyTag) && !newBody->hasTagName(framesetTag)) {
-        es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+    if (!isHTMLBodyElement(*newBody) && !isHTMLFrameSetElement(*newBody)) {
+        exceptionState.throwDOMException(HierarchyRequestError, "The new body element is of type '" + newBody->tagName() + "'. It must be either a 'BODY' or 'FRAMESET' element.");
         return;
     }
 
@@ -2231,29 +2421,52 @@ void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& es)
         return;
 
     if (oldBody)
-        documentElement()->replaceChild(newBody.release(), oldBody, es);
+        documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
     else
-        documentElement()->appendChild(newBody.release(), es);
+        documentElement()->appendChild(newBody.release(), exceptionState);
 }
 
-HTMLHeadElement* Document::head()
+HTMLHeadElement* Document::head() const
 {
     Node* de = documentElement();
     if (!de)
         return 0;
 
-    for (Node* node = de->firstChild(); node; node = node->nextSibling()) {
-        if (node->hasTagName(headTag))
-            return toHTMLHeadElement(node);
+    return Traversal<HTMLHeadElement>::firstChild(*de);
+}
+
+Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
+{
+    // If a BODY element sets non-visible overflow, it is to be propagated to the viewport, as long
+    // as the following conditions are all met:
+    // (1) The root element is HTML.
+    // (2) It is the primary BODY element (we only assert for this, expecting callers to behave).
+    // (3) The root element has visible overflow.
+    // Otherwise it's the root element's properties that are to be propagated.
+    Element* rootElement = documentElement();
+    Element* bodyElement = body();
+    if (!rootElement)
+        return 0;
+    if (!rootStyle) {
+        rootStyle = rootElement->renderStyle();
+        if (!rootStyle)
+            return 0;
     }
-    return 0;
+    if (bodyElement && rootStyle->isOverflowVisible() && isHTMLHtmlElement(*rootElement))
+        return bodyElement;
+    return rootElement;
 }
 
-void Document::close()
+void Document::close(ExceptionState& exceptionState)
 {
     // FIXME: We should follow the specification more closely:
     //        http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
 
+    if (importLoader()) {
+        exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support close().");
+        return;
+    }
+
     if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
         return;
 
@@ -2262,7 +2475,7 @@ void Document::close()
 
 void Document::explicitClose()
 {
-    if (RefPtr<DocumentParser> parser = m_parser)
+    if (RefPtrWillBeRawPtr<DocumentParser> parser = m_parser)
         parser->finish();
 
     if (!m_frame) {
@@ -2279,20 +2492,14 @@ void Document::explicitClose()
 void Document::implicitClose()
 {
     ASSERT(!inStyleRecalc());
-
-    bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
-    bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
-
-    // If the load was blocked because of a pending location change and the location change triggers a same document
-    // navigation, don't fire load events after the same document navigation completes (unless there's an explicit open).
-    m_loadEventProgress = LoadEventTried;
-
-    if (!doload)
+    if (processingLoadEvent() || !m_parser)
+        return;
+    if (frame() && frame()->navigationScheduler().locationChangePending())
         return;
 
-    // The call to dispatchWindowLoadEvent can detach the DOMWindow and cause it (and its
+    // The call to dispatchWindowLoadEvent can detach the LocalDOMWindow and cause it (and its
     // attached Document) to be destroyed.
-    RefPtr<DOMWindow> protectedWindow(this->domWindow());
+    RefPtrWillBeRawPtr<LocalDOMWindow> protectedWindow(this->domWindow());
 
     m_loadEventProgress = LoadEventInProgress;
 
@@ -2303,9 +2510,7 @@ void Document::implicitClose()
     // onLoad event handler, as in Radar 3206524.
     detachParser();
 
-    Frame* f = frame();
-    if (f && f->script().canExecuteScripts(NotAboutToExecuteScript)) {
-        ImageLoader::dispatchPendingBeforeLoadEvents();
+    if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
         ImageLoader::dispatchPendingLoadEvents();
         ImageLoader::dispatchPendingErrorEvents();
 
@@ -2313,11 +2518,13 @@ void Document::implicitClose()
         HTMLStyleElement::dispatchPendingLoadEvents();
     }
 
+    // JS running below could remove the frame or destroy the RenderView so we call
+    // those two functions repeatedly and don't save them on the stack.
+
     // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
-    // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
-    // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
+    // here, instead of doing it from SVGElement::finishedParsingChildren.
     if (svgExtensions())
-        accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
+        accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
 
     if (protectedWindow)
         protectedWindow->documentWasClosed();
@@ -2327,7 +2534,6 @@ void Document::implicitClose()
         loader()->applicationCacheHost()->stopDeferringEvents();
     }
 
-    // An event handler may have removed the frame
     if (!frame()) {
         m_loadEventProgress = LoadEventCompleted;
         return;
@@ -2341,45 +2547,41 @@ void Document::implicitClose()
         // Just bail out. Before or during the onload we were shifted to another page.
         // The old i-Bench suite does this. When this happens don't bother painting or laying out.
         m_loadEventProgress = LoadEventCompleted;
-        view()->unscheduleRelayout();
         return;
     }
 
-    RenderView* renderView = this->renderView();
-
     // We used to force a synchronous display and flush here.  This really isn't
     // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
     // (if your platform is syncing flushes and limiting them to 60fps).
-    m_overMinimumLayoutThreshold = true;
     if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
-        updateStyleIfNeeded();
+        updateRenderTreeIfNeeded();
 
         // Always do a layout after loading if needed.
-        if (view() && renderView && (!renderView->firstChild() || renderView->needsLayout()))
+        if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
             view()->layout();
     }
 
     m_loadEventProgress = LoadEventCompleted;
 
-    if (f && renderView && AXObjectCache::accessibilityEnabled()) {
+    if (frame() && renderView() && settings()->accessibilityEnabled()) {
         // The AX cache may have been cleared at this point, but we need to make sure it contains an
         // AX object to send the notification to. getOrCreate will make sure that an valid AX object
         // exists in the cache (we ignore the return value because we don't need it here). This is
         // only safe to call when a layout is not in progress, so it can not be used in postNotification.
         if (AXObjectCache* cache = axObjectCache()) {
-            cache->getOrCreate(renderView);
-            if (this == topDocument()) {
-                cache->postNotification(renderView, AXObjectCache::AXLoadComplete, true);
+            cache->getOrCreate(renderView());
+            if (this == &axObjectCacheOwner()) {
+                cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
             } else {
                 // AXLoadComplete can only be posted on the top document, so if it's a document
                 // in an iframe that just finished loading, post AXLayoutComplete instead.
-                cache->postNotification(renderView, AXObjectCache::AXLayoutComplete, true);
+                cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
             }
         }
     }
 
     if (svgExtensions())
-        accessSVGExtensions()->startAnimations();
+        accessSVGExtensions().startAnimations();
 }
 
 bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigation)
@@ -2390,9 +2592,9 @@ bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigatio
     if (!body())
         return true;
 
-    RefPtr<Document> protect(this);
+    RefPtrWillBeRawPtr<Document> protect(this);
 
-    RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
+    RefPtrWillBeRawPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
     m_loadEventProgress = BeforeUnloadEventInProgress;
     m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
     m_loadEventProgress = BeforeUnloadEventCompleted;
@@ -2402,7 +2604,7 @@ bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigatio
         return true;
 
     if (didAllowNavigation) {
-        addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
+        addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation."));
         return true;
     }
 
@@ -2416,17 +2618,20 @@ bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigatio
 
 void Document::dispatchUnloadEvents()
 {
-    RefPtr<Document> protect(this);
+    RefPtrWillBeRawPtr<Document> protect(this);
     if (m_parser)
         m_parser->stopParsing();
 
-    if (m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress) {
+    if (m_loadEventProgress == LoadEventNotRun)
+        return;
+
+    if (m_loadEventProgress <= UnloadEventInProgress) {
         Element* currentFocusedElement = focusedElement();
-        if (currentFocusedElement && currentFocusedElement->hasTagName(inputTag))
-            toHTMLInputElement(currentFocusedElement)->endEditing();
+        if (isHTMLInputElement(currentFocusedElement))
+            toHTMLInputElement(*currentFocusedElement).endEditing();
         if (m_loadEventProgress < PageHideInProgress) {
             m_loadEventProgress = PageHideInProgress;
-            if (DOMWindow* window = domWindow())
+            if (LocalDOMWindow* window = domWindow())
                 window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
             if (!m_frame)
                 return;
@@ -2436,7 +2641,7 @@ void Document::dispatchUnloadEvents()
             // time into freed memory.
             RefPtr<DocumentLoader> documentLoader =  m_frame->loader().provisionalDocumentLoader();
             m_loadEventProgress = UnloadEventInProgress;
-            RefPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
+            RefPtrWillBeRawPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
             if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
                 DocumentLoadTiming* timing = documentLoader->timing();
                 ASSERT(timing->navigationStart());
@@ -2447,7 +2652,6 @@ void Document::dispatchUnloadEvents()
                 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
             }
         }
-        updateStyleIfNeeded();
         m_loadEventProgress = UnloadEventHandled;
     }
 
@@ -2458,7 +2662,7 @@ void Document::dispatchUnloadEvents()
     bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
         && isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
     if (!keepEventListeners)
-        removeAllEventListeners();
+        removeAllEventListenersRecursively();
 }
 
 Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
@@ -2474,42 +2678,29 @@ Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
 
 void Document::setParsing(bool b)
 {
-    m_bParsing = b;
+    m_isParsing = b;
 
-    if (m_bParsing && !m_sharedObjectPool)
-        m_sharedObjectPool = DocumentSharedObjectPool::create();
-
-    if (!m_bParsing && view())
-        view()->scheduleRelayout();
+    if (m_isParsing && !m_elementDataCache)
+        m_elementDataCache = ElementDataCache::create();
 }
 
-bool Document::shouldScheduleLayout()
+bool Document::shouldScheduleLayout() const
 {
     // This function will only be called when FrameView thinks a layout is needed.
     // This enforces a couple extra rules.
     //
     //    (a) Only schedule a layout once the stylesheets are loaded.
     //    (b) Only schedule layout once we have a body element.
+    if (!isActive())
+        return false;
 
-    return (haveStylesheetsLoaded() && body())
-        || (documentElement() && !isHTMLHtmlElement(documentElement()));
-}
-
-bool Document::shouldParserYieldAgressivelyBeforeScriptExecution()
-{
-    return view() && view()->layoutPending() && !minimumLayoutDelay();
-}
-
-int Document::minimumLayoutDelay()
-{
-    if (m_overMinimumLayoutThreshold)
-        return 0;
+    if (isRenderingReady() && body())
+        return true;
 
-    int elapsed = elapsedTime();
-    m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
+    if (documentElement() && !isHTMLHtmlElement(*documentElement()))
+        return true;
 
-    // We'll want to schedule the timer to fire at the minimum layout threshold.
-    return max(0, cLayoutScheduleThreshold - elapsed);
+    return false;
 }
 
 int Document::elapsedTime() const
@@ -2517,8 +2708,13 @@ int Document::elapsedTime() const
     return static_cast<int>((currentTime() - m_startTime) * 1000);
 }
 
-void Document::write(const SegmentedString& text, Document* ownerDocument)
+void Document::write(const SegmentedString& text, Document* ownerDocument, ExceptionState& exceptionState)
 {
+    if (importLoader()) {
+        exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support write().");
+        return;
+    }
+
     NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
 
     m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
@@ -2528,8 +2724,11 @@ void Document::write(const SegmentedString& text, Document* ownerDocument)
        return;
 
     bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
-    if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
+
+    if (!hasInsertionPoint && m_ignoreDestructiveWriteCount) {
+        addConsoleMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, ExceptionMessages::failedToExecute("write", "Document", "It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.")));
         return;
+    }
 
     if (!hasInsertionPoint)
         open(ownerDocument);
@@ -2538,14 +2737,16 @@ void Document::write(const SegmentedString& text, Document* ownerDocument)
     m_parser->insert(text);
 }
 
-void Document::write(const String& text, Document* ownerDocument)
+void Document::write(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
 {
-    write(SegmentedString(text), ownerDocument);
+    write(SegmentedString(text), ownerDocument, exceptionState);
 }
 
-void Document::writeln(const String& text, Document* ownerDocument)
+void Document::writeln(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
 {
-    write(text, ownerDocument);
+    write(text, ownerDocument, exceptionState);
+    if (exceptionState.hadException())
+        return;
     write("\n", ownerDocument);
 }
 
@@ -2572,9 +2773,12 @@ EventTarget* Document::errorEventTarget()
     return domWindow();
 }
 
-void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
+void Document::logExceptionToConsole(const String& errorMessage, int scriptId, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtrWillBeRawPtr<ScriptCallStack> callStack)
 {
-    internalAddMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack, 0);
+    RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber);
+    consoleMessage->setScriptId(scriptId);
+    consoleMessage->setCallStack(callStack);
+    addConsoleMessage(consoleMessage.release());
 }
 
 void Document::setURL(const KURL& url)
@@ -2584,9 +2788,8 @@ void Document::setURL(const KURL& url)
         return;
 
     m_url = newURL;
-    m_documentURI = m_url.string();
     updateBaseURL();
-    contextFeatures()->urlDidChange(this);
+    contextFeatures().urlDidChange(this);
 }
 
 void Document::updateBaseURL()
@@ -2594,18 +2797,14 @@ void Document::updateBaseURL()
     KURL oldBaseURL = m_baseURL;
     // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
     // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
-    // from the Document interface otherwise.
+    // from the Document interface otherwise (which we store, preparsed, in m_url).
     if (!m_baseElementURL.isEmpty())
         m_baseURL = m_baseElementURL;
     else if (!m_baseURLOverride.isEmpty())
         m_baseURL = m_baseURLOverride;
-    else {
-        // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
-        // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
-        // and DOM 3 Core does not specify how it should be resolved.
-        // FIXME: Now that we don't support Objective-C this can probably be removed.
-        m_baseURL = KURL(ParsedURLString, documentURI());
-    }
+    else
+        m_baseURL = m_url;
+
     selectorQueryCache().invalidate();
 
     if (!m_baseURL.isValid())
@@ -2623,10 +2822,8 @@ void Document::updateBaseURL()
     if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
         // Base URL change changes any relative visited links.
         // FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
-        for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element)) {
-            if (isHTMLAnchorElement(element))
-                toHTMLAnchorElement(element)->invalidateCachedVisitedLinkHash();
-        }
+        for (HTMLAnchorElement* anchor = Traversal<HTMLAnchorElement>::firstWithin(*this); anchor; anchor = Traversal<HTMLAnchorElement>::next(*anchor))
+            anchor->invalidateCachedVisitedLinkHash();
     }
 }
 
@@ -2641,21 +2838,19 @@ void Document::processBaseElement()
     // Find the first href attribute in a base element and the first target attribute in a base element.
     const AtomicString* href = 0;
     const AtomicString* target = 0;
-    for (Element* element = ElementTraversal::firstWithin(this); element && (!href || !target); element = ElementTraversal::next(element)) {
-        if (element->hasTagName(baseTag)) {
-            if (!href) {
-                const AtomicString& value = element->fastGetAttribute(hrefAttr);
-                if (!value.isNull())
-                    href = &value;
-            }
-            if (!target) {
-                const AtomicString& value = element->fastGetAttribute(targetAttr);
-                if (!value.isNull())
-                    target = &value;
-            }
-            if (contentSecurityPolicy()->isActive())
-                UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
+    for (HTMLBaseElement* base = Traversal<HTMLBaseElement>::firstWithin(*this); base && (!href || !target); base = Traversal<HTMLBaseElement>::next(*base)) {
+        if (!href) {
+            const AtomicString& value = base->fastGetAttribute(hrefAttr);
+            if (!value.isNull())
+                href = &value;
+        }
+        if (!target) {
+            const AtomicString& value = base->fastGetAttribute(targetAttr);
+            if (!value.isNull())
+                target = &value;
         }
+        if (contentSecurityPolicy()->isActive())
+            UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
     }
 
     // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
@@ -2686,30 +2881,24 @@ void Document::disableEval(const String& errorMessage)
     frame()->script().disableEval(errorMessage);
 }
 
-bool Document::canNavigate(Frame* targetFrame)
+bool Document::canNavigate(const Frame& targetFrame)
 {
     if (!m_frame)
         return false;
 
-    // FIXME: We shouldn't call this function without a target frame, but
-    // fast/forms/submit-to-blank-multiple-times.html depends on this function
-    // returning true when supplied with a 0 targetFrame.
-    if (!targetFrame)
-        return true;
-
     // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
     if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
         return true;
 
     if (isSandboxed(SandboxNavigation)) {
-        if (targetFrame->tree().isDescendantOf(m_frame))
+        if (targetFrame.tree().isDescendantOf(m_frame))
             return true;
 
         const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
         if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
             reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
 
-        printNavigationErrorMessage(*targetFrame, url(), reason);
+        printNavigationErrorMessage(toLocalFrameTemporary(targetFrame), url(), reason);
         return false;
     }
 
@@ -2723,7 +2912,7 @@ bool Document::canNavigate(Frame* targetFrame)
     //
     // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
     // historical information about this security check.
-    if (canAccessAncestor(origin, targetFrame))
+    if (canAccessAncestor(origin, &targetFrame))
         return true;
 
     // Top-level frames are easier to navigate than other frames because they
@@ -2737,105 +2926,120 @@ bool Document::canNavigate(Frame* targetFrame)
     // some way related to the frame being navigate (e.g., by the "opener"
     // and/or "parent" relation). Requiring some sort of relation prevents a
     // document from navigating arbitrary, unrelated top-level frames.
-    if (!targetFrame->tree().parent()) {
+    if (!targetFrame.tree().parent()) {
         if (targetFrame == m_frame->loader().opener())
             return true;
 
-        if (canAccessAncestor(origin, targetFrame->loader().opener()))
+        // FIXME: We don't have access to RemoteFrame's opener yet.
+        if (targetFrame.isLocalFrame() && canAccessAncestor(origin, toLocalFrame(targetFrame).loader().opener()))
             return true;
     }
 
-    printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
+    printNavigationErrorMessage(toLocalFrameTemporary(targetFrame), url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
     return false;
 }
 
-Frame* Document::findUnsafeParentScrollPropagationBoundary()
+LocalFrame* Document::findUnsafeParentScrollPropagationBoundary()
 {
-    Frame* currentFrame = m_frame;
+    LocalFrame* currentFrame = m_frame;
     Frame* ancestorFrame = currentFrame->tree().parent();
 
     while (ancestorFrame) {
-        if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
+        // FIXME: We don't yet have access to a RemoteFrame's security origin.
+        if (!ancestorFrame->isLocalFrame())
+            return currentFrame;
+        if (!toLocalFrame(ancestorFrame)->document()->securityOrigin()->canAccess(securityOrigin()))
             return currentFrame;
-        currentFrame = ancestorFrame;
+        currentFrame = toLocalFrame(ancestorFrame);
         ancestorFrame = ancestorFrame->tree().parent();
     }
     return 0;
 }
 
-
-void Document::seamlessParentUpdatedStylesheets()
+void Document::didLoadAllImports()
 {
-    m_styleEngine->didModifySeamlessParentStyleSheet();
-    styleResolverChanged(RecalcStyleImmediately);
+    if (!haveStylesheetsLoaded())
+        return;
+    if (!importLoader())
+        styleResolverMayHaveChanged();
+    didLoadAllScriptBlockingResources();
 }
 
 void Document::didRemoveAllPendingStylesheet()
 {
-    m_needsNotifyRemoveAllPendingStylesheet = false;
+    styleResolverMayHaveChanged();
+
+    // Only imports on master documents can trigger rendering.
+    if (HTMLImportLoader* import = importLoader())
+        import->didRemoveAllPendingStylesheet();
+    if (!haveImportsLoaded())
+        return;
+    didLoadAllScriptBlockingResources();
+}
+
+void Document::didLoadAllScriptBlockingResources()
+{
+    m_executeScriptsWaitingForResourcesTimer.startOneShot(0, FROM_HERE);
 
-    styleResolverChanged(RecalcStyleDeferred, AnalyzedStyleUpdate);
-    executeScriptsWaitingForResourcesIfNeeded();
+    if (frame())
+        frame()->loader().client()->didRemoveAllPendingStylesheet();
 
     if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
         view()->scrollToFragment(m_url);
 }
 
-void Document::executeScriptsWaitingForResourcesIfNeeded()
+void Document::executeScriptsWaitingForResourcesTimerFired(Timer<Document>*)
 {
-    if (!haveStylesheetsAndImportsLoaded())
+    if (!isRenderingReady())
         return;
     if (ScriptableDocumentParser* parser = scriptableDocumentParser())
         parser->executeScriptsWaitingForResources();
 }
 
-
-CSSStyleSheet* Document::elementSheet()
+CSSStyleSheet& Document::elementSheet()
 {
     if (!m_elemSheet)
         m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
-    return m_elemSheet.get();
+    return *m_elemSheet;
 }
 
-void Document::processHttpEquiv(const String& equiv, const String& content)
+void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement)
 {
     ASSERT(!equiv.isNull() && !content.isNull());
 
-    if (equalIgnoringCase(equiv, "default-style"))
+    if (equalIgnoringCase(equiv, "default-style")) {
         processHttpEquivDefaultStyle(content);
-    else if (equalIgnoringCase(equiv, "refresh"))
+    } else if (equalIgnoringCase(equiv, "refresh")) {
         processHttpEquivRefresh(content);
-    else if (equalIgnoringCase(equiv, "set-cookie"))
+    } else if (equalIgnoringCase(equiv, "set-cookie")) {
         processHttpEquivSetCookie(content);
-    else if (equalIgnoringCase(equiv, "content-language"))
+    } else if (equalIgnoringCase(equiv, "content-language")) {
         setContentLanguage(content);
-    else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
+    } else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) {
         parseDNSPrefetchControlHeader(content);
-    else if (equalIgnoringCase(equiv, "x-frame-options"))
+    } else if (equalIgnoringCase(equiv, "x-frame-options")) {
         processHttpEquivXFrameOptions(content);
-    else if (equalIgnoringCase(equiv, "content-security-policy")
-        || equalIgnoringCase(equiv, "content-security-policy-report-only")
-        || equalIgnoringCase(equiv, "x-webkit-csp")
-        || equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
-        processHttpEquivContentSecurityPolicy(equiv, content);
+    } else if (equalIgnoringCase(equiv, "content-security-policy") || equalIgnoringCase(equiv, "content-security-policy-report-only")) {
+        if (inDocumentHeadElement)
+            processHttpEquivContentSecurityPolicy(equiv, content);
+        else
+            contentSecurityPolicy()->reportMetaOutsideHead(content);
+    }
 }
 
-void Document::processHttpEquivContentSecurityPolicy(const String& equiv, const String& content)
+void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
 {
+    if (importLoader())
+        return;
     if (equalIgnoringCase(equiv, "content-security-policy"))
-        contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
+        contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceMeta);
     else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
-        contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
-    // FIXME: Remove deprecation messages after the next release branch.
-    else if (equalIgnoringCase(equiv, "x-webkit-csp"))
-        UseCounter::countDeprecation(this, UseCounter::PrefixedContentSecurityPolicy);
-    else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
-        UseCounter::countDeprecation(this, UseCounter::PrefixedContentSecurityPolicyReportOnly);
+        contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeReport, ContentSecurityPolicyHeaderSourceMeta);
     else
         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
@@ -2845,10 +3049,10 @@ void Document::processHttpEquivDefaultStyle(const String& content)
     // -dwh
     m_styleEngine->setSelectedStylesheetSetName(content);
     m_styleEngine->setPreferredStylesheetSetName(content);
-    styleResolverChanged(RecalcStyleDeferred);
+    styleResolverChanged();
 }
 
-void Document::processHttpEquivRefresh(const String& content)
+void Document::processHttpEquivRefresh(const AtomicString& content)
 {
     maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
 }
@@ -2869,19 +3073,19 @@ void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType htt
 
     if (protocolIsJavaScript(refreshURL)) {
         String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
-        addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+        addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message));
         return;
     }
 
     if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
         String message = "Refused to execute the redirect specified via '<meta http-equiv='refresh' content='...'>'. The document is sandboxed, and the 'allow-scripts' keyword is not set.";
-        addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+        addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message));
         return;
     }
     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())
@@ -2891,9 +3095,9 @@ void Document::processHttpEquivSetCookie(const String& content)
     toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
 }
 
-void Document::processHttpEquivXFrameOptions(const String& content)
+void Document::processHttpEquivXFrameOptions(const AtomicString& content)
 {
-    Frame* frame = this->frame();
+    LocalFrame* frame = this->frame();
     if (!frame)
         return;
 
@@ -2905,8 +3109,10 @@ void Document::processHttpEquivXFrameOptions(const String& content)
         // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
         // intent, we must navigate away from the possibly partially-rendered document to a location that
         // doesn't inherit the parent's SecurityOrigin.
-        frame->navigationScheduler().scheduleLocationChange(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
-        addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
+        frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
+        RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message);
+        consoleMessage->setRequestIdentifier(requestIdentifier);
+        addConsoleMessage(consoleMessage.release());
     }
 }
 
@@ -2917,7 +3123,14 @@ bool Document::shouldMergeWithLegacyDescription(ViewportDescription::Type origin
 
 void Document::setViewportDescription(const ViewportDescription& viewportDescription)
 {
+    // The UA-defined min-width is used by the processing of legacy meta tags.
+    if (!viewportDescription.isSpecifiedByAuthor())
+        m_viewportDefaultMinWidth = viewportDescription.minWidth;
+
     if (viewportDescription.isLegacyViewportType()) {
+        if (settings() && !settings()->viewportMetaEnabled())
+            return;
+
         m_legacyViewportDescription = viewportDescription;
 
         // When no author style for @viewport is present, and a meta tag for defining
@@ -2939,11 +3152,8 @@ void Document::setViewportDescription(const ViewportDescription& viewportDescrip
 
 void Document::updateViewportDescription()
 {
-    if (page() && page()->mainFrame() == frame()) {
-#ifndef NDEBUG
-        m_didDispatchViewportPropertiesChanged = true;
-#endif
-        page()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
+    if (frame() && frame()->isMainFrame()) {
+        frameHost()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
     }
 }
 
@@ -2951,25 +3161,64 @@ void Document::processReferrerPolicy(const String& policy)
 {
     ASSERT(!policy.isNull());
 
-    m_referrerPolicy = ReferrerPolicyDefault;
+    if (equalIgnoringCase(policy, "never")) {
+        setReferrerPolicy(ReferrerPolicyNever);
+    } else if (equalIgnoringCase(policy, "always")) {
+        setReferrerPolicy(ReferrerPolicyAlways);
+    } else if (equalIgnoringCase(policy, "origin")) {
+        setReferrerPolicy(ReferrerPolicyOrigin);
+    } else if (equalIgnoringCase(policy, "default")) {
+        setReferrerPolicy(ReferrerPolicyDefault);
+    } else {
+        addConsoleMessage(ConsoleMessage::create(RenderingMessageSource, ErrorMessageLevel, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'."));
+        setReferrerPolicy(ReferrerPolicyNever);
+    }
+}
+
+void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
+{
+    // FIXME: Can we adopt the CSP referrer policy merge algorithm? Or does the web rely on being able to modify the referrer policy in-flight?
+    if (m_didSetReferrerPolicy)
+        UseCounter::count(this, UseCounter::ResetReferrerPolicy);
+    m_didSetReferrerPolicy = true;
+
+    m_referrerPolicy = referrerPolicy;
+}
+
+String Document::outgoingReferrer()
+{
+    // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
+    // for why we walk the parent chain for srcdoc documents.
+    Document* referrerDocument = this;
+    if (LocalFrame* frame = m_frame) {
+        while (frame->document()->isSrcdocDocument()) {
+            // Srcdoc documents must be local within the containing frame.
+            frame = toLocalFrame(frame->tree().parent());
+            // Srcdoc documents cannot be top-level documents, by definition,
+            // because they need to be contained in iframes with the srcdoc.
+            ASSERT(frame);
+        }
+        referrerDocument = frame->document();
+    }
+    return referrerDocument->m_url.strippedForUseAsReferrer();
+}
 
-    if (equalIgnoringCase(policy, "never"))
-        m_referrerPolicy = ReferrerPolicyNever;
-    else if (equalIgnoringCase(policy, "always"))
-        m_referrerPolicy = ReferrerPolicyAlways;
-    else if (equalIgnoringCase(policy, "origin"))
-        m_referrerPolicy = ReferrerPolicyOrigin;
+String Document::outgoingOrigin() const
+{
+    return securityOrigin()->toString();
 }
 
 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
 {
+    ASSERT(!renderView() || renderView()->isRenderView());
+
     // RenderView::hitTest causes a layout, and we don't want to hit that until the first
     // layout because until then, there is nothing shown on the screen - the user can't
     // have intentionally clicked on something belonging to this page. Furthermore,
     // mousemove events before the first layout should not lead to a premature layout()
     // happening, which could show a flash of white.
     // See also the similar code in EventHandler::hitTestResultAtPoint.
-    if (!isActive() || !view() || !view()->didFirstLayout())
+    if (!renderView() || !view() || !view()->didFirstLayout())
         return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
 
     HitTestResult result(documentPoint);
@@ -2989,10 +3238,7 @@ bool Document::childTypeAllowed(NodeType type) const
     case CDATA_SECTION_NODE:
     case DOCUMENT_FRAGMENT_NODE:
     case DOCUMENT_NODE:
-    case ENTITY_NODE:
-    case NOTATION_NODE:
     case TEXT_NODE:
-    case XPATH_NAMESPACE_NODE:
         return false;
     case COMMENT_NODE:
     case PROCESSING_INSTRUCTION_NODE:
@@ -3009,7 +3255,7 @@ bool Document::childTypeAllowed(NodeType type) const
     return false;
 }
 
-bool Document::canReplaceChild(Node& newChild, Node& oldChild)
+bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
 {
     if (oldChild.nodeType() == newChild.nodeType())
         return true;
@@ -3036,17 +3282,14 @@ bool Document::canReplaceChild(Node& newChild, Node& oldChild)
     }
 
     // Then, see how many doctypes and elements might be added by the new child.
-    if (newChild.nodeType() == DOCUMENT_FRAGMENT_NODE) {
-        for (Node* c = newChild.firstChild(); c; c = c->nextSibling()) {
+    if (newChild.isDocumentFragment()) {
+        for (Node* c = toDocumentFragment(newChild).firstChild(); c; c = c->nextSibling()) {
             switch (c->nodeType()) {
             case ATTRIBUTE_NODE:
             case CDATA_SECTION_NODE:
             case DOCUMENT_FRAGMENT_NODE:
             case DOCUMENT_NODE:
-            case ENTITY_NODE:
-            case NOTATION_NODE:
             case TEXT_NODE:
-            case XPATH_NAMESPACE_NODE:
                 return false;
             case COMMENT_NODE:
             case PROCESSING_INSTRUCTION_NODE:
@@ -3065,10 +3308,7 @@ bool Document::canReplaceChild(Node& newChild, Node& oldChild)
         case CDATA_SECTION_NODE:
         case DOCUMENT_FRAGMENT_NODE:
         case DOCUMENT_NODE:
-        case ENTITY_NODE:
-        case NOTATION_NODE:
         case TEXT_NODE:
-        case XPATH_NAMESPACE_NODE:
             return false;
         case COMMENT_NODE:
         case PROCESSING_INSTRUCTION_NODE:
@@ -3088,29 +3328,33 @@ bool Document::canReplaceChild(Node& newChild, Node& oldChild)
     return true;
 }
 
-PassRefPtr<Node> Document::cloneNode(bool deep)
+PassRefPtrWillBeRawPtr<Node> Document::cloneNode(bool deep)
 {
-    RefPtr<Document> clone = cloneDocumentWithoutChildren();
+    RefPtrWillBeRawPtr<Document> clone = cloneDocumentWithoutChildren();
     clone->cloneDataFromDocument(*this);
     if (deep)
         cloneChildNodes(clone.get());
     return clone.release();
 }
 
-PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
+PassRefPtrWillBeRawPtr<Document> Document::cloneDocumentWithoutChildren()
 {
     DocumentInit init(url());
-    if (isXHTMLDocument())
-        return createXHTML(init.withRegistrationContext(registrationContext()));
+    if (isXMLDocument()) {
+        if (isXHTMLDocument())
+            return XMLDocument::createXHTML(init.withRegistrationContext(registrationContext()));
+        return XMLDocument::create(init);
+    }
     return create(init);
 }
 
 void Document::cloneDataFromDocument(const Document& other)
 {
     setCompatibilityMode(other.compatibilityMode());
-    setEncoding(other.encoding());
+    setEncodingData(other.m_encodingData);
     setContextFeatures(other.contextFeatures());
     setSecurityOrigin(other.securityOrigin()->isolatedCopy());
+    setMimeType(other.contentType());
 }
 
 StyleSheetList* Document::styleSheets()
@@ -3133,73 +3377,71 @@ String Document::selectedStylesheetSet() const
 void Document::setSelectedStylesheetSet(const String& aString)
 {
     m_styleEngine->setSelectedStylesheetSetName(aString);
-    styleResolverChanged(RecalcStyleDeferred);
+    styleResolverChanged();
+}
+
+void Document::evaluateMediaQueryListIfNeeded()
+{
+    if (!m_evaluateMediaQueriesOnStyleRecalc)
+        return;
+    evaluateMediaQueryList();
+    m_evaluateMediaQueriesOnStyleRecalc = false;
 }
 
 void Document::evaluateMediaQueryList()
 {
     if (m_mediaQueryMatcher)
-        m_mediaQueryMatcher->styleResolverChanged();
+        m_mediaQueryMatcher->mediaFeaturesChanged();
 }
 
-void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
+void Document::notifyResizeForViewportUnits()
 {
-    // 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 (!isActive() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
-        m_styleResolver.clear();
+    if (m_mediaQueryMatcher)
+        m_mediaQueryMatcher->viewportChanged();
+    if (!hasViewportUnits())
         return;
-    }
-    m_didCalculateStyleResolver = true;
+    ensureStyleResolver().notifyResizeForViewportUnits();
+    setNeedsStyleRecalcForViewportUnits();
+}
 
-    bool needsRecalc = m_styleEngine->updateActiveStyleSheets(updateMode);
+void Document::styleResolverChanged(StyleResolverUpdateMode updateMode)
+{
+    // styleResolverChanged() can be invoked during Document destruction.
+    // We just skip that case.
+    if (!m_styleEngine)
+        return;
+
+    m_styleEngine->resolverChanged(updateMode);
 
     if (didLayoutWithPendingStylesheets() && !m_styleEngine->hasPendingSheets()) {
         // We need to manually repaint because we avoid doing all repaints in layout or style
         // recalc while sheets are still loading to avoid FOUC.
         m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
-        renderView()->repaintViewAndCompositedLayers();
-    }
 
-    if (!needsRecalc)
-        return;
-
-    m_evaluateMediaQueriesOnStyleRecalc = true;
-    setNeedsStyleRecalc();
-
-    if (updateTime == RecalcStyleImmediately)
-        updateStyleIfNeeded();
+        ASSERT(renderView() || importsController());
+        if (renderView())
+            renderView()->invalidatePaintForViewAndCompositedLayers();
+    }
 }
 
-void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
+void Document::styleResolverMayHaveChanged()
 {
-    // If we're not in a frame yet any potential child documents won't have a StyleResolver to update.
-    if (!frame())
-        return;
-
-    // Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
-    for (Frame* child = frame()->tree().firstChild(); child; child = child->tree().nextSibling()) {
-        Document* childDocument = child->document();
-        if (childDocument->shouldDisplaySeamlesslyWithParent()) {
-            ASSERT(childDocument->seamlessParentIFrame()->document() == this);
-            childDocument->seamlessParentUpdatedStylesheets();
-        }
-    }
+    styleResolverChanged(hasNodesWithPlaceholderStyle() ? FullStyleUpdate : AnalyzedStyleUpdate);
 }
 
-void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
+void Document::setHoverNode(PassRefPtrWillBeRawPtr<Node> newHoverNode)
 {
     m_hoverNode = newHoverNode;
 }
 
-void Document::setActiveElement(PassRefPtr<Element> newActiveElement)
+void Document::setActiveHoverElement(PassRefPtrWillBeRawPtr<Element> newActiveElement)
 {
     if (!newActiveElement) {
-        m_activeElement.clear();
+        m_activeHoverElement.clear();
         return;
     }
 
-    m_activeElement = newActiveElement;
+    m_activeHoverElement = newActiveElement;
 }
 
 void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
@@ -3207,18 +3449,12 @@ void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
     if (!m_focusedElement)
         return;
 
-    Element* focusedElement = node->treeScope().adjustedFocusedElement();
-    if (!focusedElement)
+    // We can't be focused if we're not in the document.
+    if (!node->inDocument())
         return;
-
-    bool nodeInSubtree = false;
-    if (amongChildrenOnly)
-        nodeInSubtree = focusedElement->isDescendantOf(node);
-    else
-        nodeInSubtree = (focusedElement == node) || focusedElement->isDescendantOf(node);
-
-    if (nodeInSubtree)
-        setFocusedElement(0);
+    bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
+    if (contains && (m_focusedElement != node || !amongChildrenOnly))
+        setFocusedElement(nullptr);
 }
 
 void Document::hoveredNodeDetached(Node* node)
@@ -3245,17 +3481,17 @@ void Document::hoveredNodeDetached(Node* node)
 
 void Document::activeChainNodeDetached(Node* node)
 {
-    if (!m_activeElement)
+    if (!m_activeHoverElement)
         return;
 
-    if (node != m_activeElement && (!m_activeElement->isTextNode() || node != NodeRenderingTraversal::parent(m_activeElement.get())))
+    if (node != m_activeHoverElement)
         return;
 
     Node* activeNode = NodeRenderingTraversal::parent(node);
     while (activeNode && activeNode->isElementNode() && !activeNode->renderer())
         activeNode = NodeRenderingTraversal::parent(activeNode);
 
-    m_activeElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
+    m_activeHoverElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
 }
 
 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
@@ -3269,9 +3505,11 @@ void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
     setAnnotatedRegionsDirty(false);
 }
 
-bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusDirection direction)
+bool Document::setFocusedElement(PassRefPtrWillBeRawPtr<Element> prpNewFocusedElement, FocusType type)
 {
-    RefPtr<Element> newFocusedElement = prpNewFocusedElement;
+    m_clearFocusedElementTimer.stop();
+
+    RefPtrWillBeRawPtr<Element> newFocusedElement = prpNewFocusedElement;
 
     // Make sure newFocusedNode is actually in this document
     if (newFocusedElement && (newFocusedElement->document() != this))
@@ -3284,8 +3522,8 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
         return true;
 
     bool focusChangeBlocked = false;
-    RefPtr<Element> oldFocusedElement = m_focusedElement;
-    m_focusedElement = 0;
+    RefPtrWillBeRawPtr<Element> oldFocusedElement = m_focusedElement;
+    m_focusedElement = nullptr;
 
     // Remove focus from the existing focus node (if any)
     if (oldFocusedElement) {
@@ -3296,28 +3534,27 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
 
         oldFocusedElement->setFocus(false);
 
-        // Dispatch a change event for text fields or textareas that have been edited
-        if (oldFocusedElement->wasChangedSinceLastFormControlChangeEvent())
-            oldFocusedElement->dispatchFormControlChangeEvent();
-
         // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
-        oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
-
-        if (m_focusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            newFocusedElement = 0;
-        }
+        // If page lost focus, blur event will have already been dispatched
+        if (page() && (page()->focusController().isFocused())) {
+            oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
+
+            if (m_focusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                newFocusedElement = nullptr;
+            }
 
-        oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
-        // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
-        // on it, probably when <rdar://problem/8503958> is resolved.
-        oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
+            oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
+            // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
+            // on it, probably when <rdar://problem/8503958> is resolved.
+            oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
 
-        if (m_focusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            newFocusedElement = 0;
+            if (m_focusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                newFocusedElement = nullptr;
+            }
         }
 
         if (view()) {
@@ -3327,11 +3564,6 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
             else
                 view()->setFocus(false);
         }
-
-        // Autofill client may have modified the value of newFocusedElement, thus require
-        // a layout update here, otherwise it will assert at newFocusedElement->isFocusable().
-        // See crbug.com/251163.
-        updateLayoutIgnorePendingStylesheets();
     }
 
     if (newFocusedElement && newFocusedElement->isFocusable()) {
@@ -3344,35 +3576,40 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
         m_focusedElement = newFocusedElement;
 
         // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
-        m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), direction);
+        // If page lost focus, event will be dispatched on page focus, don't duplicate
+        if (page() && (page()->focusController().isFocused())) {
+            m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), type);
 
-        if (m_focusedElement != newFocusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            goto SetFocusedElementDone;
-        }
 
-        m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
+            if (m_focusedElement != newFocusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                goto SetFocusedElementDone;
+            }
 
-        if (m_focusedElement != newFocusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            goto SetFocusedElementDone;
-        }
+            m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get(), type); // DOM level 3 bubbling focus event.
 
-        // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
-        // on it, probably when <rdar://problem/8503958> is m.
-        m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get()); // DOM level 2 for compatibility.
+            if (m_focusedElement != newFocusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                goto SetFocusedElementDone;
+            }
 
-        if (m_focusedElement != newFocusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            goto SetFocusedElementDone;
+            // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
+            // on it, probably when <rdar://problem/8503958> is m.
+            m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get(), type); // DOM level 2 for compatibility.
+
+            if (m_focusedElement != newFocusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                goto SetFocusedElementDone;
+            }
         }
+
         m_focusedElement->setFocus(true);
 
         if (m_focusedElement->isRootEditableElement())
-            frame()->editor().didBeginEditing(m_focusedElement.get());
+            frame()->spellChecker().didBeginEditing(m_focusedElement.get());
 
         // eww, I suck. set the qt focus correctly
         // ### find a better place in the code for this
@@ -3399,45 +3636,70 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
             cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
     }
 
-    if (!focusChangeBlocked && page())
-        page()->chrome().focusedNodeChanged(m_focusedElement.get());
+    if (!focusChangeBlocked && frameHost())
+        frameHost()->chrome().focusedNodeChanged(m_focusedElement.get());
 
 SetFocusedElementDone:
-    updateStyleIfNeeded();
-    if (Frame* frame = this->frame())
+    updateRenderTreeIfNeeded();
+    if (LocalFrame* frame = this->frame())
         frame->selection().didChangeFocus();
     return !focusChangeBlocked;
 }
 
-void Document::setCSSTarget(Element* n)
+void Document::setCSSTarget(Element* newTarget)
 {
     if (m_cssTarget)
-        m_cssTarget->didAffectSelector(AffectedSelectorTarget);
-    m_cssTarget = n;
-    if (n)
-        n->didAffectSelector(AffectedSelectorTarget);
+        m_cssTarget->pseudoStateChanged(CSSSelector::PseudoTarget);
+    m_cssTarget = newTarget;
+    if (m_cssTarget)
+        m_cssTarget->pseudoStateChanged(CSSSelector::PseudoTarget);
 }
 
-void Document::registerNodeList(LiveNodeListBase* list)
+void Document::registerNodeList(const LiveNodeListBase* list)
 {
-    if (list->hasIdNameCache())
-        m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
+#if ENABLE(OILPAN)
+    m_nodeLists[list->invalidationType()].add(list);
+#else
     m_nodeListCounts[list->invalidationType()]++;
+#endif
     if (list->isRootedAtDocument())
         m_listsInvalidatedAtDocument.add(list);
 }
 
-void Document::unregisterNodeList(LiveNodeListBase* list)
+void Document::unregisterNodeList(const LiveNodeListBase* list)
 {
-    if (list->hasIdNameCache())
-        m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
+#if ENABLE(OILPAN)
+    ASSERT(m_nodeLists[list->invalidationType()].contains(list));
+    m_nodeLists[list->invalidationType()].remove(list);
+#else
     m_nodeListCounts[list->invalidationType()]--;
+#endif
     if (list->isRootedAtDocument()) {
         ASSERT(m_listsInvalidatedAtDocument.contains(list));
         m_listsInvalidatedAtDocument.remove(list);
     }
 }
 
+void Document::registerNodeListWithIdNameCache(const LiveNodeListBase* list)
+{
+#if ENABLE(OILPAN)
+    m_nodeLists[InvalidateOnIdNameAttrChange].add(list);
+#else
+    m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
+#endif
+}
+
+void Document::unregisterNodeListWithIdNameCache(const LiveNodeListBase* list)
+{
+#if ENABLE(OILPAN)
+    ASSERT(m_nodeLists[InvalidateOnIdNameAttrChange].contains(list));
+    m_nodeLists[InvalidateOnIdNameAttrChange].remove(list);
+#else
+    ASSERT(m_nodeListCounts[InvalidateOnIdNameAttrChange] > 0);
+    m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
+#endif
+}
+
 void Document::attachNodeIterator(NodeIterator* ni)
 {
     m_nodeIterators.add(ni);
@@ -3450,14 +3712,14 @@ void Document::detachNodeIterator(NodeIterator* ni)
     m_nodeIterators.remove(ni);
 }
 
-void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
+void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
 {
-    HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
-    HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
-    for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
+    WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> > nodeIteratorsList = m_nodeIterators;
+    WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
+    for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
         if ((*it)->root() == node) {
             detachNodeIterator(*it);
-            newDocument->attachNodeIterator(*it);
+            newDocument.attachNodeIterator(*it);
         }
     }
 }
@@ -3465,29 +3727,40 @@ void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
 {
     if (!m_ranges.isEmpty()) {
-        HashSet<Range*>::const_iterator end = m_ranges.end();
-        for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
+        AttachedRangeSet::const_iterator end = m_ranges.end();
+        for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
             (*it)->nodeChildrenChanged(container);
     }
 }
 
-void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
+void Document::updateRangesAfterNodeMovedToAnotherDocument(const Node& node)
+{
+    ASSERT(node.document() != this);
+    if (m_ranges.isEmpty())
+        return;
+    AttachedRangeSet ranges = m_ranges;
+    AttachedRangeSet::const_iterator end = ranges.end();
+    for (AttachedRangeSet::const_iterator it = ranges.begin(); it != end; ++it)
+        (*it)->updateOwnerDocumentIfNeeded();
+}
+
+void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
 {
-    NoEventDispatchAssertion assertNoEventDispatch;
+    EventDispatchForbiddenScope assertNoEventDispatch;
     if (!m_ranges.isEmpty()) {
-        HashSet<Range*>::const_iterator end = m_ranges.end();
-        for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
+        AttachedRangeSet::const_iterator end = m_ranges.end();
+        for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
             (*it)->nodeChildrenWillBeRemoved(container);
     }
 
-    HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
-    for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
-        for (Node* n = container->firstChild(); n; n = n->nextSibling())
+    WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
+    for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
+        for (Node* n = container.firstChild(); n; n = n->nextSibling())
             (*it)->nodeWillBeRemoved(*n);
     }
 
-    if (Frame* frame = this->frame()) {
-        for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
+    if (LocalFrame* 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);
@@ -3497,17 +3770,17 @@ void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
 
 void Document::nodeWillBeRemoved(Node& n)
 {
-    HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
-    for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
+    WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
+    for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
         (*it)->nodeWillBeRemoved(n);
 
     if (!m_ranges.isEmpty()) {
-        HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
-        for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
+        AttachedRangeSet::const_iterator rangesEnd = m_ranges.end();
+        for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
             (*it)->nodeWillBeRemoved(n);
     }
 
-    if (Frame* frame = this->frame()) {
+    if (LocalFrame* frame = this->frame()) {
         frame->eventHandler().nodeWillBeRemoved(n);
         frame->selection().nodeWillBeRemoved(n);
         frame->page()->dragCaretController().nodeWillBeRemoved(n);
@@ -3517,8 +3790,8 @@ void Document::nodeWillBeRemoved(Node& n)
 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
 {
     if (!m_ranges.isEmpty()) {
-        HashSet<Range*>::const_iterator end = m_ranges.end();
-        for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
+        AttachedRangeSet::const_iterator end = m_ranges.end();
+        for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
             (*it)->didInsertText(text, offset, length);
     }
 
@@ -3529,8 +3802,8 @@ void Document::didInsertText(Node* text, unsigned offset, unsigned length)
 void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
 {
     if (!m_ranges.isEmpty()) {
-        HashSet<Range*>::const_iterator end = m_ranges.end();
-        for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
+        AttachedRangeSet::const_iterator end = m_ranges.end();
+        for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
             (*it)->didRemoveText(text, offset, length);
     }
 
@@ -3539,49 +3812,49 @@ void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
     m_markers->shiftMarkers(text, offset + length, 0 - length);
 }
 
-void Document::didMergeTextNodes(Text* oldNode, unsigned offset)
+void Document::didMergeTextNodes(Text& oldNode, unsigned offset)
 {
     if (!m_ranges.isEmpty()) {
         NodeWithIndex oldNodeWithIndex(oldNode);
-        HashSet<Range*>::const_iterator end = m_ranges.end();
-        for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
+        AttachedRangeSet::const_iterator end = m_ranges.end();
+        for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
             (*it)->didMergeTextNodes(oldNodeWithIndex, offset);
     }
 
     if (m_frame)
-        m_frame->selection().didMergeTextNodes(*oldNode, offset);
+        m_frame->selection().didMergeTextNodes(oldNode, offset);
 
     // FIXME: This should update markers for spelling and grammar checking.
 }
 
-void Document::didSplitTextNode(Text* oldNode)
+void Document::didSplitTextNode(Text& oldNode)
 {
     if (!m_ranges.isEmpty()) {
-        HashSet<Range*>::const_iterator end = m_ranges.end();
-        for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
+        AttachedRangeSet::const_iterator end = m_ranges.end();
+        for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
             (*it)->didSplitTextNode(oldNode);
     }
 
     if (m_frame)
-        m_frame->selection().didSplitTextNode(*oldNode);
+        m_frame->selection().didSplitTextNode(oldNode);
 
     // FIXME: This should update markers for spelling and grammar checking.
 }
 
-void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld)
+void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
 {
-    DOMWindow* domWindow = this->domWindow();
+    LocalDOMWindow* domWindow = this->domWindow();
     if (!domWindow)
         return;
-    domWindow->setAttributeEventListener(eventType, listener, isolatedWorld);
+    domWindow->setAttributeEventListener(eventType, listener);
 }
 
-EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld)
+EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
 {
-    DOMWindow* domWindow = this->domWindow();
+    LocalDOMWindow* domWindow = this->domWindow();
     if (!domWindow)
         return 0;
-    return domWindow->getAttributeEventListener(eventType, isolatedWorld);
+    return domWindow->getAttributeEventListener(eventType);
 }
 
 EventQueue* Document::eventQueue() const
@@ -3591,27 +3864,58 @@ EventQueue* Document::eventQueue() const
     return m_domWindow->eventQueue();
 }
 
-void Document::scheduleAnimationFrameEvent(PassRefPtr<Event> event)
+void Document::enqueueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event> event)
+{
+    ensureScriptedAnimationController().enqueueEvent(event);
+}
+
+void Document::enqueueUniqueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event> event)
 {
-    ensureScriptedAnimationController().scheduleEvent(event);
+    ensureScriptedAnimationController().enqueuePerFrameEvent(event);
 }
 
 void Document::enqueueScrollEventForNode(Node* target)
 {
     // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
-    RefPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
+    RefPtrWillBeRawPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
     scrollEvent->setTarget(target);
-    scheduleAnimationFrameEvent(scrollEvent.release());
+    ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
 }
 
-PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionState& es)
+void Document::enqueueResizeEvent()
 {
-    RefPtr<Event> event = EventFactory::create(eventType);
-    if (event)
-        return event.release();
+    RefPtrWillBeRawPtr<Event> event = Event::create(EventTypeNames::resize);
+    event->setTarget(domWindow());
+    ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
+}
 
-    es.throwUninformativeAndGenericDOMException(NotSupportedError);
-    return 0;
+void Document::enqueueMediaQueryChangeListeners(WillBeHeapVector<RefPtrWillBeMember<MediaQueryListListener> >& listeners)
+{
+    ensureScriptedAnimationController().enqueueMediaQueryChangeListeners(listeners);
+}
+
+Document::EventFactorySet& Document::eventFactories()
+{
+    DEFINE_STATIC_LOCAL(EventFactorySet, s_eventFactory, ());
+    return s_eventFactory;
+}
+
+void Document::registerEventFactory(PassOwnPtr<EventFactoryBase> eventFactory)
+{
+    ASSERT(!eventFactories().contains(eventFactory.get()));
+    eventFactories().add(eventFactory);
+}
+
+PassRefPtrWillBeRawPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
+{
+    RefPtrWillBeRawPtr<Event> event = nullptr;
+    for (EventFactorySet::const_iterator it = eventFactories().begin(); it != eventFactories().end(); ++it) {
+        event = (*it)->create(eventType);
+        if (event)
+            return event.release();
+    }
+    exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
+    return nullptr;
 }
 
 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
@@ -3641,6 +3945,7 @@ void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
         UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
         addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
     } else if (eventType == EventTypeNames::overflowchanged) {
+        UseCounter::countDeprecation(*this, UseCounter::OverflowChangedEvent);
         addListenerType(OVERFLOWCHANGED_LISTENER);
     } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
         addListenerType(ANIMATIONSTART_LISTENER);
@@ -3650,13 +3955,6 @@ void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
         addListenerType(ANIMATIONITERATION_LISTENER);
     } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
         addListenerType(TRANSITIONEND_LISTENER);
-    } else if (eventType == EventTypeNames::beforeload) {
-        if (m_frame && m_frame->script().shouldBypassMainWorldContentSecurityPolicy()) {
-            UseCounter::count(*this, UseCounter::BeforeLoadEventInIsolatedWorld);
-        } else {
-            UseCounter::count(*this, UseCounter::BeforeLoadEvent);
-        }
-        addListenerType(BEFORELOAD_LISTENER);
     } else if (eventType == EventTypeNames::scroll) {
         addListenerType(SCROLL_LISTENER);
     }
@@ -3671,10 +3969,20 @@ HTMLFrameOwnerElement* Document::ownerElement() const
 {
     if (!frame())
         return 0;
-    return frame()->ownerElement();
+    // FIXME: This probably breaks the attempts to layout after a load is finished in implicitClose(), and probably tons of other things...
+    return frame()->deprecatedLocalOwner();
+}
+
+bool Document::isInInvisibleSubframe() const
+{
+    if (!ownerElement())
+        return false; // this is the root element
+
+    ASSERT(frame());
+    return !frame()->ownerRenderer();
 }
 
-String Document::cookie(ExceptionState& es) const
+String Document::cookie(ExceptionState& exceptionState) const
 {
     if (settings() && !settings()->cookieEnabled())
         return String();
@@ -3684,13 +3992,12 @@ String Document::cookie(ExceptionState& es) const
     // browsing context.
 
     if (!securityOrigin()->canAccessCookies()) {
-        String accessDeniedMessage = "Access to 'cookie' is denied for this document.";
         if (isSandboxed(SandboxOrigin))
-            es.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"))
-            es.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+            exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
         else
-            es.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError("Access is denied for this document.");
         return String();
     }
 
@@ -3701,7 +4008,7 @@ String Document::cookie(ExceptionState& es) const
     return cookies(this, cookieURL);
 }
 
-void Document::setCookie(const String& value, ExceptionState& es)
+void Document::setCookie(const String& value, ExceptionState& exceptionState)
 {
     if (settings() && !settings()->cookieEnabled())
         return;
@@ -3711,13 +4018,12 @@ void Document::setCookie(const String& value, ExceptionState& es)
     // browsing context.
 
     if (!securityOrigin()->canAccessCookies()) {
-        String accessDeniedMessage = "Access to 'cookie' is denied for this document.";
         if (isSandboxed(SandboxOrigin))
-            es.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"))
-            es.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+            exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
         else
-            es.throwSecurityError(accessDeniedMessage);
+            exceptionState.throwSecurityError("Access is denied for this document.");
         return;
     }
 
@@ -3728,11 +4034,11 @@ void Document::setCookie(const String& value, ExceptionState& es)
     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
@@ -3740,29 +4046,39 @@ String Document::domain() const
     return securityOrigin()->domain();
 }
 
-void Document::setDomain(const String& newDomain, ExceptionState& es)
+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())) {
-        es.throwSecurityError(ExceptionMessages::failedToSet("domain", "Document", "assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme."));
+        exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
         return;
     }
 
-    String exceptionMessage = ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is not a suffix of '" + domain() + "'.");
     if (newDomain.isEmpty()) {
-        es.throwSecurityError(exceptionMessage);
+        exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
         return;
     }
 
     OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
     OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
-    if (!accessEntry.matchesOrigin(*securityOrigin())) {
-        es.throwSecurityError(exceptionMessage);
+    OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
+    if (result == OriginAccessEntry::DoesNotMatchOrigin) {
+        exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
+        return;
+    }
+
+    if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
+        exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
         return;
     }
 
     securityOrigin()->setDomainFromDOM(newDomain);
     if (m_frame)
-        m_frame->script().updateSecurityOrigin();
+        m_frame->script().updateSecurityOrigin(securityOrigin());
 }
 
 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
@@ -3771,25 +4087,25 @@ String Document::lastModified() const
     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(convertToLocalTime(parseDate(httpLastModified)));
+                foundDate = true;
+            }
         }
     }
     // FIXME: If this document came from the file system, the HTML5
     // specificiation tells us to read the last modification date from the file
     // system.
     if (!foundDate)
-        date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
+        date.setMillisecondsSinceEpochForDateTime(convertToLocalTime(currentTimeMS()));
     return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
 }
 
 const KURL& Document::firstPartyForCookies() const
 {
-    return topDocument()->url();
+    return topDocument().url();
 }
 
 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
@@ -3807,16 +4123,11 @@ static bool isValidNameNonASCII(const LChar* characters, unsigned length)
 
 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
 {
-    unsigned i = 0;
-
-    UChar32 c;
-    U16_NEXT(characters, i, length, c)
-    if (!isValidNameStart(c))
-        return false;
-
-    while (i < length) {
-        U16_NEXT(characters, i, length, c)
-        if (!isValidNamePart(c))
+    for (unsigned i = 0; i < length;) {
+        bool first = i == 0;
+        UChar32 c;
+        U16_NEXT(characters, i, length, c); // Increments i.
+        if (first ? !isValidNameStart(c) : !isValidNamePart(c))
             return false;
     }
 
@@ -3862,8 +4173,25 @@ bool Document::isValidName(const String& name)
     return isValidNameNonASCII(characters, length);
 }
 
+enum QualifiedNameStatus {
+    QNValid,
+    QNMultipleColons,
+    QNInvalidStartChar,
+    QNInvalidChar,
+    QNEmptyPrefix,
+    QNEmptyLocalName
+};
+
+struct ParseQualifiedNameResult {
+    QualifiedNameStatus status;
+    UChar32 character;
+    ParseQualifiedNameResult() { }
+    explicit ParseQualifiedNameResult(QualifiedNameStatus status) : status(status) { }
+    ParseQualifiedNameResult(QualifiedNameStatus status, UChar32 character) : status(status), character(character) { }
+};
+
 template<typename CharType>
-static bool parseQualifiedNameInternal(const String& qualifiedName, const CharType* characters, unsigned length, String& prefix, String& localName, ExceptionState& es)
+static ParseQualifiedNameResult parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName)
 {
     bool nameStart = true;
     bool sawColon = false;
@@ -3873,72 +4201,86 @@ static bool parseQualifiedNameInternal(const String& qualifiedName, const CharTy
         UChar32 c;
         U16_NEXT(characters, i, length, c)
         if (c == ':') {
-            if (sawColon) {
-                es.throwUninformativeAndGenericDOMException(NamespaceError);
-                return false; // multiple colons: not allowed
-            }
+            if (sawColon)
+                return ParseQualifiedNameResult(QNMultipleColons);
             nameStart = true;
             sawColon = true;
             colonPos = i - 1;
         } else if (nameStart) {
-            if (!isValidNameStart(c)) {
-                es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
-                return false;
-            }
+            if (!isValidNameStart(c))
+                return ParseQualifiedNameResult(QNInvalidStartChar, c);
             nameStart = false;
         } else {
-            if (!isValidNamePart(c)) {
-                es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
-                return false;
-            }
+            if (!isValidNamePart(c))
+                return ParseQualifiedNameResult(QNInvalidChar, c);
         }
     }
 
     if (!sawColon) {
-        prefix = String();
+        prefix = nullAtom;
         localName = qualifiedName;
     } else {
-        prefix = qualifiedName.substring(0, colonPos);
-        if (prefix.isEmpty()) {
-            es.throwUninformativeAndGenericDOMException(NamespaceError);
-            return false;
-        }
-        localName = qualifiedName.substring(colonPos + 1);
+        prefix = AtomicString(characters, colonPos);
+        if (prefix.isEmpty())
+            return ParseQualifiedNameResult(QNEmptyPrefix);
+        int prefixStart = colonPos + 1;
+        localName = AtomicString(characters + prefixStart, length - prefixStart);
     }
 
-    if (localName.isEmpty()) {
-        es.throwUninformativeAndGenericDOMException(NamespaceError);
-        return false;
-    }
+    if (localName.isEmpty())
+        return ParseQualifiedNameResult(QNEmptyLocalName);
 
-    return true;
+    return ParseQualifiedNameResult(QNValid);
 }
 
-bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionState& es)
+bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
 {
     unsigned length = qualifiedName.length();
 
     if (!length) {
-        es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
         return false;
     }
 
+    ParseQualifiedNameResult returnValue;
     if (qualifiedName.is8Bit())
-        return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, es);
-    return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, es);
-}
+        returnValue = parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName);
+    else
+        returnValue = parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName);
+    if (returnValue.status == QNValid)
+        return true;
 
-void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
-{
-    m_decoder = decoder;
-    setEncoding(m_decoder ? m_decoder->encoding() : WTF::TextEncoding());
+    StringBuilder message;
+    message.appendLiteral("The qualified name provided ('");
+    message.append(qualifiedName);
+    message.appendLiteral("') ");
+
+    if (returnValue.status == QNMultipleColons) {
+        message.appendLiteral("contains multiple colons.");
+    } else if (returnValue.status == QNInvalidStartChar) {
+        message.appendLiteral("contains the invalid name-start character '");
+        message.append(returnValue.character);
+        message.appendLiteral("'.");
+    } else if (returnValue.status == QNInvalidChar) {
+        message.appendLiteral("contains the invalid character '");
+        message.append(returnValue.character);
+        message.appendLiteral("'.");
+    } else if (returnValue.status == QNEmptyPrefix) {
+        message.appendLiteral("has an empty namespace prefix.");
+    } else {
+        ASSERT(returnValue.status == QNEmptyLocalName);
+        message.appendLiteral("has an empty local name.");
+    }
+
+    if (returnValue.status == QNInvalidStartChar || returnValue.status == QNInvalidChar)
+        exceptionState.throwDOMException(InvalidCharacterError, message.toString());
+    else
+        exceptionState.throwDOMException(NamespaceError, message.toString());
+    return false;
 }
 
-void Document::setEncoding(const WTF::TextEncoding& encoding)
+void Document::setEncodingData(const DocumentEncodingData& newData)
 {
-    if (m_encoding == encoding)
-        return;
-
     // It's possible for the encoding of the document to change while we're decoding
     // data. That can only occur while we're processing the <head> portion of the
     // document. There isn't much user-visible content in the <head>, but there is
@@ -3946,52 +4288,92 @@ void Document::setEncoding(const WTF::TextEncoding& encoding)
     // document's title so that the user doesn't see an incorrectly decoded title
     // in the title bar.
     if (m_titleElement
-        && !m_titleElement->firstElementChild()
-        && m_encoding == Latin1Encoding()
+        && encoding() != newData.encoding()
+        && !ElementTraversal::firstWithin(*m_titleElement)
+        && encoding() == Latin1Encoding()
         && m_titleElement->textContent().containsOnlyLatin1()) {
 
         CString originalBytes = m_titleElement->textContent().latin1();
-        OwnPtr<TextCodec> codec = newTextCodec(encoding);
-        String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), true);
-        m_titleElement->setTextContent(correctlyDecodedTitle, IGNORE_EXCEPTION);
+        OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
+        String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), DataEOF);
+        m_titleElement->setTextContent(correctlyDecodedTitle);
+    }
+
+    m_encodingData = newData;
+
+    // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
+    bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
+    if (shouldUseVisualOrdering != m_visuallyOrdered) {
+        m_visuallyOrdered = shouldUseVisualOrdering;
+        // FIXME: How is possible to not have a renderer here?
+        if (renderView())
+            renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
+        setNeedsStyleRecalc(SubtreeStyleChange);
     }
+}
 
-    m_encoding = encoding;
+KURL Document::completeURL(const String& url) const
+{
+    return completeURLWithOverride(url, m_baseURL);
 }
 
-KURL Document::completeURL(const String& url, const KURL& baseURLOverride) const
+KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
 {
     // Always return a null URL when passed a null string.
     // FIXME: Should we change the KURL constructor to have this behavior?
     // See also [CSS]StyleSheet::completeURL(const String&)
     if (url.isNull())
         return KURL();
-    const KURL& baseURL = ((baseURLOverride.isEmpty() || baseURLOverride == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : baseURLOverride;
-    if (!m_decoder)
+    // This logic is deliberately spread over many statements in an attempt to track down http://crbug.com/312410.
+    const KURL* baseURLFromParent = 0;
+    bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
+    if (!shouldUseParentBaseURL) {
+        const KURL& aboutBlankURL = blankURL();
+        shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
+    }
+    if (shouldUseParentBaseURL) {
+        if (Document* parent = parentDocument())
+            baseURLFromParent = &parent->baseURL();
+    }
+    const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
+    if (!encoding().isValid())
         return KURL(baseURL, url);
-    return KURL(baseURL, url, m_decoder->encoding());
-}
-
-KURL Document::completeURL(const String& url) const
-{
-    return completeURL(url, m_baseURL);
+    return KURL(baseURL, url, encoding());
 }
 
 // Support for Javascript execCommand, and related methods
 
 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
 {
-    Frame* frame = document->frame();
+    LocalFrame* frame = document->frame();
     if (!frame || frame->document() != document)
         return Editor::Command();
 
-    document->updateStyleIfNeeded();
+    document->updateRenderTreeIfNeeded();
     return frame->editor().command(commandName, userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
 }
 
 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
 {
-    return command(this, commandName, userInterface).execute(value);
+    // We don't allow recusrive |execCommand()| to protect against attack code.
+    // Recursive call of |execCommand()| could be happened by moving iframe
+    // with script triggered by insertion, e.g. <iframe src="javascript:...">
+    // <iframe onload="...">. This usage is valid as of the specification
+    // although, it isn't common use case, rather it is used as attack code.
+    static bool inExecCommand = false;
+    if (inExecCommand) {
+        String message = "We don't execute document.execCommand() this time, because it is called recursively.";
+        addConsoleMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, message));
+        return false;
+    }
+    TemporaryChange<bool> executeScope(inExecCommand, true);
+
+    // Postpone DOM mutation events, which can execute scripts and change
+    // DOM tree against implementation assumption.
+    EventQueueScope eventQueueScope;
+    Editor::Command editorCommand = command(this, commandName, userInterface);
+    Platform::current()->histogramSparse("WebCore.Document.execCommand", editorCommand.idForHistogram());
+    return editorCommand.execute(value);
 }
 
 bool Document::queryCommandEnabled(const String& commandName)
@@ -4035,11 +4417,7 @@ KURL Document::openSearchDescriptionURL()
     if (!head())
         return KURL();
 
-    RefPtr<HTMLCollection> children = head()->children();
-    for (unsigned i = 0; Node* child = children->item(i); i++) {
-        if (!child->hasTagName(linkTag))
-            continue;
-        HTMLLinkElement* linkElement = toHTMLLinkElement(child);
+    for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head()); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
         if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
             continue;
         if (linkElement->href().isEmpty())
@@ -4050,7 +4428,7 @@ KURL Document::openSearchDescriptionURL()
     return KURL();
 }
 
-void Document::pushCurrentScript(PassRefPtr<HTMLScriptElement> newCurrentScript)
+void Document::pushCurrentScript(PassRefPtrWillBeRawPtr<HTMLScriptElement> newCurrentScript)
 {
     ASSERT(newCurrentScript);
     m_currentScriptStack.append(newCurrentScript);
@@ -4066,15 +4444,15 @@ void Document::applyXSLTransform(ProcessingInstruction* pi)
 {
     ASSERT(!pi->isLoading());
     UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
-    RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
-    processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
+    RefPtrWillBeRawPtr<XSLTProcessor> processor = XSLTProcessor::create(*this);
+    processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
     String resultMIMEType;
     String newSource;
     String resultEncoding;
     if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
         return;
     // FIXME: If the transform failed we should probably report an error (like Mozilla does).
-    Frame* ownerFrame = frame();
+    LocalFrame* ownerFrame = frame();
     processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
     InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
 }
@@ -4087,8 +4465,13 @@ void Document::setTransformSource(PassOwnPtr<TransformSource> source)
 void Document::setDesignMode(InheritedBool value)
 {
     m_designMode = value;
-    for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
-        frame->document()->setNeedsStyleRecalc();
+    for (Frame* frame = m_frame; frame; frame = frame->tree().traverseNext(m_frame)) {
+        if (!frame->isLocalFrame())
+            continue;
+        if (!toLocalFrame(frame)->document())
+            break;
+        toLocalFrame(frame)->document()->setNeedsStyleRecalc(SubtreeStyleChange);
+    }
 }
 
 Document::InheritedBool Document::getDesignMode() const
@@ -4105,54 +4488,78 @@ bool Document::inDesignMode() const
     return false;
 }
 
+String Document::designMode() const
+{
+    return inDesignMode() ? "on" : "off";
+}
+
+void Document::setDesignMode(const String& value)
+{
+    InheritedBool mode;
+    if (equalIgnoringCase(value, "on"))
+        mode = on;
+    else if (equalIgnoringCase(value, "off"))
+        mode = off;
+    else
+        mode = inherit;
+    setDesignMode(mode);
+}
+
 Document* Document::parentDocument() const
 {
     if (!m_frame)
         return 0;
     Frame* parent = m_frame->tree().parent();
-    if (!parent)
+    if (!parent || !parent->isLocalFrame())
         return 0;
-    return parent->document();
+    return toLocalFrame(parent)->document();
 }
 
-Document* Document::topDocument() const
+Document& Document::topDocument() const
 {
+    // FIXME: Not clear what topDocument() should do in the OOPI case--should it return the topmost
+    // available Document, or something else?
     Document* doc = const_cast<Document*>(this);
-    Element* element;
-    while ((element = doc->ownerElement()))
+    for (HTMLFrameOwnerElement* element = doc->ownerElement(); element; element = doc->ownerElement())
         doc = &element->document();
 
-    return doc;
+    ASSERT(doc);
+    return *doc;
 }
 
-WeakPtr<Document> Document::contextDocument()
+WeakPtrWillBeRawPtr<Document> Document::contextDocument()
 {
     if (m_contextDocument)
         return m_contextDocument;
-    if (m_frame)
+    if (m_frame) {
+#if ENABLE(OILPAN)
+        return this;
+#else
         return m_weakFactory.createWeakPtr();
-    return WeakPtr<Document>(0);
+#endif
+    }
+    return WeakPtrWillBeRawPtr<Document>(nullptr);
 }
 
-PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionState& es)
+PassRefPtrWillBeRawPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
 {
-    return createAttributeNS(String(), name, es, true);
+    return createAttributeNS(nullAtom, name, exceptionState, true);
 }
 
-PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& es, bool shouldIgnoreNamespaceChecks)
+PassRefPtrWillBeRawPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
 {
-    String prefix, localName;
-    if (!parseQualifiedName(qualifiedName, prefix, localName, es))
-        return 0;
+    AtomicString prefix, localName;
+    if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
+        return nullptr;
 
     QualifiedName qName(prefix, localName, namespaceURI);
 
     if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
-        es.throwUninformativeAndGenericDOMException(NamespaceError);
-        return 0;
+        exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
+        return nullptr;
     }
 
-    return Attr::create(*this, qName, emptyString());
+    return Attr::create(*this, qName, emptyAtom);
 }
 
 const SVGDocumentExtensions* Document::svgExtensions()
@@ -4160,83 +4567,72 @@ const SVGDocumentExtensions* Document::svgExtensions()
     return m_svgExtensions.get();
 }
 
-SVGDocumentExtensions* Document::accessSVGExtensions()
+SVGDocumentExtensions& Document::accessSVGExtensions()
 {
     if (!m_svgExtensions)
-        m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
-    return m_svgExtensions.get();
+        m_svgExtensions = adoptPtrWillBeNoop(new SVGDocumentExtensions(this));
+    return *m_svgExtensions;
 }
 
 bool Document::hasSVGRootNode() const
 {
-    return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
-}
-
-PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
-{
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, type);
-}
-
-PassRefPtr<HTMLCollection> Document::images()
-{
-    return ensureCachedCollection(DocImages);
+    return isSVGSVGElement(documentElement());
 }
 
-PassRefPtr<HTMLCollection> Document::applets()
+PassRefPtrWillBeRawPtr<HTMLCollection> Document::images()
 {
-    return ensureCachedCollection(DocApplets);
+    return ensureCachedCollection<HTMLCollection>(DocImages);
 }
 
-PassRefPtr<HTMLCollection> Document::embeds()
+PassRefPtrWillBeRawPtr<HTMLCollection> Document::applets()
 {
-    return ensureCachedCollection(DocEmbeds);
+    return ensureCachedCollection<HTMLCollection>(DocApplets);
 }
 
-PassRefPtr<HTMLCollection> Document::plugins()
+PassRefPtrWillBeRawPtr<HTMLCollection> Document::embeds()
 {
-    // This is an alias for embeds() required for the JS DOM bindings.
-    return ensureCachedCollection(DocEmbeds);
+    return ensureCachedCollection<HTMLCollection>(DocEmbeds);
 }
 
-PassRefPtr<HTMLCollection> Document::scripts()
+PassRefPtrWillBeRawPtr<HTMLCollection> Document::scripts()
 {
-    return ensureCachedCollection(DocScripts);
+    return ensureCachedCollection<HTMLCollection>(DocScripts);
 }
 
-PassRefPtr<HTMLCollection> Document::links()
+PassRefPtrWillBeRawPtr<HTMLCollection> Document::links()
 {
-    return ensureCachedCollection(DocLinks);
+    return ensureCachedCollection<HTMLCollection>(DocLinks);
 }
 
-PassRefPtr<HTMLCollection> Document::forms()
+PassRefPtrWillBeRawPtr<HTMLCollection> Document::forms()
 {
-    return ensureCachedCollection(DocForms);
+    return ensureCachedCollection<HTMLCollection>(DocForms);
 }
 
-PassRefPtr<HTMLCollection> Document::anchors()
+PassRefPtrWillBeRawPtr<HTMLCollection> Document::anchors()
 {
-    return ensureCachedCollection(DocAnchors);
+    return ensureCachedCollection<HTMLCollection>(DocAnchors);
 }
 
-PassRefPtr<HTMLCollection> Document::allForBinding()
+PassRefPtrWillBeRawPtr<HTMLAllCollection> Document::allForBinding()
 {
     UseCounter::count(*this, UseCounter::DocumentAll);
     return all();
 }
 
-PassRefPtr<HTMLCollection> Document::all()
+PassRefPtrWillBeRawPtr<HTMLAllCollection> Document::all()
 {
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLAllCollection>(this, DocAll);
+    return ensureCachedCollection<HTMLAllCollection>(DocAll);
 }
 
-PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
+PassRefPtrWillBeRawPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
 {
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLNameCollection>(this, WindowNamedItems, name);
+    return ensureCachedCollection<WindowNameCollection>(WindowNamedItems, name);
 }
 
-PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
+PassRefPtrWillBeRawPtr<DocumentNameCollection> Document::documentNamedItems(const AtomicString& name)
 {
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLNameCollection>(this, DocumentNamedItems, name);
+    return ensureCachedCollection<DocumentNameCollection>(DocumentNamedItems, name);
 }
 
 void Document::finishedParsing()
@@ -4253,9 +4649,14 @@ void Document::finishedParsing()
     // The loader's finishedParsing() method may invoke script that causes this object to
     // be dereferenced (when this document is in an iframe and the onload causes the iframe's src to change).
     // Keep it alive until we are done.
-    RefPtr<Document> protect(this);
+    RefPtrWillBeRawPtr<Document> protect(this);
+
+    if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) {
+        // Don't update the render tree if we haven't requested the main resource yet to avoid
+        // adding extra latency. Note that the first render tree update can be expensive since it
+        // triggers the parsing of the default stylesheets which are compiled-in.
+        const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad();
 
-    if (RefPtr<Frame> f = frame()) {
         // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
         // resource loads are complete. HTMLObjectElements can start loading their resources from
         // post attach callbacks triggered by recalcStyle().  This means if we parse out an <object>
@@ -4263,70 +4664,107 @@ void Document::finishedParsing()
         // started the resource load and might fire the window load event too early.  To avoid this
         // we force the styles to be up to date before calling FrameLoader::finishedParsing().
         // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
-        updateStyleIfNeeded();
+        if (mainResourceWasAlreadyRequested)
+            updateRenderTreeIfNeeded();
 
-        f->loader().finishedParsing();
+        frame->loader().finishedParsing();
 
-        InspectorInstrumentation::domContentLoadedEventFired(f.get());
+        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", "data", InspectorMarkLoadEvent::data(frame.get()));
+        // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
+        InspectorInstrumentation::domContentLoadedEventFired(frame.get());
     }
 
-    // Schedule dropping of the DocumentSharedObjectPool. We keep it alive for a while after parsing finishes
+    // Schedule dropping of the ElementDataCache. We keep it alive for a while after parsing finishes
     // so that dynamically inserted content can also benefit from sharing optimizations.
-    // Note that we don't refresh the timer on pool access since that could lead to huge caches being kept
+    // Note that we don't refresh the timer on cache access since that could lead to huge caches being kept
     // alive indefinitely by something innocuous like JS setting .innerHTML repeatedly on a timer.
-    static const int timeToKeepSharedObjectPoolAliveAfterParsingFinishedInSeconds = 10;
-    m_sharedObjectPoolClearTimer.startOneShot(timeToKeepSharedObjectPoolAliveAfterParsingFinishedInSeconds);
+    m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
 
     // Parser should have picked up all preloads by now
     m_fetcher->clearPreloads();
-
-    if (m_import)
-        m_import->didFinishParsing();
 }
 
-void Document::sharedObjectPoolClearTimerFired(Timer<Document>*)
+void Document::elementDataCacheClearTimerFired(Timer<Document>*)
 {
-    m_sharedObjectPool.clear();
+    m_elementDataCache.clear();
 }
 
-void Document::styleResolverThrowawayTimerFired(Timer<Document>*)
+Vector<IconURL> Document::iconURLs(int iconTypesMask)
 {
-    if (m_styleResolverAccessCount == m_lastStyleResolverAccessCount)
-        clearStyleResolver();
-    m_lastStyleResolverAccessCount = m_styleResolverAccessCount;
+    IconURL firstFavicon;
+    IconURL firstTouchIcon;
+    IconURL firstTouchPrecomposedIcon;
+    Vector<IconURL> secondaryIcons;
+
+    // Start from the last child node so that icons seen later take precedence as required by the spec.
+    for (HTMLLinkElement* linkElement = head() ? Traversal<HTMLLinkElement>::firstChild(*head()) : 0; linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
+        if (!(linkElement->iconType() & iconTypesMask))
+            continue;
+        if (linkElement->href().isEmpty())
+            continue;
+        if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
+            continue;
+
+        IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
+        if (linkElement->iconType() == Favicon) {
+            if (firstFavicon.m_iconType != InvalidIcon)
+                secondaryIcons.append(firstFavicon);
+            firstFavicon = newURL;
+        } else if (linkElement->iconType() == TouchIcon) {
+            if (firstTouchIcon.m_iconType != InvalidIcon)
+                secondaryIcons.append(firstTouchIcon);
+            firstTouchIcon = newURL;
+        } else if (linkElement->iconType() == TouchPrecomposedIcon) {
+            if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
+                secondaryIcons.append(firstTouchPrecomposedIcon);
+            firstTouchPrecomposedIcon = newURL;
+        } else {
+            ASSERT_NOT_REACHED();
+        }
+    }
+
+    Vector<IconURL> iconURLs;
+    if (firstFavicon.m_iconType != InvalidIcon)
+        iconURLs.append(firstFavicon);
+    else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
+        iconURLs.append(IconURL::defaultFavicon(m_url));
+
+    if (firstTouchIcon.m_iconType != InvalidIcon)
+        iconURLs.append(firstTouchIcon);
+    if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
+        iconURLs.append(firstTouchPrecomposedIcon);
+    for (int i = secondaryIcons.size() - 1; i >= 0; --i)
+        iconURLs.append(secondaryIcons[i]);
+    return iconURLs;
 }
 
-const Vector<IconURL>& Document::shortcutIconURLs()
+Color Document::themeColor() const
 {
-    // Include any icons where type = link, rel = "shortcut icon".
-    return iconURLs(Favicon);
+    if (!RuntimeEnabledFeatures::themeColorEnabled())
+        return Color();
+
+    for (HTMLMetaElement* metaElement = head() ? Traversal<HTMLMetaElement>::firstChild(*head()) : 0; metaElement; metaElement = Traversal<HTMLMetaElement>::nextSibling(*metaElement)) {
+        RGBA32 rgb = Color::transparent;
+        if (equalIgnoringCase(metaElement->name(), "theme-color") && CSSParser::parseColor(rgb, metaElement->content().string().stripWhiteSpace(), true))
+            return Color(rgb);
+    }
+    return Color();
 }
 
-const Vector<IconURL>& Document::iconURLs(int iconTypesMask)
+HTMLLinkElement* Document::linkManifest() const
 {
-    m_iconURLs.clear();
-
-    if (!head() || !(head()->children()))
-        return m_iconURLs;
+    HTMLHeadElement* head = this->head();
+    if (!head)
+        return 0;
 
-    RefPtr<HTMLCollection> children = head()->children();
-    unsigned int length = children->length();
-    for (unsigned int i = 0; i < length; ++i) {
-        Node* child = children->item(i);
-        if (!child->hasTagName(linkTag))
-            continue;
-        HTMLLinkElement* linkElement = toHTMLLinkElement(child);
-        if (!(linkElement->iconType() & iconTypesMask))
-            continue;
-        if (linkElement->href().isEmpty())
+    // The first link element with a manifest rel must be used. Others are ignored.
+    for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
+        if (!linkElement->relAttribute().isManifest())
             continue;
-
-        // Put it at the front to ensure that icons seen later take precedence as required by the spec.
-        IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
-        m_iconURLs.prepend(newURL);
+        return linkElement;
     }
 
-    return m_iconURLs;
+    return 0;
 }
 
 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
@@ -4345,7 +4783,7 @@ bool Document::useSecureKeyboardEntryWhenActive() const
 
 void Document::initSecurityContext()
 {
-    initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_import));
+    initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_importsController));
 }
 
 void Document::initSecurityContext(const DocumentInit& initializer)
@@ -4360,7 +4798,7 @@ void Document::initSecurityContext(const DocumentInit& initializer)
         // This can occur via document.implementation.createDocument().
         m_cookieURL = KURL(ParsedURLString, emptyString());
         setSecurityOrigin(SecurityOrigin::createUnique());
-        setContentSecurityPolicy(ContentSecurityPolicy::create(this));
+        initContentSecurityPolicy();
         return;
     }
 
@@ -4369,7 +4807,16 @@ void Document::initSecurityContext(const DocumentInit& initializer)
     m_cookieURL = m_url;
     enforceSandboxFlags(initializer.sandboxFlags());
     setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
-    setContentSecurityPolicy(ContentSecurityPolicy::create(this));
+
+    if (importsController()) {
+        // If this document is an HTML import, grab a reference to it's master document's Content
+        // Security Policy. We don't call 'initContentSecurityPolicy' in this case, as we can't
+        // rebind the master document's policy object: its ExecutionContext needs to remain tied
+        // to the master document.
+        setContentSecurityPolicy(importsController()->master()->contentSecurityPolicy());
+    } else {
+        initContentSecurityPolicy();
+    }
 
     if (Settings* settings = initializer.settings()) {
         if (!settings->webSecurityEnabled()) {
@@ -4394,10 +4841,6 @@ void Document::initSecurityContext(const DocumentInit& initializer)
         setBaseURLOverride(initializer.parentBaseURL());
     }
 
-    // FIXME: What happens if we inherit the security origin? This check may need to be later.
-    // <iframe seamless src="about:blank"> likely won't work as-is.
-    m_mayDisplaySeamlesslyWithParent = initializer.isSeamlessAllowedFor(this);
-
     if (!shouldInheritSecurityOriginFromOwner(m_url))
         return;
 
@@ -4425,11 +4868,14 @@ void Document::initSecurityContext(const DocumentInit& initializer)
     setSecurityOrigin(initializer.owner()->securityOrigin());
 }
 
-void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
+void Document::initContentSecurityPolicy(PassRefPtr<ContentSecurityPolicy> csp)
 {
-    if (m_frame && m_frame->tree().parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
-        contentSecurityPolicy()->copyStateFrom(m_frame->tree().parent()->document()->contentSecurityPolicy());
-    contentSecurityPolicy()->didReceiveHeaders(headers);
+    setContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::create());
+    if (m_frame && m_frame->tree().parent() && m_frame->tree().parent()->isLocalFrame() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
+        contentSecurityPolicy()->copyStateFrom(toLocalFrame(m_frame->tree().parent())->document()->contentSecurityPolicy());
+    if (transformSourceDocument())
+        contentSecurityPolicy()->copyStateFrom(transformSourceDocument()->contentSecurityPolicy());
+    contentSecurityPolicy()->bindToExecutionContext(this);
 }
 
 bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, const String& contextURL, const WTF::OrdinalNumber& contextLine)
@@ -4441,9 +4887,10 @@ bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, con
     // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handler-attributes
     // Also, if the listening node came from other document, which happens on context-less event dispatching,
     // we also need to ask the owner document of the node.
-    if (!m_frame)
+    LocalFrame* frame = executingFrame();
+    if (!frame)
         return false;
-    if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript))
+    if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
         return false;
     if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
         return false;
@@ -4456,11 +4903,12 @@ bool Document::allowExecutingScripts(Node* node)
     // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
     // viewless document but this'll do for now.
     // See http://bugs.webkit.org/show_bug.cgi?id=5727
-    if (!frame() && !import())
+    LocalFrame* frame = executingFrame();
+    if (!frame)
         return false;
-    if (!node->document().frame() && !node->document().import())
+    if (!node->document().executingFrame())
         return false;
-    if (!contextDocument().get()->frame()->script().canExecuteScripts(AboutToExecuteScript))
+    if (!frame->script().canExecuteScripts(AboutToExecuteScript))
         return false;
     return true;
 }
@@ -4475,7 +4923,7 @@ void Document::didUpdateSecurityOrigin()
 {
     if (!m_frame)
         return;
-    m_frame->script().updateSecurityOrigin();
+    m_frame->script().updateSecurityOrigin(securityOrigin());
 }
 
 bool Document::isContextThread() const
@@ -4487,7 +4935,7 @@ void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
 {
     m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
     if (!m_updateFocusAppearanceTimer.isActive())
-        m_updateFocusAppearanceTimer.startOneShot(0);
+        m_updateFocusAppearanceTimer.startOneShot(0, FROM_HERE);
 }
 
 void Document::cancelFocusAppearanceUpdate()
@@ -4518,23 +4966,29 @@ void Document::detachRange(Range* range)
     m_ranges.remove(range);
 }
 
-CanvasRenderingContext* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
+void Document::getCSSCanvasContext(const String& type, const String& name, int width, int height, RefPtrWillBeRawPtr<CanvasRenderingContext2D>& context2d, RefPtrWillBeRawPtr<WebGLRenderingContext>& context3d)
 {
-    HTMLCanvasElement* element = getCSSCanvasElement(name);
-    if (!element)
-        return 0;
-    element->setSize(IntSize(width, height));
-    return element->getContext(type);
+    HTMLCanvasElement& element = getCSSCanvasElement(name);
+    element.setSize(IntSize(width, height));
+    CanvasRenderingContext* context = element.getContext(type);
+    if (!context)
+        return;
+
+    if (context->is2d()) {
+        context2d = toCanvasRenderingContext2D(context);
+    } else if (context->is3d()) {
+        context3d = toWebGLRenderingContext(context);
+    }
 }
 
-HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
+HTMLCanvasElement& Document::getCSSCanvasElement(const String& name)
 {
-    RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, 0).iterator->value;
+    RefPtrWillBeMember<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, nullptr).storedValue->value;
     if (!element) {
         element = HTMLCanvasElement::create(*this);
         element->setAccelerationDisabled(true);
     }
-    return element.get();
+    return *element;
 }
 
 void Document::initDNSPrefetch()
@@ -4567,130 +5021,78 @@ void Document::reportBlockedScriptExecutionToInspector(const String& directiveTe
     InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
 }
 
-void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
-{
-    internalAddMessage(source, level, message, sourceURL, lineNumber, 0, state);
-}
-
-void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state)
+void Document::addConsoleMessage(PassRefPtrWillBeRawPtr<ConsoleMessage> consoleMessage)
 {
     if (!isContextThread()) {
-        postTask(AddConsoleMessageTask::create(source, level, message));
+        m_taskRunner->postTask(AddConsoleMessageTask::create(consoleMessage->source(), consoleMessage->level(), consoleMessage->message()));
         return;
     }
-    Page* page = this->page();
-    if (!page)
+
+    if (!m_frame)
         return;
 
-    String messageURL = sourceURL;
-    if (!state && sourceURL.isNull() && !lineNumber) {
-        messageURL = url().string();
+    if (!consoleMessage->scriptState() && consoleMessage->url().isNull() && !consoleMessage->lineNumber()) {
+        consoleMessage->setURL(url().string());
         if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
             ScriptableDocumentParser* parser = scriptableDocumentParser();
             if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
-                lineNumber = parser->lineNumber().oneBasedInt();
+                consoleMessage->setLineNumber(parser->lineNumber().oneBasedInt());
         }
     }
-    page->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, state, 0);
-}
-
-void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
-{
-    if (!isContextThread()) {
-        postTask(AddConsoleMessageTask::create(source, level, message));
-        return;
-    }
-
-    if (Page* page = this->page())
-        page->console().addMessage(source, level, message, String(), 0, 0, 0, 0, requestIdentifier);
-}
-
-struct PerformTaskContext {
-    WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
-public:
-    PerformTaskContext(WeakPtr<Document> document, PassOwnPtr<ExecutionContextTask> task)
-        : documentReference(document)
-        , task(task)
-    {
-    }
-
-    WeakPtr<Document> documentReference;
-    OwnPtr<ExecutionContextTask> task;
-};
-
-void Document::didReceiveTask(void* untypedContext)
-{
-    ASSERT(isMainThread());
-
-    OwnPtr<PerformTaskContext> context = adoptPtr(static_cast<PerformTaskContext*>(untypedContext));
-    ASSERT(context);
-
-    Document* document = context->documentReference.get();
-    if (!document)
-        return;
-
-    Page* page = document->page();
-    if ((page && page->defersLoading()) || !document->m_pendingTasks.isEmpty()) {
-        document->m_pendingTasks.append(context->task.release());
-        return;
-    }
-
-    context->task->performTask(document);
+    m_frame->console().addMessage(consoleMessage);
 }
 
+// FIXME(crbug.com/305497): This should be removed after ExecutionContext-LocalDOMWindow migration.
 void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
 {
-    callOnMainThread(didReceiveTask, new PerformTaskContext(m_weakFactory.createWeakPtr(), task));
+    m_taskRunner->postTask(task);
 }
 
-void Document::pendingTasksTimerFired(Timer<Document>*)
+void Document::postInspectorTask(PassOwnPtr<ExecutionContextTask> task)
 {
-    while (!m_pendingTasks.isEmpty()) {
-        OwnPtr<ExecutionContextTask> task = m_pendingTasks[0].release();
-        m_pendingTasks.remove(0);
-        task->performTask(this);
-    }
+    m_taskRunner->postInspectorTask(task);
 }
 
-void Document::suspendScheduledTasks()
+void Document::tasksWereSuspended()
 {
-    ASSERT(!m_scheduledTasksAreSuspended);
-
-    suspendScriptedAnimationControllerCallbacks();
-    suspendActiveDOMObjects();
     scriptRunner()->suspend();
-    m_pendingTasksTimer.stop();
+
     if (m_parser)
         m_parser->suspendScheduledTasks();
-
-    m_scheduledTasksAreSuspended = true;
+    if (m_scriptedAnimationController)
+        m_scriptedAnimationController->suspend();
 }
 
-void Document::resumeScheduledTasks()
+void Document::tasksWereResumed()
 {
-    ASSERT(m_scheduledTasksAreSuspended);
+    scriptRunner()->resume();
 
     if (m_parser)
         m_parser->resumeScheduledTasks();
-    if (!m_pendingTasks.isEmpty())
-        m_pendingTasksTimer.startOneShot(0);
-    scriptRunner()->resume();
-    resumeActiveDOMObjects();
-    resumeScriptedAnimationControllerCallbacks();
+    if (m_scriptedAnimationController)
+        m_scriptedAnimationController->resume();
 
-    m_scheduledTasksAreSuspended = false;
+    MutationObserver::resumeSuspendedObservers();
 }
 
-void Document::suspendScriptedAnimationControllerCallbacks()
+// FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
+// should be moved to LocalDOMWindow once it inherits ExecutionContext
+void Document::suspendScheduledTasks()
 {
-    if (m_scriptedAnimationController)
-        m_scriptedAnimationController->suspend();
+    ExecutionContext::suspendScheduledTasks();
+    m_taskRunner->suspend();
 }
 
-void Document::resumeScriptedAnimationControllerCallbacks()
+void Document::resumeScheduledTasks()
 {
-    if (m_scriptedAnimationController)
-        m_scriptedAnimationController->resume();
+    ExecutionContext::resumeScheduledTasks();
+    m_taskRunner->resume();
+}
+
+bool Document::tasksNeedSuspension()
+{
+    Page* page = this->page();
+    return page && page->defersLoading();
 }
 
 void Document::addToTopLayer(Element* element, const Element* before)
@@ -4726,7 +5128,7 @@ HTMLDialogElement* Document::activeModalDialog() const
     return toHTMLDialogElement(m_topLayerElements.last().get());
 }
 
-void Document::webkitExitPointerLock()
+void Document::exitPointerLock()
 {
     if (!page())
         return;
@@ -4737,7 +5139,7 @@ void Document::webkitExitPointerLock()
     page()->pointerLockController().requestPointerUnlock();
 }
 
-Element* Document::webkitPointerLockElement() const
+Element* Document::pointerLockElement() const
 {
     if (!page() || page()->pointerLockController().lockPending())
         return 0;
@@ -4753,16 +5155,51 @@ void Document::decrementLoadEventDelayCount()
     ASSERT(m_loadEventDelayCount);
     --m_loadEventDelayCount;
 
-    if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
-        m_loadEventDelayTimer.startOneShot(0);
+    if (!m_loadEventDelayCount)
+        checkLoadEventSoon();
+}
+
+void Document::checkLoadEventSoon()
+{
+    if (frame() && !m_loadEventDelayTimer.isActive())
+        m_loadEventDelayTimer.startOneShot(0, FROM_HERE);
+}
+
+bool Document::isDelayingLoadEvent()
+{
+#if ENABLE(OILPAN)
+    // Always delay load events until after garbage collection.
+    // This way we don't have to explicitly delay load events via
+    // incrementLoadEventDelayCount and decrementLoadEventDelayCount in
+    // Node destructors.
+    if (ThreadState::current()->isSweepInProgress()) {
+        if (!m_loadEventDelayCount)
+            checkLoadEventSoon();
+        return true;
+    }
+#endif
+    return m_loadEventDelayCount;
 }
 
+
 void Document::loadEventDelayTimerFired(Timer<Document>*)
 {
     if (frame())
         frame()->loader().checkCompleted();
 }
 
+void Document::loadPluginsSoon()
+{
+    // FIXME: Remove this timer once we don't need to compute layout to load plugins.
+    if (!m_pluginLoadingTimer.isActive())
+        m_pluginLoadingTimer.startOneShot(0, FROM_HERE);
+}
+
+void Document::pluginLoadingTimerFired(Timer<Document>*)
+{
+    updateLayout();
+}
+
 ScriptedAnimationController& Document::ensureScriptedAnimationController()
 {
     if (!m_scriptedAnimationController) {
@@ -4774,7 +5211,7 @@ ScriptedAnimationController& Document::ensureScriptedAnimationController()
     return *m_scriptedAnimationController;
 }
 
-int Document::requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
+int Document::requestAnimationFrame(RequestAnimationFrameCallback* callback)
 {
     return ensureScriptedAnimationController().registerCallback(callback);
 }
@@ -4793,96 +5230,38 @@ void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
     m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
 }
 
-PassRefPtr<Touch> Document::createTouch(DOMWindow* window, EventTarget* target, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const
-{
+PassRefPtrWillBeRawPtr<Touch> Document::createTouch(LocalDOMWindow* window, EventTarget* target, int identifier, double pageX, double pageY, double screenX, double screenY, double radiusX, double radiusY, float rotationAngle, float force) const
+{
+    // Match behavior from when these types were integers, and avoid surprises from someone explicitly
+    // passing Infinity/NaN.
+    if (!std::isfinite(pageX))
+        pageX = 0;
+    if (!std::isfinite(pageY))
+        pageY = 0;
+    if (!std::isfinite(screenX))
+        screenX = 0;
+    if (!std::isfinite(screenY))
+        screenY = 0;
+    if (!std::isfinite(radiusX))
+        radiusX = 0;
+    if (!std::isfinite(radiusY))
+        radiusY = 0;
+    if (!std::isfinite(rotationAngle))
+        rotationAngle = 0;
+    if (!std::isfinite(force))
+        force = 0;
+
     // FIXME: It's not clear from the documentation at
     // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
     // when this method should throw and nor is it by inspection of iOS behavior. It would be nice to verify any cases where it throws under iOS
     // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
-    Frame* frame = window ? window->frame() : this->frame();
-    return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
-}
-
-PassRefPtr<TouchList> Document::createTouchList(Vector<RefPtr<Touch> >& touches) const
-{
-    return TouchList::create(touches);
-}
-
-void Document::didAddTouchEventHandler(Node* handler)
-{
-    if (!m_touchEventTargets.get())
-        m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
-    m_touchEventTargets->add(handler);
-    if (Document* parent = parentDocument()) {
-        parent->didAddTouchEventHandler(this);
-        return;
-    }
-    if (Page* page = this->page()) {
-        if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
-            scrollingCoordinator->touchEventTargetRectsDidChange(this);
-        if (m_touchEventTargets->size() == 1)
-            page->chrome().client().needTouchEvents(true);
-    }
-}
-
-void Document::didRemoveTouchEventHandler(Node* handler)
-{
-    if (!m_touchEventTargets.get())
-        return;
-    ASSERT(m_touchEventTargets->contains(handler));
-    m_touchEventTargets->remove(handler);
-    if (Document* parent = parentDocument()) {
-        parent->didRemoveTouchEventHandler(this);
-        return;
-    }
-
-    Page* page = this->page();
-    if (!page)
-        return;
-    if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
-        scrollingCoordinator->touchEventTargetRectsDidChange(this);
-    if (m_touchEventTargets->size())
-        return;
-    for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (frame->document() && frame->document()->hasTouchEventHandlers())
-            return;
-    }
-    page->chrome().client().needTouchEvents(false);
-}
-
-void Document::didRemoveEventTargetNode(Node* handler)
-{
-    if (m_touchEventTargets && !m_touchEventTargets->isEmpty()) {
-        if (handler == this)
-            m_touchEventTargets->clear();
-        else
-            m_touchEventTargets->removeAll(handler);
-        if (m_touchEventTargets->isEmpty() && parentDocument())
-            parentDocument()->didRemoveEventTargetNode(this);
-    }
-}
-
-void Document::resetLastHandledUserGestureTimestamp()
-{
-    m_lastHandledUserGestureTimestamp = currentTime();
-}
-
-HTMLIFrameElement* Document::seamlessParentIFrame() const
-{
-    if (!shouldDisplaySeamlesslyWithParent())
-        return 0;
-
-    return toHTMLIFrameElement(this->ownerElement());
+    LocalFrame* frame = window ? window->frame() : this->frame();
+    return Touch::create(frame, target, identifier, FloatPoint(screenX, screenY), FloatPoint(pageX, pageY), FloatSize(radiusX, radiusY), rotationAngle, force);
 }
 
-bool Document::shouldDisplaySeamlesslyWithParent() const
+PassRefPtrWillBeRawPtr<TouchList> Document::createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >& touches) const
 {
-    if (!RuntimeEnabledFeatures::seamlessIFramesEnabled())
-        return false;
-    HTMLFrameOwnerElement* ownerElement = this->ownerElement();
-    if (!ownerElement)
-        return false;
-    return m_mayDisplaySeamlesslyWithParent && ownerElement->hasTagName(iframeTag) && ownerElement->fastHasAttribute(seamlessAttr);
+    return TouchList::adopt(touches);
 }
 
 DocumentLoader* Document::loader() const
@@ -4904,7 +5283,7 @@ IntSize Document::initialViewportSize() const
 {
     if (!view())
         return IntSize();
-    return view()->unscaledVisibleContentSize(ScrollableArea::IncludeScrollbars);
+    return view()->unscaledVisibleContentSize(IncludeScrollbars);
 }
 
 Node* eventTargetNodeForDocument(Document* doc)
@@ -4923,25 +5302,25 @@ Node* eventTargetNodeForDocument(Document* doc)
     return node;
 }
 
-void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject* renderer)
+void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
 {
     if (!view())
         return;
 
     LayoutRect visibleContentRect = view()->visibleContentRect();
     for (size_t i = 0; i < quads.size(); ++i) {
-        quads[i].move(-visibleContentRect.x(), -visibleContentRect.y());
+        quads[i].move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
         adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
     }
 }
 
-void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject* renderer)
+void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
 {
     if (!view())
         return;
 
     LayoutRect visibleContentRect = view()->visibleContentRect();
-    rect.move(-visibleContentRect.x(), -visibleContentRect.y());
+    rect.move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
     adjustFloatRectForAbsoluteZoom(rect, renderer);
 }
 
@@ -4955,16 +5334,12 @@ void Document::decrementActiveParserCount()
     --m_activeParserCount;
     if (!frame())
         return;
-    // FIXME: This should always be enabled, but it seems to cause
-    // http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
-    // see http://webkit.org/b/110554 and http://webkit.org/b/110401
-    loader()->checkLoadComplete();
     frame()->loader().checkLoadComplete();
 }
 
-void Document::setContextFeatures(PassRefPtr<ContextFeatures> features)
+void Document::setContextFeatures(ContextFeatures& features)
 {
-    m_contextFeatures = features;
+    m_contextFeatures = PassRefPtrWillBeRawPtr<ContextFeatures>(features);
 }
 
 static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
@@ -4986,51 +5361,47 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
 {
     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);
         innerElementInDocument = innerElementInDocument->document().ownerElement();
     }
 
-    Element* oldActiveElement = activeElement();
+    Element* oldActiveElement = activeHoverElement();
     if (oldActiveElement && !request.active()) {
-        // We are clearing the :active chain because the mouse has been released.
-        for (RenderObject* curr = oldActiveElement->renderer(); curr; curr = curr->parent()) {
-            if (curr->node()) {
-                ASSERT(!curr->node()->isTextNode());
-                curr->node()->setActive(false);
-                m_userActionElements.setInActiveChain(curr->node(), false);
-            }
+        // The oldActiveElement renderer is null, dropped on :active by setting display: none,
+        // for instance. We still need to clear the ActiveChain as the mouse is released.
+        for (Node* node = oldActiveElement; node; node = NodeRenderingTraversal::parent(node)) {
+            ASSERT(!node->isTextNode());
+            node->setActive(false);
+            m_userActionElements.setInActiveChain(node, false);
         }
-        setActiveElement(0);
+        setActiveHoverElement(nullptr);
     } else {
         Element* newActiveElement = innerElementInDocument;
-        if (!oldActiveElement && newActiveElement && request.active() && !request.touchMove()) {
+        if (!oldActiveElement && newActiveElement && !newActiveElement->isDisabledFormControl() && request.active() && !request.touchMove()) {
             // We are setting the :active chain and freezing it. If future moves happen, they
             // will need to reference this chain.
-            for (RenderObject* curr = newActiveElement->renderer(); curr; curr = curr->parent()) {
-                if (curr->node() && !curr->isText())
-                    m_userActionElements.setInActiveChain(curr->node(), true);
+            for (Node* node = newActiveElement; node; node = NodeRenderingTraversal::parent(node)) {
+                ASSERT(!node->isTextNode());
+                m_userActionElements.setInActiveChain(node, true);
             }
-
-            setActiveElement(newActiveElement);
+            setActiveHoverElement(newActiveElement);
         }
     }
     // If the mouse has just been pressed, set :active on the chain. Those (and only those)
     // nodes should remain :active until the mouse is released.
-    bool allowActiveChanges = !oldActiveElement && activeElement();
+    bool allowActiveChanges = !oldActiveElement && activeHoverElement();
 
     // If the mouse is down and if this is a mouse move event, we want to restrict changes in
     // :hover/:active to only apply to elements that are in the :active chain that we froze
     // at the time the mouse went down.
     bool mustBeInActiveChain = request.active() && request.move();
 
-    RefPtr<Node> oldHoverNode = hoverNode();
-
-    // A touch release does not set a new hover target; setting the element we're working with to 0
-    // will clear the chain of hovered elements all the way to the top of the tree.
-    if (request.touchRelease())
-        innerElementInDocument = 0;
+    RefPtrWillBeRawPtr<Node> oldHoverNode = hoverNode();
 
     // Check to see if the hovered node has changed.
     // If it hasn't, we do not need to do anything.
@@ -5047,9 +5418,10 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
 
     // Locate the common ancestor render object for the two renderers.
     RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
+    RefPtrWillBeRawPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
 
-    Vector<RefPtr<Node>, 32> nodesToRemoveFromChain;
-    Vector<RefPtr<Node>, 32> nodesToAddToChain;
+    WillBeHeapVector<RefPtrWillBeMember<Node>, 32> nodesToRemoveFromChain;
+    WillBeHeapVector<RefPtrWillBeMember<Node>, 32> nodesToAddToChain;
 
     if (oldHoverObj != newHoverObj) {
         // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
@@ -5113,7 +5485,7 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
     size_t addCount = nodesToAddToChain.size();
     for (size_t i = 0; i < addCount; ++i) {
         // Elements past the common ancestor do not change hover state, but might change active state.
-        if (ancestor && nodesToAddToChain[i] == ancestor->node())
+        if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
             sawCommonAncestor = true;
         if (allowActiveChanges)
             nodesToAddToChain[i]->setActive(true);
@@ -5123,13 +5495,11 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
                 nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
         }
     }
-
-    updateStyleIfNeeded();
 }
 
 bool Document::haveStylesheetsLoaded() const
 {
-    return !m_styleEngine->hasPendingSheets() || m_ignorePendingStylesheets;
+    return m_styleEngine->haveStylesheetsLoaded();
 }
 
 Locale& Document::getCachedLocale(const AtomicString& locale)
@@ -5139,24 +5509,26 @@ Locale& Document::getCachedLocale(const AtomicString& locale)
         return Locale::defaultLocale();
     LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
     if (result.isNewEntry)
-        result.iterator->value = Locale::create(localeKey);
-    return *(result.iterator->value);
+        result.storedValue->value = Locale::create(localeKey);
+    return *(result.storedValue->value);
 }
 
 Document& Document::ensureTemplateDocument()
 {
-    if (const Document* document = templateDocument())
-        return *const_cast<Document*>(document);
+    if (isTemplateDocument())
+        return *this;
+
+    if (m_templateDocument)
+        return *m_templateDocument;
 
     if (isHTMLDocument()) {
-        DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL())
-            .withRegistrationContext(registrationContext());
+        DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
         m_templateDocument = HTMLDocument::create(init);
     } else {
         m_templateDocument = Document::create(DocumentInit(blankURL()));
     }
 
-    m_templateDocument->setTemplateDocumentHost(this); // balanced in dtor.
+    m_templateDocument->m_templateDocumentHost = this; // balanced in dtor.
 
     return *m_templateDocument.get();
 }
@@ -5167,7 +5539,7 @@ void Document::didAssociateFormControl(Element* element)
         return;
     m_associatedFormControls.add(element);
     if (!m_didAssociateFormControlsTimer.isActive())
-        m_didAssociateFormControlsTimer.startOneShot(0);
+        m_didAssociateFormControlsTimer.startOneShot(0, FROM_HERE);
 }
 
 void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
@@ -5176,7 +5548,7 @@ void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
     if (!frame() || !frame()->page())
         return;
 
-    Vector<RefPtr<Element> > associatedFormControls;
+    WillBeHeapVector<RefPtrWillBeMember<Element> > associatedFormControls;
     copyToVector(m_associatedFormControls, associatedFormControls);
 
     frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
@@ -5198,22 +5570,291 @@ DocumentLifecycleNotifier& Document::lifecycleNotifier()
     return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
 }
 
-void Document::removedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
+void Document::removedStyleSheet(StyleSheet* sheet, StyleResolverUpdateMode updateMode)
 {
-    if (!isActive())
+    // 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(updateMode);
+}
+
+void Document::modifiedStyleSheet(StyleSheet* sheet, StyleResolverUpdateMode updateMode)
+{
+    // 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(updateMode);
+}
+
+TextAutosizer* Document::textAutosizer()
+{
+    if (!m_textAutosizer)
+        m_textAutosizer = TextAutosizer::create(this);
+    return m_textAutosizer.get();
+}
+
+void Document::setAutofocusElement(Element* element)
+{
+    if (!element) {
+        m_autofocusElement = nullptr;
+        return;
+    }
+    if (m_hasAutofocused)
         return;
+    m_hasAutofocused = true;
+    ASSERT(!m_autofocusElement);
+    m_autofocusElement = element;
+    m_taskRunner->postTask(AutofocusTask::create());
+}
 
-    styleEngine()->modifiedStyleSheet(sheet);
-    styleResolverChanged(when, updateMode);
+Element* Document::activeElement() const
+{
+    if (Element* element = treeScope().adjustedFocusedElement())
+        return element;
+    return body();
 }
 
-void Document::modifiedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
+void Document::getTransitionElementData(Vector<TransitionElementData>& elementData)
 {
-    if (!isActive())
+    if (!head())
         return;
 
-    styleEngine()->modifiedStyleSheet(sheet);
-    styleResolverChanged(when, updateMode);
+    for (HTMLMetaElement* metaElement = Traversal<HTMLMetaElement>::firstChild(*head()); metaElement; metaElement = Traversal<HTMLMetaElement>::nextSibling(*metaElement)) {
+        if (metaElement->name() != "transition-elements")
+            continue;
+
+        const String& metaElementContents = metaElement->content().string();
+        size_t firstSemicolon = metaElementContents.find(';');
+        if (firstSemicolon == kNotFound)
+            continue;
+
+        TrackExceptionState exceptionState;
+        AtomicString selector(metaElementContents.substring(0, firstSemicolon));
+        RefPtrWillBeRawPtr<StaticElementList> elementList = querySelectorAll(selector, exceptionState);
+        if (!elementList || exceptionState.hadException())
+            continue;
+
+        unsigned nodeListLength = elementList->length();
+        if (!nodeListLength)
+            continue;
+
+        StringBuilder markup;
+        for (unsigned nodeIndex = 0; nodeIndex < nodeListLength; ++nodeIndex) {
+            Element* element = elementList->item(nodeIndex);
+            markup.append(createStyledMarkupForNavigationTransition(element));
+        }
+
+        TransitionElementData newElements;
+        newElements.scope = metaElementContents.substring(firstSemicolon + 1).stripWhiteSpace();
+        newElements.selector = selector;
+        newElements.markup = markup.toString();
+        elementData.append(newElements);
+    }
+}
+
+void Document::hideTransitionElements(const AtomicString& cssSelector)
+{
+    TrackExceptionState exceptionState;
+    RefPtrWillBeRawPtr<StaticElementList> elementList = querySelectorAll(cssSelector, exceptionState);
+    if (elementList && !exceptionState.hadException()) {
+        unsigned nodeListLength = elementList->length();
+
+        for (unsigned nodeIndex = 0; nodeIndex < nodeListLength; ++nodeIndex) {
+            Element* element = elementList->item(nodeIndex);
+            element->setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
+        }
+    }
+}
+
+bool Document::hasFocus() const
+{
+    Page* page = this->page();
+    if (!page)
+        return false;
+    if (!page->focusController().isActive() || !page->focusController().isFocused())
+        return false;
+    Frame* focusedFrame = page->focusController().focusedFrame();
+    if (focusedFrame && focusedFrame->isLocalFrame()) {
+        if (toLocalFrame(focusedFrame)->tree().isDescendantOf(frame()))
+            return true;
+    }
+    return false;
+}
+
+#if ENABLE(OILPAN)
+template<unsigned type>
+bool shouldInvalidateNodeListCachesForAttr(const HeapHashSet<WeakMember<const LiveNodeListBase> > nodeLists[], const QualifiedName& attrName)
+{
+    if (!nodeLists[type].isEmpty() && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
+        return true;
+    return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeLists, attrName);
+}
+
+template<>
+bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const HeapHashSet<WeakMember<const LiveNodeListBase> >[], const QualifiedName&)
+{
+    return false;
+}
+#else
+template<unsigned type>
+bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
+{
+    if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
+        return true;
+    return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
+}
+
+template<>
+bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
+{
+    return false;
+}
+#endif
+
+bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
+{
+    if (attrName) {
+#if ENABLE(OILPAN)
+        return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeLists, *attrName);
+#else
+        return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
+#endif
+    }
+
+    for (int type = 0; type < numNodeListInvalidationTypes; ++type) {
+#if ENABLE(OILPAN)
+        if (!m_nodeLists[type].isEmpty())
+#else
+        if (m_nodeListCounts[type])
+#endif
+            return true;
+    }
+
+    return false;
+}
+
+void Document::invalidateNodeListCaches(const QualifiedName* attrName)
+{
+    WillBeHeapHashSet<RawPtrWillBeWeakMember<const LiveNodeListBase> >::const_iterator end = m_listsInvalidatedAtDocument.end();
+    for (WillBeHeapHashSet<RawPtrWillBeWeakMember<const LiveNodeListBase> >::const_iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
+        (*it)->invalidateCacheForAttribute(attrName);
+}
+
+void Document::clearWeakMembers(Visitor* visitor)
+{
+    if (m_axObjectCache)
+        m_axObjectCache->clearWeakMembers(visitor);
+}
+
+v8::Handle<v8::Object> Document::wrap(v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
+{
+    // It's possible that no one except for the new wrapper owns this object at
+    // this moment, so we have to prevent GC to collect this object until the
+    // object gets associated with the wrapper.
+    RefPtrWillBeRawPtr<Document> protect(this);
+
+    ASSERT(!DOMDataStore::containsWrapperNonTemplate(this, isolate));
+
+    const WrapperTypeInfo* wrapperType = wrapperTypeInfo();
+
+    if (frame() && frame()->script().initializeMainWorld()) {
+        // initializeMainWorld may have created a wrapper for the object, retry from the start.
+        v8::Handle<v8::Object> wrapper = DOMDataStore::getWrapperNonTemplate(this, isolate);
+        if (!wrapper.IsEmpty())
+            return wrapper;
+    }
+
+    v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, wrapperType, toScriptWrappableBase(), isolate);
+    if (UNLIKELY(wrapper.IsEmpty()))
+        return wrapper;
+
+    wrapperType->installConditionallyEnabledProperties(wrapper, isolate);
+    return associateWithWrapper(wrapperType, wrapper, isolate);
+}
+
+v8::Handle<v8::Object> Document::associateWithWrapper(const WrapperTypeInfo* wrapperType, v8::Handle<v8::Object> wrapper, v8::Isolate* isolate)
+{
+    V8DOMWrapper::associateObjectWithWrapperNonTemplate(this, wrapperType, wrapper, isolate);
+    DOMWrapperWorld& world = DOMWrapperWorld::current(isolate);
+    if (world.isMainWorld() && frame())
+        frame()->script().windowProxy(world)->updateDocumentWrapper(wrapper);
+    return wrapper;
+}
+
+void Document::trace(Visitor* visitor)
+{
+#if ENABLE(OILPAN)
+    visitor->trace(m_importsController);
+    visitor->trace(m_docType);
+    visitor->trace(m_implementation);
+    visitor->trace(m_autofocusElement);
+    visitor->trace(m_focusedElement);
+    visitor->trace(m_hoverNode);
+    visitor->trace(m_activeHoverElement);
+    visitor->trace(m_documentElement);
+    visitor->trace(m_titleElement);
+    visitor->trace(m_markers);
+    visitor->trace(m_cssTarget);
+    visitor->trace(m_currentScriptStack);
+    visitor->trace(m_scriptRunner);
+    visitor->trace(m_transformSourceDocument);
+    visitor->trace(m_listsInvalidatedAtDocument);
+    for (int i = 0; i < numNodeListInvalidationTypes; ++i)
+        visitor->trace(m_nodeLists[i]);
+    visitor->trace(m_cssCanvasElements);
+    visitor->trace(m_topLayerElements);
+    visitor->trace(m_elemSheet);
+    visitor->trace(m_nodeIterators);
+    visitor->trace(m_ranges);
+    visitor->trace(m_styleEngine);
+    visitor->trace(m_formController);
+    visitor->trace(m_visitedLinkState);
+    visitor->trace(m_frame);
+    visitor->trace(m_domWindow);
+    visitor->trace(m_fetcher);
+    visitor->trace(m_parser);
+    visitor->trace(m_contextFeatures);
+    visitor->trace(m_styleSheetList);
+    visitor->trace(m_mediaQueryMatcher);
+    visitor->trace(m_scriptedAnimationController);
+    visitor->trace(m_textAutosizer);
+    visitor->trace(m_registrationContext);
+    visitor->trace(m_customElementMicrotaskRunQueue);
+    visitor->trace(m_elementDataCache);
+    visitor->trace(m_associatedFormControls);
+    visitor->trace(m_useElementsNeedingUpdate);
+    visitor->trace(m_layerUpdateSVGFilterElements);
+    visitor->trace(m_templateDocument);
+    visitor->trace(m_templateDocumentHost);
+    visitor->trace(m_visibilityObservers);
+    visitor->trace(m_userActionElements);
+    visitor->trace(m_svgExtensions);
+    visitor->trace(m_timeline);
+    visitor->trace(m_compositorPendingAnimations);
+    visitor->trace(m_contextDocument);
+    visitor->registerWeakMembers<Document, &Document::clearWeakMembers>(this);
+    DocumentSupplementable::trace(visitor);
+#endif
+    TreeScope::trace(visitor);
+    ContainerNode::trace(visitor);
+    ExecutionContext::trace(visitor);
+    LifecycleContext<Document>::trace(visitor);
 }
 
-} // namespace WebCore
+} // namespace blink
+
+#ifndef NDEBUG
+using namespace blink;
+void showLiveDocumentInstances()
+{
+    WeakDocumentSet& set = liveDocumentSet();
+    fprintf(stderr, "There are %u documents currently alive:\n", set.size());
+    for (WeakDocumentSet::const_iterator it = set.begin(); it != set.end(); ++it) {
+        fprintf(stderr, "- Document %p URL: %s\n", *it, (*it)->url().string().utf8().data());
+    }
+}
+#endif