OSDN Git Service

/cp
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
index f150d8f..820b1ff 100644 (file)
@@ -1,6 +1,6 @@
 /* Handle parameterized types (templates) for GNU C++.
    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
-   2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010
+   2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010, 2011
    Free Software Foundation, Inc.
    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
    Rewritten by Jason Merrill (jason@cygnus.com).
@@ -36,6 +36,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "flags.h"
 #include "cp-tree.h"
 #include "c-family/c-common.h"
+#include "c-family/c-objc.h"
 #include "cp-objcp-common.h"
 #include "tree-inline.h"
 #include "decl.h"
@@ -52,7 +53,7 @@ typedef int (*tree_fn_t) (tree, void*);
 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
    instantiations have been deferred, either because their definitions
    were not yet available, or because we were putting off doing the work.  */
-struct GTY (()) pending_template {
+struct GTY ((chain_next ("%h.next"))) pending_template {
   struct pending_template *next;
   struct tinst_level *tinst;
 };
@@ -108,13 +109,22 @@ static GTY(()) VEC(tree,gc) *canonical_template_parms;
 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
 
+enum template_base_result {
+  tbr_incomplete_type,
+  tbr_ambiguous_baseclass,
+  tbr_success
+};
+
 static void push_access_scope (tree);
 static void pop_access_scope (tree);
+static void push_deduction_access_scope (tree);
+static void pop_deduction_access_scope (tree);
 static bool resolve_overloaded_unification (tree, tree, tree, tree,
-                                           unification_kind_t, int);
+                                           unification_kind_t, int,
+                                           bool);
 static int try_one_overload (tree, tree, tree, tree, tree,
-                            unification_kind_t, int, bool);
-static int unify (tree, tree, tree, tree, int);
+                            unification_kind_t, int, bool, bool);
+static int unify (tree, tree, tree, tree, int, bool);
 static void add_pending_template (tree);
 static tree reopen_tinst_level (struct tinst_level *);
 static tree tsubst_initializer_list (tree, tree);
@@ -128,7 +138,8 @@ static bool check_instantiated_args (tree, tree, tsubst_flags_t);
 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
                                             tree);
 static int type_unification_real (tree, tree, tree, const tree *,
-                                 unsigned int, int, unification_kind_t, int);
+                                 unsigned int, int, unification_kind_t, int,
+                                 bool);
 static void note_template_header (int);
 static tree convert_nontype_argument_function (tree, tree);
 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
@@ -137,7 +148,7 @@ static tree convert_template_argument (tree, tree, tree,
 static int for_each_template_parm (tree, tree_fn_t, void*,
                                   struct pointer_set_t*, bool);
 static tree expand_template_argument_pack (tree);
-static tree build_template_parm_index (int, int, int, tree, tree);
+static tree build_template_parm_index (int, int, int, int, tree, tree);
 static bool inline_needs_template_parms (tree);
 static void push_inline_template_parms_recursive (tree, int);
 static tree retrieve_local_specialization (tree);
@@ -153,7 +164,8 @@ static tree get_bindings (tree, tree, tree, bool);
 static int template_decl_level (tree);
 static int check_cv_quals_for_unify (int, tree, tree);
 static void template_parm_level_and_index (tree, int*, int*);
-static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
+static int unify_pack_expansion (tree, tree, tree,
+                                tree, unification_kind_t, bool, bool);
 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
@@ -165,8 +177,9 @@ static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
 static bool check_specialization_scope (void);
 static tree process_partial_specialization (tree);
 static void set_current_access_from_decl (tree);
-static tree get_template_base (tree, tree, tree, tree);
-static tree try_class_unification (tree, tree, tree, tree);
+static enum template_base_result get_template_base (tree, tree, tree, tree,
+                                                   bool , tree *);
+static tree try_class_unification (tree, tree, tree, tree, bool);
 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
                                           tree, tree);
 static bool template_template_parm_bindings_ok_p (tree, tree);
@@ -187,9 +200,14 @@ static tree tsubst_decl (tree, tree, tsubst_flags_t);
 static void perform_typedefs_access_check (tree tmpl, tree targs);
 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
                                                        location_t);
-static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
 static tree listify (tree);
 static tree listify_autos (tree, tree);
+static tree template_parm_to_arg (tree t);
+static bool arg_from_parm_pack_p (tree, tree);
+static tree current_template_args (void);
+static tree fixup_template_type_parm_type (tree, int);
+static tree fixup_template_parm_index (tree, tree, int);
+static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
 
 /* Make the current scope suitable for access checking when we are
    processing T.  T can be FUNCTION_DECL for instantiated function
@@ -796,7 +814,13 @@ maybe_process_partial_specialization (tree type)
 
   context = TYPE_CONTEXT (type);
 
-  if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
+  if ((CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
+      /* Consider non-class instantiations of alias templates as
+        well.  */
+      || (TYPE_P (type)
+         && TYPE_TEMPLATE_INFO (type)
+         && DECL_LANG_SPECIFIC (TYPE_NAME (type))
+         && DECL_USE_TEMPLATE (TYPE_NAME (type))))
     {
       /* This is for ordinary explicit specialization and partial
         specialization of a template class such as:
@@ -809,7 +833,8 @@ maybe_process_partial_specialization (tree type)
 
         Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
 
-      if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
+      if (CLASS_TYPE_P (type)
+         && CLASSTYPE_IMPLICIT_INSTANTIATION (type)
          && !COMPLETE_TYPE_P (type))
        {
          check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
@@ -821,8 +846,16 @@ maybe_process_partial_specialization (tree type)
                return error_mark_node;
            }
        }
-      else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
+      else if (CLASS_TYPE_P (type)
+              && CLASSTYPE_TEMPLATE_INSTANTIATION (type))
        error ("specialization of %qT after instantiation", type);
+
+      if (DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (type)))
+       {
+         error ("partial specialization of alias template %qD",
+                TYPE_TI_TEMPLATE (type));
+         return error_mark_node;
+       }
     }
   else if (CLASS_TYPE_P (type)
           && !CLASSTYPE_USE_TEMPLATE (type)
@@ -874,7 +907,8 @@ maybe_process_partial_specialization (tree type)
                     instantiation.  Reassign it to the new member
                     specialization template.  */
                  spec_entry elt;
-                 spec_entry **slot;
+                 spec_entry *entry;
+                 void **slot;
 
                  elt.tmpl = most_general_template (tmpl);
                  elt.args = CLASSTYPE_TI_ARGS (inst);
@@ -885,10 +919,10 @@ maybe_process_partial_specialization (tree type)
                  elt.tmpl = tmpl;
                  elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
 
-                 slot = (spec_entry **)
-                   htab_find_slot (type_specializations, &elt, INSERT);
-                 *slot = ggc_alloc_spec_entry ();
-                 **slot = elt;
+                 slot = htab_find_slot (type_specializations, &elt, INSERT);
+                 entry = ggc_alloc_spec_entry ();
+                 *entry = elt;
+                 *slot = entry;
                }
              else if (COMPLETE_OR_OPEN_TYPE_P (inst))
                /* But if we've had an implicit instantiation, that's a
@@ -1276,7 +1310,7 @@ register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
                         hashval_t hash)
 {
   tree fn;
-  spec_entry **slot = NULL;
+  void **slot = NULL;
   spec_entry elt;
 
   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
@@ -1309,10 +1343,10 @@ register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
       if (hash == 0)
        hash = hash_specialization (&elt);
 
-      slot = (spec_entry **)
+      slot =
        htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
       if (*slot)
-       fn = (*slot)->spec;
+       fn = ((spec_entry *) *slot)->spec;
       else
        fn = NULL_TREE;
     }
@@ -1405,11 +1439,12 @@ register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
       && !check_specialization_namespace (tmpl))
     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
 
-  if (!optimize_specialization_lookup_p (tmpl))
+  if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
     {
+      spec_entry *entry = ggc_alloc_spec_entry ();
       gcc_assert (tmpl && args && spec);
-      *slot = ggc_alloc_spec_entry ();
-      **slot = elt;
+      *entry = elt;
+      *slot = entry;
       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
          && PRIMARY_TEMPLATE_P (tmpl)
          && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
@@ -1458,7 +1493,7 @@ hash_specialization (const void *p)
 /* Recursively calculate a hash value for a template argument ARG, for use
    in the hash tables of template specializations.  */
 
-static hashval_t
+hashval_t
 iterative_hash_template_arg (tree arg, hashval_t val)
 {
   unsigned HOST_WIDE_INT i;
@@ -1499,7 +1534,8 @@ iterative_hash_template_arg (tree arg, hashval_t val)
 
     case TYPE_PACK_EXPANSION:
     case EXPR_PACK_EXPANSION:
-      return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
+      val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
+      return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
 
     case TYPE_ARGUMENT_PACK:
     case NONTYPE_ARGUMENT_PACK:
@@ -1511,8 +1547,8 @@ iterative_hash_template_arg (tree arg, hashval_t val)
       return val;
 
     case OVERLOAD:
-      for (; arg; arg = OVL_CHAIN (arg))
-       val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
+      for (; arg; arg = OVL_NEXT (arg))
+       val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
       return val;
 
     case CONSTRUCTOR:
@@ -1528,7 +1564,10 @@ iterative_hash_template_arg (tree arg, hashval_t val)
 
     case PARM_DECL:
       if (!DECL_ARTIFICIAL (arg))
-       val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
+       {
+         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
+         val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
+       }
       return iterative_hash_template_arg (TREE_TYPE (arg), val);
 
     case TARGET_EXPR:
@@ -1561,13 +1600,6 @@ iterative_hash_template_arg (tree arg, hashval_t val)
       val = iterative_hash_object (code, val);
       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
 
-    case ARRAY_TYPE:
-      /* layout_type sets structural equality for arrays of
-        incomplete type, so we can't rely on the canonical type
-        for hashing.  */
-      val = iterative_hash_template_arg (TREE_TYPE (arg), val);
-      return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
-
     case LAMBDA_EXPR:
       /* A lambda can't appear in a template arg, but don't crash on
         erroneous input.  */
@@ -1575,6 +1607,7 @@ iterative_hash_template_arg (tree arg, hashval_t val)
       return val;
 
     case CAST_EXPR:
+    case IMPLICIT_CONV_EXPR:
     case STATIC_CAST_EXPR:
     case REINTERPRET_CAST_EXPR:
     case CONST_CAST_EXPR:
@@ -1606,7 +1639,7 @@ iterative_hash_template_arg (tree arg, hashval_t val)
     default:
       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
       {
-       unsigned n = TREE_OPERAND_LENGTH (arg);
+       unsigned n = cp_tree_operand_length (arg);
        for (i = 0; i < n; ++i)
          val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
        return val;
@@ -1625,19 +1658,19 @@ iterative_hash_template_arg (tree arg, hashval_t val)
 bool
 reregister_specialization (tree spec, tree tinfo, tree new_spec)
 {
-  spec_entry **slot;
+  spec_entry *entry;
   spec_entry elt;
 
   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
   elt.args = TI_ARGS (tinfo);
   elt.spec = NULL_TREE;
 
-  slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
-  if (*slot)
+  entry = (spec_entry *) htab_find (decl_specializations, &elt);
+  if (entry != NULL)
     {
-      gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
+      gcc_assert (entry->spec == spec || entry->spec == new_spec);
       gcc_assert (new_spec != NULL_TREE);
-      (*slot)->spec = new_spec;
+      entry->spec = new_spec;
       return 1;
     }
 
@@ -1705,7 +1738,6 @@ print_candidates_1 (tree fns, bool more, const char **str)
   for (fn = fns; fn; fn = OVL_NEXT (fn))
     if (TREE_CODE (fn) == TREE_LIST)
       {
-        gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
           print_candidates_1 (TREE_VALUE (fn2),
                               TREE_CHAIN (fn2) || more, str);
@@ -1735,7 +1767,8 @@ print_candidates_1 (tree fns, bool more, const char **str)
     }
 }
 
-/* Print the list of candidate FNS in an error message.  */
+/* Print the list of candidate FNS in an error message.  FNS can also
+   be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
 
 void
 print_candidates (tree fns)
@@ -1788,7 +1821,7 @@ determine_specialization (tree template_id,
      with the signature of DECL.  */
   tree templates = NULL_TREE;
   int header_count;
-  struct cp_binding_level *b;
+  cp_binding_level *b;
 
   *targs_out = NULL_TREE;
 
@@ -2728,12 +2761,15 @@ template_parameter_pack_p (const_tree parm)
   if (TREE_CODE (parm) == PARM_DECL)
     return (DECL_TEMPLATE_PARM_P (parm) 
             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
+  if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
+    return TEMPLATE_PARM_PARAMETER_PACK (parm);
 
   /* If this is a list of template parameters, we could get a
      TYPE_DECL or a TEMPLATE_DECL.  */ 
   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
     parm = TREE_TYPE (parm);
 
+  /* Otherwise it must be a type template parameter.  */
   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
           || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
          && TEMPLATE_TYPE_PARAMETER_PACK (parm));
@@ -2822,8 +2858,8 @@ make_ith_pack_parameter_name (tree name, int i)
   return get_identifier (newname);
 }
 
-/* Return true if T is a primary function
-   or class template instantiation.  */
+/* Return true if T is a primary function, class or alias template
+   instantiation.  */
 
 bool
 primary_template_instantiation_p (const_tree t)
@@ -2835,9 +2871,14 @@ primary_template_instantiation_p (const_tree t)
     return DECL_LANG_SPECIFIC (t)
           && DECL_TEMPLATE_INSTANTIATION (t)
           && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
-  else if (CLASS_TYPE_P (t))
+  else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
           && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
+  else if (TYPE_P (t)
+          && TYPE_TEMPLATE_INFO (t)
+          && PRIMARY_TEMPLATE_P (TYPE_TI_TEMPLATE (t))
+          && DECL_TEMPLATE_INSTANTIATION (TYPE_NAME (t)))
+    return true;
   return false;
 }
 
@@ -2935,6 +2976,20 @@ find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
     (struct find_parameter_pack_data*)data;
   bool parameter_pack_p = false;
 
+  /* Handle type aliases/typedefs.  */
+  if (TYPE_P (t)
+      && TYPE_NAME (t)
+      && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL
+      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
+    {
+      if (TYPE_TEMPLATE_INFO (t))
+       cp_walk_tree (&TYPE_TI_ARGS (t),
+                     &find_parameter_packs_r,
+                     ppd, ppd->visited);
+      *walk_subtrees = 0;
+      return NULL_TREE;
+    }
+
   /* Identify whether this is a parameter pack or not.  */
   switch (TREE_CODE (t))
     {
@@ -2944,6 +2999,7 @@ find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
       break;
 
     case TEMPLATE_TYPE_PARM:
+      t = TYPE_MAIN_VARIANT (t);
     case TEMPLATE_TEMPLATE_PARM:
       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
         parameter_pack_p = true;
@@ -2959,6 +3015,9 @@ find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
         }
       break;
 
+    case BASES:
+      parameter_pack_p = true;
+      break;
     default:
       /* Not a parameter pack.  */
       break;
@@ -3012,6 +3071,7 @@ find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
       *walk_subtrees = 0;
       return NULL_TREE;
 
+    case CONSTRUCTOR:
     case TEMPLATE_DECL:
       cp_walk_tree (&TREE_TYPE (t),
                    &find_parameter_packs_r, ppd, ppd->visited);
@@ -3354,12 +3414,14 @@ check_template_shadow (tree decl)
 }
 
 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
-   ORIG_LEVEL, DECL, and TYPE.  */
+   ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
+   template parameters.  */
 
 static tree
 build_template_parm_index (int index,
                           int level,
                           int orig_level,
+                          int num_siblings,
                           tree decl,
                           tree type)
 {
@@ -3367,6 +3429,7 @@ build_template_parm_index (int index,
   TEMPLATE_PARM_IDX (t) = index;
   TEMPLATE_PARM_LEVEL (t) = level;
   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
+  TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
   TEMPLATE_PARM_DECL (t) = decl;
   TREE_TYPE (t) = type;
   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
@@ -3378,6 +3441,7 @@ build_template_parm_index (int index,
 /* Find the canonical type parameter for the given template type
    parameter.  Returns the canonical type parameter, which may be TYPE
    if no such parameter existed.  */
+
 static tree
 canonical_type_parameter (tree type)
 {
@@ -3431,6 +3495,7 @@ reduce_template_parm_level (tree index, tree type, int levels, tree args,
       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
                                     TEMPLATE_PARM_LEVEL (index) - levels,
                                     TEMPLATE_PARM_ORIG_LEVEL (index),
+                                    TEMPLATE_PARM_NUM_SIBLINGS (index),
                                     decl, type);
       TEMPLATE_PARM_DESCENDANTS (index) = t;
       TEMPLATE_PARM_PARAMETER_PACK (t) 
@@ -3446,15 +3511,20 @@ reduce_template_parm_level (tree index, tree type, int levels, tree args,
   return TEMPLATE_PARM_DESCENDANTS (index);
 }
 
-/* Process information from new template parameter PARM and append it to the
-   LIST being built.  This new parameter is a non-type parameter iff
-   IS_NON_TYPE is true. This new parameter is a parameter
-   pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
-   PARM_LOC.  */
+/* Process information from new template parameter PARM and append it
+   to the LIST being built.  This new parameter is a non-type
+   parameter iff IS_NON_TYPE is true. This new parameter is a
+   parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
+   is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
+   parameter list PARM belongs to. This is used used to create a
+   proper canonical type for the type of PARM that is to be created,
+   iff PARM is a type.  If the size is not known, this parameter shall
+   be set to 0.  */
 
 tree
-process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
-                       bool is_parameter_pack)
+process_template_parm (tree list, location_t parm_loc, tree parm,
+                      bool is_non_type, bool is_parameter_pack,
+                      unsigned num_template_parms)
 {
   tree decl = 0;
   tree defval;
@@ -3529,6 +3599,7 @@ process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_ty
       DECL_INITIAL (parm) = DECL_INITIAL (decl)
        = build_template_parm_index (idx, processing_template_decl,
                                     processing_template_decl,
+                                    num_template_parms,
                                     decl, TREE_TYPE (parm));
 
       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
@@ -3562,6 +3633,7 @@ process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_ty
       TEMPLATE_TYPE_PARM_INDEX (t)
        = build_template_parm_index (idx, processing_template_decl,
                                     processing_template_decl,
+                                    num_template_parms,
                                     decl, TREE_TYPE (parm));
       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
       TYPE_CANONICAL (t) = canonical_type_parameter (t);
@@ -3594,9 +3666,6 @@ end_template_parm_list (tree parms)
       next = TREE_CHAIN (parm);
       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
       TREE_CHAIN (parm) = NULL_TREE;
-      if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
-       TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
-             current_template_parms;
     }
 
   --processing_template_parmlist;
@@ -3604,6 +3673,305 @@ end_template_parm_list (tree parms)
   return saved_parmlist;
 }
 
+/* Create a new type almost identical to TYPE but which has the
+   following differences:
+
+     1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
+     template sibling parameters of T.
+
+     2/ T has a new canonical type that matches the new number
+     of sibling parms.
+
+     3/ From now on, T is going to be what lookups referring to the
+     name of TYPE will return. No lookup should return TYPE anymore.
+
+   NUM_PARMS is the new number of sibling parms TYPE belongs to.
+
+   This is a subroutine of fixup_template_parms.  */
+
+static tree
+fixup_template_type_parm_type (tree type, int num_parms)
+{
+  tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
+  tree t;
+  /* This is the decl which name is inserted into the symbol table for
+     the template parm type. So whenever we lookup the type name, this
+     is the DECL we get.  */
+  tree decl;
+
+  /* Do not fix up the type twice.  */
+  if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
+    return type;
+
+  t = copy_type (type);
+  decl = TYPE_NAME (t);
+
+  TYPE_MAIN_VARIANT (t) = t;
+  TYPE_NEXT_VARIANT (t)= NULL_TREE;
+  TYPE_POINTER_TO (t) = 0;
+  TYPE_REFERENCE_TO (t) = 0;
+
+  idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
+                                  TEMPLATE_PARM_LEVEL (orig_idx),
+                                  TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
+                                  num_parms,
+                                  decl, t);
+  TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
+  TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
+  TEMPLATE_TYPE_PARM_INDEX (t) = idx;
+
+  TYPE_STUB_DECL (t) = decl;
+  TEMPLATE_TYPE_DECL (t) = decl;
+  if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
+    TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
+
+  /* Update the type associated to the type name stored in the symbol
+     table. Now, whenever the type name is looked up, the resulting
+     type is properly fixed up.  */
+  TREE_TYPE (decl) = t;
+
+  TYPE_CANONICAL (t) = canonical_type_parameter (t);
+
+  return t;
+}
+
+/* Create and return a new TEMPLATE_PARM_INDEX that is almost
+   identical to I, but that is fixed up as to:
+
+   1/ carry the number of sibling parms (NUM_PARMS) of the template
+   parm represented by I.
+
+   2/ replace all references to template parm types declared before I
+   (in the same template parm list as I) by references to template
+   parm types contained in ARGS. ARGS should contain the list of
+   template parms that have been fixed up so far, in a form suitable
+   to be passed to tsubst.
+
+   This is a subroutine of fixup_template_parms.  */
+
+static tree
+fixup_template_parm_index (tree i, tree args, int num_parms)
+{
+  tree index, decl, type;
+
+  if (i == NULL_TREE
+      || TREE_CODE (i) != TEMPLATE_PARM_INDEX
+      /* Do not fix up the index twice.  */
+      || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
+    return i;
+
+  decl = TEMPLATE_PARM_DECL (i);
+  type = TREE_TYPE (decl);
+
+  index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
+                                    TEMPLATE_PARM_LEVEL (i),
+                                    TEMPLATE_PARM_ORIG_LEVEL (i),
+                                    num_parms,
+                                    decl, type);
+
+  TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
+  TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
+
+  type = tsubst (type, args, tf_none, NULL_TREE);
+  
+  TREE_TYPE (decl) = type;
+  TREE_TYPE (index) = type;
+
+  return index;
+}
+
+/* 
+   This is a subroutine of fixup_template_parms.
+
+   It computes the canonical type of the type of the template
+   parameter PARM_DESC and update all references to that type so that
+   they use the newly computed canonical type. No access check is
+   performed during the fixup. PARM_DESC is a TREE_LIST which
+   TREE_VALUE is the template parameter and its TREE_PURPOSE is the
+   default argument of the template parm if any. IDX is the index of
+   the template parameter, starting at 0. NUM_PARMS is the number of
+   template parameters in the set PARM_DESC belongs to. ARGLIST is a
+   TREE_VEC containing the full set of template parameters in a form
+   suitable to be passed to substs functions as their ARGS
+   argument. This is what current_template_args returns for a given
+   template. The innermost vector of args in ARGLIST is the set of
+   template parms that have been fixed up so far. This function adds
+   the fixed up parameter into that vector.  */
+
+static void
+fixup_template_parm (tree parm_desc,
+                    int idx,
+                    int num_parms,
+                    tree arglist)
+{
+  tree parm = TREE_VALUE (parm_desc);
+  tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
+
+  push_deferring_access_checks (dk_no_check);
+
+  if (TREE_CODE (parm) == TYPE_DECL)
+    {
+      /* PARM is a template type parameter. Fix up its type, add
+        the fixed-up template parm to the vector of fixed-up
+        template parms so far, and substitute the fixed-up
+        template parms into the default argument of this
+        parameter.  */
+      tree t =
+       fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
+      TREE_TYPE (parm) = t;
+
+      TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
+    }
+  else if (TREE_CODE (parm) == TEMPLATE_DECL)
+    {
+      /* PARM is a template template parameter. This is going to
+        be interesting.  */
+      tree tparms, targs, innermost_args, t;
+      int j;
+
+      /* First, fix up the parms of the template template parm
+        because the parms are involved in defining the new canonical
+        type of the template template parm.  */
+
+      /* So we need to substitute the template parm types that have
+        been fixed up so far into the template parms of this template
+        template parm. E.g, consider this:
+
+        template<class T, template<T u> class TT> class S;
+
+        In this case we want to substitute T into the
+        template parameters of TT.
+
+        So let's walk the template parms of PARM here, and
+        tsubst ARGLIST into into each of the template
+        parms.   */
+
+      /* For this substitution we need to build the full set of
+        template parameters and use that as arguments for the
+        tsubsting function.  */
+      tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
+
+      /* This will contain the innermost parms of PARM into which
+        we have substituted so far.  */
+      innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
+      targs = add_to_template_args (arglist, innermost_args);
+      for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
+       {
+         tree parameter;
+
+         parameter = TREE_VEC_ELT (tparms, j);
+
+         /* INNERMOST_ARGS needs to have at least the same number
+            of elements as the index PARAMETER, ortherwise
+            tsubsting into PARAMETER will result in partially
+            instantiating it, reducing its tempate parm
+            level. Let's tactically fill INNERMOST_ARGS for that
+            purpose.  */
+         TREE_VEC_ELT (innermost_args, j) =
+           template_parm_to_arg (parameter);
+
+         fixup_template_parm (parameter, j,
+                              TREE_VEC_LENGTH (tparms),
+                              targs);
+       }
+
+      /* Now fix up the type of the template template parm.  */
+
+      t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
+      TREE_TYPE (parm) = t;
+
+      TREE_VEC_ELT (fixedup_args, idx) =
+       template_parm_to_arg (parm_desc);
+    }
+  else if (TREE_CODE (parm) == PARM_DECL)
+    {
+      /* PARM is a non-type template parameter. We need to:
+
+       * Fix up its TEMPLATE_PARM_INDEX to make it carry the
+       proper number of sibling parameters.
+
+       * Make lookups of the template parameter return a reference
+       to the fixed-up index. No lookup should return references
+       to the former index anymore.
+
+       * Substitute the template parms that got fixed up so far
+
+       * into the type of PARM.  */
+
+      tree index = DECL_INITIAL (parm);
+
+      /* PUSHED_DECL is the decl added to the symbol table with
+        the name of the parameter. E,g:
+            
+        template<class T, T u> //#0
+        auto my_function(T t) -> decltype(u); //#1
+
+        Here, when looking up u at //#1, we get the decl of u
+        resulting from the declaration in #0. This is what
+        PUSHED_DECL is. We need to replace the reference to the
+        old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
+        fixed-up TEMPLATE_PARM_INDEX.  */
+      tree pushed_decl = TEMPLATE_PARM_DECL (index);
+
+      /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
+        fixup the type of PUSHED_DECL as well and luckily
+        fixup_template_parm_index does it for us too.  */
+      tree fixed_up_index =
+       fixup_template_parm_index (index, arglist, num_parms);
+
+      DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
+
+      /* Add this fixed up PARM to the template parms we've fixed
+        up so far and use that to substitute the fixed-up
+        template parms into the type of PARM.  */
+      TREE_VEC_ELT (fixedup_args, idx) =
+       template_parm_to_arg (parm_desc);
+      TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
+                                tf_none, NULL_TREE);
+    }
+
+  TREE_PURPOSE (parm_desc) =
+    tsubst_template_arg (TREE_PURPOSE (parm_desc),
+                        arglist, tf_none, parm);
+
+  pop_deferring_access_checks ();
+}
+
+/* Walk the current template parms and properly compute the canonical
+   types of the dependent types created during
+   cp_parser_template_parameter_list.  */
+
+void
+fixup_template_parms (void)
+{
+  tree arglist;
+  tree parameter_vec;
+  tree fixedup_args;
+  int i, num_parms;
+
+  parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
+  if (parameter_vec == NULL_TREE)
+    return;
+
+  num_parms = TREE_VEC_LENGTH (parameter_vec);
+
+  /* This vector contains the current innermost template parms that
+     have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
+     to be passed to tsubst* functions as their ARGS argument.  */
+  fixedup_args = make_tree_vec (num_parms);
+
+  /* This vector contains the full set of template parms in a form
+     suitable to be passed to substs functions as their ARGS
+     argument.  */
+  arglist = current_template_args ();
+  arglist = add_outermost_template_args (arglist, fixedup_args);
+
+  /* Let's do the proper fixup now.  */
+  for (i = 0; i < num_parms; ++i)
+    fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
+                        i, num_parms, arglist);
+}
+
 /* end_template_decl is called after a template declaration is seen.  */
 
 void
