Wunused-parameter warnings are given from cgraph::finalize_function,
[gcc.git] / gcc / ipa-devirt.c
index 0a11eb72085fd7c1f02564fb9340381f9c38adc8..905776e0a0cbbcfe29488063d0b5d70c12a77825 100644 (file)
@@ -1,6 +1,6 @@
 /* Basic IPA utilities for type inheritance graph construction and
    devirtualization.
-   Copyright (C) 2013-2014 Free Software Foundation, Inc.
+   Copyright (C) 2013-2015 Free Software Foundation, Inc.
    Contributed by Jan Hubicka
 
 This file is part of GCC.
@@ -19,7 +19,7 @@ You should have received a copy of the GNU General Public License
 along with GCC; see the file COPYING3.  If not see
 <http://www.gnu.org/licenses/>.  */
 
-/* Brief vocalburary:
+/* Brief vocabulary:
      ODR = One Definition Rule
         In short, the ODR states that:
        1 In any translation unit, a template, type, function, or object can
@@ -44,7 +44,7 @@ along with GCC; see the file COPYING3.  If not see
 
      BINFO
        This is the type inheritance information attached to each tree
-       RECORD_TYPE by the C++ frotend.  It provides information about base
+       RECORD_TYPE by the C++ frontend.  It provides information about base
        types and virtual tables.
 
        BINFO is linked to the RECORD_TYPE by TYPE_BINFO.
@@ -61,7 +61,7 @@ along with GCC; see the file COPYING3.  If not see
        In the case of single inheritance, the virtual table is shared
        and BINFO_VTABLE of base BINFO is NULL.  In the case of multiple
        inheritance the individual virtual tables are pointer to by
-       BINFO_VTABLE of base binfos (that differs of BINFO_VTABLE of 
+       BINFO_VTABLE of base binfos (that differs of BINFO_VTABLE of
        binfo associated to the base type).
 
        BINFO lookup for a given base type and offset can be done by
@@ -75,7 +75,7 @@ along with GCC; see the file COPYING3.  If not see
        or from DECL_VINDEX of a given virtual table.
 
      polymorphic (indirect) call
-       This is callgraph represention of virtual method call.  Every
+       This is callgraph representation of virtual method call.  Every
        polymorphic call contains otr_type and otr_token taken from
        original OBJ_TYPE_REF at callgraph construction time.
 
@@ -88,7 +88,7 @@ along with GCC; see the file COPYING3.  If not see
      This means that the graph is not complete. Types with no methods are not
      inserted into the graph.  Also types without virtual methods are not
      represented at all, though it may be easy to add this.
-  
      The inheritance graph is represented as follows:
 
        Vertices are structures odr_type.  Every odr_type may correspond
@@ -109,16 +109,29 @@ along with GCC; see the file COPYING3.  If not see
 #include "system.h"
 #include "coretypes.h"
 #include "tm.h"
+#include "alias.h"
+#include "symtab.h"
 #include "tree.h"
+#include "fold-const.h"
 #include "print-tree.h"
 #include "calls.h"
+#include "predict.h"
+#include "basic-block.h"
+#include "hard-reg-set.h"
+#include "function.h"
 #include "cgraph.h"
+#include "rtl.h"
+#include "flags.h"
+#include "insn-config.h"
+#include "expmed.h"
+#include "dojump.h"
+#include "explow.h"
+#include "emit-rtl.h"
+#include "varasm.h"
+#include "stmt.h"
 #include "expr.h"
 #include "tree-pass.h"
-#include "hash-set.h"
 #include "target.h"
-#include "hash-table.h"
-#include "inchash.h"
 #include "tree-pretty-print.h"
 #include "ipa-utils.h"
 #include "tree-ssa-alias.h"
@@ -126,6 +139,9 @@ along with GCC; see the file COPYING3.  If not see
 #include "gimple-fold.h"
 #include "gimple-expr.h"
 #include "gimple.h"
+#include "alloc-pool.h"
+#include "symbol-summary.h"
+#include "ipa-prop.h"
 #include "ipa-inline.h"
 #include "diagnostic.h"
 #include "tree-dfa.h"
@@ -134,7 +150,8 @@ along with GCC; see the file COPYING3.  If not see
 #include "gimple-pretty-print.h"
 #include "stor-layout.h"
 #include "intl.h"
-#include "hash-map.h"
+#include "streamer-hooks.h"
+#include "lto-streamer.h"
 
 /* Hash based set of pairs of types.  */
 typedef struct
@@ -143,8 +160,11 @@ typedef struct
   tree second;
 } type_pair;
 
-struct pair_traits : default_hashset_traits
+template <>
+struct default_hash_traits <type_pair> : typed_noop_remove <type_pair>
 {
+  typedef type_pair value_type;
+  typedef type_pair compare_type;
   static hashval_t
   hash (type_pair p)
   {
@@ -173,7 +193,8 @@ struct pair_traits : default_hashset_traits
 };
 
 static bool odr_types_equivalent_p (tree, tree, bool, bool *,
-                                   hash_set<type_pair,pair_traits> *);
+                                   hash_set<type_pair> *,
+                                   location_t, location_t);
 
 static bool odr_violation_reported = false;
 
@@ -182,17 +203,17 @@ static bool odr_violation_reported = false;
 static hash_set<cgraph_node *> *cached_polymorphic_call_targets;
 
 /* The node of type inheritance graph.  For each type unique in
-   One Defintion Rule (ODR) sense, we produce one node linking all 
+   One Definition Rule (ODR) sense, we produce one node linking all
    main variants of types equivalent to it, bases and derived types.  */
 
 struct GTY(()) odr_type_d
 {
   /* leader type.  */
   tree type;
-  /* All bases; built only for main variants of types  */
+  /* All bases; built only for main variants of types.  */
   vec<odr_type> GTY((skip)) bases;
-  /* All derrived types with virtual methods seen in unit;
-     built only for main variants oftypes  */
+  /* All derived types with virtual methods seen in unit;
+     built only for main variants of types.  */
   vec<odr_type> GTY((skip)) derived_types;
 
   /* All equivalent types, if more than one.  */
@@ -208,24 +229,98 @@ struct GTY(()) odr_type_d
   bool all_derivations_known;
   /* Did we report ODR violation here?  */
   bool odr_violated;
+  /* Set when virtual table without RTTI previaled table with.  */
+  bool rtti_broken;
 };
 
-static bool contains_type_p (tree, HOST_WIDE_INT, tree);
+/* Return true if T is a type with linkage defined.  */
+
+bool
+type_with_linkage_p (const_tree t)
+{
+  /* Builtin types do not define linkage, their TYPE_CONTEXT is NULL.  */
+  if (!TYPE_CONTEXT (t)
+      || !TYPE_NAME (t) || TREE_CODE (TYPE_NAME (t)) != TYPE_DECL
+      || !TYPE_STUB_DECL (t))
+    return false;
+
+  /* In LTO do not get confused by non-C++ produced types or types built
+     with -fno-lto-odr-type-merigng.  */
+  if (in_lto_p)
+    {
+      /* To support -fno-lto-odr-type-merigng recognize types with vtables
+         to have linkage.  */
+      if (RECORD_OR_UNION_TYPE_P (t)
+         && TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)))
+        return true;
+      /* Do not accept any other types - we do not know if they were produced
+         by C++ FE.  */
+      if (!DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t)))
+        return false;
+    }
+
+  return (RECORD_OR_UNION_TYPE_P (t)
+         || TREE_CODE (t) == ENUMERAL_TYPE);
+}
+
+/* Return true if T is in anonymous namespace.
+   This works only on those C++ types with linkage defined.  */
+
+bool
+type_in_anonymous_namespace_p (const_tree t)
+{
+  gcc_assert (type_with_linkage_p (t));
 
+  /* Keep -fno-lto-odr-type-merging working by recognizing classes with vtables
+     properly into anonymous namespaces.  */
+  if (RECORD_OR_UNION_TYPE_P (t)
+      && TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)))
+    return (TYPE_STUB_DECL (t) && !TREE_PUBLIC (TYPE_STUB_DECL (t)));
 
-/* Return true if BINFO corresponds to a type with virtual methods. 
+  if (TYPE_STUB_DECL (t) && !TREE_PUBLIC (TYPE_STUB_DECL (t)))
+    {
+      /* C++ FE uses magic <anon> as assembler names of anonymous types.
+        verify that this match with type_in_anonymous_namespace_p.  */
+#ifdef ENABLE_CHECKING
+      if (in_lto_p)
+       gcc_assert (!strcmp ("<anon>",
+                   IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (TYPE_NAME (t)))));
+#endif
+      return true;
+    }
+  return false;
+}
 
-   Every type has several BINFOs.  One is the BINFO associated by the type
-   while other represents bases of derived types.  The BINFOs representing
-   bases do not have BINFO_VTABLE pointer set when this is the single
-   inheritance (because vtables are shared).  Look up the BINFO of type
-   and check presence of its vtable.  */
+/* Return true of T is type with One Definition Rule info attached. 
+   It means that either it is anonymous type or it has assembler name
+   set.  */
 
-static inline bool
-polymorphic_type_binfo_p (tree binfo)
+bool
+odr_type_p (const_tree t)
 {
-  /* See if BINFO's type has an virtual table associtated with it.  */
-  return BINFO_VTABLE (TYPE_BINFO (BINFO_TYPE (binfo)));
+  /* We do not have this information when not in LTO, but we do not need
+     to care, since it is used only for type merging.  */
+  gcc_checking_assert (in_lto_p || flag_lto);
+
+  /* To support -fno-lto-odr-type-merging consider types with vtables ODR.  */
+  if (type_with_linkage_p (t) && type_in_anonymous_namespace_p (t))
+    return true;
+
+  if (TYPE_NAME (t) && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL
+      && (DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t))))
+    {
+#ifdef ENABLE_CHECKING
+      /* C++ FE uses magic <anon> as assembler names of anonymous types.
+        verify that this match with type_in_anonymous_namespace_p.  */
+      gcc_assert (!type_with_linkage_p (t)
+                 || strcmp ("<anon>",
+                            IDENTIFIER_POINTER
+                               (DECL_ASSEMBLER_NAME (TYPE_NAME (t))))
+                 || type_in_anonymous_namespace_p (t));
+#endif
+      return true;
+    }
+  return false;
 }
 
 /* Return TRUE if all derived types of T are known and thus
@@ -235,19 +330,22 @@ polymorphic_type_binfo_p (tree binfo)
    defined within functions (that may be COMDAT and thus shared across units,
    but with the same set of derived types).  */
 
-static bool
-type_all_derivations_known_p (tree t)
+bool
+type_all_derivations_known_p (const_tree t)
 {
   if (TYPE_FINAL_P (t))
     return true;
   if (flag_ltrans)
     return false;
+  /* Non-C++ types may have IDENTIFIER_NODE here, do not crash.  */
+  if (!TYPE_NAME (t) || TREE_CODE (TYPE_NAME (t)) != TYPE_DECL)
+    return true;
   if (type_in_anonymous_namespace_p (t))
     return true;
   return (decl_function_context (TYPE_NAME (t)) != NULL);
 }
 
-/* Return TURE if type's constructors are all visible.  */
+/* Return TRUE if type's constructors are all visible.  */
 
 static bool
 type_all_ctors_visible_p (tree t)
@@ -256,7 +354,7 @@ type_all_ctors_visible_p (tree t)
         && symtab->state >= CONSTRUCTION
         /* We can not always use type_all_derivations_known_p.
            For function local types we must assume case where
-           the function is COMDAT and shared in between units. 
+           the function is COMDAT and shared in between units.
 
            TODO: These cases are quite easy to get, but we need
            to keep track of C++ privatizing via -Wno-weak
@@ -283,15 +381,25 @@ type_possibly_instantiated_p (tree t)
   return vnode && vnode->definition;
 }
 
-/* One Definition Rule hashtable helpers.  */
+/* Hash used to unify ODR types based on their mangled name and for anonymous
+   namespace types.  */
+
+struct odr_name_hasher : pointer_hash <odr_type_d>
+{
+  typedef union tree_node *compare_type;
+  static inline hashval_t hash (const odr_type_d *);
+  static inline bool equal (const odr_type_d *, const tree_node *);
+  static inline void remove (odr_type_d *);
+};
+
+/* Has used to unify ODR types based on their associated virtual table.
+   This hash is needed to keep -fno-lto-odr-type-merging to work and contains
+   only polymorphic types.  Types with mangled names are inserted to both.  */
 
-struct odr_hasher 
+struct odr_vtable_hasher:odr_name_hasher
 {
-  typedef odr_type_d value_type;
-  typedef union tree_node compare_type;
-  static inline hashval_t hash (const value_type *);
-  static inline bool equal (const value_type *, const compare_type *);
-  static inline void remove (value_type *);
+  static inline hashval_t hash (const odr_type_d *);
+  static inline bool equal (const odr_type_d *, const tree_node *);
 };
 
 /* Return type that was declared with T's name so that T is an
@@ -307,10 +415,16 @@ main_odr_variant (const_tree t)
     return TYPE_MAIN_VARIANT (t);
 }
 
-/* Produce hash based on type name.  */
+static bool
+can_be_name_hashed_p (tree t)
+{
+  return (!in_lto_p || odr_type_p (t));
+}
+
+/* Hash type by its ODR name.  */
 
 static hashval_t
-hash_type_name (tree t)
+hash_odr_name (const_tree t)
 {
   gcc_checking_assert (main_odr_variant (t) == t);
 
@@ -320,68 +434,94 @@ hash_type_name (tree t)
     return htab_hash_pointer (t);
 
   /* Anonymous types are unique.  */
-  if (type_in_anonymous_namespace_p (t))
+  if (type_with_linkage_p (t) && type_in_anonymous_namespace_p (t))
     return htab_hash_pointer (t);
 
-  /* ODR types have name specified.  */
-  if (TYPE_NAME (t)
-      && DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t)))
-    return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME (TYPE_NAME (t)));
+  gcc_checking_assert (TYPE_NAME (t)
+                      && DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t)));
+  return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME (TYPE_NAME (t)));
+}
 
-  /* For polymorphic types that was compiled with -fno-lto-odr-type-merging
-     we can simply hash the virtual table.  */
-  if (TREE_CODE (t) == RECORD_TYPE
-      && TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)))
-    {
-      tree v = BINFO_VTABLE (TYPE_BINFO (t));
-      hashval_t hash = 0;
+/* Return the computed hashcode for ODR_TYPE.  */
 
-      if (TREE_CODE (v) == POINTER_PLUS_EXPR)
-       {
-         hash = TREE_INT_CST_LOW (TREE_OPERAND (v, 1));
-         v = TREE_OPERAND (TREE_OPERAND (v, 0), 0);
-       }
+inline hashval_t
+odr_name_hasher::hash (const odr_type_d *odr_type)
+{
+  return hash_odr_name (odr_type->type);
+}
+
+static bool
+can_be_vtable_hashed_p (tree t)
+{
+  /* vtable hashing can distinguish only main variants.  */
+  if (TYPE_MAIN_VARIANT (t) != t)
+    return false;
+  /* Anonymous namespace types are always handled by name hash.  */
+  if (type_with_linkage_p (t) && type_in_anonymous_namespace_p (t))
+    return false;
+  return (TREE_CODE (t) == RECORD_TYPE
+         && TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)));
+}
+
+/* Hash type by assembler name of its vtable.  */
+
+static hashval_t
+hash_odr_vtable (const_tree t)
+{
+  tree v = BINFO_VTABLE (TYPE_BINFO (TYPE_MAIN_VARIANT (t)));
+  inchash::hash hstate;
+
+  gcc_checking_assert (in_lto_p);
+  gcc_checking_assert (!type_in_anonymous_namespace_p (t));
+  gcc_checking_assert (TREE_CODE (t) == RECORD_TYPE
+                      && TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)));
+  gcc_checking_assert (main_odr_variant (t) == t);
 
-      v = DECL_ASSEMBLER_NAME (v);
-      hash = iterative_hash_hashval_t (hash, htab_hash_pointer (v));
-      return hash;
+  if (TREE_CODE (v) == POINTER_PLUS_EXPR)
+    {
+      add_expr (TREE_OPERAND (v, 1), hstate);
+      v = TREE_OPERAND (TREE_OPERAND (v, 0), 0);
     }
 
-  /* Builtin types may appear as main variants of ODR types and are unique.
-     Sanity check we do not get anything that looks non-builtin.  */
-  gcc_checking_assert (TREE_CODE (t) == INTEGER_TYPE
-                      || TREE_CODE (t) == VOID_TYPE
-                      || TREE_CODE (t) == COMPLEX_TYPE
-                      || TREE_CODE (t) == REAL_TYPE
-                      || TREE_CODE (t) == POINTER_TYPE);
-  return htab_hash_pointer (t);
+  hstate.add_wide_int (IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME (v)));
+  return hstate.end ();
 }
 
 /* Return the computed hashcode for ODR_TYPE.  */
 
 inline hashval_t
-odr_hasher::hash (const value_type *odr_type)
+odr_vtable_hasher::hash (const odr_type_d *odr_type)
 {
-  return hash_type_name (odr_type->type);
+  return hash_odr_vtable (odr_type->type);
 }
 
 /* For languages with One Definition Rule, work out if
    types are the same based on their name.
-   This is non-trivial for LTO where minnor differences in
+
+   This is non-trivial for LTO where minor differences in
    the type representation may have prevented type merging
    to merge two copies of otherwise equivalent type.
 
    Until we start streaming mangled type names, this function works
-   only for polymorphic types.  */
+   only for polymorphic types.
+
+   When STRICT is true, we compare types by their names for purposes of
+   ODR violation warnings.  When strict is false, we consider variants
+   equivalent, becuase it is all that matters for devirtualization machinery.
+*/
 
 bool
-types_same_for_odr (const_tree type1, const_tree type2)
+types_same_for_odr (const_tree type1, const_tree type2, bool strict)
 {
   gcc_checking_assert (TYPE_P (type1) && TYPE_P (type2));
 
   type1 = main_odr_variant (type1);
   type2 = main_odr_variant (type2);
+  if (!strict)
+    {
+      type1 = TYPE_MAIN_VARIANT (type1);
+      type2 = TYPE_MAIN_VARIANT (type2);
+    }
 
   if (type1 == type2)
     return true;
@@ -391,14 +531,14 @@ types_same_for_odr (const_tree type1, const_tree type2)
 
   /* Check for anonymous namespaces. Those have !TREE_PUBLIC
      on the corresponding TYPE_STUB_DECL.  */
-  if (type_in_anonymous_namespace_p (type1)
-      || type_in_anonymous_namespace_p (type2))
+  if ((type_with_linkage_p (type1) && type_in_anonymous_namespace_p (type1))
+      || (type_with_linkage_p (type2) && type_in_anonymous_namespace_p (type2)))
     return false;
 
 
   /* ODR name of the type is set in DECL_ASSEMBLER_NAME of its TYPE_NAME.
 
-     Ideally we should never meed types without ODR names here.  It can however
+     Ideally we should never need types without ODR names here.  It can however
      happen in two cases:
 
        1) for builtin types that are not streamed but rebuilt in lto/lto-lang.c
@@ -411,22 +551,23 @@ types_same_for_odr (const_tree type1, const_tree type2)
   if ((!TYPE_NAME (type1) || !DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (type1)))
       || (!TYPE_NAME (type2) || !DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (type2))))
     {
-      /* See if types are obvoiusly different (i.e. different codes
-        or polymorphis wrt non-polymorphic).  This is not strictly correct
+      /* See if types are obviously different (i.e. different codes
+        or polymorphic wrt non-polymorphic).  This is not strictly correct
         for ODR violating programs, but we can't do better without streaming
         ODR names.  */
       if (TREE_CODE (type1) != TREE_CODE (type2))
        return false;
       if (TREE_CODE (type1) == RECORD_TYPE
-         && (TYPE_BINFO (type1) == NULL_TREE) != (TYPE_BINFO (type1) == NULL_TREE))
+         && (TYPE_BINFO (type1) == NULL_TREE)
+             != (TYPE_BINFO (type1) == NULL_TREE))
        return false;
       if (TREE_CODE (type1) == RECORD_TYPE && TYPE_BINFO (type1)
          && (BINFO_VTABLE (TYPE_BINFO (type1)) == NULL_TREE)
             != (BINFO_VTABLE (TYPE_BINFO (type2)) == NULL_TREE))
        return false;
 
-      /* At the moment we have no way to establish ODR equivlaence at LTO
-        other than comparing virtual table pointrs of polymorphic types.
+      /* At the moment we have no way to establish ODR equivalence at LTO
+        other than comparing virtual table pointers of polymorphic types.
         Eventually we should start saving mangled names in TYPE_NAME.
         Then this condition will become non-trivial.  */
 
@@ -452,27 +593,146 @@ types_same_for_odr (const_tree type1, const_tree type2)
          == DECL_ASSEMBLER_NAME (TYPE_NAME (type2)));
 }
 
+/* Return true if we can decide on ODR equivalency.
+
+   In non-LTO it is always decide, in LTO however it depends in the type has
+   ODR info attached.
+
+   When STRICT is false, compare main variants.  */
+
+bool
+types_odr_comparable (tree t1, tree t2, bool strict)
+{
+  return (!in_lto_p
+         || (strict ? (main_odr_variant (t1) == main_odr_variant (t2)
+                       && main_odr_variant (t1))
+             : TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
+         || (odr_type_p (t1) && odr_type_p (t2))
+         || (TREE_CODE (t1) == RECORD_TYPE && TREE_CODE (t2) == RECORD_TYPE
+             && TYPE_BINFO (t1) && TYPE_BINFO (t2)
+             && polymorphic_type_binfo_p (TYPE_BINFO (t1))
+             && polymorphic_type_binfo_p (TYPE_BINFO (t2))));
+}
+
+/* Return true if T1 and T2 are ODR equivalent.  If ODR equivalency is not
+   known, be conservative and return false.  */
+
+bool
+types_must_be_same_for_odr (tree t1, tree t2)
+{
+  if (types_odr_comparable (t1, t2))
+    return types_same_for_odr (t1, t2);
+  else
+    return TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2);
+}
+
+/* If T is compound type, return type it is based on.  */
+
+static tree
+compound_type_base (const_tree t)
+{
+  if (TREE_CODE (t) == ARRAY_TYPE
+      || POINTER_TYPE_P (t)
+      || TREE_CODE (t) == COMPLEX_TYPE
+      || VECTOR_TYPE_P (t))
+    return TREE_TYPE (t);
+  if (TREE_CODE (t) == METHOD_TYPE)
+    return TYPE_METHOD_BASETYPE (t);
+  if (TREE_CODE (t) == OFFSET_TYPE)
+    return TYPE_OFFSET_BASETYPE (t);
+  return NULL_TREE;
+}
+
+/* Return true if T is either ODR type or compound type based from it.
+   If the function return true, we know that T is a type originating from C++
+   source even at link-time.  */
+
+bool
+odr_or_derived_type_p (const_tree t)
+{
+  do
+    {
+      if (odr_type_p (t))
+       return true;
+      /* Function type is a tricky one. Basically we can consider it
+        ODR derived if return type or any of the parameters is.
+        We need to check all parameters because LTO streaming merges
+        common types (such as void) and they are not considered ODR then.  */
+      if (TREE_CODE (t) == FUNCTION_TYPE)
+       {
+         if (TYPE_METHOD_BASETYPE (t))
+           t = TYPE_METHOD_BASETYPE (t);
+         else
+          {
+            if (TREE_TYPE (t) && odr_or_derived_type_p (TREE_TYPE (t)))
+              return true;
+            for (t = TYPE_ARG_TYPES (t); t; t = TREE_CHAIN (t))
+              if (odr_or_derived_type_p (TREE_VALUE (t)))
+                return true;
+            return false;
+          }
+       }
+      else
+       t = compound_type_base (t);
+    }
+  while (t);
+  return t;
+}
 
 /* Compare types T1 and T2 and return true if they are
    equivalent.  */
 
 inline bool
