xref: /netbsd-src/external/gpl3/gcc.old/dist/gcc/ipa-devirt.c (revision 122b5006ee1bd67145794b4cde92f4fe4781a5ec)
1 /* Basic IPA utilities for type inheritance graph construction and
2    devirtualization.
3    Copyright (C) 2013-2019 Free Software Foundation, Inc.
4    Contributed by Jan Hubicka
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12 
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21 
22 /* Brief vocabulary:
23      ODR = One Definition Rule
24         In short, the ODR states that:
25 	1 In any translation unit, a template, type, function, or object can
26 	  have no more than one definition. Some of these can have any number
27 	  of declarations. A definition provides an instance.
28         2 In the entire program, an object or non-inline function cannot have
29 	  more than one definition; if an object or function is used, it must
30 	  have exactly one definition. You can declare an object or function
31 	  that is never used, in which case you don't have to provide
32 	  a definition. In no event can there be more than one definition.
33         3 Some things, like types, templates, and extern inline functions, can
34 	  be defined in more than one translation unit. For a given entity,
35 	  each definition must be the same. Non-extern objects and functions
36 	  in different translation units are different entities, even if their
37 	  names and types are the same.
38 
39      OTR = OBJ_TYPE_REF
40        This is the Gimple representation of type information of a polymorphic call.
41        It contains two parameters:
42 	 otr_type is a type of class whose method is called.
43 	 otr_token is the index into virtual table where address is taken.
44 
45      BINFO
46        This is the type inheritance information attached to each tree
47        RECORD_TYPE by the C++ frontend.  It provides information about base
48        types and virtual tables.
49 
50        BINFO is linked to the RECORD_TYPE by TYPE_BINFO.
51        BINFO also links to its type by BINFO_TYPE and to the virtual table by
52        BINFO_VTABLE.
53 
54        Base types of a given type are enumerated by BINFO_BASE_BINFO
55        vector.  Members of this vectors are not BINFOs associated
56        with a base type.  Rather they are new copies of BINFOs
57        (base BINFOs). Their virtual tables may differ from
58        virtual table of the base type.  Also BINFO_OFFSET specifies
59        offset of the base within the type.
60 
61        In the case of single inheritance, the virtual table is shared
62        and BINFO_VTABLE of base BINFO is NULL.  In the case of multiple
63        inheritance the individual virtual tables are pointer to by
64        BINFO_VTABLE of base binfos (that differs of BINFO_VTABLE of
65        binfo associated to the base type).
66 
67        BINFO lookup for a given base type and offset can be done by
68        get_binfo_at_offset.  It returns proper BINFO whose virtual table
69        can be used for lookup of virtual methods associated with the
70        base type.
71 
72      token
73        This is an index of virtual method in virtual table associated
74        to the type defining it. Token can be looked up from OBJ_TYPE_REF
75        or from DECL_VINDEX of a given virtual table.
76 
77      polymorphic (indirect) call
78        This is callgraph representation of virtual method call.  Every
79        polymorphic call contains otr_type and otr_token taken from
80        original OBJ_TYPE_REF at callgraph construction time.
81 
82    What we do here:
83 
84    build_type_inheritance_graph triggers a construction of the type inheritance
85    graph.
86 
87      We reconstruct it based on types of methods we see in the unit.
88      This means that the graph is not complete. Types with no methods are not
89      inserted into the graph.  Also types without virtual methods are not
90      represented at all, though it may be easy to add this.
91 
92      The inheritance graph is represented as follows:
93 
94        Vertices are structures odr_type.  Every odr_type may correspond
95        to one or more tree type nodes that are equivalent by ODR rule.
96        (the multiple type nodes appear only with linktime optimization)
97 
98        Edges are represented by odr_type->base and odr_type->derived_types.
99        At the moment we do not track offsets of types for multiple inheritance.
100        Adding this is easy.
101 
102   possible_polymorphic_call_targets returns, given an parameters found in
103   indirect polymorphic edge all possible polymorphic call targets of the call.
104 
105   pass_ipa_devirt performs simple speculative devirtualization.
106 */
107 
108 #include "config.h"
109 #include "system.h"
110 #include "coretypes.h"
111 #include "backend.h"
112 #include "rtl.h"
113 #include "tree.h"
114 #include "gimple.h"
115 #include "alloc-pool.h"
116 #include "tree-pass.h"
117 #include "cgraph.h"
118 #include "lto-streamer.h"
119 #include "fold-const.h"
120 #include "print-tree.h"
121 #include "calls.h"
122 #include "ipa-utils.h"
123 #include "gimple-fold.h"
124 #include "symbol-summary.h"
125 #include "tree-vrp.h"
126 #include "ipa-prop.h"
127 #include "ipa-fnsummary.h"
128 #include "demangle.h"
129 #include "dbgcnt.h"
130 #include "gimple-pretty-print.h"
131 #include "intl.h"
132 #include "stringpool.h"
133 #include "attribs.h"
134 
135 /* Hash based set of pairs of types.  */
136 struct type_pair
137 {
138   tree first;
139   tree second;
140 };
141 
142 template <>
143 struct default_hash_traits <type_pair>
144   : typed_noop_remove <type_pair>
145 {
146   GTY((skip)) typedef type_pair value_type;
147   GTY((skip)) typedef type_pair compare_type;
148   static hashval_t
149   hash (type_pair p)
150   {
151     return TYPE_UID (p.first) ^ TYPE_UID (p.second);
152   }
153   static bool
154   is_empty (type_pair p)
155   {
156     return p.first == NULL;
157   }
158   static bool
159   is_deleted (type_pair p ATTRIBUTE_UNUSED)
160     {
161       return false;
162     }
163   static bool
164   equal (const type_pair &a, const type_pair &b)
165     {
166       return a.first==b.first && a.second == b.second;
167     }
168   static void
169   mark_empty (type_pair &e)
170     {
171       e.first = NULL;
172     }
173 };
174 
175 static bool odr_types_equivalent_p (tree, tree, bool, bool *,
176 				    hash_set<type_pair> *,
177 				    location_t, location_t);
178 static void warn_odr (tree t1, tree t2, tree st1, tree st2,
179 		      bool warn, bool *warned, const char *reason);
180 
181 static bool odr_violation_reported = false;
182 
183 
184 /* Pointer set of all call targets appearing in the cache.  */
185 static hash_set<cgraph_node *> *cached_polymorphic_call_targets;
186 
187 /* The node of type inheritance graph.  For each type unique in
188    One Definition Rule (ODR) sense, we produce one node linking all
189    main variants of types equivalent to it, bases and derived types.  */
190 
191 struct GTY(()) odr_type_d
192 {
193   /* leader type.  */
194   tree type;
195   /* All bases; built only for main variants of types.  */
196   vec<odr_type> GTY((skip)) bases;
197   /* All derived types with virtual methods seen in unit;
198      built only for main variants of types.  */
199   vec<odr_type> GTY((skip)) derived_types;
200 
201   /* All equivalent types, if more than one.  */
202   vec<tree, va_gc> *types;
203   /* Set of all equivalent types, if NON-NULL.  */
204   hash_set<tree> * GTY((skip)) types_set;
205 
206   /* Unique ID indexing the type in odr_types array.  */
207   int id;
208   /* Is it in anonymous namespace? */
209   bool anonymous_namespace;
210   /* Do we know about all derivations of given type?  */
211   bool all_derivations_known;
212   /* Did we report ODR violation here?  */
213   bool odr_violated;
214   /* Set when virtual table without RTTI previaled table with.  */
215   bool rtti_broken;
216 };
217 
218 /* Return TRUE if all derived types of T are known and thus
219    we may consider the walk of derived type complete.
220 
221    This is typically true only for final anonymous namespace types and types
222    defined within functions (that may be COMDAT and thus shared across units,
223    but with the same set of derived types).  */
224 
225 bool
226 type_all_derivations_known_p (const_tree t)
227 {
228   if (TYPE_FINAL_P (t))
229     return true;
230   if (flag_ltrans)
231     return false;
232   /* Non-C++ types may have IDENTIFIER_NODE here, do not crash.  */
233   if (!TYPE_NAME (t) || TREE_CODE (TYPE_NAME (t)) != TYPE_DECL)
234     return true;
235   if (type_in_anonymous_namespace_p (t))
236     return true;
237   return (decl_function_context (TYPE_NAME (t)) != NULL);
238 }
239 
240 /* Return TRUE if type's constructors are all visible.  */
241 
242 static bool
243 type_all_ctors_visible_p (tree t)
244 {
245   return !flag_ltrans
246 	 && symtab->state >= CONSTRUCTION
247 	 /* We cannot always use type_all_derivations_known_p.
248 	    For function local types we must assume case where
249 	    the function is COMDAT and shared in between units.
250 
251 	    TODO: These cases are quite easy to get, but we need
252 	    to keep track of C++ privatizing via -Wno-weak
253 	    as well as the  IPA privatizing.  */
254 	 && type_in_anonymous_namespace_p (t);
255 }
256 
257 /* Return TRUE if type may have instance.  */
258 
259 static bool
260 type_possibly_instantiated_p (tree t)
261 {
262   tree vtable;
263   varpool_node *vnode;
264 
265   /* TODO: Add abstract types here.  */
266   if (!type_all_ctors_visible_p (t))
267     return true;
268 
269   vtable = BINFO_VTABLE (TYPE_BINFO (t));
270   if (TREE_CODE (vtable) == POINTER_PLUS_EXPR)
271     vtable = TREE_OPERAND (TREE_OPERAND (vtable, 0), 0);
272   vnode = varpool_node::get (vtable);
273   return vnode && vnode->definition;
274 }
275 
276 /* Hash used to unify ODR types based on their mangled name and for anonymous
277    namespace types.  */
278 
279 struct odr_name_hasher : pointer_hash <odr_type_d>
280 {
281   typedef union tree_node *compare_type;
282   static inline hashval_t hash (const odr_type_d *);
283   static inline bool equal (const odr_type_d *, const tree_node *);
284   static inline void remove (odr_type_d *);
285 };
286 
287 /* Has used to unify ODR types based on their associated virtual table.
288    This hash is needed to keep -fno-lto-odr-type-merging to work and contains
289    only polymorphic types.  Types with mangled names are inserted to both.  */
290 
291 struct odr_vtable_hasher:odr_name_hasher
292 {
293   static inline hashval_t hash (const odr_type_d *);
294   static inline bool equal (const odr_type_d *, const tree_node *);
295 };
296 
297 static bool
298 can_be_name_hashed_p (tree t)
299 {
300   return (!in_lto_p || odr_type_p (t));
301 }
302 
303 /* Hash type by its ODR name.  */
304 
305 static hashval_t
306 hash_odr_name (const_tree t)
307 {
308   gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
309 
310   /* If not in LTO, all main variants are unique, so we can do
311      pointer hash.  */
312   if (!in_lto_p)
313     return htab_hash_pointer (t);
314 
315   /* Anonymous types are unique.  */
316   if (type_with_linkage_p (t) && type_in_anonymous_namespace_p (t))
317     return htab_hash_pointer (t);
318 
319   gcc_checking_assert (TYPE_NAME (t)
320 		       && DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t)));
321   return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME (TYPE_NAME (t)));
322 }
323 
324 /* Return the computed hashcode for ODR_TYPE.  */
325 
326 inline hashval_t
327 odr_name_hasher::hash (const odr_type_d *odr_type)
328 {
329   return hash_odr_name (odr_type->type);
330 }
331 
332 static bool
333 can_be_vtable_hashed_p (tree t)
334 {
335   /* vtable hashing can distinguish only main variants.  */
336   if (TYPE_MAIN_VARIANT (t) != t)
337     return false;
338   /* Anonymous namespace types are always handled by name hash.  */
339   if (type_with_linkage_p (t) && type_in_anonymous_namespace_p (t))
340     return false;
341   return (TREE_CODE (t) == RECORD_TYPE
342 	  && TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)));
343 }
344 
345 /* Hash type by assembler name of its vtable.  */
346 
347 static hashval_t
348 hash_odr_vtable (const_tree t)
349 {
350   tree v = BINFO_VTABLE (TYPE_BINFO (TYPE_MAIN_VARIANT (t)));
351   inchash::hash hstate;
352 
353   gcc_checking_assert (in_lto_p);
354   gcc_checking_assert (!type_in_anonymous_namespace_p (t));
355   gcc_checking_assert (TREE_CODE (t) == RECORD_TYPE
356 		       && TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)));
357   gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
358 
359   if (TREE_CODE (v) == POINTER_PLUS_EXPR)
360     {
361       add_expr (TREE_OPERAND (v, 1), hstate);
362       v = TREE_OPERAND (TREE_OPERAND (v, 0), 0);
363     }
364 
365   hstate.add_hwi (IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME (v)));
366   return hstate.end ();
367 }
368 
369 /* Return the computed hashcode for ODR_TYPE.  */
370 
371 inline hashval_t
372 odr_vtable_hasher::hash (const odr_type_d *odr_type)
373 {
374   return hash_odr_vtable (odr_type->type);
375 }
376 
377 /* For languages with One Definition Rule, work out if
378    types are the same based on their name.
379 
380    This is non-trivial for LTO where minor differences in
381    the type representation may have prevented type merging
382    to merge two copies of otherwise equivalent type.
383 
384    Until we start streaming mangled type names, this function works
385    only for polymorphic types.
386 */
387 
388 bool
389 types_same_for_odr (const_tree type1, const_tree type2)
390 {
391   gcc_checking_assert (TYPE_P (type1) && TYPE_P (type2));
392 
393   type1 = TYPE_MAIN_VARIANT (type1);
394   type2 = TYPE_MAIN_VARIANT (type2);
395 
396   if (type1 == type2)
397     return true;
398 
399   if (!in_lto_p)
400     return false;
401 
402   /* Anonymous namespace types are never duplicated.  */
403   if ((type_with_linkage_p (type1) && type_in_anonymous_namespace_p (type1))
404       || (type_with_linkage_p (type2) && type_in_anonymous_namespace_p (type2)))
405     return false;
406 
407 
408   /* ODR name of the type is set in DECL_ASSEMBLER_NAME of its TYPE_NAME.
409 
410      Ideally we should never need types without ODR names here.  It can however
411      happen in two cases:
412 
413        1) for builtin types that are not streamed but rebuilt in lto/lto-lang.c
414           Here testing for equivalence is safe, since their MAIN_VARIANTs are
415           unique.
416        2) for units streamed with -fno-lto-odr-type-merging.  Here we can't
417 	  establish precise ODR equivalency, but for correctness we care only
418 	  about equivalency on complete polymorphic types.  For these we can
419 	  compare assembler names of their virtual tables.  */
420   if ((!TYPE_NAME (type1) || !DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (type1)))
421       || (!TYPE_NAME (type2) || !DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (type2))))
422     {
423       /* See if types are obviously different (i.e. different codes
424 	 or polymorphic wrt non-polymorphic).  This is not strictly correct
425 	 for ODR violating programs, but we can't do better without streaming
426 	 ODR names.  */
427       if (TREE_CODE (type1) != TREE_CODE (type2))
428 	return false;
429       if (TREE_CODE (type1) == RECORD_TYPE
430 	  && (TYPE_BINFO (type1) == NULL_TREE)
431 	      != (TYPE_BINFO (type2) == NULL_TREE))
432 	return false;
433       if (TREE_CODE (type1) == RECORD_TYPE && TYPE_BINFO (type1)
434 	  && (BINFO_VTABLE (TYPE_BINFO (type1)) == NULL_TREE)
435 	     != (BINFO_VTABLE (TYPE_BINFO (type2)) == NULL_TREE))
436 	return false;
437 
438       /* At the moment we have no way to establish ODR equivalence at LTO
439 	 other than comparing virtual table pointers of polymorphic types.
440 	 Eventually we should start saving mangled names in TYPE_NAME.
441 	 Then this condition will become non-trivial.  */
442 
443       if (TREE_CODE (type1) == RECORD_TYPE
444 	  && TYPE_BINFO (type1) && TYPE_BINFO (type2)
445 	  && BINFO_VTABLE (TYPE_BINFO (type1))
446 	  && BINFO_VTABLE (TYPE_BINFO (type2)))
447 	{
448 	  tree v1 = BINFO_VTABLE (TYPE_BINFO (type1));
449 	  tree v2 = BINFO_VTABLE (TYPE_BINFO (type2));
450 	  gcc_assert (TREE_CODE (v1) == POINTER_PLUS_EXPR
451 		      && TREE_CODE (v2) == POINTER_PLUS_EXPR);
452 	  return (operand_equal_p (TREE_OPERAND (v1, 1),
453 				   TREE_OPERAND (v2, 1), 0)
454 		  && DECL_ASSEMBLER_NAME
455 			 (TREE_OPERAND (TREE_OPERAND (v1, 0), 0))
456 		     == DECL_ASSEMBLER_NAME
457 			 (TREE_OPERAND (TREE_OPERAND (v2, 0), 0)));
458 	}
459       gcc_unreachable ();
460     }
461   return (DECL_ASSEMBLER_NAME (TYPE_NAME (type1))
462 	  == DECL_ASSEMBLER_NAME (TYPE_NAME (type2)));
463 }
464 
465 /* Return true if we can decide on ODR equivalency.
466 
467    In non-LTO it is always decide, in LTO however it depends in the type has
468    ODR info attached. */
469 
470 bool
471 types_odr_comparable (tree t1, tree t2)
472 {
473   return (!in_lto_p
474 	  || TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2)
475 	  || (odr_type_p (TYPE_MAIN_VARIANT (t1))
476 	      && odr_type_p (TYPE_MAIN_VARIANT (t2)))
477 	  || (TREE_CODE (t1) == RECORD_TYPE && TREE_CODE (t2) == RECORD_TYPE
478 	      && TYPE_BINFO (t1) && TYPE_BINFO (t2)
479 	      && polymorphic_type_binfo_p (TYPE_BINFO (t1))
480 	      && polymorphic_type_binfo_p (TYPE_BINFO (t2))));
481 }
482 
483 /* Return true if T1 and T2 are ODR equivalent.  If ODR equivalency is not
484    known, be conservative and return false.  */
485 
486 bool
487 types_must_be_same_for_odr (tree t1, tree t2)
488 {
489   if (types_odr_comparable (t1, t2))
490     return types_same_for_odr (t1, t2);
491   else
492     return TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2);
493 }
494 
495 /* If T is compound type, return type it is based on.  */
496 
497 static tree
498 compound_type_base (const_tree t)
499 {
500   if (TREE_CODE (t) == ARRAY_TYPE
501       || POINTER_TYPE_P (t)
502       || TREE_CODE (t) == COMPLEX_TYPE
503       || VECTOR_TYPE_P (t))
504     return TREE_TYPE (t);
505   if (TREE_CODE (t) == METHOD_TYPE)
506     return TYPE_METHOD_BASETYPE (t);
507   if (TREE_CODE (t) == OFFSET_TYPE)
508     return TYPE_OFFSET_BASETYPE (t);
509   return NULL_TREE;
510 }
511 
512 /* Return true if T is either ODR type or compound type based from it.
513    If the function return true, we know that T is a type originating from C++
514    source even at link-time.  */
515 
516 bool
517 odr_or_derived_type_p (const_tree t)
518 {
519   do
520     {
521       if (odr_type_p (TYPE_MAIN_VARIANT (t)))
522 	return true;
523       /* Function type is a tricky one. Basically we can consider it
524 	 ODR derived if return type or any of the parameters is.
525 	 We need to check all parameters because LTO streaming merges
526 	 common types (such as void) and they are not considered ODR then.  */
527       if (TREE_CODE (t) == FUNCTION_TYPE)
528 	{
529 	  if (TYPE_METHOD_BASETYPE (t))
530 	    t = TYPE_METHOD_BASETYPE (t);
531 	  else
532 	   {
533 	     if (TREE_TYPE (t) && odr_or_derived_type_p (TREE_TYPE (t)))
534 	       return true;
535 	     for (t = TYPE_ARG_TYPES (t); t; t = TREE_CHAIN (t))
536 	       if (odr_or_derived_type_p (TYPE_MAIN_VARIANT (TREE_VALUE (t))))
537 		 return true;
538 	     return false;
539 	   }
540 	}
541       else
542 	t = compound_type_base (t);
543     }
544   while (t);
545   return t;
546 }
547 
548 /* Compare types T1 and T2 and return true if they are
549    equivalent.  */
550 
551 inline bool
552 odr_name_hasher::equal (const odr_type_d *o1, const tree_node *t2)
553 {
554   tree t1 = o1->type;
555 
556   gcc_checking_assert (TYPE_MAIN_VARIANT (t2) == t2);
557   gcc_checking_assert (TYPE_MAIN_VARIANT (t1) == t1);
558   if (t1 == t2)
559     return true;
560   if (!in_lto_p)
561     return false;
562   /* Check for anonymous namespaces.  */
563   if ((type_with_linkage_p (t1) && type_in_anonymous_namespace_p (t1))
564       || (type_with_linkage_p (t2) && type_in_anonymous_namespace_p (t2)))
565     return false;
566   gcc_checking_assert (DECL_ASSEMBLER_NAME (TYPE_NAME (t1)));
567   gcc_checking_assert (DECL_ASSEMBLER_NAME (TYPE_NAME (t2)));
568   return (DECL_ASSEMBLER_NAME (TYPE_NAME (t1))
569 	  == DECL_ASSEMBLER_NAME (TYPE_NAME (t2)));
570 }
571 
572 /* Compare types T1 and T2 and return true if they are
573    equivalent.  */
574 
575 inline bool
576 odr_vtable_hasher::equal (const odr_type_d *o1, const tree_node *t2)
577 {
578   tree t1 = o1->type;
579 
580   gcc_checking_assert (TYPE_MAIN_VARIANT (t2) == t2);
581   gcc_checking_assert (TYPE_MAIN_VARIANT (t1) == t1);
582   gcc_checking_assert (in_lto_p);
583   t1 = TYPE_MAIN_VARIANT (t1);
584   t2 = TYPE_MAIN_VARIANT (t2);
585   if (t1 == t2)
586     return true;
587   tree v1 = BINFO_VTABLE (TYPE_BINFO (t1));
588   tree v2 = BINFO_VTABLE (TYPE_BINFO (t2));
589   return (operand_equal_p (TREE_OPERAND (v1, 1),
590 			   TREE_OPERAND (v2, 1), 0)
591 	  && DECL_ASSEMBLER_NAME
592 		 (TREE_OPERAND (TREE_OPERAND (v1, 0), 0))
593 	     == DECL_ASSEMBLER_NAME
594 		 (TREE_OPERAND (TREE_OPERAND (v2, 0), 0)));
595 }
596 
597 /* Free ODR type V.  */
598 
599 inline void
600 odr_name_hasher::remove (odr_type_d *v)
601 {
602   v->bases.release ();
603   v->derived_types.release ();
604   if (v->types_set)
605     delete v->types_set;
606   ggc_free (v);
607 }
608 
609 /* ODR type hash used to look up ODR type based on tree type node.  */
610 
611 typedef hash_table<odr_name_hasher> odr_hash_type;
612 static odr_hash_type *odr_hash;
613 typedef hash_table<odr_vtable_hasher> odr_vtable_hash_type;
614 static odr_vtable_hash_type *odr_vtable_hash;
615 
616 /* ODR types are also stored into ODR_TYPE vector to allow consistent
617    walking.  Bases appear before derived types.  Vector is garbage collected
618    so we won't end up visiting empty types.  */
619 
620 static GTY(()) vec <odr_type, va_gc> *odr_types_ptr;
621 #define odr_types (*odr_types_ptr)
622 
623 /* Set TYPE_BINFO of TYPE and its variants to BINFO.  */
624 void
625 set_type_binfo (tree type, tree binfo)
626 {
627   for (; type; type = TYPE_NEXT_VARIANT (type))
628     if (COMPLETE_TYPE_P (type))
629       TYPE_BINFO (type) = binfo;
630     else
631       gcc_assert (!TYPE_BINFO (type));
632 }
633 
634 /* Return true if type variants match.
635    This assumes that we already verified that T1 and T2 are variants of the
636    same type.  */
637 
638 static bool
639 type_variants_equivalent_p (tree t1, tree t2)
640 {
641   if (TYPE_QUALS (t1) != TYPE_QUALS (t2))
642     return false;
643 
644   if (comp_type_attributes (t1, t2) != 1)
645     return false;
646 
647   if (COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2)
648       && TYPE_ALIGN (t1) != TYPE_ALIGN (t2))
649     return false;
650 
651   return true;
652 }
653 
654 /* Compare T1 and T2 based on name or structure.  */
655 
656 static bool
657 odr_subtypes_equivalent_p (tree t1, tree t2,
658 			   hash_set<type_pair> *visited,
659 			   location_t loc1, location_t loc2)
660 {
661 
662   /* This can happen in incomplete types that should be handled earlier.  */
663   gcc_assert (t1 && t2);
664 
665   if (t1 == t2)
666     return true;
667 
668   /* Anonymous namespace types must match exactly.  */
669   if ((type_with_linkage_p (TYPE_MAIN_VARIANT (t1))
670        && type_in_anonymous_namespace_p (TYPE_MAIN_VARIANT (t1)))
671       || (type_with_linkage_p (TYPE_MAIN_VARIANT (t2))
672 	  && type_in_anonymous_namespace_p (TYPE_MAIN_VARIANT (t2))))
673     return false;
674 
675   /* For ODR types be sure to compare their names.
676      To support -Wno-odr-type-merging we allow one type to be non-ODR
677      and other ODR even though it is a violation.  */
678   if (types_odr_comparable (t1, t2))
679     {
680       if (t1 != t2
681 	  && odr_type_p (TYPE_MAIN_VARIANT (t1))
682 	  && get_odr_type (TYPE_MAIN_VARIANT (t1), true)->odr_violated)
683 	return false;
684       if (!types_same_for_odr (t1, t2))
685         return false;
686       if (!type_variants_equivalent_p (t1, t2))
687 	return false;
688       /* Limit recursion: If subtypes are ODR types and we know
689 	 that they are same, be happy.  */
690       if (odr_type_p (TYPE_MAIN_VARIANT (t1)))
691         return true;
692     }
693 
694   /* Component types, builtins and possibly violating ODR types
695      have to be compared structurally.  */
696   if (TREE_CODE (t1) != TREE_CODE (t2))
697     return false;
698   if (AGGREGATE_TYPE_P (t1)
699       && (TYPE_NAME (t1) == NULL_TREE) != (TYPE_NAME (t2) == NULL_TREE))
700     return false;
701 
702   type_pair pair={TYPE_MAIN_VARIANT (t1), TYPE_MAIN_VARIANT (t2)};
703   if (TYPE_UID (TYPE_MAIN_VARIANT (t1)) > TYPE_UID (TYPE_MAIN_VARIANT (t2)))
704     {
705       pair.first = TYPE_MAIN_VARIANT (t2);
706       pair.second = TYPE_MAIN_VARIANT (t1);
707     }
708   if (visited->add (pair))
709     return true;
710   if (!odr_types_equivalent_p (TYPE_MAIN_VARIANT (t1), TYPE_MAIN_VARIANT (t2),
711 			      false, NULL, visited, loc1, loc2))
712     return false;
713   if (!type_variants_equivalent_p (t1, t2))
714     return false;
715   return true;
716 }
717 
718 /* Return true if DECL1 and DECL2 are identical methods.  Consider
719    name equivalent to name.localalias.xyz.  */
720 
721 static bool
722 methods_equal_p (tree decl1, tree decl2)
723 {
724   if (DECL_ASSEMBLER_NAME (decl1) == DECL_ASSEMBLER_NAME (decl2))
725     return true;
726   const char sep = symbol_table::symbol_suffix_separator ();
727 
728   const char *name1 = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl1));
729   const char *ptr1 = strchr (name1, sep);
730   int len1 = ptr1 ? ptr1 - name1 : strlen (name1);
731 
732   const char *name2 = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl2));
733   const char *ptr2 = strchr (name2, sep);
734   int len2 = ptr2 ? ptr2 - name2 : strlen (name2);
735 
736   if (len1 != len2)
737     return false;
738   return !strncmp (name1, name2, len1);
739 }
740 
741 /* Compare two virtual tables, PREVAILING and VTABLE and output ODR
742    violation warnings.  */
743 
744 void
745 compare_virtual_tables (varpool_node *prevailing, varpool_node *vtable)
746 {
747   int n1, n2;
748 
749   if (DECL_VIRTUAL_P (prevailing->decl) != DECL_VIRTUAL_P (vtable->decl))
750     {
751       odr_violation_reported = true;
752       if (DECL_VIRTUAL_P (prevailing->decl))
753 	{
754 	  varpool_node *tmp = prevailing;
755 	  prevailing = vtable;
756 	  vtable = tmp;
757 	}
758       auto_diagnostic_group d;
759       if (warning_at (DECL_SOURCE_LOCATION
760 			(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
761 		      OPT_Wodr,
762 		      "virtual table of type %qD violates one definition rule",
763 		      DECL_CONTEXT (vtable->decl)))
764 	inform (DECL_SOURCE_LOCATION (prevailing->decl),
765 		"variable of same assembler name as the virtual table is "
766 		"defined in another translation unit");
767       return;
768     }
769   if (!prevailing->definition || !vtable->definition)
770     return;
771 
772   /* If we do not stream ODR type info, do not bother to do useful compare.  */
773   if (!TYPE_BINFO (DECL_CONTEXT (vtable->decl))
774       || !polymorphic_type_binfo_p (TYPE_BINFO (DECL_CONTEXT (vtable->decl))))
775     return;
776 
777   odr_type class_type = get_odr_type (DECL_CONTEXT (vtable->decl), true);
778 
779   if (class_type->odr_violated)
780     return;
781 
782   for (n1 = 0, n2 = 0; true; n1++, n2++)
783     {
784       struct ipa_ref *ref1, *ref2;
785       bool end1, end2;
786 
787       end1 = !prevailing->iterate_reference (n1, ref1);
788       end2 = !vtable->iterate_reference (n2, ref2);
789 
790       /* !DECL_VIRTUAL_P means RTTI entry;
791 	 We warn when RTTI is lost because non-RTTI previals; we silently
792 	 accept the other case.  */
793       while (!end2
794 	     && (end1
795 	         || (methods_equal_p (ref1->referred->decl,
796 				      ref2->referred->decl)
797 	             && TREE_CODE (ref1->referred->decl) == FUNCTION_DECL))
798 	     && TREE_CODE (ref2->referred->decl) != FUNCTION_DECL)
799 	{
800 	  if (!class_type->rtti_broken)
801 	    {
802 	      auto_diagnostic_group d;
803 	      if (warning_at (DECL_SOURCE_LOCATION
804 				  (TYPE_NAME (DECL_CONTEXT (vtable->decl))),
805 				OPT_Wodr,
806 				"virtual table of type %qD contains RTTI "
807 				"information",
808 				DECL_CONTEXT (vtable->decl)))
809 		{
810 		  inform (DECL_SOURCE_LOCATION
811 			      (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
812 			    "but is prevailed by one without from other"
813 			    " translation unit");
814 		  inform (DECL_SOURCE_LOCATION
815 			      (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
816 			    "RTTI will not work on this type");
817 		  class_type->rtti_broken = true;
818 		}
819 	    }
820 	  n2++;
821           end2 = !vtable->iterate_reference (n2, ref2);
822 	}
823       while (!end1
824 	     && (end2
825 	         || (methods_equal_p (ref2->referred->decl, ref1->referred->decl)
826 	             && TREE_CODE (ref2->referred->decl) == FUNCTION_DECL))
827 	     && TREE_CODE (ref1->referred->decl) != FUNCTION_DECL)
828 	{
829 	  n1++;
830           end1 = !prevailing->iterate_reference (n1, ref1);
831 	}
832 
833       /* Finished?  */
834       if (end1 && end2)
835 	{
836 	  /* Extra paranoia; compare the sizes.  We do not have information
837 	     about virtual inheritance offsets, so just be sure that these
838 	     match.
839 	     Do this as very last check so the not very informative error
840 	     is not output too often.  */
841 	  if (DECL_SIZE (prevailing->decl) != DECL_SIZE (vtable->decl))
842 	    {
843 	      class_type->odr_violated = true;
844 	      auto_diagnostic_group d;
845 	      tree ctx = TYPE_NAME (DECL_CONTEXT (vtable->decl));
846 	      if (warning_at (DECL_SOURCE_LOCATION (ctx), OPT_Wodr,
847 			      "virtual table of type %qD violates "
848 			      "one definition rule",
849 			      DECL_CONTEXT (vtable->decl)))
850 		{
851 		  ctx = TYPE_NAME (DECL_CONTEXT (prevailing->decl));
852 		  inform (DECL_SOURCE_LOCATION (ctx),
853 			  "the conflicting type defined in another translation"
854 			  " unit has virtual table of different size");
855 		}
856 	    }
857 	  return;
858 	}
859 
860       if (!end1 && !end2)
861 	{
862 	  if (methods_equal_p (ref1->referred->decl, ref2->referred->decl))
863 	    continue;
864 
865 	  class_type->odr_violated = true;
866 
867 	  /* If the loops above stopped on non-virtual pointer, we have
868 	     mismatch in RTTI information mangling.  */
869 	  if (TREE_CODE (ref1->referred->decl) != FUNCTION_DECL
870 	      && TREE_CODE (ref2->referred->decl) != FUNCTION_DECL)
871 	    {
872 	      auto_diagnostic_group d;
873 	      if (warning_at (DECL_SOURCE_LOCATION
874 				(TYPE_NAME (DECL_CONTEXT (vtable->decl))),
875 			      OPT_Wodr,
876 			      "virtual table of type %qD violates "
877 			      "one definition rule",
878 			      DECL_CONTEXT (vtable->decl)))
879 		{
880 		  inform (DECL_SOURCE_LOCATION
881 			    (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
882 			  "the conflicting type defined in another translation "
883 			  "unit with different RTTI information");
884 		}
885 	      return;
886 	    }
887 	  /* At this point both REF1 and REF2 points either to virtual table
888 	     or virtual method.  If one points to virtual table and other to
889 	     method we can complain the same way as if one table was shorter
890 	     than other pointing out the extra method.  */
891 	  if (TREE_CODE (ref1->referred->decl)
892 	      != TREE_CODE (ref2->referred->decl))
893 	    {
894 	      if (VAR_P (ref1->referred->decl))
895 		end1 = true;
896 	      else if (VAR_P (ref2->referred->decl))
897 		end2 = true;
898 	    }
899 	}
900 
901       class_type->odr_violated = true;
902 
903       /* Complain about size mismatch.  Either we have too many virutal
904  	 functions or too many virtual table pointers.  */
905       if (end1 || end2)
906 	{
907 	  if (end1)
908 	    {
909 	      varpool_node *tmp = prevailing;
910 	      prevailing = vtable;
911 	      vtable = tmp;
912 	      ref1 = ref2;
913 	    }
914 	  auto_diagnostic_group d;
915 	  if (warning_at (DECL_SOURCE_LOCATION
916 			    (TYPE_NAME (DECL_CONTEXT (vtable->decl))),
917 			  OPT_Wodr,
918 			  "virtual table of type %qD violates "
919 			  "one definition rule",
920 			  DECL_CONTEXT (vtable->decl)))
921 	    {
922 	      if (TREE_CODE (ref1->referring->decl) == FUNCTION_DECL)
923 		{
924 		  inform (DECL_SOURCE_LOCATION
925 			   (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
926 			  "the conflicting type defined in another translation "
927 			  "unit");
928 		  inform (DECL_SOURCE_LOCATION
929 			    (TYPE_NAME (DECL_CONTEXT (ref1->referring->decl))),
930 			  "contains additional virtual method %qD",
931 			  ref1->referred->decl);
932 		}
933 	      else
934 		{
935 		  inform (DECL_SOURCE_LOCATION
936 			   (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
937 			  "the conflicting type defined in another translation "
938 			  "unit has virtual table with more entries");
939 		}
940 	    }
941 	  return;
942 	}
943 
944       /* And in the last case we have either mistmatch in between two virtual
945 	 methods or two virtual table pointers.  */
946       auto_diagnostic_group d;
947       if (warning_at (DECL_SOURCE_LOCATION
948 			(TYPE_NAME (DECL_CONTEXT (vtable->decl))), OPT_Wodr,
949 		      "virtual table of type %qD violates "
950 		      "one definition rule  ",
951 		      DECL_CONTEXT (vtable->decl)))
952 	{
953 	  if (TREE_CODE (ref1->referred->decl) == FUNCTION_DECL)
954 	    {
955 	      inform (DECL_SOURCE_LOCATION
956 			(TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
957 		      "the conflicting type defined in another translation "
958 		      "unit");
959 	      gcc_assert (TREE_CODE (ref2->referred->decl)
960 			  == FUNCTION_DECL);
961 	      inform (DECL_SOURCE_LOCATION
962 			 (ref1->referred->ultimate_alias_target ()->decl),
963 		      "virtual method %qD",
964 		      ref1->referred->ultimate_alias_target ()->decl);
965 	      inform (DECL_SOURCE_LOCATION
966 			 (ref2->referred->ultimate_alias_target ()->decl),
967 		      "ought to match virtual method %qD but does not",
968 		      ref2->referred->ultimate_alias_target ()->decl);
969 	    }
970 	  else
971 	    inform (DECL_SOURCE_LOCATION
972 		      (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
973 		    "the conflicting type defined in another translation "
974 		    "unit has virtual table with different contents");
975 	  return;
976 	}
977     }
978 }
979 
980 /* Output ODR violation warning about T1 and T2 with REASON.
981    Display location of ST1 and ST2 if REASON speaks about field or
982    method of the type.
983    If WARN is false, do nothing. Set WARNED if warning was indeed
984    output.  */
985 
986 static void
987 warn_odr (tree t1, tree t2, tree st1, tree st2,
988 	  bool warn, bool *warned, const char *reason)
989 {
990   tree decl2 = TYPE_NAME (TYPE_MAIN_VARIANT (t2));
991   if (warned)
992     *warned = false;
993 
994   if (!warn || !TYPE_NAME(TYPE_MAIN_VARIANT (t1)))
995     return;
996 
997   /* ODR warnings are output druing LTO streaming; we must apply location
998      cache for potential warnings to be output correctly.  */
999   if (lto_location_cache::current_cache)
1000     lto_location_cache::current_cache->apply_location_cache ();
1001 
1002   auto_diagnostic_group d;
1003   if (t1 != TYPE_MAIN_VARIANT (t1)
1004       && TYPE_NAME (t1) != TYPE_NAME (TYPE_MAIN_VARIANT (t1)))
1005     {
1006       if (!warning_at (DECL_SOURCE_LOCATION (TYPE_NAME (TYPE_MAIN_VARIANT (t1))),
1007 		       OPT_Wodr, "type %qT (typedef of %qT) violates the "
1008 		       "C++ One Definition Rule",
1009 		       t1, TYPE_MAIN_VARIANT (t1)))
1010 	return;
1011     }
1012   else
1013     {
1014       if (!warning_at (DECL_SOURCE_LOCATION (TYPE_NAME (TYPE_MAIN_VARIANT (t1))),
1015 		       OPT_Wodr, "type %qT violates the C++ One Definition Rule",
1016 		       t1))
1017 	return;
1018     }
1019   if (!st1 && !st2)
1020     ;
1021   /* For FIELD_DECL support also case where one of fields is
1022      NULL - this is used when the structures have mismatching number of
1023      elements.  */
1024   else if (!st1 || TREE_CODE (st1) == FIELD_DECL)
1025     {
1026       inform (DECL_SOURCE_LOCATION (decl2),
1027 	      "a different type is defined in another translation unit");
1028       if (!st1)
1029 	{
1030 	  st1 = st2;
1031 	  st2 = NULL;
1032 	}
1033       inform (DECL_SOURCE_LOCATION (st1),
1034 	      "the first difference of corresponding definitions is field %qD",
1035 	      st1);
1036       if (st2)
1037         decl2 = st2;
1038     }
1039   else if (TREE_CODE (st1) == FUNCTION_DECL)
1040     {
1041       inform (DECL_SOURCE_LOCATION (decl2),
1042 	      "a different type is defined in another translation unit");
1043       inform (DECL_SOURCE_LOCATION (st1),
1044 	      "the first difference of corresponding definitions is method %qD",
1045 	      st1);
1046       decl2 = st2;
1047     }
1048   else
1049     return;
1050   inform (DECL_SOURCE_LOCATION (decl2), reason);
1051 
1052   if (warned)
1053     *warned = true;
1054 }
1055 
1056 /* Return ture if T1 and T2 are incompatible and we want to recusively
1057    dive into them from warn_type_mismatch to give sensible answer.  */
1058 
1059 static bool
1060 type_mismatch_p (tree t1, tree t2)
1061 {
1062   if (odr_or_derived_type_p (t1) && odr_or_derived_type_p (t2)
1063       && !odr_types_equivalent_p (t1, t2))
1064     return true;
1065   return !types_compatible_p (t1, t2);
1066 }
1067 
1068 
1069 /* Types T1 and T2 was found to be incompatible in a context they can't
1070    (either used to declare a symbol of same assembler name or unified by
1071    ODR rule).  We already output warning about this, but if possible, output
1072    extra information on how the types mismatch.
1073 
1074    This is hard to do in general.  We basically handle the common cases.
1075 
1076    If LOC1 and LOC2 are meaningful locations, use it in the case the types
1077    themselves do no thave one.*/
1078 
1079 void
1080 warn_types_mismatch (tree t1, tree t2, location_t loc1, location_t loc2)
1081 {
1082   /* Location of type is known only if it has TYPE_NAME and the name is
1083      TYPE_DECL.  */
1084   location_t loc_t1 = TYPE_NAME (t1) && TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL
1085 		      ? DECL_SOURCE_LOCATION (TYPE_NAME (t1))
1086 		      : UNKNOWN_LOCATION;
1087   location_t loc_t2 = TYPE_NAME (t2) && TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL
1088 		      ? DECL_SOURCE_LOCATION (TYPE_NAME (t2))
1089 		      : UNKNOWN_LOCATION;
1090   bool loc_t2_useful = false;
1091 
1092   /* With LTO it is a common case that the location of both types match.
1093      See if T2 has a location that is different from T1. If so, we will
1094      inform user about the location.
1095      Do not consider the location passed to us in LOC1/LOC2 as those are
1096      already output.  */
1097   if (loc_t2 > BUILTINS_LOCATION && loc_t2 != loc_t1)
1098     {
1099       if (loc_t1 <= BUILTINS_LOCATION)
1100 	loc_t2_useful = true;
1101       else
1102 	{
1103 	  expanded_location xloc1 = expand_location (loc_t1);
1104 	  expanded_location xloc2 = expand_location (loc_t2);
1105 
1106 	  if (strcmp (xloc1.file, xloc2.file)
1107 	      || xloc1.line != xloc2.line
1108 	      || xloc1.column != xloc2.column)
1109 	    loc_t2_useful = true;
1110 	}
1111     }
1112 
1113   if (loc_t1 <= BUILTINS_LOCATION)
1114     loc_t1 = loc1;
1115   if (loc_t2 <= BUILTINS_LOCATION)
1116     loc_t2 = loc2;
1117 
1118   location_t loc = loc_t1 <= BUILTINS_LOCATION ? loc_t2 : loc_t1;
1119 
1120   /* It is a quite common bug to reference anonymous namespace type in
1121      non-anonymous namespace class.  */
1122   if ((type_with_linkage_p (TYPE_MAIN_VARIANT (t1))
1123        && type_in_anonymous_namespace_p (TYPE_MAIN_VARIANT (t1)))
1124       || (type_with_linkage_p (TYPE_MAIN_VARIANT (t2))
1125 	  && type_in_anonymous_namespace_p (TYPE_MAIN_VARIANT (t2))))
1126     {
1127       if (type_with_linkage_p (TYPE_MAIN_VARIANT (t1))
1128 	  && !type_in_anonymous_namespace_p (TYPE_MAIN_VARIANT (t1)))
1129 	{
1130 	  std::swap (t1, t2);
1131 	  std::swap (loc_t1, loc_t2);
1132 	}
1133       gcc_assert (TYPE_NAME (t1) && TYPE_NAME (t2)
1134 		  && TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL
1135 		  && TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL);
1136       tree n1 = TYPE_NAME (t1);
1137       tree n2 = TYPE_NAME (t2);
1138       if (TREE_CODE (n1) == TYPE_DECL)
1139 	n1 = DECL_NAME (n1);
1140       if (TREE_CODE (n2) == TYPE_DECL)
1141 	n2 = DECL_NAME (n2);
1142       /* Most of the time, the type names will match, do not be unnecesarily
1143          verbose.  */
1144       if (IDENTIFIER_POINTER (n1) != IDENTIFIER_POINTER (n2))
1145         inform (loc_t1,
1146 	        "type %qT defined in anonymous namespace cannot match "
1147 	        "type %qT across the translation unit boundary",
1148 	        t1, t2);
1149       else
1150         inform (loc_t1,
1151 	        "type %qT defined in anonymous namespace cannot match "
1152 	        "across the translation unit boundary",
1153 	        t1);
1154       if (loc_t2_useful)
1155         inform (loc_t2,
1156 	        "the incompatible type defined in another translation unit");
1157       return;
1158     }
1159   tree mt1 = TYPE_MAIN_VARIANT (t1);
1160   tree mt2 = TYPE_MAIN_VARIANT (t2);
1161   /* If types have mangled ODR names and they are different, it is most
1162      informative to output those.
1163      This also covers types defined in different namespaces.  */
1164   if (TYPE_NAME (mt1) && TYPE_NAME (mt2)
1165       && TREE_CODE (TYPE_NAME (mt1)) == TYPE_DECL
1166       && TREE_CODE (TYPE_NAME (mt2)) == TYPE_DECL
1167       && DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (mt1))
1168       && DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (mt2))
1169       && DECL_ASSEMBLER_NAME (TYPE_NAME (mt1))
1170 	 != DECL_ASSEMBLER_NAME (TYPE_NAME (mt2)))
1171     {
1172       char *name1 = xstrdup (cplus_demangle
1173 	 (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (TYPE_NAME (mt1))),
1174 	  DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES));
1175       char *name2 = cplus_demangle
1176 	 (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (TYPE_NAME (mt2))),
1177 	  DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES);
1178       if (name1 && name2 && strcmp (name1, name2))
1179 	{
1180 	  inform (loc_t1,
1181 		  "type name %qs should match type name %qs",
1182 		  name1, name2);
1183 	  if (loc_t2_useful)
1184 	    inform (loc_t2,
1185 		    "the incompatible type is defined here");
1186 	  free (name1);
1187 	  return;
1188 	}
1189       free (name1);
1190     }
1191   /* A tricky case are compound types.  Often they appear the same in source
1192      code and the mismatch is dragged in by type they are build from.
1193      Look for those differences in subtypes and try to be informative.  In other
1194      cases just output nothing because the source code is probably different
1195      and in this case we already output a all necessary info.  */
1196   if (!TYPE_NAME (t1) || !TYPE_NAME (t2))
1197     {
1198       if (TREE_CODE (t1) == TREE_CODE (t2))
1199 	{
1200 	  if (TREE_CODE (t1) == ARRAY_TYPE
1201 	      && COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2))
1202 	    {
1203 	      tree i1 = TYPE_DOMAIN (t1);
1204 	      tree i2 = TYPE_DOMAIN (t2);
1205 
1206 	      if (i1 && i2
1207 		  && TYPE_MAX_VALUE (i1)
1208 		  && TYPE_MAX_VALUE (i2)
1209 		  && !operand_equal_p (TYPE_MAX_VALUE (i1),
1210 				       TYPE_MAX_VALUE (i2), 0))
1211 		{
1212 		  inform (loc,
1213 			  "array types have different bounds");
1214 		  return;
1215 		}
1216 	    }
1217 	  if ((POINTER_TYPE_P (t1) || TREE_CODE (t1) == ARRAY_TYPE)
1218 	      && type_mismatch_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1219 	    warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc_t1, loc_t2);
1220 	  else if (TREE_CODE (t1) == METHOD_TYPE
1221 		   || TREE_CODE (t1) == FUNCTION_TYPE)
1222 	    {
1223 	      tree parms1 = NULL, parms2 = NULL;
1224 	      int count = 1;
1225 
1226 	      if (type_mismatch_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1227 		{
1228 		  inform (loc, "return value type mismatch");
1229 		  warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc_t1,
1230 				       loc_t2);
1231 		  return;
1232 		}
1233 	      if (prototype_p (t1) && prototype_p (t2))
1234 		for (parms1 = TYPE_ARG_TYPES (t1), parms2 = TYPE_ARG_TYPES (t2);
1235 		     parms1 && parms2;
1236 		     parms1 = TREE_CHAIN (parms1), parms2 = TREE_CHAIN (parms2),
1237 		     count++)
1238 		  {
1239 		    if (type_mismatch_p (TREE_VALUE (parms1), TREE_VALUE (parms2)))
1240 		      {
1241 			if (count == 1 && TREE_CODE (t1) == METHOD_TYPE)
1242 			  inform (loc,
1243 				  "implicit this pointer type mismatch");
1244 			else
1245 			  inform (loc,
1246 				  "type mismatch in parameter %i",
1247 				  count - (TREE_CODE (t1) == METHOD_TYPE));
1248 			warn_types_mismatch (TREE_VALUE (parms1),
1249 					     TREE_VALUE (parms2),
1250 					     loc_t1, loc_t2);
1251 			return;
1252 		      }
1253 		  }
1254 	      if (parms1 || parms2)
1255 		{
1256 		  inform (loc,
1257 			  "types have different parameter counts");
1258 		  return;
1259 		}
1260 	    }
1261 	}
1262       return;
1263     }
1264 
1265   if (types_odr_comparable (t1, t2)
1266       /* We make assign integers mangled names to be able to handle
1267 	 signed/unsigned chars.  Accepting them here would however lead to
1268 	 confussing message like
1269 	 "type ‘const int’ itself violates the C++ One Definition Rule"  */
1270       && TREE_CODE (t1) != INTEGER_TYPE
1271       && types_same_for_odr (t1, t2))
1272     inform (loc_t1,
1273 	    "type %qT itself violates the C++ One Definition Rule", t1);
1274   /* Prevent pointless warnings like "struct aa" should match "struct aa".  */
1275   else if (TYPE_NAME (t1) == TYPE_NAME (t2)
1276 	   && TREE_CODE (t1) == TREE_CODE (t2) && !loc_t2_useful)
1277     return;
1278   else
1279     inform (loc_t1, "type %qT should match type %qT",
1280 	    t1, t2);
1281   if (loc_t2_useful)
1282     inform (loc_t2, "the incompatible type is defined here");
1283 }
1284 
1285 /* Return true if T should be ignored in TYPE_FIELDS for ODR comparsion.  */
1286 
1287 static bool
1288 skip_in_fields_list_p (tree t)
1289 {
1290   if (TREE_CODE (t) != FIELD_DECL)
1291     return true;
1292   /* C++ FE introduces zero sized fields depending on -std setting, see
1293      PR89358.  */
1294   if (DECL_SIZE (t)
1295       && integer_zerop (DECL_SIZE (t))
1296       && DECL_ARTIFICIAL (t)
1297       && DECL_IGNORED_P (t)
1298       && !DECL_NAME (t))
1299     return true;
1300   return false;
1301 }
1302 
1303 /* Compare T1 and T2, report ODR violations if WARN is true and set
1304    WARNED to true if anything is reported.  Return true if types match.
1305    If true is returned, the types are also compatible in the sense of
1306    gimple_canonical_types_compatible_p.
1307    If LOC1 and LOC2 is not UNKNOWN_LOCATION it may be used to output a warning
1308    about the type if the type itself do not have location.  */
1309 
1310 static bool
1311 odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned,
1312 			hash_set<type_pair> *visited,
1313 			location_t loc1, location_t loc2)
1314 {
1315   /* Check first for the obvious case of pointer identity.  */
1316   if (t1 == t2)
1317     return true;
1318 
1319   /* Can't be the same type if the types don't have the same code.  */
1320   if (TREE_CODE (t1) != TREE_CODE (t2))
1321     {
1322       warn_odr (t1, t2, NULL, NULL, warn, warned,
1323 	        G_("a different type is defined in another translation unit"));
1324       return false;
1325     }
1326 
1327   if ((type_with_linkage_p (TYPE_MAIN_VARIANT (t1))
1328        && type_in_anonymous_namespace_p (TYPE_MAIN_VARIANT (t1)))
1329       || (type_with_linkage_p (TYPE_MAIN_VARIANT (t2))
1330 	  && type_in_anonymous_namespace_p (TYPE_MAIN_VARIANT (t2))))
1331     {
1332       /* We cannot trip this when comparing ODR types, only when trying to
1333 	 match different ODR derivations from different declarations.
1334 	 So WARN should be always false.  */
1335       gcc_assert (!warn);
1336       return false;
1337     }
1338 
1339   if (TREE_CODE (t1) == ENUMERAL_TYPE
1340       && TYPE_VALUES (t1) && TYPE_VALUES (t2))
1341     {
1342       tree v1, v2;
1343       for (v1 = TYPE_VALUES (t1), v2 = TYPE_VALUES (t2);
1344 	   v1 && v2 ; v1 = TREE_CHAIN (v1), v2 = TREE_CHAIN (v2))
1345 	{
1346 	  if (TREE_PURPOSE (v1) != TREE_PURPOSE (v2))
1347 	    {
1348 	      warn_odr (t1, t2, NULL, NULL, warn, warned,
1349 			G_("an enum with different value name"
1350 			   " is defined in another translation unit"));
1351 	      return false;
1352 	    }
1353 	  if (!operand_equal_p (TREE_VALUE (v1), TREE_VALUE (v2), 0))
1354 	    {
1355 	      warn_odr (t1, t2, NULL, NULL, warn, warned,
1356 			G_("an enum with different values is defined"
1357 			   " in another translation unit"));
1358 	      return false;
1359 	    }
1360 	}
1361       if (v1 || v2)
1362 	{
1363 	  warn_odr (t1, t2, NULL, NULL, warn, warned,
1364 		    G_("an enum with mismatching number of values "
1365 		       "is defined in another translation unit"));
1366 	  return false;
1367 	}
1368     }
1369 
1370   /* Non-aggregate types can be handled cheaply.  */
1371   if (INTEGRAL_TYPE_P (t1)
1372       || SCALAR_FLOAT_TYPE_P (t1)
1373       || FIXED_POINT_TYPE_P (t1)
1374       || TREE_CODE (t1) == VECTOR_TYPE
1375       || TREE_CODE (t1) == COMPLEX_TYPE
1376       || TREE_CODE (t1) == OFFSET_TYPE
1377       || POINTER_TYPE_P (t1))
1378     {
1379       if (TYPE_PRECISION (t1) != TYPE_PRECISION (t2))
1380 	{
1381 	  warn_odr (t1, t2, NULL, NULL, warn, warned,
1382 		    G_("a type with different precision is defined "
1383 		       "in another translation unit"));
1384 	  return false;
1385 	}
1386       if (TYPE_UNSIGNED (t1) != TYPE_UNSIGNED (t2))
1387 	{
1388 	  warn_odr (t1, t2, NULL, NULL, warn, warned,
1389 		    G_("a type with different signedness is defined "
1390 		       "in another translation unit"));
1391 	  return false;
1392 	}
1393 
1394       if (TREE_CODE (t1) == INTEGER_TYPE
1395 	  && TYPE_STRING_FLAG (t1) != TYPE_STRING_FLAG (t2))
1396 	{
1397 	  /* char WRT uint_8?  */
1398 	  warn_odr (t1, t2, NULL, NULL, warn, warned,
1399 		    G_("a different type is defined in another "
1400 		       "translation unit"));
1401 	  return false;
1402 	}
1403 
1404       /* For canonical type comparisons we do not want to build SCCs
1405 	 so we cannot compare pointed-to types.  But we can, for now,
1406 	 require the same pointed-to type kind and match what
1407 	 useless_type_conversion_p would do.  */
1408       if (POINTER_TYPE_P (t1))
1409 	{
1410 	  if (TYPE_ADDR_SPACE (TREE_TYPE (t1))
1411 	      != TYPE_ADDR_SPACE (TREE_TYPE (t2)))
1412 	    {
1413 	      warn_odr (t1, t2, NULL, NULL, warn, warned,
1414 			G_("it is defined as a pointer in different address "
1415 			   "space in another translation unit"));
1416 	      return false;
1417 	    }
1418 
1419 	  if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2),
1420 					  visited, loc1, loc2))
1421 	    {
1422 	      warn_odr (t1, t2, NULL, NULL, warn, warned,
1423 			G_("it is defined as a pointer to different type "
1424 			   "in another translation unit"));
1425 	      if (warn && warned)
1426 	        warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2),
1427 				     loc1, loc2);
1428 	      return false;
1429 	    }
1430 	}
1431 
1432       if ((TREE_CODE (t1) == VECTOR_TYPE || TREE_CODE (t1) == COMPLEX_TYPE)
1433 	  && !odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2),
1434 					 visited, loc1, loc2))
1435 	{
1436 	  /* Probably specific enough.  */
1437 	  warn_odr (t1, t2, NULL, NULL, warn, warned,
1438 		    G_("a different type is defined "
1439 		       "in another translation unit"));
1440 	  if (warn && warned)
1441 	    warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc1, loc2);
1442 	  return false;
1443 	}
1444     }
1445   /* Do type-specific comparisons.  */
1446   else switch (TREE_CODE (t1))
1447     {
1448     case ARRAY_TYPE:
1449       {
1450 	/* Array types are the same if the element types are the same and
1451 	   the number of elements are the same.  */
1452 	if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2),
1453 					visited, loc1, loc2))
1454 	  {
1455 	    warn_odr (t1, t2, NULL, NULL, warn, warned,
1456 		      G_("a different type is defined in another "
1457 			 "translation unit"));
1458 	    if (warn && warned)
1459 	      warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc1, loc2);
1460 	  }
1461 	gcc_assert (TYPE_STRING_FLAG (t1) == TYPE_STRING_FLAG (t2));
1462 	gcc_assert (TYPE_NONALIASED_COMPONENT (t1)
1463 		    == TYPE_NONALIASED_COMPONENT (t2));
1464 
1465 	tree i1 = TYPE_DOMAIN (t1);
1466 	tree i2 = TYPE_DOMAIN (t2);
1467 
1468 	/* For an incomplete external array, the type domain can be
1469 	   NULL_TREE.  Check this condition also.  */
1470 	if (i1 == NULL_TREE || i2 == NULL_TREE)
1471           return type_variants_equivalent_p (t1, t2);
1472 
1473 	tree min1 = TYPE_MIN_VALUE (i1);
1474 	tree min2 = TYPE_MIN_VALUE (i2);
1475 	tree max1 = TYPE_MAX_VALUE (i1);
1476 	tree max2 = TYPE_MAX_VALUE (i2);
1477 
1478 	/* In C++, minimums should be always 0.  */
1479 	gcc_assert (min1 == min2);
1480 	if (!operand_equal_p (max1, max2, 0))
1481 	  {
1482 	    warn_odr (t1, t2, NULL, NULL, warn, warned,
1483 		      G_("an array of different size is defined "
1484 			 "in another translation unit"));
1485 	    return false;
1486 	  }
1487       }
1488     break;
1489 
1490     case METHOD_TYPE:
1491     case FUNCTION_TYPE:
1492       /* Function types are the same if the return type and arguments types
1493 	 are the same.  */
1494       if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2),
1495 				      visited, loc1, loc2))
1496 	{
1497 	  warn_odr (t1, t2, NULL, NULL, warn, warned,
1498 		    G_("has different return value "
1499 		       "in another translation unit"));
1500 	  if (warn && warned)
1501 	    warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2), loc1, loc2);
1502 	  return false;
1503 	}
1504 
1505       if (TYPE_ARG_TYPES (t1) == TYPE_ARG_TYPES (t2)
1506 	  || !prototype_p (t1) || !prototype_p (t2))
1507         return type_variants_equivalent_p (t1, t2);
1508       else
1509 	{
1510 	  tree parms1, parms2;
1511 
1512 	  for (parms1 = TYPE_ARG_TYPES (t1), parms2 = TYPE_ARG_TYPES (t2);
1513 	       parms1 && parms2;
1514 	       parms1 = TREE_CHAIN (parms1), parms2 = TREE_CHAIN (parms2))
1515 	    {
1516 	      if (!odr_subtypes_equivalent_p
1517 		     (TREE_VALUE (parms1), TREE_VALUE (parms2),
1518 		      visited, loc1, loc2))
1519 		{
1520 		  warn_odr (t1, t2, NULL, NULL, warn, warned,
1521 			    G_("has different parameters in another "
1522 			       "translation unit"));
1523 		  if (warn && warned)
1524 		    warn_types_mismatch (TREE_VALUE (parms1),
1525 					 TREE_VALUE (parms2), loc1, loc2);
1526 		  return false;
1527 		}
1528 	    }
1529 
1530 	  if (parms1 || parms2)
1531 	    {
1532 	      warn_odr (t1, t2, NULL, NULL, warn, warned,
1533 			G_("has different parameters "
1534 			   "in another translation unit"));
1535 	      return false;
1536 	    }
1537 
1538           return type_variants_equivalent_p (t1, t2);
1539 	}
1540 
1541     case RECORD_TYPE:
1542     case UNION_TYPE:
1543     case QUAL_UNION_TYPE:
1544       {
1545 	tree f1, f2;
1546 
1547 	/* For aggregate types, all the fields must be the same.  */
1548 	if (COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2))
1549 	  {
1550 	    if (TYPE_BINFO (t1) && TYPE_BINFO (t2)
1551 	        && polymorphic_type_binfo_p (TYPE_BINFO (t1))
1552 		   != polymorphic_type_binfo_p (TYPE_BINFO (t2)))
1553 	      {
1554 		if (polymorphic_type_binfo_p (TYPE_BINFO (t1)))
1555 		  warn_odr (t1, t2, NULL, NULL, warn, warned,
1556 			    G_("a type defined in another translation unit "
1557 			       "is not polymorphic"));
1558 		else
1559 		  warn_odr (t1, t2, NULL, NULL, warn, warned,
1560 			    G_("a type defined in another translation unit "
1561 			       "is polymorphic"));
1562 		return false;
1563 	      }
1564 	    for (f1 = TYPE_FIELDS (t1), f2 = TYPE_FIELDS (t2);
1565 		 f1 || f2;
1566 		 f1 = TREE_CHAIN (f1), f2 = TREE_CHAIN (f2))
1567 	      {
1568 		/* Skip non-fields.  */
1569 		while (f1 && skip_in_fields_list_p (f1))
1570 		  f1 = TREE_CHAIN (f1);
1571 		while (f2 && skip_in_fields_list_p (f2))
1572 		  f2 = TREE_CHAIN (f2);
1573 		if (!f1 || !f2)
1574 		  break;
1575 		if (DECL_VIRTUAL_P (f1) != DECL_VIRTUAL_P (f2))
1576 		  {
1577 		    warn_odr (t1, t2, NULL, NULL, warn, warned,
1578 			      G_("a type with different virtual table pointers"
1579 			         " is defined in another translation unit"));
1580 		    return false;
1581 		  }
1582 		if (DECL_ARTIFICIAL (f1) != DECL_ARTIFICIAL (f2))
1583 		  {
1584 		    warn_odr (t1, t2, NULL, NULL, warn, warned,
1585 			      G_("a type with different bases is defined "
1586 				 "in another translation unit"));
1587 		    return false;
1588 		  }
1589 		if (DECL_NAME (f1) != DECL_NAME (f2)
1590 		    && !DECL_ARTIFICIAL (f1))
1591 		  {
1592 		    warn_odr (t1, t2, f1, f2, warn, warned,
1593 			      G_("a field with different name is defined "
1594 				 "in another translation unit"));
1595 		    return false;
1596 		  }
1597 		if (!odr_subtypes_equivalent_p (TREE_TYPE (f1),
1598 						TREE_TYPE (f2),
1599 						visited, loc1, loc2))
1600 		  {
1601 		    /* Do not warn about artificial fields and just go into
1602  		       generic field mismatch warning.  */
1603 		    if (DECL_ARTIFICIAL (f1))
1604 		      break;
1605 
1606 		    warn_odr (t1, t2, f1, f2, warn, warned,
1607 			      G_("a field of same name but different type "
1608 				 "is defined in another translation unit"));
1609 		    if (warn && warned)
1610 		      warn_types_mismatch (TREE_TYPE (f1), TREE_TYPE (f2), loc1, loc2);
1611 		    return false;
1612 		  }
1613 		if (!gimple_compare_field_offset (f1, f2))
1614 		  {
1615 		    /* Do not warn about artificial fields and just go into
1616 		       generic field mismatch warning.  */
1617 		    if (DECL_ARTIFICIAL (f1))
1618 		      break;
1619 		    warn_odr (t1, t2, f1, f2, warn, warned,
1620 			      G_("fields have different layout "
1621 				 "in another translation unit"));
1622 		    return false;
1623 		  }
1624 		if (DECL_BIT_FIELD (f1) != DECL_BIT_FIELD (f2))
1625 		  {
1626 		    warn_odr (t1, t2, f1, f2, warn, warned,
1627 			      G_("one field is a bitfield while the other "
1628 				 "is not"));
1629 		    return false;
1630 		  }
1631 		else
1632 		  gcc_assert (DECL_NONADDRESSABLE_P (f1)
1633 			      == DECL_NONADDRESSABLE_P (f2));
1634 	      }
1635 
1636 	    /* If one aggregate has more fields than the other, they
1637 	       are not the same.  */
1638 	    if (f1 || f2)
1639 	      {
1640 		if ((f1 && DECL_VIRTUAL_P (f1)) || (f2 && DECL_VIRTUAL_P (f2)))
1641 		  warn_odr (t1, t2, NULL, NULL, warn, warned,
1642 			    G_("a type with different virtual table pointers"
1643 			       " is defined in another translation unit"));
1644 		else if ((f1 && DECL_ARTIFICIAL (f1))
1645 		         || (f2 && DECL_ARTIFICIAL (f2)))
1646 		  warn_odr (t1, t2, NULL, NULL, warn, warned,
1647 			    G_("a type with different bases is defined "
1648 			       "in another translation unit"));
1649 		else
1650 		  warn_odr (t1, t2, f1, f2, warn, warned,
1651 			    G_("a type with different number of fields "
1652 			       "is defined in another translation unit"));
1653 
1654 		return false;
1655 	      }
1656 	  }
1657 	break;
1658       }
1659     case VOID_TYPE:
1660     case NULLPTR_TYPE:
1661       break;
1662 
1663     default:
1664       debug_tree (t1);
1665       gcc_unreachable ();
1666     }
1667 
1668   /* Those are better to come last as they are utterly uninformative.  */
1669   if (TYPE_SIZE (t1) && TYPE_SIZE (t2)
1670       && !operand_equal_p (TYPE_SIZE (t1), TYPE_SIZE (t2), 0))
1671     {
1672       warn_odr (t1, t2, NULL, NULL, warn, warned,
1673 		G_("a type with different size "
1674 		   "is defined in another translation unit"));
1675       return false;
1676     }
1677 
1678   gcc_assert (!TYPE_SIZE_UNIT (t1) || !TYPE_SIZE_UNIT (t2)
1679 	      || operand_equal_p (TYPE_SIZE_UNIT (t1),
1680 				  TYPE_SIZE_UNIT (t2), 0));
1681   return type_variants_equivalent_p (t1, t2);
1682 }
1683 
1684 /* Return true if TYPE1 and TYPE2 are equivalent for One Definition Rule.  */
1685 
1686 bool
1687 odr_types_equivalent_p (tree type1, tree type2)
1688 {
1689   gcc_checking_assert (odr_or_derived_type_p (type1)
1690 		       && odr_or_derived_type_p (type2));
1691 
1692   hash_set<type_pair> visited;
1693   return odr_types_equivalent_p (type1, type2, false, NULL,
1694 			         &visited, UNKNOWN_LOCATION, UNKNOWN_LOCATION);
1695 }
1696 
1697 /* TYPE is equivalent to VAL by ODR, but its tree representation differs
1698    from VAL->type.  This may happen in LTO where tree merging did not merge
1699    all variants of the same type or due to ODR violation.
1700 
1701    Analyze and report ODR violations and add type to duplicate list.
1702    If TYPE is more specified than VAL->type, prevail VAL->type.  Also if
1703    this is first time we see definition of a class return true so the
1704    base types are analyzed.  */
1705 
1706 static bool
1707 add_type_duplicate (odr_type val, tree type)
1708 {
1709   bool build_bases = false;
1710   bool prevail = false;
1711   bool odr_must_violate = false;
1712 
1713   if (!val->types_set)
1714     val->types_set = new hash_set<tree>;
1715 
1716   /* Chose polymorphic type as leader (this happens only in case of ODR
1717      violations.  */
1718   if ((TREE_CODE (type) == RECORD_TYPE && TYPE_BINFO (type)
1719        && polymorphic_type_binfo_p (TYPE_BINFO (type)))
1720       && (TREE_CODE (val->type) != RECORD_TYPE || !TYPE_BINFO (val->type)
1721           || !polymorphic_type_binfo_p (TYPE_BINFO (val->type))))
1722     {
1723       prevail = true;
1724       build_bases = true;
1725     }
1726   /* Always prefer complete type to be the leader.  */
1727   else if (!COMPLETE_TYPE_P (val->type) && COMPLETE_TYPE_P (type))
1728     {
1729       prevail = true;
1730       if (TREE_CODE (type) == RECORD_TYPE)
1731         build_bases = TYPE_BINFO (type);
1732     }
1733   else if (COMPLETE_TYPE_P (val->type) && !COMPLETE_TYPE_P (type))
1734     ;
1735   else if (TREE_CODE (val->type) == ENUMERAL_TYPE
1736 	   && TREE_CODE (type) == ENUMERAL_TYPE
1737 	   && !TYPE_VALUES (val->type) && TYPE_VALUES (type))
1738     prevail = true;
1739   else if (TREE_CODE (val->type) == RECORD_TYPE
1740 	   && TREE_CODE (type) == RECORD_TYPE
1741 	   && TYPE_BINFO (type) && !TYPE_BINFO (val->type))
1742     {
1743       gcc_assert (!val->bases.length ());
1744       build_bases = true;
1745       prevail = true;
1746     }
1747 
1748   if (prevail)
1749     std::swap (val->type, type);
1750 
1751   val->types_set->add (type);
1752 
1753   /* If we now have a mangled name, be sure to record it to val->type
1754      so ODR hash can work.  */
1755 
1756   if (can_be_name_hashed_p (type) && !can_be_name_hashed_p (val->type))
1757     SET_DECL_ASSEMBLER_NAME (TYPE_NAME (val->type),
1758 			     DECL_ASSEMBLER_NAME (TYPE_NAME (type)));
1759 
1760   bool merge = true;
1761   bool base_mismatch = false;
1762   unsigned int i;
1763   bool warned = false;
1764   hash_set<type_pair> visited;
1765 
1766   gcc_assert (in_lto_p);
1767   vec_safe_push (val->types, type);
1768 
1769   /* If both are class types, compare the bases.  */
1770   if (COMPLETE_TYPE_P (type) && COMPLETE_TYPE_P (val->type)
1771       && TREE_CODE (val->type) == RECORD_TYPE
1772       && TREE_CODE (type) == RECORD_TYPE
1773       && TYPE_BINFO (val->type) && TYPE_BINFO (type))
1774     {
1775       if (BINFO_N_BASE_BINFOS (TYPE_BINFO (type))
1776 	  != BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)))
1777 	{
1778 	  if (!flag_ltrans && !warned && !val->odr_violated)
1779 	    {
1780 	      tree extra_base;
1781 	      warn_odr (type, val->type, NULL, NULL, !warned, &warned,
1782 			"a type with the same name but different "
1783 			"number of polymorphic bases is "
1784 			"defined in another translation unit");
1785 	      if (warned)
1786 		{
1787 		  if (BINFO_N_BASE_BINFOS (TYPE_BINFO (type))
1788 		      > BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)))
1789 		    extra_base = BINFO_BASE_BINFO
1790 				 (TYPE_BINFO (type),
1791 				  BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)));
1792 		  else
1793 		    extra_base = BINFO_BASE_BINFO
1794 				 (TYPE_BINFO (val->type),
1795 				  BINFO_N_BASE_BINFOS (TYPE_BINFO (type)));
1796 		  tree extra_base_type = BINFO_TYPE (extra_base);
1797 		  inform (DECL_SOURCE_LOCATION (TYPE_NAME (extra_base_type)),
1798 			  "the extra base is defined here");
1799 		}
1800 	    }
1801 	  base_mismatch = true;
1802 	}
1803       else
1804 	for (i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
1805 	  {
1806 	    tree base1 = BINFO_BASE_BINFO (TYPE_BINFO (type), i);
1807 	    tree base2 = BINFO_BASE_BINFO (TYPE_BINFO (val->type), i);
1808 	    tree type1 = BINFO_TYPE (base1);
1809 	    tree type2 = BINFO_TYPE (base2);
1810 
1811 	    if (types_odr_comparable (type1, type2))
1812 	      {
1813 		if (!types_same_for_odr (type1, type2))
1814 		  base_mismatch = true;
1815 	      }
1816 	    else
1817 	      if (!odr_types_equivalent_p (type1, type2))
1818 		base_mismatch = true;
1819 	    if (base_mismatch)
1820 	      {
1821 		if (!warned && !val->odr_violated)
1822 		  {
1823 		    warn_odr (type, val->type, NULL, NULL,
1824 			      !warned, &warned,
1825 			      "a type with the same name but different base "
1826 			      "type is defined in another translation unit");
1827 		    if (warned)
1828 		      warn_types_mismatch (type1, type2,
1829 					    UNKNOWN_LOCATION, UNKNOWN_LOCATION);
1830 		  }
1831 		break;
1832 	      }
1833 	    if (BINFO_OFFSET (base1) != BINFO_OFFSET (base2))
1834 	      {
1835 		base_mismatch = true;
1836 		if (!warned && !val->odr_violated)
1837 		  warn_odr (type, val->type, NULL, NULL,
1838 			    !warned, &warned,
1839 			    "a type with the same name but different base "
1840 			    "layout is defined in another translation unit");
1841 		break;
1842 	      }
1843 	    /* One of bases is not of complete type.  */
1844 	    if (!TYPE_BINFO (type1) != !TYPE_BINFO (type2))
1845 	      {
1846 		/* If we have a polymorphic type info specified for TYPE1
1847 		   but not for TYPE2 we possibly missed a base when recording
1848 		   VAL->type earlier.
1849 		   Be sure this does not happen.  */
1850 		if (TYPE_BINFO (type1)
1851 		    && polymorphic_type_binfo_p (TYPE_BINFO (type1))
1852 		    && !build_bases)
1853 		  odr_must_violate = true;
1854 	        break;
1855 	      }
1856 	    /* One base is polymorphic and the other not.
1857 	       This ought to be diagnosed earlier, but do not ICE in the
1858 	       checking bellow.  */
1859 	    else if (TYPE_BINFO (type1)
1860 		     && polymorphic_type_binfo_p (TYPE_BINFO (type1))
1861 		        != polymorphic_type_binfo_p (TYPE_BINFO (type2)))
1862 	      {
1863 		if (!warned && !val->odr_violated)
1864 		  warn_odr (type, val->type, NULL, NULL,
1865 			    !warned, &warned,
1866 			    "a base of the type is polymorphic only in one "
1867 			    "translation unit");
1868 		base_mismatch = true;
1869 		break;
1870 	      }
1871 	  }
1872       if (base_mismatch)
1873 	{
1874 	  merge = false;
1875 	  odr_violation_reported = true;
1876 	  val->odr_violated = true;
1877 
1878 	  if (symtab->dump_file)
1879 	    {
1880 	      fprintf (symtab->dump_file, "ODR base violation\n");
1881 
1882 	      print_node (symtab->dump_file, "", val->type, 0);
1883 	      putc ('\n',symtab->dump_file);
1884 	      print_node (symtab->dump_file, "", type, 0);
1885 	      putc ('\n',symtab->dump_file);
1886 	    }
1887 	}
1888     }
1889 
1890   /* Next compare memory layout.
1891      The DECL_SOURCE_LOCATIONs in this invocation came from LTO streaming.
1892      We must apply the location cache to ensure that they are valid
1893      before we can pass them to odr_types_equivalent_p (PR lto/83121).  */
1894   if (lto_location_cache::current_cache)
1895     lto_location_cache::current_cache->apply_location_cache ();
1896   /* As a special case we stream mangles names of integer types so we can see
1897      if they are believed to be same even though they have different
1898      representation.  Avoid bogus warning on mismatches in these.  */
1899   if (TREE_CODE (type) != INTEGER_TYPE
1900       && TREE_CODE (val->type) != INTEGER_TYPE
1901       && !odr_types_equivalent_p (val->type, type,
1902 			       !flag_ltrans && !val->odr_violated && !warned,
1903 			       &warned, &visited,
1904 			       DECL_SOURCE_LOCATION (TYPE_NAME (val->type)),
1905 			       DECL_SOURCE_LOCATION (TYPE_NAME (type))))
1906     {
1907       merge = false;
1908       odr_violation_reported = true;
1909       val->odr_violated = true;
1910     }
1911   gcc_assert (val->odr_violated || !odr_must_violate);
1912   /* Sanity check that all bases will be build same way again.  */
1913   if (flag_checking
1914       && COMPLETE_TYPE_P (type) && COMPLETE_TYPE_P (val->type)
1915       && TREE_CODE (val->type) == RECORD_TYPE
1916       && TREE_CODE (type) == RECORD_TYPE
1917       && TYPE_BINFO (val->type) && TYPE_BINFO (type)
1918       && !val->odr_violated
1919       && !base_mismatch && val->bases.length ())
1920     {
1921       unsigned int num_poly_bases = 0;
1922       unsigned int j;
1923 
1924       for (i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
1925 	if (polymorphic_type_binfo_p (BINFO_BASE_BINFO
1926 					 (TYPE_BINFO (type), i)))
1927 	  num_poly_bases++;
1928       gcc_assert (num_poly_bases == val->bases.length ());
1929       for (j = 0, i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type));
1930 	   i++)
1931 	if (polymorphic_type_binfo_p (BINFO_BASE_BINFO
1932 				       (TYPE_BINFO (type), i)))
1933 	  {
1934 	    odr_type base = get_odr_type
1935 			       (BINFO_TYPE
1936 				  (BINFO_BASE_BINFO (TYPE_BINFO (type),
1937 						     i)),
1938 				true);
1939 	    gcc_assert (val->bases[j] == base);
1940 	    j++;
1941 	  }
1942     }
1943 
1944 
1945   /* Regularize things a little.  During LTO same types may come with
1946      different BINFOs.  Either because their virtual table was
1947      not merged by tree merging and only later at decl merging or
1948      because one type comes with external vtable, while other
1949      with internal.  We want to merge equivalent binfos to conserve
1950      memory and streaming overhead.
1951 
1952      The external vtables are more harmful: they contain references
1953      to external declarations of methods that may be defined in the
1954      merged LTO unit.  For this reason we absolutely need to remove
1955      them and replace by internal variants. Not doing so will lead
1956      to incomplete answers from possible_polymorphic_call_targets.
1957 
1958      FIXME: disable for now; because ODR types are now build during
1959      streaming in, the variants do not need to be linked to the type,
1960      yet.  We need to do the merging in cleanup pass to be implemented
1961      soon.  */
1962   if (!flag_ltrans && merge
1963       && 0
1964       && TREE_CODE (val->type) == RECORD_TYPE
1965       && TREE_CODE (type) == RECORD_TYPE
1966       && TYPE_BINFO (val->type) && TYPE_BINFO (type)
1967       && TYPE_MAIN_VARIANT (type) == type
1968       && TYPE_MAIN_VARIANT (val->type) == val->type
1969       && BINFO_VTABLE (TYPE_BINFO (val->type))
1970       && BINFO_VTABLE (TYPE_BINFO (type)))
1971     {
1972       tree master_binfo = TYPE_BINFO (val->type);
1973       tree v1 = BINFO_VTABLE (master_binfo);
1974       tree v2 = BINFO_VTABLE (TYPE_BINFO (type));
1975 
1976       if (TREE_CODE (v1) == POINTER_PLUS_EXPR)
1977 	{
1978 	  gcc_assert (TREE_CODE (v2) == POINTER_PLUS_EXPR
1979 		      && operand_equal_p (TREE_OPERAND (v1, 1),
1980 					  TREE_OPERAND (v2, 1), 0));
1981 	  v1 = TREE_OPERAND (TREE_OPERAND (v1, 0), 0);
1982 	  v2 = TREE_OPERAND (TREE_OPERAND (v2, 0), 0);
1983 	}
1984       gcc_assert (DECL_ASSEMBLER_NAME (v1)
1985 		  == DECL_ASSEMBLER_NAME (v2));
1986 
1987       if (DECL_EXTERNAL (v1) && !DECL_EXTERNAL (v2))
1988 	{
1989 	  unsigned int i;
1990 
1991 	  set_type_binfo (val->type, TYPE_BINFO (type));
1992 	  for (i = 0; i < val->types->length (); i++)
1993 	    {
1994 	      if (TYPE_BINFO ((*val->types)[i])
1995 		  == master_binfo)
1996 		set_type_binfo ((*val->types)[i], TYPE_BINFO (type));
1997 	    }
1998 	  BINFO_TYPE (TYPE_BINFO (type)) = val->type;
1999 	}
2000       else
2001 	set_type_binfo (type, master_binfo);
2002     }
2003   return build_bases;
2004 }
2005 
2006 /* REF is OBJ_TYPE_REF, return the class the ref corresponds to.  */
2007 
2008 tree
2009 obj_type_ref_class (const_tree ref)
2010 {
2011   gcc_checking_assert (TREE_CODE (ref) == OBJ_TYPE_REF);
2012   ref = TREE_TYPE (ref);
2013   gcc_checking_assert (TREE_CODE (ref) == POINTER_TYPE);
2014   ref = TREE_TYPE (ref);
2015   /* We look for type THIS points to.  ObjC also builds
2016      OBJ_TYPE_REF with non-method calls, Their first parameter
2017      ID however also corresponds to class type. */
2018   gcc_checking_assert (TREE_CODE (ref) == METHOD_TYPE
2019 		       || TREE_CODE (ref) == FUNCTION_TYPE);
2020   ref = TREE_VALUE (TYPE_ARG_TYPES (ref));
2021   gcc_checking_assert (TREE_CODE (ref) == POINTER_TYPE);
2022   tree ret = TREE_TYPE (ref);
2023   if (!in_lto_p && !TYPE_STRUCTURAL_EQUALITY_P (ret))
2024     ret = TYPE_CANONICAL (ret);
2025   else
2026     ret = get_odr_type (ret)->type;
2027   return ret;
2028 }
2029 
2030 /* Get ODR type hash entry for TYPE.  If INSERT is true, create
2031    possibly new entry.  */
2032 
2033 odr_type
2034 get_odr_type (tree type, bool insert)
2035 {
2036   odr_type_d **slot = NULL;
2037   odr_type_d **vtable_slot = NULL;
2038   odr_type val = NULL;
2039   hashval_t hash;
2040   bool build_bases = false;
2041   bool insert_to_odr_array = false;
2042   int base_id = -1;
2043 
2044   type = TYPE_MAIN_VARIANT (type);
2045   if (!in_lto_p && !TYPE_STRUCTURAL_EQUALITY_P (type))
2046     type = TYPE_CANONICAL (type);
2047 
2048   gcc_checking_assert (can_be_name_hashed_p (type)
2049 		       || can_be_vtable_hashed_p (type));
2050 
2051   /* Lookup entry, first try name hash, fallback to vtable hash.  */
2052   if (can_be_name_hashed_p (type))
2053     {
2054       hash = hash_odr_name (type);
2055       slot = odr_hash->find_slot_with_hash (type, hash,
2056 					    insert ? INSERT : NO_INSERT);
2057     }
2058   if ((!slot || !*slot) && in_lto_p && can_be_vtable_hashed_p (type))
2059     {
2060       hash = hash_odr_vtable (type);
2061       if (!odr_vtable_hash)
2062         odr_vtable_hash = new odr_vtable_hash_type (23);
2063       vtable_slot = odr_vtable_hash->find_slot_with_hash (type, hash,
2064 					           insert ? INSERT : NO_INSERT);
2065     }
2066 
2067   if (!slot && !vtable_slot)
2068     return NULL;
2069 
2070   /* See if we already have entry for type.  */
2071   if ((slot && *slot) || (vtable_slot && *vtable_slot))
2072     {
2073       if (slot && *slot)
2074 	{
2075 	  val = *slot;
2076 	  if (flag_checking
2077 	      && in_lto_p && can_be_vtable_hashed_p (type))
2078 	    {
2079 	      hash = hash_odr_vtable (type);
2080 	      vtable_slot = odr_vtable_hash->find_slot_with_hash (type, hash,
2081 						                  NO_INSERT);
2082 	      gcc_assert (!vtable_slot || *vtable_slot == *slot);
2083 	      vtable_slot = NULL;
2084 	    }
2085 	}
2086       else if (*vtable_slot)
2087 	val = *vtable_slot;
2088 
2089       if (val->type != type && insert
2090 	  && (!val->types_set || !val->types_set->add (type)))
2091 	{
2092 	  /* We have type duplicate, but it may introduce vtable name or
2093  	     mangled name; be sure to keep hashes in sync.  */
2094 	  if (in_lto_p && can_be_vtable_hashed_p (type)
2095 	      && (!vtable_slot || !*vtable_slot))
2096 	    {
2097 	      if (!vtable_slot)
2098 		{
2099 		  hash = hash_odr_vtable (type);
2100 		  vtable_slot = odr_vtable_hash->find_slot_with_hash
2101 			     (type, hash, INSERT);
2102 		  gcc_checking_assert (!*vtable_slot || *vtable_slot == val);
2103 		}
2104 	      *vtable_slot = val;
2105 	    }
2106 	  if (slot && !*slot)
2107 	    *slot = val;
2108 	  build_bases = add_type_duplicate (val, type);
2109 	}
2110     }
2111   else
2112     {
2113       val = ggc_cleared_alloc<odr_type_d> ();
2114       val->type = type;
2115       val->bases = vNULL;
2116       val->derived_types = vNULL;
2117       if (type_with_linkage_p (type))
2118         val->anonymous_namespace = type_in_anonymous_namespace_p (type);
2119       else
2120 	val->anonymous_namespace = 0;
2121       build_bases = COMPLETE_TYPE_P (val->type);
2122       insert_to_odr_array = true;
2123       if (slot)
2124         *slot = val;
2125       if (vtable_slot)
2126 	*vtable_slot = val;
2127     }
2128 
2129   if (build_bases && TREE_CODE (type) == RECORD_TYPE && TYPE_BINFO (type)
2130       && type_with_linkage_p (type)
2131       && type == TYPE_MAIN_VARIANT (type))
2132     {
2133       tree binfo = TYPE_BINFO (type);
2134       unsigned int i;
2135 
2136       gcc_assert (BINFO_TYPE (TYPE_BINFO (val->type)) == type);
2137 
2138       val->all_derivations_known = type_all_derivations_known_p (type);
2139       for (i = 0; i < BINFO_N_BASE_BINFOS (binfo); i++)
2140 	/* For now record only polymorphic types. other are
2141 	   pointless for devirtualization and we cannot precisely
2142 	   determine ODR equivalency of these during LTO.  */
2143 	if (polymorphic_type_binfo_p (BINFO_BASE_BINFO (binfo, i)))
2144 	  {
2145 	    tree base_type= BINFO_TYPE (BINFO_BASE_BINFO (binfo, i));
2146 	    odr_type base = get_odr_type (base_type, true);
2147 	    gcc_assert (TYPE_MAIN_VARIANT (base_type) == base_type);
2148 	    base->derived_types.safe_push (val);
2149 	    val->bases.safe_push (base);
2150 	    if (base->id > base_id)
2151 	      base_id = base->id;
2152 	  }
2153       }
2154   /* Ensure that type always appears after bases.  */
2155   if (insert_to_odr_array)
2156     {
2157       if (odr_types_ptr)
2158         val->id = odr_types.length ();
2159       vec_safe_push (odr_types_ptr, val);
2160     }
2161   else if (base_id > val->id)
2162     {
2163       odr_types[val->id] = 0;
2164       /* Be sure we did not recorded any derived types; these may need
2165 	 renumbering too.  */
2166       gcc_assert (val->derived_types.length() == 0);
2167       val->id = odr_types.length ();
2168       vec_safe_push (odr_types_ptr, val);
2169     }
2170   return val;
2171 }
2172 
2173 bool
2174 odr_type_violation_reported_p (tree type)
2175 {
2176   return get_odr_type (type, false)->odr_violated;
2177 }
2178 
2179 /* Add TYPE od ODR type hash.  */
2180 
2181 void
2182 register_odr_type (tree type)
2183 {
2184   if (!odr_hash)
2185     {
2186       odr_hash = new odr_hash_type (23);
2187       if (in_lto_p)
2188         odr_vtable_hash = new odr_vtable_hash_type (23);
2189     }
2190   if (type == TYPE_MAIN_VARIANT (type))
2191     {
2192       /* To get ODR warings right, first register all sub-types.  */
2193       if (RECORD_OR_UNION_TYPE_P (type)
2194 	  && COMPLETE_TYPE_P (type))
2195 	{
2196 	  /* Limit recursion on types which are already registered.  */
2197 	  odr_type ot = get_odr_type (type, false);
2198 	  if (ot
2199 	      && (ot->type == type
2200 		  || (ot->types_set
2201 		      && ot->types_set->contains (type))))
2202 	    return;
2203 	  for (tree f = TYPE_FIELDS (type); f; f = TREE_CHAIN (f))
2204 	    if (TREE_CODE (f) == FIELD_DECL)
2205 	      {
2206 		tree subtype = TREE_TYPE (f);
2207 
2208 		while (TREE_CODE (subtype) == ARRAY_TYPE)
2209 		  subtype = TREE_TYPE (subtype);
2210 		if (type_with_linkage_p (TYPE_MAIN_VARIANT (subtype)))
2211 		  register_odr_type (TYPE_MAIN_VARIANT (subtype));
2212 	      }
2213 	   if (TYPE_BINFO (type))
2214 	     for (unsigned int i = 0;
2215 	          i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
2216 	       register_odr_type (BINFO_TYPE (BINFO_BASE_BINFO
2217 						 (TYPE_BINFO (type), i)));
2218 	}
2219       get_odr_type (type, true);
2220     }
2221 }
2222 
2223 /* Return true if type is known to have no derivations.  */
2224 
2225 bool
2226 type_known_to_have_no_derivations_p (tree t)
2227 {
2228   return (type_all_derivations_known_p (t)
2229 	  && (TYPE_FINAL_P (t)
2230 	      || (odr_hash
2231 		  && !get_odr_type (t, true)->derived_types.length())));
2232 }
2233 
2234 /* Dump ODR type T and all its derived types.  INDENT specifies indentation for
2235    recursive printing.  */
2236 
2237 static void
2238 dump_odr_type (FILE *f, odr_type t, int indent=0)
2239 {
2240   unsigned int i;
2241   fprintf (f, "%*s type %i: ", indent * 2, "", t->id);
2242   print_generic_expr (f, t->type, TDF_SLIM);
2243   fprintf (f, "%s", t->anonymous_namespace ? " (anonymous namespace)":"");
2244   fprintf (f, "%s\n", t->all_derivations_known ? " (derivations known)":"");
2245   if (TYPE_NAME (t->type))
2246     {
2247       /*fprintf (f, "%*s defined at: %s:%i\n", indent * 2, "",
2248 	       DECL_SOURCE_FILE (TYPE_NAME (t->type)),
2249 	       DECL_SOURCE_LINE (TYPE_NAME (t->type)));*/
2250       if (DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t->type)))
2251         fprintf (f, "%*s mangled name: %s\n", indent * 2, "",
2252 		 IDENTIFIER_POINTER
2253 		   (DECL_ASSEMBLER_NAME (TYPE_NAME (t->type))));
2254     }
2255   if (t->bases.length ())
2256     {
2257       fprintf (f, "%*s base odr type ids: ", indent * 2, "");
2258       for (i = 0; i < t->bases.length (); i++)
2259 	fprintf (f, " %i", t->bases[i]->id);
2260       fprintf (f, "\n");
2261     }
2262   if (t->derived_types.length ())
2263     {
2264       fprintf (f, "%*s derived types:\n", indent * 2, "");
2265       for (i = 0; i < t->derived_types.length (); i++)
2266         dump_odr_type (f, t->derived_types[i], indent + 1);
2267     }
2268   fprintf (f, "\n");
2269 }
2270 
2271 /* Dump the type inheritance graph.  */
2272 
2273 static void
2274 dump_type_inheritance_graph (FILE *f)
2275 {
2276   unsigned int i;
2277   unsigned int num_all_types = 0, num_types = 0, num_duplicates = 0;
2278   if (!odr_types_ptr)
2279     return;
2280   fprintf (f, "\n\nType inheritance graph:\n");
2281   for (i = 0; i < odr_types.length (); i++)
2282     {
2283       if (odr_types[i] && odr_types[i]->bases.length () == 0)
2284 	dump_odr_type (f, odr_types[i]);
2285     }
2286   for (i = 0; i < odr_types.length (); i++)
2287     {
2288       if (!odr_types[i])
2289 	continue;
2290 
2291       num_all_types++;
2292       if (!odr_types[i]->types || !odr_types[i]->types->length ())
2293 	continue;
2294 
2295       /* To aid ODR warnings we also mangle integer constants but do
2296 	 not consinder duplicates there.  */
2297       if (TREE_CODE (odr_types[i]->type) == INTEGER_TYPE)
2298 	continue;
2299 
2300       /* It is normal to have one duplicate and one normal variant.  */
2301       if (odr_types[i]->types->length () == 1
2302 	  && COMPLETE_TYPE_P (odr_types[i]->type)
2303 	  && !COMPLETE_TYPE_P ((*odr_types[i]->types)[0]))
2304 	continue;
2305 
2306       num_types ++;
2307 
2308       unsigned int j;
2309       fprintf (f, "Duplicate tree types for odr type %i\n", i);
2310       print_node (f, "", odr_types[i]->type, 0);
2311       print_node (f, "", TYPE_NAME (odr_types[i]->type), 0);
2312       putc ('\n',f);
2313       for (j = 0; j < odr_types[i]->types->length (); j++)
2314 	{
2315 	  tree t;
2316 	  num_duplicates ++;
2317 	  fprintf (f, "duplicate #%i\n", j);
2318 	  print_node (f, "", (*odr_types[i]->types)[j], 0);
2319 	  t = (*odr_types[i]->types)[j];
2320 	  while (TYPE_P (t) && TYPE_CONTEXT (t))
2321 	    {
2322 	      t = TYPE_CONTEXT (t);
2323 	      print_node (f, "", t, 0);
2324 	    }
2325 	  print_node (f, "", TYPE_NAME ((*odr_types[i]->types)[j]), 0);
2326 	  putc ('\n',f);
2327 	}
2328     }
2329   fprintf (f, "Out of %i types there are %i types with duplicates; "
2330 	   "%i duplicates overall\n", num_all_types, num_types, num_duplicates);
2331 }
2332 
2333 /* Save some WPA->ltrans streaming by freeing stuff needed only for good
2334    ODR warnings.
2335    We free TYPE_VALUES of enums and also make TYPE_DECLs to not point back
2336    to the type (which is needed to keep them in the same SCC and preserve
2337    location information to output warnings) and subsequently we make all
2338    TYPE_DECLS of same assembler name equivalent.  */
2339 
2340 static void
2341 free_odr_warning_data ()
2342 {
2343   static bool odr_data_freed = false;
2344 
2345   if (odr_data_freed || !flag_wpa || !odr_types_ptr)
2346     return;
2347 
2348   odr_data_freed = true;
2349 
2350   for (unsigned int i = 0; i < odr_types.length (); i++)
2351     if (odr_types[i])
2352       {
2353 	tree t = odr_types[i]->type;
2354 
2355 	if (TREE_CODE (t) == ENUMERAL_TYPE)
2356 	  TYPE_VALUES (t) = NULL;
2357 	TREE_TYPE (TYPE_NAME (t)) = void_type_node;
2358 
2359 	if (odr_types[i]->types)
2360           for (unsigned int j = 0; j < odr_types[i]->types->length (); j++)
2361 	    {
2362 	      tree td = (*odr_types[i]->types)[j];
2363 
2364 	      if (TREE_CODE (td) == ENUMERAL_TYPE)
2365 	        TYPE_VALUES (td) = NULL;
2366 	      TYPE_NAME (td) = TYPE_NAME (t);
2367 	    }
2368       }
2369   odr_data_freed = true;
2370 }
2371 
2372 /* Initialize IPA devirt and build inheritance tree graph.  */
2373 
2374 void
2375 build_type_inheritance_graph (void)
2376 {
2377   struct symtab_node *n;
2378   FILE *inheritance_dump_file;
2379   dump_flags_t flags;
2380 
2381   if (odr_hash)
2382     {
2383       free_odr_warning_data ();
2384       return;
2385     }
2386   timevar_push (TV_IPA_INHERITANCE);
2387   inheritance_dump_file = dump_begin (TDI_inheritance, &flags);
2388   odr_hash = new odr_hash_type (23);
2389   if (in_lto_p)
2390     odr_vtable_hash = new odr_vtable_hash_type (23);
2391 
2392   /* We reconstruct the graph starting of types of all methods seen in the
2393      unit.  */
2394   FOR_EACH_SYMBOL (n)
2395     if (is_a <cgraph_node *> (n)
2396 	&& DECL_VIRTUAL_P (n->decl)
2397 	&& n->real_symbol_p ())
2398       get_odr_type (TYPE_METHOD_BASETYPE (TREE_TYPE (n->decl)), true);
2399 
2400     /* Look also for virtual tables of types that do not define any methods.
2401 
2402        We need it in a case where class B has virtual base of class A
2403        re-defining its virtual method and there is class C with no virtual
2404        methods with B as virtual base.
2405 
2406        Here we output B's virtual method in two variant - for non-virtual
2407        and virtual inheritance.  B's virtual table has non-virtual version,
2408        while C's has virtual.
2409 
2410        For this reason we need to know about C in order to include both
2411        variants of B.  More correctly, record_target_from_binfo should
2412        add both variants of the method when walking B, but we have no
2413        link in between them.
2414 
2415        We rely on fact that either the method is exported and thus we
2416        assume it is called externally or C is in anonymous namespace and
2417        thus we will see the vtable.  */
2418 
2419     else if (is_a <varpool_node *> (n)
2420 	     && DECL_VIRTUAL_P (n->decl)
2421 	     && TREE_CODE (DECL_CONTEXT (n->decl)) == RECORD_TYPE
2422 	     && TYPE_BINFO (DECL_CONTEXT (n->decl))
2423 	     && polymorphic_type_binfo_p (TYPE_BINFO (DECL_CONTEXT (n->decl))))
2424       get_odr_type (TYPE_MAIN_VARIANT (DECL_CONTEXT (n->decl)), true);
2425   if (inheritance_dump_file)
2426     {
2427       dump_type_inheritance_graph (inheritance_dump_file);
2428       dump_end (TDI_inheritance, inheritance_dump_file);
2429     }
2430   free_odr_warning_data ();
2431   timevar_pop (TV_IPA_INHERITANCE);
2432 }
2433 
2434 /* Return true if N has reference from live virtual table
2435    (and thus can be a destination of polymorphic call).
2436    Be conservatively correct when callgraph is not built or
2437    if the method may be referred externally.  */
2438 
2439 static bool
2440 referenced_from_vtable_p (struct cgraph_node *node)
2441 {
2442   int i;
2443   struct ipa_ref *ref;
2444   bool found = false;
2445 
2446   if (node->externally_visible
2447       || DECL_EXTERNAL (node->decl)
2448       || node->used_from_other_partition)
2449     return true;
2450 
2451   /* Keep this test constant time.
2452      It is unlikely this can happen except for the case where speculative
2453      devirtualization introduced many speculative edges to this node.
2454      In this case the target is very likely alive anyway.  */
2455   if (node->ref_list.referring.length () > 100)
2456     return true;
2457 
2458   /* We need references built.  */
2459   if (symtab->state <= CONSTRUCTION)
2460     return true;
2461 
2462   for (i = 0; node->iterate_referring (i, ref); i++)
2463     if ((ref->use == IPA_REF_ALIAS
2464 	 && referenced_from_vtable_p (dyn_cast<cgraph_node *> (ref->referring)))
2465 	|| (ref->use == IPA_REF_ADDR
2466 	    && VAR_P (ref->referring->decl)
2467 	    && DECL_VIRTUAL_P (ref->referring->decl)))
2468       {
2469 	found = true;
2470 	break;
2471       }
2472   return found;
2473 }
2474 
2475 /* Return if TARGET is cxa_pure_virtual.  */
2476 
2477 static bool
2478 is_cxa_pure_virtual_p (tree target)
2479 {
2480   return target && TREE_CODE (TREE_TYPE (target)) != METHOD_TYPE
2481 	 && DECL_NAME (target)
2482 	 && id_equal (DECL_NAME (target),
2483 		     "__cxa_pure_virtual");
2484 }
2485 
2486 /* If TARGET has associated node, record it in the NODES array.
2487    CAN_REFER specify if program can refer to the target directly.
2488    if TARGET is unknown (NULL) or it cannot be inserted (for example because
2489    its body was already removed and there is no way to refer to it), clear
2490    COMPLETEP.  */
2491 
2492 static void
2493 maybe_record_node (vec <cgraph_node *> &nodes,
2494 		   tree target, hash_set<tree> *inserted,
2495 		   bool can_refer,
2496 		   bool *completep)
2497 {
2498   struct cgraph_node *target_node, *alias_target;
2499   enum availability avail;
2500   bool pure_virtual = is_cxa_pure_virtual_p (target);
2501 
2502   /* __builtin_unreachable do not need to be added into
2503      list of targets; the runtime effect of calling them is undefined.
2504      Only "real" virtual methods should be accounted.  */
2505   if (target && TREE_CODE (TREE_TYPE (target)) != METHOD_TYPE && !pure_virtual)
2506     return;
2507 
2508   if (!can_refer)
2509     {
2510       /* The only case when method of anonymous namespace becomes unreferable
2511 	 is when we completely optimized it out.  */
2512       if (flag_ltrans
2513 	  || !target
2514 	  || !type_in_anonymous_namespace_p (DECL_CONTEXT (target)))
2515 	*completep = false;
2516       return;
2517     }
2518 
2519   if (!target)
2520     return;
2521 
2522   target_node = cgraph_node::get (target);
2523 
2524   /* Prefer alias target over aliases, so we do not get confused by
2525      fake duplicates.  */
2526   if (target_node)
2527     {
2528       alias_target = target_node->ultimate_alias_target (&avail);
2529       if (target_node != alias_target
2530 	  && avail >= AVAIL_AVAILABLE
2531 	  && target_node->get_availability ())
2532 	target_node = alias_target;
2533     }
2534 
2535   /* Method can only be called by polymorphic call if any
2536      of vtables referring to it are alive.
2537 
2538      While this holds for non-anonymous functions, too, there are
2539      cases where we want to keep them in the list; for example
2540      inline functions with -fno-weak are static, but we still
2541      may devirtualize them when instance comes from other unit.
2542      The same holds for LTO.
2543 
2544      Currently we ignore these functions in speculative devirtualization.
2545      ??? Maybe it would make sense to be more aggressive for LTO even
2546      elsewhere.  */
2547   if (!flag_ltrans
2548       && !pure_virtual
2549       && type_in_anonymous_namespace_p (DECL_CONTEXT (target))
2550       && (!target_node
2551           || !referenced_from_vtable_p (target_node)))
2552     ;
2553   /* See if TARGET is useful function we can deal with.  */
2554   else if (target_node != NULL
2555 	   && (TREE_PUBLIC (target)
2556 	       || DECL_EXTERNAL (target)
2557 	       || target_node->definition)
2558 	   && target_node->real_symbol_p ())
2559     {
2560       gcc_assert (!target_node->global.inlined_to);
2561       gcc_assert (target_node->real_symbol_p ());
2562       /* When sanitizing, do not assume that __cxa_pure_virtual is not called
2563 	 by valid program.  */
2564       if (flag_sanitize & SANITIZE_UNREACHABLE)
2565 	;
2566       /* Only add pure virtual if it is the only possible target.  This way
2567 	 we will preserve the diagnostics about pure virtual called in many
2568 	 cases without disabling optimization in other.  */
2569       else if (pure_virtual)
2570 	{
2571 	  if (nodes.length ())
2572 	    return;
2573 	}
2574       /* If we found a real target, take away cxa_pure_virtual.  */
2575       else if (!pure_virtual && nodes.length () == 1
2576 	       && is_cxa_pure_virtual_p (nodes[0]->decl))
2577 	nodes.pop ();
2578       if (pure_virtual && nodes.length ())
2579 	return;
2580       if (!inserted->add (target))
2581 	{
2582 	  cached_polymorphic_call_targets->add (target_node);
2583 	  nodes.safe_push (target_node);
2584 	}
2585     }
2586   else if (!completep)
2587     ;
2588   /* We have definition of __cxa_pure_virtual that is not accessible (it is
2589      optimized out or partitioned to other unit) so we cannot add it.  When
2590      not sanitizing, there is nothing to do.
2591      Otherwise declare the list incomplete.  */
2592   else if (pure_virtual)
2593     {
2594       if (flag_sanitize & SANITIZE_UNREACHABLE)
2595 	*completep = false;
2596     }
2597   else if (flag_ltrans
2598 	   || !type_in_anonymous_namespace_p (DECL_CONTEXT (target)))
2599     *completep = false;
2600 }
2601 
2602 /* See if BINFO's type matches OUTER_TYPE.  If so, look up
2603    BINFO of subtype of OTR_TYPE at OFFSET and in that BINFO find
2604    method in vtable and insert method to NODES array
2605    or BASES_TO_CONSIDER if this array is non-NULL.
2606    Otherwise recurse to base BINFOs.
2607    This matches what get_binfo_at_offset does, but with offset
2608    being unknown.
2609 
2610    TYPE_BINFOS is a stack of BINFOS of types with defined
2611    virtual table seen on way from class type to BINFO.
2612 
2613    MATCHED_VTABLES tracks virtual tables we already did lookup
2614    for virtual function in. INSERTED tracks nodes we already
2615    inserted.
2616 
2617    ANONYMOUS is true if BINFO is part of anonymous namespace.
2618 
2619    Clear COMPLETEP when we hit unreferable target.
2620   */
2621 
2622 static void
2623 record_target_from_binfo (vec <cgraph_node *> &nodes,
2624 			  vec <tree> *bases_to_consider,
2625 			  tree binfo,
2626 			  tree otr_type,
2627 			  vec <tree> &type_binfos,
2628 			  HOST_WIDE_INT otr_token,
2629 			  tree outer_type,
2630 			  HOST_WIDE_INT offset,
2631 			  hash_set<tree> *inserted,
2632 			  hash_set<tree> *matched_vtables,
2633 			  bool anonymous,
2634 			  bool *completep)
2635 {
2636   tree type = BINFO_TYPE (binfo);
2637   int i;
2638   tree base_binfo;
2639 
2640 
2641   if (BINFO_VTABLE (binfo))
2642     type_binfos.safe_push (binfo);
2643   if (types_same_for_odr (type, outer_type))
2644     {
2645       int i;
2646       tree type_binfo = NULL;
2647 
2648       /* Look up BINFO with virtual table.  For normal types it is always last
2649 	 binfo on stack.  */
2650       for (i = type_binfos.length () - 1; i >= 0; i--)
2651 	if (BINFO_OFFSET (type_binfos[i]) == BINFO_OFFSET (binfo))
2652 	  {
2653 	    type_binfo = type_binfos[i];
2654 	    break;
2655 	  }
2656       if (BINFO_VTABLE (binfo))
2657 	type_binfos.pop ();
2658       /* If this is duplicated BINFO for base shared by virtual inheritance,
2659 	 we may not have its associated vtable.  This is not a problem, since
2660 	 we will walk it on the other path.  */
2661       if (!type_binfo)
2662 	return;
2663       tree inner_binfo = get_binfo_at_offset (type_binfo,
2664 					      offset, otr_type);
2665       if (!inner_binfo)
2666 	{
2667 	  gcc_assert (odr_violation_reported);
2668 	  return;
2669 	}
2670       /* For types in anonymous namespace first check if the respective vtable
2671 	 is alive. If not, we know the type can't be called.  */
2672       if (!flag_ltrans && anonymous)
2673 	{
2674 	  tree vtable = BINFO_VTABLE (inner_binfo);
2675 	  varpool_node *vnode;
2676 
2677 	  if (TREE_CODE (vtable) == POINTER_PLUS_EXPR)
2678 	    vtable = TREE_OPERAND (TREE_OPERAND (vtable, 0), 0);
2679 	  vnode = varpool_node::get (vtable);
2680 	  if (!vnode || !vnode->definition)
2681 	    return;
2682 	}
2683       gcc_assert (inner_binfo);
2684       if (bases_to_consider
2685 	  ? !matched_vtables->contains (BINFO_VTABLE (inner_binfo))
2686 	  : !matched_vtables->add (BINFO_VTABLE (inner_binfo)))
2687 	{
2688 	  bool can_refer;
2689 	  tree target = gimple_get_virt_method_for_binfo (otr_token,
2690 							  inner_binfo,
2691 							  &can_refer);
2692 	  if (!bases_to_consider)
2693 	    maybe_record_node (nodes, target, inserted, can_refer, completep);
2694 	  /* Destructors are never called via construction vtables.  */
2695 	  else if (!target || !DECL_CXX_DESTRUCTOR_P (target))
2696 	    bases_to_consider->safe_push (target);
2697 	}
2698       return;
2699     }
2700 
2701   /* Walk bases.  */
2702   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
2703     /* Walking bases that have no virtual method is pointless exercise.  */
2704     if (polymorphic_type_binfo_p (base_binfo))
2705       record_target_from_binfo (nodes, bases_to_consider, base_binfo, otr_type,
2706 				type_binfos,
2707 				otr_token, outer_type, offset, inserted,
2708 				matched_vtables, anonymous, completep);
2709   if (BINFO_VTABLE (binfo))
2710     type_binfos.pop ();
2711 }
2712 
2713 /* Look up virtual methods matching OTR_TYPE (with OFFSET and OTR_TOKEN)
2714    of TYPE, insert them to NODES, recurse into derived nodes.
2715    INSERTED is used to avoid duplicate insertions of methods into NODES.
2716    MATCHED_VTABLES are used to avoid duplicate walking vtables.
2717    Clear COMPLETEP if unreferable target is found.
2718 
2719    If CONSIDER_CONSTRUCTION is true, record to BASES_TO_CONSIDER
2720    all cases where BASE_SKIPPED is true (because the base is abstract
2721    class).  */
2722 
2723 static void
2724 possible_polymorphic_call_targets_1 (vec <cgraph_node *> &nodes,
2725 				     hash_set<tree> *inserted,
2726 				     hash_set<tree> *matched_vtables,
2727 				     tree otr_type,
2728 				     odr_type type,
2729 				     HOST_WIDE_INT otr_token,
2730 				     tree outer_type,
2731 				     HOST_WIDE_INT offset,
2732 				     bool *completep,
2733 				     vec <tree> &bases_to_consider,
2734 				     bool consider_construction)
2735 {
2736   tree binfo = TYPE_BINFO (type->type);
2737   unsigned int i;
2738   auto_vec <tree, 8> type_binfos;
2739   bool possibly_instantiated = type_possibly_instantiated_p (type->type);
2740 
2741   /* We may need to consider types w/o instances because of possible derived
2742      types using their methods either directly or via construction vtables.
2743      We are safe to skip them when all derivations are known, since we will
2744      handle them later.
2745      This is done by recording them to BASES_TO_CONSIDER array.  */
2746   if (possibly_instantiated || consider_construction)
2747     {
2748       record_target_from_binfo (nodes,
2749 				(!possibly_instantiated
2750 				 && type_all_derivations_known_p (type->type))
2751 				? &bases_to_consider : NULL,
2752 				binfo, otr_type, type_binfos, otr_token,
2753 				outer_type, offset,
2754 				inserted, matched_vtables,
2755 				type->anonymous_namespace, completep);
2756     }
2757   for (i = 0; i < type->derived_types.length (); i++)
2758     possible_polymorphic_call_targets_1 (nodes, inserted,
2759 					 matched_vtables,
2760 					 otr_type,
2761 					 type->derived_types[i],
2762 					 otr_token, outer_type, offset, completep,
2763 					 bases_to_consider, consider_construction);
2764 }
2765 
2766 /* Cache of queries for polymorphic call targets.
2767 
2768    Enumerating all call targets may get expensive when there are many
2769    polymorphic calls in the program, so we memoize all the previous
2770    queries and avoid duplicated work.  */
2771 
2772 struct polymorphic_call_target_d
2773 {
2774   HOST_WIDE_INT otr_token;
2775   ipa_polymorphic_call_context context;
2776   odr_type type;
2777   vec <cgraph_node *> targets;
2778   tree decl_warning;
2779   int type_warning;
2780   unsigned int n_odr_types;
2781   bool complete;
2782   bool speculative;
2783 };
2784 
2785 /* Polymorphic call target cache helpers.  */
2786 
2787 struct polymorphic_call_target_hasher
2788   : pointer_hash <polymorphic_call_target_d>
2789 {
2790   static inline hashval_t hash (const polymorphic_call_target_d *);
2791   static inline bool equal (const polymorphic_call_target_d *,
2792 			    const polymorphic_call_target_d *);
2793   static inline void remove (polymorphic_call_target_d *);
2794 };
2795 
2796 /* Return the computed hashcode for ODR_QUERY.  */
2797 
2798 inline hashval_t
2799 polymorphic_call_target_hasher::hash (const polymorphic_call_target_d *odr_query)
2800 {
2801   inchash::hash hstate (odr_query->otr_token);
2802 
2803   hstate.add_hwi (odr_query->type->id);
2804   hstate.merge_hash (TYPE_UID (odr_query->context.outer_type));
2805   hstate.add_hwi (odr_query->context.offset);
2806   hstate.add_hwi (odr_query->n_odr_types);
2807 
2808   if (odr_query->context.speculative_outer_type)
2809     {
2810       hstate.merge_hash (TYPE_UID (odr_query->context.speculative_outer_type));
2811       hstate.add_hwi (odr_query->context.speculative_offset);
2812     }
2813   hstate.add_flag (odr_query->speculative);
2814   hstate.add_flag (odr_query->context.maybe_in_construction);
2815   hstate.add_flag (odr_query->context.maybe_derived_type);
2816   hstate.add_flag (odr_query->context.speculative_maybe_derived_type);
2817   hstate.commit_flag ();
2818   return hstate.end ();
2819 }
2820 
2821 /* Compare cache entries T1 and T2.  */
2822 
2823 inline bool
2824 polymorphic_call_target_hasher::equal (const polymorphic_call_target_d *t1,
2825 				       const polymorphic_call_target_d *t2)
2826 {
2827   return (t1->type == t2->type && t1->otr_token == t2->otr_token
2828 	  && t1->speculative == t2->speculative
2829 	  && t1->context.offset == t2->context.offset
2830 	  && t1->context.speculative_offset == t2->context.speculative_offset
2831 	  && t1->context.outer_type == t2->context.outer_type
2832 	  && t1->context.speculative_outer_type == t2->context.speculative_outer_type
2833 	  && t1->context.maybe_in_construction
2834 	      == t2->context.maybe_in_construction
2835 	  && t1->context.maybe_derived_type == t2->context.maybe_derived_type
2836 	  && (t1->context.speculative_maybe_derived_type
2837 	      == t2->context.speculative_maybe_derived_type)
2838 	  /* Adding new type may affect outcome of target search.  */
2839 	  && t1->n_odr_types == t2->n_odr_types);
2840 }
2841 
2842 /* Remove entry in polymorphic call target cache hash.  */
2843 
2844 inline void
2845 polymorphic_call_target_hasher::remove (polymorphic_call_target_d *v)
2846 {
2847   v->targets.release ();
2848   free (v);
2849 }
2850 
2851 /* Polymorphic call target query cache.  */
2852 
2853 typedef hash_table<polymorphic_call_target_hasher>
2854    polymorphic_call_target_hash_type;
2855 static polymorphic_call_target_hash_type *polymorphic_call_target_hash;
2856 
2857 /* Destroy polymorphic call target query cache.  */
2858 
2859 static void
2860 free_polymorphic_call_targets_hash ()
2861 {
2862   if (cached_polymorphic_call_targets)
2863     {
2864       delete polymorphic_call_target_hash;
2865       polymorphic_call_target_hash = NULL;
2866       delete cached_polymorphic_call_targets;
2867       cached_polymorphic_call_targets = NULL;
2868     }
2869 }
2870 
2871 /* Force rebuilding type inheritance graph from scratch.
2872    This is use to make sure that we do not keep references to types
2873    which was not visible to free_lang_data.  */
2874 
2875 void
2876 rebuild_type_inheritance_graph ()
2877 {
2878   if (!odr_hash)
2879     return;
2880   delete odr_hash;
2881   if (in_lto_p)
2882     delete odr_vtable_hash;
2883   odr_hash = NULL;
2884   odr_vtable_hash = NULL;
2885   odr_types_ptr = NULL;
2886   free_polymorphic_call_targets_hash ();
2887 }
2888 
2889 /* When virtual function is removed, we may need to flush the cache.  */
2890 
2891 static void
2892 devirt_node_removal_hook (struct cgraph_node *n, void *d ATTRIBUTE_UNUSED)
2893 {
2894   if (cached_polymorphic_call_targets
2895       && cached_polymorphic_call_targets->contains (n))
2896     free_polymorphic_call_targets_hash ();
2897 }
2898 
2899 /* Look up base of BINFO that has virtual table VTABLE with OFFSET.  */
2900 
2901 tree
2902 subbinfo_with_vtable_at_offset (tree binfo, unsigned HOST_WIDE_INT offset,
2903 				tree vtable)
2904 {
2905   tree v = BINFO_VTABLE (binfo);
2906   int i;
2907   tree base_binfo;
2908   unsigned HOST_WIDE_INT this_offset;
2909 
2910   if (v)
2911     {
2912       if (!vtable_pointer_value_to_vtable (v, &v, &this_offset))
2913 	gcc_unreachable ();
2914 
2915       if (offset == this_offset
2916 	  && DECL_ASSEMBLER_NAME (v) == DECL_ASSEMBLER_NAME (vtable))
2917 	return binfo;
2918     }
2919 
2920   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
2921     if (polymorphic_type_binfo_p (base_binfo))
2922       {
2923 	base_binfo = subbinfo_with_vtable_at_offset (base_binfo, offset, vtable);
2924 	if (base_binfo)
2925 	  return base_binfo;
2926       }
2927   return NULL;
2928 }
2929 
2930 /* T is known constant value of virtual table pointer.
2931    Store virtual table to V and its offset to OFFSET.
2932    Return false if T does not look like virtual table reference.  */
2933 
2934 bool
2935 vtable_pointer_value_to_vtable (const_tree t, tree *v,
2936 				unsigned HOST_WIDE_INT *offset)
2937 {
2938   /* We expect &MEM[(void *)&virtual_table + 16B].
2939      We obtain object's BINFO from the context of the virtual table.
2940      This one contains pointer to virtual table represented via
2941      POINTER_PLUS_EXPR.  Verify that this pointer matches what
2942      we propagated through.
2943 
2944      In the case of virtual inheritance, the virtual tables may
2945      be nested, i.e. the offset may be different from 16 and we may
2946      need to dive into the type representation.  */
2947   if (TREE_CODE (t) == ADDR_EXPR
2948       && TREE_CODE (TREE_OPERAND (t, 0)) == MEM_REF
2949       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (t, 0), 0)) == ADDR_EXPR
2950       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (t, 0), 1)) == INTEGER_CST
2951       && (TREE_CODE (TREE_OPERAND (TREE_OPERAND (TREE_OPERAND (t, 0), 0), 0))
2952 	  == VAR_DECL)
2953       && DECL_VIRTUAL_P (TREE_OPERAND (TREE_OPERAND
2954 					 (TREE_OPERAND (t, 0), 0), 0)))
2955     {
2956       *v = TREE_OPERAND (TREE_OPERAND (TREE_OPERAND (t, 0), 0), 0);
2957       *offset = tree_to_uhwi (TREE_OPERAND (TREE_OPERAND (t, 0), 1));
2958       return true;
2959     }
2960 
2961   /* Alternative representation, used by C++ frontend is POINTER_PLUS_EXPR.
2962      We need to handle it when T comes from static variable initializer or
2963      BINFO. */
2964   if (TREE_CODE (t) == POINTER_PLUS_EXPR)
2965     {
2966       *offset = tree_to_uhwi (TREE_OPERAND (t, 1));
2967       t = TREE_OPERAND (t, 0);
2968     }
2969   else
2970     *offset = 0;
2971 
2972   if (TREE_CODE (t) != ADDR_EXPR)
2973     return false;
2974   *v = TREE_OPERAND (t, 0);
2975   return true;
2976 }
2977 
2978 /* T is known constant value of virtual table pointer.  Return BINFO of the
2979    instance type.  */
2980 
2981 tree
2982 vtable_pointer_value_to_binfo (const_tree t)
2983 {
2984   tree vtable;
2985   unsigned HOST_WIDE_INT offset;
2986 
2987   if (!vtable_pointer_value_to_vtable (t, &vtable, &offset))
2988     return NULL_TREE;
2989 
2990   /* FIXME: for stores of construction vtables we return NULL,
2991      because we do not have BINFO for those. Eventually we should fix
2992      our representation to allow this case to be handled, too.
2993      In the case we see store of BINFO we however may assume
2994      that standard folding will be able to cope with it.  */
2995   return subbinfo_with_vtable_at_offset (TYPE_BINFO (DECL_CONTEXT (vtable)),
2996 					 offset, vtable);
2997 }
2998 
2999 /* Walk bases of OUTER_TYPE that contain OTR_TYPE at OFFSET.
3000    Look up their respective virtual methods for OTR_TOKEN and OTR_TYPE
3001    and insert them in NODES.
3002 
3003    MATCHED_VTABLES and INSERTED is used to avoid duplicated work.  */
3004 
3005 static void
3006 record_targets_from_bases (tree otr_type,
3007 			   HOST_WIDE_INT otr_token,
3008 			   tree outer_type,
3009 			   HOST_WIDE_INT offset,
3010 			   vec <cgraph_node *> &nodes,
3011 			   hash_set<tree> *inserted,
3012 			   hash_set<tree> *matched_vtables,
3013 			   bool *completep)
3014 {
3015   while (true)
3016     {
3017       HOST_WIDE_INT pos, size;
3018       tree base_binfo;
3019       tree fld;
3020 
3021       if (types_same_for_odr (outer_type, otr_type))
3022 	return;
3023 
3024       for (fld = TYPE_FIELDS (outer_type); fld; fld = DECL_CHAIN (fld))
3025 	{
3026 	  if (TREE_CODE (fld) != FIELD_DECL)
3027 	    continue;
3028 
3029 	  pos = int_bit_position (fld);
3030 	  size = tree_to_shwi (DECL_SIZE (fld));
3031 	  if (pos <= offset && (pos + size) > offset
3032 	      /* Do not get confused by zero sized bases.  */
3033 	      && polymorphic_type_binfo_p (TYPE_BINFO (TREE_TYPE (fld))))
3034 	    break;
3035 	}
3036       /* Within a class type we should always find corresponding fields.  */
3037       gcc_assert (fld && TREE_CODE (TREE_TYPE (fld)) == RECORD_TYPE);
3038 
3039       /* Nonbase types should have been stripped by outer_class_type.  */
3040       gcc_assert (DECL_ARTIFICIAL (fld));
3041 
3042       outer_type = TREE_TYPE (fld);
3043       offset -= pos;
3044 
3045       base_binfo = get_binfo_at_offset (TYPE_BINFO (outer_type),
3046 					offset, otr_type);
3047       if (!base_binfo)
3048 	{
3049 	  gcc_assert (odr_violation_reported);
3050 	  return;
3051 	}
3052       gcc_assert (base_binfo);
3053       if (!matched_vtables->add (BINFO_VTABLE (base_binfo)))
3054 	{
3055 	  bool can_refer;
3056 	  tree target = gimple_get_virt_method_for_binfo (otr_token,
3057 							  base_binfo,
3058 							  &can_refer);
3059 	  if (!target || ! DECL_CXX_DESTRUCTOR_P (target))
3060 	    maybe_record_node (nodes, target, inserted, can_refer, completep);
3061 	  matched_vtables->add (BINFO_VTABLE (base_binfo));
3062 	}
3063     }
3064 }
3065 
3066 /* When virtual table is removed, we may need to flush the cache.  */
3067 
3068 static void
3069 devirt_variable_node_removal_hook (varpool_node *n,
3070 				   void *d ATTRIBUTE_UNUSED)
3071 {
3072   if (cached_polymorphic_call_targets
3073       && DECL_VIRTUAL_P (n->decl)
3074       && type_in_anonymous_namespace_p (DECL_CONTEXT (n->decl)))
3075     free_polymorphic_call_targets_hash ();
3076 }
3077 
3078 /* Record about how many calls would benefit from given type to be final.  */
3079 
3080 struct odr_type_warn_count
3081 {
3082   tree type;
3083   int count;
3084   profile_count dyn_count;
3085 };
3086 
3087 /* Record about how many calls would benefit from given method to be final.  */
3088 
3089 struct decl_warn_count
3090 {
3091   tree decl;
3092   int count;
3093   profile_count dyn_count;
3094 };
3095 
3096 /* Information about type and decl warnings.  */
3097 
3098 struct final_warning_record
3099 {
3100   /* If needed grow type_warnings vector and initialize new decl_warn_count
3101      to have dyn_count set to profile_count::zero ().  */
3102   void grow_type_warnings (unsigned newlen);
3103 
3104   profile_count dyn_count;
3105   auto_vec<odr_type_warn_count> type_warnings;
3106   hash_map<tree, decl_warn_count> decl_warnings;
3107 };
3108 
3109 void
3110 final_warning_record::grow_type_warnings (unsigned newlen)
3111 {
3112   unsigned len = type_warnings.length ();
3113   if (newlen > len)
3114     {
3115       type_warnings.safe_grow_cleared (newlen);
3116       for (unsigned i = len; i < newlen; i++)
3117 	type_warnings[i].dyn_count = profile_count::zero ();
3118     }
3119 }
3120 
3121 struct final_warning_record *final_warning_records;
3122 
3123 /* Return vector containing possible targets of polymorphic call of type
3124    OTR_TYPE calling method OTR_TOKEN within type of OTR_OUTER_TYPE and OFFSET.
3125    If INCLUDE_BASES is true, walk also base types of OUTER_TYPES containing
3126    OTR_TYPE and include their virtual method.  This is useful for types
3127    possibly in construction or destruction where the virtual table may
3128    temporarily change to one of base types.  INCLUDE_DERIVER_TYPES make
3129    us to walk the inheritance graph for all derivations.
3130 
3131    If COMPLETEP is non-NULL, store true if the list is complete.
3132    CACHE_TOKEN (if non-NULL) will get stored to an unique ID of entry
3133    in the target cache.  If user needs to visit every target list
3134    just once, it can memoize them.
3135 
3136    If SPECULATIVE is set, the list will not contain targets that
3137    are not speculatively taken.
3138 
3139    Returned vector is placed into cache.  It is NOT caller's responsibility
3140    to free it.  The vector can be freed on cgraph_remove_node call if
3141    the particular node is a virtual function present in the cache.  */
3142 
3143 vec <cgraph_node *>
3144 possible_polymorphic_call_targets (tree otr_type,
3145 			           HOST_WIDE_INT otr_token,
3146 				   ipa_polymorphic_call_context context,
3147 			           bool *completep,
3148 			           void **cache_token,
3149 				   bool speculative)
3150 {
3151   static struct cgraph_node_hook_list *node_removal_hook_holder;
3152   vec <cgraph_node *> nodes = vNULL;
3153   auto_vec <tree, 8> bases_to_consider;
3154   odr_type type, outer_type;
3155   polymorphic_call_target_d key;
3156   polymorphic_call_target_d **slot;
3157   unsigned int i;
3158   tree binfo, target;
3159   bool complete;
3160   bool can_refer = false;
3161   bool skipped = false;
3162 
3163   otr_type = TYPE_MAIN_VARIANT (otr_type);
3164 
3165   /* If ODR is not initialized or the context is invalid, return empty
3166      incomplete list.  */
3167   if (!odr_hash || context.invalid || !TYPE_BINFO (otr_type))
3168     {
3169       if (completep)
3170 	*completep = context.invalid;
3171       if (cache_token)
3172 	*cache_token = NULL;
3173       return nodes;
3174     }
3175 
3176   /* Do not bother to compute speculative info when user do not asks for it.  */
3177   if (!speculative || !context.speculative_outer_type)
3178     context.clear_speculation ();
3179 
3180   type = get_odr_type (otr_type, true);
3181 
3182   /* Recording type variants would waste results cache.  */
3183   gcc_assert (!context.outer_type
3184 	      || TYPE_MAIN_VARIANT (context.outer_type) == context.outer_type);
3185 
3186   /* Look up the outer class type we want to walk.
3187      If we fail to do so, the context is invalid.  */
3188   if ((context.outer_type || context.speculative_outer_type)
3189       && !context.restrict_to_inner_class (otr_type))
3190     {
3191       if (completep)
3192 	*completep = true;
3193       if (cache_token)
3194 	*cache_token = NULL;
3195       return nodes;
3196     }
3197   gcc_assert (!context.invalid);
3198 
3199   /* Check that restrict_to_inner_class kept the main variant.  */
3200   gcc_assert (!context.outer_type
3201 	      || TYPE_MAIN_VARIANT (context.outer_type) == context.outer_type);
3202 
3203   /* We canonicalize our query, so we do not need extra hashtable entries.  */
3204 
3205   /* Without outer type, we have no use for offset.  Just do the
3206      basic search from inner type.  */
3207   if (!context.outer_type)
3208     context.clear_outer_type (otr_type);
3209   /* We need to update our hierarchy if the type does not exist.  */
3210   outer_type = get_odr_type (context.outer_type, true);
3211   /* If the type is complete, there are no derivations.  */
3212   if (TYPE_FINAL_P (outer_type->type))
3213     context.maybe_derived_type = false;
3214 
3215   /* Initialize query cache.  */
3216   if (!cached_polymorphic_call_targets)
3217     {
3218       cached_polymorphic_call_targets = new hash_set<cgraph_node *>;
3219       polymorphic_call_target_hash
3220        	= new polymorphic_call_target_hash_type (23);
3221       if (!node_removal_hook_holder)
3222 	{
3223 	  node_removal_hook_holder =
3224 	    symtab->add_cgraph_removal_hook (&devirt_node_removal_hook, NULL);
3225 	  symtab->add_varpool_removal_hook (&devirt_variable_node_removal_hook,
3226 					 NULL);
3227 	}
3228     }
3229 
3230   if (in_lto_p)
3231     {
3232       if (context.outer_type != otr_type)
3233         context.outer_type
3234 	  = get_odr_type (context.outer_type, true)->type;
3235       if (context.speculative_outer_type)
3236         context.speculative_outer_type
3237 	  = get_odr_type (context.speculative_outer_type, true)->type;
3238     }
3239 
3240   /* Look up cached answer.  */
3241   key.type = type;
3242   key.otr_token = otr_token;
3243   key.speculative = speculative;
3244   key.context = context;
3245   key.n_odr_types = odr_types.length ();
3246   slot = polymorphic_call_target_hash->find_slot (&key, INSERT);
3247   if (cache_token)
3248    *cache_token = (void *)*slot;
3249   if (*slot)
3250     {
3251       if (completep)
3252 	*completep = (*slot)->complete;
3253       if ((*slot)->type_warning && final_warning_records)
3254 	{
3255 	  final_warning_records->type_warnings[(*slot)->type_warning - 1].count++;
3256 	  if (!final_warning_records->type_warnings
3257 		[(*slot)->type_warning - 1].dyn_count.initialized_p ())
3258 	    final_warning_records->type_warnings
3259 		[(*slot)->type_warning - 1].dyn_count = profile_count::zero ();
3260 	  if (final_warning_records->dyn_count > 0)
3261 	    final_warning_records->type_warnings[(*slot)->type_warning - 1].dyn_count
3262 	      = final_warning_records->type_warnings[(*slot)->type_warning - 1].dyn_count
3263 	        + final_warning_records->dyn_count;
3264 	}
3265       if (!speculative && (*slot)->decl_warning && final_warning_records)
3266 	{
3267 	  struct decl_warn_count *c =
3268 	     final_warning_records->decl_warnings.get ((*slot)->decl_warning);
3269 	  c->count++;
3270 	  if (final_warning_records->dyn_count > 0)
3271 	    c->dyn_count += final_warning_records->dyn_count;
3272 	}
3273       return (*slot)->targets;
3274     }
3275 
3276   complete = true;
3277 
3278   /* Do actual search.  */
3279   timevar_push (TV_IPA_VIRTUAL_CALL);
3280   *slot = XCNEW (polymorphic_call_target_d);
3281   if (cache_token)
3282     *cache_token = (void *)*slot;
3283   (*slot)->type = type;
3284   (*slot)->otr_token = otr_token;
3285   (*slot)->context = context;
3286   (*slot)->speculative = speculative;
3287 
3288   hash_set<tree> inserted;
3289   hash_set<tree> matched_vtables;
3290 
3291   /* First insert targets we speculatively identified as likely.  */
3292   if (context.speculative_outer_type)
3293     {
3294       odr_type speculative_outer_type;
3295       bool speculation_complete = true;
3296 
3297       /* First insert target from type itself and check if it may have
3298 	 derived types.  */
3299       speculative_outer_type = get_odr_type (context.speculative_outer_type, true);
3300       if (TYPE_FINAL_P (speculative_outer_type->type))
3301 	context.speculative_maybe_derived_type = false;
3302       binfo = get_binfo_at_offset (TYPE_BINFO (speculative_outer_type->type),
3303 				   context.speculative_offset, otr_type);
3304       if (binfo)
3305 	target = gimple_get_virt_method_for_binfo (otr_token, binfo,
3306 						   &can_refer);
3307       else
3308 	target = NULL;
3309 
3310       /* In the case we get complete method, we don't need
3311 	 to walk derivations.  */
3312       if (target && DECL_FINAL_P (target))
3313 	context.speculative_maybe_derived_type = false;
3314       if (type_possibly_instantiated_p (speculative_outer_type->type))
3315 	maybe_record_node (nodes, target, &inserted, can_refer, &speculation_complete);
3316       if (binfo)
3317 	matched_vtables.add (BINFO_VTABLE (binfo));
3318 
3319 
3320       /* Next walk recursively all derived types.  */
3321       if (context.speculative_maybe_derived_type)
3322 	for (i = 0; i < speculative_outer_type->derived_types.length(); i++)
3323 	  possible_polymorphic_call_targets_1 (nodes, &inserted,
3324 					       &matched_vtables,
3325 					       otr_type,
3326 					       speculative_outer_type->derived_types[i],
3327 					       otr_token, speculative_outer_type->type,
3328 					       context.speculative_offset,
3329 					       &speculation_complete,
3330 					       bases_to_consider,
3331 					       false);
3332     }
3333 
3334   if (!speculative || !nodes.length ())
3335     {
3336       /* First see virtual method of type itself.  */
3337       binfo = get_binfo_at_offset (TYPE_BINFO (outer_type->type),
3338 				   context.offset, otr_type);
3339       if (binfo)
3340 	target = gimple_get_virt_method_for_binfo (otr_token, binfo,
3341 						   &can_refer);
3342       else
3343 	{
3344 	  gcc_assert (odr_violation_reported);
3345 	  target = NULL;
3346 	}
3347 
3348       /* Destructors are never called through construction virtual tables,
3349 	 because the type is always known.  */
3350       if (target && DECL_CXX_DESTRUCTOR_P (target))
3351 	context.maybe_in_construction = false;
3352 
3353       if (target)
3354 	{
3355 	  /* In the case we get complete method, we don't need
3356 	     to walk derivations.  */
3357 	  if (DECL_FINAL_P (target))
3358 	    context.maybe_derived_type = false;
3359 	}
3360 
3361       /* If OUTER_TYPE is abstract, we know we are not seeing its instance.  */
3362       if (type_possibly_instantiated_p (outer_type->type))
3363 	maybe_record_node (nodes, target, &inserted, can_refer, &complete);
3364       else
3365 	skipped = true;
3366 
3367       if (binfo)
3368 	matched_vtables.add (BINFO_VTABLE (binfo));
3369 
3370       /* Next walk recursively all derived types.  */
3371       if (context.maybe_derived_type)
3372 	{
3373 	  for (i = 0; i < outer_type->derived_types.length(); i++)
3374 	    possible_polymorphic_call_targets_1 (nodes, &inserted,
3375 						 &matched_vtables,
3376 						 otr_type,
3377 						 outer_type->derived_types[i],
3378 						 otr_token, outer_type->type,
3379 						 context.offset, &complete,
3380 						 bases_to_consider,
3381 						 context.maybe_in_construction);
3382 
3383 	  if (!outer_type->all_derivations_known)
3384 	    {
3385 	      if (!speculative && final_warning_records
3386 		  && nodes.length () == 1
3387 		  && TREE_CODE (TREE_TYPE (nodes[0]->decl)) == METHOD_TYPE)
3388 		{
3389 		  if (complete
3390 		      && warn_suggest_final_types
3391 		      && !outer_type->derived_types.length ())
3392 		    {
3393 		      final_warning_records->grow_type_warnings
3394 			(outer_type->id);
3395 		      final_warning_records->type_warnings[outer_type->id].count++;
3396 		      if (!final_warning_records->type_warnings
3397 				[outer_type->id].dyn_count.initialized_p ())
3398 			final_warning_records->type_warnings
3399 			   [outer_type->id].dyn_count = profile_count::zero ();
3400 		      final_warning_records->type_warnings[outer_type->id].dyn_count
3401 			+= final_warning_records->dyn_count;
3402 		      final_warning_records->type_warnings[outer_type->id].type
3403 			= outer_type->type;
3404 		      (*slot)->type_warning = outer_type->id + 1;
3405 		    }
3406 		  if (complete
3407 		      && warn_suggest_final_methods
3408 		      && types_same_for_odr (DECL_CONTEXT (nodes[0]->decl),
3409 					     outer_type->type))
3410 		    {
3411 		      bool existed;
3412 		      struct decl_warn_count &c =
3413 			 final_warning_records->decl_warnings.get_or_insert
3414 			    (nodes[0]->decl, &existed);
3415 
3416 		      if (existed)
3417 			{
3418 			  c.count++;
3419 			  c.dyn_count += final_warning_records->dyn_count;
3420 			}
3421 		      else
3422 			{
3423 			  c.count = 1;
3424 			  c.dyn_count = final_warning_records->dyn_count;
3425 			  c.decl = nodes[0]->decl;
3426 			}
3427 		      (*slot)->decl_warning = nodes[0]->decl;
3428 		    }
3429 		}
3430 	      complete = false;
3431 	    }
3432 	}
3433 
3434       if (!speculative)
3435 	{
3436 	  /* Destructors are never called through construction virtual tables,
3437 	     because the type is always known.  One of entries may be
3438 	     cxa_pure_virtual so look to at least two of them.  */
3439 	  if (context.maybe_in_construction)
3440 	    for (i =0 ; i < MIN (nodes.length (), 2); i++)
3441 	      if (DECL_CXX_DESTRUCTOR_P (nodes[i]->decl))
3442 		context.maybe_in_construction = false;
3443 	  if (context.maybe_in_construction)
3444 	    {
3445 	      if (type != outer_type
3446 		  && (!skipped
3447 		      || (context.maybe_derived_type
3448 			  && !type_all_derivations_known_p (outer_type->type))))
3449 		record_targets_from_bases (otr_type, otr_token, outer_type->type,
3450 					   context.offset, nodes, &inserted,
3451 					   &matched_vtables, &complete);
3452 	      if (skipped)
3453 		maybe_record_node (nodes, target, &inserted, can_refer, &complete);
3454 	      for (i = 0; i < bases_to_consider.length(); i++)
3455 		maybe_record_node (nodes, bases_to_consider[i], &inserted, can_refer, &complete);
3456 	    }
3457 	}
3458     }
3459 
3460   (*slot)->targets = nodes;
3461   (*slot)->complete = complete;
3462   (*slot)->n_odr_types = odr_types.length ();
3463   if (completep)
3464     *completep = complete;
3465 
3466   timevar_pop (TV_IPA_VIRTUAL_CALL);
3467   return nodes;
3468 }
3469 
3470 bool
3471 add_decl_warning (const tree &key ATTRIBUTE_UNUSED, const decl_warn_count &value,
3472 		  vec<const decl_warn_count*> *vec)
3473 {
3474   vec->safe_push (&value);
3475   return true;
3476 }
3477 
3478 /* Dump target list TARGETS into FILE.  */
3479 
3480 static void
3481 dump_targets (FILE *f, vec <cgraph_node *> targets, bool verbose)
3482 {
3483   unsigned int i;
3484 
3485   for (i = 0; i < targets.length (); i++)
3486     {
3487       char *name = NULL;
3488       if (in_lto_p)
3489 	name = cplus_demangle_v3 (targets[i]->asm_name (), 0);
3490       fprintf (f, " %s/%i", name ? name : targets[i]->name (),
3491 	       targets[i]->order);
3492       if (in_lto_p)
3493 	free (name);
3494       if (!targets[i]->definition)
3495 	fprintf (f, " (no definition%s)",
3496 		 DECL_DECLARED_INLINE_P (targets[i]->decl)
3497 		 ? " inline" : "");
3498       /* With many targets for every call polymorphic dumps are going to
3499 	 be quadratic in size.  */
3500       if (i > 10 && !verbose)
3501 	{
3502 	  fprintf (f, " ... and %i more targets\n", targets.length () - i);
3503 	  return;
3504 	}
3505     }
3506   fprintf (f, "\n");
3507 }
3508 
3509 /* Dump all possible targets of a polymorphic call.  */
3510 
3511 void
3512 dump_possible_polymorphic_call_targets (FILE *f,
3513 					tree otr_type,
3514 					HOST_WIDE_INT otr_token,
3515 					const ipa_polymorphic_call_context &ctx,
3516 					bool verbose)
3517 {
3518   vec <cgraph_node *> targets;
3519   bool final;
3520   odr_type type = get_odr_type (TYPE_MAIN_VARIANT (otr_type), false);
3521   unsigned int len;
3522 
3523   if (!type)
3524     return;
3525   targets = possible_polymorphic_call_targets (otr_type, otr_token,
3526 					       ctx,
3527 					       &final, NULL, false);
3528   fprintf (f, "  Targets of polymorphic call of type %i:", type->id);
3529   print_generic_expr (f, type->type, TDF_SLIM);
3530   fprintf (f, " token %i\n", (int)otr_token);
3531 
3532   ctx.dump (f);
3533 
3534   fprintf (f, "    %s%s%s%s\n      ",
3535 	   final ? "This is a complete list." :
3536 	   "This is partial list; extra targets may be defined in other units.",
3537 	   ctx.maybe_in_construction ? " (base types included)" : "",
3538 	   ctx.maybe_derived_type ? " (derived types included)" : "",
3539 	   ctx.speculative_maybe_derived_type ? " (speculative derived types included)" : "");
3540   len = targets.length ();
3541   dump_targets (f, targets, verbose);
3542 
3543   targets = possible_polymorphic_call_targets (otr_type, otr_token,
3544 					       ctx,
3545 					       &final, NULL, true);
3546   if (targets.length () != len)
3547     {
3548       fprintf (f, "  Speculative targets:");
3549       dump_targets (f, targets, verbose);
3550     }
3551   /* Ugly: during callgraph construction the target cache may get populated
3552      before all targets are found.  While this is harmless (because all local
3553      types are discovered and only in those case we devirtualize fully and we
3554      don't do speculative devirtualization before IPA stage) it triggers
3555      assert here when dumping at that stage also populates the case with
3556      speculative targets.  Quietly ignore this.  */
3557   gcc_assert (symtab->state < IPA_SSA || targets.length () <= len);
3558   fprintf (f, "\n");
3559 }
3560 
3561 
3562 /* Return true if N can be possibly target of a polymorphic call of
3563    OTR_TYPE/OTR_TOKEN.  */
3564 
3565 bool
3566 possible_polymorphic_call_target_p (tree otr_type,
3567 				    HOST_WIDE_INT otr_token,
3568 				    const ipa_polymorphic_call_context &ctx,
3569 				    struct cgraph_node *n)
3570 {
3571   vec <cgraph_node *> targets;
3572   unsigned int i;
3573   enum built_in_function fcode;
3574   bool final;
3575 
3576   if (TREE_CODE (TREE_TYPE (n->decl)) == FUNCTION_TYPE
3577       && ((fcode = DECL_FUNCTION_CODE (n->decl)) == BUILT_IN_UNREACHABLE
3578           || fcode == BUILT_IN_TRAP))
3579     return true;
3580 
3581   if (is_cxa_pure_virtual_p (n->decl))
3582     return true;
3583 
3584   if (!odr_hash)
3585     return true;
3586   targets = possible_polymorphic_call_targets (otr_type, otr_token, ctx, &final);
3587   for (i = 0; i < targets.length (); i++)
3588     if (n->semantically_equivalent_p (targets[i]))
3589       return true;
3590 
3591   /* At a moment we allow middle end to dig out new external declarations
3592      as a targets of polymorphic calls.  */
3593   if (!final && !n->definition)
3594     return true;
3595   return false;
3596 }
3597 
3598 
3599 
3600 /* Return true if N can be possibly target of a polymorphic call of
3601    OBJ_TYPE_REF expression REF in STMT.  */
3602 
3603 bool
3604 possible_polymorphic_call_target_p (tree ref,
3605 				    gimple *stmt,
3606 				    struct cgraph_node *n)
3607 {
3608   ipa_polymorphic_call_context context (current_function_decl, ref, stmt);
3609   tree call_fn = gimple_call_fn (stmt);
3610 
3611   return possible_polymorphic_call_target_p (obj_type_ref_class (call_fn),
3612 					     tree_to_uhwi
3613 					       (OBJ_TYPE_REF_TOKEN (call_fn)),
3614 					     context,
3615 					     n);
3616 }
3617 
3618 
3619 /* After callgraph construction new external nodes may appear.
3620    Add them into the graph.  */
3621 
3622 void
3623 update_type_inheritance_graph (void)
3624 {
3625   struct cgraph_node *n;
3626 
3627   if (!odr_hash)
3628     return;
3629   free_polymorphic_call_targets_hash ();
3630   timevar_push (TV_IPA_INHERITANCE);
3631   /* We reconstruct the graph starting from types of all methods seen in the
3632      unit.  */
3633   FOR_EACH_FUNCTION (n)
3634     if (DECL_VIRTUAL_P (n->decl)
3635 	&& !n->definition
3636 	&& n->real_symbol_p ())
3637       get_odr_type (TYPE_METHOD_BASETYPE (TREE_TYPE (n->decl)), true);
3638   timevar_pop (TV_IPA_INHERITANCE);
3639 }
3640 
3641 
3642 /* Return true if N looks like likely target of a polymorphic call.
3643    Rule out cxa_pure_virtual, noreturns, function declared cold and
3644    other obvious cases.  */
3645 
3646 bool
3647 likely_target_p (struct cgraph_node *n)
3648 {
3649   int flags;
3650   /* cxa_pure_virtual and similar things are not likely.  */
3651   if (TREE_CODE (TREE_TYPE (n->decl)) != METHOD_TYPE)
3652     return false;
3653   flags = flags_from_decl_or_type (n->decl);
3654   if (flags & ECF_NORETURN)
3655     return false;
3656   if (lookup_attribute ("cold",
3657 			DECL_ATTRIBUTES (n->decl)))
3658     return false;
3659   if (n->frequency < NODE_FREQUENCY_NORMAL)
3660     return false;
3661   /* If there are no live virtual tables referring the target,
3662      the only way the target can be called is an instance coming from other
3663      compilation unit; speculative devirtualization is built around an
3664      assumption that won't happen.  */
3665   if (!referenced_from_vtable_p (n))
3666     return false;
3667   return true;
3668 }
3669 
3670 /* Compare type warning records P1 and P2 and choose one with larger count;
3671    helper for qsort.  */
3672 
3673 int
3674 type_warning_cmp (const void *p1, const void *p2)
3675 {
3676   const odr_type_warn_count *t1 = (const odr_type_warn_count *)p1;
3677   const odr_type_warn_count *t2 = (const odr_type_warn_count *)p2;
3678 
3679   if (t1->dyn_count < t2->dyn_count)
3680    return 1;
3681   if (t1->dyn_count > t2->dyn_count)
3682    return -1;
3683   return t2->count - t1->count;
3684 }
3685 
3686 /* Compare decl warning records P1 and P2 and choose one with larger count;
3687    helper for qsort.  */
3688 
3689 int
3690 decl_warning_cmp (const void *p1, const void *p2)
3691 {
3692   const decl_warn_count *t1 = *(const decl_warn_count * const *)p1;
3693   const decl_warn_count *t2 = *(const decl_warn_count * const *)p2;
3694 
3695   if (t1->dyn_count < t2->dyn_count)
3696    return 1;
3697   if (t1->dyn_count > t2->dyn_count)
3698    return -1;
3699   return t2->count - t1->count;
3700 }
3701 
3702 
3703 /* Try to speculatively devirtualize call to OTR_TYPE with OTR_TOKEN with
3704    context CTX.  */
3705 
3706 struct cgraph_node *
3707 try_speculative_devirtualization (tree otr_type, HOST_WIDE_INT otr_token,
3708 				  ipa_polymorphic_call_context ctx)
3709 {
3710   vec <cgraph_node *>targets
3711      = possible_polymorphic_call_targets
3712 	  (otr_type, otr_token, ctx, NULL, NULL, true);
3713   unsigned int i;
3714   struct cgraph_node *likely_target = NULL;
3715 
3716   for (i = 0; i < targets.length (); i++)
3717     if (likely_target_p (targets[i]))
3718       {
3719 	if (likely_target)
3720 	  return NULL;
3721 	likely_target = targets[i];
3722       }
3723   if (!likely_target
3724       ||!likely_target->definition
3725       || DECL_EXTERNAL (likely_target->decl))
3726     return NULL;
3727 
3728   /* Don't use an implicitly-declared destructor (c++/58678).  */
3729   struct cgraph_node *non_thunk_target
3730     = likely_target->function_symbol ();
3731   if (DECL_ARTIFICIAL (non_thunk_target->decl))
3732     return NULL;
3733   if (likely_target->get_availability () <= AVAIL_INTERPOSABLE
3734       && likely_target->can_be_discarded_p ())
3735     return NULL;
3736   return likely_target;
3737 }
3738 
3739 /* The ipa-devirt pass.
3740    When polymorphic call has only one likely target in the unit,
3741    turn it into a speculative call.  */
3742 
3743 static unsigned int
3744 ipa_devirt (void)
3745 {
3746   struct cgraph_node *n;
3747   hash_set<void *> bad_call_targets;
3748   struct cgraph_edge *e;
3749 
3750   int npolymorphic = 0, nspeculated = 0, nconverted = 0, ncold = 0;
3751   int nmultiple = 0, noverwritable = 0, ndevirtualized = 0, nnotdefined = 0;
3752   int nwrong = 0, nok = 0, nexternal = 0, nartificial = 0;
3753   int ndropped = 0;
3754 
3755   if (!odr_types_ptr)
3756     return 0;
3757 
3758   if (dump_file)
3759     dump_type_inheritance_graph (dump_file);
3760 
3761   /* We can output -Wsuggest-final-methods and -Wsuggest-final-types warnings.
3762      This is implemented by setting up final_warning_records that are updated
3763      by get_polymorphic_call_targets.
3764      We need to clear cache in this case to trigger recomputation of all
3765      entries.  */
3766   if (warn_suggest_final_methods || warn_suggest_final_types)
3767     {
3768       final_warning_records = new (final_warning_record);
3769       final_warning_records->dyn_count = profile_count::zero ();
3770       final_warning_records->grow_type_warnings (odr_types.length ());
3771       free_polymorphic_call_targets_hash ();
3772     }
3773 
3774   FOR_EACH_DEFINED_FUNCTION (n)
3775     {
3776       bool update = false;
3777       if (!opt_for_fn (n->decl, flag_devirtualize))
3778 	continue;
3779       if (dump_file && n->indirect_calls)
3780 	fprintf (dump_file, "\n\nProcesing function %s\n",
3781 		 n->dump_name ());
3782       for (e = n->indirect_calls; e; e = e->next_callee)
3783 	if (e->indirect_info->polymorphic)
3784 	  {
3785 	    struct cgraph_node *likely_target = NULL;
3786 	    void *cache_token;
3787 	    bool final;
3788 
3789 	    if (final_warning_records)
3790 	      final_warning_records->dyn_count = e->count.ipa ();
3791 
3792 	    vec <cgraph_node *>targets
3793 	       = possible_polymorphic_call_targets
3794 		    (e, &final, &cache_token, true);
3795 	    unsigned int i;
3796 
3797 	    /* Trigger warnings by calculating non-speculative targets.  */
3798 	    if (warn_suggest_final_methods || warn_suggest_final_types)
3799 	      possible_polymorphic_call_targets (e);
3800 
3801 	    if (dump_file)
3802 	      dump_possible_polymorphic_call_targets
3803 		(dump_file, e, (dump_flags & TDF_DETAILS));
3804 
3805 	    npolymorphic++;
3806 
3807 	    /* See if the call can be devirtualized by means of ipa-prop's
3808 	       polymorphic call context propagation.  If not, we can just
3809 	       forget about this call being polymorphic and avoid some heavy
3810 	       lifting in remove_unreachable_nodes that will otherwise try to
3811 	       keep all possible targets alive until inlining and in the inliner
3812 	       itself.
3813 
3814 	       This may need to be revisited once we add further ways to use
3815 	       the may edges, but it is a resonable thing to do right now.  */
3816 
3817 	    if ((e->indirect_info->param_index == -1
3818 		|| (!opt_for_fn (n->decl, flag_devirtualize_speculatively)
3819 		    && e->indirect_info->vptr_changed))
3820 		&& !flag_ltrans_devirtualize)
3821 	      {
3822 		e->indirect_info->polymorphic = false;
3823 		ndropped++;
3824 	        if (dump_file)
3825 		  fprintf (dump_file, "Dropping polymorphic call info;"
3826 			   " it cannot be used by ipa-prop\n");
3827 	      }
3828 
3829 	    if (!opt_for_fn (n->decl, flag_devirtualize_speculatively))
3830 	      continue;
3831 
3832 	    if (!e->maybe_hot_p ())
3833 	      {
3834 		if (dump_file)
3835 		  fprintf (dump_file, "Call is cold\n\n");
3836 		ncold++;
3837 		continue;
3838 	      }
3839 	    if (e->speculative)
3840 	      {
3841 		if (dump_file)
3842 		  fprintf (dump_file, "Call is already speculated\n\n");
3843 		nspeculated++;
3844 
3845 		/* When dumping see if we agree with speculation.  */
3846 		if (!dump_file)
3847 		  continue;
3848 	      }
3849 	    if (bad_call_targets.contains (cache_token))
3850 	      {
3851 		if (dump_file)
3852 		  fprintf (dump_file, "Target list is known to be useless\n\n");
3853 		nmultiple++;
3854 		continue;
3855 	      }
3856 	    for (i = 0; i < targets.length (); i++)
3857 	      if (likely_target_p (targets[i]))
3858 		{
3859 		  if (likely_target)
3860 		    {
3861 		      likely_target = NULL;
3862 		      if (dump_file)
3863 			fprintf (dump_file, "More than one likely target\n\n");
3864 		      nmultiple++;
3865 		      break;
3866 		    }
3867 		  likely_target = targets[i];
3868 		}
3869 	    if (!likely_target)
3870 	      {
3871 		bad_call_targets.add (cache_token);
3872 	        continue;
3873 	      }
3874 	    /* This is reached only when dumping; check if we agree or disagree
3875  	       with the speculation.  */
3876 	    if (e->speculative)
3877 	      {
3878 		struct cgraph_edge *e2;
3879 		struct ipa_ref *ref;
3880 		e->speculative_call_info (e2, e, ref);
3881 		if (e2->callee->ultimate_alias_target ()
3882 		    == likely_target->ultimate_alias_target ())
3883 		  {
3884 		    fprintf (dump_file, "We agree with speculation\n\n");
3885 		    nok++;
3886 		  }
3887 		else
3888 		  {
3889 		    fprintf (dump_file, "We disagree with speculation\n\n");
3890 		    nwrong++;
3891 		  }
3892 		continue;
3893 	      }
3894 	    if (!likely_target->definition)
3895 	      {
3896 		if (dump_file)
3897 		  fprintf (dump_file, "Target is not a definition\n\n");
3898 		nnotdefined++;
3899 		continue;
3900 	      }
3901 	    /* Do not introduce new references to external symbols.  While we
3902 	       can handle these just well, it is common for programs to
3903 	       incorrectly with headers defining methods they are linked
3904 	       with.  */
3905 	    if (DECL_EXTERNAL (likely_target->decl))
3906 	      {
3907 		if (dump_file)
3908 		  fprintf (dump_file, "Target is external\n\n");
3909 		nexternal++;
3910 		continue;
3911 	      }
3912 	    /* Don't use an implicitly-declared destructor (c++/58678).  */
3913 	    struct cgraph_node *non_thunk_target
3914 	      = likely_target->function_symbol ();
3915 	    if (DECL_ARTIFICIAL (non_thunk_target->decl))
3916 	      {
3917 		if (dump_file)
3918 		  fprintf (dump_file, "Target is artificial\n\n");
3919 		nartificial++;
3920 		continue;
3921 	      }
3922 	    if (likely_target->get_availability () <= AVAIL_INTERPOSABLE
3923 		&& likely_target->can_be_discarded_p ())
3924 	      {
3925 		if (dump_file)
3926 		  fprintf (dump_file, "Target is overwritable\n\n");
3927 		noverwritable++;
3928 		continue;
3929 	      }
3930 	    else if (dbg_cnt (devirt))
3931 	      {
3932 		if (dump_enabled_p ())
3933                   {
3934                     dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, e->call_stmt,
3935 				     "speculatively devirtualizing call "
3936 				     "in %s to %s\n",
3937 				     n->dump_name (),
3938 				     likely_target->dump_name ());
3939                   }
3940 		if (!likely_target->can_be_discarded_p ())
3941 		  {
3942 		    cgraph_node *alias;
3943 		    alias = dyn_cast<cgraph_node *> (likely_target->noninterposable_alias ());
3944 		    if (alias)
3945 		      likely_target = alias;
3946 		  }
3947 		nconverted++;
3948 		update = true;
3949 		e->make_speculative
3950 		  (likely_target, e->count.apply_scale (8, 10));
3951 	      }
3952 	  }
3953       if (update)
3954 	ipa_update_overall_fn_summary (n);
3955     }
3956   if (warn_suggest_final_methods || warn_suggest_final_types)
3957     {
3958       if (warn_suggest_final_types)
3959 	{
3960 	  final_warning_records->type_warnings.qsort (type_warning_cmp);
3961 	  for (unsigned int i = 0;
3962 	       i < final_warning_records->type_warnings.length (); i++)
3963 	    if (final_warning_records->type_warnings[i].count)
3964 	      {
3965 	        tree type = final_warning_records->type_warnings[i].type;
3966 	        int count = final_warning_records->type_warnings[i].count;
3967 	        profile_count dyn_count
3968 		  = final_warning_records->type_warnings[i].dyn_count;
3969 
3970 		if (!(dyn_count > 0))
3971 		  warning_n (DECL_SOURCE_LOCATION (TYPE_NAME (type)),
3972 			     OPT_Wsuggest_final_types, count,
3973 			     "Declaring type %qD final "
3974 			     "would enable devirtualization of %i call",
3975 			     "Declaring type %qD final "
3976 			     "would enable devirtualization of %i calls",
3977 			     type,
3978 			     count);
3979 		else
3980 		  warning_n (DECL_SOURCE_LOCATION (TYPE_NAME (type)),
3981 			     OPT_Wsuggest_final_types, count,
3982 			     "Declaring type %qD final "
3983 			     "would enable devirtualization of %i call "
3984 			     "executed %lli times",
3985 			     "Declaring type %qD final "
3986 			     "would enable devirtualization of %i calls "
3987 			     "executed %lli times",
3988 			     type,
3989 			     count,
3990 			     (long long) dyn_count.to_gcov_type ());
3991 	      }
3992 	}
3993 
3994       if (warn_suggest_final_methods)
3995 	{
3996 	  auto_vec<const decl_warn_count*> decl_warnings_vec;
3997 
3998 	  final_warning_records->decl_warnings.traverse
3999 	    <vec<const decl_warn_count *> *, add_decl_warning> (&decl_warnings_vec);
4000 	  decl_warnings_vec.qsort (decl_warning_cmp);
4001 	  for (unsigned int i = 0; i < decl_warnings_vec.length (); i++)
4002 	    {
4003 	      tree decl = decl_warnings_vec[i]->decl;
4004 	      int count = decl_warnings_vec[i]->count;
4005 	      profile_count dyn_count
4006 		  = decl_warnings_vec[i]->dyn_count;
4007 
4008 	      if (!(dyn_count > 0))
4009 		if (DECL_CXX_DESTRUCTOR_P (decl))
4010 		  warning_n (DECL_SOURCE_LOCATION (decl),
4011 			      OPT_Wsuggest_final_methods, count,
4012 			      "Declaring virtual destructor of %qD final "
4013 			      "would enable devirtualization of %i call",
4014 			      "Declaring virtual destructor of %qD final "
4015 			      "would enable devirtualization of %i calls",
4016 			      DECL_CONTEXT (decl), count);
4017 		else
4018 		  warning_n (DECL_SOURCE_LOCATION (decl),
4019 			      OPT_Wsuggest_final_methods, count,
4020 			      "Declaring method %qD final "
4021 			      "would enable devirtualization of %i call",
4022 			      "Declaring method %qD final "
4023 			      "would enable devirtualization of %i calls",
4024 			      decl, count);
4025 	       else if (DECL_CXX_DESTRUCTOR_P (decl))
4026 		  warning_n (DECL_SOURCE_LOCATION (decl),
4027 			      OPT_Wsuggest_final_methods, count,
4028 			      "Declaring virtual destructor of %qD final "
4029 			      "would enable devirtualization of %i call "
4030 			      "executed %lli times",
4031 			      "Declaring virtual destructor of %qD final "
4032 			      "would enable devirtualization of %i calls "
4033 			      "executed %lli times",
4034 			      DECL_CONTEXT (decl), count,
4035 			      (long long)dyn_count.to_gcov_type ());
4036 		else
4037 		  warning_n (DECL_SOURCE_LOCATION (decl),
4038 			      OPT_Wsuggest_final_methods, count,
4039 			      "Declaring method %qD final "
4040 			      "would enable devirtualization of %i call "
4041 			      "executed %lli times",
4042 			      "Declaring method %qD final "
4043 			      "would enable devirtualization of %i calls "
4044 			      "executed %lli times",
4045 			      decl, count,
4046 			      (long long)dyn_count.to_gcov_type ());
4047 	    }
4048 	}
4049 
4050       delete (final_warning_records);
4051       final_warning_records = 0;
4052     }
4053 
4054   if (dump_file)
4055     fprintf (dump_file,
4056 	     "%i polymorphic calls, %i devirtualized,"
4057 	     " %i speculatively devirtualized, %i cold\n"
4058 	     "%i have multiple targets, %i overwritable,"
4059 	     " %i already speculated (%i agree, %i disagree),"
4060 	     " %i external, %i not defined, %i artificial, %i infos dropped\n",
4061 	     npolymorphic, ndevirtualized, nconverted, ncold,
4062 	     nmultiple, noverwritable, nspeculated, nok, nwrong,
4063 	     nexternal, nnotdefined, nartificial, ndropped);
4064   return ndevirtualized || ndropped ? TODO_remove_functions : 0;
4065 }
4066 
4067 namespace {
4068 
4069 const pass_data pass_data_ipa_devirt =
4070 {
4071   IPA_PASS, /* type */
4072   "devirt", /* name */
4073   OPTGROUP_NONE, /* optinfo_flags */
4074   TV_IPA_DEVIRT, /* tv_id */
4075   0, /* properties_required */
4076   0, /* properties_provided */
4077   0, /* properties_destroyed */
4078   0, /* todo_flags_start */
4079   ( TODO_dump_symtab ), /* todo_flags_finish */
4080 };
4081 
4082 class pass_ipa_devirt : public ipa_opt_pass_d
4083 {
4084 public:
4085   pass_ipa_devirt (gcc::context *ctxt)
4086     : ipa_opt_pass_d (pass_data_ipa_devirt, ctxt,
4087 		      NULL, /* generate_summary */
4088 		      NULL, /* write_summary */
4089 		      NULL, /* read_summary */
4090 		      NULL, /* write_optimization_summary */
4091 		      NULL, /* read_optimization_summary */
4092 		      NULL, /* stmt_fixup */
4093 		      0, /* function_transform_todo_flags_start */
4094 		      NULL, /* function_transform */
4095 		      NULL) /* variable_transform */
4096   {}
4097 
4098   /* opt_pass methods: */
4099   virtual bool gate (function *)
4100     {
4101       /* In LTO, always run the IPA passes and decide on function basis if the
4102 	 pass is enabled.  */
4103       if (in_lto_p)
4104 	return true;
4105       return (flag_devirtualize
4106 	      && (flag_devirtualize_speculatively
4107 		  || (warn_suggest_final_methods
4108 		      || warn_suggest_final_types))
4109 	      && optimize);
4110     }
4111 
4112   virtual unsigned int execute (function *) { return ipa_devirt (); }
4113 
4114 }; // class pass_ipa_devirt
4115 
4116 } // anon namespace
4117 
4118 ipa_opt_pass_d *
4119 make_pass_ipa_devirt (gcc::context *ctxt)
4120 {
4121   return new pass_ipa_devirt (ctxt);
4122 }
4123 
4124 #include "gt-ipa-devirt.h"
4125