@@ -3621,6 +3989,125 @@ end_template_decl (void)
   current_template_parms = TREE_CHAIN (current_template_parms);
 }
 
+/* Takes a TREE_LIST representing a template parameter and convert it
+   into an argument suitable to be passed to the type substitution
+   functions.  Note that If the TREE_LIST contains an error_mark
+   node, the returned argument is error_mark_node.  */
+
+static tree
+template_parm_to_arg (tree t)
+{
+
+  if (t == NULL_TREE
+      || TREE_CODE (t) != TREE_LIST)
+    return t;
+
+  if (error_operand_p (TREE_VALUE (t)))
+    return error_mark_node;
+
+  t = TREE_VALUE (t);
+
+  if (TREE_CODE (t) == TYPE_DECL
+      || TREE_CODE (t) == TEMPLATE_DECL)
+    {
+      t = TREE_TYPE (t);
+
+      if (TEMPLATE_TYPE_PARAMETER_PACK (t))
+       {
+         /* Turn this argument into a TYPE_ARGUMENT_PACK
+            with a single element, which expands T.  */
+         tree vec = make_tree_vec (1);
+#ifdef ENABLE_CHECKING
+         SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
+           (vec, TREE_VEC_LENGTH (vec));
+#endif
+         TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
+
+         t = cxx_make_type (TYPE_ARGUMENT_PACK);
+         SET_ARGUMENT_PACK_ARGS (t, vec);
+       }
+    }
+  else
+    {
+      t = DECL_INITIAL (t);
+
+      if (TEMPLATE_PARM_PARAMETER_PACK (t))
+       {
+         /* Turn this argument into a NONTYPE_ARGUMENT_PACK
+            with a single element, which expands T.  */
+         tree vec = make_tree_vec (1);
+         tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
+#ifdef ENABLE_CHECKING
+         SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
+           (vec, TREE_VEC_LENGTH (vec));
+#endif
+         TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
+
+         t  = make_node (NONTYPE_ARGUMENT_PACK);
+         SET_ARGUMENT_PACK_ARGS (t, vec);
+         TREE_TYPE (t) = type;
+       }
+    }
+  return t;
+}
+
+/* This function returns TRUE if PARM_PACK is a template parameter
+   pack and if ARG_PACK is what template_parm_to_arg returned when
+   passed PARM_PACK.  */
+
+static bool
+arg_from_parm_pack_p (tree arg_pack, tree parm_pack)
+{
+  /* For clarity in the comments below let's use the representation
+     argument_pack<elements>' to denote an argument pack and its
+     elements.
+
+     In the 'if' block below, we want to detect cases where
+     ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
+     check if ARG_PACK is an argument pack which sole element is
+     the expansion of PARM_PACK.  That argument pack is typically
+     created by template_parm_to_arg when passed a parameter
+     pack.  */
+
+  if (arg_pack
+      && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
+      && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
+    {
+      tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
+      tree pattern = PACK_EXPANSION_PATTERN (expansion);
+      /* So we have an argument_pack<P...>.  We want to test if P
+        is actually PARM_PACK.  We will not use cp_tree_equal to
+        test P and PARM_PACK because during type fixup (by
+        fixup_template_parm) P can be a pre-fixup version of a
+        type and PARM_PACK be its post-fixup version.
+        cp_tree_equal would consider them as different even
+        though we would want to consider them compatible for our
+        precise purpose here.
+
+        Thus we are going to consider that P and PARM_PACK are
+        compatible if they have the same DECL.  */
+      if ((/* If ARG_PACK is a type parameter pack named by the
+             same DECL as parm_pack ...  */
+          (TYPE_P (pattern)
+           && TYPE_P (parm_pack)
+           && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
+          /* ... or if PARM_PACK is a non-type parameter named by the
+             same DECL as ARG_PACK.  Note that PARM_PACK being a
+             non-type parameter means it's either a PARM_DECL or a
+             TEMPLATE_PARM_INDEX.  */
+          || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
+              && ((TREE_CODE (parm_pack) == PARM_DECL
+                   && (TEMPLATE_PARM_DECL (pattern)
+                       == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
+                  || (TREE_CODE (parm_pack) == TEMPLATE_PARM_INDEX
+                      && (TEMPLATE_PARM_DECL (pattern)
+                          == TEMPLATE_PARM_DECL (parm_pack))))))
+         && template_parameter_pack_p (pattern))
+       return true;
+    }
+  return false;
+}
+
 /* Within the declaration of a template, return all levels of template
    parameters that apply.  The template parameters are represented as
    a TREE_VEC, in the form documented in cp-tree.h for template
@@ -3647,63 +4134,7 @@ current_template_args (void)
 
       TREE_TYPE (a) = NULL_TREE;
       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
-       {
-         tree t = TREE_VEC_ELT (a, i);
-
-         /* T will be a list if we are called from within a
-            begin/end_template_parm_list pair, but a vector directly
-            if within a begin/end_member_template_processing pair.  */
-         if (TREE_CODE (t) == TREE_LIST)
-           {
-             t = TREE_VALUE (t);
-
-             if (!error_operand_p (t))
-               {
-                 if (TREE_CODE (t) == TYPE_DECL
-                     || TREE_CODE (t) == TEMPLATE_DECL)
-                    {
-                      t = TREE_TYPE (t);
-                      
-                      if (TEMPLATE_TYPE_PARAMETER_PACK (t))
-                        {
-                          /* Turn this argument into a TYPE_ARGUMENT_PACK
-                             with a single element, which expands T.  */
-                          tree vec = make_tree_vec (1);
-#ifdef ENABLE_CHECKING
-                         SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
-                               (vec, TREE_VEC_LENGTH (vec));
-#endif
-                          TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
-                          
-                          t = cxx_make_type (TYPE_ARGUMENT_PACK);
-                          SET_ARGUMENT_PACK_ARGS (t, vec);
-                        }
-                    }
-                  else
-                    {
-                      t = DECL_INITIAL (t);
-                      
-                      if (TEMPLATE_PARM_PARAMETER_PACK (t))
-                        {
-                          /* Turn this argument into a NONTYPE_ARGUMENT_PACK
-                             with a single element, which expands T.  */
-                          tree vec = make_tree_vec (1);
-                          tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
-#ifdef ENABLE_CHECKING
-                         SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
-                               (vec, TREE_VEC_LENGTH (vec));
-#endif
-                          TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
-                          
-                          t  = make_node (NONTYPE_ARGUMENT_PACK);
-                          SET_ARGUMENT_PACK_ARGS (t, vec);
-                          TREE_TYPE (t) = type;
-                        }
-                    }
-                 TREE_VEC_ELT (a, i) = t;
-                }
-           }
-       }
+       TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
 
 #ifdef ENABLE_CHECKING
       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
@@ -3715,6 +4146,21 @@ current_template_args (void)
        args = a;
     }
 
+    if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
+      /* This can happen for template parms of a template template
+        parameter, e.g:
+
+        template<template<class T, class U> class TT> struct S;
+
+        Consider the level of the parms of TT; T and U both have
+        level 2; TT has no template parm of level 1. So in this case
+        the first element of full_template_args is NULL_TREE. If we
+        leave it like this TMPL_ARG_DEPTH on args returns 1 instead
+        of 2. This will make tsubst wrongly consider that T and U
+        have level 1. Instead, let's create a dummy vector as the
+        first element of full_template_args so that TMPL_ARG_DEPTH
+        returns the correct depth for args.  */
+      TREE_VEC_ELT (args, 0) = make_tree_vec (1);
   return args;
 }
 
@@ -3779,6 +4225,7 @@ build_template_decl (tree decl, tree parms, bool member_template_p)
   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
   DECL_TEMPLATE_PARMS (tmpl) = parms;
   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
+  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
 
   return tmpl;
@@ -4238,7 +4685,7 @@ check_default_tmpl_args (tree decl, tree parms, int is_primary,
             "friend declarations");
   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
     msg = G_("default template arguments may not be used in function templates "
-            "without -std=c++0x or -std=gnu++0x");
+            "without -std=c++11 or -std=gnu++11");
   else if (is_partial)
     msg = G_("default template arguments may not be used in "
             "partial specializations");
@@ -4401,7 +4848,7 @@ push_template_decl_real (tree decl, bool is_friend)
              return error_mark_node;
            }
          if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
-             && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
+             && (!prototype_p (TREE_TYPE (decl))
                  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
                  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
                  || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
@@ -4419,6 +4866,10 @@ push_template_decl_real (tree decl, bool is_friend)
       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
               && CLASS_TYPE_P (TREE_TYPE (decl)))
        /* OK */;
+      else if (TREE_CODE (decl) == TYPE_DECL
+              && TYPE_DECL_ALIAS_P (decl))
+       /* alias-declaration */
+       gcc_assert (!DECL_ARTIFICIAL (decl));
       else
        {
          error ("template declaration of %q#D", decl);
@@ -4468,7 +4919,10 @@ push_template_decl_real (tree decl, bool is_friend)
       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
        TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
     }
-  else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
+  else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
+                                           && TYPE_DECL_ALIAS_P (decl))
+                                          ? DECL_ORIGINAL_TYPE (decl)
+                                          : TREE_TYPE (decl)))
     {
       TREE_TYPE (decl) = error_mark_node;
       return error_mark_node;
@@ -4683,8 +5137,13 @@ template arguments to %qD do not match original template %qD",
 
   if (DECL_IMPLICIT_TYPEDEF_P (decl))
     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
-  else if (DECL_LANG_SPECIFIC (decl))
-    DECL_TEMPLATE_INFO (decl) = info;
+  else
+    {
+      if (primary && !DECL_LANG_SPECIFIC (decl))
+       retrofit_lang_decl (decl);
+      if (DECL_LANG_SPECIFIC (decl))
+       DECL_TEMPLATE_INFO (decl) = info;
+    }
 
   return DECL_TEMPLATE_RESULT (tmpl);
 }
@@ -4823,6 +5282,7 @@ fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
      as two declarations of the same function, for example.  */
   if (processing_template_decl
       && !type_dependent_expression_p (expr)
+      && potential_constant_expression (expr)
       && !value_dependent_expression_p (expr))
     {
       HOST_WIDE_INT saved_processing_template_decl;
@@ -4846,27 +5306,30 @@ fold_non_dependent_expr (tree expr)
   return fold_non_dependent_expr_sfinae (expr, tf_error);
 }
 
-/* EXPR is an expression which is used in a constant-expression context.
-   For instance, it could be a VAR_DECL with a constant initializer.
-   Extract the innermost constant expression.
-
-   This is basically a more powerful version of
-   integral_constant_value, which can be used also in templates where
-   initializers can maintain a syntactic rather than semantic form
-   (even if they are non-dependent, for access-checking purposes).  */
+/* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
+   template declaration, or a TYPE_DECL for an alias declaration.  */
 
-static tree
-fold_decl_constant_value (tree expr)
+bool
+alias_type_or_template_p (tree t)
 {
-  tree const_expr = expr;
-  do
-    {
-      expr = fold_non_dependent_expr (const_expr);
-      const_expr = integral_constant_value (expr);
-    }
-  while (expr != const_expr);
+  if (t == NULL_TREE)
+    return false;
+  return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
+         || (TYPE_P (t)
+             && TYPE_NAME (t)
+             && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
+         || DECL_ALIAS_TEMPLATE_P (t));
+}
 
-  return expr;
+/* Return TRUE iff is a specialization of an alias template.  */
+
+bool
+alias_template_specialization_p (tree t)
+{
+  if (t == NULL_TREE)
+    return false;
+  return (primary_template_instantiation_p (t)
+         && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (t)));
 }
 
 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
@@ -4879,6 +5342,7 @@ convert_nontype_argument_function (tree type, tree expr)
 {
   tree fns = expr;
   tree fn, fn_no_ptr;
+  linkage_kind linkage;
 
   fn = instantiate_type (type, fns, tf_none);
   if (fn == error_mark_node)
@@ -4887,7 +5351,7 @@ convert_nontype_argument_function (tree type, tree expr)
   fn_no_ptr = fn;
   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
-  if (TREE_CODE (fn_no_ptr) == BASELINK)
+  if (BASELINK_P (fn_no_ptr))
     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
  
   /* [temp.arg.nontype]/1
@@ -4895,12 +5359,19 @@ convert_nontype_argument_function (tree type, tree expr)
      A template-argument for a non-type, non-template template-parameter
      shall be one of:
      [...]
-     -- the address of an object or function with external linkage.  */
-  if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
+     -- the address of an object or function with external [C++11: or
+        internal] linkage.  */
+  linkage = decl_linkage (fn_no_ptr);
+  if (cxx_dialect >= cxx0x ? linkage == lk_none : linkage != lk_external)
     {
-      error ("%qE is not a valid template argument for type %qT "
-            "because function %qD has not external linkage",
-            expr, type, fn_no_ptr);
+      if (cxx_dialect >= cxx0x)
+       error ("%qE is not a valid template argument for type %qT "
+              "because %qD has no linkage",
+              expr, type, fn_no_ptr);
+      else
+       error ("%qE is not a valid template argument for type %qT "
+              "because %qD does not have external linkage",
+              expr, type, fn_no_ptr);
       return NULL_TREE;
     }
 
@@ -4912,14 +5383,20 @@ convert_nontype_argument_function (tree type, tree expr)
    Emit an error otherwise.  */
 
 static bool
-check_valid_ptrmem_cst_expr (tree type, tree expr)
+check_valid_ptrmem_cst_expr (tree type, tree expr,
+                            tsubst_flags_t complain)
 {
   STRIP_NOPS (expr);
   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
     return true;
-  error ("%qE is not a valid template argument for type %qT",
-        expr, type);
-  error ("it must be a pointer-to-member of the form `&X::Y'");
+  if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
+    return true;
+  if (complain & tf_error)
+    {
+      error ("%qE is not a valid template argument for type %qT",
+            expr, type);
+      error ("it must be a pointer-to-member of the form %<&X::Y%>");
+    }
   return false;
 }
 
@@ -4953,54 +5430,267 @@ has_value_dependent_address (tree op)
   return false;
 }
 
-/* Attempt to convert the non-type template parameter EXPR to the
-   indicated TYPE.  If the conversion is successful, return the
-   converted value.  If the conversion is unsuccessful, return
-   NULL_TREE if we issued an error message, or error_mark_node if we
-   did not.  We issue error messages for out-and-out bad template
-   parameters, but not simply because the conversion failed, since we
-   might be just trying to do argument deduction.  Both TYPE and EXPR
-   must be non-dependent.
+/* The next set of functions are used for providing helpful explanatory
+   diagnostics for failed overload resolution.  Their messages should be
+   indented by two spaces for consistency with the messages in
+   call.c  */
 
-   The conversion follows the special rules described in
-   [temp.arg.nontype], and it is much more strict than an implicit
-   conversion.
+static int
+unify_success (bool explain_p ATTRIBUTE_UNUSED)
+{
+  return 0;
+}
 
-   This function is called twice for each template argument (see
-   lookup_template_class for a more accurate description of this
-   problem). This means that we need to handle expressions which
-   are not valid in a C++ source, but can be created from the
-   first call (for instance, casts to perform conversions). These
-   hacks can go away after we fix the double coercion problem.  */
+static int
+unify_parameter_deduction_failure (bool explain_p, tree parm)
+{
+  if (explain_p)
+    inform (input_location,
+           "  couldn't deduce template parameter %qD", parm);
+  return 1;
+}
 
-static tree
-convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
+static int
+unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
 {
-  tree expr_type;
+  return 1;
+}
 
-  /* Detect immediately string literals as invalid non-type argument.
-     This special-case is not needed for correctness (we would easily
-     catch this later), but only to provide better diagnostic for this
-     common user mistake. As suggested by DR 100, we do not mention
-     linkage issues in the diagnostic as this is not the point.  */
-  /* FIXME we're making this OK.  */
-  if (TREE_CODE (expr) == STRING_CST)
-    {
-      if (complain & tf_error)
-       error ("%qE is not a valid template argument for type %qT "
-              "because string literals can never be used in this context",
-              expr, type);
-      return NULL_TREE;
-    }
+static int
+unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
+{
+  if (explain_p)
+    inform (input_location,
+           "  types %qT and %qT have incompatible cv-qualifiers",
+           parm, arg);
+  return 1;
+}
 
-  /* Add the ADDR_EXPR now for the benefit of
-     value_dependent_expression_p.  */
-  if (TYPE_PTROBV_P (type))
-    expr = decay_conversion (expr);
+static int
+unify_type_mismatch (bool explain_p, tree parm, tree arg)
+{
+  if (explain_p)
+    inform (input_location, "  mismatched types %qT and %qT", parm, arg);
+  return 1;
+}
 
-  /* If we are in a template, EXPR may be non-dependent, but still
-     have a syntactic, rather than semantic, form.  For example, EXPR
-     might be a SCOPE_REF, rather than the VAR_DECL to which the
+static int
+unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
+{
+  if (explain_p)
+    inform (input_location,
+           "  template parameter %qD is not a parameter pack, but "
+           "argument %qD is",
+           parm, arg);
+  return 1;
+}
+
+static int
+unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
+{
+  if (explain_p)
+    inform (input_location,
+           "  template argument %qE does not match "
+           "pointer-to-member constant %qE",
+           arg, parm);
+  return 1;
+}
+
+static int
+unify_expression_unequal (bool explain_p, tree parm, tree arg)
+{
+  if (explain_p)
+    inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
+  return 1;
+}
+
+static int
+unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
+{
+  if (explain_p)
+    inform (input_location,
+           "  inconsistent parameter pack deduction with %qT and %qT",
+           old_arg, new_arg);
+  return 1;
+}
+
+static int
+unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
+{
+  if (explain_p)
+    {
+      if (TYPE_P (parm))
+       inform (input_location,
+               "  deduced conflicting types for parameter %qT (%qT and %qT)",
+               parm, first, second);
+      else
+       inform (input_location,
+               "  deduced conflicting values for non-type parameter "
+               "%qE (%qE and %qE)", parm, first, second);
+    }
+  return 1;
+}
+
+static int
+unify_vla_arg (bool explain_p, tree arg)
+{
+  if (explain_p)
+    inform (input_location,
+           "  variable-sized array type %qT is not "
+           "a valid template argument",
+           arg);
+  return 1;
+}
+
+static int
+unify_method_type_error (bool explain_p, tree arg)
+{
+  if (explain_p)
+    inform (input_location,
+           "  member function type %qT is not a valid template argument",
+           arg);
+  return 1;
+}
+
+static int
+unify_arity (bool explain_p, int have, int wanted)
+{
+  if (explain_p)
+    inform_n (input_location, wanted,
+             "  candidate expects %d argument, %d provided",
+             "  candidate expects %d arguments, %d provided",
+             wanted, have);
+  return 1;
+}
+
+static int
+unify_too_many_arguments (bool explain_p, int have, int wanted)
+{
+  return unify_arity (explain_p, have, wanted);
+}
+
+static int
+unify_too_few_arguments (bool explain_p, int have, int wanted)
+{
+  return unify_arity (explain_p, have, wanted);
+}
+
+static int
+unify_arg_conversion (bool explain_p, tree to_type,
+                     tree from_type, tree arg)
+{
+  if (explain_p)
+    inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
+           arg, from_type, to_type);
+  return 1;
+}
+
+static int
+unify_no_common_base (bool explain_p, enum template_base_result r,
+                     tree parm, tree arg)
+{
+  if (explain_p)
+    switch (r)
+      {
+      case tbr_ambiguous_baseclass:
+       inform (input_location, "  %qT is an ambiguous base class of %qT",
+               arg, parm);
+       break;
+      default:
+       inform (input_location, "  %qT is not derived from %qT", arg, parm);
+       break;
+      }
+  return 1;
+}
+
+static int
+unify_inconsistent_template_template_parameters (bool explain_p)
+{
+  if (explain_p)
+    inform (input_location,
+           "  template parameters of a template template argument are "
+           "inconsistent with other deduced template arguments");
+  return 1;
+}
+
+static int
+unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
+{
+  if (explain_p)
+    inform (input_location,
+           "  can't deduce a template for %qT from non-template type %qT",
+           parm, arg);
+  return 1;
+}
+
+static int
+unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
+{
+  if (explain_p)
+    inform (input_location,
+           "  template argument %qE does not match %qD", arg, parm);
+  return 1;
+}
+
+static int
+unify_overload_resolution_failure (bool explain_p, tree arg)
+{
+  if (explain_p)
+    inform (input_location,
+           "  could not resolve address from overloaded function %qE",
+           arg);
+  return 1;
+}
+
+/* Attempt to convert the non-type template parameter EXPR to the
+   indicated TYPE.  If the conversion is successful, return the
+   converted value.  If the conversion is unsuccessful, return
+   NULL_TREE if we issued an error message, or error_mark_node if we
+   did not.  We issue error messages for out-and-out bad template
+   parameters, but not simply because the conversion failed, since we
+   might be just trying to do argument deduction.  Both TYPE and EXPR
+   must be non-dependent.
+
+   The conversion follows the special rules described in
+   [temp.arg.nontype], and it is much more strict than an implicit
+   conversion.
+
+   This function is called twice for each template argument (see
+   lookup_template_class for a more accurate description of this
+   problem). This means that we need to handle expressions which
+   are not valid in a C++ source, but can be created from the
+   first call (for instance, casts to perform conversions). These
+   hacks can go away after we fix the double coercion problem.  */
+
+static tree
+convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
+{
+  tree expr_type;
+
+  /* Detect immediately string literals as invalid non-type argument.
+     This special-case is not needed for correctness (we would easily
+     catch this later), but only to provide better diagnostic for this
+     common user mistake. As suggested by DR 100, we do not mention
+     linkage issues in the diagnostic as this is not the point.  */
+  /* FIXME we're making this OK.  */
+  if (TREE_CODE (expr) == STRING_CST)
+    {
+      if (complain & tf_error)
+       error ("%qE is not a valid template argument for type %qT "
+              "because string literals can never be used in this context",
+              expr, type);
+      return NULL_TREE;
+    }
+
+  /* Add the ADDR_EXPR now for the benefit of
+     value_dependent_expression_p.  */
+  if (TYPE_PTROBV_P (type)
+      && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
+    expr = decay_conversion (expr);
+
+  /* If we are in a template, EXPR may be non-dependent, but still
+     have a syntactic, rather than semantic, form.  For example, EXPR
+     might be a SCOPE_REF, rather than the VAR_DECL to which the
      SCOPE_REF refers.  Preserving the qualifying scope is necessary
      so that access checking can be performed when the template is
      instantiated -- but here we need the resolved form so that we can
@@ -5018,6 +5708,35 @@ convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
   else
     expr = mark_rvalue_use (expr);
 
+  /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
+     to a non-type argument of "nullptr".  */
+  if (expr == nullptr_node
+      && (TYPE_PTR_P (type) || TYPE_PTR_TO_MEMBER_P (type)))
+    expr = convert (type, expr);
+
+  /* In C++11, integral or enumeration non-type template arguments can be
+     arbitrary constant expressions.  Pointer and pointer to
+     member arguments can be general constant expressions that evaluate
+     to a null value, but otherwise still need to be of a specific form.  */
+  if (cxx_dialect >= cxx0x)
+    {
+      if (TREE_CODE (expr) == PTRMEM_CST)
+       /* A PTRMEM_CST is already constant, and a valid template
+          argument for a parameter of pointer to member type, we just want
+          to leave it in that form rather than lower it to a
+          CONSTRUCTOR.  */;
+      else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
+       expr = maybe_constant_value (expr);
+      else if (TYPE_PTR_P (type)
+              || TYPE_PTR_TO_MEMBER_P (type))
+       {
+         tree folded = maybe_constant_value (expr);
+         if (TYPE_PTR_P (type) ? integer_zerop (folded)
+             : null_member_pointer_value_p (folded))
+           expr = folded;
+       }
+    }
+
   /* HACK: Due to double coercion, we can get a
      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
      which is the tree that we built on the first call (see
@@ -5025,41 +5744,45 @@ convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
      function). We just strip everything and get to the arg.
      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
      for examples.  */
-  if (TREE_CODE (expr) == NOP_EXPR)
+  if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
     {
-      if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
+      tree probe_type, probe = expr;
+      if (REFERENCE_REF_P (probe))
+       probe = TREE_OPERAND (probe, 0);
+      probe_type = TREE_TYPE (probe);
+      if (TREE_CODE (probe) == NOP_EXPR)
        {
          /* ??? Maybe we could use convert_from_reference here, but we
             would need to relax its constraints because the NOP_EXPR
             could actually change the type to something more cv-qualified,
             and this is not folded by convert_from_reference.  */
-         tree addr = TREE_OPERAND (expr, 0);
-         gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
+         tree addr = TREE_OPERAND (probe, 0);
+         gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
          gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
          gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
          gcc_assert (same_type_ignoring_top_level_qualifiers_p
-                     (TREE_TYPE (expr_type),
+                     (TREE_TYPE (probe_type),
                       TREE_TYPE (TREE_TYPE (addr))));
 
          expr = TREE_OPERAND (addr, 0);
          expr_type = TREE_TYPE (expr);
        }
+    }
 
-      /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
-        parameter is a pointer to object, through decay and
-        qualification conversion. Let's strip everything.  */
-      else if (TYPE_PTROBV_P (type))
-       {
-         STRIP_NOPS (expr);
-         gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
-         gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
-         /* Skip the ADDR_EXPR only if it is part of the decay for
-            an array. Otherwise, it is part of the original argument
-            in the source code.  */
-         if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
-           expr = TREE_OPERAND (expr, 0);
-         expr_type = TREE_TYPE (expr);
-       }
+  /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
+     parameter is a pointer to object, through decay and
+     qualification conversion. Let's strip everything.  */
+  else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
+    {
+      STRIP_NOPS (expr);
+      gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
+      gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
+      /* Skip the ADDR_EXPR only if it is part of the decay for
+        an array. Otherwise, it is part of the original argument
+        in the source code.  */
+      if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
+       expr = TREE_OPERAND (expr, 0);
+      expr_type = TREE_TYPE (expr);
     }
 
   /* [temp.arg.nontype]/5, bullet 1
@@ -5069,29 +5792,34 @@ convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
      (_conv.integral_) are applied.  */
   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
     {
-      if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
+      tree t = build_integral_nontype_arg_conv (type, expr, complain);
+      t = maybe_constant_value (t);
+      if (t != error_mark_node)
+       expr = t;
+
+      if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
        return error_mark_node;
 
-      expr = fold_decl_constant_value (expr);
       /* Notice that there are constant expressions like '4 % 0' which
         do not fold into integer constants.  */
       if (TREE_CODE (expr) != INTEGER_CST)
        {
          if (complain & tf_error)
-           error ("%qE is not a valid template argument for type %qT "
-                  "because it is a non-constant expression", expr, type);
-         return NULL_TREE;
+           {
+             int errs = errorcount, warns = warningcount;
+             expr = cxx_constant_value (expr);
+             if (errorcount > errs || warningcount > warns)
+               inform (EXPR_LOC_OR_HERE (expr),
+                       "in template argument for type %qT ", type);
+             if (expr == error_mark_node)
+               return NULL_TREE;
+             /* else cxx_constant_value complained but gave us
+                a real constant, so go ahead.  */
+             gcc_assert (TREE_CODE (expr) == INTEGER_CST);
+           }
+         else
+           return NULL_TREE;
        }
-
-      /* At this point, an implicit conversion does what we want,
-        because we already know that the expression is of integral
-        type.  */
-      expr = perform_implicit_conversion (type, expr, complain);
-      if (expr == error_mark_node)
-       return error_mark_node;
-
-      /* Conversion was allowed: fold it to a bare integer constant.  */
-      expr = fold (expr);
     }
   /* [temp.arg.nontype]/5, bullet 2
 
@@ -5117,6 +5845,8 @@ convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
        /* Non-type template parameters are OK.  */
        ;
+      else if (cxx_dialect >= cxx0x && integer_zerop (expr))
+       /* Null pointer values are OK in C++11.  */;
       else if (TREE_CODE (expr) != ADDR_EXPR
               && TREE_CODE (expr_type) != ARRAY_TYPE)
        {
@@ -5145,13 +5875,20 @@ convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
                     expr, type, decl);
              return NULL_TREE;
            }
-         else if (!DECL_EXTERNAL_LINKAGE_P (decl))
+         else if (cxx_dialect < cxx0x && !DECL_EXTERNAL_LINKAGE_P (decl))
            {
              error ("%qE is not a valid template argument of type %qT "
                     "because %qD does not have external linkage",
                     expr, type, decl);
              return NULL_TREE;
            }
+         else if (cxx_dialect >= cxx0x && decl_linkage (decl) == lk_none)
+           {
+             error ("%qE is not a valid template argument of type %qT "
+                    "because %qD has no linkage",
+                    expr, type, decl);
+             return NULL_TREE;
+           }
        }
 
       expr = decay_conversion (expr);
@@ -5244,6 +5981,10 @@ convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
            return error_mark_node;
        }
 