-odr_hasher::equal (const value_type *t1, const compare_type *ct2)
+odr_name_hasher::equal (const odr_type_d *o1, const tree_node *t2)
 {
-  tree t2 = const_cast <tree> (ct2);
+  tree t1 = o1->type;
 
   gcc_checking_assert (main_odr_variant (t2) == t2);
-  if (t1->type == t2)
+  gcc_checking_assert (main_odr_variant (t1) == t1);
+  if (t1 == t2)
     return true;
   if (!in_lto_p)
     return false;
-  return types_same_for_odr (t1->type, t2);
+  /* Check for anonymous namespaces. Those have !TREE_PUBLIC
+     on the corresponding TYPE_STUB_DECL.  */
+  if ((type_with_linkage_p (t1) && type_in_anonymous_namespace_p (t1))
+      || (type_with_linkage_p (t2) && type_in_anonymous_namespace_p (t2)))
+    return false;
+  gcc_checking_assert (DECL_ASSEMBLER_NAME (TYPE_NAME (t1)));
+  gcc_checking_assert (DECL_ASSEMBLER_NAME (TYPE_NAME (t2)));
+  return (DECL_ASSEMBLER_NAME (TYPE_NAME (t1))
+         == DECL_ASSEMBLER_NAME (TYPE_NAME (t2)));
+}
+
+/* Compare types T1 and T2 and return true if they are
+   equivalent.  */
+
+inline bool
+odr_vtable_hasher::equal (const odr_type_d *o1, const tree_node *t2)
+{
+  tree t1 = o1->type;
+
+  gcc_checking_assert (main_odr_variant (t2) == t2);
+  gcc_checking_assert (main_odr_variant (t1) == t1);
+  gcc_checking_assert (in_lto_p);
+  t1 = TYPE_MAIN_VARIANT (t1);
+  t2 = TYPE_MAIN_VARIANT (t2);
+  if (t1 == t2)
+    return true;
+  tree v1 = BINFO_VTABLE (TYPE_BINFO (t1));
+  tree v2 = BINFO_VTABLE (TYPE_BINFO (t2));
+  return (operand_equal_p (TREE_OPERAND (v1, 1),
+                          TREE_OPERAND (v2, 1), 0)
+         && DECL_ASSEMBLER_NAME
+                (TREE_OPERAND (TREE_OPERAND (v1, 0), 0))
+            == DECL_ASSEMBLER_NAME
+                (TREE_OPERAND (TREE_OPERAND (v2, 0), 0)));
 }
 
 /* Free ODR type V.  */
 
 inline void
-odr_hasher::remove (value_type *v)
+odr_name_hasher::remove (odr_type_d *v)
 {
   v->bases.release ();
   v->derived_types.release ();
@@ -481,10 +741,12 @@ odr_hasher::remove (value_type *v)
   ggc_free (v);
 }
 
-/* ODR type hash used to lookup ODR type based on tree type node.  */
+/* ODR type hash used to look up ODR type based on tree type node.  */
 
-typedef hash_table<odr_hasher> odr_hash_type;
+typedef hash_table<odr_name_hasher> odr_hash_type;
 static odr_hash_type *odr_hash;
+typedef hash_table<odr_vtable_hasher> odr_vtable_hash_type;
+static odr_vtable_hash_type *odr_vtable_hash;
 
 /* ODR types are also stored into ODR_TYPE vector to allow consistent
    walking.  Bases appear before derived types.  Vector is garbage collected
@@ -507,9 +769,10 @@ set_type_binfo (tree type, tree binfo)
 /* Compare T2 and T2 based on name or structure.  */
 
 static bool
-odr_subtypes_equivalent_p (tree t1, tree t2, hash_set<type_pair,pair_traits> *visited)
+odr_subtypes_equivalent_p (tree t1, tree t2,
+                          hash_set<type_pair> *visited,
+                          location_t loc1, location_t loc2)
 {
-  bool an1, an2;
 
   /* This can happen in incomplete types that should be handled earlier.  */
   gcc_assert (t1 && t2);
@@ -520,35 +783,29 @@ odr_subtypes_equivalent_p (tree t1, tree t2, hash_set<type_pair,pair_traits> *vi
     return true;
 
   /* Anonymous namespace types must match exactly.  */
-  an1 = type_in_anonymous_namespace_p (t1);
-  an2 = type_in_anonymous_namespace_p (t2);
-  if (an1 != an2 || an1)
+  if ((type_with_linkage_p (t1) && type_in_anonymous_namespace_p (t1))
+      || (type_with_linkage_p (t2) && type_in_anonymous_namespace_p (t2)))
     return false;
 
   /* For ODR types be sure to compare their names.
      To support -wno-odr-type-merging we allow one type to be non-ODR
      and other ODR even though it is a violation.  */
-  if ((odr_type_p (t1) && odr_type_p (t2))
-      || (TREE_CODE (t1) == RECORD_TYPE && TREE_CODE (t2) == RECORD_TYPE
-          && TYPE_BINFO (t1) && TYPE_BINFO (t2)
-          && polymorphic_type_binfo_p (TYPE_BINFO (t1))
-          && polymorphic_type_binfo_p (TYPE_BINFO (t2))))
+  if (types_odr_comparable (t1, t2, true))
     {
-      if (!types_same_for_odr (t1, t2))
+      if (!types_same_for_odr (t1, t2, true))
         return false;
       /* Limit recursion: If subtypes are ODR types and we know
          that they are same, be happy.  */
-      if (!get_odr_type (t1, true)->odr_violated)
+      if (!odr_type_p (t1) || !get_odr_type (t1, true)->odr_violated)
         return true;
     }
 
-  /* Component types, builtins and possibly vioalting ODR types
+  /* Component types, builtins and possibly violating ODR types
      have to be compared structurally.  */
   if (TREE_CODE (t1) != TREE_CODE (t2))
     return false;
-  if ((TYPE_NAME (t1) == NULL_TREE) != (TYPE_NAME (t2) == NULL_TREE))
-    return false;
-  if (TYPE_NAME (t1) && DECL_NAME (TYPE_NAME (t1)) != DECL_NAME (TYPE_NAME (t2)))
+  if (AGGREGATE_TYPE_P (t1)
+      && (TYPE_NAME (t1) == NULL_TREE) != (TYPE_NAME (t2) == NULL_TREE))
     return false;
 
   type_pair pair={t1,t2};
@@ -559,16 +816,17 @@ odr_subtypes_equivalent_p (tree t1, tree t2, hash_set<type_pair,pair_traits> *vi
     }
   if (visited->add (pair))
     return true;
-  return odr_types_equivalent_p (t1, t2, false, NULL, visited);
+  return odr_types_equivalent_p (t1, t2, false, NULL, visited, loc1, loc2);
 }
 
 /* Compare two virtual tables, PREVAILING and VTABLE and output ODR
-   violation warings.  */
+   violation warnings.  */
 
 void
 compare_virtual_tables (varpool_node *prevailing, varpool_node *vtable)
 {
   int n1, n2;
+
   if (DECL_VIRTUAL_P (prevailing->decl) != DECL_VIRTUAL_P (vtable->decl))
     {
       odr_violation_reported = true;
@@ -578,7 +836,8 @@ compare_virtual_tables (varpool_node *prevailing, varpool_node *vtable)
          prevailing = vtable;
          vtable = tmp;
        }
-      if (warning_at (DECL_SOURCE_LOCATION (TYPE_NAME (DECL_CONTEXT (vtable->decl))),
+      if (warning_at (DECL_SOURCE_LOCATION
+                       (TYPE_NAME (DECL_CONTEXT (vtable->decl))),
                      OPT_Wodr,
                      "virtual table of type %qD violates one definition rule",
                      DECL_CONTEXT (vtable->decl)))
@@ -589,43 +848,138 @@ compare_virtual_tables (varpool_node *prevailing, varpool_node *vtable)
     }
   if (!prevailing->definition || !vtable->definition)
     return;
+
+  /* If we do not stream ODR type info, do not bother to do useful compare.  */
+  if (!TYPE_BINFO (DECL_CONTEXT (vtable->decl))
+      || !polymorphic_type_binfo_p (TYPE_BINFO (DECL_CONTEXT (vtable->decl))))
+    return;
+
+  odr_type class_type = get_odr_type (DECL_CONTEXT (vtable->decl), true);
+
+  if (class_type->odr_violated)
+    return;
+
   for (n1 = 0, n2 = 0; true; n1++, n2++)
     {
       struct ipa_ref *ref1, *ref2;
       bool end1, end2;
+
       end1 = !prevailing->iterate_reference (n1, ref1);
       end2 = !vtable->iterate_reference (n2, ref2);
-      if (end1 && end2)
-       return;
-      if (!end1 && !end2
-         && DECL_ASSEMBLER_NAME (ref1->referred->decl)
-            != DECL_ASSEMBLER_NAME (ref2->referred->decl)
-         && !n2
-         && !DECL_VIRTUAL_P (ref2->referred->decl)
-         && DECL_VIRTUAL_P (ref1->referred->decl))
+
+      /* !DECL_VIRTUAL_P means RTTI entry;
+        We warn when RTTI is lost because non-RTTI previals; we silently
+        accept the other case.  */
+      while (!end2
+            && (end1
+                || (DECL_ASSEMBLER_NAME (ref1->referred->decl)
+                    != DECL_ASSEMBLER_NAME (ref2->referred->decl)
+                    && TREE_CODE (ref1->referred->decl) == FUNCTION_DECL))
+            && TREE_CODE (ref2->referred->decl) != FUNCTION_DECL)
        {
-         if (warning_at (DECL_SOURCE_LOCATION (TYPE_NAME (DECL_CONTEXT (vtable->decl))), 0,
-                         "virtual table of type %qD contains RTTI information",
-                         DECL_CONTEXT (vtable->decl)))
+         if (!class_type->rtti_broken
+             && warning_at (DECL_SOURCE_LOCATION
+                             (TYPE_NAME (DECL_CONTEXT (vtable->decl))),
+                            OPT_Wodr,
+                            "virtual table of type %qD contains RTTI "
+                            "information",
+                            DECL_CONTEXT (vtable->decl)))
            {
-             inform (DECL_SOURCE_LOCATION (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
-                     "but is prevailed by one without from other translation unit");
-             inform (DECL_SOURCE_LOCATION (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
+             inform (DECL_SOURCE_LOCATION
+                       (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
+                     "but is prevailed by one without from other translation "
+                     "unit");
+             inform (DECL_SOURCE_LOCATION
+                       (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
                      "RTTI will not work on this type");
+             class_type->rtti_broken = true;
            }
          n2++;
           end2 = !vtable->iterate_reference (n2, ref2);
        }
-      if (!end1 && !end2
-         && DECL_ASSEMBLER_NAME (ref1->referred->decl)
-            != DECL_ASSEMBLER_NAME (ref2->referred->decl)
-         && !n1
-         && !DECL_VIRTUAL_P (ref1->referred->decl)
-         && DECL_VIRTUAL_P (ref2->referred->decl))
+      while (!end1
+            && (end2
+                || (DECL_ASSEMBLER_NAME (ref2->referred->decl)
+                    != DECL_ASSEMBLER_NAME (ref1->referred->decl)
+                    && TREE_CODE (ref2->referred->decl) == FUNCTION_DECL))
+            && TREE_CODE (ref1->referred->decl) != FUNCTION_DECL)
        {
          n1++;
-          end1 = !vtable->iterate_reference (n1, ref1);
+          end1 = !prevailing->iterate_reference (n1, ref1);
+       }
+
+      /* Finished?  */
+      if (end1 && end2)
+       {
+         /* Extra paranoia; compare the sizes.  We do not have information
+            about virtual inheritance offsets, so just be sure that these
+            match. 
+            Do this as very last check so the not very informative error
+            is not output too often.  */
+         if (DECL_SIZE (prevailing->decl) != DECL_SIZE (vtable->decl))
+           {
+             class_type->odr_violated = true;
+             if (warning_at (DECL_SOURCE_LOCATION
+                               (TYPE_NAME (DECL_CONTEXT (vtable->decl))),
+                             OPT_Wodr,
+                             "virtual table of type %qD violates "
+                             "one definition rule  ",
+                             DECL_CONTEXT (vtable->decl)))
+               {
+                 inform (DECL_SOURCE_LOCATION
+                           (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
+                         "the conflicting type defined in another translation "
+                         "unit has virtual table of different size");
+               }
+           }
+         return;
+       }
+
+      if (!end1 && !end2)
+       {
+         if (DECL_ASSEMBLER_NAME (ref1->referred->decl)
+             == DECL_ASSEMBLER_NAME (ref2->referred->decl))
+           continue;
+
+         class_type->odr_violated = true;
+
+         /* If the loops above stopped on non-virtual pointer, we have
+            mismatch in RTTI information mangling.  */
+         if (TREE_CODE (ref1->referred->decl) != FUNCTION_DECL
+             && TREE_CODE (ref2->referred->decl) != FUNCTION_DECL)
+           {
+             if (warning_at (DECL_SOURCE_LOCATION
+                               (TYPE_NAME (DECL_CONTEXT (vtable->decl))),
+                             OPT_Wodr,
+                             "virtual table of type %qD violates "
+                             "one definition rule  ",
+                             DECL_CONTEXT (vtable->decl)))
+               {
+                 inform (DECL_SOURCE_LOCATION
+                           (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
+                         "the conflicting type defined in another translation "
+                         "unit with different RTTI information");
+               }
+             return;
+           }
+         /* At this point both REF1 and REF2 points either to virtual table
+            or virtual method.  If one points to virtual table and other to
+            method we can complain the same way as if one table was shorter
+            than other pointing out the extra method.  */
+         if (TREE_CODE (ref1->referred->decl)
+             != TREE_CODE (ref2->referred->decl))
+           {
+             if (TREE_CODE (ref1->referred->decl) == VAR_DECL)
+               end1 = true;
+             else if (TREE_CODE (ref2->referred->decl) == VAR_DECL)
+               end2 = true;
+           }
        }
+
+      class_type->odr_violated = true;
+
+      /* Complain about size mismatch.  Either we have too many virutal
+        functions or too many virtual table pointers.  */
       if (end1 || end2)
        {
          if (end1)
@@ -636,42 +990,62 @@ compare_virtual_tables (varpool_node *prevailing, varpool_node *vtable)
              ref1 = ref2;
            }
          if (warning_at (DECL_SOURCE_LOCATION
-                           (TYPE_NAME (DECL_CONTEXT (vtable->decl))), 0,
+                           (TYPE_NAME (DECL_CONTEXT (vtable->decl))),
+                         OPT_Wodr,
                          "virtual table of type %qD violates "
                          "one definition rule",
                          DECL_CONTEXT (vtable->decl)))
            {
-             inform (DECL_SOURCE_LOCATION
-                      (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
-                     "the conflicting type defined in another translation "
-                     "unit");
-             inform (DECL_SOURCE_LOCATION
-                       (TYPE_NAME (DECL_CONTEXT (ref1->referring->decl))),
-                     "contains additional virtual method %qD",
-                     ref1->referred->decl);
+             if (TREE_CODE (ref1->referring->decl) == FUNCTION_DECL)
+               {
+                 inform (DECL_SOURCE_LOCATION
+                          (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
+                         "the conflicting type defined in another translation "
+                         "unit");
+                 inform (DECL_SOURCE_LOCATION
+                           (TYPE_NAME (DECL_CONTEXT (ref1->referring->decl))),
+                         "contains additional virtual method %qD",
+                         ref1->referred->decl);
+               }
+             else
+               {
+                 inform (DECL_SOURCE_LOCATION
+                          (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
+                         "the conflicting type defined in another translation "
+                         "unit has virtual table table with more entries");
+               }
            }
          return;
        }
-      if (DECL_ASSEMBLER_NAME (ref1->referred->decl)
-         != DECL_ASSEMBLER_NAME (ref2->referred->decl))
+
+      /* And in the last case we have either mistmatch in between two virtual
+        methods or two virtual table pointers.  */
+      if (warning_at (DECL_SOURCE_LOCATION
+                       (TYPE_NAME (DECL_CONTEXT (vtable->decl))), OPT_Wodr,
+                     "virtual table of type %qD violates "
+                     "one definition rule  ",
+                     DECL_CONTEXT (vtable->decl)))
        {
-         if (warning_at (DECL_SOURCE_LOCATION
-                           (TYPE_NAME (DECL_CONTEXT (vtable->decl))), 0,
-                         "virtual table of type %qD violates "
-                         "one definition rule  ",
-                         DECL_CONTEXT (vtable->decl)))
+         if (TREE_CODE (ref1->referred->decl) == FUNCTION_DECL)
            {
-             inform (DECL_SOURCE_LOCATION 
+             inform (DECL_SOURCE_LOCATION
                        (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
                      "the conflicting type defined in another translation "
                      "unit");
+             gcc_assert (TREE_CODE (ref2->referred->decl)
+                         == FUNCTION_DECL);
              inform (DECL_SOURCE_LOCATION (ref1->referred->decl),
                      "virtual method %qD", ref1->referred->decl);
              inform (DECL_SOURCE_LOCATION (ref2->referred->decl),
                      "ought to match virtual method %qD but does not",
                      ref2->referred->decl);
-             return;
            }
+         else
+           inform (DECL_SOURCE_LOCATION
+                     (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
+                   "the conflicting type defined in another translation "
+                   "unit has virtual table table with different contents");
+         return;
        }
     }
 }
@@ -687,11 +1061,19 @@ warn_odr (tree t1, tree t2, tree st1, tree st2,
          bool warn, bool *warned, const char *reason)
 {
   tree decl2 = TYPE_NAME (t2);
+  if (warned)
+    *warned = false;
 
-  if (!warn)
+  if (!warn || !TYPE_NAME(t1))
     return;
+
+  /* ODR warnings are output druing LTO streaming; we must apply location
+     cache for potential warnings to be output correctly.  */
+  if (lto_location_cache::current_cache)
+    lto_location_cache::current_cache->apply_location_cache ();
+
   if (!warning_at (DECL_SOURCE_LOCATION (TYPE_NAME (t1)), OPT_Wodr,
-                  "type %qT violates one definition rule",
+                  "type %qT violates the C++ One Definition Rule",
                   t1))
     return;
   if (!st1 && !st2)
@@ -731,49 +1113,237 @@ warn_odr (tree t1, tree t2, tree st1, tree st2,
     *warned = true;
 }
 
-/* We already warned about ODR mismatch.  T1 and T2 ought to be equivalent
-   because they are used on same place in ODR matching types.
-   They are not; inform the user.  */
+/* Return ture if T1 and T2 are incompatible and we want to recusively
+   dive into them from warn_type_mismatch to give sensible answer.  */
 
-void
-warn_types_mismatch (tree t1, tree t2)
+static bool
+type_mismatch_p (tree t1, tree t2)
 {
+  if (odr_or_derived_type_p (t1) && odr_or_derived_type_p (t2)
+      && !odr_types_equivalent_p (t1, t2))
+    return true;
+  return !types_compatible_p (t1, t2);
+}
+
+
+/* Types T1 and T2 was found to be incompatible in a context they can't
+   (either used to declare a symbol of same assembler name or unified by
+   ODR rule).  We already output warning about this, but if possible, output
+   extra information on how the types mismatch.
+
+   This is hard to do in general.  We basically handle the common cases.
+
+   If LOC1 and LOC2 are meaningful locations, use it in the case the types
+   themselves do no thave one.*/
+
+void
+warn_types_mismatch (tree t1, tree t2, location_t loc1, location_t loc2)
+{
+  /* Location of type is known only if it has TYPE_NAME and the name is
+     TYPE_DECL.  */
+  location_t loc_t1 = TYPE_NAME (t1) && TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL
+                     ? DECL_SOURCE_LOCATION (TYPE_NAME (t1))
+                     : UNKNOWN_LOCATION;
+  location_t loc_t2 = TYPE_NAME (t2) && TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL
+                     ? DECL_SOURCE_LOCATION (TYPE_NAME (t2))
+                     : UNKNOWN_LOCATION;
+  bool loc_t2_useful = false;
+
+  /* With LTO it is a common case that the location of both types match.
+     See if T2 has a location that is different from T1. If so, we will
+     inform user about the location.
+     Do not consider the location passed to us in LOC1/LOC2 as those are
+     already output.  */
+  if (loc_t2 > BUILTINS_LOCATION && loc_t2 != loc_t1)
+    {
+      if (loc_t1 <= BUILTINS_LOCATION)
+       loc_t2_useful = true;
+      else
+       {
+         expanded_location xloc1 = expand_location (loc_t1);
+         expanded_location xloc2 = expand_location (loc_t2);
+
+         if (strcmp (xloc1.file, xloc2.file)
+             || xloc1.line != xloc2.line
+             || xloc1.column != xloc2.column)
+           loc_t2_useful = true;
+       }
+    }
+
+  if (loc_t1 <= BUILTINS_LOCATION)
+    loc_t1 = loc1;
+  if (loc_t2 <= BUILTINS_LOCATION)
+    loc_t2 = loc2;
+
+  location_t loc = loc_t1 <= BUILTINS_LOCATION ? loc_t2 : loc_t1;
+
+  /* It is a quite common bug to reference anonymous namespace type in
+     non-anonymous namespace class.  */
+  if ((type_with_linkage_p (t1) && type_in_anonymous_namespace_p (t1))
+      || (type_with_linkage_p (t2) && type_in_anonymous_namespace_p (t2)))
+    {
+      if (type_with_linkage_p (t1) && !type_in_anonymous_namespace_p (t1))
+       {
+         std::swap (t1, t2);
+         std::swap (loc_t1, loc_t2);
+       }
+      gcc_assert (TYPE_NAME (t1) && TYPE_NAME (t2)
+                 && TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL
+                 && TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL);
+      /* Most of the time, the type names will match, do not be unnecesarily
+         verbose.  */
+      if (IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (t1)))
+         != IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (t2))))
+        inform (loc_t1,
+               "type %qT defined in anonymous namespace can not match "
+               "type %qT across the translation unit boundary",
+               t1, t2);
+      else
+        inform (loc_t1,
+               "type %qT defined in anonymous namespace can not match "
+               "across the translation unit boundary",
+               t1);
+      if (loc_t2_useful)
+        inform (loc_t2,
+               "the incompatible type defined in another translation unit");
+      return;
+    }
+  /* If types have mangled ODR names and they are different, it is most
+     informative to output those.
+     This also covers types defined in different namespaces.  */
+  if (TYPE_NAME (t1) && TYPE_NAME (t2)
+      && TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL
+      && TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL
+      && DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t1))
+      && DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t2))
+      && DECL_ASSEMBLER_NAME (TYPE_NAME (t1))
+        != DECL_ASSEMBLER_NAME (TYPE_NAME (t2)))
+    {
+      char *name1 = xstrdup (cplus_demangle
+        (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (TYPE_NAME (t1))),
+         DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES));
+      char *name2 = cplus_demangle
+        (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (TYPE_NAME (t2))),
+         DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES);
+      if (name1 && name2 && strcmp (name1, name2))
+       {
+         inform (loc_t1,
+                 "type name %<%s%> should match type name %<%s%>",
+                 name1, name2);
+         if (loc_t2_useful)
+           inform (loc_t2,
+                   "the incompatible type is defined here");
+         free (name1);
+         return;
+       }
+      free (name1);
+    }
+  /* A tricky case are compound types.  Often they appear the same in source
+     code and the mismatch is dragged in by type they are build from.
+     Look for those differences in subtypes and try to be informative.  In other
+     cases just output nothing because the source code is probably different
+     and in this case we already output a all necessary info.  */
   if (!TYPE_NAME (t1) || !TYPE_NAME (t2))
+    {
+      if (TREE_CODE (t1) == TREE_CODE (t2))
+       {
+         if (TREE_CODE (t1) == ARRAY_TYPE
+             && COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2))
+           {
+             tree i1 = TYPE_DOMAIN (t1);
+             tree i2 = TYPE_DOMAIN (t2);
+       
+             if (i1 && i2
+                 && TYPE_MAX_VALUE (i1)
+                 && TYPE_MAX_VALUE (i2)
+                 && !operand_equal_p (TYPE_MAX_VALUE (i1),
+                                      TYPE_MAX_VALUE (i2), 0))
+               {
+                 inform (loc,
+                         "array types have different bounds");
+                 return;
+               }
+           }
+         if ((POINTER_TYPE_P (t1) || TREE_CODE (t1) == ARRAY_TYPE)
+             && type_mismatch_p (TREE_TYPE (t1), TREE_TYPE (t2)))
+           warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc_t1, loc_t2);
+         else if (TREE_CODE (t1) == METHOD_TYPE
+                  || TREE_CODE (t1) == FUNCTION_TYPE)
+           {
+             tree parms1 = NULL, parms2 = NULL;
+             int count = 1;
+
+             if (type_mismatch_p (TREE_TYPE (t1), TREE_TYPE (t2)))
+               {
+                 inform (loc, "return value type mismatch");
+                 warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc_t1,
+                                      loc_t2);
+                 return;
+               }
+             if (prototype_p (t1) && prototype_p (t2))
+               for (parms1 = TYPE_ARG_TYPES (t1), parms2 = TYPE_ARG_TYPES (t2);
+                    parms1 && parms2;
+                    parms1 = TREE_CHAIN (parms1), parms2 = TREE_CHAIN (parms2),
+                    count++)
+                 {
+                   if (type_mismatch_p (TREE_VALUE (parms1), TREE_VALUE (parms2)))
+                     {
+                       if (count == 1 && TREE_CODE (t1) == METHOD_TYPE)
+                         inform (loc,
+                                 "implicit this pointer type mismatch");
+                       else
+                         inform (loc,
+                                 "type mismatch in parameter %i",
+                                 count - (TREE_CODE (t1) == METHOD_TYPE));
+                       warn_types_mismatch (TREE_VALUE (parms1),
+                                            TREE_VALUE (parms2),
+                                            loc_t1, loc_t2);
+                       return;
+                     }
+                 }
+             if (parms1 || parms2)
+               {
+                 inform (loc,
+                         "types have different parameter counts");
+                 return;
+               }
+           }
+       }
+      return;
+    }
+
+  if (types_odr_comparable (t1, t2, true)
+      && types_same_for_odr (t1, t2, true))
+    inform (loc_t1,
+           "type %qT itself violate the C++ One Definition Rule", t1);
+  /* Prevent pointless warnings like "struct aa" should match "struct aa".  */
+  else if (TYPE_NAME (t1) == TYPE_NAME (t2)
+          && TREE_CODE (t1) == TREE_CODE (t2) && !loc_t2_useful)
     return;
-  /* In Firefox it is a common bug to have same types but in
-     different namespaces.  Be a bit more informative on
-     this.  */
-  if (TYPE_CONTEXT (t1) && TYPE_CONTEXT (t2)
-      && (((TREE_CODE (TYPE_CONTEXT (t1)) == NAMESPACE_DECL)
-           != (TREE_CODE (TYPE_CONTEXT (t2)) == NAMESPACE_DECL))
-          || (TREE_CODE (TYPE_CONTEXT (t1)) == NAMESPACE_DECL
-              && (DECL_NAME (TYPE_CONTEXT (t1)) !=
-                  DECL_NAME (TYPE_CONTEXT (t2))))))
-    inform (DECL_SOURCE_LOCATION (TYPE_NAME (t1)),
-           "type %qT should match type %qT but is defined "
-           "in different namespace  ",
-           t1, t2);
   else
-    inform (DECL_SOURCE_LOCATION (TYPE_NAME (t1)),
-           "type %qT should match type %qT",
+    inform (loc_t1, "type %qT should match type %qT",
            t1, t2);
-  inform (DECL_SOURCE_LOCATION (TYPE_NAME (t2)),
-         "the incompatible type is defined here");
+  if (loc_t2_useful)
+    inform (loc_t2, "the incompatible type is defined here");
 }
 
 /* Compare T1 and T2, report ODR violations if WARN is true and set
    WARNED to true if anything is reported.  Return true if types match.
    If true is returned, the types are also compatible in the sense of
-   gimple_canonical_types_compatible_p.  */
+   gimple_canonical_types_compatible_p.
+   If LOC1 and LOC2 is not UNKNOWN_LOCATION it may be used to output a warning
+   about the type if the type itself do not have location.  */
 
 static bool
-odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type_pair,pair_traits> *visited)
+odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned,
+                       hash_set<type_pair> *visited,
+                       location_t loc1, location_t loc2)
 {
   /* Check first for the obvious case of pointer identity.  */
   if (t1 == t2)
     return true;
-  gcc_assert (!type_in_anonymous_namespace_p (t1));
-  gcc_assert (!type_in_anonymous_namespace_p (t2));
+  gcc_assert (!type_with_linkage_p (t1) || !type_in_anonymous_namespace_p (t1));
+  gcc_assert (!type_with_linkage_p (t2) || !type_in_anonymous_namespace_p (t2));
 
   /* Can't be the same type if the types don't have the same code.  */
   if (TREE_CODE (t1) != TREE_CODE (t2))
@@ -791,15 +1361,26 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
       return false;
     }
 
+  if ((type_with_linkage_p (t1) && type_in_anonymous_namespace_p (t1))
+      || (type_with_linkage_p (t2) && type_in_anonymous_namespace_p (t2)))
+    {
+      /* We can not trip this when comparing ODR types, only when trying to
+        match different ODR derivations from different declarations.
+        So WARN should be always false.  */
+      gcc_assert (!warn);
+      return false;
+    }
+
   if (comp_type_attributes (t1, t2) != 1)
     {
       warn_odr (t1, t2, NULL, NULL, warn, warned,
-               G_("a type with attributes "
+               G_("a type with different attributes "
                   "is defined in another translation unit"));
       return false;
     }
 
-  if (TREE_CODE (t1) == ENUMERAL_TYPE)
+  if (TREE_CODE (t1) == ENUMERAL_TYPE
+      && TYPE_VALUES (t1) && TYPE_VALUES (t2))
     {
       tree v1, v2;
       for (v1 = TYPE_VALUES (t1), v2 = TYPE_VALUES (t2);
@@ -880,26 +1461,29 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
              return false;
            }
 
-         if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2), visited))
+         if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2),
+                                         visited, loc1, loc2))
            {
              warn_odr (t1, t2, NULL, NULL, warn, warned,
                        G_("it is defined as a pointer to different type "
                           "in another translation unit"));
              if (warn && warned)
-               warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2));
+               warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2),
+                                    loc1, loc2);
              return false;
            }
        }
 
       if ((TREE_CODE (t1) == VECTOR_TYPE || TREE_CODE (t1) == COMPLEX_TYPE)
-         && !odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2), visited))
+         && !odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2),
+                                        visited, loc1, loc2))
        {
          /* Probably specific enough.  */
          warn_odr (t1, t2, NULL, NULL, warn, warned,
                    G_("a different type is defined "
                       "in another translation unit"));
          if (warn && warned)
-           warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2));
+           warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc1, loc2);
          return false;
        }
     }
