diff --git a/core/lib/Drupal/Component/Utility/SafeMarkup.php b/core/lib/Drupal/Component/Utility/SafeMarkup.php
index 69d12fe..598b5f1 100644
--- a/core/lib/Drupal/Component/Utility/SafeMarkup.php
+++ b/core/lib/Drupal/Component/Utility/SafeMarkup.php
@@ -91,7 +91,7 @@ public static function set($string, $strategy = 'html') {
    *   TRUE if the string has been marked secure, FALSE otherwise.
    */
   public static function isSafe($string, $strategy = 'html') {
-    return isset(static::$safeStrings[(string) $string][$strategy]) ||
+    return ($string instanceof \Twig_Markup) || isset(static::$safeStrings[(string) $string][$strategy]) ||
       isset(static::$safeStrings[(string) $string]['all']);
   }
 
diff --git a/core/lib/Drupal/Core/Theme/ThemeManager.php b/core/lib/Drupal/Core/Theme/ThemeManager.php
index 6850fcb..c991cf0 100644
--- a/core/lib/Drupal/Core/Theme/ThemeManager.php
+++ b/core/lib/Drupal/Core/Theme/ThemeManager.php
@@ -385,7 +385,7 @@ protected function theme($hook, $variables = array()) {
       $output = $render_function($template_file, $variables);
     }
 
-    return (string) $output;
+    return ($output instanceof \Twig_Markup) ? $output : (string) $output;
   }
 
   /**
diff --git a/core/themes/engines/twig/twig.engine b/core/themes/engines/twig/twig.engine
index 9f8bc4a..b7df114 100644
--- a/core/themes/engines/twig/twig.engine
+++ b/core/themes/engines/twig/twig.engine
@@ -103,7 +103,8 @@ function twig_render_template($template_file, array $variables) {
     $output['debug_info']   .= "\n<!-- BEGIN OUTPUT from '" . SafeMarkup::checkPlain($template_file) . "' -->\n";
     $output['debug_suffix'] .= "\n<!-- END OUTPUT from '" . SafeMarkup::checkPlain($template_file) . "' -->\n\n";
   }
-  return SafeMarkup::set(implode('', $output));
+  // This output has already been rendered and is therefore considered safe.
+  return new \Twig_Markup(implode('', $output), 'UTF-8');
 }
 
 /**