+      if (cxx_dialect >= cxx0x && integer_zerop (expr))
+       /* Null pointer values are OK in C++11.  */
+       return perform_qualification_conversions (type, expr);
+
       expr = convert_nontype_argument_function (type, expr);
       if (!expr || expr == error_mark_node)
        return expr;
@@ -5291,7 +6032,7 @@ convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
 
       /* [temp.arg.nontype] bullet 1 says the pointer to member
          expression must be a pointer-to-member constant.  */
-      if (!check_valid_ptrmem_cst_expr (type, expr))
+      if (!check_valid_ptrmem_cst_expr (type, expr, complain))
        return error_mark_node;
 
       /* There is no way to disable standard conversions in
@@ -5323,13 +6064,23 @@ convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
     {
       /* [temp.arg.nontype] bullet 1 says the pointer to member
          expression must be a pointer-to-member constant.  */
-      if (!check_valid_ptrmem_cst_expr (type, expr))
+      if (!check_valid_ptrmem_cst_expr (type, expr, complain))
        return error_mark_node;
 
       expr = perform_qualification_conversions (type, expr);
       if (expr == error_mark_node)
        return expr;
     }
+  else if (NULLPTR_TYPE_P (type))
+    {
+      if (expr != nullptr_node)
+       {
+         error ("%qE is not a valid template argument for type %qT "
+                "because it is of type %qT", expr, type, TREE_TYPE (expr));
+         return NULL_TREE;
+       }
+      return expr;
+    }
   /* A template non-type parameter must be one of the above.  */
   else
     gcc_unreachable ();
@@ -5596,6 +6347,28 @@ template_template_parm_bindings_ok_p (tree tparms, tree targs)
   return ret;
 }
 
+/* Since type attributes aren't mangled, we need to strip them from
+   template type arguments.  */
+
+static tree
+canonicalize_type_argument (tree arg, tsubst_flags_t complain)
+{
+  tree mv;
+  if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
+    return arg;
+  mv = TYPE_MAIN_VARIANT (arg);
+  arg = strip_typedefs (arg);
+  if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
+      || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
+    {
+      if (complain & tf_warning)
+       warning (0, "ignoring attributes on template argument %qT", arg);
+      arg = build_aligned_type (arg, TYPE_ALIGN (mv));
+      arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
+    }
+  return arg;
+}
+
 /* Convert the indicated template ARG as necessary to match the
    indicated template PARM.  Returns the converted ARG, or
    error_mark_node if the conversion was unsuccessful.  Error and
@@ -5644,7 +6417,9 @@ convert_template_argument (tree parm,
       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
       if (TREE_CODE (t) == TEMPLATE_DECL)
        {
-         if (complain & tf_warning_or_error)
+         if (cxx_dialect >= cxx0x)
+           /* OK under DR 1004.  */;
+         else if (complain & tf_warning_or_error)
            pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
                     " used as template template argument", TYPE_NAME (arg));
          else if (flag_pedantic_errors)
@@ -5670,8 +6445,16 @@ convert_template_argument (tree parm,
   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
     {
-      permerror (input_location, "to refer to a type member of a template parameter, "
-                "use %<typename %E%>", orig_arg);
+      if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
+       {
+         if (complain & tf_error)
+           error ("invalid use of destructor %qE as a type", orig_arg);
+         return error_mark_node;
+       }
+
+      permerror (input_location,
+                "to refer to a type member of a template parameter, "
+                "use %<typename %E%>", orig_arg);
 
       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
                                     TREE_OPERAND (arg, 1),
@@ -5770,7 +6553,7 @@ convert_template_argument (tree parm,
         the typedef, which is confusing if those future uses do not
         themselves also use the typedef.  */
       if (TYPE_P (val))
-       val = strip_typedefs (val);
+       val = canonicalize_type_argument (val, complain);
     }
   else
     {
@@ -5814,8 +6597,9 @@ convert_template_argument (tree parm,
       if (TREE_CODE (val) == SCOPE_REF)
        {
          /* Strip typedefs from the SCOPE_REF.  */
-         tree type = strip_typedefs (TREE_TYPE (val));
-         tree scope = strip_typedefs (TREE_OPERAND (val, 0));
+         tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
+         tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
+                                                  complain);
          val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
                                      QUALIFIED_NAME_IS_TEMPLATE (val));
        }
@@ -5977,6 +6761,7 @@ coerce_template_parms (tree parms,
      subtract it from nparms to get the number of non-variadic
      parameters.  */
   int variadic_p = 0;
+  int post_variadic_parms = 0;
 
   if (args == error_mark_node)
     return error_mark_node;
@@ -5987,19 +6772,22 @@ coerce_template_parms (tree parms,
   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
     {
       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
+      if (variadic_p)
+       ++post_variadic_parms;
       if (template_parameter_pack_p (tparm))
        ++variadic_p;
     }
 
   inner_args = INNERMOST_TEMPLATE_ARGS (args);
-  /* If there are 0 or 1 parameter packs, we need to expand any argument
-     packs so that we can deduce a parameter pack from some non-packed args
-     followed by an argument pack, as in variadic85.C.  If there are more
-     than that, we need to leave argument packs intact so the arguments are
-     assigned to the right parameter packs.  This should only happen when
-     dealing with a nested class inside a partial specialization of a class
-     template, as in variadic92.C.  */
-  if (variadic_p <= 1)
+  /* If there are no parameters that follow a parameter pack, we need to
+     expand any argument packs so that we can deduce a parameter pack from
+     some non-packed args followed by an argument pack, as in variadic85.C.
+     If there are such parameters, we need to leave argument packs intact
+     so the arguments are assigned properly.  This can happen when dealing
+     with a nested class inside a partial specialization of a class
+     template, as in variadic92.C, or when deducing a template parameter pack
+     from a sub-declarator, as in variadic114.C.  */
+  if (!post_variadic_parms)
     inner_args = expand_template_argument_pack (inner_args);
 
   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
@@ -6014,7 +6802,7 @@ coerce_template_parms (tree parms,
        {
           if (variadic_p)
             {
-              --nparms;
+              nparms -= variadic_p;
              error ("wrong number of template arguments "
                     "(%d, should be %d or more)", nargs, nparms);
             }
@@ -6081,22 +6869,10 @@ coerce_template_parms (tree parms,
        {
           if (PACK_EXPANSION_P (arg))
             {
-             if (complain & tf_error)
-               {
-                 /* FIXME this restriction was removed by N2555; see
-                    bug 35722.  */
-                 /* If ARG is a pack expansion, but PARM is not a
-                    template parameter pack (if it were, we would have
-                    handled it above), we're trying to expand into a
-                    fixed-length argument list.  */
-                 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
-                   sorry ("cannot expand %<%E%> into a fixed-length "
-                          "argument list", arg);
-                 else
-                   sorry ("cannot expand %<%T%> into a fixed-length "
-                          "argument list", arg);
-               }
-             return error_mark_node;
+              /* We don't know how many args we have yet, just
+                 use the unconverted ones for now.  */
+              new_inner_args = args;
+              break;
             }
         }
       else if (require_all_args)
@@ -6124,7 +6900,7 @@ coerce_template_parms (tree parms,
            reported) that we are trying to recover from, e.g., a class
            template with a parameter list such as
            template<typename..., typename>.  */
-        return error_mark_node;
+       ++lost;
       else
        arg = convert_template_argument (TREE_VALUE (parm),
                                         arg, new_args, complain, 
@@ -6156,14 +6932,18 @@ template_args_equal (tree ot, tree nt)
 {
   if (nt == ot)
     return 1;
+  if (nt == NULL_TREE || ot == NULL_TREE)
+    return false;
 
   if (TREE_CODE (nt) == TREE_VEC)
     /* For member templates */
     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
   else if (PACK_EXPANSION_P (ot))
-    return PACK_EXPANSION_P (nt) 
-      && template_args_equal (PACK_EXPANSION_PATTERN (ot),
-                              PACK_EXPANSION_PATTERN (nt));
+    return (PACK_EXPANSION_P (nt)
+           && template_args_equal (PACK_EXPANSION_PATTERN (ot),
+                                   PACK_EXPANSION_PATTERN (nt))
+           && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
+                                   PACK_EXPANSION_EXTRA_ARGS (nt)));
   else if (ARGUMENT_PACK_P (ot))
     {
       int i, len;
@@ -6203,14 +6983,22 @@ template_args_equal (tree ot, tree nt)
     return cp_tree_equal (ot, nt);
 }
 
-/* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
-   of template arguments.  Returns 0 otherwise.  */
+/* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
+   template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
+   NEWARG_PTR with the offending arguments if they are non-NULL.  */
 
-int
-comp_template_args (tree oldargs, tree newargs)
+static int
+comp_template_args_with_info (tree oldargs, tree newargs,
+                             tree *oldarg_ptr, tree *newarg_ptr)
 {
   int i;
 
+  if (oldargs == newargs)
+    return 1;
+
+  if (!oldargs || !newargs)
+    return 0;
+
   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
     return 0;
 
@@ -6220,11 +7008,26 @@ comp_template_args (tree oldargs, tree newargs)
       tree ot = TREE_VEC_ELT (oldargs, i);
 
       if (! template_args_equal (ot, nt))
-       return 0;
+       {
+         if (oldarg_ptr != NULL)
+           *oldarg_ptr = ot;
+         if (newarg_ptr != NULL)
+           *newarg_ptr = nt;
+         return 0;
+       }
     }
   return 1;
 }
 
+/* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
+   of template arguments.  Returns 0 otherwise.  */
+
+int
+comp_template_args (tree oldargs, tree newargs)
+{
+  return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
+}
+
 static void
 add_pending_template (tree d)
 {
@@ -6275,8 +7078,12 @@ lookup_template_function (tree fns, tree arglist)
     return error_mark_node;
 
   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
-  gcc_assert (fns && (is_overloaded_fn (fns)
-                     || TREE_CODE (fns) == IDENTIFIER_NODE));
+
+  if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
+    {
+      error ("%q#D is not a function template", fns);
+      return error_mark_node;
+    }
 
   if (BASELINK_P (fns))
     {
@@ -6364,23 +7171,17 @@ maybe_get_template_decl_from_type_decl (tree decl)
    that we want to avoid. It also causes some problems with argument
    coercion (see convert_nontype_argument for more information on this).  */
 
-tree
-lookup_template_class (tree d1,
-                      tree arglist,
-                      tree in_decl,
-                      tree context,
-                      int entering_scope,
-                      tsubst_flags_t complain)
+static tree
+lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
+                        int entering_scope, tsubst_flags_t complain)
 {
   tree templ = NULL_TREE, parmlist;
   tree t;
-  spec_entry **slot;
+  void **slot;
   spec_entry *entry;
   spec_entry elt;
   hashval_t hash;
 
-  timevar_push (TV_NAME_LOOKUP);
-
   if (TREE_CODE (d1) == IDENTIFIER_NODE)
     {
       tree value = innermost_non_namespace_value (d1);
@@ -6433,7 +7234,7 @@ lookup_template_class (tree d1,
     {
       if (complain & tf_error)
        error ("%qT is not a template", d1);
-      POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
+      return error_mark_node;
     }
 
   if (TREE_CODE (templ) != TEMPLATE_DECL
@@ -6448,7 +7249,7 @@ lookup_template_class (tree d1,
          if (in_decl)
            error ("for template declaration %q+D", in_decl);
        }
-      POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
+      return error_mark_node;
     }
 
   complain &= ~tf_user;
@@ -6498,10 +7299,10 @@ lookup_template_class (tree d1,
       if (arglist2 == error_mark_node
          || (!uses_template_parms (arglist2)
              && check_instantiated_args (templ, arglist2, complain)))
-       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
+       return error_mark_node;
 
       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
-      POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
+      return parm;
     }
   else
     {
@@ -6514,6 +7315,12 @@ lookup_template_class (tree d1,
       int is_dependent_type;
       int use_partial_inst_tmpl = false;
 
+      if (template_type == error_mark_node)
+       /* An error occured while building the template TEMPL, and a
+          diagnostic has most certainly been emitted for that
+          already.  Let's propagate that error.  */
+       return error_mark_node;
+
       gen_tmpl = most_general_template (templ);
       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
       parm_depth = TMPL_PARMS_DEPTH (parmlist);
@@ -6577,7 +7384,7 @@ lookup_template_class (tree d1,
                {
                  /* Restore the ARGLIST to its full size.  */
                  TREE_VEC_LENGTH (arglist) = saved_depth;
-                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
+                 return error_mark_node;
                }
 
              SET_TMPL_ARGS_LEVEL (bound_args, i, a);
@@ -6595,21 +7402,17 @@ lookup_template_class (tree d1,
          arglist = bound_args;
        }
       else
-       {
-         push_tinst_level (templ);
-         arglist
-           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
-                                    INNERMOST_TEMPLATE_ARGS (arglist),
-                                    gen_tmpl,
-                                    complain,
-                                    /*require_all_args=*/true,
-                                    /*use_default_args=*/true);
-         pop_tinst_level ();
-       }
+       arglist
+         = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
+                                  INNERMOST_TEMPLATE_ARGS (arglist),
+                                  gen_tmpl,
+                                  complain,
+                                  /*require_all_args=*/true,
+                                  /*use_default_args=*/true);
 
       if (arglist == error_mark_node)
        /* We were unable to bind the arguments.  */
-       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
+       return error_mark_node;
 
       /* In the scope of a template class, explicit references to the
         template class refer to the type of the template, not any
@@ -6625,7 +7428,7 @@ lookup_template_class (tree d1,
          /* comp_template_args is expensive, check it last.  */
          && comp_template_args (TYPE_TI_ARGS (template_type),
                                 arglist))
-       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
+       return template_type;
 
       /* If we already have this specialization, return it.  */
       elt.tmpl = gen_tmpl;
@@ -6635,7 +7438,7 @@ lookup_template_class (tree d1,
                                                  &elt, hash);
 
       if (entry)
-       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
+       return entry->spec;
 
       is_dependent_type = uses_template_parms (arglist);
 
@@ -6645,7 +7448,7 @@ lookup_template_class (tree d1,
          && check_instantiated_args (gen_tmpl,
                                      INNERMOST_TEMPLATE_ARGS (arglist),
                                      complain))
-       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
+       return error_mark_node;
 
       if (!is_dependent_type
          && !PRIMARY_TEMPLATE_P (gen_tmpl)
@@ -6655,7 +7458,7 @@ lookup_template_class (tree d1,
          found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
                                      DECL_NAME (gen_tmpl),
                                      /*tag_scope=*/ts_global);
-         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
+         return found;
        }
 
       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
@@ -6684,8 +7487,34 @@ lookup_template_class (tree d1,
               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
             }
           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
+         ENUM_FIXED_UNDERLYING_TYPE_P (t)
+           = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
        }
-      else
+      else if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
+       {
+         /* The user referred to a specialization of an alias
+           template represented by GEN_TMPL.
+
+           [temp.alias]/2 says:
+
+               When a template-id refers to the specialization of an
+               alias template, it is equivalent to the associated
+               type obtained by substitution of its
+               template-arguments for the template-parameters in the
+               type-id of the alias template.  */
+
+         t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
+         /* Note that the call above (by indirectly calling
+            register_specialization in tsubst_decl) registers the
+            TYPE_DECL representing the specialization of the alias
+            template.  So next time someone substitutes ARGLIST for
+            the template parms into the alias template (GEN_TMPL),
+            she'll get that TYPE_DECL back.  */
+
+         if (t == error_mark_node)
+           return t;
+       }
+      else if (CLASS_TYPE_P (template_type))
        {
          t = make_class_type (TREE_CODE (template_type));
          CLASSTYPE_DECLARED_CLASS (t)
@@ -6708,6 +7537,8 @@ lookup_template_class (tree d1,
               structural equality testing. */
            SET_TYPE_STRUCTURAL_EQUALITY (t);
        }
+      else
+       gcc_unreachable ();
 
       /* If we called start_enum or pushtag above, this information
         will already be set up.  */
@@ -6723,14 +7554,17 @@ lookup_template_class (tree d1,
       else
        type_decl = TYPE_NAME (t);
 
-      TREE_PRIVATE (type_decl)
-       = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
-      TREE_PROTECTED (type_decl)
-       = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
-      if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
+      if (CLASS_TYPE_P (template_type))
        {
-         DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
-         DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
+         TREE_PRIVATE (type_decl)
+           = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
+         TREE_PROTECTED (type_decl)
+           = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
+         if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
+           {
+             DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
+             DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
+           }
        }
 
       /* Let's consider the explicit specialization of a member
@@ -6786,7 +7620,7 @@ lookup_template_class (tree d1,
          ++processing_template_decl;
          partial_inst_args =
            tsubst (INNERMOST_TEMPLATE_ARGS
-                       (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
+                       (TYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
                    arglist, complain, NULL_TREE);
          --processing_template_decl;
          TREE_VEC_LENGTH (arglist)++;
@@ -6810,16 +7644,25 @@ lookup_template_class (tree d1,
          TREE_VEC_LENGTH (arglist)--;
          found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
          TREE_VEC_LENGTH (arglist)++;
-         found = CLASSTYPE_TI_TEMPLATE (found);
+         /* FOUND is either a proper class type, or an alias
+            template specialization.  In the later case, it's a
+            TYPE_DECL, resulting from the substituting of arguments
+            for parameters in the TYPE_DECL of the alias template
+            done earlier.  So be careful while getting the template
+            of FOUND.  */
+         found = TREE_CODE (found) == TYPE_DECL
+           ? TYPE_TI_TEMPLATE (TREE_TYPE (found))
+           : CLASSTYPE_TI_TEMPLATE (found);
        }
 
       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
 
       elt.spec = t;
-      slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
-                                                      &elt, hash, INSERT);
-      *slot = ggc_alloc_spec_entry ();
-      **slot = elt;
+      slot = htab_find_slot_with_hash (type_specializations,
+                                      &elt, hash, INSERT);
+      entry = ggc_alloc_spec_entry ();
+      *entry = elt;
+      *slot = entry;
 
       /* Note this use of the partial instantiation so we can check it
         later in maybe_process_partial_specialization.  */
@@ -6837,7 +7680,7 @@ lookup_template_class (tree d1,
           the instantiation and exit above.  */
        tsubst_enum (template_type, t, arglist);
 
-      if (is_dependent_type)
+      if (CLASS_TYPE_P (template_type) && is_dependent_type)
        /* If the type makes use of template parameters, the
           code that generates debugging information will crash.  */
        DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
@@ -6846,9 +7689,22 @@ lookup_template_class (tree d1,
       TREE_PUBLIC (type_decl) = 1;
       determine_visibility (type_decl);
 
-      POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
+      return t;
     }
-  timevar_pop (TV_NAME_LOOKUP);
+}
+
+/* Wrapper for lookup_template_class_1.  */
+
+tree
+lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
+                       int entering_scope, tsubst_flags_t complain)
+{
+  tree ret;
+  timevar_push (TV_TEMPLATE_INST);
+  ret = lookup_template_class_1 (d1, arglist, in_decl, context,
+                                 entering_scope, complain);
+  timevar_pop (TV_TEMPLATE_INST);
+  return ret;
 }
 \f
 struct pair_fn_data
@@ -6939,6 +7795,7 @@ for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
       break;
 
     case TYPEOF_TYPE:
+    case UNDERLYING_TYPE:
       if (pfd->include_nondeduced_p
          && for_each_template_parm (TYPE_FIELDS (t), fn, data,
                                     pfd->visited, 
@@ -7021,6 +7878,7 @@ for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
 
     case MODOP_EXPR:
     case CAST_EXPR:
+    case IMPLICIT_CONV_EXPR:
     case REINTERPRET_CAST_EXPR:
     case CONST_CAST_EXPR:
     case STATIC_CAST_EXPR:
@@ -7115,7 +7973,7 @@ uses_template_parms (tree t)
           || EXPR_P (t)
           || TREE_CODE (t) == TEMPLATE_PARM_INDEX
           || TREE_CODE (t) == OVERLOAD
-          || TREE_CODE (t) == BASELINK
+          || BASELINK_P (t)
           || TREE_CODE (t) == IDENTIFIER_NODE
           || TREE_CODE (t) == TRAIT_EXPR
           || TREE_CODE (t) == CONSTRUCTOR
@@ -7142,13 +8000,42 @@ uses_template_parms_level (tree t, int level)
                                 /*include_nondeduced_p=*/true);
 }
 
+/* Returns TRUE iff INST is an instantiation we don't need to do in an
+   ill-formed translation unit, i.e. a variable or function that isn't
+   usable in a constant expression.  */
+
+static inline bool
+neglectable_inst_p (tree d)
+{
+  return (DECL_P (d)
+         && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
+              : decl_maybe_constant_var_p (d)));
+}
+
+/* Returns TRUE iff we should refuse to instantiate DECL because it's
+   neglectable and instantiated from within an erroneous instantiation.  */
+
+static bool
+limit_bad_template_recursion (tree decl)
+{
+  struct tinst_level *lev = current_tinst_level;
+  int errs = errorcount + sorrycount;
+  if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
+    return false;
+
+  for (; lev; lev = lev->next)
+    if (neglectable_inst_p (lev->decl))
+      break;
+
+  return (lev && errs > lev->errors);
+}
+
 static int tinst_depth;
 extern int max_tinst_depth;
 #ifdef GATHER_STATISTICS
 int depth_reached;
 #endif
-static int tinst_level_tick;
-static int last_template_error_tick;
+static GTY(()) struct tinst_level *last_error_tinst_level;
 
 /* We're starting to instantiate D; record the template instantiation context
    for diagnostics and to restore it later.  */
@@ -7160,25 +8047,31 @@ push_tinst_level (tree d)
 
   if (tinst_depth >= max_tinst_depth)
     {
-      /* If the instantiation in question still has unbound template parms,
-        we don't really care if we can't instantiate it, so just return.
-        This happens with base instantiation for implicit `typename'.  */
-      if (uses_template_parms (d))
-       return 0;
-
-      last_template_error_tick = tinst_level_tick;
-      error ("template instantiation depth exceeds maximum of %d (use "
-            "-ftemplate-depth= to increase the maximum) instantiating %qD",
-            max_tinst_depth, d);
+      last_error_tinst_level = current_tinst_level;
+      if (TREE_CODE (d) == TREE_LIST)
+       error ("template instantiation depth exceeds maximum of %d (use "
+              "-ftemplate-depth= to increase the maximum) substituting %qS",
+              max_tinst_depth, d);
+      else
+       error ("template instantiation depth exceeds maximum of %d (use "
+              "-ftemplate-depth= to increase the maximum) instantiating %qD",
+              max_tinst_depth, d);
 
       print_instantiation_context ();
 
       return 0;
     }
 
+  /* If the current instantiation caused problems, don't let it instantiate
+     anything else.  Do allow deduction substitution and decls usable in
+     constant expressions.  */
+  if (limit_bad_template_recursion (d))
+    return 0;
+
   new_level = ggc_alloc_tinst_level ();
   new_level->decl = d;
   new_level->locus = input_location;
+  new_level->errors = errorcount+sorrycount;
   new_level->in_system_header_p = in_system_header;
   new_level->next = current_tinst_level;
   current_tinst_level = new_level;
@@ -7189,7 +8082,6 @@ push_tinst_level (tree d)
     depth_reached = tinst_depth;
 #endif
 
-  ++tinst_level_tick;
   return 1;
 }
 
@@ -7204,7 +8096,6 @@ pop_tinst_level (void)
   input_location = current_tinst_level->locus;
   current_tinst_level = current_tinst_level->next;
   --tinst_depth;
-  ++tinst_level_tick;
 }
 
 /* We're instantiating a deferred template; restore the template
@@ -7222,6 +8113,8 @@ reopen_tinst_level (struct tinst_level *level)
 
   current_tinst_level = level;
   pop_tinst_level ();
+  if (current_tinst_level)
+    current_tinst_level->errors = errorcount+sorrycount;
   return level->decl;
 }
 
@@ -7256,8 +8149,13 @@ parameter_of_template_p (tree parm, tree templ)
   parms = INNERMOST_TEMPLATE_PARMS (parms);
 
   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
-    if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
-      return true;
+    {
+      tree p = TREE_VALUE (TREE_VEC_ELT (parms, i));
+      if (parm == p
+         || (DECL_INITIAL (parm)
+             && DECL_INITIAL (parm) == DECL_INITIAL (p)))
+       return true;
+    }
 
   return false;
 }
@@ -7785,8 +8683,8 @@ perform_typedefs_access_check (tree tmpl, tree targs)
     input_location = saved_location;
 }
 
-tree
-instantiate_class_template (tree type)
+static tree
+instantiate_class_template_1 (tree type)
 {
   tree templ, args, pattern, t, member;
   tree typedecl;
@@ -7864,16 +8762,6 @@ instantiate_class_template (tree type)
   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
     DECL_SOURCE_LOCATION (typedecl);
 
-  TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
-  TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
-  TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
-  TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
-  TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
-  TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
-  TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
-  TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
-  TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
-  TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
   TYPE_PACKED (type) = TYPE_PACKED (pattern);
   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
@@ -7884,7 +8772,10 @@ instantiate_class_template (tree type)
     {
       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
+      /* Adjust visibility for template arguments.  */
+      determine_visibility (TYPE_MAIN_DECL (type));
     }
+  CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
 
   pbinfo = TYPE_BINFO (pattern);
 
@@ -8040,6 +8931,9 @@ instantiate_class_template (tree type)
                --processing_template_decl;
              set_current_access_from_decl (r);
              finish_member_declaration (r);
+             /* Instantiate members marked with attribute used.  */
+             if (r != error_mark_node && DECL_PRESERVE_P (r))
+               mark_used (r);
            }
          else
            {
@@ -8089,8 +8983,9 @@ instantiate_class_template (tree type)
                         /*init_const_expr_p=*/false,
                         /*asmspec_tree=*/NULL_TREE,
                         /*flags=*/0);
-                     if (DECL_INITIALIZED_IN_CLASS_P (r))
-                       check_static_variable_definition (r, TREE_TYPE (r));
+                     /* Instantiate members marked with attribute used.  */
+                     if (r != error_mark_node && DECL_PRESERVE_P (r))
+                       mark_used (r);
                    }
                  else if (TREE_CODE (r) == FIELD_DECL)
                    {
@@ -8147,7 +9042,8 @@ instantiate_class_template (tree type)
                    friend_type = TREE_TYPE (friend_type);
                  adjust_processing_template_decl = true;
                }
-             else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
+             else if (TREE_CODE (friend_type) == TYPENAME_TYPE
+                      || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
                {
                  /* This could be either
 
@@ -8241,6 +9137,24 @@ instantiate_class_template (tree type)
        }
     }
 
+  if (CLASSTYPE_LAMBDA_EXPR (type))
+    {
+      tree decl = lambda_function (type);
+      if (decl)
+       {
+         tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
+         if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
+           {
+             apply_lambda_return_type (lambda, void_type_node);
+             LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
+           }
+         instantiate_decl (decl, false, false);
+         maybe_add_lambda_conv_op (type);
+       }
+      else
+       gcc_assert (errorcount);
+    }
+
   /* Set the file and line number information to whatever is given for
      the class itself.  This puts error messages involving generated
      implicit functions at a predictable point, and the same point
@@ -8280,6 +9194,18 @@ instantiate_class_template (tree type)
   return type;
 }
 
+/* Wrapper for instantiate_class_template_1.  */
+
+tree
+instantiate_class_template (tree type)
+{
+  tree ret;
+  timevar_push (TV_TEMPLATE_INST);
+  ret = instantiate_class_template_1 (type);
+  timevar_pop (TV_TEMPLATE_INST);
+  return ret;
+}
+
 static tree
 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
 {
@@ -8297,15 +9223,20 @@ tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
                       /*integral_constant_expression_p=*/true);
       if (!(complain & tf_warning))
        --c_inhibit_evaluation_warnings;
+      /* Preserve the raw-reference nature of T.  */
+      if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
+         && REFERENCE_REF_P (r))
+       r = TREE_OPERAND (r, 0);
     }
   return r;
 }
 
-/* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
-   NONTYPE_ARGUMENT_PACK.  */
+/* Given a function parameter pack TMPL_PARM and some function parameters
+   instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
+   and set *SPEC_P to point at the next point in the list.  */
 
 static tree
-make_fnparm_pack (tree spec_parm)
+extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
 {
   /* Collect all of the extra "packed" parameters into an
      argument pack.  */
@@ -8313,11 +9244,18 @@ make_fnparm_pack (tree spec_parm)
   tree parmtypevec;
   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
-  int i, len = list_length (spec_parm);
+  tree spec_parm = *spec_p;
+  int i, len;
+
+  for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
+    if (tmpl_parm
+       && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
+      break;
 
   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
   parmvec = make_tree_vec (len);
   parmtypevec = make_tree_vec (len);
+  spec_parm = *spec_p;
   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
     {
       TREE_VEC_ELT (parmvec, i) = spec_parm;
@@ -8328,9 +9266,19 @@ make_fnparm_pack (tree spec_parm)
   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
   TREE_TYPE (argpack) = argtypepack;
+  *spec_p = spec_parm;
 
   return argpack;
-}        
+}
+
+/* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
+   NONTYPE_ARGUMENT_PACK.  */
+
+static tree
+make_fnparm_pack (tree spec_parm)
+{
+  return extract_fnparm_pack (NULL_TREE, &spec_parm);
+}
 
 /* Substitute ARGS into T, which is an pack expansion
    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
@@ -8342,15 +9290,23 @@ tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
                       tree in_decl)
 {
   tree pattern;
-  tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
+  tree pack, packs = NULL_TREE;
+  bool unsubstituted_packs = false;
+  bool real_packs = false;
+  int missing_level = 0;
   int i, len = -1;
   tree result;
-  int incomplete = 0;
   htab_t saved_local_specializations = NULL;
+  int levels;
 
   gcc_assert (PACK_EXPANSION_P (t));
   pattern = PACK_EXPANSION_PATTERN (t);
 
+  /* Add in any args remembered from an earlier partial instantiation.  */
+  args = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
+
+  levels = TMPL_ARGS_DEPTH (args);
+
   /* Determine the argument packs that will instantiate the parameter
      packs used in the expansion expression. While we're at it,
      compute the number of arguments to be expanded and make sure it
@@ -8361,7 +9317,17 @@ tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
       tree parm_pack = TREE_VALUE (pack);
       tree arg_pack = NULL_TREE;
       tree orig_arg = NULL_TREE;
+      int level = 0;
 
+      if (TREE_CODE (parm_pack) == BASES)
+       {
+         if (BASES_DIRECT (parm_pack))
+           return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
+                                                        args, complain, in_decl, false));
+         else
+           return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
+                                                 args, complain, in_decl, false));
+       }
       if (TREE_CODE (parm_pack) == PARM_DECL)
        {
          if (!cp_unevaluated_operand)
@@ -8374,15 +9340,19 @@ tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
                 have the wrong value for a recursive call.  Just make a
                 dummy decl, since it's only used for its type.  */
              arg_pack = tsubst_decl (parm_pack, args, complain);
-             arg_pack = make_fnparm_pack (arg_pack);
+             if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
+               /* Partial instantiation of the parm_pack, we can't build
+                  up an argument pack yet.  */
+               arg_pack = NULL_TREE;
+             else
+               arg_pack = make_fnparm_pack (arg_pack);
            }
        }
       else
         {
-          int level, idx, levels;
+         int idx;
           template_parm_level_and_index (parm_pack, &level, &idx);
 
-          levels = TMPL_ARGS_DEPTH (args);
           if (level <= levels)
             arg_pack = TMPL_ARG (args, level, idx);
         }
@@ -8400,43 +9370,31 @@ tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
          return result;
        }
 