@@ -910,13 +1494,14 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
       {
        /* Array types are the same if the element types are the same and
           the number of elements are the same.  */
-       if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2), visited))
+       if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2),
+                                       visited, loc1, loc2))
          {
            warn_odr (t1, t2, NULL, NULL, warn, warned,
                      G_("a different type is defined in another "
                         "translation unit"));
            if (warn && warned)
-             warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2));
+             warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc1, loc2);
          }
        gcc_assert (TYPE_STRING_FLAG (t1) == TYPE_STRING_FLAG (t2));
        gcc_assert (TYPE_NONALIASED_COMPONENT (t1)
@@ -951,17 +1536,19 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
     case FUNCTION_TYPE:
       /* Function types are the same if the return type and arguments types
         are the same.  */
-      if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2), visited))
+      if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2),
+                                     visited, loc1, loc2))
        {
          warn_odr (t1, t2, NULL, NULL, warn, warned,
                    G_("has different return value "
                       "in another translation unit"));
          if (warn && warned)
-           warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2));
+           warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc1, loc2);
          return false;
        }
 
-      if (TYPE_ARG_TYPES (t1) == TYPE_ARG_TYPES (t2))
+      if (TYPE_ARG_TYPES (t1) == TYPE_ARG_TYPES (t2)
+         || !prototype_p (t1) || !prototype_p (t2))
        return true;
       else
        {
@@ -972,14 +1559,15 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
               parms1 = TREE_CHAIN (parms1), parms2 = TREE_CHAIN (parms2))
            {
              if (!odr_subtypes_equivalent_p
-                    (TREE_VALUE (parms1), TREE_VALUE (parms2), visited))
+                    (TREE_VALUE (parms1), TREE_VALUE (parms2), visited,
+                     loc1, loc2))
                {
                  warn_odr (t1, t2, NULL, NULL, warn, warned,
                            G_("has different parameters in another "
                               "translation unit"));
                  if (warn && warned)
                    warn_types_mismatch (TREE_VALUE (parms1),
-                                        TREE_VALUE (parms2));
+                                        TREE_VALUE (parms2), loc1, loc2);
                  return false;
                }
            }
@@ -1004,6 +1592,20 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
        /* For aggregate types, all the fields must be the same.  */
        if (COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2))
          {
+           if (TYPE_BINFO (t1) && TYPE_BINFO (t2)
+               && polymorphic_type_binfo_p (TYPE_BINFO (t1))
+                  != polymorphic_type_binfo_p (TYPE_BINFO (t2)))
+             {
+               if (polymorphic_type_binfo_p (TYPE_BINFO (t1)))
+                 warn_odr (t1, t2, NULL, NULL, warn, warned,
+                           G_("a type defined in another translation unit "
+                              "is not polymorphic"));
+               else
+                 warn_odr (t1, t2, NULL, NULL, warn, warned,
+                           G_("a type defined in another translation unit "
+                              "is polymorphic"));
+               return false;
+             }
            for (f1 = TYPE_FIELDS (t1), f2 = TYPE_FIELDS (t2);
                 f1 || f2;
                 f1 = TREE_CHAIN (f1), f2 = TREE_CHAIN (f2))
@@ -1015,8 +1617,20 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
                  f2 = TREE_CHAIN (f2);
                if (!f1 || !f2)
                  break;
+               if (DECL_VIRTUAL_P (f1) != DECL_VIRTUAL_P (f2))
+                 {
+                   warn_odr (t1, t2, NULL, NULL, warn, warned,
+                             G_("a type with different virtual table pointers"
+                                " is defined in another translation unit"));
+                   return false;
+                 }
                if (DECL_ARTIFICIAL (f1) != DECL_ARTIFICIAL (f2))
-                 break;
+                 {
+                   warn_odr (t1, t2, NULL, NULL, warn, warned,
+                             G_("a type with different bases is defined "
+                                "in another translation unit"));
+                   return false;
+                 }
                if (DECL_NAME (f1) != DECL_NAME (f2)
                    && !DECL_ARTIFICIAL (f1))
                  {
@@ -1025,10 +1639,12 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
                                 "in another translation unit"));
                    return false;
                  }
-               if (!odr_subtypes_equivalent_p (TREE_TYPE (f1), TREE_TYPE (f2), visited))
+               if (!odr_subtypes_equivalent_p (TREE_TYPE (f1),
+                                               TREE_TYPE (f2), visited,
+                                               loc1, loc2))
                  {
-                   /* Do not warn about artificial fields and just go into generic
-                      field mismatch warning.  */
+                   /* Do not warn about artificial fields and just go into
+                      generic field mismatch warning.  */
                    if (DECL_ARTIFICIAL (f1))
                      break;
 
@@ -1036,16 +1652,16 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
                              G_("a field of same name but different type "
                                 "is defined in another translation unit"));
                    if (warn && warned)
-                     warn_types_mismatch (TREE_TYPE (f1), TREE_TYPE (f2));
+                     warn_types_mismatch (TREE_TYPE (f1), TREE_TYPE (f2), loc1, loc2);
                    return false;
                  }
                if (!gimple_compare_field_offset (f1, f2))
                  {
-                   /* Do not warn about artificial fields and just go into generic
-                      field mismatch warning.  */
+                   /* Do not warn about artificial fields and just go into
+                      generic field mismatch warning.  */
                    if (DECL_ARTIFICIAL (f1))
                      break;
-                   warn_odr (t1, t2, t1, t2, warn, warned,
+                   warn_odr (t1, t2, f1, f2, warn, warned,
                              G_("fields has different layout "
                                 "in another translation unit"));
                    return false;
@@ -1058,60 +1674,71 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
               are not the same.  */
            if (f1 || f2)
              {
-               if (f1 && DECL_ARTIFICIAL (f1))
-                 f1 = NULL;
-               if (f2 && DECL_ARTIFICIAL (f2))
-                 f2 = NULL;
-               if (f1 || f2)
-                 warn_odr (t1, t2, f1, f2, warn, warned,
-                           G_("a type with different number of fields "
-                              "is defined in another translation unit"));
-               /* Ideally we should never get this generic message.  */
+               if ((f1 && DECL_VIRTUAL_P (f1)) || (f2 && DECL_VIRTUAL_P (f2)))
+                 warn_odr (t1, t2, NULL, NULL, warn, warned,
+                           G_("a type with different virtual table pointers"
+                              " is defined in another translation unit"));
+               else if ((f1 && DECL_ARTIFICIAL (f1))
+                        || (f2 && DECL_ARTIFICIAL (f2)))
+                 warn_odr (t1, t2, NULL, NULL, warn, warned,
+                           G_("a type with different bases is defined "
+                              "in another translation unit"));
                else
                  warn_odr (t1, t2, f1, f2, warn, warned,
-                           G_("a type with different memory representation "
+                           G_("a type with different number of fields "
                               "is defined in another translation unit"));
                
                return false;
              }
            if ((TYPE_MAIN_VARIANT (t1) == t1 || TYPE_MAIN_VARIANT (t2) == t2)
+               && COMPLETE_TYPE_P (TYPE_MAIN_VARIANT (t1))
+               && COMPLETE_TYPE_P (TYPE_MAIN_VARIANT (t2))
+               && odr_type_p (TYPE_MAIN_VARIANT (t1))
+               && odr_type_p (TYPE_MAIN_VARIANT (t2))
                && (TYPE_METHODS (TYPE_MAIN_VARIANT (t1))
                    != TYPE_METHODS (TYPE_MAIN_VARIANT (t2))))
              {
-               for (f1 = TYPE_METHODS (TYPE_MAIN_VARIANT (t1)),
-                    f2 = TYPE_METHODS (TYPE_MAIN_VARIANT (t2));
-                    f1 && f2 ; f1 = DECL_CHAIN (f1), f2 = DECL_CHAIN (f2))
-                 {
-                   if (DECL_ASSEMBLER_NAME (f1) != DECL_ASSEMBLER_NAME (f2))
-                     {
-                       warn_odr (t1, t2, f1, f2, warn, warned,
-                                 G_("a different method of same type "
-                                    "is defined in another translation unit"));
-                       return false;
-                     }
-                   if (DECL_VIRTUAL_P (f1) != DECL_VIRTUAL_P (f2))
-                     {
-                       warn_odr (t1, t2, f1, f2, warn, warned,
-                                 G_("s definition that differs by virtual "
-                                    "keyword in another translation unit"));
-                       return false;
-                     }
-                   if (DECL_VINDEX (f1) != DECL_VINDEX (f2))
-                     {
-                       warn_odr (t1, t2, f1, f2, warn, warned,
-                                 G_("virtual table layout differs in another "
-                                    "translation unit"));
-                       return false;
-                     }
-                   if (odr_subtypes_equivalent_p (TREE_TYPE (f1), TREE_TYPE (f2), visited))
-                     {
-                       warn_odr (t1, t2, f1, f2, warn, warned,
-                                 G_("method with incompatible type is defined "
-                                    "in another translation unit"));
-                       return false;
-                     }
-                 }
-               if (f1 || f2)
+               /* Currently free_lang_data sets TYPE_METHODS to error_mark_node
+                  if it is non-NULL so this loop will never realy execute.  */
+               if (TYPE_METHODS (TYPE_MAIN_VARIANT (t1)) != error_mark_node
+                   && TYPE_METHODS (TYPE_MAIN_VARIANT (t2)) != error_mark_node)
+                 for (f1 = TYPE_METHODS (TYPE_MAIN_VARIANT (t1)),
+                      f2 = TYPE_METHODS (TYPE_MAIN_VARIANT (t2));
+                      f1 && f2 ; f1 = DECL_CHAIN (f1), f2 = DECL_CHAIN (f2))
+                   {
+                     if (DECL_ASSEMBLER_NAME (f1) != DECL_ASSEMBLER_NAME (f2))
+                       {
+                         warn_odr (t1, t2, f1, f2, warn, warned,
+                                   G_("a different method of same type "
+                                      "is defined in another "
+                                      "translation unit"));
+                         return false;
+                       }
+                     if (DECL_VIRTUAL_P (f1) != DECL_VIRTUAL_P (f2))
+                       {
+                         warn_odr (t1, t2, f1, f2, warn, warned,
+                                   G_("s definition that differs by virtual "
+                                      "keyword in another translation unit"));
+                         return false;
+                       }
+                     if (DECL_VINDEX (f1) != DECL_VINDEX (f2))
+                       {
+                         warn_odr (t1, t2, f1, f2, warn, warned,
+                                   G_("virtual table layout differs "
+                                      "in another translation unit"));
+                         return false;
+                       }
+                     if (odr_subtypes_equivalent_p (TREE_TYPE (f1),
+                                                    TREE_TYPE (f2), visited,
+                                                    loc1, loc2))
+                       {
+                         warn_odr (t1, t2, f1, f2, warn, warned,
+                                   G_("method with incompatible type is "
+                                      "defined in another translation unit"));
+                         return false;
+                       }
+                   }
+               if ((f1 == NULL) != (f2 == NULL))
                  {
                    warn_odr (t1, t2, NULL, NULL, warn, warned,
                              G_("a type with different number of methods "
@@ -1123,6 +1750,7 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
        break;
       }
     case VOID_TYPE:
+    case NULLPTR_TYPE:
       break;
 
     default:
@@ -1153,51 +1781,203 @@ odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned, hash_set<type
   return true;
 }
 
+/* Return true if TYPE1 and TYPE2 are equivalent for One Definition Rule.  */
+
+bool
+odr_types_equivalent_p (tree type1, tree type2)
+{
+  hash_set<type_pair> visited;
+
+#ifdef ENABLE_CHECKING
+  gcc_assert (odr_or_derived_type_p (type1) && odr_or_derived_type_p (type2));
+#endif
+  return odr_types_equivalent_p (type1, type2, false, NULL,
+                                &visited, UNKNOWN_LOCATION, UNKNOWN_LOCATION);
+}
+
 /* TYPE is equivalent to VAL by ODR, but its tree representation differs
    from VAL->type.  This may happen in LTO where tree merging did not merge
-   all variants of the same type.  It may or may not mean the ODR violation.
-   Add it to the list of duplicates and warn on some violations.  */
+   all variants of the same type or due to ODR violation.
+
+   Analyze and report ODR violations and add type to duplicate list.
+   If TYPE is more specified than VAL->type, prevail VAL->type.  Also if
+   this is first time we see definition of a class return true so the
+   base types are analyzed.  */
 
 static bool
 add_type_duplicate (odr_type val, tree type)
 {
   bool build_bases = false;
+  bool prevail = false;
+  bool odr_must_violate = false;
+
   if (!val->types_set)
     val->types_set = new hash_set<tree>;
 
+  /* Chose polymorphic type as leader (this happens only in case of ODR
+     violations.  */
+  if ((TREE_CODE (type) == RECORD_TYPE && TYPE_BINFO (type)
+       && polymorphic_type_binfo_p (TYPE_BINFO (type)))
+      && (TREE_CODE (val->type) != RECORD_TYPE || !TYPE_BINFO (val->type)
+          || !polymorphic_type_binfo_p (TYPE_BINFO (val->type))))
+    {
+      prevail = true;
+      build_bases = true;
+    }
   /* Always prefer complete type to be the leader.  */
-  if (!COMPLETE_TYPE_P (val->type)
-      && COMPLETE_TYPE_P (type))
+  else if (!COMPLETE_TYPE_P (val->type) && COMPLETE_TYPE_P (type))
     {
-      tree tmp = type;
-
+      prevail = true;
+      build_bases = TYPE_BINFO (type);
+    }
+  else if (COMPLETE_TYPE_P (val->type) && !COMPLETE_TYPE_P (type))
+    ;
+  else if (TREE_CODE (val->type) == ENUMERAL_TYPE
+          && TREE_CODE (type) == ENUMERAL_TYPE
+          && !TYPE_VALUES (val->type) && TYPE_VALUES (type))
+    prevail = true;
+  else if (TREE_CODE (val->type) == RECORD_TYPE
+          && TREE_CODE (type) == RECORD_TYPE
+          && TYPE_BINFO (type) && !TYPE_BINFO (val->type))
+    {
+      gcc_assert (!val->bases.length ());
       build_bases = true;
-      type = val->type;
-      val->type = tmp;
+      prevail = true;
     }
 
-  /* See if this duplicate is new.  */
-  if (!val->types_set->add (type))
+  if (prevail)
+    std::swap (val->type, type);
+
+  val->types_set->add (type);
+
+  /* If we now have a mangled name, be sure to record it to val->type
+     so ODR hash can work.  */
+
+  if (can_be_name_hashed_p (type) && !can_be_name_hashed_p (val->type))
+    SET_DECL_ASSEMBLER_NAME (TYPE_NAME (val->type),
+                            DECL_ASSEMBLER_NAME (TYPE_NAME (type)));
+
+  bool merge = true;
+  bool base_mismatch = false;
+  unsigned int i;
+  bool warned = false;
+  hash_set<type_pair> visited;
+
+  gcc_assert (in_lto_p);
+  vec_safe_push (val->types, type);
+
+  /* If both are class types, compare the bases.  */
+  if (COMPLETE_TYPE_P (type) && COMPLETE_TYPE_P (val->type)
+      && TREE_CODE (val->type) == RECORD_TYPE
+      && TREE_CODE (type) == RECORD_TYPE
+      && TYPE_BINFO (val->type) && TYPE_BINFO (type))
     {
-      bool merge = true;
-      bool base_mismatch = false;
-      unsigned int i,j;
-      bool warned = false;
-      hash_set<type_pair,pair_traits> visited;
-
-      gcc_assert (in_lto_p);
-      vec_safe_push (val->types, type);
-
-      /* First we compare memory layout.  */
-      if (!odr_types_equivalent_p (val->type, type, !flag_ltrans && !val->odr_violated,
-                                  &warned, &visited))
+      if (BINFO_N_BASE_BINFOS (TYPE_BINFO (type))
+         != BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)))
+       {
+         if (!flag_ltrans && !warned && !val->odr_violated)
+           {
+             tree extra_base;
+             warn_odr (type, val->type, NULL, NULL, !warned, &warned,
+                       "a type with the same name but different "
+                       "number of polymorphic bases is "
+                       "defined in another translation unit");
+             if (warned)
+               {
+                 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (type))
+                     > BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)))
+                   extra_base = BINFO_BASE_BINFO
+                                (TYPE_BINFO (type),
+                                 BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)));
+                 else
+                   extra_base = BINFO_BASE_BINFO
+                                (TYPE_BINFO (val->type),
+                                 BINFO_N_BASE_BINFOS (TYPE_BINFO (type)));
+                 tree extra_base_type = BINFO_TYPE (extra_base);
+                 inform (DECL_SOURCE_LOCATION (TYPE_NAME (extra_base_type)),
+                         "the extra base is defined here");
+               }
+           }
+         base_mismatch = true;
+       }
+      else
+       for (i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
+         {
+           tree base1 = BINFO_BASE_BINFO (TYPE_BINFO (type), i);
+           tree base2 = BINFO_BASE_BINFO (TYPE_BINFO (val->type), i);
+           tree type1 = BINFO_TYPE (base1);
+           tree type2 = BINFO_TYPE (base2);
+
+           if (types_odr_comparable (type1, type2))
+             {
+               if (!types_same_for_odr (type1, type2))
+                 base_mismatch = true;
+             }
+           else
+             if (!odr_types_equivalent_p (type1, type2))
+               base_mismatch = true;
+           if (base_mismatch)
+             {
+               if (!warned && !val->odr_violated)
+                 {
+                   warn_odr (type, val->type, NULL, NULL,
+                             !warned, &warned,
+                             "a type with the same name but different base "
+                             "type is defined in another translation unit");
+                   if (warned)
+                     warn_types_mismatch (type1, type2,
+                                           UNKNOWN_LOCATION, UNKNOWN_LOCATION);
+                 }
+               break;
+             }
+           if (BINFO_OFFSET (base1) != BINFO_OFFSET (base2))
+             {
+               base_mismatch = true;
+               if (!warned && !val->odr_violated)
+                 warn_odr (type, val->type, NULL, NULL,
+                           !warned, &warned,
+                           "a type with the same name but different base "
+                           "layout is defined in another translation unit");
+               break;
+             }
+           /* One of bases is not of complete type.  */
+           if (!TYPE_BINFO (type1) != !TYPE_BINFO (type2))
+             {
+               /* If we have a polymorphic type info specified for TYPE1
+                  but not for TYPE2 we possibly missed a base when recording
+                  VAL->type earlier.
+                  Be sure this does not happen.  */
+               if (TYPE_BINFO (type1)
+                   && polymorphic_type_binfo_p (TYPE_BINFO (type1))
+                   && !build_bases)
+                 odr_must_violate = true;
+               break;
+             }
+           /* One base is polymorphic and the other not.
+              This ought to be diagnosed earlier, but do not ICE in the
+              checking bellow.  */
+           else if (TYPE_BINFO (type1)
+                    && polymorphic_type_binfo_p (TYPE_BINFO (type1))
+                       != polymorphic_type_binfo_p (TYPE_BINFO (type2)))
+             {
+               if (!warned && !val->odr_violated)
+                 warn_odr (type, val->type, NULL, NULL,
+                           !warned, &warned,
+                           "a base of the type is polymorphic only in one "
+                           "translation unit");
+               base_mismatch = true;
+               break;
+             }
+         }
+      if (base_mismatch)
        {
          merge = false;
          odr_violation_reported = true;
          val->odr_violated = true;
+
          if (symtab->dump_file)
            {
-             fprintf (symtab->dump_file, "ODR violation\n");
+             fprintf (symtab->dump_file, "ODR base violation\n");
            
              print_node (symtab->dump_file, "", val->type, 0);
              putc ('\n',symtab->dump_file);
@@ -1205,106 +1985,120 @@ add_type_duplicate (odr_type val, tree type)
              putc ('\n',symtab->dump_file);
            }
        }
+    }
 