-      if (arg_pack
-          && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
-          && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
-        {
-          tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
-          tree pattern = PACK_EXPANSION_PATTERN (expansion);
-          if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
-              || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
-            /* The argument pack that the parameter maps to is just an
-               expansion of the parameter itself, such as one would
-               find in the implicit typedef of a class inside the
-               class itself.  Consider this parameter "unsubstituted",
-               so that we will maintain the outer pack expansion.  */
-            arg_pack = NULL_TREE;
-        }
+      if (arg_from_parm_pack_p (arg_pack, parm_pack))
+       /* The argument pack that the parameter maps to is just an
+          expansion of the parameter itself, such as one would find
+          in the implicit typedef of a class inside the class itself.
+          Consider this parameter "unsubstituted", so that we will
+          maintain the outer pack expansion.  */
+       arg_pack = NULL_TREE;
           
       if (arg_pack)
         {
           int my_len = 
             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
 
-          /* It's all-or-nothing with incomplete argument packs.  */
-          if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
-            return error_mark_node;
-          
+         /* Don't bother trying to do a partial substitution with
+            incomplete packs; we'll try again after deduction.  */
           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
-            incomplete = 1;
+            return t;
 
           if (len < 0)
            len = my_len;
           else if (len != my_len)
             {
-             if (incomplete)
-               /* We got explicit args for some packs but not others;
-                  do nothing now and try again after deduction.  */
-               return t;
-              if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
+             if (!(complain & tf_error))
+               /* Fail quietly.  */;
+              else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
                 error ("mismatched argument pack lengths while expanding "
                        "%<%T%>",
                        pattern);
@@ -8447,31 +9405,71 @@ tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
               return error_mark_node;
             }
 
+         if (TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
+             && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack),
+                                                0)))
+           /* This isn't a real argument pack yet.  */;
+         else
+           real_packs = true;
+
           /* Keep track of the parameter packs and their corresponding
              argument packs.  */
           packs = tree_cons (parm_pack, arg_pack, packs);
           TREE_TYPE (packs) = orig_arg;
         }
       else
-        /* We can't substitute for this parameter pack.  */
-        unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
-                                         TREE_VALUE (pack),
-                                         unsubstituted_packs);
+       {
+         /* We can't substitute for this parameter pack.  We use a flag as
+            well as the missing_level counter because function parameter
+            packs don't have a level.  */
+         unsubstituted_packs = true;
+         if (!missing_level || missing_level > level)
+           missing_level = level;
+       }
     }
 
   /* We cannot expand this expansion expression, because we don't have
-     all of the argument packs we need. Substitute into the pattern
-     and return a PACK_EXPANSION_*. The caller will need to deal with
-     that.  */
+     all of the argument packs we need.  */
   if (unsubstituted_packs)
     {
-      tree new_pat;
-      if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
-       new_pat = tsubst_expr (pattern, args, complain, in_decl,
-                              /*integral_constant_expression_p=*/false);
+      if (real_packs)
+       {
+         /* We got some full packs, but we can't substitute them in until we
+            have values for all the packs.  So remember these until then.  */
+         tree save_args;
+
+         t = make_pack_expansion (pattern);
+
+         /* The call to add_to_template_args above assumes no overlap
+            between saved args and new args, so prune away any fake
+            args, i.e. those that satisfied arg_from_parm_pack_p above.  */
+         if (missing_level && levels >= missing_level)
+           {
+             gcc_assert (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
+                         && missing_level > 1);
+             TREE_VEC_LENGTH (args) = missing_level - 1;
+             save_args = copy_node (args);
+             TREE_VEC_LENGTH (args) = levels;
+           }
+         else
+           save_args = args;
+
+         PACK_EXPANSION_EXTRA_ARGS (t) = save_args;
+       }
       else
-       new_pat = tsubst (pattern, args, complain, in_decl);
-      return make_pack_expansion (new_pat);
+       {
+         /* There were no real arguments, we're just replacing a parameter
+            pack with another version of itself. Substitute into the
+            pattern and return a PACK_EXPANSION_*. The caller will need to
+            deal with that.  */
+         if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
+           t = tsubst_expr (pattern, args, complain, in_decl,
+                            /*integral_constant_expression_p=*/false);
+         else
+           t = tsubst (pattern, args, complain, in_decl);
+         t = make_pack_expansion (t);
+       }
+      return t;
     }
 
   /* We could not find any argument packs that work.  */
@@ -8493,8 +9491,8 @@ tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
 
   /* For each argument in each argument pack, substitute into the
      pattern.  */
-  result = make_tree_vec (len + incomplete);
-  for (i = 0; i < len + incomplete; ++i)
+  result = make_tree_vec (len);
+  for (i = 0; i < len; ++i)
     {
       /* For parameter pack, change the substitution of the parameter
          pack to the ith argument in its argument pack, then expand
@@ -8502,33 +9500,38 @@ tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
       for (pack = packs; pack; pack = TREE_CHAIN (pack))
         {
           tree parm = TREE_PURPOSE (pack);
+         tree arg;
 
+         /* Select the Ith argument from the pack.  */
           if (TREE_CODE (parm) == PARM_DECL)
             {
-             /* Select the Ith argument from the pack.  */
-             tree arg = make_node (ARGUMENT_PACK_SELECT);
-             ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
-             ARGUMENT_PACK_SELECT_INDEX (arg) = i;
-              mark_used (parm);
-              register_local_specialization (arg, parm);
+             if (i == 0)
+               {
+                 arg = make_node (ARGUMENT_PACK_SELECT);
+                 ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
+                 mark_used (parm);
+                 register_local_specialization (arg, parm);
+               }
+             else
+               arg = retrieve_local_specialization (parm);
             }
           else
             {
-              tree value = parm;
               int idx, level;
               template_parm_level_and_index (parm, &level, &idx);
-              
-             if (i < len) 
+
+             if (i == 0)
                {
-                 /* Select the Ith argument from the pack. */
-                 value = make_node (ARGUMENT_PACK_SELECT);
-                 ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
-                 ARGUMENT_PACK_SELECT_INDEX (value) = i;
+                 arg = make_node (ARGUMENT_PACK_SELECT);
+                 ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
+                 /* Update the corresponding argument.  */
+                 TMPL_ARG (args, level, idx) = arg;
                }
-
-              /* Update the corresponding argument.  */
-              TMPL_ARG (args, level, idx) = value;
+             else
+               /* Re-use the ARGUMENT_PACK_SELECT.  */
+               arg = TMPL_ARG (args, level, idx);
             }
+         ARGUMENT_PACK_SELECT_INDEX (arg) = i;
         }
 
       /* Substitute into the PATTERN with the altered arguments.  */
@@ -8539,13 +9542,6 @@ tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
       else
         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
 
-      if (i == len)
-        /* When we have incomplete argument packs, the last "expanded"
-           result is itself a pack expansion, which allows us
-           to deduce more arguments.  */
-        TREE_VEC_ELT (result, i) = 
-          make_pack_expansion (TREE_VEC_ELT (result, i));
-
       if (TREE_VEC_ELT (result, i) == error_mark_node)
        {
          result = error_mark_node;
@@ -8620,9 +9616,14 @@ static tree
 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
 {
   tree orig_t = t;
-  int len = TREE_VEC_LENGTH (t);
-  int need_new = 0, i, expanded_len_adjust = 0, out;
-  tree *elts = XALLOCAVEC (tree, len);
+  int len, need_new = 0, i, expanded_len_adjust = 0, out;
+  tree *elts;
+
+  if (t == error_mark_node)
+    return error_mark_node;
+
+  len = TREE_VEC_LENGTH (t);
+  elts = XALLOCAVEC (tree, len);
 
   for (i = 0; i < len; i++)
     {
@@ -8752,8 +9753,6 @@ tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
        {
           tree tuple;
-          tree default_value;
-          tree parm_decl;
 
           if (parms == error_mark_node)
             continue;
@@ -8763,18 +9762,8 @@ tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
           if (tuple == error_mark_node)
             continue;
 
-          default_value = TREE_PURPOSE (tuple);
-          parm_decl = TREE_VALUE (tuple);
-
-         parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
-         if (TREE_CODE (parm_decl) == PARM_DECL
-             && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
-           parm_decl = error_mark_node;
-         default_value = tsubst_template_arg (default_value, args,
-                                              complain, NULL_TREE);
-
-         tuple = build_tree_list (default_value, parm_decl);
-         TREE_VEC_ELT (new_vec, i) = tuple;
+         TREE_VEC_ELT (new_vec, i) =
+           tsubst_template_parm (tuple, args, complain);
        }
 
       *new_parms =
@@ -8788,6 +9777,36 @@ tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
   return r;
 }
 
+/* Return the result of substituting ARGS into one template parameter
+   given by T. T Must be a TREE_LIST which TREE_VALUE is the template
+   parameter and which TREE_PURPOSE is the default argument of the
+   template parameter.  */
+
+static tree
+tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
+{
+  tree default_value, parm_decl;
+
+  if (args == NULL_TREE
+      || t == NULL_TREE
+      || t == error_mark_node)
+    return t;
+
+  gcc_assert (TREE_CODE (t) == TREE_LIST);
+
+  default_value = TREE_PURPOSE (t);
+  parm_decl = TREE_VALUE (t);
+
+  parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
+  if (TREE_CODE (parm_decl) == PARM_DECL
+      && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
+    parm_decl = error_mark_node;
+  default_value = tsubst_template_arg (default_value, args,
+                                      complain, NULL_TREE);
+
+  return build_tree_list (default_value, parm_decl);
+}
+
 /* Substitute the ARGS into the indicated aggregate (or enumeration)
    type T.  If T is not an aggregate or enumeration type, it is
    handled as if by tsubst.  IN_DECL is as for tsubst.  If
@@ -8830,14 +9849,13 @@ tsubst_aggr_type (tree t,
          /* First, determine the context for the type we are looking
             up.  */
          context = TYPE_CONTEXT (t);
-         if (context)
+         if (context && TYPE_P (context))
            {
              context = tsubst_aggr_type (context, args, complain,
                                          in_decl, /*entering_scope=*/1);
              /* If context is a nested class inside a class template,
                 it may still need to be instantiated (c++/33959).  */
-             if (TYPE_P (context))
-               context = complete_type (context);
+             context = complete_type (context);
            }
 
          /* Then, figure out what arguments are appropriate for the
@@ -9054,7 +10072,8 @@ tsubst_decl (tree t, tree args, tsubst_flags_t complain)
 
        DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
 
-       if (TREE_CODE (decl) == TYPE_DECL)
+       if (TREE_CODE (decl) == TYPE_DECL
+           && !TYPE_DECL_ALIAS_P (decl))
          {
            tree new_type;
            ++processing_template_decl;
@@ -9144,6 +10163,8 @@ tsubst_decl (tree t, tree args, tsubst_flags_t complain)
                                           (DECL_TEMPLATE_RESULT
                                                  (DECL_TI_TEMPLATE (t))),
                                           args, complain, in_decl);
+           if (argvec == error_mark_node)
+             RETURN (error_mark_node);
 
            /* Check to see if we already have this specialization.  */
            hash = hash_tmpl_and_args (gen_tmpl, argvec);
@@ -9409,14 +10430,14 @@ tsubst_decl (tree t, tree args, tsubst_flags_t complain)
             if (DECL_TEMPLATE_PARM_P (t))
               SET_DECL_TEMPLATE_PARM_P (r);
 
-           /* An argument of a function parameter pack is not a parameter
-              pack.  */
-           FUNCTION_PARAMETER_PACK_P (r) = false;
-
             if (expanded_types)
               /* We're on the Ith parameter of the function parameter
                  pack.  */
               {
+               /* An argument of a function parameter pack is not a parameter
+                  pack.  */
+               FUNCTION_PARAMETER_PACK_P (r) = false;
+
                 /* Get the Ith type.  */
                 type = TREE_VEC_ELT (expanded_types, i);
 
@@ -9482,11 +10503,24 @@ tsubst_decl (tree t, tree args, tsubst_flags_t complain)
        TREE_TYPE (r) = type;
        cp_apply_type_quals_to_decl (cp_type_quals (type), r);
 
-       /* DECL_INITIAL gives the number of bits in a bit-field.  */
-       DECL_INITIAL (r)
-         = tsubst_expr (DECL_INITIAL (t), args,
-                        complain, in_decl,
-                        /*integral_constant_expression_p=*/true);
+       if (DECL_C_BIT_FIELD (r))
+         /* For bit-fields, DECL_INITIAL gives the number of bits.  For
+            non-bit-fields DECL_INITIAL is a non-static data member
+            initializer, which gets deferred instantiation.  */
+         DECL_INITIAL (r)
+           = tsubst_expr (DECL_INITIAL (t), args,
+                          complain, in_decl,
+                          /*integral_constant_expression_p=*/true);
+       else if (DECL_INITIAL (t))
+         {
+           /* Set up DECL_TEMPLATE_INFO so that we can get at the
+              NSDMI in perform_member_init.  Still set DECL_INITIAL
+              so that we know there is one.  */
+           DECL_INITIAL (r) = void_zero_node;
+           gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
+           retrofit_lang_decl (r);
+           DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
+         }
        /* We don't have to set DECL_CONTEXT here; it is set by
           finish_member_declaration.  */
        DECL_CHAIN (r) = NULL_TREE;
@@ -9572,8 +10606,15 @@ tsubst_decl (tree t, tree args, tsubst_flags_t complain)
                   referencing a static data member within in its own
                   class.  We can use pointer equality, rather than
                   same_type_p, because DECL_CONTEXT is always
-                  canonical.  */
-               if (ctx == DECL_CONTEXT (t))
+                  canonical...  */
+               if (ctx == DECL_CONTEXT (t)
+                   && (TREE_CODE (t) != TYPE_DECL
+                       /* ... unless T is a member template; in which
+                          case our caller can be willing to create a
+                          specialization of that template represented
+                          by T.  */
+                       || !(DECL_TI_TEMPLATE (t)
+                            && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t)))))
                  spec = t;
              }
 
@@ -9610,7 +10651,9 @@ tsubst_decl (tree t, tree args, tsubst_flags_t complain)
              type = DECL_ORIGINAL_TYPE (t);
            else
              type = TREE_TYPE (t);
-           if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
+           if (TREE_CODE (t) == VAR_DECL
+               && VAR_HAD_UNKNOWN_BOUND (t)
+               && type != error_mark_node)
              type = strip_array_domain (type);
            type = tsubst (type, args, complain, in_decl);
          }
@@ -9645,8 +10688,9 @@ tsubst_decl (tree t, tree args, tsubst_flags_t complain)
                RETURN (error_mark_node);
              }
            type = complete_type (type);
-           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
-             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
+           /* Wait until cp_finish_decl to set this again, to handle
+              circular dependency (template/instantiate6.C). */
+           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
            type = check_var_type (DECL_NAME (r), type);
 
            if (DECL_HAS_VALUE_EXPR_P (t))
@@ -9654,6 +10698,11 @@ tsubst_decl (tree t, tree args, tsubst_flags_t complain)
                tree ve = DECL_VALUE_EXPR (t);
                ve = tsubst_expr (ve, args, complain, in_decl,
                                  /*constant_expression_p=*/false);
+               if (REFERENCE_REF_P (ve))
+                 {
+                   gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
+                   ve = TREE_OPERAND (ve, 0);
+                 }
                SET_DECL_VALUE_EXPR (r, ve);
              }
          }
@@ -9703,14 +10752,14 @@ tsubst_decl (tree t, tree args, tsubst_flags_t complain)
               scope, such as for a lambda return type.  Don't add it to
               local_specializations, do perform auto deduction.  */
            tree auto_node = type_uses_auto (type);
-           tree init
-             = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
-                            /*constant_expression_p=*/false);
-
-           if (auto_node && init && describable_type (init))
+           if (auto_node)
              {
-               type = do_auto_deduction (type, init, auto_node);
-               TREE_TYPE (r) = type;
+               tree init
+                 = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
+                                /*constant_expression_p=*/false);
+               init = resolve_nondeduced_context (init);
+               TREE_TYPE (r) = type
+                 = do_auto_deduction (type, init, auto_node);
              }
          }
        else
@@ -9810,7 +10859,7 @@ tsubst_arg_types (tree arg_types,
     
     /* Do array-to-pointer, function-to-pointer conversion, and ignore
        top-level qualifiers as required.  */
-    type = TYPE_MAIN_VARIANT (type_decays_to (type));
+    type = cv_unqualified (type_decays_to (type));
 
     /* We do not substitute into default arguments here.  The standard
        mandates that they be instantiated only when needed, which is
@@ -9933,7 +10982,8 @@ static tree
 tsubst_exception_specification (tree fntype,
                                tree args,
                                tsubst_flags_t complain,
-                               tree in_decl)
+                               tree in_decl,
+                               bool defer_ok)
 {
   tree specs;
   tree new_specs;
@@ -9943,9 +10993,33 @@ tsubst_exception_specification (tree fntype,
   if (specs && TREE_PURPOSE (specs))
     {
       /* A noexcept-specifier.  */
-      new_specs = tsubst_copy_and_build
-       (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
-        /*integral_constant_expression_p=*/true);
+      tree expr = TREE_PURPOSE (specs);
+      if (expr == boolean_true_node || expr == boolean_false_node)
+       new_specs = expr;
+      else if (defer_ok)
+       {
+         /* Defer instantiation of noexcept-specifiers to avoid
+            excessive instantiations (c++/49107).  */
+         new_specs = make_node (DEFERRED_NOEXCEPT);
+         if (DEFERRED_NOEXCEPT_SPEC_P (specs))
+           {
+             /* We already partially instantiated this member template,
+                so combine the new args with the old.  */
+             DEFERRED_NOEXCEPT_PATTERN (new_specs)
+               = DEFERRED_NOEXCEPT_PATTERN (expr);
+             DEFERRED_NOEXCEPT_ARGS (new_specs)
+               = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
+           }
+         else
+           {
+             DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
+             DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
+           }
+       }
+      else
+       new_specs = tsubst_copy_and_build
+         (expr, args, complain, in_decl, /*function_p=*/false,
+          /*integral_constant_expression_p=*/true);
       new_specs = build_noexcept_spec (new_specs, complain);
     }
   else if (specs)
@@ -10023,7 +11097,7 @@ tree
 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
 {
   enum tree_code code;
-  tree type, r;
+  tree type, r = NULL_TREE;
 
   if (t == NULL_TREE || t == error_mark_node
       || t == integer_type_node
@@ -10055,10 +11129,21 @@ tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
       && typedef_variant_p (t))
     {
       tree decl = TYPE_NAME (t);
-      
-      if (DECL_CLASS_SCOPE_P (decl)
-         && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
-         && uses_template_parms (DECL_CONTEXT (decl)))
+
+      if (TYPE_DECL_ALIAS_P (decl)
+         && DECL_LANG_SPECIFIC (decl)
+         && DECL_TEMPLATE_INFO (decl)
+         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
+       {
+         /* DECL represents an alias template and we want to
+            instantiate it.  Let's substitute our arguments for the
+            template parameters into the declaration and get the
+            resulting type.  */
+         r = tsubst (decl, args, complain, decl);
+       }
+      else if (DECL_CLASS_SCOPE_P (decl)
+              && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
+              && uses_template_parms (DECL_CONTEXT (decl)))
        {
          tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
          tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
@@ -10133,9 +11218,6 @@ tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
            && !TREE_TYPE (max))
          TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
 
-       max = mark_rvalue_use (max);
-       max = fold_decl_constant_value (max);
-
        /* If we're in a partial instantiation, preserve the magic NOP_EXPR
           with TREE_SIDE_EFFECTS that indicates this is not an integral
           constant expression.  */
@@ -10146,38 +11228,7 @@ tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
            TREE_SIDE_EFFECTS (max) = 1;
          }
 
-       if (TREE_CODE (max) != INTEGER_CST
-           && !at_function_scope_p ()
-           && !TREE_SIDE_EFFECTS (max)
-           && !value_dependent_expression_p (max))
-         {
-           if (complain & tf_error)
-             error ("array bound is not an integer constant");
-           return error_mark_node;
-         }
-
-       /* [temp.deduct]
-
-          Type deduction may fail for any of the following
-          reasons:
-
-            Attempting to create an array with a size that is
-            zero or negative.  */
-       if (integer_zerop (max) && !(complain & tf_error))
-         /* We must fail if performing argument deduction (as
-            indicated by the state of complain), so that
-            another substitution can be found.  */
-         return error_mark_node;
-       else if (TREE_CODE (max) == INTEGER_CST
-                && INT_CST_LT (max, integer_zero_node))
-         {
-           if (complain & tf_error)
-             error ("creating array with negative size (%qE)", max);
-
-           return error_mark_node;
-         }
-
-       return compute_array_index_type (NULL_TREE, max);
+       return compute_array_index_type (NULL_TREE, max, complain);
       }
 
     case TEMPLATE_TYPE_PARM:
@@ -10242,6 +11293,46 @@ tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
                if (argvec == error_mark_node)
                  return error_mark_node;
 
+               gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
+                           || TREE_CODE (arg) == TEMPLATE_DECL
+                           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
+
+               if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
+                 /* Consider this code:
+
+                       template <template <class> class Template>
+                       struct Internal {
+                       template <class Arg> using Bind = Template<Arg>;
+                       };
+
+                       template <template <class> class Template, class Arg>
+                       using Instantiate = Template<Arg>; //#0
+
+                       template <template <class> class Template,
+                                  class Argument>
+                       using Bind =
+                         Instantiate<Internal<Template>::template Bind,
+                                     Argument>; //#1
+
+                    When #1 is parsed, the
+                    BOUND_TEMPLATE_TEMPLATE_PARM representing the
+                    parameter `Template' in #0 matches the
+                    UNBOUND_CLASS_TEMPLATE representing the argument
+                    `Internal<Template>::template Bind'; We then want
+                    to assemble the type `Bind<Argument>' that can't
+                    be fully created right now, because
+                    `Internal<Template>' not being complete, the Bind
+                    template cannot be looked up in that context.  So
+                    we need to "store" `Bind<Argument>' for later
+                    when the context of Bind becomes complete.  Let's
+                    store that in a TYPENAME_TYPE.  */
+                 return make_typename_type (TYPE_CONTEXT (arg),
+                                            build_nt (TEMPLATE_ID_EXPR,
+                                                      TYPE_IDENTIFIER (arg),
+                                                      argvec),
+                                            typename_type,
+                                            complain);
+
                /* We can get a TEMPLATE_TEMPLATE_PARM here when we
                   are resolving nested-types in the signature of a
                   member function templates.  Otherwise ARG is a
@@ -10260,7 +11351,7 @@ tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
              }
            else
              /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
-             return unshare_expr (arg);
+             return convert_from_reference (unshare_expr (arg));
          }
 
        if (level == 1)
@@ -10504,7 +11595,7 @@ tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
 
        /* Substitute the exception specification.  */
        specs = tsubst_exception_specification (t, args, complain,
-                                               in_decl);
+                                               in_decl, /*defer_ok*/true);
        if (specs == error_mark_node)
          return error_mark_node;
        if (specs)
@@ -10584,8 +11675,7 @@ tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
               But, such constructs have already been resolved by this
               point, so here CTX really should have complete type, unless
               it's a partial instantiation.  */
-           if (!(complain & tf_no_class_instantiations))
-             ctx = complete_type (ctx);
+           ctx = complete_type (ctx);
            if (!COMPLETE_TYPE_P (ctx))
              {
                if (complain & tf_error)
@@ -10607,11 +11697,21 @@ tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
        if (TREE_CODE (f) != TYPENAME_TYPE)
          {
            if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
-             error ("%qT resolves to %qT, which is not an enumeration type",
-                    t, f);
+             {
+               if (complain & tf_error)
+                 error ("%qT resolves to %qT, which is not an enumeration type",
+                        t, f);
+               else
+                 return error_mark_node;
+             }
            else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
-             error ("%qT resolves to %qT, which is is not a class type",
-                    t, f);
+             {
+               if (complain & tf_error)
+                 error ("%qT resolves to %qT, which is is not a class type",
+                        t, f);
+               else
+                 return error_mark_node;
+             }
          }
 
        return cp_build_qualified_type_real
@@ -10670,17 +11770,24 @@ tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
 
        if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
          type = lambda_capture_field_type (type);
-       else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
-         type = lambda_return_type (type);
+       else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
+         type = lambda_proxy_type (type);
        else
          type = finish_decltype_type
-           (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
+           (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
        return cp_build_qualified_type_real (type,
                                             cp_type_quals (t)
                                             | cp_type_quals (type),
                                             complain);
       }
 
+    case UNDERLYING_TYPE:
+      {
+       tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
+                           complain, in_decl);
+       return finish_underlying_type (type);
+      }
+
     case TYPE_ARGUMENT_PACK:
     case NONTYPE_ARGUMENT_PACK:
       {
@@ -10839,8 +11946,12 @@ tsubst_qualified_id (tree qualified_id, tree args,
     expr = name;
 
   if (dependent_scope_p (scope))
-    return build_qualified_name (NULL_TREE, scope, expr,
-                                QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
+    {
+      if (is_template)
+       expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
+      return build_qualified_name (NULL_TREE, scope, expr,
+                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
+    }
 
   if (!BASELINK_P (name) && !DECL_P (expr))
     {
@@ -10900,7 +12011,7 @@ tsubst_qualified_id (tree qualified_id, tree args,
       expr = (adjust_result_of_qualified_name_lookup
              (expr, scope, current_class_type));
       expr = (finish_qualified_id_expr
-             (scope, expr, done, address_p,
+             (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
               QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
               /*template_arg_p=*/false));
     }
@@ -10917,7 +12028,7 @@ tsubst_qualified_id (tree qualified_id, tree args,
 
 /* Like tsubst, but deals with expressions.  This function just replaces
    template parms; to finish processing the resultant expression, use
-   tsubst_expr.  */
+   tsubst_copy_and_build or tsubst_expr.  */
 
 static tree
 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
@@ -10938,6 +12049,13 @@ tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
       if (r == NULL)
        {
          tree c;
+
+         /* We get here for a use of 'this' in an NSDMI.  */
+         if (DECL_NAME (t) == this_identifier
+             && at_function_scope_p ()
+             && DECL_CONSTRUCTOR_P (current_function_decl))
+           return current_class_ptr;
+
          /* This can happen for a parameter name used later in a function
             declaration (such as in a late-specified return type).  Just
             make a dummy decl, since it's only used for its type.  */
@@ -11029,6 +12147,9 @@ tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
       mark_used (t);
       return t;
 
+    case NAMESPACE_DECL:
+      return t;
+
     case OVERLOAD:
       /* An OVERLOAD will always be a non-dependent overload set; an
         overload set from function scope will just be represented with an
@@ -11075,6 +12196,8 @@ tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
     case CONST_CAST_EXPR:
     case STATIC_CAST_EXPR:
     case DYNAMIC_CAST_EXPR:
+    case IMPLICIT_CONV_EXPR:
+    case CONVERT_EXPR:
     case NOP_EXPR:
       return build1
        (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
@@ -11083,11 +12206,18 @@ tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
     case SIZEOF_EXPR:
       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
         {
-          /* We only want to compute the number of arguments.  */
-          tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
-                                                complain, in_decl);
+
+          tree expanded;
          int len = 0;
 
+         ++cp_unevaluated_operand;
+         ++c_inhibit_evaluation_warnings;
+         /* We only want to compute the number of arguments.  */
+         expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
+                                           complain, in_decl);
+         --cp_unevaluated_operand;
+         --c_inhibit_evaluation_warnings;
+
          if (TREE_CODE (expanded) == TREE_VEC)
            len = TREE_VEC_LENGTH (expanded);
 
@@ -11156,7 +12286,7 @@ tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
                                         base, name,
                                         /*template_p=*/false);
          }
-       else if (TREE_CODE (name) == BASELINK)
+       else if (BASELINK_P (name))
          name = tsubst_baselink (name,
                                  non_reference (TREE_TYPE (object)),
                                  args, complain,
@@ -11365,6 +12495,7 @@ tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
     case INTEGER_CST:
     case REAL_CST:
     case STRING_CST:
+    case COMPLEX_CST:
       {
        /* Instantiate any typedefs in the type.  */
        tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
@@ -11380,7 +12511,9 @@ tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
       return t;
 
     default:
-      gcc_unreachable ();
+      /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
+      gcc_checking_assert (false);
+      return t;
     }
 }
 
@@ -11420,6 +12553,7 @@ tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
        case OMP_CLAUSE_NUM_THREADS:
        case OMP_CLAUSE_SCHEDULE:
        case OMP_CLAUSE_COLLAPSE:
+       case OMP_CLAUSE_FINAL:
          OMP_CLAUSE_OPERAND (nc, 0)
            = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
                           in_decl, /*integral_constant_expression_p=*/false);
@@ -11428,6 +12562,7 @@ tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
        case OMP_CLAUSE_ORDERED:
        case OMP_CLAUSE_DEFAULT:
        case OMP_CLAUSE_UNTIED:
+       case OMP_CLAUSE_MERGEABLE:
          break;
        default:
          gcc_unreachable ();
@@ -11666,10 +12801,10 @@ tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
 
     case DECL_EXPR:
       {
-       tree decl;
+       tree decl, pattern_decl;
        tree init;
 
-       decl = DECL_EXPR_DECL (t);
+       pattern_decl = decl = DECL_EXPR_DECL (t);
        if (TREE_CODE (decl) == LABEL_DECL)
          finish_label_decl (DECL_NAME (decl));
        else if (TREE_CODE (decl) == USING_DECL)
@@ -11704,8 +12839,14 @@ tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
                    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
                  /* Anonymous aggregates are a special case.  */
                  finish_anon_union (decl);
+               else if (is_capture_proxy (DECL_EXPR_DECL (t)))
+                 {
+                   DECL_CONTEXT (decl) = current_function_decl;
+                   insert_capture_proxy (decl);
+                 }
                else
                  {
+                   int const_init = false;
                    maybe_push_decl (decl);
                    if (TREE_CODE (decl) == VAR_DECL
                        && DECL_PRETTY_FUNCTION_P (decl))
@@ -11732,13 +12873,16 @@ tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
                            init = build_value_init (TREE_TYPE (decl),
                                                     complain);
                            if (TREE_CODE (init) == AGGR_INIT_EXPR)
-                             init = get_target_expr (init);
+                             init = get_target_expr_sfinae (init, complain);
                          }
                        else
                          init = t;
                      }
 
-                   cp_finish_decl (decl, init, false, NULL_TREE, 0);
+                   if (TREE_CODE (decl) == VAR_DECL)
+                     const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
+                                   (pattern_decl));
+                   cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
                  }
              }
          }
@@ -11749,7 +12893,7 @@ tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
       }
 
     case FOR_STMT:
-      stmt = begin_for_stmt ();
+      stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
       RECUR (FOR_INIT_STMT (t));
       finish_for_init_stmt (stmt);
       tmp = RECUR (FOR_COND (t));
@@ -11763,7 +12907,7 @@ tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
     case RANGE_FOR_STMT:
       {
         tree decl, expr;
-        stmt = begin_for_stmt ();
+        stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
         decl = RANGE_FOR_DECL (t);
         decl = tsubst (decl, args, complain, in_decl);
         maybe_push_decl (decl);
@@ -12054,14 +13198,93 @@ tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
 
     case OMP_ATOMIC:
       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
+      if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
+       {
+         tree op1 = TREE_OPERAND (t, 1);
+         tree rhs1 = NULL_TREE;
+         tree lhs, rhs;
+         if (TREE_CODE (op1) == COMPOUND_EXPR)
+           {
+             rhs1 = RECUR (TREE_OPERAND (op1, 0));
+             op1 = TREE_OPERAND (op1, 1);
+           }
+         lhs = RECUR (TREE_OPERAND (op1, 0));
+         rhs = RECUR (TREE_OPERAND (op1, 1));
+         finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
+                            NULL_TREE, NULL_TREE, rhs1);
+       }
+      else
+       {
+         tree op1 = TREE_OPERAND (t, 1);
+         tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
+         tree rhs1 = NULL_TREE;
+         enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
+         enum tree_code opcode = NOP_EXPR;
+         if (code == OMP_ATOMIC_READ)
+           {
+             v = RECUR (TREE_OPERAND (op1, 0));
+             lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
+           }
+         else if (code == OMP_ATOMIC_CAPTURE_OLD
+                  || code == OMP_ATOMIC_CAPTURE_NEW)
+           {
+             tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
+             v = RECUR (TREE_OPERAND (op1, 0));
+             lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
+             if (TREE_CODE (op11) == COMPOUND_EXPR)
+               {
+                 rhs1 = RECUR (TREE_OPERAND (op11, 0));
+                 op11 = TREE_OPERAND (op11, 1);
+               }
+             lhs = RECUR (TREE_OPERAND (op11, 0));
+             rhs = RECUR (TREE_OPERAND (op11, 1));
+             opcode = TREE_CODE (op11);
+           }
+         else
+           {
+             code = OMP_ATOMIC;
+             lhs = RECUR (TREE_OPERAND (op1, 0));
+             rhs = RECUR (TREE_OPERAND (op1, 1));
+           }
+         finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
+       }
+      break;
+
+    case TRANSACTION_EXPR:
       {
-       tree op1 = TREE_OPERAND (t, 1);
-       tree lhs = RECUR (TREE_OPERAND (op1, 0));
-       tree rhs = RECUR (TREE_OPERAND (op1, 1));
-       finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
+       int flags = 0;
+       flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
+       flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
+
+        if (TRANSACTION_EXPR_IS_STMT (t))
+          {
+           tree body = TRANSACTION_EXPR_BODY (t);
+           tree noex = NULL_TREE;
+           if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
+             {
+               noex = MUST_NOT_THROW_COND (body);
+               if (noex == NULL_TREE)
+                 noex = boolean_true_node;
+               body = TREE_OPERAND (body, 0);
+             }
+            stmt = begin_transaction_stmt (input_location, NULL, flags);
+            RECUR (body);
+            finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
+          }
+        else
+          {
+            stmt = build_transaction_expr (EXPR_LOCATION (t),
+                                          RECUR (TRANSACTION_EXPR_BODY (t)),
+                                          flags, NULL_TREE);
+            return stmt;
+          }
       }
       break;
 
+    case MUST_NOT_THROW_EXPR:
+      return build_must_not_throw_expr (RECUR (TREE_OPERAND (t, 0)),
+                                       RECUR (MUST_NOT_THROW_COND (t)));
+
     case EXPR_PACK_EXPANSION:
       error ("invalid use of pack expansion expression");
       return error_mark_node;