-      /* Next sanity check that bases are the same.  If not, we will end
-        up producing wrong answers.  */
-      if (COMPLETE_TYPE_P (type) && COMPLETE_TYPE_P (val->type)
-         && TREE_CODE (val->type) == RECORD_TYPE
-         && TREE_CODE (type) == RECORD_TYPE
-         && TYPE_BINFO (val->type) && TYPE_BINFO (type))
+  /* Next compare memory layout.  */
+  if (!odr_types_equivalent_p (val->type, type,
+                              !flag_ltrans && !val->odr_violated && !warned,
+                              &warned, &visited,
+                              DECL_SOURCE_LOCATION (TYPE_NAME (val->type)),
+                              DECL_SOURCE_LOCATION (TYPE_NAME (type))))
+    {
+      merge = false;
+      odr_violation_reported = true;
+      val->odr_violated = true;
+      if (symtab->dump_file)
        {
-         for (j = 0, i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
-           if (polymorphic_type_binfo_p (BINFO_BASE_BINFO (TYPE_BINFO (type), i)))
-             {
-               odr_type base = get_odr_type
-                                  (BINFO_TYPE
-                                     (BINFO_BASE_BINFO (TYPE_BINFO (type),
-                                                        i)),
-                                   true);
-               if (val->bases.length () <= j || val->bases[j] != base)
-                 base_mismatch = true;
-               j++;
-             }
-         if (base_mismatch)
-           {
-             merge = false;
-             odr_violation_reported = true;
-
-             if (!warned && !val->odr_violated)
-               warn_odr (type, val->type, NULL, NULL, !warned, &warned,
-                         "a type with the same name but different bases is "
-                         "defined in another translation unit");
-             val->odr_violated = true;
-             if (symtab->dump_file)
-               {
-                 fprintf (symtab->dump_file, "ODR bse violation or merging bug?\n");
-               
-                 print_node (symtab->dump_file, "", val->type, 0);
-                 putc ('\n',symtab->dump_file);
-                 print_node (symtab->dump_file, "", type, 0);
-                 putc ('\n',symtab->dump_file);
-               }
-           }
-       }
+         fprintf (symtab->dump_file, "ODR violation\n");
 
-      /* Regularize things a little.  During LTO same types may come with
-        different BINFOs.  Either because their virtual table was
-        not merged by tree merging and only later at decl merging or
-        because one type comes with external vtable, while other
-        with internal.  We want to merge equivalent binfos to conserve
-        memory and streaming overhead.
-
-        The external vtables are more harmful: they contain references
-        to external declarations of methods that may be defined in the
-        merged LTO unit.  For this reason we absolutely need to remove
-        them and replace by internal variants. Not doing so will lead
-         to incomplete answers from possible_polymorphic_call_targets.
-
-        FIXME: disable for now; because ODR types are now build during
-        streaming in, the variants do not need to be linked to the type,
-        yet.  We need to do the merging in cleanup pass to be implemented
-        soon.  */
-      if (!flag_ltrans && merge
-         && 0
-         && TREE_CODE (val->type) == RECORD_TYPE
-         && TREE_CODE (type) == RECORD_TYPE
-         && TYPE_BINFO (val->type) && TYPE_BINFO (type)
-         && TYPE_MAIN_VARIANT (type) == type
-         && TYPE_MAIN_VARIANT (val->type) == val->type
-         && BINFO_VTABLE (TYPE_BINFO (val->type))
-         && BINFO_VTABLE (TYPE_BINFO (type)))
+         print_node (symtab->dump_file, "", val->type, 0);
+         putc ('\n',symtab->dump_file);
+         print_node (symtab->dump_file, "", type, 0);
+         putc ('\n',symtab->dump_file);
+       }
+    }
+  gcc_assert (val->odr_violated || !odr_must_violate);
+  /* Sanity check that all bases will be build same way again.  */
+#ifdef ENABLE_CHECKING
+  if (COMPLETE_TYPE_P (type) && COMPLETE_TYPE_P (val->type)
+      && TREE_CODE (val->type) == RECORD_TYPE
+      && TREE_CODE (type) == RECORD_TYPE
+      && TYPE_BINFO (val->type) && TYPE_BINFO (type)
+      && !val->odr_violated
+      && !base_mismatch && val->bases.length ())
+    {
+      unsigned int num_poly_bases = 0;
+      unsigned int j;
+
+      for (i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
+       if (polymorphic_type_binfo_p (BINFO_BASE_BINFO
+                                        (TYPE_BINFO (type), i)))
+         num_poly_bases++;
+      gcc_assert (num_poly_bases == val->bases.length ());
+      for (j = 0, i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type));
+          i++)
+       if (polymorphic_type_binfo_p (BINFO_BASE_BINFO
+                                      (TYPE_BINFO (type), i)))
+         {
+           odr_type base = get_odr_type
+                              (BINFO_TYPE
+                                 (BINFO_BASE_BINFO (TYPE_BINFO (type),
+                                                    i)),
+                               true);
+           gcc_assert (val->bases[j] == base);
+           j++;
+         }
+    }
+#endif
+
+
+  /* Regularize things a little.  During LTO same types may come with
+     different BINFOs.  Either because their virtual table was
+     not merged by tree merging and only later at decl merging or
+     because one type comes with external vtable, while other
+     with internal.  We want to merge equivalent binfos to conserve
+     memory and streaming overhead.
+
+     The external vtables are more harmful: they contain references
+     to external declarations of methods that may be defined in the
+     merged LTO unit.  For this reason we absolutely need to remove
+     them and replace by internal variants. Not doing so will lead
+     to incomplete answers from possible_polymorphic_call_targets.
+
+     FIXME: disable for now; because ODR types are now build during
+     streaming in, the variants do not need to be linked to the type,
+     yet.  We need to do the merging in cleanup pass to be implemented
+     soon.  */
+  if (!flag_ltrans && merge
+      && 0
+      && TREE_CODE (val->type) == RECORD_TYPE
+      && TREE_CODE (type) == RECORD_TYPE
+      && TYPE_BINFO (val->type) && TYPE_BINFO (type)
+      && TYPE_MAIN_VARIANT (type) == type
+      && TYPE_MAIN_VARIANT (val->type) == val->type
+      && BINFO_VTABLE (TYPE_BINFO (val->type))
+      && BINFO_VTABLE (TYPE_BINFO (type)))
+    {
+      tree master_binfo = TYPE_BINFO (val->type);
+      tree v1 = BINFO_VTABLE (master_binfo);
+      tree v2 = BINFO_VTABLE (TYPE_BINFO (type));
+
+      if (TREE_CODE (v1) == POINTER_PLUS_EXPR)
        {
-         tree master_binfo = TYPE_BINFO (val->type);
-         tree v1 = BINFO_VTABLE (master_binfo);
-         tree v2 = BINFO_VTABLE (TYPE_BINFO (type));
+         gcc_assert (TREE_CODE (v2) == POINTER_PLUS_EXPR
+                     && operand_equal_p (TREE_OPERAND (v1, 1),
+                                         TREE_OPERAND (v2, 1), 0));
+         v1 = TREE_OPERAND (TREE_OPERAND (v1, 0), 0);
+         v2 = TREE_OPERAND (TREE_OPERAND (v2, 0), 0);
+       }
+      gcc_assert (DECL_ASSEMBLER_NAME (v1)
+                 == DECL_ASSEMBLER_NAME (v2));
 
-         if (TREE_CODE (v1) == POINTER_PLUS_EXPR)
-           {
-             gcc_assert (TREE_CODE (v2) == POINTER_PLUS_EXPR
-                         && operand_equal_p (TREE_OPERAND (v1, 1),
-                                             TREE_OPERAND (v2, 1), 0));
-             v1 = TREE_OPERAND (TREE_OPERAND (v1, 0), 0);
-             v2 = TREE_OPERAND (TREE_OPERAND (v2, 0), 0);
-           }
-         gcc_assert (DECL_ASSEMBLER_NAME (v1)
-                     == DECL_ASSEMBLER_NAME (v2));
+      if (DECL_EXTERNAL (v1) && !DECL_EXTERNAL (v2))
+       {
+         unsigned int i;
 
-         if (DECL_EXTERNAL (v1) && !DECL_EXTERNAL (v2))
+         set_type_binfo (val->type, TYPE_BINFO (type));
+         for (i = 0; i < val->types->length (); i++)
            {
-             unsigned int i;
-
-             set_type_binfo (val->type, TYPE_BINFO (type));
-             for (i = 0; i < val->types->length (); i++)
-               {
-                 if (TYPE_BINFO ((*val->types)[i])
-                     == master_binfo)
-                   set_type_binfo ((*val->types)[i], TYPE_BINFO (type));
-               }
-             BINFO_TYPE (TYPE_BINFO (type)) = val->type;
+             if (TYPE_BINFO ((*val->types)[i])
+                 == master_binfo)
+               set_type_binfo ((*val->types)[i], TYPE_BINFO (type));
            }
-         else
-           set_type_binfo (type, master_binfo);
+         BINFO_TYPE (TYPE_BINFO (type)) = val->type;
        }
+      else
+       set_type_binfo (type, master_binfo);
     }
   return build_bases;
 }