@@ -12151,7 +13374,7 @@ tsubst_copy_and_build (tree t,
        decl = finish_id_expression (t, decl, NULL_TREE,
                                     &idk,
                                     integral_constant_expression_p,
-                                    /*allow_non_integral_constant_expression_p=*/false,
+          /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx0x),
                                     &non_integral_constant_expression_p,
                                     /*template_p=*/false,
                                     /*done=*/true,
@@ -12162,7 +13385,11 @@ tsubst_copy_and_build (tree t,
        if (error_msg)
          error (error_msg);
        if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
-         decl = unqualified_name_lookup_error (decl);
+         {
+           if (complain & tf_error)
+             unqualified_name_lookup_error (decl);
+           decl = error_mark_node;
+         }
        return decl;
       }
 
@@ -12213,6 +13440,23 @@ tsubst_copy_and_build (tree t,
        (tsubst (TREE_TYPE (t), args, complain, in_decl),
         RECUR (TREE_OPERAND (t, 0)));
 
+    case IMPLICIT_CONV_EXPR:
+      {
+       tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
+       tree expr = RECUR (TREE_OPERAND (t, 0));
+       int flags = LOOKUP_IMPLICIT;
+       if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
+         flags = LOOKUP_NORMAL;
+       return perform_implicit_conversion_flags (type, expr, complain,
+                                                 flags);
+      }
+
+    case CONVERT_EXPR:
+      return build1
+       (CONVERT_EXPR,
+        tsubst (TREE_TYPE (t), args, complain, in_decl),
+        RECUR (TREE_OPERAND (t, 0)));
+
     case CAST_EXPR:
     case REINTERPRET_CAST_EXPR:
     case CONST_CAST_EXPR:
@@ -12269,6 +13513,10 @@ tsubst_copy_and_build (tree t,
       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
                                complain);
 
+    case FIX_TRUNC_EXPR:
+      return cp_build_unary_op (FIX_TRUNC_EXPR, RECUR (TREE_OPERAND (t, 0)),
+                               0, complain);
+
     case ADDR_EXPR:
       op1 = TREE_OPERAND (t, 0);
       if (TREE_CODE (op1) == LABEL_DECL)
@@ -12323,7 +13571,7 @@ tsubst_copy_and_build (tree t,
         (TREE_NO_WARNING (TREE_OPERAND (t, 1))
          ? ERROR_MARK
          : TREE_CODE (TREE_OPERAND (t, 1))),
-        /*overloaded_p=*/NULL,
+        /*overload=*/NULL,
         complain);
 
     case SCOPE_REF:
@@ -12473,7 +13721,8 @@ tsubst_copy_and_build (tree t,
        (RECUR (TREE_OPERAND (t, 0)),
        RECUR (TREE_OPERAND (t, 1)),
        DELETE_EXPR_USE_VEC (t),
-       DELETE_EXPR_USE_GLOBAL (t));
+       DELETE_EXPR_USE_GLOBAL (t),
+       complain);
 
     case COMPOUND_EXPR:
       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
@@ -12500,6 +13749,20 @@ tsubst_copy_and_build (tree t,
                                            /*done=*/false,
                                            /*address_p=*/false);
          }
+       else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
+         {
+           /* Do nothing; calling tsubst_copy_and_build on an identifier
+              would incorrectly perform unqualified lookup again.
+
+              Note that we can also have an IDENTIFIER_NODE if the earlier
+              unqualified lookup found a member function; in that case
+              koenig_p will be false and we do want to do the lookup
+              again to find the instantiated member function.
+
+              FIXME but doing that causes c++/15272, so we need to stop
+              using IDENTIFIER_NODE in that situation.  */
+           qualified_p = false;
+         }
        else
          {
            if (TREE_CODE (function) == COMPONENT_REF)
@@ -12571,13 +13834,65 @@ tsubst_copy_and_build (tree t,
               into a non-dependent call.  */
            && type_dependent_expression_p_push (t)
            && !any_type_dependent_arguments_p (call_args))
-         function = perform_koenig_lookup (function, call_args, false);
+         function = perform_koenig_lookup (function, call_args, false,
+                                           tf_none);
 
-       if (TREE_CODE (function) == IDENTIFIER_NODE)
+       if (TREE_CODE (function) == IDENTIFIER_NODE
+           && !any_type_dependent_arguments_p (call_args))
          {
-           unqualified_name_lookup_error (function);
-           release_tree_vector (call_args);
-           return error_mark_node;
+           if (koenig_p && (complain & tf_warning_or_error))
+             {
+               /* For backwards compatibility and good diagnostics, try
+                  the unqualified lookup again if we aren't in SFINAE
+                  context.  */
+               tree unq = (tsubst_copy_and_build
+                           (function, args, complain, in_decl, true,
+                            integral_constant_expression_p));
+               if (unq == error_mark_node)
+                 return error_mark_node;
+
+               if (unq != function)
+                 {
+                   tree fn = unq;
+                   if (TREE_CODE (fn) == INDIRECT_REF)
+                     fn = TREE_OPERAND (fn, 0);
+                   if (TREE_CODE (fn) == COMPONENT_REF)
+                     fn = TREE_OPERAND (fn, 1);
+                   if (is_overloaded_fn (fn))
+                     fn = get_first_fn (fn);
+                   permerror (EXPR_LOC_OR_HERE (t),
+                              "%qD was not declared in this scope, "
+                              "and no declarations were found by "
+                              "argument-dependent lookup at the point "
+                              "of instantiation", function);
+                   if (!DECL_P (fn))
+                     /* Can't say anything more.  */;
+                   else if (DECL_CLASS_SCOPE_P (fn))
+                     {
+                       inform (EXPR_LOC_OR_HERE (t),
+                               "declarations in dependent base %qT are "
+                               "not found by unqualified lookup",
+                               DECL_CLASS_CONTEXT (fn));
+                       if (current_class_ptr)
+                         inform (EXPR_LOC_OR_HERE (t),
+                                 "use %<this->%D%> instead", function);
+                       else
+                         inform (EXPR_LOC_OR_HERE (t),
+                                 "use %<%T::%D%> instead",
+                                 current_class_name, function);
+                     }
+                   else
+                     inform (0, "%q+D declared here, later in the "
+                               "translation unit", fn);
+                   function = unq;
+                 }
+             }
+           if (TREE_CODE (function) == IDENTIFIER_NODE)
+             {
+               unqualified_name_lookup_error (function);
+               release_tree_vector (call_args);
+               return error_mark_node;
+             }
          }
 
        /* Remember that there was a reference to this entity.  */
@@ -12633,7 +13948,7 @@ tsubst_copy_and_build (tree t,
       return finish_pseudo_destructor_expr
        (RECUR (TREE_OPERAND (t, 0)),
         RECUR (TREE_OPERAND (t, 1)),
-        RECUR (TREE_OPERAND (t, 2)));
+        tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
 
     case TREE_LIST:
       {
@@ -12744,7 +14059,9 @@ tsubst_copy_and_build (tree t,
        if (member == error_mark_node)
          return error_mark_node;
 
-       if (object_type && !CLASS_TYPE_P (object_type))
+       if (type_dependent_expression_p (object))
+         /* We can't do much here.  */;
+       else if (!CLASS_TYPE_P (object_type))
          {
            if (SCALAR_TYPE_P (object_type))
              {
@@ -12767,14 +14084,12 @@ tsubst_copy_and_build (tree t,
        else if (TREE_CODE (member) == SCOPE_REF
                 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
          {
-           tree tmpl;
-           tree args;
-
            /* Lookup the template functions now that we know what the
               scope is.  */
-           tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
-           args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
-           member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
+           tree scope = TREE_OPERAND (member, 0);
+           tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
+           tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
+           member = lookup_qualified_name (scope, tmpl,
                                            /*is_type_p=*/false,
                                            /*complain=*/false);
            if (BASELINK_P (member))
@@ -12788,7 +14103,7 @@ tsubst_copy_and_build (tree t,
              }
            else
              {
-               qualified_name_lookup_error (object_type, tmpl, member,
+               qualified_name_lookup_error (scope, tmpl, member,
                                             input_location);
                return error_mark_node;
              }
@@ -12856,7 +14171,8 @@ tsubst_copy_and_build (tree t,
                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
                                                   in_decl);
 
-               if (ce->value == error_mark_node)
+               if (ce->value == error_mark_node
+                   || PACK_EXPANSION_P (ce->value))
                  ;
                else if (TREE_VEC_LENGTH (ce->value) == 1)
                   /* Just move the argument into place.  */
@@ -12897,8 +14213,9 @@ tsubst_copy_and_build (tree t,
        CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
 
        if (TREE_HAS_CONSTRUCTOR (t))
-         return finish_compound_literal (type, r);
+         return finish_compound_literal (type, r, complain);
 
+       TREE_TYPE (r) = type;
        return r;
       }
 
@@ -12935,8 +14252,7 @@ tsubst_copy_and_build (tree t,
 
     case VA_ARG_EXPR:
       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
-                            tsubst_copy (TREE_TYPE (t), args, complain,
-                                         in_decl));
+                            tsubst (TREE_TYPE (t), args, complain, in_decl));
 
     case OFFSETOF_EXPR:
       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
@@ -12976,7 +14292,7 @@ tsubst_copy_and_build (tree t,
       t = tsubst_copy (t, args, complain, in_decl);
       /* As in finish_id_expression, we resolve enumeration constants
         to their underlying values.  */
-      if (TREE_CODE (t) == CONST_DECL)
+      if (TREE_CODE (t) == CONST_DECL && !processing_template_decl)
        {
          used_types_insert (TREE_TYPE (t));
          return DECL_INITIAL (t);
@@ -12987,8 +14303,8 @@ tsubst_copy_and_build (tree t,
       {
        tree r = build_lambda_expr ();
 
-       tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
-       TREE_TYPE (r) = type;
+       tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
+       LAMBDA_EXPR_CLOSURE (r) = type;
        CLASSTYPE_LAMBDA_EXPR (type) = r;
 
        LAMBDA_EXPR_LOCATION (r)
@@ -12998,12 +14314,19 @@ tsubst_copy_and_build (tree t,
        LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
        LAMBDA_EXPR_DISCRIMINATOR (r)
          = (LAMBDA_EXPR_DISCRIMINATOR (t));
-       LAMBDA_EXPR_CAPTURE_LIST (r)
-         = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
-       LAMBDA_EXPR_THIS_CAPTURE (r)
-         = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
        LAMBDA_EXPR_EXTRA_SCOPE (r)
          = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
+       if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
+         {
+           LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
+           LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
+         }
+       else
+         LAMBDA_EXPR_RETURN_TYPE (r)
+           = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
+
+       gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
+                   && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
 
        /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
        determine_visibility (TYPE_NAME (type));
@@ -13011,13 +14334,28 @@ tsubst_copy_and_build (tree t,
           declaration of the op() for later calls to lambda_function.  */
        complete_type (type);
 
-       type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
-       if (type)
-         apply_lambda_return_type (r, type);
+       /* The capture list refers to closure members, so this needs to
+          wait until after we finish instantiating the type.  */
+       LAMBDA_EXPR_CAPTURE_LIST (r)
+         = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
 
        return build_lambda_object (r);
       }
 
+    case TARGET_EXPR:
+      /* We can get here for a constant initializer of non-dependent type.
+         FIXME stop folding in cp_parser_initializer_clause.  */
+      gcc_assert (TREE_CONSTANT (t));
+      {
+       tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
+       TREE_CONSTANT (r) = true;
+       return r;
+      }
+
+    case TRANSACTION_EXPR:
+      return tsubst_expr(t, args, complain, in_decl,
+            integral_constant_expression_p);
+
     default:
       /* Handle Objective-C++ constructs, if appropriate.  */
       {
@@ -13117,22 +14455,81 @@ check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
   return result;
 }
 
-/* Instantiate the indicated variable or function template TMPL with
-   the template arguments in TARG_PTR.  */
+/* In C++0x, it's possible to have a function template whose type depends
+   on itself recursively.  This is most obvious with decltype, but can also
+   occur with enumeration scope (c++/48969).  So we need to catch infinite
+   recursion and reject the substitution at deduction time; this function
+   will return error_mark_node for any repeated substitution.
 
-tree
-instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
+   This also catches excessive recursion such as when f<N> depends on
+   f<N-1> across all integers, and returns error_mark_node for all the
+   substitutions back up to the initial one.
+
+   This is, of course, not reentrant.  */
+
+static tree
+deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
 {
-  tree targ_ptr = orig_args;
-  tree fndecl;
-  tree gen_tmpl;
-  tree spec;
-  HOST_WIDE_INT saved_processing_template_decl;
+  static bool excessive_deduction_depth;
+  static int deduction_depth;
+  struct pending_template *old_last_pend = last_pending_template;
+  struct tinst_level *old_error_tinst = last_error_tinst_level;
 
-  if (tmpl == error_mark_node)
+  tree fntype = TREE_TYPE (fn);
+  tree tinst;
+  tree r;
+
+  if (excessive_deduction_depth)
     return error_mark_node;
 
-  gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
+  tinst = build_tree_list (fn, targs);
+  if (!push_tinst_level (tinst))
+    {
+      excessive_deduction_depth = true;
+      ggc_free (tinst);
+      return error_mark_node;
+    }
+
+  input_location = DECL_SOURCE_LOCATION (fn);
+  ++deduction_depth;
+  push_deduction_access_scope (fn);
+  r = tsubst (fntype, targs, complain, NULL_TREE);
+  pop_deduction_access_scope (fn);
+  --deduction_depth;
+
+  if (excessive_deduction_depth)
+    {
+      r = error_mark_node;
+      if (deduction_depth == 0)
+       /* Reset once we're all the way out.  */
+       excessive_deduction_depth = false;
+    }
+
+  pop_tinst_level ();
+  /* We can't free this if a pending_template entry or last_error_tinst_level
+     is pointing at it.  */
+  if (last_pending_template == old_last_pend
+      && last_error_tinst_level == old_error_tinst)
+    ggc_free (tinst);
+  return r;
+}
+
+/* Instantiate the indicated variable or function template TMPL with
+   the template arguments in TARG_PTR.  */
+
+static tree
+instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
+{
+  tree targ_ptr = orig_args;
+  tree fndecl;
+  tree gen_tmpl;
+  tree spec;
+  HOST_WIDE_INT saved_processing_template_decl;
+
+  if (tmpl == error_mark_node)
+    return error_mark_node;
+
+  gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
 
   /* If this function is a clone, handle it specially.  */
   if (DECL_CLONED_FUNCTION_P (tmpl))
@@ -13230,6 +14627,82 @@ instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
   return fndecl;
 }
 
+/* Wrapper for instantiate_template_1.  */
+
+tree
+instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
+{
+  tree ret;
+  timevar_push (TV_TEMPLATE_INST);
+  ret = instantiate_template_1 (tmpl, orig_args,  complain);
+  timevar_pop (TV_TEMPLATE_INST);
+  return ret;
+}
+
+/* We're going to do deduction substitution on the type of TMPL, a function
+   template.  In C++11 mode, push into that access scope.  In C++03 mode,
+   disable access checking.  */
+
+static void
+push_deduction_access_scope (tree tmpl)
+{
+  if (cxx_dialect >= cxx0x)
+    {
+      int ptd = processing_template_decl;
+      push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
+      /* Preserve processing_template_decl across push_to_top_level.  */
+      if (ptd && !processing_template_decl)
+       ++processing_template_decl;
+    }
+  else
+    push_deferring_access_checks (dk_no_check);
+}
+
+/* And pop back out.  */
+
+static void
+pop_deduction_access_scope (tree tmpl)
+{
+  if (cxx_dialect >= cxx0x)
+    pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
+  else
+    pop_deferring_access_checks ();
+}
+
+/* PARM is a template parameter pack for FN.  Returns true iff
+   PARM is used in a deducible way in the argument list of FN.  */
+
+static bool
+pack_deducible_p (tree parm, tree fn)
+{
+  tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
+  for (; t; t = TREE_CHAIN (t))
+    {
+      tree type = TREE_VALUE (t);
+      tree packs;
+      if (!PACK_EXPANSION_P (type))
+       continue;
+      for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
+          packs; packs = TREE_CHAIN (packs))
+       if (TREE_VALUE (packs) == parm)
+         {
+           /* The template parameter pack is used in a function parameter
+              pack.  If this is the end of the parameter list, the
+              template parameter pack is deducible.  */
+           if (TREE_CHAIN (t) == void_list_node)
+             return true;
+           else
+             /* Otherwise, not.  Well, it could be deduced from
+                a non-pack parameter, but doing so would end up with
+                a deduction mismatch, so don't bother.  */
+             return false;
+         }
+    }
+  /* The template parameter pack isn't used in any function parameter
+     packs, but it might be used deeper, e.g. tuple<Args...>.  */
+  return true;
+}
+
 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
    NARGS elements of the arguments that are being used when calling
    it.  TARGS is a vector into which the deduced template arguments
@@ -13269,12 +14742,12 @@ fn_type_unification (tree fn,
                     unsigned int nargs,
                     tree return_type,
                     unification_kind_t strict,
-                    int flags)
+                    int flags,
+                    bool explain_p)
 {
   tree parms;
   tree fntype;
   int result;
-  bool incomplete_argument_packs_p = false;
 
   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
 
@@ -13304,12 +14777,15 @@ fn_type_unification (tree fn,
       bool incomplete = false;
 
       if (explicit_targs == error_mark_node)
-       return 1;
+       return unify_invalid (explain_p);
 
       converted_args
-       = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
-                                 /*require_all_args=*/false,
-                                 /*use_default_args=*/false));
+       = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
+                                 (explain_p
+                                  ? tf_warning_or_error
+                                  : tf_none),
+                                  /*require_all_args=*/false,
+                                  /*use_default_args=*/false));
       if (converted_args == error_mark_node)
        return 1;
 
@@ -13323,6 +14799,7 @@ fn_type_unification (tree fn,
         {
           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
           bool parameter_pack = false;
+         tree targ = TREE_VEC_ELT (converted_args, i);
 
           /* Dig out the actual parm.  */
           if (TREE_CODE (parm) == TYPE_DECL
@@ -13337,15 +14814,15 @@ fn_type_unification (tree fn,
               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
             }
 
-          if (parameter_pack)
-            {
-              int level, idx;
-              tree targ;
-              template_parm_level_and_index (parm, &level, &idx);
+         if (!parameter_pack && targ == NULL_TREE)
+           /* No explicit argument for this template parameter.  */
+           incomplete = true;
 
+          if (parameter_pack && pack_deducible_p (parm, fn))
+            {
               /* Mark the argument pack as "incomplete". We could
-                 still deduce more arguments during unification.  */
-              targ = TMPL_ARG (converted_args, level, idx);
+                 still deduce more arguments during unification.
+                We remove this mark in type_unification_real.  */
               if (targ)
                 {
                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
@@ -13354,20 +14831,15 @@ fn_type_unification (tree fn,
                 }
 
               /* We have some incomplete argument packs.  */
-              incomplete_argument_packs_p = true;
+              incomplete = true;
             }
         }
 
-      if (incomplete_argument_packs_p)
-        /* Any substitution is guaranteed to be incomplete if there
-           are incomplete argument packs, because we can still deduce
-           more arguments.  */
-        incomplete = 1;
-      else
-        incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
-
       processing_template_decl += incomplete;
-      fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
+      fntype = deduction_tsubst_fntype (fn, converted_args,
+                                       (explain_p
+                                        ? tf_warning_or_error
+                                        : tf_none));
       processing_template_decl -= incomplete;
 
       if (fntype == error_mark_node)
@@ -13399,23 +14871,7 @@ fn_type_unification (tree fn,
      event.  */
   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
                                  targs, parms, args, nargs, /*subr=*/0,
-                                 strict, flags);
-
-  if (result == 0 && incomplete_argument_packs_p)
-    {
-      int i, len = NUM_TMPL_ARGS (targs);
-
-      /* Clear the "incomplete" flags on all argument packs.  */
-      for (i = 0; i < len; i++)
-        {
-          tree arg = TREE_VEC_ELT (targs, i);
-          if (ARGUMENT_PACK_P (arg))
-            {
-              ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
-              ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
-            }
-        }
-    }
+                                 strict, flags, explain_p);
 
   /* Now that we have bindings for all of the template arguments,
      ensure that the arguments deduced for the template template
@@ -13441,7 +14897,7 @@ fn_type_unification (tree fn,
   if (result == 0
       && !template_template_parm_bindings_ok_p 
            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
-    return 1;
+    return unify_inconsistent_template_template_parameters (explain_p);
 
   if (result == 0)
     /* All is well so far.  Now, check:
@@ -13454,7 +14910,10 @@ fn_type_unification (tree fn,
        substitution results in an invalid type, as described above,
        type deduction fails.  */
     {
-      tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
+      tree substed = deduction_tsubst_fntype (fn, targs,
+                                             (explain_p
+                                              ? tf_warning_or_error
+                                              : tf_none));
       if (substed == error_mark_node)
        return 1;
 
@@ -13471,7 +14930,8 @@ fn_type_unification (tree fn,
            sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
          for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
            if (!same_type_p (args[i], TREE_VALUE (sarg)))
-             return 1;
+             return unify_type_mismatch (explain_p, args[i],
+                                         TREE_VALUE (sarg));
        }
     }
 
@@ -13561,7 +15021,10 @@ maybe_adjust_types_for_deduction (unification_kind_t strict,
       && TYPE_REF_IS_RVALUE (*parm)
       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
-      && arg_expr && real_lvalue_p (arg_expr))
+      && (arg_expr ? real_lvalue_p (arg_expr)
+         /* try_one_overload doesn't provide an arg_expr, but
+            functions are always lvalues.  */
+         : TREE_CODE (*arg) == FUNCTION_TYPE))
     *arg = build_reference_type (*arg);
 
   /* [temp.deduct.call]
@@ -13585,6 +15048,134 @@ maybe_adjust_types_for_deduction (unification_kind_t strict,
   return result;
 }
 
+/* Subroutine of unify_one_argument.  PARM is a function parameter of a
+   template which does contain any deducible template parameters; check if
+   ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
+   unify_one_argument.  */
+
+static int
+check_non_deducible_conversion (tree parm, tree arg, int strict,
+                               int flags, bool explain_p)
+{
+  tree type;
+
+  if (!TYPE_P (arg))
+    type = TREE_TYPE (arg);
+  else
+    type = arg;
+
+  if (same_type_p (parm, type))
+    return unify_success (explain_p);
+
+  if (strict == DEDUCE_CONV)
+    {
+      if (can_convert_arg (type, parm, NULL_TREE, flags))
+       return unify_success (explain_p);
+    }
+  else if (strict != DEDUCE_EXACT)
+    {
+      if (can_convert_arg (parm, type,
+                          TYPE_P (arg) ? NULL_TREE : arg,
+                          flags))
+       return unify_success (explain_p);
+    }
+
+  if (strict == DEDUCE_EXACT)
+    return unify_type_mismatch (explain_p, parm, arg);
+  else
+    return unify_arg_conversion (explain_p, parm, type, arg);
+}
+
+/* Subroutine of type_unification_real and unify_pack_expansion to
+   handle unification of a single P/A pair.  Parameters are as
+   for those functions.  */
+
+static int
+unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
+                   int subr, unification_kind_t strict, int flags,
+                   bool explain_p)
+{
+  tree arg_expr = NULL_TREE;
+  int arg_strict;
+
+  if (arg == error_mark_node || parm == error_mark_node)
+    return unify_invalid (explain_p);
+  if (arg == unknown_type_node)
+    /* We can't deduce anything from this, but we might get all the
+       template args from other function args.  */
+    return unify_success (explain_p);
+
+  /* FIXME uses_deducible_template_parms */
+  if (TYPE_P (parm) && !uses_template_parms (parm))
+    return check_non_deducible_conversion (parm, arg, strict, flags,
+                                          explain_p);
+
+  switch (strict)
+    {
+    case DEDUCE_CALL:
+      arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
+                   | UNIFY_ALLOW_MORE_CV_QUAL
+                   | UNIFY_ALLOW_DERIVED);
+      break;
+
+    case DEDUCE_CONV:
+      arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
+      break;
+
+    case DEDUCE_EXACT:
+      arg_strict = UNIFY_ALLOW_NONE;
+      break;
+
+    default:
+      gcc_unreachable ();
+    }
+
+  /* We only do these transformations if this is the top-level
+     parameter_type_list in a call or declaration matching; in other
+     situations (nested function declarators, template argument lists) we
+     won't be comparing a type to an expression, and we don't do any type
+     adjustments.  */
+  if (!subr)
+    {
+      if (!TYPE_P (arg))
+       {
+         gcc_assert (TREE_TYPE (arg) != NULL_TREE);
+         if (type_unknown_p (arg))
+           {
+             /* [temp.deduct.type] A template-argument can be
+                deduced from a pointer to function or pointer
+                to member function argument if the set of
+                overloaded functions does not contain function
+                templates and at most one of a set of
+                overloaded functions provides a unique
+                match.  */
+
+             if (resolve_overloaded_unification
+                 (tparms, targs, parm, arg, strict,
+                  arg_strict, explain_p))
+               return unify_success (explain_p);
+             return unify_overload_resolution_failure (explain_p, arg);
+           }
+
+         arg_expr = arg;
+         arg = unlowered_expr_type (arg);
+         if (arg == error_mark_node)
+           return unify_invalid (explain_p);
+       }
+
+      arg_strict |=
+       maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
+    }
+  else
+    gcc_assert ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
+               == (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL));
+
+  /* For deduction from an init-list we need the actual list.  */
+  if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
+    arg = arg_expr;
+  return unify (tparms, targs, parm, arg, arg_strict, explain_p);
+}
+
 /* Most parms like fn_type_unification.
 
    If SUBR is 1, we're being called recursively (to unify the
@@ -13599,12 +15190,12 @@ type_unification_real (tree tparms,
                       unsigned int xnargs,
                       int subr,
                       unification_kind_t strict,
-                      int flags)
+                      int flags,
+                      bool explain_p)
 {
-  tree parm, arg, arg_expr;
+  tree parm, arg;
   int i;
   int ntparms = TREE_VEC_LENGTH (tparms);
-  int sub_strict;
   int saw_undeduced = 0;
   tree parms;
   const tree *args;
@@ -13616,28 +15207,9 @@ type_unification_real (tree tparms,
   gcc_assert (ntparms > 0);
 
   /* Reset the number of non-defaulted template arguments contained
-     in in TARGS.  */
+     in TARGS.  */
   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
 
-  switch (strict)
-    {
-    case DEDUCE_CALL:
-      sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
-                   | UNIFY_ALLOW_DERIVED);
-      break;
-
-    case DEDUCE_CONV:
-      sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
-      break;
-
-    case DEDUCE_EXACT:
-      sub_strict = UNIFY_ALLOW_NONE;
-      break;
-
-    default:
-      gcc_unreachable ();
-    }
-
  again:
   parms = xparms;
   args = xargs;
@@ -13647,84 +15219,32 @@ type_unification_real (tree tparms,
   while (parms && parms != void_list_node
         && ia < nargs)
     {
-      if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
-        break;
-
       parm = TREE_VALUE (parms);
-      parms = TREE_CHAIN (parms);
-      arg = args[ia];
-      ++ia;
-      arg_expr = NULL;
-
-      if (arg == error_mark_node)
-       return 1;
-      if (arg == unknown_type_node)
-       /* We can't deduce anything from this, but we might get all the
-          template args from other function args.  */
-       continue;
-
-      /* Conversions will be performed on a function argument that
-        corresponds with a function parameter that contains only
-        non-deducible template parameters and explicitly specified
-        template parameters.  */
-      if (!uses_template_parms (parm))
-       {
-         tree type;
-
-         if (!TYPE_P (arg))
-           type = TREE_TYPE (arg);
-         else
-           type = arg;
 
-         if (same_type_p (parm, type))
-           continue;
-         if (strict != DEDUCE_EXACT
-             && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
-                                 flags))
-           continue;
-
-         return 1;
-       }
-
-      if (!TYPE_P (arg))
-       {
-         gcc_assert (TREE_TYPE (arg) != NULL_TREE);
-         if (type_unknown_p (arg))
-           {
-             /* [temp.deduct.type] 
-
-                A template-argument can be deduced from a pointer to
-                function or pointer to member function argument if
-                the set of overloaded functions does not contain
-                function templates and at most one of a set of
-                overloaded functions provides a unique match.  */
-             if (resolve_overloaded_unification
-                 (tparms, targs, parm, arg, strict, sub_strict))
-               continue;
+      if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
+         && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
+       /* For a function parameter pack that occurs at the end of the
+          parameter-declaration-list, the type A of each remaining
+          argument of the call is compared with the type P of the
+          declarator-id of the function parameter pack.  */
+       break;
 
-             return 1;
-           }
-         arg_expr = arg;
-         arg = unlowered_expr_type (arg);
-         if (arg == error_mark_node)
-           return 1;
-       }
+      parms = TREE_CHAIN (parms);
 
-      {
-       int arg_strict = sub_strict;
+      if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
+       /* For a function parameter pack that does not occur at the
+          end of the parameter-declaration-list, the type of the
+          parameter pack is a non-deduced context.  */
+       continue;
 
-       if (!subr)
-         arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
-                                                         arg_expr);
+      arg = args[ia];
+      ++ia;
 
-       if (arg == init_list_type_node && arg_expr)
-         arg = arg_expr;
-       if (unify (tparms, targs, parm, arg, arg_strict))
-         return 1;
-      }
+      if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
+                             flags, explain_p))
+       return 1;
     }
 
-
   if (parms 
       && parms != void_list_node
       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
@@ -13741,7 +15261,7 @@ type_unification_real (tree tparms,
       /* Copy the parameter into parmvec.  */
       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
-                                /*call_args_p=*/true, /*subr=*/subr))
+                                /*subr=*/subr, explain_p))
         return 1;
 
       /* Advance to the end of the list of parameters.  */
@@ -13751,22 +15271,37 @@ type_unification_real (tree tparms,
   /* Fail if we've reached the end of the parm list, and more args
      are present, and the parm list isn't variadic.  */
   if (ia < nargs && parms == void_list_node)
-    return 1;
+    return unify_too_many_arguments (explain_p, nargs, ia);
   /* Fail if parms are left and they don't have default values.  */
   if (parms && parms != void_list_node
       && TREE_PURPOSE (parms) == NULL_TREE)
-    return 1;
+    {
+      unsigned int count = nargs;
+      tree p = parms;
+      while (p && p != void_list_node)
+       {
+         count++;
+         p = TREE_CHAIN (p);
+       }
+      return unify_too_few_arguments (explain_p, ia, count);
+    }
 
   if (!subr)
-    for (i = 0; i < ntparms; i++)
-      if (!TREE_VEC_ELT (targs, i))
-       {
-         tree tparm;
+    {
+      tsubst_flags_t complain = (explain_p
+                                ? tf_warning_or_error
+                                : tf_none);
 
-          if (TREE_VEC_ELT (tparms, i) == error_mark_node)
-            continue;
+      /* Check to see if we need another pass before we start clearing
+        ARGUMENT_PACK_INCOMPLETE_P.  */
+      for (i = 0; i < ntparms; i++)
+       {
+         tree targ = TREE_VEC_ELT (targs, i);
+         tree tparm = TREE_VEC_ELT (tparms, i);
 
-          tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
+         if (targ || tparm == error_mark_node)
+           continue;
+         tparm = TREE_VALUE (tparm);
 
          /* If this is an undeduced nontype parameter that depends on
             a type parameter, try another pass; its type may have been
@@ -13776,65 +15311,88 @@ type_unification_real (tree tparms,
              && uses_template_parms (TREE_TYPE (tparm))
              && !saw_undeduced++)
            goto again;
+       }
 
-          /* Core issue #226 (C++0x) [temp.deduct]:
+      for (i = 0; i < ntparms; i++)
+       {
+         tree targ = TREE_VEC_ELT (targs, i);
+         tree tparm = TREE_VEC_ELT (tparms, i);
 
-               If a template argument has not been deduced, its
-               default template argument, if any, is used. 
+         /* Clear the "incomplete" flags on all argument packs now so that
+            substituting them into later default arguments works.  */
+         if (targ && ARGUMENT_PACK_P (targ))
+            {
+              ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
+              ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
+            }
+
+         if (targ || tparm == error_mark_node)
+           continue;
+         tparm = TREE_VALUE (tparm);
 
-             When we are in C++98 mode, TREE_PURPOSE will either
+         /* Core issue #226 (C++0x) [temp.deduct]:
+
+            If a template argument has not been deduced, its
+            default template argument, if any, is used. 
+
+            When we are in C++98 mode, TREE_PURPOSE will either
             be NULL_TREE or ERROR_MARK_NODE, so we do not need
             to explicitly check cxx_dialect here.  */
-          if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
-            {
+         if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
+           {
              tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
              tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
-              arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
-             arg = convert_template_argument (parm, arg, targs, tf_none,
+             location_t save_loc = input_location;
+             if (DECL_P (parm))
+               input_location = DECL_SOURCE_LOCATION (parm);
+             arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
+             arg = convert_template_argument (parm, arg, targs, complain,
                                               i, NULL_TREE);
-              if (arg == error_mark_node)
-                return 1;
-              else
-                {
-                  TREE_VEC_ELT (targs, i) = arg;
+             input_location = save_loc;
+             if (arg == error_mark_node)
+               return 1;
+             else
+               {
+                 TREE_VEC_ELT (targs, i) = arg;
                  /* The position of the first default template argument,
                     is also the number of non-defaulted arguments in TARGS.
                     Record that.  */
                  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
                    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
-                  continue;
-                }
-            }
+                 continue;
+               }
+           }
 
-          /* If the type parameter is a parameter pack, then it will
-             be deduced to an empty parameter pack.  */
-          if (template_parameter_pack_p (tparm))
-            {
-              tree arg;
+         /* If the type parameter is a parameter pack, then it will
+            be deduced to an empty parameter pack.  */
+         if (template_parameter_pack_p (tparm))
+           {
+             tree arg;
 
-              if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
-                {
-                  arg = make_node (NONTYPE_ARGUMENT_PACK);
-                  TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
-                  TREE_CONSTANT (arg) = 1;
-                }
-              else
-                arg = cxx_make_type (TYPE_ARGUMENT_PACK);
+             if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
+               {
+                 arg = make_node (NONTYPE_ARGUMENT_PACK);
+                 TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
+                 TREE_CONSTANT (arg) = 1;
+               }
+             else
+               arg = cxx_make_type (TYPE_ARGUMENT_PACK);
 
-              SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
+             SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
 
-              TREE_VEC_ELT (targs, i) = arg;
-              continue;
-            }
+             TREE_VEC_ELT (targs, i) = arg;
+             continue;
+           }
 
-         return 2;
+         return unify_parameter_deduction_failure (explain_p, tparm);
        }
+    }
 #ifdef ENABLE_CHECKING
   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
 #endif
 
-  return 0;
+  return unify_success (explain_p);
 }
 
 /* Subroutine of type_unification_real.  Args are like the variables
@@ -13849,7 +15407,8 @@ resolve_overloaded_unification (tree tparms,
                                tree parm,
                                tree arg,
                                unification_kind_t strict,
-                               int sub_strict)
+                               int sub_strict,
+                               bool explain_p)
 {
   tree tempargs = copy_node (targs);
   int good = 0;
@@ -13882,6 +15441,7 @@ resolve_overloaded_unification (tree tparms,
         the affected templates before we try to unify, in case the
         explicit args will completely resolve the templates in question.  */
 
+      int ok = 0;
       tree expl_subargs = TREE_OPERAND (arg, 1);
       arg = TREE_OPERAND (arg, 0);
 
@@ -13896,19 +15456,27 @@ resolve_overloaded_unification (tree tparms,
          ++processing_template_decl;
          subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
                                  expl_subargs, /*check_ret=*/false);
-         if (subargs)
+         if (subargs && !any_dependent_template_arguments_p (subargs))
            {
              elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
              if (try_one_overload (tparms, targs, tempargs, parm,
-                                   elem, strict, sub_strict, addr_p)
+                                   elem, strict, sub_strict, addr_p, explain_p)
                  && (!goodfn || !decls_match (goodfn, elem)))
                {
                  goodfn = elem;
                  ++good;
                }
            }
+         else if (subargs)
+           ++ok;
          --processing_template_decl;
        }
+      /* If no templates (or more than one) are fully resolved by the
+        explicit arguments, this template-id is a non-deduced context; it
+        could still be OK if we deduce all template arguments for the
+        enclosing call through other arguments.  */
+      if (good != 1)
+       good = ok;
     }
   else if (TREE_CODE (arg) != OVERLOAD
           && TREE_CODE (arg) != FUNCTION_DECL)
@@ -13920,7 +15488,7 @@ resolve_overloaded_unification (tree tparms,
     for (; arg; arg = OVL_NEXT (arg))
       if (try_one_overload (tparms, targs, tempargs, parm,
                            TREE_TYPE (OVL_CURRENT (arg)),
-                           strict, sub_strict, addr_p)
+                           strict, sub_strict, addr_p, explain_p)
          && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
        {
          goodfn = OVL_CURRENT (arg);
@@ -13978,7 +15546,7 @@ resolve_nondeduced_context (tree orig_expr)
       offset = expr;
       expr = TREE_OPERAND (expr, 1);
     }
-  if (TREE_CODE (expr) == BASELINK)
+  if (BASELINK_P (expr))
     {
       baselink = expr;
       expr = BASELINK_FUNCTIONS (expr);
@@ -14027,16 +15595,20 @@ resolve_nondeduced_context (tree orig_expr)
        }
       if (good == 1)
        {
+         mark_used (goodfn);
          expr = goodfn;
          if (baselink)
            expr = build_baselink (BASELINK_BINFO (baselink),
                                   BASELINK_ACCESS_BINFO (baselink),
                                   expr, BASELINK_OPTYPE (baselink));
          if (offset)
-           expr = build2 (OFFSET_REF, TREE_TYPE (expr),
-                          TREE_OPERAND (offset, 0), expr);
+           {
+             tree base
+               = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
+             expr = build_offset_ref (base, expr, addr);
+           }
          if (addr)
-           expr = build_address (expr);
+           expr = cp_build_addr_expr (expr, tf_warning_or_error);
          return expr;
        }
       else if (good == 0 && badargs)
@@ -14063,7 +15635,8 @@ try_one_overload (tree tparms,
                  tree arg,
                  unification_kind_t strict,
                  int sub_strict,
-                 bool addr_p)
+                 bool addr_p,
+                 bool explain_p)
 {
   int nargs;
   tree tempargs;
@@ -14093,7 +15666,7 @@ try_one_overload (tree tparms,
   nargs = TREE_VEC_LENGTH (targs);
   tempargs = make_tree_vec (nargs);
 
-  if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
+  if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
     return 0;
 
   /* First make sure we didn't deduce anything that conflicts with
@@ -14131,7 +15704,8 @@ try_one_overload (tree tparms,
    TARGS are as for unify.  */
 
 static tree
-try_class_unification (tree tparms, tree targs, tree parm, tree arg)
+try_class_unification (tree tparms, tree targs, tree parm, tree arg,
+                      bool explain_p)
 {
   tree copy_of_targs;
 
@@ -14174,7 +15748,7 @@ try_class_unification (tree tparms, tree targs, tree parm, tree arg)
 
   /* If unification failed, we're done.  */
   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
-            CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
+            CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
     return NULL_TREE;
 
   return arg;
@@ -14187,8 +15761,9 @@ try_class_unification (tree tparms, tree targs, tree parm, tree arg)
    a partial specialization, as well as a plain template type.  Used
    by unify.  */
 
-static tree
-get_template_base (tree tparms, tree targs, tree parm, tree arg)
+static enum template_base_result
+get_template_base (tree tparms, tree targs, tree parm, tree arg,
+                  bool explain_p, tree *result)
 {
   tree rval = NULL_TREE;
   tree binfo;
@@ -14197,14 +15772,18 @@ get_template_base (tree tparms, tree targs, tree parm, tree arg)
 
   binfo = TYPE_BINFO (complete_type (arg));
   if (!binfo)
-    /* The type could not be completed.  */
-    return NULL_TREE;
+    {
+      /* The type could not be completed.  */
+      *result = NULL_TREE;
+      return tbr_incomplete_type;
+    }
 
   /* Walk in inheritance graph order.  The search order is not
      important, and this avoids multiple walks of virtual bases.  */
   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
     {
-      tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
+      tree r = try_class_unification (tparms, targs, parm,
+                                     BINFO_TYPE (binfo), explain_p);
 
       if (r)
        {
@@ -14217,13 +15796,17 @@ get_template_base (tree tparms, tree targs, tree parm, tree arg)
 
             applies.  */
          if (rval && !same_type_p (r, rval))
-           return NULL_TREE;
+           {
+             *result = NULL_TREE;
+             return tbr_ambiguous_baseclass;
+           }
 
          rval = r;
        }
     }
 
-  return rval;
+  *result = rval;
+  return tbr_success;
 }
 
 /* Returns the level of DECL, which declares a template parameter.  */
@@ -14305,17 +15888,25 @@ template_parm_level_and_index (tree parm, int* level, int* index)
     }
 }
 
+#define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                   \
+  do {                                                                 \
+    if (unify (TP, TA, P, A, S, EP))                                   \
+      return 1;                                                                \
+  } while (0);
+
 /* Unifies the remaining arguments in PACKED_ARGS with the pack
    expansion at the end of PACKED_PARMS. Returns 0 if the type
    deduction succeeds, 1 otherwise. STRICT is the same as in
    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
    call argument list. We'll need to adjust the arguments to make them
    types. SUBR tells us if this is from a recursive call to
-   type_unification_real.  */
-int
+   type_unification_real, or for comparing two template argument
+   lists. */
+
+static int
 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
-                      tree packed_args, int strict, bool call_args_p,
-                      bool subr)
+                      tree packed_args, unification_kind_t strict,
+                      bool subr, bool explain_p)
 {
   tree parm 
     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
@@ -14345,98 +15936,55 @@ unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
      unified and unify each with the pattern.  */
   for (i = start; i < len; i++)
     {
-      tree parm = pattern;
+      tree parm;
+      bool any_explicit = false;
+      tree arg = TREE_VEC_ELT (packed_args, i);
 
-      /* For each parameter pack, clear out the deduced value so that
-         we can deduce it again.  */
+      /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
+        or the element of its argument pack at the current index if
+        this argument was explicitly specified.  */
       for (pack = packs; pack; pack = TREE_CHAIN (pack))
         {
           int idx, level;
+          tree arg, pargs;
           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
 
-          TMPL_ARG (targs, level, idx) = NULL_TREE;
+          arg = NULL_TREE;
+          if (TREE_VALUE (pack)
+              && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
+              && (i < TREE_VEC_LENGTH (pargs)))
+            {
+              any_explicit = true;
+              arg = TREE_VEC_ELT (pargs, i);
+            }
+          TMPL_ARG (targs, level, idx) = arg;
         }
 
-      /* Unify the pattern with the current argument.  */
-      {
-        tree arg = TREE_VEC_ELT (packed_args, i);
-       tree arg_expr = NULL_TREE;
-        int arg_strict = strict;
-        bool skip_arg_p = false;
-
-        if (call_args_p)
-          {
-            int sub_strict;
-
-            /* This mirrors what we do in type_unification_real.  */
-            switch (strict)
-              {
-              case DEDUCE_CALL:
-                sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
-                              | UNIFY_ALLOW_MORE_CV_QUAL
-                              | UNIFY_ALLOW_DERIVED);
-                break;
-                
-              case DEDUCE_CONV:
-                sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
-                break;
-                
-              case DEDUCE_EXACT:
-                sub_strict = UNIFY_ALLOW_NONE;
-                break;
-                
-              default:
-                gcc_unreachable ();
-              }
-
-            if (!TYPE_P (arg))
-              {
-                gcc_assert (TREE_TYPE (arg) != NULL_TREE);
-                if (type_unknown_p (arg))
-                  {
-                    /* [temp.deduct.type] A template-argument can be
-                       deduced from a pointer to function or pointer
-                       to member function argument if the set of
-                       overloaded functions does not contain function
-                       templates and at most one of a set of
-                       overloaded functions provides a unique
-                       match.  */
-
-                    if (resolve_overloaded_unification
-                        (tparms, targs, parm, arg,
-                        (unification_kind_t) strict,
-                        sub_strict)
-                        != 0)
-                      return 1;
-                    skip_arg_p = true;
-                  }
-
-                if (!skip_arg_p)
-                  {
-                   arg_expr = arg;
-                    arg = unlowered_expr_type (arg);
-                    if (arg == error_mark_node)
-                      return 1;
-                  }
-              }
-      
-            arg_strict = sub_strict;
-
-            if (!subr)
-              arg_strict |= 
-                maybe_adjust_types_for_deduction ((unification_kind_t) strict,
-                                                 &parm, &arg, arg_expr);
-          }
+      /* If we had explicit template arguments, substitute them into the
+        pattern before deduction.  */
+      if (any_explicit)
+       {
+         /* Some arguments might still be unspecified or dependent.  */
+         bool dependent;
+         ++processing_template_decl;
+         dependent = any_dependent_template_arguments_p (targs);
+         if (!dependent)
+           --processing_template_decl;
+         parm = tsubst (pattern, targs,
+                        explain_p ? tf_warning_or_error : tf_none,
+                        NULL_TREE);
+         if (dependent)
+           --processing_template_decl;
+         if (parm == error_mark_node)
+           return 1;
+       }
+      else
+       parm = pattern;
 
-        if (!skip_arg_p)
-          {
-           /* For deduction from an init-list we need the actual list.  */
-           if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
-             arg = arg_expr;
-            if (unify (tparms, targs, parm, arg, arg_strict))
-              return 1;
-          }
-      }
+      /* Unify the pattern with the current argument.  */
+      if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
+                             LOOKUP_IMPLICIT, explain_p))
+       return 1;
 
       /* For each parameter pack, collect the deduced value.  */
       for (pack = packs; pack; pack = TREE_CHAIN (pack))
@@ -14476,21 +16024,12 @@ unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
 
       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
         {
-          /* Prepend the explicit arguments onto NEW_ARGS.  */
+          /* If we had fewer function args than explicit template args,
+             just use the explicits.  */
           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
-          tree old_args = new_args;
-          int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
-          int len = explicit_len + TREE_VEC_LENGTH (old_args);
-
-          /* Copy the explicit arguments.  */
-          new_args = make_tree_vec (len);
-          for (i = 0; i < explicit_len; i++)
-            TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
-
-          /* Copy the deduced arguments.  */
-          for (; i < len; i++)
-            TREE_VEC_ELT (new_args, i) =
-              TREE_VEC_ELT (old_args, i - explicit_len);
+          int explicit_len = TREE_VEC_LENGTH (explicit_args);
+          if (len < explicit_len)
+            new_args = explicit_args;
         }
 
       if (!old_pack)
@@ -14525,13 +16064,21 @@ unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
         }
-      else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
-                                    new_args))
-        /* Inconsistent unification of this parameter pack.  */
-        return 1;
+      else
+       {
+         tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
+         tree old_args = ARGUMENT_PACK_ARGS (old_pack);
+
+         if (!comp_template_args_with_info (old_args, new_args,
+                                            &bad_old_arg, &bad_new_arg))
+           /* Inconsistent unification of this parameter pack.  */
+           return unify_parameter_pack_inconsistent (explain_p,
+                                                     bad_old_arg,
+                                                     bad_new_arg);
+       }
     }
 
-  return 0;
+  return unify_success (explain_p);
 }
 
 /* Deduce the value of template parameters.  TPARMS is the (innermost)
@@ -14576,7 +16123,8 @@ unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
        qualified at this point.  */
 
 static int
-unify (tree tparms, tree targs, tree parm, tree arg, int strict)
+unify (tree tparms, tree targs, tree parm, tree arg, int strict,
+       bool explain_p)
 {
   int idx;
   tree targ;
@@ -14591,19 +16139,19 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
     parm = TREE_OPERAND (parm, 0);
 
   if (arg == error_mark_node)
-    return 1;
+    return unify_invalid (explain_p);
   if (arg == unknown_type_node
       || arg == init_list_type_node)
     /* We can't deduce anything from this, but we might get all the
        template args from other function args.  */
-    return 0;
+    return unify_success (explain_p);
 
   /* If PARM uses template parameters, then we can't bail out here,
      even if ARG == PARM, since we won't record unifications for the
      template parameters.  We might need them if we're trying to
      figure out which of two things is more specialized.  */
   if (arg == parm && !uses_template_parms (parm))
-    return 0;
+    return unify_success (explain_p);
 
   /* Handle init lists early, so the rest of the function can assume
      we're dealing with a type. */
@@ -14622,7 +16170,7 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
        /* We can only deduce from an initializer list argument if the
           parameter is std::initializer_list; otherwise this is a
           non-deduced context. */
-       return 0;
+       return unify_success (explain_p);
 
       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
 
@@ -14631,7 +16179,7 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
          int elt_strict = strict;
 
          if (elt == error_mark_node)
-           return 1;
+           return unify_invalid (explain_p);
 
          if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
            {
@@ -14643,8 +16191,8 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
              elt = type;
            }
 
-         if (unify (tparms, targs, elttype, elt, elt_strict))
-           return 1;
+         RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
+                                  explain_p);
        }
 
       /* If the std::initializer_list<T> deduction worked, replace the
@@ -14656,7 +16204,7 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
          targ = listify (targ);
          TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
        }
-      return 0;
+      return unify_success (explain_p);
     }
 
   /* Immediately reject some pairs that won't unify because of
@@ -14673,7 +16221,7 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
         is more specialized, for example.  */
       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
       && !check_cv_quals_for_unify (strict_in, arg, parm))
-    return 1;
+    return unify_cv_qual_mismatch (explain_p, parm, arg);
 
   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
@@ -14691,21 +16239,26 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
       /* In a type which contains a nested-name-specifier, template
         argument values cannot be deduced for template parameters used
         within the nested-name-specifier.  */
-      return 0;
+      return unify_success (explain_p);
 
     case TEMPLATE_TYPE_PARM:
     case TEMPLATE_TEMPLATE_PARM:
     case BOUND_TEMPLATE_TEMPLATE_PARM:
       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
       if (tparm == error_mark_node)
-       return 1;
+       return unify_invalid (explain_p);
 
       if (TEMPLATE_TYPE_LEVEL (parm)
          != template_decl_level (tparm))
        /* The PARM is not one we're trying to unify.  Just check
           to see if it matches ARG.  */
-       return (TREE_CODE (arg) == TREE_CODE (parm)
-               && same_type_p (parm, arg)) ? 0 : 1;
+       {
+         if (TREE_CODE (arg) == TREE_CODE (parm)
+             && same_type_p (parm, arg))
+           return unify_success (explain_p);
+         else
+           return unify_type_mismatch (explain_p, parm, arg);
+       }
       idx = TEMPLATE_TYPE_IDX (parm);
       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
@@ -14715,7 +16268,7 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
           && TREE_CODE (tparm) != TYPE_DECL)
          || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
              && TREE_CODE (tparm) != TEMPLATE_DECL))
-       return 1;
+       gcc_unreachable ();
 
       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
        {
@@ -14723,11 +16276,12 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
             template parameter.  */
          if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
              && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
-           return 1;
+           return unify_template_deduction_failure (explain_p, parm, arg);
 
          {
            tree parmvec = TYPE_TI_ARGS (parm);
            tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
+           tree full_argvec = add_to_template_args (targs, argvec);
            tree parm_parms 
               = DECL_INNERMOST_TEMPLATE_PARMS
                  (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
@@ -14762,9 +16316,11 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
              the global operator+ will be used; if they are not, the
              Lvalue_proxy will be converted to float.  */
            if (coerce_template_parms (parm_parms,
-                                       argvec,
+                                       full_argvec,
                                       TYPE_TI_TEMPLATE (parm),
-                                      tf_none,
+                                      (explain_p
+                                       ? tf_warning_or_error
+                                       : tf_none),
                                       /*require_all_args=*/true,
                                       /*use_default_args=*/false)
                == error_mark_node)
@@ -14787,23 +16343,22 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
               parm_variadic_p = 1;
             
             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
-              return 1;
+              return unify_too_few_arguments (explain_p,
+                                             TREE_VEC_LENGTH (argvec), len);
 
              for (i = 0; i < len - parm_variadic_p; ++i)
              {
-               if (unify (tparms, targs,
-                          TREE_VEC_ELT (parmvec, i),
-                          TREE_VEC_ELT (argvec, i),
-                          UNIFY_ALLOW_NONE))
-                 return 1;
+               RECUR_AND_CHECK_FAILURE (tparms, targs,
+                                        TREE_VEC_ELT (parmvec, i),
+                                        TREE_VEC_ELT (argvec, i),
+                                        UNIFY_ALLOW_NONE, explain_p);
              }
 
            if (parm_variadic_p
                && unify_pack_expansion (tparms, targs,
                                         parmvec, argvec,
-                                        UNIFY_ALLOW_NONE,
-                                        /*call_args_p=*/false,
-                                        /*subr=*/false))
+                                        DEDUCE_EXACT,
+                                        /*subr=*/true, explain_p))
              return 1;
          }
          arg = TYPE_TI_TEMPLATE (arg);
@@ -14818,9 +16373,9 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
 
          /* Simple cases: Value already set, does match or doesn't.  */
          if (targ != NULL_TREE && template_args_equal (targ, arg))
-           return 0;
+           return unify_success (explain_p);
          else if (targ)
-           return 1;
+           return unify_inconsistency (explain_p, parm, targ, arg);
        }
       else
        {
@@ -14830,68 +16385,79 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
             that binds `const int' to `T'.  */
          if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
                                         arg, parm))
-           return 1;
+           return unify_cv_qual_mismatch (explain_p, parm, arg);
 
          /* Consider the case where ARG is `const volatile int' and
             PARM is `const T'.  Then, T should be `volatile int'.  */
          arg = cp_build_qualified_type_real
            (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
          if (arg == error_mark_node)
-           return 1;
+           return unify_invalid (explain_p);
 
          /* Simple cases: Value already set, does match or doesn't.  */
          if (targ != NULL_TREE && same_type_p (targ, arg))
-           return 0;
+           return unify_success (explain_p);
          else if (targ)
-           return 1;
+           return unify_inconsistency (explain_p, parm, targ, arg);
 
          /* Make sure that ARG is not a variable-sized array.  (Note
             that were talking about variable-sized arrays (like
             `int[n]'), rather than arrays of unknown size (like
             `int[]').)  We'll get very confused by such a type since
-            the bound of the array will not be computable in an
-            instantiation.  Besides, such types are not allowed in
-            ISO C++, so we can do as we please here.  */
-         if (variably_modified_type_p (arg, NULL_TREE))
-           return 1;
+            the bound of the array is not constant, and therefore
+            not mangleable.  Besides, such types are not allowed in
+            ISO C++, so we can do as we please here.  We do allow
+            them for 'auto' deduction, since that isn't ABI-exposed.  */
+         if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
+           return unify_vla_arg (explain_p, arg);
 
          /* Strip typedefs as in convert_template_argument.  */
-         arg = strip_typedefs (arg);
+         arg = canonicalize_type_argument (arg, tf_none);
        }
 
       /* If ARG is a parameter pack or an expansion, we cannot unify
         against it unless PARM is also a parameter pack.  */
       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
          && !template_parameter_pack_p (parm))
-       return 1;
+       return unify_parameter_pack_mismatch (explain_p, parm, arg);
 
       /* If the argument deduction results is a METHOD_TYPE,
          then there is a problem.
          METHOD_TYPE doesn't map to any real C++ type the result of
         the deduction can not be of that type.  */
       if (TREE_CODE (arg) == METHOD_TYPE)
-       return 1;
+       return unify_method_type_error (explain_p, arg);
 
       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
-      return 0;
+      return unify_success (explain_p);
 
     case TEMPLATE_PARM_INDEX:
       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
       if (tparm == error_mark_node)
-       return 1;
+       return unify_invalid (explain_p);
 
       if (TEMPLATE_PARM_LEVEL (parm)
          != template_decl_level (tparm))
-       /* The PARM is not one we're trying to unify.  Just check
-          to see if it matches ARG.  */
-       return !(TREE_CODE (arg) == TREE_CODE (parm)
-                && cp_tree_equal (parm, arg));
+       {
+         /* The PARM is not one we're trying to unify.  Just check
+            to see if it matches ARG.  */
+         int result = !(TREE_CODE (arg) == TREE_CODE (parm)
+                        && cp_tree_equal (parm, arg));
+         if (result)
+           unify_expression_unequal (explain_p, parm, arg);
+         return result;
+       }
 
       idx = TEMPLATE_PARM_IDX (parm);
       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
 
       if (targ)
-       return !cp_tree_equal (targ, arg);
+       {
+         int x = !cp_tree_equal (targ, arg);
+         if (x)
+           unify_inconsistency (explain_p, parm, targ, arg);
+         return x;
+       }
 
       /* [temp.deduct.type] If, in the declaration of a function template
         with a non-type template-parameter, the non-type
@@ -14918,25 +16484,25 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
       else if (uses_template_parms (tparm))
        /* We haven't deduced the type of this parameter yet.  Try again
           later.  */
-       return 0;
+       return unify_success (explain_p);
       else
-       return 1;
+       return unify_type_mismatch (explain_p, tparm, arg);
 
       /* If ARG is a parameter pack or an expansion, we cannot unify
         against it unless PARM is also a parameter pack.  */
       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
          && !TEMPLATE_PARM_PARAMETER_PACK (parm))
-       return 1;
+       return unify_parameter_pack_mismatch (explain_p, parm, arg);
 
       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
-      return 0;
+      return unify_success (explain_p);
 
     case PTRMEM_CST:
      {
        /* A pointer-to-member constant can be unified only with
         another constant.  */
       if (TREE_CODE (arg) != PTRMEM_CST)
-       return 1;
+       return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
 
       /* Just unify the class member. It would be useless (and possibly
         wrong, depending on the strict flags) to unify also
@@ -14949,13 +16515,13 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
 
         Unification of &A::x and &B::x must succeed.  */
       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
-                   PTRMEM_CST_MEMBER (arg), strict);
+                   PTRMEM_CST_MEMBER (arg), strict, explain_p);
      }
 
     case POINTER_TYPE:
       {
        if (TREE_CODE (arg) != POINTER_TYPE)
-         return 1;
+         return unify_type_mismatch (explain_p, parm, arg);
 
        /* [temp.deduct.call]
 
@@ -14973,21 +16539,21 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
          strict |= (strict_in & UNIFY_ALLOW_DERIVED);
 
        return unify (tparms, targs, TREE_TYPE (parm),
-                     TREE_TYPE (arg), strict);
+                     TREE_TYPE (arg), strict, explain_p);
       }
 
     case REFERENCE_TYPE:
       if (TREE_CODE (arg) != REFERENCE_TYPE)
-       return 1;
+       return unify_type_mismatch (explain_p, parm, arg);
       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
-                   strict & UNIFY_ALLOW_MORE_CV_QUAL);
+                   strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
 
     case ARRAY_TYPE:
       if (TREE_CODE (arg) != ARRAY_TYPE)
-       return 1;
+       return unify_type_mismatch (explain_p, parm, arg);
       if ((TYPE_DOMAIN (parm) == NULL_TREE)
          != (TYPE_DOMAIN (arg) == NULL_TREE))
-       return 1;
+       return unify_type_mismatch (explain_p, parm, arg);
       if (TYPE_DOMAIN (parm) != NULL_TREE)
        {
          tree parm_max;
@@ -15026,7 +16592,7 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
                 Here, the type of the ARG will be "int [g(i)]", and
                 may be a SAVE_EXPR, etc.  */
              if (TREE_CODE (arg_max) != MINUS_EXPR)
-               return 1;
+               return unify_vla_arg (explain_p, arg);
              arg_max = TREE_OPERAND (arg_max, 0);
            }
 
@@ -15043,11 +16609,11 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
                                   arg_max,
                                   integer_one_node);
 
-         if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
-           return 1;
+         RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
+                                  UNIFY_ALLOW_INTEGER, explain_p);
        }
       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
-                   strict & UNIFY_ALLOW_MORE_CV_QUAL);
+                   strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
 
     case REAL_TYPE:
     case COMPLEX_TYPE:
@@ -15056,17 +16622,18 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
     case BOOLEAN_TYPE:
     case ENUMERAL_TYPE:
     case VOID_TYPE:
+    case NULLPTR_TYPE:
       if (TREE_CODE (arg) != TREE_CODE (parm))
-       return 1;
+       return unify_type_mismatch (explain_p, parm, arg);
 
       /* We have already checked cv-qualification at the top of the
         function.  */
       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
-       return 1;
+       return unify_type_mismatch (explain_p, parm, arg);
 
       /* As far as unification is concerned, this wins.         Later checks
         will invalidate it if necessary.  */
-      return 0;
+      return unify_success (explain_p);
 
       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
       /* Type INTEGER_CST can come from ordinary constant template args.  */
@@ -15075,38 +16642,79 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
        arg = TREE_OPERAND (arg, 0);
 
       if (TREE_CODE (arg) != INTEGER_CST)
-       return 1;
-      return !tree_int_cst_equal (parm, arg);
+       return unify_template_argument_mismatch (explain_p, parm, arg);
+      return (tree_int_cst_equal (parm, arg)
+             ? unify_success (explain_p)
+             : unify_template_argument_mismatch (explain_p, parm, arg));
 
     case TREE_VEC:
       {
-       int i;
+       int i, len, argslen;
+       int parm_variadic_p = 0;
+
        if (TREE_CODE (arg) != TREE_VEC)
-         return 1;
-       if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
-         return 1;
-       for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
-         if (unify (tparms, targs,
-                    TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
-                    UNIFY_ALLOW_NONE))
-           return 1;
-       return 0;
+         return unify_template_argument_mismatch (explain_p, parm, arg);
+
+       len = TREE_VEC_LENGTH (parm);
+       argslen = TREE_VEC_LENGTH (arg);
+
+       /* Check for pack expansions in the parameters.  */
+       for (i = 0; i < len; ++i)
+         {
+           if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
+             {
+               if (i == len - 1)
+                 /* We can unify against something with a trailing
+                    parameter pack.  */
+                 parm_variadic_p = 1;
+               else
+                 /* [temp.deduct.type]/9: If the template argument list of
+                    P contains a pack expansion that is not the last
+                    template argument, the entire template argument list
+                    is a non-deduced context.  */
+                 return unify_success (explain_p);
+             }
+         }
+
+        /* If we don't have enough arguments to satisfy the parameters
+           (not counting the pack expression at the end), or we have
+           too many arguments for a parameter list that doesn't end in
+           a pack expression, we can't unify.  */
+       if (parm_variadic_p
+           ? argslen < len - parm_variadic_p
+           : argslen != len)
+         return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
+
+       /* Unify all of the parameters that precede the (optional)
+          pack expression.  */
+       for (i = 0; i < len - parm_variadic_p; ++i)
+         {
+           RECUR_AND_CHECK_FAILURE (tparms, targs,
+                                    TREE_VEC_ELT (parm, i),
+                                    TREE_VEC_ELT (arg, i),
+                                    UNIFY_ALLOW_NONE, explain_p);
+         }
+       if (parm_variadic_p)
+         return unify_pack_expansion (tparms, targs, parm, arg,
+                                      DEDUCE_EXACT,
+                                      /*subr=*/true, explain_p);
+       return unify_success (explain_p);
       }
 
     case RECORD_TYPE:
     case UNION_TYPE:
       if (TREE_CODE (arg) != TREE_CODE (parm))
-       return 1;
+       return unify_type_mismatch (explain_p, parm, arg);
 
       if (TYPE_PTRMEMFUNC_P (parm))
        {
          if (!TYPE_PTRMEMFUNC_P (arg))
-           return 1;
+           return unify_type_mismatch (explain_p, parm, arg);
 
          return unify (tparms, targs,
                        TYPE_PTRMEMFUNC_FN_TYPE (parm),
                        TYPE_PTRMEMFUNC_FN_TYPE (arg),
-                       strict);
+                       strict, explain_p);
        }
 
       if (CLASSTYPE_TEMPLATE_INFO (parm))
@@ -15117,7 +16725,7 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
            {
              /* First, we try to unify the PARM and ARG directly.  */
              t = try_class_unification (tparms, targs,
-                                        parm, arg);
+                                        parm, arg, explain_p);
 
              if (!t)
                {
@@ -15130,10 +16738,12 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
                       a class of the form template-id, A can be a
                       pointer to a derived class pointed to by the
                       deduced A.  */
-                 t = get_template_base (tparms, targs, parm, arg);
+                 enum template_base_result r;
+                 r = get_template_base (tparms, targs, parm, arg,
+                                        explain_p, &t);
 
                  if (!t)
-                   return 1;
+                   return unify_no_common_base (explain_p, r, parm, arg);
                }
            }
          else if (CLASSTYPE_TEMPLATE_INFO (arg)
@@ -15144,14 +16754,14 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
            t = arg;
          else
            /* There's no chance of unification succeeding.  */
-           return 1;
+           return unify_type_mismatch (explain_p, parm, arg);
 
          return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
-                       CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
+                       CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
        }
       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
-       return 1;
-      return 0;
+       return unify_type_mismatch (explain_p, parm, arg);
+      return unify_success (explain_p);
 
     case METHOD_TYPE:
     case FUNCTION_TYPE:
@@ -15162,7 +16772,7 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
        unsigned int i;
 
        if (TREE_CODE (arg) != TREE_CODE (parm))
-         return 1;
+         return unify_type_mismatch (explain_p, parm, arg);
 
        /* CV qualifications for methods can never be deduced, they must
           match exactly.  We need to check them explicitly here,
@@ -15171,13 +16781,12 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
        if (TREE_CODE (parm) == METHOD_TYPE
            && (!check_cv_quals_for_unify
                (UNIFY_ALLOW_NONE,
-                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
-                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
-         return 1;
+                class_of_this_parm (arg),
+                class_of_this_parm (parm))))
+         return unify_cv_qual_mismatch (explain_p, parm, arg);
 
-       if (unify (tparms, targs, TREE_TYPE (parm),
-                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
-         return 1;
+       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
+                                TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
 
        nargs = list_length (TYPE_ARG_TYPES (arg));
        args = XALLOCAVEC (tree, nargs);
@@ -15189,7 +16798,7 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
 
        return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
                                      args, nargs, 1, DEDUCE_EXACT,
-                                     LOOKUP_NORMAL);
+                                     LOOKUP_NORMAL, explain_p);
       }
 
     case OFFSET_TYPE:
@@ -15202,11 +16811,11 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
 
          /* Check top-level cv qualifiers */
          if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
-           return 1;
+           return unify_cv_qual_mismatch (explain_p, parm, arg);
 
-         if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
-                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
-           return 1;
+         RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
+                                  TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
+                                  UNIFY_ALLOW_NONE, explain_p);
 
          /* Determine the type of the function we are unifying against. */
          method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
@@ -15218,28 +16827,28 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
             implicit object parameter and place them on the function
             type to be restored later. */
          fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
-         return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
+         return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
        }
 
       if (TREE_CODE (arg) != OFFSET_TYPE)
-       return 1;
-      if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
-                TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
-       return 1;
+       return unify_type_mismatch (explain_p, parm, arg);
+      RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
+                              TYPE_OFFSET_BASETYPE (arg),
+                              UNIFY_ALLOW_NONE, explain_p);
       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
-                   strict);
+                   strict, explain_p);
 
     case CONST_DECL:
       if (DECL_TEMPLATE_PARM_P (parm))
-       return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
+       return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
       if (arg != integral_constant_value (parm))
-       return 1;
-      return 0;
+       return unify_template_argument_mismatch (explain_p, parm, arg);
+      return unify_success (explain_p);
 
     case FIELD_DECL:
     case TEMPLATE_DECL:
       /* Matched cases are handled by the ARG == PARM test above.  */
-      return 1;
+      return unify_template_argument_mismatch (explain_p, parm, arg);
 
     case VAR_DECL:
       /* A non-type template parameter that is a variable should be a
@@ -15250,68 +16859,24 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
 
     case TYPE_ARGUMENT_PACK:
     case NONTYPE_ARGUMENT_PACK:
-      {
-        tree packed_parms = ARGUMENT_PACK_ARGS (parm);
-        tree packed_args = ARGUMENT_PACK_ARGS (arg);
-        int i, len = TREE_VEC_LENGTH (packed_parms);
-        int argslen = TREE_VEC_LENGTH (packed_args);
-        int parm_variadic_p = 0;
-
-       for (i = 0; i < len; ++i)
-         {
-           if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
-             {
-               if (i == len - 1)
-                 /* We can unify against something with a trailing
-                    parameter pack.  */
-                 parm_variadic_p = 1;
-               else
-                 /* Since there is something following the pack
-                    expansion, we cannot unify this template argument
-                    list.  */
-                 return 0;
-             }
-         }
-         
-
-        /* If we don't have enough arguments to satisfy the parameters
-           (not counting the pack expression at the end), or we have
-           too many arguments for a parameter list that doesn't end in
-           a pack expression, we can't unify.  */
-        if (argslen < (len - parm_variadic_p)
-            || (argslen > len && !parm_variadic_p))
-          return 1;
-
-        /* Unify all of the parameters that precede the (optional)
-           pack expression.  */
-        for (i = 0; i < len - parm_variadic_p; ++i)
-          {
-            if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
-                       TREE_VEC_ELT (packed_args, i), strict))
-              return 1;
-          }
-
-        if (parm_variadic_p)
-          return unify_pack_expansion (tparms, targs, 
-                                       packed_parms, packed_args,
-                                       strict, /*call_args_p=*/false,
-                                       /*subr=*/false);
-        return 0;
-      }
-
-      break;
+      return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
+                   ARGUMENT_PACK_ARGS (arg), strict, explain_p);
 
     case TYPEOF_TYPE:
     case DECLTYPE_TYPE:
-      /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
-         nodes.  */
-      return 0;
+    case UNDERLYING_TYPE:
+      /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
+        or UNDERLYING_TYPE nodes.  */
+      return unify_success (explain_p);
 
     case ERROR_MARK:
       /* Unification fails if we hit an error node.  */
-      return 1;
+      return unify_invalid (explain_p);
 
     default:
+      /* An unresolved overload is a nondeduced context.  */
+      if (type_unknown_p (parm))
+       return unify_success (explain_p);
       gcc_assert (EXPR_P (parm));
 
       /* We must be looking at an expression.  This can happen with
@@ -15335,11 +16900,12 @@ unify (tree tparms, tree targs, tree parm, tree arg, int strict)
 
       if (!uses_template_parms (parm)
          && !template_args_equal (parm, arg))
-       return 1;
+       return unify_expression_unequal (explain_p, parm, arg);
       else
-       return 0;
+       return unify_success (explain_p);
     }
 }
+#undef RECUR_AND_CHECK_FAILURE
 \f
 /* Note that DECL can be defined in this translation unit, if
    required.  */
@@ -15602,10 +17168,10 @@ more_specialized_fn (tree pat1, tree pat2, int len)
           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
 
-          deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
-                                          argvec, UNIFY_ALLOW_NONE, 
-                                           /*call_args_p=*/false, 
-                                          /*subr=*/0);
+          deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
+                                          argvec, DEDUCE_EXACT,
+                                          /*subr=*/true, /*explain_p=*/false)
+                    == 0);
 
           /* We cannot deduce in the other direction, because ARG1 is
              a pack expansion but ARG2 is not.  */
@@ -15626,10 +17192,10 @@ more_specialized_fn (tree pat1, tree pat2, int len)
           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
 
-          deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
-                                          argvec, UNIFY_ALLOW_NONE, 
-                                           /*call_args_p=*/false, 
-                                          /*subr=*/0);
+          deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
+                                          argvec, DEDUCE_EXACT,
+                                          /*subr=*/true, /*explain_p=*/false)
+                    == 0);
 
           /* We cannot deduce in the other direction, because ARG2 is
              a pack expansion but ARG1 is not.*/
@@ -15640,8 +17206,12 @@ more_specialized_fn (tree pat1, tree pat2, int len)
         {
           /* The normal case, where neither argument is a pack
              expansion.  */
-          deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
-          deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
+          deduce1 = (unify (tparms1, targs1, arg1, arg2,
+                           UNIFY_ALLOW_NONE, /*explain_p=*/false)
+                    == 0);
+          deduce2 = (unify (tparms2, targs2, arg2, arg1,
+                           UNIFY_ALLOW_NONE, /*explain_p=*/false)
+                    == 0);
         }
 
       /* If we couldn't deduce arguments for tparms1 to make arg1 match
@@ -15855,7 +17425,7 @@ get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
                           args, ix,
                           (check_rettype || DECL_CONV_FN_P (fn)
                            ? TREE_TYPE (decl_type) : NULL_TREE),
-                          DEDUCE_EXACT, LOOKUP_NORMAL))
+                          DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
     return NULL_TREE;
 
   return targs;
@@ -15897,7 +17467,7 @@ get_class_bindings (tree tparms, tree spec_args, tree args)
   if (unify (tparms, deduced_args,
             INNERMOST_TEMPLATE_ARGS (spec_args),
             INNERMOST_TEMPLATE_ARGS (args),
-            UNIFY_ALLOW_NONE))
+            UNIFY_ALLOW_NONE, /*explain_p=*/false))
     return NULL_TREE;
 
   for (i =  0; i < ntparms; ++i)
@@ -15960,12 +17530,12 @@ most_specialized_instantiation (tree templates)
 
       if (get_bindings (TREE_VALUE (champ),
                        DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
-                       NULL_TREE, /*check_ret=*/false))
+                       NULL_TREE, /*check_ret=*/true))
        fate--;
 
       if (get_bindings (TREE_VALUE (fn),
                        DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
-                       NULL_TREE, /*check_ret=*/false))
+                       NULL_TREE, /*check_ret=*/true))
        fate++;
 
       if (fate == -1)