@@ -1315,8 +2109,9 @@ add_type_duplicate (odr_type val, tree type)
 odr_type
 get_odr_type (tree type, bool insert)
 {
-  odr_type_d **slot;
-  odr_type val;
+  odr_type_d **slot = NULL;
+  odr_type_d **vtable_slot = NULL;
+  odr_type val = NULL;
   hashval_t hash;
   bool build_bases = false;
   bool insert_to_odr_array = false;
@@ -1324,21 +2119,68 @@ get_odr_type (tree type, bool insert)
 
   type = main_odr_variant (type);
 
-  hash = hash_type_name (type);
-  slot
-     = odr_hash->find_slot_with_hash (type, hash, insert ? INSERT : NO_INSERT);
-  if (!slot)
+  gcc_checking_assert (can_be_name_hashed_p (type)
+                      || can_be_vtable_hashed_p (type));
+
+  /* Lookup entry, first try name hash, fallback to vtable hash.  */
+  if (can_be_name_hashed_p (type))
+    {
+      hash = hash_odr_name (type);
+      slot = odr_hash->find_slot_with_hash (type, hash,
+                                           insert ? INSERT : NO_INSERT);
+    }
+  if ((!slot || !*slot) && in_lto_p && can_be_vtable_hashed_p (type))
+    {
+      hash = hash_odr_vtable (type);
+      vtable_slot = odr_vtable_hash->find_slot_with_hash (type, hash,
+                                                  insert ? INSERT : NO_INSERT);
+    }
+
+  if (!slot && !vtable_slot)
     return NULL;
 
   /* See if we already have entry for type.  */
-  if (*slot)
+  if ((slot && *slot) || (vtable_slot && *vtable_slot))
     {
-      val = *slot;
+      if (slot && *slot)
+       {
+         val = *slot;
+#ifdef ENABLE_CHECKING
+         if (in_lto_p && can_be_vtable_hashed_p (type))
+           {
+             hash = hash_odr_vtable (type);
+             vtable_slot = odr_vtable_hash->find_slot_with_hash (type, hash,
+                                                                 NO_INSERT);
+             gcc_assert (!vtable_slot || *vtable_slot == *slot);
+             vtable_slot = NULL;
+           }
+#endif
+       }
+      else if (*vtable_slot)
+       val = *vtable_slot;
 
-      /* With LTO we need to support multiple tree representation of
-        the same ODR type.  */
-      if (val->type != type)
-        build_bases = add_type_duplicate (val, type);
+      if (val->type != type
+         && (!val->types_set || !val->types_set->add (type)))
+       {
+         gcc_assert (insert);
+         /* We have type duplicate, but it may introduce vtable name or
+            mangled name; be sure to keep hashes in sync.  */
+         if (in_lto_p && can_be_vtable_hashed_p (type)
+             && (!vtable_slot || !*vtable_slot))
+           {
+             if (!vtable_slot)
+               {
+                 hash = hash_odr_vtable (type);
+                 vtable_slot = odr_vtable_hash->find_slot_with_hash
+                            (type, hash, INSERT);
+                 gcc_checking_assert (!*vtable_slot || *vtable_slot == val);
+               }
+             *vtable_slot = val;
+           }
+         if (slot && !*slot)
+           *slot = val;
+         build_bases = add_type_duplicate (val, type);
+       }
     }
   else
     {
@@ -1346,31 +2188,37 @@ get_odr_type (tree type, bool insert)
       val->type = type;
       val->bases = vNULL;
       val->derived_types = vNULL;
-      val->anonymous_namespace = type_in_anonymous_namespace_p (type);
+      if (type_with_linkage_p (type))
+        val->anonymous_namespace = type_in_anonymous_namespace_p (type);
+      else
+       val->anonymous_namespace = 0;
       build_bases = COMPLETE_TYPE_P (val->type);
       insert_to_odr_array = true;
+      if (slot)
+        *slot = val;
+      if (vtable_slot)
+       *vtable_slot = val;
     }
 
   if (build_bases && TREE_CODE (type) == RECORD_TYPE && TYPE_BINFO (type)
+      && type_with_linkage_p (type)
       && type == TYPE_MAIN_VARIANT (type))
     {
       tree binfo = TYPE_BINFO (type);
       unsigned int i;
 
-      gcc_assert (BINFO_TYPE (TYPE_BINFO (val->type)) = type);
+      gcc_assert (BINFO_TYPE (TYPE_BINFO (val->type)) == type);
   
       val->all_derivations_known = type_all_derivations_known_p (type);
-      *slot = val;
       for (i = 0; i < BINFO_N_BASE_BINFOS (binfo); i++)
        /* For now record only polymorphic types. other are
           pointless for devirtualization and we can not precisely
           determine ODR equivalency of these during LTO.  */
        if (polymorphic_type_binfo_p (BINFO_BASE_BINFO (binfo, i)))
          {
-           odr_type base = get_odr_type (BINFO_TYPE (BINFO_BASE_BINFO (binfo,
-                                                                       i)),
-                                         true);
-           gcc_assert (TYPE_MAIN_VARIANT (base->type) == base->type);
+           tree base_type= BINFO_TYPE (BINFO_BASE_BINFO (binfo, i));
+           odr_type base = get_odr_type (base_type, true);
+           gcc_assert (TYPE_MAIN_VARIANT (base_type) == base_type);
            base->derived_types.safe_push (val);
            val->bases.safe_push (base);
            if (base->id > base_id)
@@ -1403,16 +2251,36 @@ void
 register_odr_type (tree type)
 {
   if (!odr_hash)
-    odr_hash = new odr_hash_type (23);
-  /* Arrange things to be nicer and insert main variants first.  */
-  if (odr_type_p (TYPE_MAIN_VARIANT (type)))
+    {
+      odr_hash = new odr_hash_type (23);
+      if (in_lto_p)
+        odr_vtable_hash = new odr_vtable_hash_type (23);
+    }
+  /* Arrange things to be nicer and insert main variants first.
+     ??? fundamental prerecorded types do not have mangled names; this
+     makes it possible that non-ODR type is main_odr_variant of ODR type.
+     Things may get smoother if LTO FE set mangled name of those types same
+     way as C++ FE does.  */
+  if (odr_type_p (main_odr_variant (TYPE_MAIN_VARIANT (type)))
+      && odr_type_p (TYPE_MAIN_VARIANT (type)))
     get_odr_type (TYPE_MAIN_VARIANT (type), true);
-  if (TYPE_MAIN_VARIANT (type) != type)
+  if (TYPE_MAIN_VARIANT (type) != type && odr_type_p (main_odr_variant (type)))
     get_odr_type (type, true);
 }
 
-/* Dump ODR type T and all its derrived type.  INDENT specify indentation for
-   recusive printing.  */
+/* Return true if type is known to have no derivations.  */
+
+bool
+type_known_to_have_no_derivations_p (tree t)
+{
+  return (type_all_derivations_known_p (t)
+         && (TYPE_FINAL_P (t)
+             || (odr_hash
+                 && !get_odr_type (t, true)->derived_types.length())));
+}
+
+/* Dump ODR type T and all its derived types.  INDENT specifies indentation for
+   recursive printing.  */
 
 static void
 dump_odr_type (FILE *f, odr_type t, int indent=0)
@@ -1424,9 +2292,13 @@ dump_odr_type (FILE *f, odr_type t, int indent=0)
   fprintf (f, "%s\n", t->all_derivations_known ? " (derivations known)":"");
   if (TYPE_NAME (t->type))
     {
-      fprintf (f, "%*s defined at: %s:%i\n", indent * 2, "",
+      /*fprintf (f, "%*s defined at: %s:%i\n", indent * 2, "",
               DECL_SOURCE_FILE (TYPE_NAME (t->type)),
-              DECL_SOURCE_LINE (TYPE_NAME (t->type)));
+              DECL_SOURCE_LINE (TYPE_NAME (t->type)));*/
+      if (DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t->type)))
+        fprintf (f, "%*s mangled name: %s\n", indent * 2, "",
+                IDENTIFIER_POINTER
+                  (DECL_ASSEMBLER_NAME (TYPE_NAME (t->type))));
     }
   if (t->bases.length ())
     {
@@ -1482,18 +2354,6 @@ dump_type_inheritance_graph (FILE *f)
     }
 }
 
-/* Given method type T, return type of class it belongs to.
-   Lookup this pointer and get its type.    */
-
-tree
-method_class_type (const_tree t)
-{
-  tree first_parm_type = TREE_VALUE (TYPE_ARG_TYPES (t));
-  gcc_assert (TREE_CODE (t) == METHOD_TYPE);
-
-  return TREE_TYPE (first_parm_type);
-}
-
 /* Initialize IPA devirt and build inheritance tree graph.  */
 
 void
@@ -1508,6 +2368,8 @@ build_type_inheritance_graph (void)
   timevar_push (TV_IPA_INHERITANCE);
   inheritance_dump_file = dump_begin (TDI_inheritance, &flags);
   odr_hash = new odr_hash_type (23);
+  if (in_lto_p)
+    odr_vtable_hash = new odr_vtable_hash_type (23);
 
   /* We reconstruct the graph starting of types of all methods seen in the
      the unit.  */
@@ -1515,8 +2377,7 @@ build_type_inheritance_graph (void)
     if (is_a <cgraph_node *> (n)
        && DECL_VIRTUAL_P (n->decl)
        && n->real_symbol_p ())
-      get_odr_type (TYPE_MAIN_VARIANT (method_class_type (TREE_TYPE (n->decl))),
-                   true);
+      get_odr_type (TYPE_METHOD_BASETYPE (TREE_TYPE (n->decl)), true);
 
     /* Look also for virtual tables of types that do not define any methods.
  
@@ -1580,7 +2441,6 @@ referenced_from_vtable_p (struct cgraph_node *node)
     return true;
 
   for (i = 0; node->iterate_referring (i, ref); i++)
-       
     if ((ref->use == IPA_REF_ALIAS
         && referenced_from_vtable_p (dyn_cast<cgraph_node *> (ref->referring)))
        || (ref->use == IPA_REF_ADDR
@@ -1630,7 +2490,7 @@ maybe_record_node (vec <cgraph_node *> &nodes,
 
   target_node = cgraph_node::get (target);
 
-  /* Preffer alias target over aliases, so we do not get confused by
+  /* Prefer alias target over aliases, so we do not get confused by
      fake duplicates.  */
   if (target_node)
     {
@@ -1642,7 +2502,7 @@ maybe_record_node (vec <cgraph_node *> &nodes,
     }
 
   /* Method can only be called by polymorphic call if any
-     of vtables refering to it are alive. 
+     of vtables referring to it are alive. 
 
      While this holds for non-anonymous functions, too, there are
      cases where we want to keep them in the list; for example
@@ -1652,7 +2512,7 @@ maybe_record_node (vec <cgraph_node *> &nodes,
 
      Currently we ignore these functions in speculative devirtualization.
      ??? Maybe it would make sense to be more aggressive for LTO even
-     eslewhere.  */
+     elsewhere.  */
   if (!flag_ltrans
       && type_in_anonymous_namespace_p (DECL_CONTEXT (target))
       && (!target_node
@@ -1680,12 +2540,12 @@ maybe_record_node (vec <cgraph_node *> &nodes,
     *completep = false;
 }
 
-/* See if BINFO's type match OUTER_TYPE.  If so, lookup 
+/* See if BINFO's type matches OUTER_TYPE.  If so, look up 
    BINFO of subtype of OTR_TYPE at OFFSET and in that BINFO find
    method in vtable and insert method to NODES array
    or BASES_TO_CONSIDER if this array is non-NULL.
    Otherwise recurse to base BINFOs.
-   This match what get_binfo_at_offset does, but with offset
+   This matches what get_binfo_at_offset does, but with offset
    being unknown.
 
    TYPE_BINFOS is a stack of BINFOS of types with defined
@@ -1726,7 +2586,7 @@ record_target_from_binfo (vec <cgraph_node *> &nodes,
       int i;
       tree type_binfo = NULL;
 
-      /* Lookup BINFO with virtual table.  For normal types it is always last
+      /* Look up BINFO with virtual table.  For normal types it is always last
         binfo on stack.  */
       for (i = type_binfos.length () - 1; i >= 0; i--)
        if (BINFO_OFFSET (type_binfos[i]) == BINFO_OFFSET (binfo))
@@ -1781,7 +2641,7 @@ record_target_from_binfo (vec <cgraph_node *> &nodes,
 
   /* Walk bases.  */
   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
-    /* Walking bases that have no virtual method is pointless excercise.  */
+    /* Walking bases that have no virtual method is pointless exercise.  */
     if (polymorphic_type_binfo_p (base_binfo))
       record_target_from_binfo (nodes, bases_to_consider, base_binfo, otr_type,
                                type_binfos, 
@@ -1791,13 +2651,13 @@ record_target_from_binfo (vec <cgraph_node *> &nodes,
     type_binfos.pop ();
 }
      
-/* Lookup virtual methods matching OTR_TYPE (with OFFSET and OTR_TOKEN)
+/* Look up virtual methods matching OTR_TYPE (with OFFSET and OTR_TOKEN)
    of TYPE, insert them to NODES, recurse into derived nodes. 
    INSERTED is used to avoid duplicate insertions of methods into NODES.
    MATCHED_VTABLES are used to avoid duplicate walking vtables.
    Clear COMPLETEP if unreferable target is found.
  
-   If CONSIDER_CONSTURCTION is true, record to BASES_TO_CONSDIER
+   If CONSIDER_CONSTRUCTION is true, record to BASES_TO_CONSIDER
    all cases where BASE_SKIPPED is true (because the base is abstract
    class).  */
 
@@ -1816,7 +2676,7 @@ possible_polymorphic_call_targets_1 (vec <cgraph_node *> &nodes,
 {
   tree binfo = TYPE_BINFO (type->type);
   unsigned int i;
-  vec <tree> type_binfos = vNULL;
+  auto_vec <tree, 8> type_binfos;
   bool possibly_instantiated = type_possibly_instantiated_p (type->type);
 
   /* We may need to consider types w/o instances because of possible derived
@@ -1835,7 +2695,6 @@ possible_polymorphic_call_targets_1 (vec <cgraph_node *> &nodes,
                                inserted, matched_vtables,
                                type->anonymous_namespace, completep);
     }
-  type_binfos.release ();
   for (i = 0; i < type->derived_types.length (); i++)
     possible_polymorphic_call_targets_1 (nodes, inserted, 
                                         matched_vtables,
@@ -1857,27 +2716,27 @@ struct polymorphic_call_target_d
   ipa_polymorphic_call_context context;
   odr_type type;
   vec <cgraph_node *> targets;
-  int speculative_targets;
-  bool complete;
-  int type_warning;
   tree decl_warning;
+  int type_warning;
+  bool complete;
+  bool speculative;
 };
 
 /* Polymorphic call target cache helpers.  */
 
-struct polymorphic_call_target_hasher 
+struct polymorphic_call_target_hasher
+  : pointer_hash <polymorphic_call_target_d>
 {
-  typedef polymorphic_call_target_d value_type;
-  typedef polymorphic_call_target_d compare_type;
-  static inline hashval_t hash (const value_type *);
-  static inline bool equal (const value_type *, const compare_type *);
-  static inline void remove (value_type *);
+  static inline hashval_t hash (const polymorphic_call_target_d *);
+  static inline bool equal (const polymorphic_call_target_d *,
+                           const polymorphic_call_target_d *);
+  static inline void remove (polymorphic_call_target_d *);
 };
 
 /* Return the computed hashcode for ODR_QUERY.  */
 
 inline hashval_t
-polymorphic_call_target_hasher::hash (const value_type *odr_query)
+polymorphic_call_target_hasher::hash (const polymorphic_call_target_d *odr_query)
 {
   inchash::hash hstate (odr_query->otr_token);
 
@@ -1890,6 +2749,7 @@ polymorphic_call_target_hasher::hash (const value_type *odr_query)
       hstate.merge_hash (TYPE_UID (odr_query->context.speculative_outer_type));
       hstate.add_wide_int (odr_query->context.speculative_offset);
     }
+  hstate.add_flag (odr_query->speculative);
   hstate.add_flag (odr_query->context.maybe_in_construction);
   hstate.add_flag (odr_query->context.maybe_derived_type);
   hstate.add_flag (odr_query->context.speculative_maybe_derived_type);
@@ -1900,10 +2760,11 @@ polymorphic_call_target_hasher::hash (const value_type *odr_query)
 /* Compare cache entries T1 and T2.  */
 
 inline bool
-polymorphic_call_target_hasher::equal (const value_type *t1,
-                                      const compare_type *t2)
+polymorphic_call_target_hasher::equal (const polymorphic_call_target_d *t1,
+                                      const polymorphic_call_target_d *t2)
 {
   return (t1->type == t2->type && t1->otr_token == t2->otr_token
+         && t1->speculative == t2->speculative
          && t1->context.offset == t2->context.offset
          && t1->context.speculative_offset == t2->context.speculative_offset
          && t1->context.outer_type == t2->context.outer_type
@@ -1918,7 +2779,7 @@ polymorphic_call_target_hasher::equal (const value_type *t1,
 /* Remove entry in polymorphic call target cache hash.  */
 
 inline void
-polymorphic_call_target_hasher::remove (value_type *v)
+polymorphic_call_target_hasher::remove (polymorphic_call_target_d *v)
 {
   v->targets.release ();
   free (v);
@@ -1954,261 +2815,9 @@ devirt_node_removal_hook (struct cgraph_node *n, void *d ATTRIBUTE_UNUSED)
     free_polymorphic_call_targets_hash ();
 }
 
-/* Return true when TYPE contains an polymorphic type and thus is interesting
-   for devirtualization machinery.  */
-
-bool
-contains_polymorphic_type_p (const_tree type)
-{
-  type = TYPE_MAIN_VARIANT (type);
-
-  if (RECORD_OR_UNION_TYPE_P (type))
-    {
-      if (TYPE_BINFO (type)
-          && polymorphic_type_binfo_p (TYPE_BINFO (type)))
-       return true;
-      for (tree fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
-       if (TREE_CODE (fld) == FIELD_DECL
-           && !DECL_ARTIFICIAL (fld)
-           && contains_polymorphic_type_p (TREE_TYPE (fld)))
-         return true;
-      return false;
-    }
-  if (TREE_CODE (type) == ARRAY_TYPE)
-    return contains_polymorphic_type_p (TREE_TYPE (type));
-  return false;
-}
-
-/* THIS->OUTER_TYPE is a type of memory object where object of EXPECTED_TYPE
-   is contained at THIS->OFFSET.  Walk the memory representation of
-   THIS->OUTER_TYPE and find the outermost class type that match
-   EXPECTED_TYPE or contain EXPECTED_TYPE as a base.  Update THIS
-   to represent it.
-
-   For example when THIS represents type
-   class A
-     {
-       int a;
-       class B b;
-     }
-   and we look for type at offset sizeof(int), we end up with B and offset 0.
-   If the same is produced by multiple inheritance, we end up with A and offset
-   sizeof(int). 
-
-   If we can not find corresponding class, give up by setting
-   THIS->OUTER_TYPE to EXPECTED_TYPE and THIS->OFFSET to NULL. 
-   Return true when lookup was sucesful.  */
-
-bool
-ipa_polymorphic_call_context::restrict_to_inner_class (tree expected_type)
-{
-  tree type = outer_type;
-  HOST_WIDE_INT cur_offset = offset;
-  bool speculative = false;
-  bool speculation_valid = false;
-  bool valid = false;
-
- if (!outer_type)
-   {
-     type = outer_type = expected_type;
-     offset = cur_offset = 0;
-   }
-
- if (speculative_outer_type == outer_type
-     && (!maybe_derived_type
-        || speculative_maybe_derived_type))
-   {
-      speculative_outer_type = NULL;
-      speculative_offset = 0;
-      speculative_maybe_derived_type = false;
-   }
-
-  /* See if speculative type seem to be derrived from outer_type.
-     Then speculation is valid only if it really is a derivate and derived types
-     are allowed.  
-
-     The test does not really look for derivate, but also accepts the case where
-     outer_type is a field of speculative_outer_type.  In this case eiter
-     MAYBE_DERIVED_TYPE is false and we have full non-speculative information or
-     the loop bellow will correctly update SPECULATIVE_OUTER_TYPE
-     and SPECULATIVE_MAYBE_DERIVED_TYPE.  */
-  if (speculative_outer_type
-      && speculative_offset >= offset
-      && contains_type_p (speculative_outer_type,
-                         offset - speculative_offset,
-                         outer_type))
-    speculation_valid = maybe_derived_type;
-  else
-    clear_speculation ();
-                              
-  /* Find the sub-object the constant actually refers to and mark whether it is
-     an artificial one (as opposed to a user-defined one).
-
-     This loop is performed twice; first time for outer_type and second time
-     for speculative_outer_type.  The second iteration has SPECULATIVE set.  */
-  while (true)
-    {
-      HOST_WIDE_INT pos, size;
-      tree fld;
-
-      /* On a match, just return what we found.  */
-      if (TREE_CODE (type) == TREE_CODE (expected_type)
-         && (!in_lto_p
-             || (TREE_CODE (type) == RECORD_TYPE
-                 && TYPE_BINFO (type)
-                 && polymorphic_type_binfo_p (TYPE_BINFO (type))))
-         && types_same_for_odr (type, expected_type))
-       {
-         if (speculative)
-           {
-             gcc_assert (speculation_valid);
-             gcc_assert (valid);
-
-             /* If we did not match the offset, just give up on speculation.  */
-             if (cur_offset != 0
-                 || (types_same_for_odr (speculative_outer_type,
-                                         outer_type)
-                     && (maybe_derived_type
-                         == speculative_maybe_derived_type)))
-               clear_speculation ();
-             return true;
-           }
-         else
-           {
-             /* Type can not contain itself on an non-zero offset.  In that case
-                just give up.  */
-             if (cur_offset != 0)
-               {
-                 valid = false;
-                 goto give_up;
-               }
-             valid = true;
-             /* If speculation is not valid or we determined type precisely,
-                we are done.  */
-             if (!speculation_valid
-                 || !maybe_derived_type)
-               {
-                 clear_speculation ();
-                 return true;
-               }
-             /* Otherwise look into speculation now.  */
-             else
-               {
-                 speculative = true;
-                 type = speculative_outer_type;
-                 cur_offset = speculative_offset;
-                 continue;
-               }
-           }
-       }
-
-      /* Walk fields and find corresponding on at OFFSET.  */
-      if (TREE_CODE (type) == RECORD_TYPE)
-       {
-         for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
-           {
-             if (TREE_CODE (fld) != FIELD_DECL)
-               continue;
-
-             pos = int_bit_position (fld);
-             size = tree_to_uhwi (DECL_SIZE (fld));
-             if (pos <= cur_offset && (pos + size) > cur_offset)
-               break;
-           }
-
-         if (!fld)
-           goto give_up;
-
-         type = TYPE_MAIN_VARIANT (TREE_TYPE (fld));
-         cur_offset -= pos;
-         /* DECL_ARTIFICIAL represents a basetype.  */
-         if (!DECL_ARTIFICIAL (fld))
-           {
-             if (!speculative)
-               {
-                 outer_type = type;
-                 offset = cur_offset;
-                 /* As soon as we se an field containing the type,
-                    we know we are not looking for derivations.  */
-                 maybe_derived_type = false;
-               }
-             else
-               {
-                 speculative_outer_type = type;
-                 speculative_offset = cur_offset;
-                 speculative_maybe_derived_type = false;
-               }
-           }
-       }
-      else if (TREE_CODE (type) == ARRAY_TYPE)
-       {
-         tree subtype = TYPE_MAIN_VARIANT (TREE_TYPE (type));
-
-         /* Give up if we don't know array size.  */
-         if (!TYPE_SIZE (subtype)
-             || !tree_fits_shwi_p (TYPE_SIZE (subtype))
-             || tree_to_shwi (TYPE_SIZE (subtype)) <= 0
-             || !contains_polymorphic_type_p (subtype))
-           goto give_up;
-         cur_offset = cur_offset % tree_to_shwi (TYPE_SIZE (subtype));
-         type = subtype;
-         if (!speculative)
-           {
-             outer_type = type;
-             offset = cur_offset;
-             maybe_derived_type = false;
-           }
-         else
-           {
-             speculative_outer_type = type;
-             speculative_offset = cur_offset;
-             speculative_maybe_derived_type = false;
-           }
-       }
-      /* Give up on anything else.  */
-      else
-       goto give_up;
-    }
-
-  /* If we failed to find subtype we look for, give up and fall back to the
-     most generic query.  */
-give_up:
-  clear_speculation ();
-  if (valid)
-    return true;
-  outer_type = expected_type;
-  offset = 0;
-  maybe_derived_type = true;
-  maybe_in_construction = true;
-  /* POD can be changed to an instance of a polymorphic type by
-     placement new.  Here we play safe and assume that any
-     non-polymorphic type is POD.  */
-  if ((TREE_CODE (type) != RECORD_TYPE
-       || !TYPE_BINFO (type)
-       || !polymorphic_type_binfo_p (TYPE_BINFO (type)))
-      && (!TYPE_SIZE (type)
-         || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
-         || (cur_offset + tree_to_uhwi (TYPE_SIZE (expected_type)) <=
-             tree_to_uhwi (TYPE_SIZE (type)))))
-    return true;
-  return false;
-}
-
-/* Return true if OUTER_TYPE contains OTR_TYPE at OFFSET.  */
-
-static bool
-contains_type_p (tree outer_type, HOST_WIDE_INT offset,
-                tree otr_type)
-{
-  ipa_polymorphic_call_context context;
-  context.offset = offset;
-  context.outer_type = TYPE_MAIN_VARIANT (outer_type);
-  return context.restrict_to_inner_class (otr_type);
-}
-
-/* Lookup base of BINFO that has virtual table VTABLE with OFFSET.  */
+/* Look up base of BINFO that has virtual table VTABLE with OFFSET.  */
 
-static tree
+tree
 subbinfo_with_vtable_at_offset (tree binfo, unsigned HOST_WIDE_INT offset,
                                tree vtable)
 {
@@ -2248,7 +2857,7 @@ vtable_pointer_value_to_vtable (const_tree t, tree *v,
   /* We expect &MEM[(void *)&virtual_table + 16B].
      We obtain object's BINFO from the context of the virtual table. 
      This one contains pointer to virtual table represented via
-     POINTER_PLUS_EXPR.  Verify that this pointer match to what
+     POINTER_PLUS_EXPR.  Verify that this pointer matches what
      we propagated through.
 
      In the case of virtual inheritance, the virtual tables may
@@ -2301,1036 +2910,53 @@ vtable_pointer_value_to_binfo (const_tree t)
      because we do not have BINFO for those. Eventually we should fix
      our representation to allow this case to be handled, too.
      In the case we see store of BINFO we however may assume
-     that standard folding will be ale to cope with it.  */
+     that standard folding will be able to cope with it.  */
   return subbinfo_with_vtable_at_offset (TYPE_BINFO (DECL_CONTEXT (vtable)),
                                         offset, vtable);
 }
 
-/* We know that the instance is stored in variable or parameter
-   (not dynamically allocated) and we want to disprove the fact
-   that it may be in construction at invocation of CALL.
+/* Walk bases of OUTER_TYPE that contain OTR_TYPE at OFFSET.
+   Look up their respective virtual methods for OTR_TOKEN and OTR_TYPE
+   and insert them in NODES.
 
-   For the variable to be in construction we actually need to
-   be in constructor of corresponding global variable or
-   the inline stack of CALL must contain the constructor.
-   Check this condition.  This check works safely only before
-   IPA passes, because inline stacks may become out of date
-   later.  */
+   MATCHED_VTABLES and INSERTED is used to avoid duplicated work.  */
 
-bool
-decl_maybe_in_construction_p (tree base, tree outer_type,
-                             gimple call, tree function)
+static void
+record_targets_from_bases (tree otr_type,
+                          HOST_WIDE_INT otr_token,
+                          tree outer_type,
+                          HOST_WIDE_INT offset,
+                          vec <cgraph_node *> &nodes,
+                          hash_set<tree> *inserted,
+                          hash_set<tree> *matched_vtables,
+                          bool *completep)
 {
-  outer_type = TYPE_MAIN_VARIANT (outer_type);
-  gcc_assert (DECL_P (base));
-
-  /* After inlining the code unification optimizations may invalidate
-     inline stacks.  Also we need to give up on global variables after
-     IPA, because addresses of these may have been propagated to their
-     constructors.  */
-  if (DECL_STRUCT_FUNCTION (function)->after_inlining)
-    return true;
+  while (true)
+    {
+      HOST_WIDE_INT pos, size;
+      tree base_binfo;
+      tree fld;
 
-  /* Pure functions can not do any changes on the dynamic type;
-     that require writting to memory.  */
-  if (!auto_var_in_fn_p (base, function)
-      && flags_from_decl_or_type (function) & (ECF_PURE | ECF_CONST))
-    return false;
+      if (types_same_for_odr (outer_type, otr_type))
+       return;
 
-  for (tree block = gimple_block (call); block && TREE_CODE (block) == BLOCK;
-       block = BLOCK_SUPERCONTEXT (block))
-    if (BLOCK_ABSTRACT_ORIGIN (block)
-       && TREE_CODE (BLOCK_ABSTRACT_ORIGIN (block)) == FUNCTION_DECL)
-      {
-       tree fn = BLOCK_ABSTRACT_ORIGIN (block);
+      for (fld = TYPE_FIELDS (outer_type); fld; fld = DECL_CHAIN (fld))
+       {
+         if (TREE_CODE (fld) != FIELD_DECL)
+           continue;
 
-       if (TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
-           || (!DECL_CXX_CONSTRUCTOR_P (fn)
-               && !DECL_CXX_DESTRUCTOR_P (fn)))
-         {
-           /* Watch for clones where we constant propagated the first
-              argument (pointer to the instance).  */
-           fn = DECL_ABSTRACT_ORIGIN (fn);
-           if (!fn
-               || !is_global_var (base)
-               || TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
-               || (!DECL_CXX_CONSTRUCTOR_P (fn)
-                   && !DECL_CXX_DESTRUCTOR_P (fn)))
-             continue;
-         }
-       if (flags_from_decl_or_type (fn) & (ECF_PURE | ECF_CONST))
-         continue;
+         pos = int_bit_position (fld);
+         size = tree_to_shwi (DECL_SIZE (fld));
+         if (pos <= offset && (pos + size) > offset
+             /* Do not get confused by zero sized bases.  */
+             && polymorphic_type_binfo_p (TYPE_BINFO (TREE_TYPE (fld))))
+           break;
+       }
+      /* Within a class type we should always find corresponding fields.  */
+      gcc_assert (fld && TREE_CODE (TREE_TYPE (fld)) == RECORD_TYPE);
 
-       /* FIXME: this can go away once we have ODR types equivalency on
-          LTO level.  */
-       if (in_lto_p && !polymorphic_type_binfo_p (TYPE_BINFO (outer_type)))
-         return true;
-       tree type = TYPE_MAIN_VARIANT (method_class_type (TREE_TYPE (fn)));
-       if (types_same_for_odr (type, outer_type))
-         return true;
-      }
-
-  if (TREE_CODE (base) == VAR_DECL
-      && is_global_var (base))
-    {
-      if (TREE_CODE (TREE_TYPE (function)) != METHOD_TYPE
-         || (!DECL_CXX_CONSTRUCTOR_P (function)
-             && !DECL_CXX_DESTRUCTOR_P (function)))
-       {
-         if (!DECL_ABSTRACT_ORIGIN (function))
-           return false;
-         /* Watch for clones where we constant propagated the first
-            argument (pointer to the instance).  */
-         function = DECL_ABSTRACT_ORIGIN (function);
-         if (!function
-             || TREE_CODE (TREE_TYPE (function)) != METHOD_TYPE
-             || (!DECL_CXX_CONSTRUCTOR_P (function)
-                 && !DECL_CXX_DESTRUCTOR_P (function)))
-           return false;
-       }
-      /* FIXME: this can go away once we have ODR types equivalency on
-        LTO level.  */
-      if (in_lto_p && !polymorphic_type_binfo_p (TYPE_BINFO (outer_type)))
-       return true;
-      tree type = TYPE_MAIN_VARIANT (method_class_type (TREE_TYPE (function)));
-      if (types_same_for_odr (type, outer_type))
-       return true;
-    }
-  return false;
-}
-
-/* Proudce polymorphic call context for call method of instance
-   that is located within BASE (that is assumed to be a decl) at OFFSET. */
-
-static void
-get_polymorphic_call_info_for_decl (ipa_polymorphic_call_context *context,
-                                   tree base, HOST_WIDE_INT offset)
-{
-  gcc_assert (DECL_P (base));
-
-  context->outer_type = TYPE_MAIN_VARIANT (TREE_TYPE (base));
-  context->offset = offset;
-  context->speculative_outer_type = NULL;
-  context->speculative_offset = 0;
-  context->speculative_maybe_derived_type = true;
-  /* Make very conservative assumption that all objects
-     may be in construction. 
-     TODO: ipa-prop already contains code to tell better. 
-     merge it later.  */
-  context->maybe_in_construction = true;
-  context->maybe_derived_type = false;
-}
-
-/* CST is an invariant (address of decl), try to get meaningful
-   polymorphic call context for polymorphic call of method 
-   if instance of OTR_TYPE that is located at OFFSET of this invariant.
-   Return FALSE if nothing meaningful can be found.  */
-
-bool
-get_polymorphic_call_info_from_invariant (ipa_polymorphic_call_context *context,
-                                         tree cst,
-                                         tree otr_type,
-                                         HOST_WIDE_INT offset)
-{
-  HOST_WIDE_INT offset2, size, max_size;
-  tree base;
-
-  if (TREE_CODE (cst) != ADDR_EXPR)
-    return false;
-
-  cst = TREE_OPERAND (cst, 0);
-  base = get_ref_base_and_extent (cst, &offset2, &size, &max_size);
-  if (!DECL_P (base) || max_size == -1 || max_size != size)
-    return false;
-
-  /* Only type inconsistent programs can have otr_type that is
-     not part of outer type.  */
-  if (!contains_type_p (TREE_TYPE (base), offset, otr_type))
-    return false;
-
-  get_polymorphic_call_info_for_decl (context, base, offset);
-  return true;
-}
-
-/* See if OP is SSA name initialized as a copy or by single assignment.
-   If so, walk the SSA graph up.  */
-
-static tree
-walk_ssa_copies (tree op)
-{
-  STRIP_NOPS (op);
-  while (TREE_CODE (op) == SSA_NAME
-        && !SSA_NAME_IS_DEFAULT_DEF (op)
-        && SSA_NAME_DEF_STMT (op)
-        && gimple_assign_single_p (SSA_NAME_DEF_STMT (op)))
-    {
-      if (gimple_assign_load_p (SSA_NAME_DEF_STMT (op)))
-       return op;
-      op = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (op));
-      STRIP_NOPS (op);
-    }
-  return op;
-}
-
-/* Given REF call in FNDECL, determine class of the polymorphic
-   call (OTR_TYPE), its token (OTR_TOKEN) and CONTEXT.
-   CALL is optional argument giving the actual statement (usually call) where
-   the context is used.
-   Return pointer to object described by the context or an declaration if
-   we found the instance to be stored in the static storage.  */
-
-tree
-get_polymorphic_call_info (tree fndecl,
-                          tree ref,
-                          tree *otr_type,
-                          HOST_WIDE_INT *otr_token,
-                          ipa_polymorphic_call_context *context,
-                          gimple call)
-{
-  tree base_pointer;
-  *otr_type = obj_type_ref_class (ref);
-  *otr_token = tree_to_uhwi (OBJ_TYPE_REF_TOKEN (ref));
-
-  /* Set up basic info in case we find nothing interesting in the analysis.  */
-  context->speculative_outer_type = NULL;
-  context->speculative_offset = 0;
-  context->speculative_maybe_derived_type = true;
-  context->outer_type = TYPE_MAIN_VARIANT (*otr_type);
-  context->offset = 0;
-  base_pointer = OBJ_TYPE_REF_OBJECT (ref);
-  context->maybe_derived_type = true;
-  context->maybe_in_construction = true;
-
-  /* Walk SSA for outer object.  */
-  do 
-    {
-      base_pointer = walk_ssa_copies (base_pointer);
-      if (TREE_CODE (base_pointer) == ADDR_EXPR)
-       {
-         HOST_WIDE_INT size, max_size;
-         HOST_WIDE_INT offset2;
-         tree base = get_ref_base_and_extent (TREE_OPERAND (base_pointer, 0),
-                                              &offset2, &size, &max_size);
-
-         /* If this is a varying address, punt.  */
-         if ((TREE_CODE (base) == MEM_REF || DECL_P (base))
-             && max_size != -1
-             && max_size == size)
-           {
-             /* We found dereference of a pointer.  Type of the pointer
-                and MEM_REF is meaningless, but we can look futher.  */
-             if (TREE_CODE (base) == MEM_REF)
-               {
-                 base_pointer = TREE_OPERAND (base, 0);
-                 context->offset
-                   += offset2 + mem_ref_offset (base).to_short_addr () * BITS_PER_UNIT;
-                 context->outer_type = NULL;
-               }
-             /* We found base object.  In this case the outer_type
-                is known.  */
-             else if (DECL_P (base))
-               {
-                 gcc_assert (!POINTER_TYPE_P (TREE_TYPE (base)));
-
-                 /* Only type inconsistent programs can have otr_type that is
-                    not part of outer type.  */
-                 if (!contains_type_p (TREE_TYPE (base),
-                                       context->offset + offset2, *otr_type))
-                   {
-                     /* Use OTR_TOKEN = INT_MAX as a marker of probably type inconsistent
-                        code sequences; we arrange the calls to be builtin_unreachable
-                        later.  */
-                     *otr_token = INT_MAX;
-                     return base_pointer;
-                   }
-                 get_polymorphic_call_info_for_decl (context, base,
-                                                     context->offset + offset2);
-                 if (context->maybe_in_construction && call)
-                   context->maybe_in_construction
-                    = decl_maybe_in_construction_p (base,
-                                                    context->outer_type,
-                                                    call,
-                                                    fndecl);
-                 return base;
-               }
-             else
-               break;
-           }
-         else
-           break;
-       }
-      else if (TREE_CODE (base_pointer) == POINTER_PLUS_EXPR
-              && tree_fits_uhwi_p (TREE_OPERAND (base_pointer, 1)))
-       {
-         context->offset += tree_to_shwi (TREE_OPERAND (base_pointer, 1))
-                   * BITS_PER_UNIT;
-         base_pointer = TREE_OPERAND (base_pointer, 0);
-       }
-      else
-       break;
-    }
-  while (true);
-
-  /* Try to determine type of the outer object.  */
-  if (TREE_CODE (base_pointer) == SSA_NAME
-      && SSA_NAME_IS_DEFAULT_DEF (base_pointer)
-      && TREE_CODE (SSA_NAME_VAR (base_pointer)) == PARM_DECL)
-    {
-      /* See if parameter is THIS pointer of a method.  */
-      if (TREE_CODE (TREE_TYPE (fndecl)) == METHOD_TYPE
-         && SSA_NAME_VAR (base_pointer) == DECL_ARGUMENTS (fndecl))
-       {
-         context->outer_type
-            = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (base_pointer)));
-         gcc_assert (TREE_CODE (context->outer_type) == RECORD_TYPE);
-
-         /* Dynamic casting has possibly upcasted the type
-            in the hiearchy.  In this case outer type is less
-            informative than inner type and we should forget
-            about it.  */
-         if (!contains_type_p (context->outer_type, context->offset,
-                               *otr_type))
-           {
-             context->outer_type = NULL;
-             return base_pointer;
-           }
-
-         /* If the function is constructor or destructor, then
-            the type is possibly in construction, but we know
-            it is not derived type.  */
-         if (DECL_CXX_CONSTRUCTOR_P (fndecl)
-             || DECL_CXX_DESTRUCTOR_P (fndecl))
-           {
-             context->maybe_in_construction = true;
-             context->maybe_derived_type = false;
-           }
-         else
-           {
-             context->maybe_derived_type = true;
-             context->maybe_in_construction = false;
-           }
-         return base_pointer;
-       }
-      /* Non-PODs passed by value are really passed by invisible
-        reference.  In this case we also know the type of the
-        object.  */
-      if (DECL_BY_REFERENCE (SSA_NAME_VAR (base_pointer)))
-       {
-         context->outer_type
-            = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (base_pointer)));
-         gcc_assert (!POINTER_TYPE_P (context->outer_type));
-         /* Only type inconsistent programs can have otr_type that is
-            not part of outer type.  */
-         if (!contains_type_p (context->outer_type, context->offset,
-                               *otr_type))
-           { 
-             /* Use OTR_TOKEN = INT_MAX as a marker of probably type inconsistent
-                code sequences; we arrange the calls to be builtin_unreachable
-                later.  */
-             *otr_token = INT_MAX;
-             return base_pointer;
-           }
-         context->maybe_derived_type = false;
-         context->maybe_in_construction = false;
-          return base_pointer;
-       }
-    }
-
-  tree base_type = TREE_TYPE (base_pointer);
-
-  if (TREE_CODE (base_pointer) == SSA_NAME
-      && SSA_NAME_IS_DEFAULT_DEF (base_pointer)
-      && TREE_CODE (SSA_NAME_VAR (base_pointer)) != PARM_DECL)
-    {
-      /* Use OTR_TOKEN = INT_MAX as a marker of probably type inconsistent
-        code sequences; we arrange the calls to be builtin_unreachable
-        later.  */
-      *otr_token = INT_MAX;
-      return base_pointer;
-    }
-  if (TREE_CODE (base_pointer) == SSA_NAME
-      && SSA_NAME_DEF_STMT (base_pointer)
-      && gimple_assign_single_p (SSA_NAME_DEF_STMT (base_pointer)))
-    base_type = TREE_TYPE (gimple_assign_rhs1
-                           (SSA_NAME_DEF_STMT (base_pointer)));
-  if (POINTER_TYPE_P (base_type)
-      && contains_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (base_type)),
-                         context->offset,
-                         *otr_type))
-    {
-      context->speculative_outer_type = TYPE_MAIN_VARIANT
-                                         (TREE_TYPE (base_type));
-      context->speculative_offset = context->offset;
-      context->speculative_maybe_derived_type = true;
-    }
-  /* TODO: There are multiple ways to derive a type.  For instance
-     if BASE_POINTER is passed to an constructor call prior our refernece.
-     We do not make this type of flow sensitive analysis yet.  */
-  return base_pointer;
-}
-
-/* Structure to be passed in between detect_type_change and
-   check_stmt_for_type_change.  */
-
-struct type_change_info
-{
-  /* Offset into the object where there is the virtual method pointer we are
-     looking for.  */
-  HOST_WIDE_INT offset;
-  /* The declaration or SSA_NAME pointer of the base that we are checking for
-     type change.  */
-  tree instance;
-  /* The reference to virtual table pointer used.  */
-  tree vtbl_ptr_ref;
-  tree otr_type;
-  /* If we actually can tell the type that the object has changed to, it is
-     stored in this field.  Otherwise it remains NULL_TREE.  */
-  tree known_current_type;
-  HOST_WIDE_INT known_current_offset;
-
-  /* Set to true if dynamic type change has been detected.  */
-  bool type_maybe_changed;
-  /* Set to true if multiple types have been encountered.  known_current_type
-     must be disregarded in that case.  */
-  bool multiple_types_encountered;
-  /* Set to true if we possibly missed some dynamic type changes and we should
-     consider the set to be speculative.  */
-  bool speculative;
-  bool seen_unanalyzed_store;
-};
-
-/* Return true if STMT is not call and can modify a virtual method table pointer.
-   We take advantage of fact that vtable stores must appear within constructor
-   and destructor functions.  */
-
-bool
-noncall_stmt_may_be_vtbl_ptr_store (gimple stmt)
-{
-  if (is_gimple_assign (stmt))
-    {
-      tree lhs = gimple_assign_lhs (stmt);
-
-      if (gimple_clobber_p (stmt))
-       return false;
-      if (!AGGREGATE_TYPE_P (TREE_TYPE (lhs)))
-       {
-         if (flag_strict_aliasing
-             && !POINTER_TYPE_P (TREE_TYPE (lhs)))
-           return false;
-
-         if (TREE_CODE (lhs) == COMPONENT_REF
-             && !DECL_VIRTUAL_P (TREE_OPERAND (lhs, 1)))
-           return false;
-         /* In the future we might want to use get_base_ref_and_offset to find
-            if there is a field corresponding to the offset and if so, proceed
-            almost like if it was a component ref.  */
-       }
-    }
-
-  /* Code unification may mess with inline stacks.  */
-  if (cfun->after_inlining)
-    return true;
-
-  /* Walk the inline stack and watch out for ctors/dtors.
-     TODO: Maybe we can require the store to appear in toplevel
-     block of CTOR/DTOR.  */
-  for (tree block = gimple_block (stmt); block && TREE_CODE (block) == BLOCK;
-       block = BLOCK_SUPERCONTEXT (block))
-    if (BLOCK_ABSTRACT_ORIGIN (block)
-       && TREE_CODE (BLOCK_ABSTRACT_ORIGIN (block)) == FUNCTION_DECL)
-      {
-       tree fn = BLOCK_ABSTRACT_ORIGIN (block);
-
-       if (flags_from_decl_or_type (fn) & (ECF_PURE | ECF_CONST))
-         return false;
-       return (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
-               && (DECL_CXX_CONSTRUCTOR_P (fn)
-                   || DECL_CXX_DESTRUCTOR_P (fn)));
-      }
-  return (TREE_CODE (TREE_TYPE (current_function_decl)) == METHOD_TYPE
-         && (DECL_CXX_CONSTRUCTOR_P (current_function_decl)
-             || DECL_CXX_DESTRUCTOR_P (current_function_decl)));
-}
-
-/* If STMT can be proved to be an assignment to the virtual method table
-   pointer of ANALYZED_OBJ and the type associated with the new table
-   identified, return the type.  Otherwise return NULL_TREE.  */
-
-static tree
-extr_type_from_vtbl_ptr_store (gimple stmt, struct type_change_info *tci,
-                              HOST_WIDE_INT *type_offset)
-{
-  HOST_WIDE_INT offset, size, max_size;
-  tree lhs, rhs, base;
-
-  if (!gimple_assign_single_p (stmt))
-    return NULL_TREE;
-
-  lhs = gimple_assign_lhs (stmt);
-  rhs = gimple_assign_rhs1 (stmt);
-  if (TREE_CODE (lhs) != COMPONENT_REF
-      || !DECL_VIRTUAL_P (TREE_OPERAND (lhs, 1)))
-     {
-       if (dump_file)
-         fprintf (dump_file, "  LHS is not virtual table.\n");
-       return NULL_TREE;
-     }
-
-  if (tci->vtbl_ptr_ref && operand_equal_p (lhs, tci->vtbl_ptr_ref, 0))
-    ;
-  else
-    {
-      base = get_ref_base_and_extent (lhs, &offset, &size, &max_size);
-      if (offset != tci->offset
-         || size != POINTER_SIZE
-         || max_size != POINTER_SIZE)
-       {
-         if (dump_file)
-           fprintf (dump_file, "    wrong offset %i!=%i or size %i\n",
-                    (int)offset, (int)tci->offset, (int)size);
-         return NULL_TREE;
-       }
-      if (DECL_P (tci->instance))
-       {
-         if (base != tci->instance)
-           {
-             if (dump_file)
-               {
-                 fprintf (dump_file, "    base:");
-                 print_generic_expr (dump_file, base, TDF_SLIM);
-                 fprintf (dump_file, " does not match instance:");
-                 print_generic_expr (dump_file, tci->instance, TDF_SLIM);
-                 fprintf (dump_file, "\n");
-               }
-             return NULL_TREE;
-           }
-       }
-      else if (TREE_CODE (base) == MEM_REF)
-       {
-         if (!operand_equal_p (tci->instance, TREE_OPERAND (base, 0), 0)
-             || !integer_zerop (TREE_OPERAND (base, 1)))
-           {
-             if (dump_file)
-               {
-                 fprintf (dump_file, "    base mem ref:");
-                 print_generic_expr (dump_file, base, TDF_SLIM);
-                 fprintf (dump_file, " has nonzero offset or does not match instance:");
-                 print_generic_expr (dump_file, tci->instance, TDF_SLIM);
-                 fprintf (dump_file, "\n");
-               }
-             return NULL_TREE;
-           }
-       }
-      else if (!operand_equal_p (tci->instance, base, 0)
-              || tci->offset)
-       {
-         if (dump_file)
-           {
-             fprintf (dump_file, "    base:");
-             print_generic_expr (dump_file, base, TDF_SLIM);
-             fprintf (dump_file, " does not match instance:");
-             print_generic_expr (dump_file, tci->instance, TDF_SLIM);
-             fprintf (dump_file, " with offset %i\n", (int)tci->offset);
-           }
-         return NULL_TREE;
-       }
-    }
-
-  tree vtable;
-  unsigned HOST_WIDE_INT offset2;
-
-  if (!vtable_pointer_value_to_vtable (rhs, &vtable, &offset2))
-    {
-      if (dump_file)
-       fprintf (dump_file, "    Failed to lookup binfo\n");
-      return NULL;
-    }
-
-  tree binfo = subbinfo_with_vtable_at_offset (TYPE_BINFO (DECL_CONTEXT (vtable)),
-                                              offset2, vtable);
-  if (!binfo)
-    {
-      if (dump_file)
-       fprintf (dump_file, "    Construction vtable used\n");
-      /* FIXME: We should suport construction contextes.  */
-      return NULL;
-    }
-  *type_offset = tree_to_shwi (BINFO_OFFSET (binfo)) * BITS_PER_UNIT;
-  return DECL_CONTEXT (vtable);
-}
-
-/* Record dynamic type change of TCI to TYPE.  */
-
-void
-record_known_type (struct type_change_info *tci, tree type, HOST_WIDE_INT offset)
-{
-  if (dump_file)
-    {
-      if (type)
-       {
-          fprintf (dump_file, "  Recording type: ");
-         print_generic_expr (dump_file, type, TDF_SLIM);
-          fprintf (dump_file, " at offset %i\n", (int)offset);
-       }
-     else
-       fprintf (dump_file, "  Recording unknown type\n");
-    }
-
-  /* If we found a constructor of type that is not polymorphic or
-     that may contain the type in question as a field (not as base),
-     restrict to the inner class first to make type matching bellow
-     happier.  */
-  if (type
-      && (offset
-          || (TREE_CODE (type) != RECORD_TYPE
-             || !polymorphic_type_binfo_p (TYPE_BINFO (type)))))
-    {
-      ipa_polymorphic_call_context context;
-
-      context.offset = offset;
-      context.outer_type = type;
-      context.maybe_in_construction = false;
-      context.maybe_derived_type = false;
-      /* If we failed to find the inner type, we know that the call
-        would be undefined for type produced here.  */
-      if (!context.restrict_to_inner_class (tci->otr_type))
-       {
-         if (dump_file)
-           fprintf (dump_file, "  Ignoring; does not contain otr_type\n");
-         return;
-       }
-      /* Watch for case we reached an POD type and anticipate placement
-        new.  */
-      if (!context.maybe_derived_type)
-       {
-          type = context.outer_type;
-          offset = context.offset;
-       }
-    }
-  if (tci->type_maybe_changed
-      && (!types_same_for_odr (type, tci->known_current_type)
-         || offset != tci->known_current_offset))
-    tci->multiple_types_encountered = true;
-  tci->known_current_type = TYPE_MAIN_VARIANT (type);
-  tci->known_current_offset = offset;
-  tci->type_maybe_changed = true;
-}
-
-/* Callback of walk_aliased_vdefs and a helper function for
-   detect_type_change to check whether a particular statement may modify
-   the virtual table pointer, and if possible also determine the new type of
-   the (sub-)object.  It stores its result into DATA, which points to a
-   type_change_info structure.  */
-
-static bool
-check_stmt_for_type_change (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef, void *data)
-{
-  gimple stmt = SSA_NAME_DEF_STMT (vdef);
-  struct type_change_info *tci = (struct type_change_info *) data;
-  tree fn;
-
-  /* If we already gave up, just terminate the rest of walk.  */
-  if (tci->multiple_types_encountered)
-    return true;
-
-  if (is_gimple_call (stmt))
-    {
-      if (gimple_call_flags (stmt) & (ECF_CONST | ECF_PURE))
-       return false;
-
-      /* Check for a constructor call.  */
-      if ((fn = gimple_call_fndecl (stmt)) != NULL_TREE
-         && DECL_CXX_CONSTRUCTOR_P (fn)
-         && TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
-         && gimple_call_num_args (stmt))
-      {
-       tree op = walk_ssa_copies (gimple_call_arg (stmt, 0));
-       tree type = method_class_type (TREE_TYPE (fn));
-       HOST_WIDE_INT offset = 0, size, max_size;
-
-       if (dump_file)
-         {
-           fprintf (dump_file, "  Checking constructor call: ");
-           print_gimple_stmt (dump_file, stmt, 0, 0);
-         }
-
-       /* See if THIS parameter seems like instance pointer.  */
-       if (TREE_CODE (op) == ADDR_EXPR)
-         {
-           op = get_ref_base_and_extent (TREE_OPERAND (op, 0),
-                                         &offset, &size, &max_size);
-           if (size != max_size || max_size == -1)
-             {
-                tci->speculative = true;
-               return false;
-             }
-           if (op && TREE_CODE (op) == MEM_REF)
-             {
-               if (!tree_fits_shwi_p (TREE_OPERAND (op, 1)))
-                 {
-                    tci->speculative = true;
-                   return false;
-                 }
-               offset += tree_to_shwi (TREE_OPERAND (op, 1))
-                         * BITS_PER_UNIT;
-               op = TREE_OPERAND (op, 0);
-             }
-           else if (DECL_P (op))
-             ;
-           else
-             {
-                tci->speculative = true;
-               return false;
-             }
-           op = walk_ssa_copies (op);
-         }
-       if (operand_equal_p (op, tci->instance, 0)
-           && TYPE_SIZE (type)
-           && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
-           && tree_fits_shwi_p (TYPE_SIZE (type))
-           && tree_to_shwi (TYPE_SIZE (type)) + offset > tci->offset)
-         {
-           record_known_type (tci, type, tci->offset - offset);
-           return true;
-         }
-      }
-     /* Calls may possibly change dynamic type by placement new. Assume
-        it will not happen, but make result speculative only.  */
-     if (dump_file)
-       {
-          fprintf (dump_file, "  Function call may change dynamic type:");
-         print_gimple_stmt (dump_file, stmt, 0, 0);
-       }
-     tci->speculative = true;
-     return false;
-   }
-  /* Check for inlined virtual table store.  */
-  else if (noncall_stmt_may_be_vtbl_ptr_store (stmt))
-    {
-      tree type;
-      HOST_WIDE_INT offset = 0;
-      if (dump_file)
-       {
-         fprintf (dump_file, "  Checking vtbl store: ");
-         print_gimple_stmt (dump_file, stmt, 0, 0);
-       }
-
-      type = extr_type_from_vtbl_ptr_store (stmt, tci, &offset);
-      gcc_assert (!type || TYPE_MAIN_VARIANT (type) == type);
-      if (!type)
-       {
-         if (dump_file)
-           fprintf (dump_file, "  Unanalyzed store may change type.\n");
-         tci->seen_unanalyzed_store = true;
-         tci->speculative = true;
-       }
-      else
-        record_known_type (tci, type, offset);
-      return true;
-    }
-  else
-    return false;
-}
-
-/* THIS is polymorphic call context obtained from get_polymorphic_context.
-   OTR_OBJECT is pointer to the instance returned by OBJ_TYPE_REF_OBJECT.
-   INSTANCE is pointer to the outer instance as returned by
-   get_polymorphic_context.  To avoid creation of temporary expressions,
-   INSTANCE may also be an declaration of get_polymorphic_context found the
-   value to be in static storage.
-
-   If the type of instance is not fully determined
-   (either OUTER_TYPE is unknown or MAYBE_IN_CONSTRUCTION/INCLUDE_DERIVED_TYPES
-   is set), try to walk memory writes and find the actual construction of the
-   instance.
-
-   We do not include this analysis in the context analysis itself, because
-   it needs memory SSA to be fully built and the walk may be expensive.
-   So it is not suitable for use withing fold_stmt and similar uses.  */
-
-bool
-ipa_polymorphic_call_context::get_dynamic_type (tree instance,
-                                               tree otr_object,
-                                               tree otr_type,
-                                               gimple call)
-{
-  struct type_change_info tci;
-  ao_ref ao;
-  bool function_entry_reached = false;
-  tree instance_ref = NULL;
-  gimple stmt = call;
-  /* Remember OFFSET before it is modified by restrict_to_inner_class.
-     This is because we do not update INSTANCE when walking inwards.  */
-  HOST_WIDE_INT instance_offset = offset;
-
-  otr_type = TYPE_MAIN_VARIANT (otr_type);
-
-  /* Walk into inner type. This may clear maybe_derived_type and save us
-     from useless work.  It also makes later comparsions with static type
-     easier.  */
-  if (outer_type)
-    {
-      if (!restrict_to_inner_class (otr_type))
-        return false;
-    }
-
-  if (!maybe_in_construction && !maybe_derived_type)
-    return false;
-
-  /* We need to obtain refernce to virtual table pointer.  It is better
-     to look it up in the code rather than build our own.  This require bit
-     of pattern matching, but we end up verifying that what we found is
-     correct. 
-
-     What we pattern match is:
-
-       tmp = instance->_vptr.A;   // vtbl ptr load
-       tmp2 = tmp[otr_token];    // vtable lookup
-       OBJ_TYPE_REF(tmp2;instance->0) (instance);
-     We want to start alias oracle walk from vtbl pointer load,
-     but we may not be able to identify it, for example, when PRE moved the
-     load around.  */
-
-  if (gimple_code (call) == GIMPLE_CALL)
-    {
-      tree ref = gimple_call_fn (call);
-      HOST_WIDE_INT offset2, size, max_size;
-
-      if (TREE_CODE (ref) == OBJ_TYPE_REF)
-       {
-         ref = OBJ_TYPE_REF_EXPR (ref);
-         ref = walk_ssa_copies (ref);
-
-         /* Check if definition looks like vtable lookup.  */
-         if (TREE_CODE (ref) == SSA_NAME
-             && !SSA_NAME_IS_DEFAULT_DEF (ref)
-             && gimple_assign_load_p (SSA_NAME_DEF_STMT (ref))
-             && TREE_CODE (gimple_assign_rhs1
-                            (SSA_NAME_DEF_STMT (ref))) == MEM_REF)
-           {
-             ref = get_base_address
-                    (TREE_OPERAND (gimple_assign_rhs1
-                                    (SSA_NAME_DEF_STMT (ref)), 0));
-             ref = walk_ssa_copies (ref);
-             /* Find base address of the lookup and see if it looks like
-                vptr load.  */
-             if (TREE_CODE (ref) == SSA_NAME
-                 && !SSA_NAME_IS_DEFAULT_DEF (ref)
-                 && gimple_assign_load_p (SSA_NAME_DEF_STMT (ref)))
-               {
-                 tree ref_exp = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (ref));
-                 tree base_ref = get_ref_base_and_extent
-                                  (ref_exp, &offset2, &size, &max_size);
-
-                 /* Finally verify that what we found looks like read from OTR_OBJECT
-                    or from INSTANCE with offset OFFSET.  */
-                 if (base_ref
-                     && ((TREE_CODE (base_ref) == MEM_REF
-                          && ((offset2 == instance_offset
-                               && TREE_OPERAND (base_ref, 0) == instance)
-                              || (!offset2 && TREE_OPERAND (base_ref, 0) == otr_object)))
-                         || (DECL_P (instance) && base_ref == instance
-                             && offset2 == instance_offset)))
-                   {
-                     stmt = SSA_NAME_DEF_STMT (ref);
-                     instance_ref = ref_exp;
-                   }
-               }
-           }
-       }
-    }
-  /* If we failed to look up the refernece in code, build our own.  */
-  if (!instance_ref)
-    {
-      /* If the statement in question does not use memory, we can't tell
-        anything.  */
-      if (!gimple_vuse (stmt))
-       return false;
-      ao_ref_init_from_ptr_and_size (&ao, otr_object, NULL);
-    }
-  else
-  /* Otherwise use the real reference.  */
-    ao_ref_init (&ao, instance_ref);
-
-  /* We look for vtbl pointer read.  */
-  ao.size = POINTER_SIZE;
-  ao.max_size = ao.size;
-  ao.ref_alias_set
-    = get_deref_alias_set (TREE_TYPE (BINFO_VTABLE (TYPE_BINFO (otr_type))));
-
-  if (dump_file)
-    {
-      fprintf (dump_file, "Determining dynamic type for call: ");
-      print_gimple_stmt (dump_file, call, 0, 0);
-      fprintf (dump_file, "  Starting walk at: ");
-      print_gimple_stmt (dump_file, stmt, 0, 0);
-      fprintf (dump_file, "  instance pointer: ");
-      print_generic_expr (dump_file, otr_object, TDF_SLIM);
-      fprintf (dump_file, "  Outer instance pointer: ");
-      print_generic_expr (dump_file, instance, TDF_SLIM);
-      fprintf (dump_file, " offset: %i (bits)", (int)offset);
-      fprintf (dump_file, " vtbl reference: ");
-      print_generic_expr (dump_file, instance_ref, TDF_SLIM);
-      fprintf (dump_file, "\n");
-    }
-
-  tci.offset = offset;
-  tci.instance = instance;
-  tci.vtbl_ptr_ref = instance_ref;
-  gcc_assert (TREE_CODE (instance) != MEM_REF);
-  tci.known_current_type = NULL_TREE;
-  tci.known_current_offset = 0;
-  tci.otr_type = otr_type;
-  tci.type_maybe_changed = false;
-  tci.multiple_types_encountered = false;
-  tci.speculative = false;
-  tci.seen_unanalyzed_store = false;
-
-  walk_aliased_vdefs (&ao, gimple_vuse (stmt), check_stmt_for_type_change,
-                     &tci, NULL, &function_entry_reached);
-
-  /* If we did not find any type changing statements, we may still drop
-     maybe_in_construction flag if the context already have outer type. 
-
-     Here we make special assumptions about both constructors and
-     destructors which are all the functions that are allowed to alter the
-     VMT pointers.  It assumes that destructors begin with assignment into
-     all VMT pointers and that constructors essentially look in the
-     following way:
-
-     1) The very first thing they do is that they call constructors of
-     ancestor sub-objects that have them.
-
-     2) Then VMT pointers of this and all its ancestors is set to new
-     values corresponding to the type corresponding to the constructor.
-
-     3) Only afterwards, other stuff such as constructor of member
-     sub-objects and the code written by the user is run.  Only this may
-     include calling virtual functions, directly or indirectly.
-
-     4) placement new can not be used to change type of non-POD statically
-     allocated variables.
-
-     There is no way to call a constructor of an ancestor sub-object in any
-     other way.
-
-     This means that we do not have to care whether constructors get the
-     correct type information because they will always change it (in fact,
-     if we define the type to be given by the VMT pointer, it is undefined).
-
-     The most important fact to derive from the above is that if, for some
-     statement in the section 3, we try to detect whether the dynamic type
-     has changed, we can safely ignore all calls as we examine the function
-     body backwards until we reach statements in section 2 because these
-     calls cannot be ancestor constructors or destructors (if the input is
-     not bogus) and so do not change the dynamic type (this holds true only
-     for automatically allocated objects but at the moment we devirtualize
-     only these).  We then must detect that statements in section 2 change
-     the dynamic type and can try to derive the new type.  That is enough
-     and we can stop, we will never see the calls into constructors of
-     sub-objects in this code. 
-
-     Therefore if the static outer type was found (outer_type)
-     we can safely ignore tci.speculative that is set on calls and give up
-     only if there was dyanmic type store that may affect given variable
-     (seen_unanalyzed_store)  */
-
-  if (!tci.type_maybe_changed
-      || (outer_type
-         && !tci.seen_unanalyzed_store
-         && !tci.multiple_types_encountered
-         && offset == tci.offset
-         && types_same_for_odr (tci.known_current_type,
-                                outer_type)))
-    {
-      if (!outer_type || tci.seen_unanalyzed_store)
-       return false;
-      if (maybe_in_construction)
-        maybe_in_construction = false;
-      if (dump_file)
-       fprintf (dump_file, "  No dynamic type change found.\n");
-      return true;
-    }
-
-  if (tci.known_current_type
-      && !function_entry_reached
-      && !tci.multiple_types_encountered)
-    {
-      if (!tci.speculative)
-       {
-         outer_type = TYPE_MAIN_VARIANT (tci.known_current_type);
-         offset = tci.known_current_offset;
-         maybe_in_construction = false;
-         maybe_derived_type = false;
-         if (dump_file)
-           fprintf (dump_file, "  Determined dynamic type.\n");
-       }
-      else if (!speculative_outer_type
-              || speculative_maybe_derived_type)
-       {
-         speculative_outer_type = TYPE_MAIN_VARIANT (tci.known_current_type);
-         speculative_offset = tci.known_current_offset;
-         speculative_maybe_derived_type = false;
-         if (dump_file)
-           fprintf (dump_file, "  Determined speculative dynamic type.\n");
-       }
-    }
-  else if (dump_file)
-    {
-      fprintf (dump_file, "  Found multiple types%s%s\n",
-              function_entry_reached ? " (function entry reached)" : "",
-              function_entry_reached ? " (multiple types encountered)" : "");
-    }
-
-  return true;
-}
-
-/* Walk bases of OUTER_TYPE that contain OTR_TYPE at OFFSET.
-   Lookup their respecitve virtual methods for OTR_TOKEN and OTR_TYPE
-   and insert them to NODES.
-
-   MATCHED_VTABLES and INSERTED is used to avoid duplicated work.  */
-
-static void
-record_targets_from_bases (tree otr_type,
-                          HOST_WIDE_INT otr_token,
-                          tree outer_type,
-                          HOST_WIDE_INT offset,
-                          vec <cgraph_node *> &nodes,
-                          hash_set<tree> *inserted,
-                          hash_set<tree> *matched_vtables,
-                          bool *completep)
-{
-  while (true)
-    {
-      HOST_WIDE_INT pos, size;
-      tree base_binfo;
-      tree fld;
-
-      if (types_same_for_odr (outer_type, otr_type))
-       return;
-
-      for (fld = TYPE_FIELDS (outer_type); fld; fld = DECL_CHAIN (fld))
-       {
-         if (TREE_CODE (fld) != FIELD_DECL)
-           continue;
-
-         pos = int_bit_position (fld);
-         size = tree_to_shwi (DECL_SIZE (fld));
-         if (pos <= offset && (pos + size) > offset
-             /* Do not get confused by zero sized bases.  */
-             && polymorphic_type_binfo_p (TYPE_BINFO (TREE_TYPE (fld))))
-           break;
-       }
-      /* Within a class type we should always find correcponding fields.  */
-      gcc_assert (fld && TREE_CODE (TREE_TYPE (fld)) == RECORD_TYPE);
-
-      /* Nonbasetypes should have been stripped by outer_class_type.  */
-      gcc_assert (DECL_ARTIFICIAL (fld));
+      /* Nonbase types should have been stripped by outer_class_type.  */
+      gcc_assert (DECL_ARTIFICIAL (fld));
 
       outer_type = TREE_TYPE (fld);
       offset -= pos;
@@ -3397,25 +3023,20 @@ struct final_warning_record
 struct final_warning_record *final_warning_records;
 
 /* Return vector containing possible targets of polymorphic call of type
-   OTR_TYPE caling method OTR_TOKEN within type of OTR_OUTER_TYPE and OFFSET.
-   If INCLUDE_BASES is true, walk also base types of OUTER_TYPES containig
+   OTR_TYPE calling method OTR_TOKEN within type of OTR_OUTER_TYPE and OFFSET.
+   If INCLUDE_BASES is true, walk also base types of OUTER_TYPES containing
    OTR_TYPE and include their virtual method.  This is useful for types
    possibly in construction or destruction where the virtual table may
    temporarily change to one of base types.  INCLUDE_DERIVER_TYPES make
    us to walk the inheritance graph for all derivations.
 
-   OTR_TOKEN == INT_MAX is used to mark calls that are provably
-   undefined and should be redirected to unreachable.
-
    If COMPLETEP is non-NULL, store true if the list is complete. 
    CACHE_TOKEN (if non-NULL) will get stored to an unique ID of entry
    in the target cache.  If user needs to visit every target list
    just once, it can memoize them.
 
-   SPECULATION_TARGETS specify number of targets that are speculatively
-   likely.  These include targets specified by the speculative part
-   of polymoprhic call context and also exclude all targets for classes
-   in construction.
+   If SPECULATIVE is set, the list will not contain targets that
+   are not speculatively taken.
 
    Returned vector is placed into cache.  It is NOT caller's responsibility
    to free it.  The vector can be freed on cgraph_remove_node call if
@@ -3427,68 +3048,55 @@ possible_polymorphic_call_targets (tree otr_type,
                                   ipa_polymorphic_call_context context,
                                   bool *completep,
                                   void **cache_token,
-                                  int *speculative_targetsp)
+                                  bool speculative)
 {
   static struct cgraph_node_hook_list *node_removal_hook_holder;
   vec <cgraph_node *> nodes = vNULL;
-  vec <tree> bases_to_consider = vNULL;
+  auto_vec <tree, 8> bases_to_consider;
   odr_type type, outer_type;
   polymorphic_call_target_d key;
   polymorphic_call_target_d **slot;
   unsigned int i;
   tree binfo, target;
   bool complete;
-  bool can_refer;
+  bool can_refer = false;
   bool skipped = false;
 
   otr_type = TYPE_MAIN_VARIANT (otr_type);
 
-  /* If ODR is not initialized, return empty incomplete list.  */
-  if (!odr_hash)
-    {
-      if (completep)
-       *completep = false;
-      if (cache_token)
-       *cache_token = NULL;
-      if (speculative_targetsp)
-       *speculative_targetsp = 0;
-      return nodes;
-    }
-
-  /* If we hit type inconsistency, just return empty list of targets.  */
-  if (otr_token == INT_MAX)
+  /* If ODR is not initialized or the context is invalid, return empty
+     incomplete list.  */
+  if (!odr_hash || context.invalid || !TYPE_BINFO (otr_type))
     {
       if (completep)
-       *completep = true;
+       *completep = context.invalid;
       if (cache_token)
        *cache_token = NULL;
-      if (speculative_targetsp)
-       *speculative_targetsp = 0;
       return nodes;
     }
 
   /* Do not bother to compute speculative info when user do not asks for it.  */
-  if (!speculative_targetsp || !context.speculative_outer_type)
+  if (!speculative || !context.speculative_outer_type)
     context.clear_speculation ();
 
   type = get_odr_type (otr_type, true);
 
-  /* Recording type variants would wast results cache.  */
+  /* Recording type variants would waste results cache.  */
   gcc_assert (!context.outer_type
              || TYPE_MAIN_VARIANT (context.outer_type) == context.outer_type);
 
-  /* Lookup the outer class type we want to walk.  */
+  /* Look up the outer class type we want to walk.
+     If we fail to do so, the context is invalid.  */
   if ((context.outer_type || context.speculative_outer_type)
       && !context.restrict_to_inner_class (otr_type))
     {
       if (completep)
-       *completep = false;
+       *completep = true;
       if (cache_token)
        *cache_token = NULL;
-      if (speculative_targetsp)
-       *speculative_targetsp = 0;
       return nodes;
     }
+  gcc_assert (!context.invalid);
 
   /* Check that restrict_to_inner_class kept the main variant.  */
   gcc_assert (!context.outer_type
@@ -3497,13 +3105,10 @@ possible_polymorphic_call_targets (tree otr_type,
   /* We canonicalize our query, so we do not need extra hashtable entries.  */
 
   /* Without outer type, we have no use for offset.  Just do the
-     basic search from innter type  */
+     basic search from inner type.  */
   if (!context.outer_type)
-    {
-      context.outer_type = otr_type;
-      context.offset = 0;
-    }
-  /* We need to update our hiearchy if the type does not exist.  */
+    context.clear_outer_type (otr_type);
+  /* We need to update our hierarchy if the type does not exist.  */
   outer_type = get_odr_type (context.outer_type, true);
   /* If the type is complete, there are no derivations.  */
   if (TYPE_FINAL_P (outer_type->type))
@@ -3524,9 +3129,20 @@ possible_polymorphic_call_targets (tree otr_type,
        }
     }
 
-  /* Lookup cached answer.  */
+  if (in_lto_p)
+    {
+      if (context.outer_type != otr_type)
+        context.outer_type
+         = get_odr_type (context.outer_type, true)->type;
+      if (context.speculative_outer_type)
+        context.speculative_outer_type
+         = get_odr_type (context.speculative_outer_type, true)->type;
+    }
+
+  /* Look up cached answer.  */
   key.type = type;
   key.otr_token = otr_token;
+  key.speculative = speculative;
   key.context = context;
   slot = polymorphic_call_target_hash->find_slot (&key, INSERT);
   if (cache_token)
@@ -3535,15 +3151,13 @@ possible_polymorphic_call_targets (tree otr_type,
     {
       if (completep)
        *completep = (*slot)->complete;
-      if (speculative_targetsp)
-       *speculative_targetsp = (*slot)->speculative_targets;
       if ((*slot)->type_warning && final_warning_records)
        {
          final_warning_records->type_warnings[(*slot)->type_warning - 1].count++;
          final_warning_records->type_warnings[(*slot)->type_warning - 1].dyn_count
            += final_warning_records->dyn_count;
        }
-      if ((*slot)->decl_warning && final_warning_records)
+      if (!speculative && (*slot)->decl_warning && final_warning_records)
        {
          struct decl_warn_count *c =
             final_warning_records->decl_warnings.get ((*slot)->decl_warning);
@@ -3563,7 +3177,7 @@ possible_polymorphic_call_targets (tree otr_type,
   (*slot)->type = type;
   (*slot)->otr_token = otr_token;
   (*slot)->context = context;
-  (*slot)->speculative_targets = 0;
+  (*slot)->speculative = speculative;
 
   hash_set<tree> inserted;
   hash_set<tree> matched_vtables;
@@ -3574,7 +3188,8 @@ possible_polymorphic_call_targets (tree otr_type,
       odr_type speculative_outer_type;
       bool speculation_complete = true;
 
-      /* First insert target from type itself and check if it may have derived types.  */
+      /* First insert target from type itself and check if it may have
+        derived types.  */
       speculative_outer_type = get_odr_type (context.speculative_outer_type, true);
       if (TYPE_FINAL_P (speculative_outer_type->type))
        context.speculative_maybe_derived_type = false;
@@ -3608,140 +3223,135 @@ possible_polymorphic_call_targets (tree otr_type,
                                               &speculation_complete,
                                               bases_to_consider,
                                               false);
-      (*slot)->speculative_targets = nodes.length();
     }
 
-  /* First see virtual method of type itself.  */
-  binfo = get_binfo_at_offset (TYPE_BINFO (outer_type->type),
-                              context.offset, otr_type);
-  if (binfo)
-    target = gimple_get_virt_method_for_binfo (otr_token, binfo,
-                                              &can_refer);
-  else
+  if (!speculative || !nodes.length ())
     {
-      gcc_assert (odr_violation_reported);
-      target = NULL;
-    }
+      /* First see virtual method of type itself.  */
+      binfo = get_binfo_at_offset (TYPE_BINFO (outer_type->type),
+                                  context.offset, otr_type);
+      if (binfo)
+       target = gimple_get_virt_method_for_binfo (otr_token, binfo,
+                                                  &can_refer);
+      else
+       {
+         gcc_assert (odr_violation_reported);
+         target = NULL;
+       }
 
-  /* Destructors are never called through construction virtual tables,
-     because the type is always known.  */
-  if (target && DECL_CXX_DESTRUCTOR_P (target))
-    context.maybe_in_construction = false;
+      /* Destructors are never called through construction virtual tables,
+        because the type is always known.  */
+      if (target && DECL_CXX_DESTRUCTOR_P (target))
+       context.maybe_in_construction = false;
 
-  if (target)
-    {
-      /* In the case we get complete method, we don't need 
-        to walk derivations.  */
-      if (DECL_FINAL_P (target))
-       context.maybe_derived_type = false;
-    }
+      if (target)
+       {
+         /* In the case we get complete method, we don't need 
+            to walk derivations.  */
+         if (DECL_FINAL_P (target))
+           context.maybe_derived_type = false;
+       }
 
-  /* If OUTER_TYPE is abstract, we know we are not seeing its instance.  */
-  if (type_possibly_instantiated_p (outer_type->type))
-    maybe_record_node (nodes, target, &inserted, can_refer, &complete);
-  else
-    {
-      skipped = true;
-      gcc_assert (in_lto_p || context.maybe_derived_type);
-    }
+      /* If OUTER_TYPE is abstract, we know we are not seeing its instance.  */
+      if (type_possibly_instantiated_p (outer_type->type))
+       maybe_record_node (nodes, target, &inserted, can_refer, &complete);
+      else
+       skipped = true;
 
-  if (binfo)
-    matched_vtables.add (BINFO_VTABLE (binfo));
+      if (binfo)
+       matched_vtables.add (BINFO_VTABLE (binfo));
 
-  /* Next walk recursively all derived types.  */
-  if (context.maybe_derived_type)
-    {
-      for (i = 0; i < outer_type->derived_types.length(); i++)
-       possible_polymorphic_call_targets_1 (nodes, &inserted,
-                                            &matched_vtables,
-                                            otr_type,
-                                            outer_type->derived_types[i],
-                                            otr_token, outer_type->type,
-                                            context.offset, &complete,
-                                            bases_to_consider,
-                                            context.maybe_in_construction);
-
-      if (!outer_type->all_derivations_known)
+      /* Next walk recursively all derived types.  */
+      if (context.maybe_derived_type)
        {
-         if (final_warning_records)
+         for (i = 0; i < outer_type->derived_types.length(); i++)
+           possible_polymorphic_call_targets_1 (nodes, &inserted,
+                                                &matched_vtables,
+                                                otr_type,
+                                                outer_type->derived_types[i],
+                                                otr_token, outer_type->type,
+                                                context.offset, &complete,
+                                                bases_to_consider,
+                                                context.maybe_in_construction);
+
+         if (!outer_type->all_derivations_known)
            {
-             if (complete
-                 && nodes.length () == 1
-                 && warn_suggest_final_types
-                 && !outer_type->derived_types.length ())
-               {
-                 if (outer_type->id >= (int)final_warning_records->type_warnings.length ())
-                   final_warning_records->type_warnings.safe_grow_cleared
-                     (odr_types.length ());
-                 final_warning_records->type_warnings[outer_type->id].count++;
-                 final_warning_records->type_warnings[outer_type->id].dyn_count
-                   += final_warning_records->dyn_count;
-                 final_warning_records->type_warnings[outer_type->id].type
-                   = outer_type->type;
-                 (*slot)->type_warning = outer_type->id + 1;
-               }
-             if (complete
-                 && warn_suggest_final_methods
-                 && nodes.length () == 1
-                 && types_same_for_odr (DECL_CONTEXT (nodes[0]->decl),
-                                        outer_type->type))
+             if (!speculative && final_warning_records)
                {
-                 bool existed;
-                 struct decl_warn_count &c =
-                    final_warning_records->decl_warnings.get_or_insert
-                       (nodes[0]->decl, &existed);
-
-                 if (existed)
+                 if (complete
+                     && nodes.length () == 1
+                     && warn_suggest_final_types
+                     && !outer_type->derived_types.length ())
                    {
-                     c.count++;
-                     c.dyn_count += final_warning_records->dyn_count;
+                     if (outer_type->id >= (int)final_warning_records->type_warnings.length ())
+                       final_warning_records->type_warnings.safe_grow_cleared
+                         (odr_types.length ());
+                     final_warning_records->type_warnings[outer_type->id].count++;
+                     final_warning_records->type_warnings[outer_type->id].dyn_count
+                       += final_warning_records->dyn_count;
+                     final_warning_records->type_warnings[outer_type->id].type
+                       = outer_type->type;
+                     (*slot)->type_warning = outer_type->id + 1;
                    }
-                 else
+                 if (complete
+                     && warn_suggest_final_methods
+                     && nodes.length () == 1
+                     && types_same_for_odr (DECL_CONTEXT (nodes[0]->decl),
+                                            outer_type->type))
                    {
-                     c.count = 1;
-                     c.dyn_count = final_warning_records->dyn_count;
-                     c.decl = nodes[0]->decl;
+                     bool existed;
+                     struct decl_warn_count &c =
+                        final_warning_records->decl_warnings.get_or_insert
+                           (nodes[0]->decl, &existed);
+
+                     if (existed)
+                       {
+                         c.count++;
+                         c.dyn_count += final_warning_records->dyn_count;
+                       }
+                     else
+                       {
+                         c.count = 1;
+                         c.dyn_count = final_warning_records->dyn_count;
+                         c.decl = nodes[0]->decl;
+                       }
+                     (*slot)->decl_warning = nodes[0]->decl;
                    }
-                 (*slot)->decl_warning = nodes[0]->decl;
                }
+             complete = false;
            }
-         complete = false;
        }
-    }
-
-  /* Finally walk bases, if asked to.  */
-  if (!(*slot)->speculative_targets)
-    (*slot)->speculative_targets = nodes.length();
 
-  /* Destructors are never called through construction virtual tables,
-     because the type is always known.  One of entries may be cxa_pure_virtual
-     so look to at least two of them.  */
-  if (context.maybe_in_construction)
-    for (i =0 ; i < MIN (nodes.length (), 2); i++)
-      if (DECL_CXX_DESTRUCTOR_P (nodes[i]->decl))
-       context.maybe_in_construction = false;
-  if (context.maybe_in_construction)
-    {
-      if (type != outer_type
-         && (!skipped
-             || (context.maybe_derived_type
-                 && !type_all_derivations_known_p (outer_type->type))))
-       record_targets_from_bases (otr_type, otr_token, outer_type->type,
-                                  context.offset, nodes, &inserted,
-                                  &matched_vtables, &complete);
-      if (skipped)
-        maybe_record_node (nodes, target, &inserted, can_refer, &complete);
-      for (i = 0; i < bases_to_consider.length(); i++)
-        maybe_record_node (nodes, bases_to_consider[i], &inserted, can_refer, &complete);
+      if (!speculative)
+       {
+         /* Destructors are never called through construction virtual tables,
+            because the type is always known.  One of entries may be
+            cxa_pure_virtual so look to at least two of them.  */
+         if (context.maybe_in_construction)
+           for (i =0 ; i < MIN (nodes.length (), 2); i++)
+             if (DECL_CXX_DESTRUCTOR_P (nodes[i]->decl))
+               context.maybe_in_construction = false;
+         if (context.maybe_in_construction)
+           {
+             if (type != outer_type
+                 && (!skipped
+                     || (context.maybe_derived_type
+                         && !type_all_derivations_known_p (outer_type->type))))
+               record_targets_from_bases (otr_type, otr_token, outer_type->type,
+                                          context.offset, nodes, &inserted,
+                                          &matched_vtables, &complete);
+             if (skipped)
+               maybe_record_node (nodes, target, &inserted, can_refer, &complete);
+             for (i = 0; i < bases_to_consider.length(); i++)
+               maybe_record_node (nodes, bases_to_consider[i], &inserted, can_refer, &complete);
+           }
+       }
     }
-  bases_to_consider.release();
 
   (*slot)->targets = nodes;
   (*slot)->complete = complete;
   if (completep)
     *completep = complete;
-  if (speculative_targetsp)
-    *speculative_targetsp = (*slot)->speculative_targets;
 
   timevar_pop (TV_IPA_VIRTUAL_CALL);
   return nodes;
@@ -3755,6 +3365,29 @@ add_decl_warning (const tree &key ATTRIBUTE_UNUSED, const decl_warn_count &value
   return true;
 }
 
+/* Dump target list TARGETS into FILE.  */
+
+static void
+dump_targets (FILE *f, vec <cgraph_node *> targets)
+{
+  unsigned int i;
+
+  for (i = 0; i < targets.length (); i++)
+    {
+      char *name = NULL;
+      if (in_lto_p)
+       name = cplus_demangle_v3 (targets[i]->asm_name (), 0);
+      fprintf (f, " %s/%i", name ? name : targets[i]->name (), targets[i]->order);
+      if (in_lto_p)
+       free (name);
+      if (!targets[i]->definition)
+       fprintf (f, " (no definition%s)",
+                DECL_DECLARED_INLINE_P (targets[i]->decl)
+                ? " inline" : "");
+    }
+  fprintf (f, "\n");
+}
+
 /* Dump all possible targets of a polymorphic call.  */
 
 void
@@ -3766,31 +3399,18 @@ dump_possible_polymorphic_call_targets (FILE *f,
   vec <cgraph_node *> targets;
   bool final;
   odr_type type = get_odr_type (TYPE_MAIN_VARIANT (otr_type), false);
-  unsigned int i;
-  int speculative;
+  unsigned int len;
 
   if (!type)
     return;
   targets = possible_polymorphic_call_targets (otr_type, otr_token,
                                               ctx,
-                                              &final, NULL, &speculative);
+                                              &final, NULL, false);
   fprintf (f, "  Targets of polymorphic call of type %i:", type->id);
   print_generic_expr (f, type->type, TDF_SLIM);
   fprintf (f, " token %i\n", (int)otr_token);
-  if (ctx.outer_type || ctx.offset)
-    {
-      fprintf (f, "    Contained in type:");
-      print_generic_expr (f, ctx.outer_type, TDF_SLIM);
-      fprintf (f, " at offset "HOST_WIDE_INT_PRINT_DEC"\n",
-              ctx.offset);
-    }
-  if (ctx.speculative_outer_type)
-    {
-      fprintf (f, "    Speculatively contained in type:");
-      print_generic_expr (f, ctx.speculative_outer_type, TDF_SLIM);
-      fprintf (f, " at offset "HOST_WIDE_INT_PRINT_DEC"\n",
-              ctx.speculative_offset);
-    }
+
+  ctx.dump (f);
 
   fprintf (f, "    %s%s%s%s\n      ",
           final ? "This is a complete list." :
@@ -3798,23 +3418,19 @@ dump_possible_polymorphic_call_targets (FILE *f,
           ctx.maybe_in_construction ? " (base types included)" : "",
           ctx.maybe_derived_type ? " (derived types included)" : "",
           ctx.speculative_maybe_derived_type ? " (speculative derived types included)" : "");
-  for (i = 0; i < targets.length (); i++)
+  len = targets.length ();
+  dump_targets (f, targets);
+
+  targets = possible_polymorphic_call_targets (otr_type, otr_token,
+                                              ctx,
+                                              &final, NULL, true);
+  if (targets.length () != len)
     {
-      char *name = NULL;
-      if (i == (unsigned)speculative)
-       fprintf (f, "\n     Targets that are not likely:\n"
-                "      ");
-      if (in_lto_p)
-       name = cplus_demangle_v3 (targets[i]->asm_name (), 0);
-      fprintf (f, " %s/%i", name ? name : targets[i]->name (), targets[i]->order);
-      if (in_lto_p)
-       free (name);
-      if (!targets[i]->definition)
-       fprintf (f, " (no definition%s)",
-                DECL_DECLARED_INLINE_P (targets[i]->decl)
-                ? " inline" : "");
+      fprintf (f, "  Speculative targets:");
+      dump_targets (f, targets);
     }
-  fprintf (f, "\n\n");
+  gcc_assert (targets.length () <= len);
+  fprintf (f, "\n");
 }
 
 
@@ -3853,6 +3469,26 @@ possible_polymorphic_call_target_p (tree otr_type,
 }
 
 
+
+/* Return true if N can be possibly target of a polymorphic call of
+   OBJ_TYPE_REF expression REF in STMT.  */
+
+bool
+possible_polymorphic_call_target_p (tree ref,
+                                   gimple stmt,
+                                   struct cgraph_node *n)
+{
+  ipa_polymorphic_call_context context (current_function_decl, ref, stmt);
+  tree call_fn = gimple_call_fn (stmt);
+
+  return possible_polymorphic_call_target_p (obj_type_ref_class (call_fn),
+                                            tree_to_uhwi
+                                              (OBJ_TYPE_REF_TOKEN (call_fn)),
+                                            context,
+                                            n);
+}
+
+
 /* After callgraph construction new external nodes may appear.
    Add them into the graph.  */
 
@@ -3871,8 +3507,7 @@ update_type_inheritance_graph (void)
     if (DECL_VIRTUAL_P (n->decl)
        && !n->definition
        && n->real_symbol_p ())
-      get_odr_type (method_class_type (TYPE_MAIN_VARIANT (TREE_TYPE (n->decl))),
-                                      true);
+      get_odr_type (TYPE_METHOD_BASETYPE (TREE_TYPE (n->decl)), true);
   timevar_pop (TV_IPA_INHERITANCE);
 }
 
@@ -3896,16 +3531,16 @@ likely_target_p (struct cgraph_node *n)
     return false;
   if (n->frequency < NODE_FREQUENCY_NORMAL)
     return false;
-  /* If there are no virtual tables refering the target alive,
-     the only way the target can be called is an instance comming from other
-     compilation unit; speculative devirtualization is build around an
+  /* If there are no live virtual tables referring the target,
+     the only way the target can be called is an instance coming from other
+     compilation unit; speculative devirtualization is built around an
      assumption that won't happen.  */
   if (!referenced_from_vtable_p (n))
     return false;
   return true;
 }
 
-/* Compare type warning records P1 and P2 and chose one with larger count;
+/* Compare type warning records P1 and P2 and choose one with larger count;
    helper for qsort.  */
 
 int
@@ -3921,7 +3556,7 @@ type_warning_cmp (const void *p1, const void *p2)
   return t2->count - t1->count;
 }
 
-/* Compare decl warning records P1 and P2 and chose one with larger count;
+/* Compare decl warning records P1 and P2 and choose one with larger count;
    helper for qsort.  */
 
 int
@@ -3937,9 +3572,46 @@ decl_warning_cmp (const void *p1, const void *p2)
   return t2->count - t1->count;
 }
 
+
+/* Try to speculatively devirtualize call to OTR_TYPE with OTR_TOKEN with
+   context CTX.  */
+
+struct cgraph_node *
+try_speculative_devirtualization (tree otr_type, HOST_WIDE_INT otr_token,
+                                 ipa_polymorphic_call_context ctx)
+{
+  vec <cgraph_node *>targets
+     = possible_polymorphic_call_targets
+         (otr_type, otr_token, ctx, NULL, NULL, true);
+  unsigned int i;
+  struct cgraph_node *likely_target = NULL;
+
+  for (i = 0; i < targets.length (); i++)
+    if (likely_target_p (targets[i]))
+      {
+       if (likely_target)
+         return NULL;
+       likely_target = targets[i];
+      }
+  if (!likely_target
+      ||!likely_target->definition
+      || DECL_EXTERNAL (likely_target->decl))
+    return NULL;
+
+  /* Don't use an implicitly-declared destructor (c++/58678).  */
+  struct cgraph_node *non_thunk_target
+    = likely_target->function_symbol ();
+  if (DECL_ARTIFICIAL (non_thunk_target->decl))
+    return NULL;
+  if (likely_target->get_availability () <= AVAIL_INTERPOSABLE
+      && likely_target->can_be_discarded_p ())
+    return NULL;
+  return likely_target;
+}
+
 /* The ipa-devirt pass.
    When polymorphic call has only one likely target in the unit,
-   turn it into speculative call.  */
+   turn it into speculative call.  */
 
 static unsigned int
 ipa_devirt (void)
@@ -3951,6 +3623,13 @@ ipa_devirt (void)
   int npolymorphic = 0, nspeculated = 0, nconverted = 0, ncold = 0;
   int nmultiple = 0, noverwritable = 0, ndevirtualized = 0, nnotdefined = 0;
   int nwrong = 0, nok = 0, nexternal = 0, nartificial = 0;
+  int ndropped = 0;
+
+  if (!odr_types_ptr)
+    return 0;
+
+  if (dump_file)
+    dump_type_inheritance_graph (dump_file);
 
   /* We can output -Wsuggest-final-methods and -Wsuggest-final-types warnings.
      This is implemented by setting up final_warning_records that are updated
@@ -3968,6 +3647,8 @@ ipa_devirt (void)
   FOR_EACH_DEFINED_FUNCTION (n)
     {  
       bool update = false;
+      if (!opt_for_fn (n->decl, flag_devirtualize))
+       continue;
       if (dump_file && n->indirect_calls)
        fprintf (dump_file, "\n\nProcesing function %s/%i\n",
                 n->name (), n->order);
@@ -3977,23 +3658,48 @@ ipa_devirt (void)
            struct cgraph_node *likely_target = NULL;
            void *cache_token;
            bool final;
-           int speculative_targets;
 
            if (final_warning_records)
              final_warning_records->dyn_count = e->count;
 
            vec <cgraph_node *>targets
               = possible_polymorphic_call_targets
-                   (e, &final, &cache_token, &speculative_targets);
+                   (e, &final, &cache_token, true);
            unsigned int i;
 
+           /* Trigger warnings by calculating non-speculative targets.  */
+           if (warn_suggest_final_methods || warn_suggest_final_types)
+             possible_polymorphic_call_targets (e);
+
            if (dump_file)
              dump_possible_polymorphic_call_targets 
                (dump_file, e);
 
            npolymorphic++;
 
-           if (!flag_devirtualize_speculatively)
+           /* See if the call can be devirtualized by means of ipa-prop's
+              polymorphic call context propagation.  If not, we can just
+              forget about this call being polymorphic and avoid some heavy
+              lifting in remove_unreachable_nodes that will otherwise try to
+              keep all possible targets alive until inlining and in the inliner
+              itself.
+
+              This may need to be revisited once we add further ways to use
+              the may edges, but it is a resonable thing to do right now.  */
+
+           if ((e->indirect_info->param_index == -1
+               || (!opt_for_fn (n->decl, flag_devirtualize_speculatively)
+                   && e->indirect_info->vptr_changed))
+               && !flag_ltrans_devirtualize)
+             {
+               e->indirect_info->polymorphic = false;
+               ndropped++;
+               if (dump_file)
+                 fprintf (dump_file, "Dropping polymorphic call info;"
+                          " it can not be used by ipa-prop\n");
+             }
+
+           if (!opt_for_fn (n->decl, flag_devirtualize_speculatively))
              continue;
 
            if (!e->maybe_hot_p ())
@@ -4006,7 +3712,7 @@ ipa_devirt (void)
            if (e->speculative)
              {
                if (dump_file)
-                 fprintf (dump_file, "Call is aready speculated\n\n");
+                 fprintf (dump_file, "Call is already speculated\n\n");
                nspeculated++;
 
                /* When dumping see if we agree with speculation.  */
@@ -4025,13 +3731,10 @@ ipa_devirt (void)
                {
                  if (likely_target)
                    {
-                     if (i < (unsigned) speculative_targets)
-                       {
-                         likely_target = NULL;
-                         if (dump_file)
-                           fprintf (dump_file, "More than one likely target\n\n");
-                         nmultiple++;
-                       }
+                     likely_target = NULL;
+                     if (dump_file)
+                       fprintf (dump_file, "More than one likely target\n\n");
+                     nmultiple++;
                      break;
                    }
                  likely_target = targets[i];
@@ -4064,7 +3767,7 @@ ipa_devirt (void)
            if (!likely_target->definition)
              {
                if (dump_file)
-                 fprintf (dump_file, "Target is not an definition\n\n");
+                 fprintf (dump_file, "Target is not a definition\n\n");
                nnotdefined++;
                continue;
              }
@@ -4134,12 +3837,31 @@ ipa_devirt (void)
            if (final_warning_records->type_warnings[i].count)
              {
                tree type = final_warning_records->type_warnings[i].type;
-               warning_at (DECL_SOURCE_LOCATION (TYPE_NAME (type)),
-                           OPT_Wsuggest_final_types,
-                           "Declaring type %qD final "
-                           "would enable devirtualization of %i calls",
-                           type,
-                           final_warning_records->type_warnings[i].count);
+               int count = final_warning_records->type_warnings[i].count;
+               long long dyn_count
+                 = final_warning_records->type_warnings[i].dyn_count;
+
+               if (!dyn_count)
+                 warning_n (DECL_SOURCE_LOCATION (TYPE_NAME (type)),
+                            OPT_Wsuggest_final_types, count,
+                            "Declaring type %qD final "
+                            "would enable devirtualization of %i call",
+                            "Declaring type %qD final "
+                            "would enable devirtualization of %i calls",
+                            type,
+                            count);
+               else
+                 warning_n (DECL_SOURCE_LOCATION (TYPE_NAME (type)),
+                            OPT_Wsuggest_final_types, count,
+                            "Declaring type %qD final "
+                            "would enable devirtualization of %i call "
+                            "executed %lli times",
+                            "Declaring type %qD final "
+                            "would enable devirtualization of %i calls "
+                            "executed %lli times",
+                            type,
+                            count,
+                            dyn_count);
              }
        }
 
@@ -4154,19 +3876,45 @@ ipa_devirt (void)
            {
              tree decl = decl_warnings_vec[i]->decl;
              int count = decl_warnings_vec[i]->count;
-
-             if (DECL_CXX_DESTRUCTOR_P (decl))
-               warning_at (DECL_SOURCE_LOCATION (decl),
-                           OPT_Wsuggest_final_methods,
-                           "Declaring virtual destructor of %qD final "
-                           "would enable devirtualization of %i calls",
-                           DECL_CONTEXT (decl), count);
-             else
-               warning_at (DECL_SOURCE_LOCATION (decl),
-                           OPT_Wsuggest_final_methods,
-                           "Declaring method %qD final "
-                           "would enable devirtualization of %i calls",
-                           decl, count);
+             long long dyn_count = decl_warnings_vec[i]->dyn_count;
+
+             if (!dyn_count)
+               if (DECL_CXX_DESTRUCTOR_P (decl))
+                 warning_n (DECL_SOURCE_LOCATION (decl),
+                             OPT_Wsuggest_final_methods, count,
+                             "Declaring virtual destructor of %qD final "
+                             "would enable devirtualization of %i call",
+                             "Declaring virtual destructor of %qD final "
+                             "would enable devirtualization of %i calls",
+                             DECL_CONTEXT (decl), count);
+               else
+                 warning_n (DECL_SOURCE_LOCATION (decl),
+                             OPT_Wsuggest_final_methods, count,
+                             "Declaring method %qD final "
+                             "would enable devirtualization of %i call",
+                             "Declaring method %qD final "
+                             "would enable devirtualization of %i calls",
+                             decl, count);
+              else if (DECL_CXX_DESTRUCTOR_P (decl))
+                 warning_n (DECL_SOURCE_LOCATION (decl),
+                             OPT_Wsuggest_final_methods, count,
+                             "Declaring virtual destructor of %qD final "
+                             "would enable devirtualization of %i call "
+                             "executed %lli times",
+                             "Declaring virtual destructor of %qD final "
+                             "would enable devirtualization of %i calls "
+                             "executed %lli times",
+                             DECL_CONTEXT (decl), count, dyn_count);
+               else
+                 warning_n (DECL_SOURCE_LOCATION (decl),
+                             OPT_Wsuggest_final_methods, count,
+                             "Declaring method %qD final "
+                             "would enable devirtualization of %i call "
+                             "executed %lli times",
+                             "Declaring method %qD final "
+                             "would enable devirtualization of %i calls "
+                             "executed %lli times",
+                             decl, count, dyn_count);
            }
        }
        
@@ -4180,11 +3928,11 @@ ipa_devirt (void)
             " %i speculatively devirtualized, %i cold\n"
             "%i have multiple targets, %i overwritable,"
             " %i already speculated (%i agree, %i disagree),"
-            " %i external, %i not defined, %i artificial\n",
+            " %i external, %i not defined, %i artificial, %i infos dropped\n",
             npolymorphic, ndevirtualized, nconverted, ncold,
             nmultiple, noverwritable, nspeculated, nok, nwrong,
-            nexternal, nnotdefined, nartificial);
-  return ndevirtualized ? TODO_remove_functions : 0;
+            nexternal, nnotdefined, nartificial, ndropped);
+  return ndevirtualized || ndropped ? TODO_remove_functions : 0;
 }
 
 namespace {
@@ -4221,6 +3969,10 @@ public:
   /* opt_pass methods: */
   virtual bool gate (function *)
     {
+      /* In LTO, always run the IPA passes and decide on function basis if the
+        pass is enabled.  */
+      if (in_lto_p)
+       return true;
       return (flag_devirtualize
              && (flag_devirtualize_speculatively
                  || (warn_suggest_final_methods