@@ -15987,10 +17557,10 @@ most_specialized_instantiation (tree templates)
     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
       if (get_bindings (TREE_VALUE (champ),
                        DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
-                       NULL_TREE, /*check_ret=*/false)
+                       NULL_TREE, /*check_ret=*/true)
          || !get_bindings (TREE_VALUE (fn),
                            DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
-                           NULL_TREE, /*check_ret=*/false))
+                           NULL_TREE, /*check_ret=*/true))
        {
          champ = NULL_TREE;
          break;
@@ -16198,7 +17768,7 @@ most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
       if (!(complain & tf_error))
        return error_mark_node;
       error ("ambiguous class template instantiation for %q#T", type);
-      str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
+      str = ngettext ("candidate is:", "candidates are:", list_length (list));
       for (t = list; t; t = TREE_CHAIN (t))
         {
           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
@@ -16388,7 +17958,12 @@ do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
 
   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
     {
-      error ("explicit instantiation of non-template type %qT", t);
+      tree tmpl =
+       (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
+      if (tmpl)
+       error ("explicit instantiation of non-class template %qD", tmpl);
+      else
+       error ("explicit instantiation of non-template type %qT", t);
       return;
     }
 
@@ -16559,8 +18134,9 @@ regenerate_decl_from_template (tree decl, tree tmpl)
        args = get_innermost_template_args (args, parms_depth);
 
       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
-                                             args, tf_error, NULL_TREE);
-      if (specs)
+                                             args, tf_error, NULL_TREE,
+                                             /*defer_ok*/false);
+      if (specs && specs != error_mark_node)
        TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
                                                    specs);
 
@@ -16721,7 +18297,72 @@ always_instantiate_p (tree decl)
             their initializers are available in integral constant
             expressions.  */
          || (TREE_CODE (decl) == VAR_DECL
-             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
+             && decl_maybe_constant_var_p (decl)));
+}
+
+/* If FN has a noexcept-specifier that hasn't been instantiated yet,
+   instantiate it now, modifying TREE_TYPE (fn).  */
+
+void
+maybe_instantiate_noexcept (tree fn)
+{
+  tree fntype, spec, noex, clone;
+
+  if (DECL_CLONED_FUNCTION_P (fn))
+    fn = DECL_CLONED_FUNCTION (fn);
+  fntype = TREE_TYPE (fn);
+  spec = TYPE_RAISES_EXCEPTIONS (fntype);
+
+  if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
+    return;
+
+  noex = TREE_PURPOSE (spec);
+
+  if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
+    {
+      if (push_tinst_level (fn))
+       {
+         push_access_scope (fn);
+         input_location = DECL_SOURCE_LOCATION (fn);
+         noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
+                                       DEFERRED_NOEXCEPT_ARGS (noex),
+                                       tf_warning_or_error, fn,
+                                       /*function_p=*/false,
+                                       /*integral_constant_expression_p=*/true);
+         pop_access_scope (fn);
+         pop_tinst_level ();
+         spec = build_noexcept_spec (noex, tf_warning_or_error);
+         if (spec == error_mark_node)
+           spec = noexcept_false_spec;
+       }
+      else
+       spec = noexcept_false_spec;
+    }
+  else
+    {
+      /* This is an implicitly declared function, so NOEX is a list of
+        other functions to evaluate and merge.  */
+      tree elt;
+      spec = noexcept_true_spec;
+      for (elt = noex; elt; elt = OVL_NEXT (elt))
+       {
+         tree fn = OVL_CURRENT (elt);
+         tree subspec;
+         maybe_instantiate_noexcept (fn);
+         subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
+         spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
+       }
+    }
+
+  TREE_TYPE (fn) = build_exception_variant (fntype, spec);
+
+  FOR_EACH_CLONE (clone, fn)
+    {
+      if (TREE_TYPE (clone) == fntype)
+       TREE_TYPE (clone) = TREE_TYPE (fn);
+      else
+       TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
+    }
 }
 
 /* Produce the definition of D, a _DECL generated from a template.  If
@@ -16757,7 +18398,8 @@ instantiate_decl (tree d, int defer_ok,
      case that an expression refers to the value of the variable --
      if the variable has a constant value the referring expression can
      take advantage of that fact.  */
-  if (TREE_CODE (d) == VAR_DECL)
+  if (TREE_CODE (d) == VAR_DECL
+      || DECL_DECLARED_CONSTEXPR_P (d))
     defer_ok = 0;
 
   /* Don't instantiate cloned functions.  Instead, instantiate the
@@ -16766,6 +18408,8 @@ instantiate_decl (tree d, int defer_ok,
     d = DECL_CLONED_FUNCTION (d);
 
   if (DECL_TEMPLATE_INSTANTIATED (d)
+      || (TREE_CODE (d) == FUNCTION_DECL
+         && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
       || DECL_TEMPLATE_SPECIALIZATION (d))
     /* D has already been instantiated or explicitly specialized, so
        there's nothing for us to do here.
@@ -16801,7 +18445,7 @@ instantiate_decl (tree d, int defer_ok,
   if (! push_tinst_level (d))
     return d;
 
-  timevar_push (TV_PARSE);
+  timevar_push (TV_TEMPLATE_INST);
 
   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
      for the instantiation.  */
@@ -16823,7 +18467,8 @@ instantiate_decl (tree d, int defer_ok,
     args = gen_args;
 
   if (TREE_CODE (d) == FUNCTION_DECL)
-    pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
+    pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
+                      || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
   else
     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
 
@@ -16838,6 +18483,8 @@ instantiate_decl (tree d, int defer_ok,
       && !DECL_NOT_REALLY_EXTERN (d))
     mark_definable (d);
 
+  DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
+  DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
   input_location = DECL_SOURCE_LOCATION (d);
 
   /* If D is a member of an explicitly instantiated class template,
@@ -16846,11 +18493,19 @@ instantiate_decl (tree d, int defer_ok,
   if (!pattern_defined && expl_inst_class_mem_p
       && DECL_EXPLICIT_INSTANTIATION (d))
     {
-      DECL_NOT_REALLY_EXTERN (d) = 0;
-      DECL_INTERFACE_KNOWN (d) = 0;
+      /* Leave linkage flags alone on instantiations with anonymous
+        visibility.  */
+      if (TREE_PUBLIC (d))
+       {
+         DECL_NOT_REALLY_EXTERN (d) = 0;
+         DECL_INTERFACE_KNOWN (d) = 0;
+       }
       SET_DECL_IMPLICIT_INSTANTIATION (d);
     }
 
+  if (TREE_CODE (d) == FUNCTION_DECL)
+    maybe_instantiate_noexcept (d);
+
   /* Recheck the substitutions to obtain any warning messages
      about ignoring cv qualifiers.  Don't do this for artificial decls,
      as it breaks the context-sensitive substitution for lambda op(). */
@@ -16868,7 +18523,7 @@ instantiate_decl (tree d, int defer_ok,
        {
          tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
-                                          d);
+                                          d, /*defer_ok*/true);
          /* Don't simply tsubst the function type, as that will give
             duplicate warnings about poor parameter qualifications.
             The function arguments are the same as the decl_arguments
@@ -16901,6 +18556,7 @@ instantiate_decl (tree d, int defer_ok,
        {
          tree ns;
          tree init;
+         bool const_init = false;
 
          ns = decl_namespace_context (d);
          push_nested_namespace (ns);
@@ -16909,7 +18565,11 @@ instantiate_decl (tree d, int defer_ok,
                              args,
                              tf_warning_or_error, NULL_TREE,
                              /*integral_constant_expression_p=*/false);
-         cp_finish_decl (d, init, /*init_const_expr_p=*/false,
+         /* Make sure the initializer is still constant, in case of
+            circular dependency (template/instantiate6.C). */
+         const_init
+           = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
+         cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
                          /*asmspec_tree=*/NULL_TREE,
                          LOOKUP_ONLYCONVERTING);
          pop_nested_class ();
@@ -16933,6 +18593,11 @@ instantiate_decl (tree d, int defer_ok,
        permerror (input_location,  "explicit instantiation of %qD "
                   "but no definition available", d);
 
+      /* If we're in unevaluated context, we just wanted to get the
+        constant value; this isn't an odr use, so don't queue
+        a full instantiation.  */
+      if (cp_unevaluated_operand != 0)
+       goto out;
       /* ??? Historically, we have instantiated inline functions, even
         when marked as "extern template".  */
       if (!(external_p && TREE_CODE (d) == VAR_DECL))
@@ -16975,6 +18640,7 @@ instantiate_decl (tree d, int defer_ok,
   if (TREE_CODE (d) == VAR_DECL)
     {
       tree init;
+      bool const_init = false;
 
       /* Clear out DECL_RTL; whatever was there before may not be right
         since we've reset the type of the declaration.  */
@@ -16982,7 +18648,8 @@ instantiate_decl (tree d, int defer_ok,
       DECL_IN_AGGR_P (d) = 0;
 
       /* The initializer is placed in DECL_INITIAL by
-        regenerate_decl_from_template.  Pull it out so that
+        regenerate_decl_from_template so we don't need to
+        push/pop_access_scope again here.  Pull it out so that
         cp_finish_decl can process it.  */
       init = DECL_INITIAL (d);
       DECL_INITIAL (d) = NULL_TREE;
@@ -16995,9 +18662,12 @@ instantiate_decl (tree d, int defer_ok,
 
       /* Enter the scope of D so that access-checking works correctly.  */
       push_nested_class (DECL_CONTEXT (d));
-      cp_finish_decl (d, init, false, NULL_TREE, 0);
+      const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
+      cp_finish_decl (d, init, const_init, NULL_TREE, 0);
       pop_nested_class ();
     }
+  else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
+    synthesize_method (d);
   else if (TREE_CODE (d) == FUNCTION_DECL)
     {
       htab_t saved_local_specializations;
@@ -17028,21 +18698,21 @@ instantiate_decl (tree d, int defer_ok,
          spec_parm = skip_artificial_parms_for (d, spec_parm);
          tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
        }
-      while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
+      for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
        {
-         register_local_specialization (spec_parm, tmpl_parm);
-         tmpl_parm = DECL_CHAIN (tmpl_parm);
-         spec_parm = DECL_CHAIN (spec_parm);
+         if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
+           {
+             register_local_specialization (spec_parm, tmpl_parm);
+             spec_parm = DECL_CHAIN (spec_parm);
+           }
+         else
+           {
+             /* Register the (value) argument pack as a specialization of
+                TMPL_PARM, then move on.  */
+             tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
+             register_local_specialization (argpack, tmpl_parm);
+           }
        }
-      if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
-        {
-          /* Register the (value) argument pack as a specialization of
-             TMPL_PARM, then move on.  */
-         tree argpack = make_fnparm_pack (spec_parm);
-          register_local_specialization (argpack, tmpl_parm);
-          tmpl_parm = DECL_CHAIN (tmpl_parm);
-         spec_parm = NULL_TREE;
-        }
       gcc_assert (!spec_parm);
 
       /* Substitute into the body of the function.  */
@@ -17074,7 +18744,7 @@ out:
   pop_deferring_access_checks ();
   pop_tinst_level ();
 
-  timevar_pop (TV_PARSE);
+  timevar_pop (TV_TEMPLATE_INST);
 
   return d;
 }
@@ -17385,7 +19055,7 @@ get_mostly_instantiated_function_type (tree decl)
     ;
   else
     {
-      int i, save_access_control;
+      int i;
       tree partial_args;
 
       /* Replace the innermost level of the TARGS with NULL_TREEs to
@@ -17398,10 +19068,9 @@ get_mostly_instantiated_function_type (tree decl)
                           TMPL_ARGS_DEPTH (targs),
                           make_tree_vec (DECL_NTPARMS (tmpl)));
 
-      /* Disable access control as this function is used only during
-        name-mangling.  */
-      save_access_control = flag_access_control;
-      flag_access_control = 0;
+      /* Make sure that we can see identifiers, and compute access
+        correctly.  */
+      push_access_scope (decl);
 
       ++processing_template_decl;
       /* Now, do the (partial) substitution to figure out the
@@ -17416,7 +19085,7 @@ get_mostly_instantiated_function_type (tree decl)
       TREE_VEC_LENGTH (partial_args)--;
       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
 
-      flag_access_control = save_access_control;
+      pop_access_scope (decl);
     }
 
   return fn_type;
@@ -17427,14 +19096,14 @@ get_mostly_instantiated_function_type (tree decl)
 int
 problematic_instantiation_changed (void)
 {
-  return last_template_error_tick != tinst_level_tick;
+  return current_tinst_level != last_error_tinst_level;
 }
 
 /* Remember current template involved in diagnostics.  */
 void
 record_last_problematic_instantiation (void)
 {
-  last_template_error_tick = tinst_level_tick;
+  last_error_tinst_level = current_tinst_level;
 }
 
 struct tinst_level *
@@ -17460,9 +19129,19 @@ invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
     return 0;
   else if (TREE_CODE (type) == TYPENAME_TYPE)
     return 0;
+  else if (TREE_CODE (type) == DECLTYPE_TYPE)
+    return 0;
+  else if (TREE_CODE (type) == NULLPTR_TYPE)
+    return 0;
 
   if (complain & tf_error)
-    error ("%q#T is not a valid type for a template constant parameter", type);
+    {
+      if (type == error_mark_node)
+       inform (input_location, "invalid template non-type parameter");
+      else
+       error ("%q#T is not a valid type for a template non-type parameter",
+              type);
+    }
   return 1;
 }
 
@@ -17539,11 +19218,12 @@ dependent_type_p_r (tree type)
               (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
     return true;
 
-  /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
-     argument of the `typeof' expression is not type-dependent, then
-     it should already been have resolved.  */
+  /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
+     dependent; if the argument of the `typeof' expression is not
+     type-dependent, then it should already been have resolved.  */
   if (TREE_CODE (type) == TYPEOF_TYPE
-      || TREE_CODE (type) == DECLTYPE_TYPE)
+      || TREE_CODE (type) == DECLTYPE_TYPE
+      || TREE_CODE (type) == UNDERLYING_TYPE)
     return true;
 
   /* A template argument pack is dependent if any of its packed
@@ -17576,15 +19256,22 @@ dependent_type_p_r (tree type)
   scope = TYPE_CONTEXT (type);
   if (scope && TYPE_P (scope))
     return dependent_type_p (scope);
-  else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
-    return type_dependent_expression_p (scope);
+  /* Don't use type_dependent_expression_p here, as it can lead
+     to infinite recursion trying to determine whether a lambda
+     nested in a lambda is dependent (c++/47687).  */
+  else if (scope && TREE_CODE (scope) == FUNCTION_DECL
+          && DECL_LANG_SPECIFIC (scope)
+          && DECL_TEMPLATE_INFO (scope)
+          && (any_dependent_template_arguments_p
+              (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
+    return true;
 
   /* Other types are non-dependent.  */
   return false;
 }
 
 /* Returns TRUE if TYPE is dependent, in the sense of
-   [temp.dep.type].  */
+   [temp.dep.type].  Note that a NULL type is considered dependent.  */
 
 bool
 dependent_type_p (tree type)
@@ -17635,6 +19322,23 @@ dependent_scope_p (tree scope)
    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
    expression.  */
 
+/* Note that this predicate is not appropriate for general expressions;
+   only constant expressions (that satisfy potential_constant_expression)
+   can be tested for value dependence.
+
+   We should really also have a predicate for "instantiation-dependent".
+
+   fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
+     (what about instantiation-dependent constant-expressions?)
+   is_late_template_attribute: defer if instantiation-dependent.
+   compute_array_index_type: proceed if constant and not t- or v-dependent
+     if instantiation-dependent, need to remember full expression
+   uses_template_parms: FIXME - need to audit callers
+   tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
+   dependent_type_p [array_type]: dependent if index type is dependent
+     (or non-constant?)
+   static_assert - instantiation-dependent */
+
 bool
 value_dependent_expression_p (tree expression)
 {
@@ -17662,10 +19366,10 @@ value_dependent_expression_p (tree expression)
       return value_dependent_expression_p (DECL_INITIAL (expression));
 
     case VAR_DECL:
-       /* A constant with integral or enumeration type and is initialized
+       /* A constant with literal type and is initialized
          with an expression that is value-dependent.  */
       if (DECL_INITIAL (expression)
-         && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
+         && decl_constant_var_p (expression)
          && value_dependent_expression_p (DECL_INITIAL (expression)))
        return true;
       return false;
@@ -17691,7 +19395,8 @@ value_dependent_expression_p (tree expression)
            /* If there are no operands, it must be an expression such
               as "int()". This should not happen for aggregate types
               because it would form non-constant expressions.  */
-           gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
+           gcc_assert (cxx_dialect >= cxx0x
+                       || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
 
            return false;
          }
@@ -17704,6 +19409,7 @@ value_dependent_expression_p (tree expression)
 
     case SIZEOF_EXPR:
     case ALIGNOF_EXPR:
+    case TYPEID_EXPR:
       /* A `sizeof' expression is value-dependent if the operand is
         type-dependent or is a pack expansion.  */
       expression = TREE_OPERAND (expression, 0);
@@ -17721,9 +19427,7 @@ value_dependent_expression_p (tree expression)
 
     case NOEXCEPT_EXPR:
       expression = TREE_OPERAND (expression, 0);
-      /* FIXME why check value-dependency?  */
-      return (type_dependent_expression_p (expression)
-             || value_dependent_expression_p (expression));
+      return type_dependent_expression_p (expression);
 
     case SCOPE_REF:
       {
@@ -17735,12 +19439,6 @@ value_dependent_expression_p (tree expression)
       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
              || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
 
-    case CALL_EXPR:
-      /* A CALL_EXPR may appear in a constant expression if it is a
-        call to a builtin function, e.g., __builtin_constant_p.  All
-        such calls are value-dependent.  */
-      return true;
-
     case NONTYPE_ARGUMENT_PACK:
       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
          is value-dependent.  */
@@ -17766,6 +19464,10 @@ value_dependent_expression_p (tree expression)
       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
              || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
 
+    case ARRAY_REF:
+      return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
+             || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
+
     case ADDR_EXPR:
       {
        tree op = TREE_OPERAND (expression, 0);
@@ -17773,6 +19475,45 @@ value_dependent_expression_p (tree expression)
                || has_value_dependent_address (op));
       }
 
+    case CALL_EXPR:
+      {
+       tree fn = get_callee_fndecl (expression);
+       int i, nargs;
+       if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
+         return true;
+       nargs = call_expr_nargs (expression);
+       for (i = 0; i < nargs; ++i)
+         {
+           tree op = CALL_EXPR_ARG (expression, i);
+           /* In a call to a constexpr member function, look through the
+              implicit ADDR_EXPR on the object argument so that it doesn't
+              cause the call to be considered value-dependent.  We also
+              look through it in potential_constant_expression.  */
+           if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
+               && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
+               && TREE_CODE (op) == ADDR_EXPR)
+             op = TREE_OPERAND (op, 0);
+           if (value_dependent_expression_p (op))
+             return true;
+         }
+       return false;
+      }
+
+    case TEMPLATE_ID_EXPR:
+      /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
+        type-dependent.  */
+      return type_dependent_expression_p (expression);
+
+    case CONSTRUCTOR:
+      {
+       unsigned ix;
+       tree val;
+       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
+         if (value_dependent_expression_p (val))
+           return true;
+       return false;
+      }
+
     default:
       /* A constant expression is value-dependent if any subexpression is
         value-dependent.  */
@@ -17780,35 +19521,30 @@ value_dependent_expression_p (tree expression)
        {
        case tcc_reference:
        case tcc_unary:
-         return (value_dependent_expression_p
-                 (TREE_OPERAND (expression, 0)));
-
        case tcc_comparison:
        case tcc_binary:
-         return ((value_dependent_expression_p
-                  (TREE_OPERAND (expression, 0)))
-                 || (value_dependent_expression_p
-                     (TREE_OPERAND (expression, 1))));
-
        case tcc_expression:
        case tcc_vl_exp:
          {
-           int i;
-           for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
-             /* In some cases, some of the operands may be missing.
-                (For example, in the case of PREDECREMENT_EXPR, the
-                amount to increment by may be missing.)  That doesn't
-                make the expression dependent.  */
-             if (TREE_OPERAND (expression, i)
-                 && (value_dependent_expression_p
-                     (TREE_OPERAND (expression, i))))
-               return true;
-           return false;
-         }
+           int i, len = cp_tree_operand_length (expression);
 
+           for (i = 0; i < len; i++)
+             {
+               tree t = TREE_OPERAND (expression, i);
+
+               /* In some cases, some of the operands may be missing.l
+                  (For example, in the case of PREDECREMENT_EXPR, the
+                  amount to increment by may be missing.)  That doesn't
+                  make the expression dependent.  */
+               if (t && value_dependent_expression_p (t))
+                 return true;
+             }
+         }
+         break;
        default:
          break;
        }
+      break;
     }
 
   /* The expression is not value-dependent.  */
@@ -17816,7 +19552,10 @@ value_dependent_expression_p (tree expression)
 }
 
 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
-   [temp.dep.expr].  */
+   [temp.dep.expr].  Note that an expression with no type is
+   considered dependent.  Other parts of the compiler arrange for an
+   expression with type-dependent subexpressions to have no type, so
+   this function doesn't have to be fully recursive.  */
 
 bool
 type_dependent_expression_p (tree expression)
@@ -17851,6 +19590,7 @@ type_dependent_expression_p (tree expression)
       || TREE_CODE (expression) == STATIC_CAST_EXPR
       || TREE_CODE (expression) == CONST_CAST_EXPR
       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
+      || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
       || TREE_CODE (expression) == CAST_EXPR)
     return dependent_type_p (TREE_TYPE (expression));
 
@@ -17940,7 +19680,7 @@ type_dependent_expression_p (tree expression)
       if (TREE_CODE (expression) == SCOPE_REF)
        return false;
 
-      if (TREE_CODE (expression) == BASELINK)
+      if (BASELINK_P (expression))
        expression = BASELINK_FUNCTIONS (expression);
 
       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
@@ -17997,6 +19737,19 @@ any_type_dependent_arguments_p (const VEC(tree,gc) *args)
 }
 
 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
+   expressions) contains any type-dependent expressions.  */
+
+bool
+any_type_dependent_elements_p (const_tree list)
+{
+  for (; list; list = TREE_CHAIN (list))
+    if (value_dependent_expression_p (TREE_VALUE (list)))
+      return true;
+
+  return false;
+}
+
+/* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
    expressions) contains any value-dependent expressions.  */
 
 bool
@@ -18017,6 +19770,16 @@ dependent_template_arg_p (tree arg)
   if (!processing_template_decl)
     return false;
 
+  /* Assume a template argument that was wrongly written by the user
+     is dependent. This is consistent with what
+     any_dependent_template_arguments_p [that calls this function]
+     does.  */
+  if (!arg || arg == error_mark_node)
+    return true;
+
+  if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
+    arg = ARGUMENT_PACK_SELECT_ARG (arg);
+
   if (TREE_CODE (arg) == TEMPLATE_DECL
       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
     return dependent_template_p (arg);
@@ -18125,9 +19888,9 @@ dependent_template_p (tree tmpl)
     {
       while (tmpl)
        {
-         if (dependent_template_p (OVL_FUNCTION (tmpl)))
+         if (dependent_template_p (OVL_CURRENT (tmpl)))
            return true;
-         tmpl = OVL_CHAIN (tmpl);
+         tmpl = OVL_NEXT (tmpl);
        }
       return false;
     }
@@ -18277,7 +20040,8 @@ resolve_typename_type (tree type, bool only_current_p)
      longer be considered a dependent type.  */
   pushed_scope = push_scope (scope);
   /* Look up the declaration.  */
-  decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
+  decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
+                       tf_warning_or_error);
 
   result = NULL_TREE;
   
@@ -18343,10 +20107,13 @@ build_non_dependent_expr (tree expr)
 {
   tree inner_expr;
 
-  /* Preserve null pointer constants so that the type of things like
-     "p == 0" where "p" is a pointer can be determined.  */
-  if (null_ptr_cst_p (expr))
-    return expr;
+#ifdef ENABLE_CHECKING
+  /* Try to get a constant value for all non-type-dependent expressions in
+      order to expose bugs in *_dependent_expression_p and constexpr.  */
+  if (cxx_dialect >= cxx0x)
+    maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
+#endif
+
   /* Preserve OVERLOADs; the functions must be available to resolve
      types.  */
   inner_expr = expr;
@@ -18379,6 +20146,10 @@ build_non_dependent_expr (tree expr)
   if (TREE_CODE (expr) == THROW_EXPR)
     return expr;
 
+  /* Don't wrap an initializer list, we need to be able to look inside.  */
+  if (BRACE_ENCLOSED_INITIALIZER_P (expr))
+    return expr;
+
   if (TREE_CODE (expr) == COND_EXPR)
     return build3 (COND_EXPR,
                   TREE_TYPE (expr),
@@ -18397,21 +20168,8 @@ build_non_dependent_expr (tree expr)
   /* If the type is unknown, it can't really be non-dependent */
   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
 
-  /* Otherwise, build a NON_DEPENDENT_EXPR.
-
-     REFERENCE_TYPEs are not stripped for expressions in templates
-     because doing so would play havoc with mangling.  Consider, for
-     example:
-
-       template <typename T> void f<T& g>() { g(); }
-
-     In the body of "f", the expression for "g" will have
-     REFERENCE_TYPE, even though the standard says that it should
-     not.  The reason is that we must preserve the syntactic form of
-     the expression so that mangling (say) "f<g>" inside the body of
-     "f" works out correctly.  Therefore, the REFERENCE_TYPE is
-     stripped here.  */
-  return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
+  /* Otherwise, build a NON_DEPENDENT_EXPR.  */
+  return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
 }
 
 /* ARGS is a vector of expressions as arguments to a function call.
@@ -18444,7 +20202,7 @@ make_auto (void)
   TYPE_STUB_DECL (au) = TYPE_NAME (au);
   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
     (0, processing_template_decl + 1, processing_template_decl + 1,
-     TYPE_NAME (au), NULL_TREE);
+     0, TYPE_NAME (au), NULL_TREE);
   TYPE_CANONICAL (au) = canonical_type_parameter (au);
   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
@@ -18510,6 +20268,12 @@ do_auto_deduction (tree type, tree init, tree auto_node)
   tree decl;
   int val;
 
+  if (processing_template_decl
+      && (TREE_TYPE (init) == NULL_TREE
+         || BRACE_ENCLOSED_INITIALIZER_P (init)))
+    /* Not enough information to try this yet.  */
+    return type;
+
   /* The name of the object being declared shall not appear in the
      initializer expression.  */
   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
@@ -18527,6 +20291,8 @@ do_auto_deduction (tree type, tree init, tree auto_node)
   if (BRACE_ENCLOSED_INITIALIZER_P (init))
     type = listify_autos (type, auto_node);
 
+  init = resolve_nondeduced_context (init);
+
   parms = build_tree_list (NULL_TREE, type);
   args[0] = init;
   tparms = make_tree_vec (1);
@@ -18534,10 +20300,18 @@ do_auto_deduction (tree type, tree init, tree auto_node)
   TREE_VEC_ELT (tparms, 0)
     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
   val = type_unification_real (tparms, targs, parms, args, 1, 0,
-                              DEDUCE_CALL, LOOKUP_NORMAL);
+                              DEDUCE_CALL, LOOKUP_NORMAL,
+                              /*explain_p=*/false);
   if (val > 0)
     {
-      error ("unable to deduce %qT from %qE", type, init);
+      if (processing_template_decl)
+       /* Try again at instantiation time.  */
+       return type;
+      if (type && type != error_mark_node)
+       /* If type is error_mark_node a diagnostic must have been
+          emitted by now.  Also, having a mention to '<type error>'
+          in the diagnostic is not really useful to the user.  */
+       error ("unable to deduce %qT from %qE", type, init);
       return error_mark_node;
     }
 
@@ -18571,7 +20345,12 @@ splice_late_return_type (tree type, tree late_return_type)
     return type;
   argvec = make_tree_vec (1);
   TREE_VEC_ELT (argvec, 0) = late_return_type;
-  if (processing_template_decl)
+  if (processing_template_parmlist)
+    /* For a late-specified return type in a template type-parameter, we
+       need to add a dummy argument level for its parmlist.  */
+    argvec = add_to_template_args
+      (make_tree_vec (processing_template_parmlist), argvec);
+  if (current_template_parms)
     argvec = add_to_template_args (current_template_args (), argvec);
   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
 }