c++: Prevent overwriting arguments when merging duplicates [PR112588]
[official-gcc.git] / gcc / cp / module.cc
blob8db662c0267f85bb9649b1174daa6ada2a76c0be
1 /* C++ modules. Experimental!
2 Copyright (C) 2017-2024 Free Software Foundation, Inc.
3 Written by Nathan Sidwell <nathan@acm.org> while at FaceBook
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* Comments in this file have a non-negligible chance of being wrong
22 or at least inaccurate. Due to (a) my misunderstanding, (b)
23 ambiguities that I have interpretted differently to original intent
24 (c) changes in the specification, (d) my poor wording, (e) source
25 changes. */
27 /* (Incomplete) Design Notes
29 A hash table contains all module names. Imported modules are
30 present in a modules array, which by construction places an
31 import's dependencies before the import itself. The single
32 exception is the current TU, which always occupies slot zero (even
33 when it is not a module).
35 Imported decls occupy an entity_ary, an array of binding_slots, indexed
36 by importing module and index within that module. A flat index is
37 used, as each module reserves a contiguous range of indices.
38 Initially each slot indicates the CMI section containing the
39 streamed decl. When the decl is imported it will point to the decl
40 itself.
42 Additionally each imported decl is mapped in the entity_map via its
43 DECL_UID to the flat index in the entity_ary. Thus we can locate
44 the index for any imported decl by using this map and then
45 de-flattening the index via a binary seach of the module vector.
46 Cross-module references are by (remapped) module number and
47 module-local index.
49 Each importable DECL contains several flags. The simple set are
50 DECL_MODULE_EXPORT_P, DECL_MODULE_PURVIEW_P, DECL_MODULE_ATTACH_P
51 and DECL_MODULE_IMPORT_P. The first indicates whether it is
52 exported, the second whether it is in module or header-unit
53 purview. The third indicates it is attached to the named module in
54 whose purview it resides and the fourth indicates whether it was an
55 import into this TU or not. DECL_MODULE_ATTACH_P will be false for
56 all decls in a header-unit, and for those in a named module inside
57 a linkage declaration.
59 The more detailed flags are DECL_MODULE_PARTITION_P,
60 DECL_MODULE_ENTITY_P. The first is set in a primary interface unit
61 on decls that were read from module partitions (these will have
62 DECL_MODULE_IMPORT_P set too). Such decls will be streamed out to
63 the primary's CMI. DECL_MODULE_ENTITY_P is set when an entity is
64 imported, even if it matched a non-imported entity. Such a decl
65 will not have DECL_MODULE_IMPORT_P set, even though it has an entry
66 in the entity map and array.
68 Header units are module-like.
70 For namespace-scope lookup, the decls for a particular module are
71 held located in a sparse array hanging off the binding of the name.
72 This is partitioned into two: a few fixed slots at the start
73 followed by the sparse slots afterwards. By construction we only
74 need to append new slots to the end -- there is never a need to
75 insert in the middle. The fixed slots are MODULE_SLOT_CURRENT for
76 the current TU (regardless of whether it is a module or not),
77 MODULE_SLOT_GLOBAL and MODULE_SLOT_PARTITION. These latter two
78 slots are used for merging entities across the global module and
79 module partitions respectively. MODULE_SLOT_PARTITION is only
80 present in a module. Neither of those two slots is searched during
81 name lookup -- they are internal use only. This vector is created
82 lazily once we require it, if there is only a declaration from the
83 current TU, a regular binding is present. It is converted on
84 demand.
86 OPTIMIZATION: Outside of the current TU, we only need ADL to work.
87 We could optimize regular lookup for the current TU by glomming all
88 the visible decls on its slot. Perhaps wait until design is a
89 little more settled though.
91 There is only one instance of each extern-linkage namespace. It
92 appears in every module slot that makes it visible. It also
93 appears in MODULE_SLOT_GLOBAL. (It is an ODR violation if they
94 collide with some other global module entity.) We also have an
95 optimization that shares the slot for adjacent modules that declare
96 the same such namespace.
98 A module interface compilation produces a Compiled Module Interface
99 (CMI). The format used is Encapsulated Lazy Records Of Numbered
100 Declarations, which is essentially ELF's section encapsulation. (As
101 all good nerds are aware, Elrond is half Elf.) Some sections are
102 named, and contain information about the module as a whole (indices
103 etc), and other sections are referenced by number. Although I
104 don't defend against actively hostile CMIs, there is some
105 checksumming involved to verify data integrity. When dumping out
106 an interface, we generate a graph of all the
107 independently-redeclarable DECLS that are needed, and the decls
108 they reference. From that we determine the strongly connected
109 components (SCC) within this TU. Each SCC is dumped to a separate
110 numbered section of the CMI. We generate a binding table section,
111 mapping each namespace&name to a defining section. This allows
112 lazy loading.
114 Lazy loading employs mmap to map a read-only image of the CMI.
115 It thus only occupies address space and is paged in on demand,
116 backed by the CMI file itself. If mmap is unavailable, regular
117 FILEIO is used. Also, there's a bespoke ELF reader/writer here,
118 which implements just the section table and sections (including
119 string sections) of a 32-bit ELF in host byte-order. You can of
120 course inspect it with readelf. I figured 32-bit is sufficient,
121 for a single module. I detect running out of section numbers, but
122 do not implement the ELF overflow mechanism. At least you'll get
123 an error if that happens.
125 We do not separate declarations and definitions. My guess is that
126 if you refer to the declaration, you'll also need the definition
127 (template body, inline function, class definition etc). But this
128 does mean we can get larger SCCs than if we separated them. It is
129 unclear whether this is a win or not.
131 Notice that we embed section indices into the contents of other
132 sections. Thus random manipulation of the CMI file by ELF tools
133 may well break it. The kosher way would probably be to introduce
134 indirection via section symbols, but that would require defining a
135 relocation type.
137 Notice that lazy loading of one module's decls can cause lazy
138 loading of other decls in the same or another module. Clearly we
139 want to avoid loops. In a correct program there can be no loops in
140 the module dependency graph, and the above-mentioned SCC algorithm
141 places all intra-module circular dependencies in the same SCC. It
142 also orders the SCCs wrt each other, so dependent SCCs come first.
143 As we load dependent modules first, we know there can be no
144 reference to a higher-numbered module, and because we write out
145 dependent SCCs first, likewise for SCCs within the module. This
146 allows us to immediately detect broken references. When loading,
147 we must ensure the rest of the compiler doesn't cause some
148 unconnected load to occur (for instance, instantiate a template).
150 Classes used:
152 dumper - logger
154 data - buffer
156 bytes - data streamer
157 bytes_in : bytes - scalar reader
158 bytes_out : bytes - scalar writer
160 elf - ELROND format
161 elf_in : elf - ELROND reader
162 elf_out : elf - ELROND writer
164 trees_in : bytes_in - tree reader
165 trees_out : bytes_out - tree writer
167 depset - dependency set
168 depset::hash - hash table of depsets
169 depset::tarjan - SCC determinator
171 uidset<T> - set T's related to a UID
172 uidset<T>::hash hash table of uidset<T>
174 loc_spans - location map data
176 module_state - module object
178 slurping - data needed during loading
180 macro_import - imported macro data
181 macro_export - exported macro data
183 The ELROND objects use mmap, for both reading and writing. If mmap
184 is unavailable, fileno IO is used to read and write blocks of data.
186 The mapper object uses fileno IO to communicate with the server or
187 program. */
189 /* In expermental (trunk) sources, MODULE_VERSION is a #define passed
190 in from the Makefile. It records the modification date of the
191 source directory -- that's the only way to stay sane. In release
192 sources, we (plan to) use the compiler's major.minor versioning.
193 While the format might not change between at minor versions, it
194 seems simplest to tie the two together. There's no concept of
195 inter-version compatibility. */
196 #define IS_EXPERIMENTAL(V) ((V) >= (1U << 20))
197 #define MODULE_MAJOR(V) ((V) / 10000)
198 #define MODULE_MINOR(V) ((V) % 10000)
199 #define EXPERIMENT(A,B) (IS_EXPERIMENTAL (MODULE_VERSION) ? (A) : (B))
200 #ifndef MODULE_VERSION
201 #include "bversion.h"
202 #define MODULE_VERSION (BUILDING_GCC_MAJOR * 10000U + BUILDING_GCC_MINOR)
203 #elif !IS_EXPERIMENTAL (MODULE_VERSION)
204 #error "This is not the version I was looking for."
205 #endif
207 #define _DEFAULT_SOURCE 1 /* To get TZ field of struct tm, if available. */
208 #include "config.h"
209 #define INCLUDE_MEMORY
210 #define INCLUDE_STRING
211 #define INCLUDE_VECTOR
212 #include "system.h"
213 #include "coretypes.h"
214 #include "cp-tree.h"
215 #include "timevar.h"
216 #include "stringpool.h"
217 #include "dumpfile.h"
218 #include "bitmap.h"
219 #include "cgraph.h"
220 #include "tree-iterator.h"
221 #include "cpplib.h"
222 #include "mkdeps.h"
223 #include "incpath.h"
224 #include "libiberty.h"
225 #include "stor-layout.h"
226 #include "version.h"
227 #include "tree-diagnostic.h"
228 #include "toplev.h"
229 #include "opts.h"
230 #include "attribs.h"
231 #include "intl.h"
232 #include "langhooks.h"
233 /* This TU doesn't need or want to see the networking. */
234 #define CODY_NETWORKING 0
235 #include "mapper-client.h"
237 #if 0 // 1 for testing no mmap
238 #define MAPPED_READING 0
239 #define MAPPED_WRITING 0
240 #else
241 #if HAVE_MMAP_FILE && _POSIX_MAPPED_FILES > 0
242 /* mmap, munmap. */
243 #define MAPPED_READING 1
244 #if HAVE_SYSCONF && defined (_SC_PAGE_SIZE)
245 /* msync, sysconf (_SC_PAGE_SIZE), ftruncate */
246 /* posix_fallocate used if available. */
247 #define MAPPED_WRITING 1
248 #else
249 #define MAPPED_WRITING 0
250 #endif
251 #else
252 #define MAPPED_READING 0
253 #define MAPPED_WRITING 0
254 #endif
255 #endif
257 /* Some open(2) flag differences, what a colourful world it is! */
258 #if defined (O_CLOEXEC)
259 // OK
260 #elif defined (_O_NOINHERIT)
261 /* Windows' _O_NOINHERIT matches O_CLOEXEC flag */
262 #define O_CLOEXEC _O_NOINHERIT
263 #else
264 #define O_CLOEXEC 0
265 #endif
266 #if defined (O_BINARY)
267 // Ok?
268 #elif defined (_O_BINARY)
269 /* Windows' open(2) call defaults to text! */
270 #define O_BINARY _O_BINARY
271 #else
272 #define O_BINARY 0
273 #endif
275 static inline cpp_hashnode *cpp_node (tree id)
277 return CPP_HASHNODE (GCC_IDENT_TO_HT_IDENT (id));
280 static inline tree identifier (const cpp_hashnode *node)
282 /* HT_NODE() expands to node->ident that HT_IDENT_TO_GCC_IDENT()
283 then subtracts a nonzero constant, deriving a pointer to
284 a different member than ident. That's strictly undefined
285 and detected by -Warray-bounds. Suppress it. See PR 101372. */
286 #pragma GCC diagnostic push
287 #pragma GCC diagnostic ignored "-Warray-bounds"
288 return HT_IDENT_TO_GCC_IDENT (HT_NODE (const_cast<cpp_hashnode *> (node)));
289 #pragma GCC diagnostic pop
292 /* Id for dumping module information. */
293 int module_dump_id;
295 /* We have a special module owner. */
296 #define MODULE_UNKNOWN (~0U) /* Not yet known. */
298 /* Prefix for section names. */
299 #define MOD_SNAME_PFX ".gnu.c++"
301 /* Format a version for user consumption. */
303 typedef char verstr_t[32];
304 static void
305 version2string (unsigned version, verstr_t &out)
307 unsigned major = MODULE_MAJOR (version);
308 unsigned minor = MODULE_MINOR (version);
310 if (IS_EXPERIMENTAL (version))
311 sprintf (out, "%04u/%02u/%02u-%02u:%02u%s",
312 2000 + major / 10000, (major / 100) % 100, (major % 100),
313 minor / 100, minor % 100,
314 EXPERIMENT ("", " (experimental)"));
315 else
316 sprintf (out, "%u.%u", major, minor);
319 /* Include files to note translation for. */
320 static vec<const char *, va_heap, vl_embed> *note_includes;
322 /* Modules to note CMI pathames. */
323 static vec<const char *, va_heap, vl_embed> *note_cmis;
325 /* Traits to hash an arbitrary pointer. Entries are not deletable,
326 and removal is a noop (removal needed upon destruction). */
327 template <typename T>
328 struct nodel_ptr_hash : pointer_hash<T>, typed_noop_remove <T *> {
329 /* Nothing is deletable. Everything is insertable. */
330 static bool is_deleted (T *) { return false; }
331 static void mark_deleted (T *) { gcc_unreachable (); }
334 /* Map from pointer to signed integer. */
335 typedef simple_hashmap_traits<nodel_ptr_hash<void>, int> ptr_int_traits;
336 typedef hash_map<void *,signed,ptr_int_traits> ptr_int_hash_map;
338 /********************************************************************/
339 /* Basic streaming & ELF. Serialization is usually via mmap. For
340 writing we slide a buffer over the output file, syncing it
341 approproiately. For reading we simply map the whole file (as a
342 file-backed read-only map -- it's just address space, leaving the
343 OS pager to deal with getting the data to us). Some buffers need
344 to be more conventional malloc'd contents. */
346 /* Variable length buffer. */
348 class data {
349 public:
350 class allocator {
351 public:
352 /* Tools tend to moan if the dtor's not virtual. */
353 virtual ~allocator () {}
355 public:
356 void grow (data &obj, unsigned needed, bool exact);
357 void shrink (data &obj);
359 public:
360 virtual char *grow (char *ptr, unsigned needed);
361 virtual void shrink (char *ptr);
364 public:
365 char *buffer; /* Buffer being transferred. */
366 /* Although size_t would be the usual size, we know we never get
367 more than 4GB of buffer -- because that's the limit of the
368 encapsulation format. And if you need bigger imports, you're
369 doing it wrong. */
370 unsigned size; /* Allocated size of buffer. */
371 unsigned pos; /* Position in buffer. */
373 public:
374 data ()
375 :buffer (NULL), size (0), pos (0)
378 ~data ()
380 /* Make sure the derived and/or using class know what they're
381 doing. */
382 gcc_checking_assert (!buffer);
385 protected:
386 char *use (unsigned count)
388 if (size < pos + count)
389 return NULL;
390 char *res = &buffer[pos];
391 pos += count;
392 return res;
395 public:
396 void unuse (unsigned count)
398 pos -= count;
401 public:
402 static allocator simple_memory;
405 /* The simple data allocator. */
406 data::allocator data::simple_memory;
408 /* Grow buffer to at least size NEEDED. */
410 void
411 data::allocator::grow (data &obj, unsigned needed, bool exact)
413 gcc_checking_assert (needed ? needed > obj.size : !obj.size);
414 if (!needed)
415 /* Pick a default size. */
416 needed = EXPERIMENT (100, 1000);
418 if (!exact)
419 needed *= 2;
420 obj.buffer = grow (obj.buffer, needed);
421 if (obj.buffer)
422 obj.size = needed;
423 else
424 obj.pos = obj.size = 0;
427 /* Free a buffer. */
429 void
430 data::allocator::shrink (data &obj)
432 shrink (obj.buffer);
433 obj.buffer = NULL;
434 obj.size = 0;
437 char *
438 data::allocator::grow (char *ptr, unsigned needed)
440 return XRESIZEVAR (char, ptr, needed);
443 void
444 data::allocator::shrink (char *ptr)
446 XDELETEVEC (ptr);
449 /* Byte streamer base. Buffer with read/write position and smarts
450 for single bits. */
452 class bytes : public data {
453 public:
454 typedef data parent;
456 protected:
457 uint32_t bit_val; /* Bit buffer. */
458 unsigned bit_pos; /* Next bit in bit buffer. */
460 public:
461 bytes ()
462 :parent (), bit_val (0), bit_pos (0)
464 ~bytes ()
468 protected:
469 unsigned calc_crc (unsigned) const;
471 protected:
472 /* Finish bit packet. Rewind the bytes not used. */
473 unsigned bit_flush ()
475 gcc_assert (bit_pos);
476 unsigned bytes = (bit_pos + 7) / 8;
477 unuse (4 - bytes);
478 bit_pos = 0;
479 bit_val = 0;
480 return bytes;
484 /* Calculate the crc32 of the buffer. Note the CRC is stored in the
485 first 4 bytes, so don't include them. */
487 unsigned
488 bytes::calc_crc (unsigned l) const
490 unsigned crc = 0;
491 for (size_t ix = 4; ix < l; ix++)
492 crc = crc32_byte (crc, buffer[ix]);
493 return crc;
496 class elf_in;
498 /* Byte stream reader. */
500 class bytes_in : public bytes {
501 typedef bytes parent;
503 protected:
504 bool overrun; /* Sticky read-too-much flag. */
506 public:
507 bytes_in ()
508 : parent (), overrun (false)
511 ~bytes_in ()
515 public:
516 /* Begin reading a named section. */
517 bool begin (location_t loc, elf_in *src, const char *name);
518 /* Begin reading a numbered section with optional name. */
519 bool begin (location_t loc, elf_in *src, unsigned, const char * = NULL);
520 /* Complete reading a buffer. Propagate errors and return true on
521 success. */
522 bool end (elf_in *src);
523 /* Return true if there is unread data. */
524 bool more_p () const
526 return pos != size;
529 public:
530 /* Start reading at OFFSET. */
531 void random_access (unsigned offset)
533 if (offset > size)
534 set_overrun ();
535 pos = offset;
536 bit_pos = bit_val = 0;
539 public:
540 void align (unsigned boundary)
542 if (unsigned pad = pos & (boundary - 1))
543 read (boundary - pad);
546 public:
547 const char *read (unsigned count)
549 char *ptr = use (count);
550 if (!ptr)
551 set_overrun ();
552 return ptr;
555 public:
556 bool check_crc () const;
557 /* We store the CRC in the first 4 bytes, using host endianness. */
558 unsigned get_crc () const
560 return *(const unsigned *)&buffer[0];
563 public:
564 /* Manipulate the overrun flag. */
565 bool get_overrun () const
567 return overrun;
569 void set_overrun ()
571 overrun = true;
574 public:
575 unsigned u32 (); /* Read uncompressed integer. */
577 public:
578 bool b (); /* Read a bool. */
579 void bflush (); /* Completed a block of bools. */
581 private:
582 void bfill (); /* Get the next block of bools. */
584 public:
585 int c (); /* Read a char. */
586 int i (); /* Read a signed int. */
587 unsigned u (); /* Read an unsigned int. */
588 size_t z (); /* Read a size_t. */
589 HOST_WIDE_INT wi (); /* Read a HOST_WIDE_INT. */
590 unsigned HOST_WIDE_INT wu (); /* Read an unsigned HOST_WIDE_INT. */
591 const char *str (size_t * = NULL); /* Read a string. */
592 const void *buf (size_t); /* Read a fixed-length buffer. */
593 cpp_hashnode *cpp_node (); /* Read a cpp node. */
596 /* Verify the buffer's CRC is correct. */
598 bool
599 bytes_in::check_crc () const
601 if (size < 4)
602 return false;
604 unsigned c_crc = calc_crc (size);
605 if (c_crc != get_crc ())
606 return false;
608 return true;
611 class elf_out;
613 /* Byte stream writer. */
615 class bytes_out : public bytes {
616 typedef bytes parent;
618 public:
619 allocator *memory; /* Obtainer of memory. */
621 public:
622 bytes_out (allocator *memory)
623 : parent (), memory (memory)
626 ~bytes_out ()
630 public:
631 bool streaming_p () const
633 return memory != NULL;
636 public:
637 void set_crc (unsigned *crc_ptr);
639 public:
640 /* Begin writing, maybe reserve space for CRC. */
641 void begin (bool need_crc = true);
642 /* Finish writing. Spill to section by number. */
643 unsigned end (elf_out *, unsigned, unsigned *crc_ptr = NULL);
645 public:
646 void align (unsigned boundary)
648 if (unsigned pad = pos & (boundary - 1))
649 write (boundary - pad);
652 public:
653 char *write (unsigned count, bool exact = false)
655 if (size < pos + count)
656 memory->grow (*this, pos + count, exact);
657 return use (count);
660 public:
661 void u32 (unsigned); /* Write uncompressed integer. */
663 public:
664 void b (bool); /* Write bool. */
665 void bflush (); /* Finish block of bools. */
667 public:
668 void c (unsigned char); /* Write unsigned char. */
669 void i (int); /* Write signed int. */
670 void u (unsigned); /* Write unsigned int. */
671 void z (size_t s); /* Write size_t. */
672 void wi (HOST_WIDE_INT); /* Write HOST_WIDE_INT. */
673 void wu (unsigned HOST_WIDE_INT); /* Write unsigned HOST_WIDE_INT. */
674 void str (const char *ptr)
676 str (ptr, strlen (ptr));
678 void cpp_node (const cpp_hashnode *node)
680 str ((const char *)NODE_NAME (node), NODE_LEN (node));
682 void str (const char *, size_t); /* Write string of known length. */
683 void buf (const void *, size_t); /* Write fixed length buffer. */
684 void *buf (size_t); /* Create a writable buffer */
686 public:
687 /* Format a NUL-terminated raw string. */
688 void printf (const char *, ...) ATTRIBUTE_PRINTF_2;
689 void print_time (const char *, const tm *, const char *);
691 public:
692 /* Dump instrumentation. */
693 static void instrument ();
695 protected:
696 /* Instrumentation. */
697 static unsigned spans[4];
698 static unsigned lengths[4];
699 static int is_set;
702 /* Instrumentation. */
703 unsigned bytes_out::spans[4];
704 unsigned bytes_out::lengths[4];
705 int bytes_out::is_set = -1;
707 /* If CRC_PTR non-null, set the CRC of the buffer. Mix the CRC into
708 that pointed to by CRC_PTR. */
710 void
711 bytes_out::set_crc (unsigned *crc_ptr)
713 if (crc_ptr)
715 gcc_checking_assert (pos >= 4);
717 unsigned crc = calc_crc (pos);
718 unsigned accum = *crc_ptr;
719 /* Only mix the existing *CRC_PTR if it is non-zero. */
720 accum = accum ? crc32_unsigned (accum, crc) : crc;
721 *crc_ptr = accum;
723 /* Buffer will be sufficiently aligned. */
724 *(unsigned *)buffer = crc;
728 /* Finish a set of bools. */
730 void
731 bytes_out::bflush ()
733 if (bit_pos)
735 u32 (bit_val);
736 lengths[2] += bit_flush ();
738 spans[2]++;
739 is_set = -1;
742 void
743 bytes_in::bflush ()
745 if (bit_pos)
746 bit_flush ();
749 /* When reading, we don't know how many bools we'll read in. So read
750 4 bytes-worth, and then rewind when flushing if we didn't need them
751 all. You can't have a block of bools closer than 4 bytes to the
752 end of the buffer. */
754 void
755 bytes_in::bfill ()
757 bit_val = u32 ();
760 /* Bools are packed into bytes. You cannot mix bools and non-bools.
761 You must call bflush before emitting another type. So batch your
762 bools.
764 It may be worth optimizing for most bools being zero. Some kind of
765 run-length encoding? */
767 void
768 bytes_out::b (bool x)
770 if (is_set != x)
772 is_set = x;
773 spans[x]++;
775 lengths[x]++;
776 bit_val |= unsigned (x) << bit_pos++;
777 if (bit_pos == 32)
779 u32 (bit_val);
780 lengths[2] += bit_flush ();
784 bool
785 bytes_in::b ()
787 if (!bit_pos)
788 bfill ();
789 bool v = (bit_val >> bit_pos++) & 1;
790 if (bit_pos == 32)
791 bit_flush ();
792 return v;
795 /* Exactly 4 bytes. Used internally for bool packing and a few other
796 places. We can't simply use uint32_t because (a) alignment and
797 (b) we need little-endian for the bool streaming rewinding to make
798 sense. */
800 void
801 bytes_out::u32 (unsigned val)
803 if (char *ptr = write (4))
805 ptr[0] = val;
806 ptr[1] = val >> 8;
807 ptr[2] = val >> 16;
808 ptr[3] = val >> 24;
812 unsigned
813 bytes_in::u32 ()
815 unsigned val = 0;
816 if (const char *ptr = read (4))
818 val |= (unsigned char)ptr[0];
819 val |= (unsigned char)ptr[1] << 8;
820 val |= (unsigned char)ptr[2] << 16;
821 val |= (unsigned char)ptr[3] << 24;
824 return val;
827 /* Chars are unsigned and written as single bytes. */
829 void
830 bytes_out::c (unsigned char v)
832 if (char *ptr = write (1))
833 *ptr = v;
837 bytes_in::c ()
839 int v = 0;
840 if (const char *ptr = read (1))
841 v = (unsigned char)ptr[0];
842 return v;
845 /* Ints 7-bit as a byte. Otherwise a 3bit count of following bytes in
846 big-endian form. 4 bits are in the first byte. */
848 void
849 bytes_out::i (int v)
851 if (char *ptr = write (1))
853 if (v <= 0x3f && v >= -0x40)
854 *ptr = v & 0x7f;
855 else
857 unsigned bytes = 0;
858 int probe;
859 if (v >= 0)
860 for (probe = v >> 8; probe > 0x7; probe >>= 8)
861 bytes++;
862 else
863 for (probe = v >> 8; probe < -0x8; probe >>= 8)
864 bytes++;
865 *ptr = 0x80 | bytes << 4 | (probe & 0xf);
866 if ((ptr = write (++bytes)))
867 for (; bytes--; v >>= 8)
868 ptr[bytes] = v & 0xff;
874 bytes_in::i ()
876 int v = 0;
877 if (const char *ptr = read (1))
879 v = *ptr & 0xff;
880 if (v & 0x80)
882 unsigned bytes = (v >> 4) & 0x7;
883 v &= 0xf;
884 if (v & 0x8)
885 v |= -1 ^ 0x7;
886 /* unsigned necessary due to left shifts of -ve values. */
887 unsigned uv = unsigned (v);
888 if ((ptr = read (++bytes)))
889 while (bytes--)
890 uv = (uv << 8) | (*ptr++ & 0xff);
891 v = int (uv);
893 else if (v & 0x40)
894 v |= -1 ^ 0x3f;
897 return v;
900 void
901 bytes_out::u (unsigned v)
903 if (char *ptr = write (1))
905 if (v <= 0x7f)
906 *ptr = v;
907 else
909 unsigned bytes = 0;
910 unsigned probe;
911 for (probe = v >> 8; probe > 0xf; probe >>= 8)
912 bytes++;
913 *ptr = 0x80 | bytes << 4 | probe;
914 if ((ptr = write (++bytes)))
915 for (; bytes--; v >>= 8)
916 ptr[bytes] = v & 0xff;
921 unsigned
922 bytes_in::u ()
924 unsigned v = 0;
926 if (const char *ptr = read (1))
928 v = *ptr & 0xff;
929 if (v & 0x80)
931 unsigned bytes = (v >> 4) & 0x7;
932 v &= 0xf;
933 if ((ptr = read (++bytes)))
934 while (bytes--)
935 v = (v << 8) | (*ptr++ & 0xff);
939 return v;
942 void
943 bytes_out::wi (HOST_WIDE_INT v)
945 if (char *ptr = write (1))
947 if (v <= 0x3f && v >= -0x40)
948 *ptr = v & 0x7f;
949 else
951 unsigned bytes = 0;
952 HOST_WIDE_INT probe;
953 if (v >= 0)
954 for (probe = v >> 8; probe > 0x7; probe >>= 8)
955 bytes++;
956 else
957 for (probe = v >> 8; probe < -0x8; probe >>= 8)
958 bytes++;
959 *ptr = 0x80 | bytes << 4 | (probe & 0xf);
960 if ((ptr = write (++bytes)))
961 for (; bytes--; v >>= 8)
962 ptr[bytes] = v & 0xff;
967 HOST_WIDE_INT
968 bytes_in::wi ()
970 HOST_WIDE_INT v = 0;
971 if (const char *ptr = read (1))
973 v = *ptr & 0xff;
974 if (v & 0x80)
976 unsigned bytes = (v >> 4) & 0x7;
977 v &= 0xf;
978 if (v & 0x8)
979 v |= -1 ^ 0x7;
980 /* unsigned necessary due to left shifts of -ve values. */
981 unsigned HOST_WIDE_INT uv = (unsigned HOST_WIDE_INT) v;
982 if ((ptr = read (++bytes)))
983 while (bytes--)
984 uv = (uv << 8) | (*ptr++ & 0xff);
985 v = (HOST_WIDE_INT) uv;
987 else if (v & 0x40)
988 v |= -1 ^ 0x3f;
991 return v;
994 /* unsigned wide ints are just written as signed wide ints. */
996 inline void
997 bytes_out::wu (unsigned HOST_WIDE_INT v)
999 wi ((HOST_WIDE_INT) v);
1002 inline unsigned HOST_WIDE_INT
1003 bytes_in::wu ()
1005 return (unsigned HOST_WIDE_INT) wi ();
1008 /* size_t written as unsigned or unsigned wide int. */
1010 inline void
1011 bytes_out::z (size_t s)
1013 if (sizeof (s) == sizeof (unsigned))
1014 u (s);
1015 else
1016 wu (s);
1019 inline size_t
1020 bytes_in::z ()
1022 if (sizeof (size_t) == sizeof (unsigned))
1023 return u ();
1024 else
1025 return wu ();
1028 /* Buffer simply memcpied. */
1029 void *
1030 bytes_out::buf (size_t len)
1032 align (sizeof (void *) * 2);
1033 return write (len);
1036 void
1037 bytes_out::buf (const void *src, size_t len)
1039 if (void *ptr = buf (len))
1040 memcpy (ptr, src, len);
1043 const void *
1044 bytes_in::buf (size_t len)
1046 align (sizeof (void *) * 2);
1047 const char *ptr = read (len);
1049 return ptr;
1052 /* strings as an size_t length, followed by the buffer. Make sure
1053 there's a NUL terminator on read. */
1055 void
1056 bytes_out::str (const char *string, size_t len)
1058 z (len);
1059 if (len)
1061 gcc_checking_assert (!string[len]);
1062 buf (string, len + 1);
1066 const char *
1067 bytes_in::str (size_t *len_p)
1069 size_t len = z ();
1071 /* We're about to trust some user data. */
1072 if (overrun)
1073 len = 0;
1074 if (len_p)
1075 *len_p = len;
1076 const char *str = NULL;
1077 if (len)
1079 str = reinterpret_cast<const char *> (buf (len + 1));
1080 if (!str || str[len])
1082 set_overrun ();
1083 str = NULL;
1086 return str ? str : "";
1089 cpp_hashnode *
1090 bytes_in::cpp_node ()
1092 size_t len;
1093 const char *s = str (&len);
1094 if (!len)
1095 return NULL;
1096 return ::cpp_node (get_identifier_with_length (s, len));
1099 /* Format a string directly to the buffer, including a terminating
1100 NUL. Intended for human consumption. */
1102 void
1103 bytes_out::printf (const char *format, ...)
1105 va_list args;
1106 /* Exercise buffer expansion. */
1107 size_t len = EXPERIMENT (10, 500);
1109 while (char *ptr = write (len))
1111 va_start (args, format);
1112 size_t actual = vsnprintf (ptr, len, format, args) + 1;
1113 va_end (args);
1114 if (actual <= len)
1116 unuse (len - actual);
1117 break;
1119 unuse (len);
1120 len = actual;
1124 void
1125 bytes_out::print_time (const char *kind, const tm *time, const char *tz)
1127 printf ("%stime: %4u/%02u/%02u %02u:%02u:%02u %s",
1128 kind, time->tm_year + 1900, time->tm_mon + 1, time->tm_mday,
1129 time->tm_hour, time->tm_min, time->tm_sec, tz);
1132 /* Encapsulated Lazy Records Of Named Declarations.
1133 Header: Stunningly Elf32_Ehdr-like
1134 Sections: Sectional data
1135 [1-N) : User data sections
1136 N .strtab : strings, stunningly ELF STRTAB-like
1137 Index: Section table, stunningly ELF32_Shdr-like. */
1139 class elf {
1140 protected:
1141 /* Constants used within the format. */
1142 enum private_constants {
1143 /* File kind. */
1144 ET_NONE = 0,
1145 EM_NONE = 0,
1146 OSABI_NONE = 0,
1148 /* File format. */
1149 EV_CURRENT = 1,
1150 CLASS32 = 1,
1151 DATA2LSB = 1,
1152 DATA2MSB = 2,
1154 /* Section numbering. */
1155 SHN_UNDEF = 0,
1156 SHN_LORESERVE = 0xff00,
1157 SHN_XINDEX = 0xffff,
1159 /* Section types. */
1160 SHT_NONE = 0, /* No contents. */
1161 SHT_PROGBITS = 1, /* Random bytes. */
1162 SHT_STRTAB = 3, /* A string table. */
1164 /* Section flags. */
1165 SHF_NONE = 0x00, /* Nothing. */
1166 SHF_STRINGS = 0x20, /* NUL-Terminated strings. */
1168 /* I really hope we do not get CMI files larger than 4GB. */
1169 MY_CLASS = CLASS32,
1170 /* It is host endianness that is relevant. */
1171 MY_ENDIAN = DATA2LSB
1172 #ifdef WORDS_BIGENDIAN
1173 ^ DATA2LSB ^ DATA2MSB
1174 #endif
1177 public:
1178 /* Constants visible to users. */
1179 enum public_constants {
1180 /* Special error codes. Breaking layering a bit. */
1181 E_BAD_DATA = -1, /* Random unexpected data errors. */
1182 E_BAD_LAZY = -2, /* Badly ordered laziness. */
1183 E_BAD_IMPORT = -3 /* A nested import failed. */
1186 protected:
1187 /* File identification. On-disk representation. */
1188 struct ident {
1189 uint8_t magic[4]; /* 0x7f, 'E', 'L', 'F' */
1190 uint8_t klass; /* 4:CLASS32 */
1191 uint8_t data; /* 5:DATA2[LM]SB */
1192 uint8_t version; /* 6:EV_CURRENT */
1193 uint8_t osabi; /* 7:OSABI_NONE */
1194 uint8_t abiver; /* 8: 0 */
1195 uint8_t pad[7]; /* 9-15 */
1197 /* File header. On-disk representation. */
1198 struct header {
1199 struct ident ident;
1200 uint16_t type; /* ET_NONE */
1201 uint16_t machine; /* EM_NONE */
1202 uint32_t version; /* EV_CURRENT */
1203 uint32_t entry; /* 0 */
1204 uint32_t phoff; /* 0 */
1205 uint32_t shoff; /* Section Header Offset in file */
1206 uint32_t flags;
1207 uint16_t ehsize; /* ELROND Header SIZE -- sizeof (header) */
1208 uint16_t phentsize; /* 0 */
1209 uint16_t phnum; /* 0 */
1210 uint16_t shentsize; /* Section Header SIZE -- sizeof (section) */
1211 uint16_t shnum; /* Section Header NUM */
1212 uint16_t shstrndx; /* Section Header STRing iNDeX */
1214 /* File section. On-disk representation. */
1215 struct section {
1216 uint32_t name; /* String table offset. */
1217 uint32_t type; /* SHT_* */
1218 uint32_t flags; /* SHF_* */
1219 uint32_t addr; /* 0 */
1220 uint32_t offset; /* OFFSET in file */
1221 uint32_t size; /* SIZE of section */
1222 uint32_t link; /* 0 */
1223 uint32_t info; /* 0 */
1224 uint32_t addralign; /* 0 */
1225 uint32_t entsize; /* ENTry SIZE, usually 0 */
1228 protected:
1229 data hdr; /* The header. */
1230 data sectab; /* The section table. */
1231 data strtab; /* String table. */
1232 int fd; /* File descriptor we're reading or writing. */
1233 int err; /* Sticky error code. */
1235 public:
1236 /* Construct from STREAM. E is errno if STREAM NULL. */
1237 elf (int fd, int e)
1238 :hdr (), sectab (), strtab (), fd (fd), err (fd >= 0 ? 0 : e)
1240 ~elf ()
1242 gcc_checking_assert (fd < 0 && !hdr.buffer
1243 && !sectab.buffer && !strtab.buffer);
1246 public:
1247 /* Return the error, if we have an error. */
1248 int get_error () const
1250 return err;
1252 /* Set the error, unless it's already been set. */
1253 void set_error (int e = E_BAD_DATA)
1255 if (!err)
1256 err = e;
1258 /* Get an error string. */
1259 const char *get_error (const char *) const;
1261 public:
1262 /* Begin reading/writing file. Return false on error. */
1263 bool begin () const
1265 return !get_error ();
1267 /* Finish reading/writing file. Return false on error. */
1268 bool end ();
1271 /* Return error string. */
1273 const char *
1274 elf::get_error (const char *name) const
1276 if (!name)
1277 return "Unknown CMI mapping";
1279 switch (err)
1281 case 0:
1282 gcc_unreachable ();
1283 case E_BAD_DATA:
1284 return "Bad file data";
1285 case E_BAD_IMPORT:
1286 return "Bad import dependency";
1287 case E_BAD_LAZY:
1288 return "Bad lazy ordering";
1289 default:
1290 return xstrerror (err);
1294 /* Finish file, return true if there's an error. */
1296 bool
1297 elf::end ()
1299 /* Close the stream and free the section table. */
1300 if (fd >= 0 && close (fd))
1301 set_error (errno);
1302 fd = -1;
1304 return !get_error ();
1307 /* ELROND reader. */
1309 class elf_in : public elf {
1310 typedef elf parent;
1312 private:
1313 /* For freezing & defrosting. */
1314 #if !defined (HOST_LACKS_INODE_NUMBERS)
1315 dev_t device;
1316 ino_t inode;
1317 #endif
1319 public:
1320 elf_in (int fd, int e)
1321 :parent (fd, e)
1324 ~elf_in ()
1328 public:
1329 bool is_frozen () const
1331 return fd < 0 && hdr.pos;
1333 bool is_freezable () const
1335 return fd >= 0 && hdr.pos;
1337 void freeze ();
1338 bool defrost (const char *);
1340 /* If BYTES is in the mmapped area, allocate a new buffer for it. */
1341 void preserve (bytes_in &bytes ATTRIBUTE_UNUSED)
1343 #if MAPPED_READING
1344 if (hdr.buffer && bytes.buffer >= hdr.buffer
1345 && bytes.buffer < hdr.buffer + hdr.pos)
1347 char *buf = bytes.buffer;
1348 bytes.buffer = data::simple_memory.grow (NULL, bytes.size);
1349 memcpy (bytes.buffer, buf, bytes.size);
1351 #endif
1353 /* If BYTES is not in SELF's mmapped area, free it. SELF might be
1354 NULL. */
1355 static void release (elf_in *self ATTRIBUTE_UNUSED, bytes_in &bytes)
1357 #if MAPPED_READING
1358 if (!(self && self->hdr.buffer && bytes.buffer >= self->hdr.buffer
1359 && bytes.buffer < self->hdr.buffer + self->hdr.pos))
1360 #endif
1361 data::simple_memory.shrink (bytes.buffer);
1362 bytes.buffer = NULL;
1363 bytes.size = 0;
1366 public:
1367 static void grow (data &data, unsigned needed)
1369 gcc_checking_assert (!data.buffer);
1370 #if !MAPPED_READING
1371 data.buffer = XNEWVEC (char, needed);
1372 #endif
1373 data.size = needed;
1375 static void shrink (data &data)
1377 #if !MAPPED_READING
1378 XDELETEVEC (data.buffer);
1379 #endif
1380 data.buffer = NULL;
1381 data.size = 0;
1384 public:
1385 const section *get_section (unsigned s) const
1387 if (s * sizeof (section) < sectab.size)
1388 return reinterpret_cast<const section *>
1389 (&sectab.buffer[s * sizeof (section)]);
1390 else
1391 return NULL;
1393 unsigned get_section_limit () const
1395 return sectab.size / sizeof (section);
1398 protected:
1399 const char *read (data *, unsigned, unsigned);
1401 public:
1402 /* Read section by number. */
1403 bool read (data *d, const section *s)
1405 return s && read (d, s->offset, s->size);
1408 /* Find section by name. */
1409 unsigned find (const char *name);
1410 /* Find section by index. */
1411 const section *find (unsigned snum, unsigned type = SHT_PROGBITS);
1413 public:
1414 /* Release the string table, when we're done with it. */
1415 void release ()
1417 shrink (strtab);
1420 public:
1421 bool begin (location_t);
1422 bool end ()
1424 release ();
1425 #if MAPPED_READING
1426 if (hdr.buffer)
1427 munmap (hdr.buffer, hdr.pos);
1428 hdr.buffer = NULL;
1429 #endif
1430 shrink (sectab);
1432 return parent::end ();
1435 public:
1436 /* Return string name at OFFSET. Checks OFFSET range. Always
1437 returns non-NULL. We know offset 0 is an empty string. */
1438 const char *name (unsigned offset)
1440 return &strtab.buffer[offset < strtab.size ? offset : 0];
1444 /* ELROND writer. */
1446 class elf_out : public elf, public data::allocator {
1447 typedef elf parent;
1448 /* Desired section alignment on disk. */
1449 static const int SECTION_ALIGN = 16;
1451 private:
1452 ptr_int_hash_map identtab; /* Map of IDENTIFIERS to strtab offsets. */
1453 unsigned pos; /* Write position in file. */
1454 #if MAPPED_WRITING
1455 unsigned offset; /* Offset of the mapping. */
1456 unsigned extent; /* Length of mapping. */
1457 unsigned page_size; /* System page size. */
1458 #endif
1460 public:
1461 elf_out (int fd, int e)
1462 :parent (fd, e), identtab (500), pos (0)
1464 #if MAPPED_WRITING
1465 offset = extent = 0;
1466 page_size = sysconf (_SC_PAGE_SIZE);
1467 if (page_size < SECTION_ALIGN)
1468 /* Something really strange. */
1469 set_error (EINVAL);
1470 #endif
1472 ~elf_out ()
1474 data::simple_memory.shrink (hdr);
1475 data::simple_memory.shrink (sectab);
1476 data::simple_memory.shrink (strtab);
1479 #if MAPPED_WRITING
1480 private:
1481 void create_mapping (unsigned ext, bool extending = true);
1482 void remove_mapping ();
1483 #endif
1485 protected:
1486 using allocator::grow;
1487 char *grow (char *, unsigned needed) final override;
1488 #if MAPPED_WRITING
1489 using allocator::shrink;
1490 void shrink (char *) final override;
1491 #endif
1493 public:
1494 unsigned get_section_limit () const
1496 return sectab.pos / sizeof (section);
1499 protected:
1500 unsigned add (unsigned type, unsigned name = 0,
1501 unsigned off = 0, unsigned size = 0, unsigned flags = SHF_NONE);
1502 unsigned write (const data &);
1503 #if MAPPED_WRITING
1504 unsigned write (const bytes_out &);
1505 #endif
1507 public:
1508 /* IDENTIFIER to strtab offset. */
1509 unsigned name (tree ident);
1510 /* String literal to strtab offset. */
1511 unsigned name (const char *n);
1512 /* Qualified name of DECL to strtab offset. */
1513 unsigned qualified_name (tree decl, bool is_defn);
1515 private:
1516 unsigned strtab_write (const char *s, unsigned l);
1517 void strtab_write (tree decl, int);
1519 public:
1520 /* Add a section with contents or strings. */
1521 unsigned add (const bytes_out &, bool string_p, unsigned name);
1523 public:
1524 /* Begin and end writing. */
1525 bool begin ();
1526 bool end ();
1529 /* Begin reading section NAME (of type PROGBITS) from SOURCE.
1530 Data always checked for CRC. */
1532 bool
1533 bytes_in::begin (location_t loc, elf_in *source, const char *name)
1535 unsigned snum = source->find (name);
1537 return begin (loc, source, snum, name);
1540 /* Begin reading section numbered SNUM with NAME (may be NULL). */
1542 bool
1543 bytes_in::begin (location_t loc, elf_in *source, unsigned snum, const char *name)
1545 if (!source->read (this, source->find (snum))
1546 || !size || !check_crc ())
1548 source->set_error (elf::E_BAD_DATA);
1549 source->shrink (*this);
1550 if (name)
1551 error_at (loc, "section %qs is missing or corrupted", name);
1552 else
1553 error_at (loc, "section #%u is missing or corrupted", snum);
1554 return false;
1556 pos = 4;
1557 return true;
1560 /* Finish reading a section. */
1562 bool
1563 bytes_in::end (elf_in *src)
1565 if (more_p ())
1566 set_overrun ();
1567 if (overrun)
1568 src->set_error ();
1570 src->shrink (*this);
1572 return !overrun;
1575 /* Begin writing buffer. */
1577 void
1578 bytes_out::begin (bool need_crc)
1580 if (need_crc)
1581 pos = 4;
1582 memory->grow (*this, 0, false);
1585 /* Finish writing buffer. Stream out to SINK as named section NAME.
1586 Return section number or 0 on failure. If CRC_PTR is true, crc
1587 the data. Otherwise it is a string section. */
1589 unsigned
1590 bytes_out::end (elf_out *sink, unsigned name, unsigned *crc_ptr)
1592 lengths[3] += pos;
1593 spans[3]++;
1595 set_crc (crc_ptr);
1596 unsigned sec_num = sink->add (*this, !crc_ptr, name);
1597 memory->shrink (*this);
1599 return sec_num;
1602 /* Close and open the file, without destroying it. */
1604 void
1605 elf_in::freeze ()
1607 gcc_checking_assert (!is_frozen ());
1608 #if MAPPED_READING
1609 if (munmap (hdr.buffer, hdr.pos) < 0)
1610 set_error (errno);
1611 #endif
1612 if (close (fd) < 0)
1613 set_error (errno);
1614 fd = -1;
1617 bool
1618 elf_in::defrost (const char *name)
1620 gcc_checking_assert (is_frozen ());
1621 struct stat stat;
1623 fd = open (name, O_RDONLY | O_CLOEXEC | O_BINARY);
1624 if (fd < 0 || fstat (fd, &stat) < 0)
1625 set_error (errno);
1626 else
1628 bool ok = hdr.pos == unsigned (stat.st_size);
1629 #ifndef HOST_LACKS_INODE_NUMBERS
1630 if (device != stat.st_dev
1631 || inode != stat.st_ino)
1632 ok = false;
1633 #endif
1634 if (!ok)
1635 set_error (EMFILE);
1636 #if MAPPED_READING
1637 if (ok)
1639 char *mapping = reinterpret_cast<char *>
1640 (mmap (NULL, hdr.pos, PROT_READ, MAP_SHARED, fd, 0));
1641 if (mapping == MAP_FAILED)
1642 fail:
1643 set_error (errno);
1644 else
1646 if (madvise (mapping, hdr.pos, MADV_RANDOM))
1647 goto fail;
1649 /* These buffers are never NULL in this case. */
1650 strtab.buffer = mapping + strtab.pos;
1651 sectab.buffer = mapping + sectab.pos;
1652 hdr.buffer = mapping;
1655 #endif
1658 return !get_error ();
1661 /* Read at current position into BUFFER. Return true on success. */
1663 const char *
1664 elf_in::read (data *data, unsigned pos, unsigned length)
1666 #if MAPPED_READING
1667 if (pos + length > hdr.pos)
1669 set_error (EINVAL);
1670 return NULL;
1672 #else
1673 if (pos != ~0u && lseek (fd, pos, SEEK_SET) < 0)
1675 set_error (errno);
1676 return NULL;
1678 #endif
1679 grow (*data, length);
1680 #if MAPPED_READING
1681 data->buffer = hdr.buffer + pos;
1682 #else
1683 if (::read (fd, data->buffer, data->size) != ssize_t (length))
1685 set_error (errno);
1686 shrink (*data);
1687 return NULL;
1689 #endif
1691 return data->buffer;
1694 /* Read section SNUM of TYPE. Return section pointer or NULL on error. */
1696 const elf::section *
1697 elf_in::find (unsigned snum, unsigned type)
1699 const section *sec = get_section (snum);
1700 if (!snum || !sec || sec->type != type)
1701 return NULL;
1702 return sec;
1705 /* Find a section NAME and TYPE. Return section number, or zero on
1706 failure. */
1708 unsigned
1709 elf_in::find (const char *sname)
1711 for (unsigned pos = sectab.size; pos -= sizeof (section); )
1713 const section *sec
1714 = reinterpret_cast<const section *> (&sectab.buffer[pos]);
1716 if (0 == strcmp (sname, name (sec->name)))
1717 return pos / sizeof (section);
1720 return 0;
1723 /* Begin reading file. Verify header. Pull in section and string
1724 tables. Return true on success. */
1726 bool
1727 elf_in::begin (location_t loc)
1729 if (!parent::begin ())
1730 return false;
1732 struct stat stat;
1733 unsigned size = 0;
1734 if (!fstat (fd, &stat))
1736 #if !defined (HOST_LACKS_INODE_NUMBERS)
1737 device = stat.st_dev;
1738 inode = stat.st_ino;
1739 #endif
1740 /* Never generate files > 4GB, check we've not been given one. */
1741 if (stat.st_size == unsigned (stat.st_size))
1742 size = unsigned (stat.st_size);
1745 #if MAPPED_READING
1746 /* MAP_SHARED so that the file is backing store. If someone else
1747 concurrently writes it, they're wrong. */
1748 void *mapping = mmap (NULL, size, PROT_READ, MAP_SHARED, fd, 0);
1749 if (mapping == MAP_FAILED)
1751 fail:
1752 set_error (errno);
1753 return false;
1755 /* We'll be hopping over this randomly. Some systems declare the
1756 first parm as char *, and other declare it as void *. */
1757 if (madvise (reinterpret_cast <char *> (mapping), size, MADV_RANDOM))
1758 goto fail;
1760 hdr.buffer = (char *)mapping;
1761 #else
1762 read (&hdr, 0, sizeof (header));
1763 #endif
1764 hdr.pos = size; /* Record size of the file. */
1766 const header *h = reinterpret_cast<const header *> (hdr.buffer);
1767 if (!h)
1768 return false;
1770 if (h->ident.magic[0] != 0x7f
1771 || h->ident.magic[1] != 'E'
1772 || h->ident.magic[2] != 'L'
1773 || h->ident.magic[3] != 'F')
1775 error_at (loc, "not Encapsulated Lazy Records of Named Declarations");
1776 failed:
1777 shrink (hdr);
1778 return false;
1781 /* We expect a particular format -- the ELF is not intended to be
1782 distributable. */
1783 if (h->ident.klass != MY_CLASS
1784 || h->ident.data != MY_ENDIAN
1785 || h->ident.version != EV_CURRENT
1786 || h->type != ET_NONE
1787 || h->machine != EM_NONE
1788 || h->ident.osabi != OSABI_NONE)
1790 error_at (loc, "unexpected encapsulation format or type");
1791 goto failed;
1794 int e = -1;
1795 if (!h->shoff || h->shentsize != sizeof (section))
1797 malformed:
1798 set_error (e);
1799 error_at (loc, "encapsulation is malformed");
1800 goto failed;
1803 unsigned strndx = h->shstrndx;
1804 unsigned shnum = h->shnum;
1805 if (shnum == SHN_XINDEX)
1807 if (!read (&sectab, h->shoff, sizeof (section)))
1809 section_table_fail:
1810 e = errno;
1811 goto malformed;
1813 shnum = get_section (0)->size;
1814 /* Freeing does mean we'll re-read it in the case we're not
1815 mapping, but this is going to be rare. */
1816 shrink (sectab);
1819 if (!shnum)
1820 goto malformed;
1822 if (!read (&sectab, h->shoff, shnum * sizeof (section)))
1823 goto section_table_fail;
1825 if (strndx == SHN_XINDEX)
1826 strndx = get_section (0)->link;
1828 if (!read (&strtab, find (strndx, SHT_STRTAB)))
1829 goto malformed;
1831 /* The string table should be at least one byte, with NUL chars
1832 at either end. */
1833 if (!(strtab.size && !strtab.buffer[0]
1834 && !strtab.buffer[strtab.size - 1]))
1835 goto malformed;
1837 #if MAPPED_READING
1838 /* Record the offsets of the section and string tables. */
1839 sectab.pos = h->shoff;
1840 strtab.pos = shnum * sizeof (section);
1841 #else
1842 shrink (hdr);
1843 #endif
1845 return true;
1848 /* Create a new mapping. */
1850 #if MAPPED_WRITING
1851 void
1852 elf_out::create_mapping (unsigned ext, bool extending)
1854 #ifndef HAVE_POSIX_FALLOCATE
1855 #define posix_fallocate(fd,off,len) ftruncate (fd, off + len)
1856 #endif
1857 void *mapping = MAP_FAILED;
1858 if (extending && ext < 1024 * 1024)
1860 if (!posix_fallocate (fd, offset, ext * 2))
1861 mapping = mmap (NULL, ext * 2, PROT_READ | PROT_WRITE,
1862 MAP_SHARED, fd, offset);
1863 if (mapping != MAP_FAILED)
1864 ext *= 2;
1866 if (mapping == MAP_FAILED)
1868 if (!extending || !posix_fallocate (fd, offset, ext))
1869 mapping = mmap (NULL, ext, PROT_READ | PROT_WRITE,
1870 MAP_SHARED, fd, offset);
1871 if (mapping == MAP_FAILED)
1873 set_error (errno);
1874 mapping = NULL;
1875 ext = 0;
1878 #undef posix_fallocate
1879 hdr.buffer = (char *)mapping;
1880 extent = ext;
1882 #endif
1884 /* Flush out the current mapping. */
1886 #if MAPPED_WRITING
1887 void
1888 elf_out::remove_mapping ()
1890 if (hdr.buffer)
1892 /* MS_ASYNC dtrt with the removed mapping, including a
1893 subsequent overlapping remap. */
1894 if (msync (hdr.buffer, extent, MS_ASYNC)
1895 || munmap (hdr.buffer, extent))
1896 /* We're somewhat screwed at this point. */
1897 set_error (errno);
1900 hdr.buffer = NULL;
1902 #endif
1904 /* Grow a mapping of PTR to be NEEDED bytes long. This gets
1905 interesting if the new size grows the EXTENT. */
1907 char *
1908 elf_out::grow (char *data, unsigned needed)
1910 if (!data)
1912 /* First allocation, check we're aligned. */
1913 gcc_checking_assert (!(pos & (SECTION_ALIGN - 1)));
1914 #if MAPPED_WRITING
1915 data = hdr.buffer + (pos - offset);
1916 #endif
1919 #if MAPPED_WRITING
1920 unsigned off = data - hdr.buffer;
1921 if (off + needed > extent)
1923 /* We need to grow the mapping. */
1924 unsigned lwm = off & ~(page_size - 1);
1925 unsigned hwm = (off + needed + page_size - 1) & ~(page_size - 1);
1927 gcc_checking_assert (hwm > extent);
1929 remove_mapping ();
1931 offset += lwm;
1932 create_mapping (extent < hwm - lwm ? hwm - lwm : extent);
1934 data = hdr.buffer + (off - lwm);
1936 #else
1937 data = allocator::grow (data, needed);
1938 #endif
1940 return data;
1943 #if MAPPED_WRITING
1944 /* Shrinking is a NOP. */
1945 void
1946 elf_out::shrink (char *)
1949 #endif
1951 /* Write S of length L to the strtab buffer. L must include the ending
1952 NUL, if that's what you want. */
1954 unsigned
1955 elf_out::strtab_write (const char *s, unsigned l)
1957 if (strtab.pos + l > strtab.size)
1958 data::simple_memory.grow (strtab, strtab.pos + l, false);
1959 memcpy (strtab.buffer + strtab.pos, s, l);
1960 unsigned res = strtab.pos;
1961 strtab.pos += l;
1962 return res;
1965 /* Write qualified name of decl. INNER >0 if this is a definition, <0
1966 if this is a qualifier of an outer name. */
1968 void
1969 elf_out::strtab_write (tree decl, int inner)
1971 tree ctx = CP_DECL_CONTEXT (decl);
1972 if (TYPE_P (ctx))
1973 ctx = TYPE_NAME (ctx);
1974 if (ctx != global_namespace)
1975 strtab_write (ctx, -1);
1977 tree name = DECL_NAME (decl);
1978 if (!name)
1979 name = DECL_ASSEMBLER_NAME_RAW (decl);
1980 strtab_write (IDENTIFIER_POINTER (name), IDENTIFIER_LENGTH (name));
1982 if (inner)
1983 strtab_write (&"::{}"[inner+1], 2);
1986 /* Map IDENTIFIER IDENT to strtab offset. Inserts into strtab if not
1987 already there. */
1989 unsigned
1990 elf_out::name (tree ident)
1992 unsigned res = 0;
1993 if (ident)
1995 bool existed;
1996 int *slot = &identtab.get_or_insert (ident, &existed);
1997 if (!existed)
1998 *slot = strtab_write (IDENTIFIER_POINTER (ident),
1999 IDENTIFIER_LENGTH (ident) + 1);
2000 res = *slot;
2002 return res;
2005 /* Map LITERAL to strtab offset. Does not detect duplicates and
2006 expects LITERAL to remain live until strtab is written out. */
2008 unsigned
2009 elf_out::name (const char *literal)
2011 return strtab_write (literal, strlen (literal) + 1);
2014 /* Map a DECL's qualified name to strtab offset. Does not detect
2015 duplicates. */
2017 unsigned
2018 elf_out::qualified_name (tree decl, bool is_defn)
2020 gcc_checking_assert (DECL_P (decl) && decl != global_namespace);
2021 unsigned result = strtab.pos;
2023 strtab_write (decl, is_defn);
2024 strtab_write ("", 1);
2026 return result;
2029 /* Add section to file. Return section number. TYPE & NAME identify
2030 the section. OFF and SIZE identify the file location of its
2031 data. FLAGS contains additional info. */
2033 unsigned
2034 elf_out::add (unsigned type, unsigned name, unsigned off, unsigned size,
2035 unsigned flags)
2037 gcc_checking_assert (!(off & (SECTION_ALIGN - 1)));
2038 if (sectab.pos + sizeof (section) > sectab.size)
2039 data::simple_memory.grow (sectab, sectab.pos + sizeof (section), false);
2040 section *sec = reinterpret_cast<section *> (sectab.buffer + sectab.pos);
2041 memset (sec, 0, sizeof (section));
2042 sec->type = type;
2043 sec->flags = flags;
2044 sec->name = name;
2045 sec->offset = off;
2046 sec->size = size;
2047 if (flags & SHF_STRINGS)
2048 sec->entsize = 1;
2050 unsigned res = sectab.pos;
2051 sectab.pos += sizeof (section);
2052 return res / sizeof (section);
2055 /* Pad to the next alignment boundary, then write BUFFER to disk.
2056 Return the position of the start of the write, or zero on failure. */
2058 unsigned
2059 elf_out::write (const data &buffer)
2061 #if MAPPED_WRITING
2062 /* HDR is always mapped. */
2063 if (&buffer != &hdr)
2065 bytes_out out (this);
2066 grow (out, buffer.pos, true);
2067 if (out.buffer)
2068 memcpy (out.buffer, buffer.buffer, buffer.pos);
2069 shrink (out);
2071 else
2072 /* We should have been aligned during the first allocation. */
2073 gcc_checking_assert (!(pos & (SECTION_ALIGN - 1)));
2074 #else
2075 if (::write (fd, buffer.buffer, buffer.pos) != ssize_t (buffer.pos))
2077 set_error (errno);
2078 return 0;
2080 #endif
2081 unsigned res = pos;
2082 pos += buffer.pos;
2084 if (unsigned padding = -pos & (SECTION_ALIGN - 1))
2086 #if !MAPPED_WRITING
2087 /* Align the section on disk, should help the necessary copies.
2088 fseeking to extend is non-portable. */
2089 static char zero[SECTION_ALIGN];
2090 if (::write (fd, &zero, padding) != ssize_t (padding))
2091 set_error (errno);
2092 #endif
2093 pos += padding;
2095 return res;
2098 /* Write a streaming buffer. It must be using us as an allocator. */
2100 #if MAPPED_WRITING
2101 unsigned
2102 elf_out::write (const bytes_out &buf)
2104 gcc_checking_assert (buf.memory == this);
2105 /* A directly mapped buffer. */
2106 gcc_checking_assert (buf.buffer - hdr.buffer >= 0
2107 && buf.buffer - hdr.buffer + buf.size <= extent);
2108 unsigned res = pos;
2109 pos += buf.pos;
2111 /* Align up. We're not going to advance into the next page. */
2112 pos += -pos & (SECTION_ALIGN - 1);
2114 return res;
2116 #endif
2118 /* Write data and add section. STRING_P is true for a string
2119 section, false for PROGBITS. NAME identifies the section (0 is the
2120 empty name). DATA is the contents. Return section number or 0 on
2121 failure (0 is the undef section). */
2123 unsigned
2124 elf_out::add (const bytes_out &data, bool string_p, unsigned name)
2126 unsigned off = write (data);
2128 return add (string_p ? SHT_STRTAB : SHT_PROGBITS, name,
2129 off, data.pos, string_p ? SHF_STRINGS : SHF_NONE);
2132 /* Begin writing the file. Initialize the section table and write an
2133 empty header. Return false on failure. */
2135 bool
2136 elf_out::begin ()
2138 if (!parent::begin ())
2139 return false;
2141 /* Let the allocators pick a default. */
2142 data::simple_memory.grow (strtab, 0, false);
2143 data::simple_memory.grow (sectab, 0, false);
2145 /* The string table starts with an empty string. */
2146 name ("");
2148 /* Create the UNDEF section. */
2149 add (SHT_NONE);
2151 #if MAPPED_WRITING
2152 /* Start a mapping. */
2153 create_mapping (EXPERIMENT (page_size,
2154 (32767 + page_size) & ~(page_size - 1)));
2155 if (!hdr.buffer)
2156 return false;
2157 #endif
2159 /* Write an empty header. */
2160 grow (hdr, sizeof (header), true);
2161 header *h = reinterpret_cast<header *> (hdr.buffer);
2162 memset (h, 0, sizeof (header));
2163 hdr.pos = hdr.size;
2164 write (hdr);
2165 return !get_error ();
2168 /* Finish writing the file. Write out the string & section tables.
2169 Fill in the header. Return true on error. */
2171 bool
2172 elf_out::end ()
2174 if (fd >= 0)
2176 /* Write the string table. */
2177 unsigned strnam = name (".strtab");
2178 unsigned stroff = write (strtab);
2179 unsigned strndx = add (SHT_STRTAB, strnam, stroff, strtab.pos,
2180 SHF_STRINGS);
2182 /* Store escape values in section[0]. */
2183 if (strndx >= SHN_LORESERVE)
2185 reinterpret_cast<section *> (sectab.buffer)->link = strndx;
2186 strndx = SHN_XINDEX;
2188 unsigned shnum = sectab.pos / sizeof (section);
2189 if (shnum >= SHN_LORESERVE)
2191 reinterpret_cast<section *> (sectab.buffer)->size = shnum;
2192 shnum = SHN_XINDEX;
2195 unsigned shoff = write (sectab);
2197 #if MAPPED_WRITING
2198 if (offset)
2200 remove_mapping ();
2201 offset = 0;
2202 create_mapping ((sizeof (header) + page_size - 1) & ~(page_size - 1),
2203 false);
2205 unsigned length = pos;
2206 #else
2207 if (lseek (fd, 0, SEEK_SET) < 0)
2208 set_error (errno);
2209 #endif
2210 /* Write header. */
2211 if (!get_error ())
2213 /* Write the correct header now. */
2214 header *h = reinterpret_cast<header *> (hdr.buffer);
2215 h->ident.magic[0] = 0x7f;
2216 h->ident.magic[1] = 'E'; /* Elrond */
2217 h->ident.magic[2] = 'L'; /* is an */
2218 h->ident.magic[3] = 'F'; /* elf. */
2219 h->ident.klass = MY_CLASS;
2220 h->ident.data = MY_ENDIAN;
2221 h->ident.version = EV_CURRENT;
2222 h->ident.osabi = OSABI_NONE;
2223 h->type = ET_NONE;
2224 h->machine = EM_NONE;
2225 h->version = EV_CURRENT;
2226 h->shoff = shoff;
2227 h->ehsize = sizeof (header);
2228 h->shentsize = sizeof (section);
2229 h->shnum = shnum;
2230 h->shstrndx = strndx;
2232 pos = 0;
2233 write (hdr);
2236 #if MAPPED_WRITING
2237 remove_mapping ();
2238 if (ftruncate (fd, length))
2239 set_error (errno);
2240 #endif
2243 data::simple_memory.shrink (sectab);
2244 data::simple_memory.shrink (strtab);
2246 return parent::end ();
2249 /********************************************************************/
2251 /* A dependency set. This is used during stream out to determine the
2252 connectivity of the graph. Every namespace-scope declaration that
2253 needs writing has a depset. The depset is filled with the (depsets
2254 of) declarations within this module that it references. For a
2255 declaration that'll generally be named types. For definitions
2256 it'll also be declarations in the body.
2258 From that we can convert the graph to a DAG, via determining the
2259 Strongly Connected Clusters. Each cluster is streamed
2260 independently, and thus we achieve lazy loading.
2262 Other decls that get a depset are namespaces themselves and
2263 unnameable declarations. */
2265 class depset {
2266 private:
2267 tree entity; /* Entity, or containing namespace. */
2268 uintptr_t discriminator; /* Flags or identifier. */
2270 public:
2271 /* The kinds of entity the depset could describe. The ordering is
2272 significant, see entity_kind_name. */
2273 enum entity_kind
2275 EK_DECL, /* A decl. */
2276 EK_SPECIALIZATION, /* A specialization. */
2277 EK_PARTIAL, /* A partial specialization. */
2278 EK_USING, /* A using declaration (at namespace scope). */
2279 EK_NAMESPACE, /* A namespace. */
2280 EK_REDIRECT, /* Redirect to a template_decl. */
2281 EK_EXPLICIT_HWM,
2282 EK_BINDING = EK_EXPLICIT_HWM, /* Implicitly encoded. */
2283 EK_FOR_BINDING, /* A decl being inserted for a binding. */
2284 EK_INNER_DECL, /* A decl defined outside of its imported
2285 context. */
2286 EK_DIRECT_HWM = EK_PARTIAL + 1,
2288 EK_BITS = 3 /* Only need to encode below EK_EXPLICIT_HWM. */
2291 private:
2292 /* Placement of bit fields in discriminator. */
2293 enum disc_bits
2295 DB_ZERO_BIT, /* Set to disambiguate identifier from flags */
2296 DB_SPECIAL_BIT, /* First dep slot is special. */
2297 DB_KIND_BIT, /* Kind of the entity. */
2298 DB_KIND_BITS = EK_BITS,
2299 DB_DEFN_BIT = DB_KIND_BIT + DB_KIND_BITS,
2300 DB_IS_MEMBER_BIT, /* Is an out-of-class member. */
2301 DB_IS_INTERNAL_BIT, /* It is an (erroneous)
2302 internal-linkage entity. */
2303 DB_REFS_INTERNAL_BIT, /* Refers to an internal-linkage
2304 entity. */
2305 DB_IMPORTED_BIT, /* An imported entity. */
2306 DB_UNREACHED_BIT, /* A yet-to-be reached entity. */
2307 DB_HIDDEN_BIT, /* A hidden binding. */
2308 /* The following bits are not independent, but enumerating them is
2309 awkward. */
2310 DB_ALIAS_TMPL_INST_BIT, /* An alias template instantiation. */
2311 DB_ALIAS_SPEC_BIT, /* Specialization of an alias template
2312 (in both spec tables). */
2313 DB_TYPE_SPEC_BIT, /* Specialization in the type table.
2315 DB_FRIEND_SPEC_BIT, /* An instantiated template friend. */
2318 public:
2319 /* The first slot is special for EK_SPECIALIZATIONS it is a
2320 spec_entry pointer. It is not relevant for the SCC
2321 determination. */
2322 vec<depset *> deps; /* Depsets we reference. */
2324 public:
2325 unsigned cluster; /* Strongly connected cluster, later entity number */
2326 unsigned section; /* Section written to. */
2327 /* During SCC construction, section is lowlink, until the depset is
2328 removed from the stack. See Tarjan algorithm for details. */
2330 private:
2331 /* Construction via factories. Destruction via hash traits. */
2332 depset (tree entity);
2333 ~depset ();
2335 public:
2336 static depset *make_binding (tree, tree);
2337 static depset *make_entity (tree, entity_kind, bool = false);
2338 /* Late setting a binding name -- /then/ insert into hash! */
2339 inline void set_binding_name (tree name)
2341 gcc_checking_assert (!get_name ());
2342 discriminator = reinterpret_cast<uintptr_t> (name);
2345 private:
2346 template<unsigned I> void set_flag_bit ()
2348 gcc_checking_assert (I < 2 || !is_binding ());
2349 discriminator |= 1u << I;
2351 template<unsigned I> void clear_flag_bit ()
2353 gcc_checking_assert (I < 2 || !is_binding ());
2354 discriminator &= ~(1u << I);
2356 template<unsigned I> bool get_flag_bit () const
2358 gcc_checking_assert (I < 2 || !is_binding ());
2359 return bool ((discriminator >> I) & 1);
2362 public:
2363 bool is_binding () const
2365 return !get_flag_bit<DB_ZERO_BIT> ();
2367 entity_kind get_entity_kind () const
2369 if (is_binding ())
2370 return EK_BINDING;
2371 return entity_kind ((discriminator >> DB_KIND_BIT) & ((1u << EK_BITS) - 1));
2373 const char *entity_kind_name () const;
2375 public:
2376 bool has_defn () const
2378 return get_flag_bit<DB_DEFN_BIT> ();
2381 public:
2382 /* This class-member is defined here, but the class was imported. */
2383 bool is_member () const
2385 gcc_checking_assert (get_entity_kind () == EK_DECL);
2386 return get_flag_bit<DB_IS_MEMBER_BIT> ();
2388 public:
2389 bool is_internal () const
2391 return get_flag_bit<DB_IS_INTERNAL_BIT> ();
2393 bool refs_internal () const
2395 return get_flag_bit<DB_REFS_INTERNAL_BIT> ();
2397 bool is_import () const
2399 return get_flag_bit<DB_IMPORTED_BIT> ();
2401 bool is_unreached () const
2403 return get_flag_bit<DB_UNREACHED_BIT> ();
2405 bool is_alias_tmpl_inst () const
2407 return get_flag_bit<DB_ALIAS_TMPL_INST_BIT> ();
2409 bool is_alias () const
2411 return get_flag_bit<DB_ALIAS_SPEC_BIT> ();
2413 bool is_hidden () const
2415 return get_flag_bit<DB_HIDDEN_BIT> ();
2417 bool is_type_spec () const
2419 return get_flag_bit<DB_TYPE_SPEC_BIT> ();
2421 bool is_friend_spec () const
2423 return get_flag_bit<DB_FRIEND_SPEC_BIT> ();
2426 public:
2427 /* We set these bit outside of depset. */
2428 void set_hidden_binding ()
2430 set_flag_bit<DB_HIDDEN_BIT> ();
2432 void clear_hidden_binding ()
2434 clear_flag_bit<DB_HIDDEN_BIT> ();
2437 public:
2438 bool is_special () const
2440 return get_flag_bit<DB_SPECIAL_BIT> ();
2442 void set_special ()
2444 set_flag_bit<DB_SPECIAL_BIT> ();
2447 public:
2448 tree get_entity () const
2450 return entity;
2452 tree get_name () const
2454 gcc_checking_assert (is_binding ());
2455 return reinterpret_cast <tree> (discriminator);
2458 public:
2459 /* Traits for a hash table of pointers to bindings. */
2460 struct traits {
2461 /* Each entry is a pointer to a depset. */
2462 typedef depset *value_type;
2463 /* We lookup by container:maybe-identifier pair. */
2464 typedef std::pair<tree,tree> compare_type;
2466 static const bool empty_zero_p = true;
2468 /* hash and equality for compare_type. */
2469 inline static hashval_t hash (const compare_type &p)
2471 hashval_t h = pointer_hash<tree_node>::hash (p.first);
2472 if (p.second)
2474 hashval_t nh = IDENTIFIER_HASH_VALUE (p.second);
2475 h = iterative_hash_hashval_t (h, nh);
2477 return h;
2479 inline static bool equal (const value_type b, const compare_type &p)
2481 if (b->entity != p.first)
2482 return false;
2484 if (p.second)
2485 return b->discriminator == reinterpret_cast<uintptr_t> (p.second);
2486 else
2487 return !b->is_binding ();
2490 /* (re)hasher for a binding itself. */
2491 inline static hashval_t hash (const value_type b)
2493 hashval_t h = pointer_hash<tree_node>::hash (b->entity);
2494 if (b->is_binding ())
2496 hashval_t nh = IDENTIFIER_HASH_VALUE (b->get_name ());
2497 h = iterative_hash_hashval_t (h, nh);
2499 return h;
2502 /* Empty via NULL. */
2503 static inline void mark_empty (value_type &p) {p = NULL;}
2504 static inline bool is_empty (value_type p) {return !p;}
2506 /* Nothing is deletable. Everything is insertable. */
2507 static bool is_deleted (value_type) { return false; }
2508 static void mark_deleted (value_type) { gcc_unreachable (); }
2510 /* We own the entities in the hash table. */
2511 static void remove (value_type p)
2513 delete (p);
2517 public:
2518 class hash : public hash_table<traits> {
2519 typedef traits::compare_type key_t;
2520 typedef hash_table<traits> parent;
2522 public:
2523 vec<depset *> worklist; /* Worklist of decls to walk. */
2524 hash *chain; /* Original table. */
2525 depset *current; /* Current depset being depended. */
2526 unsigned section; /* When writing out, the section. */
2527 bool sneakoscope; /* Detecting dark magic (of a voldemort). */
2528 bool reached_unreached; /* We reached an unreached entity. */
2530 public:
2531 hash (size_t size, hash *c = NULL)
2532 : parent (size), chain (c), current (NULL), section (0),
2533 sneakoscope (false), reached_unreached (false)
2535 worklist.create (size);
2537 ~hash ()
2539 worklist.release ();
2542 public:
2543 bool is_key_order () const
2545 return chain != NULL;
2548 private:
2549 depset **entity_slot (tree entity, bool = true);
2550 depset **binding_slot (tree ctx, tree name, bool = true);
2551 depset *maybe_add_declaration (tree decl);
2553 public:
2554 depset *find_dependency (tree entity);
2555 depset *find_binding (tree ctx, tree name);
2556 depset *make_dependency (tree decl, entity_kind);
2557 void add_dependency (depset *);
2559 public:
2560 void add_mergeable (depset *);
2561 depset *add_dependency (tree decl, entity_kind);
2562 void add_namespace_context (depset *, tree ns);
2564 private:
2565 static bool add_binding_entity (tree, WMB_Flags, void *);
2567 public:
2568 bool add_namespace_entities (tree ns, bitmap partitions);
2569 void add_specializations (bool decl_p);
2570 void add_partial_entities (vec<tree, va_gc> *);
2571 void add_class_entities (vec<tree, va_gc> *);
2573 public:
2574 void find_dependencies (module_state *);
2575 bool finalize_dependencies ();
2576 vec<depset *> connect ();
2579 public:
2580 struct tarjan {
2581 vec<depset *> result;
2582 vec<depset *> stack;
2583 unsigned index;
2585 tarjan (unsigned size)
2586 : index (0)
2588 result.create (size);
2589 stack.create (50);
2591 ~tarjan ()
2593 gcc_assert (!stack.length ());
2594 stack.release ();
2597 public:
2598 void connect (depset *);
2602 inline
2603 depset::depset (tree entity)
2604 :entity (entity), discriminator (0), cluster (0), section (0)
2606 deps.create (0);
2609 inline
2610 depset::~depset ()
2612 deps.release ();
2615 const char *
2616 depset::entity_kind_name () const
2618 /* Same order as entity_kind. */
2619 static const char *const names[] =
2620 {"decl", "specialization", "partial", "using",
2621 "namespace", "redirect", "binding"};
2622 entity_kind kind = get_entity_kind ();
2623 gcc_checking_assert (kind < ARRAY_SIZE (names));
2624 return names[kind];
2627 /* Create a depset for a namespace binding NS::NAME. */
2629 depset *depset::make_binding (tree ns, tree name)
2631 depset *binding = new depset (ns);
2633 binding->discriminator = reinterpret_cast <uintptr_t> (name);
2635 return binding;
2638 depset *depset::make_entity (tree entity, entity_kind ek, bool is_defn)
2640 depset *r = new depset (entity);
2642 r->discriminator = ((1 << DB_ZERO_BIT)
2643 | (ek << DB_KIND_BIT)
2644 | is_defn << DB_DEFN_BIT);
2646 return r;
2649 class pending_key
2651 public:
2652 tree ns;
2653 tree id;
2656 template<>
2657 struct default_hash_traits<pending_key>
2659 using value_type = pending_key;
2661 static const bool empty_zero_p = false;
2662 static hashval_t hash (const value_type &k)
2664 hashval_t h = IDENTIFIER_HASH_VALUE (k.id);
2665 h = iterative_hash_hashval_t (DECL_UID (k.ns), h);
2667 return h;
2669 static bool equal (const value_type &k, const value_type &l)
2671 return k.ns == l.ns && k.id == l.id;
2673 static void mark_empty (value_type &k)
2675 k.ns = k.id = NULL_TREE;
2677 static void mark_deleted (value_type &k)
2679 k.ns = NULL_TREE;
2680 gcc_checking_assert (k.id);
2682 static bool is_empty (const value_type &k)
2684 return k.ns == NULL_TREE && k.id == NULL_TREE;
2686 static bool is_deleted (const value_type &k)
2688 return k.ns == NULL_TREE && k.id != NULL_TREE;
2690 static void remove (value_type &)
2695 typedef hash_map<pending_key, auto_vec<unsigned>> pending_map_t;
2697 /* Not-loaded entities that are keyed to a namespace-scope
2698 identifier. See module_state::write_pendings for details. */
2699 pending_map_t *pending_table;
2701 /* Decls that need some post processing once a batch of lazy loads has
2702 completed. */
2703 vec<tree, va_heap, vl_embed> *post_load_decls;
2705 /* Some entities are keyed to another entitity for ODR purposes.
2706 For example, at namespace scope, 'inline auto var = []{};', that
2707 lambda is keyed to 'var', and follows its ODRness. */
2708 typedef hash_map<tree, auto_vec<tree>> keyed_map_t;
2709 static keyed_map_t *keyed_table;
2711 /********************************************************************/
2712 /* Tree streaming. The tree streaming is very specific to the tree
2713 structures themselves. A tag indicates the kind of tree being
2714 streamed. -ve tags indicate backreferences to already-streamed
2715 trees. Backreferences are auto-numbered. */
2717 /* Tree tags. */
2718 enum tree_tag {
2719 tt_null, /* NULL_TREE. */
2720 tt_fixed, /* Fixed vector index. */
2722 tt_node, /* By-value node. */
2723 tt_decl, /* By-value mergeable decl. */
2724 tt_tpl_parm, /* Template parm. */
2726 /* The ordering of the following 4 is relied upon in
2727 trees_out::tree_node. */
2728 tt_id, /* Identifier node. */
2729 tt_conv_id, /* Conversion operator name. */
2730 tt_anon_id, /* Anonymous name. */
2731 tt_lambda_id, /* Lambda name. */
2733 tt_typedef_type, /* A (possibly implicit) typedefed type. */
2734 tt_derived_type, /* A type derived from another type. */
2735 tt_variant_type, /* A variant of another type. */
2737 tt_tinfo_var, /* Typeinfo object. */
2738 tt_tinfo_typedef, /* Typeinfo typedef. */
2739 tt_ptrmem_type, /* Pointer to member type. */
2740 tt_nttp_var, /* NTTP_OBJECT VAR_DECL. */
2742 tt_parm, /* Function parameter or result. */
2743 tt_enum_value, /* An enum value. */
2744 tt_enum_decl, /* An enum decl. */
2745 tt_data_member, /* Data member/using-decl. */
2747 tt_binfo, /* A BINFO. */
2748 tt_vtable, /* A vtable. */
2749 tt_thunk, /* A thunk. */
2750 tt_clone_ref,
2752 tt_entity, /* A extra-cluster entity. */
2754 tt_template, /* The TEMPLATE_RESULT of a template. */
2757 enum walk_kind {
2758 WK_none, /* No walk to do (a back- or fixed-ref happened). */
2759 WK_normal, /* Normal walk (by-name if possible). */
2761 WK_value, /* By-value walk. */
2764 enum merge_kind
2766 MK_unique, /* Known unique. */
2767 MK_named, /* Found by CTX, NAME + maybe_arg types etc. */
2768 MK_field, /* Found by CTX and index on TYPE_FIELDS */
2769 MK_vtable, /* Found by CTX and index on TYPE_VTABLES */
2770 MK_as_base, /* Found by CTX. */
2772 MK_partial,
2774 MK_enum, /* Found by CTX, & 1stMemberNAME. */
2775 MK_keyed, /* Found by key & index. */
2777 MK_friend_spec, /* Like named, but has a tmpl & args too. */
2778 MK_local_friend, /* Found by CTX, index. */
2780 MK_indirect_lwm = MK_enum,
2782 /* Template specialization kinds below. These are all found via
2783 primary template and specialization args. */
2784 MK_template_mask = 0x10, /* A template specialization. */
2786 MK_tmpl_decl_mask = 0x4, /* In decl table. */
2787 MK_tmpl_alias_mask = 0x2, /* Also in type table */
2789 MK_tmpl_tmpl_mask = 0x1, /* We want TEMPLATE_DECL. */
2791 MK_type_spec = MK_template_mask,
2792 MK_decl_spec = MK_template_mask | MK_tmpl_decl_mask,
2793 MK_alias_spec = MK_decl_spec | MK_tmpl_alias_mask,
2795 MK_hwm = 0x20
2797 /* This is more than a debugging array. NULLs are used to determine
2798 an invalid merge_kind number. */
2799 static char const *const merge_kind_name[MK_hwm] =
2801 "unique", "named", "field", "vtable", /* 0...3 */
2802 "asbase", "partial", "enum", "attached", /* 4...7 */
2804 "friend spec", "local friend", NULL, NULL, /* 8...11 */
2805 NULL, NULL, NULL, NULL,
2807 "type spec", "type tmpl spec", /* 16,17 type (template). */
2808 NULL, NULL,
2810 "decl spec", "decl tmpl spec", /* 20,21 decl (template). */
2811 "alias spec", "alias tmpl spec", /* 22,23 alias (template). */
2812 NULL, NULL, NULL, NULL,
2813 NULL, NULL, NULL, NULL,
2816 /* Mergeable entity location data. */
2817 struct merge_key {
2818 cp_ref_qualifier ref_q : 2;
2819 unsigned index;
2821 tree ret; /* Return type, if appropriate. */
2822 tree args; /* Arg types, if appropriate. */
2824 tree constraints; /* Constraints. */
2826 merge_key ()
2827 :ref_q (REF_QUAL_NONE), index (0),
2828 ret (NULL_TREE), args (NULL_TREE),
2829 constraints (NULL_TREE)
2834 /* Hashmap of merged duplicates. Usually decls, but can contain
2835 BINFOs. */
2836 typedef hash_map<tree,uintptr_t,
2837 simple_hashmap_traits<nodel_ptr_hash<tree_node>,uintptr_t> >
2838 duplicate_hash_map;
2840 /* Tree stream reader. Note that reading a stream doesn't mark the
2841 read trees with TREE_VISITED. Thus it's quite safe to have
2842 multiple concurrent readers. Which is good, because lazy
2843 loading. */
2844 class trees_in : public bytes_in {
2845 typedef bytes_in parent;
2847 private:
2848 module_state *state; /* Module being imported. */
2849 vec<tree> back_refs; /* Back references. */
2850 duplicate_hash_map *duplicates; /* Map from existings to duplicate. */
2851 vec<tree> post_decls; /* Decls to post process. */
2852 unsigned unused; /* Inhibit any interior TREE_USED
2853 marking. */
2855 public:
2856 trees_in (module_state *);
2857 ~trees_in ();
2859 public:
2860 int insert (tree);
2861 tree back_ref (int);
2863 private:
2864 tree start (unsigned = 0);
2866 public:
2867 /* Needed for binfo writing */
2868 bool core_bools (tree);
2870 private:
2871 /* Stream tree_core, lang_decl_specific and lang_type_specific
2872 bits. */
2873 bool core_vals (tree);
2874 bool lang_type_bools (tree);
2875 bool lang_type_vals (tree);
2876 bool lang_decl_bools (tree);
2877 bool lang_decl_vals (tree);
2878 bool lang_vals (tree);
2879 bool tree_node_bools (tree);
2880 bool tree_node_vals (tree);
2881 tree tree_value ();
2882 tree decl_value ();
2883 tree tpl_parm_value ();
2885 private:
2886 tree chained_decls (); /* Follow DECL_CHAIN. */
2887 vec<tree, va_heap> *vec_chained_decls ();
2888 vec<tree, va_gc> *tree_vec (); /* vec of tree. */
2889 vec<tree_pair_s, va_gc> *tree_pair_vec (); /* vec of tree_pair. */
2890 tree tree_list (bool has_purpose);
2892 public:
2893 /* Read a tree node. */
2894 tree tree_node (bool is_use = false);
2896 private:
2897 bool install_entity (tree decl);
2898 tree tpl_parms (unsigned &tpl_levels);
2899 bool tpl_parms_fini (tree decl, unsigned tpl_levels);
2900 bool tpl_header (tree decl, unsigned *tpl_levels);
2901 int fn_parms_init (tree);
2902 void fn_parms_fini (int tag, tree fn, tree existing, bool has_defn);
2903 unsigned add_indirect_tpl_parms (tree);
2904 public:
2905 bool add_indirects (tree);
2907 public:
2908 /* Serialize various definitions. */
2909 bool read_definition (tree decl);
2911 private:
2912 bool is_matching_decl (tree existing, tree decl, bool is_typedef);
2913 static bool install_implicit_member (tree decl);
2914 bool read_function_def (tree decl, tree maybe_template);
2915 bool read_var_def (tree decl, tree maybe_template);
2916 bool read_class_def (tree decl, tree maybe_template);
2917 bool read_enum_def (tree decl, tree maybe_template);
2919 public:
2920 tree decl_container ();
2921 tree key_mergeable (int tag, merge_kind, tree decl, tree inner, tree type,
2922 tree container, bool is_attached);
2923 unsigned binfo_mergeable (tree *);
2925 private:
2926 uintptr_t *find_duplicate (tree existing);
2927 void register_duplicate (tree decl, tree existing);
2928 /* Mark as an already diagnosed bad duplicate. */
2929 void unmatched_duplicate (tree existing)
2931 *find_duplicate (existing) |= 1;
2934 public:
2935 bool is_duplicate (tree decl)
2937 return find_duplicate (decl) != NULL;
2939 tree maybe_duplicate (tree decl)
2941 if (uintptr_t *dup = find_duplicate (decl))
2942 return reinterpret_cast<tree> (*dup & ~uintptr_t (1));
2943 return decl;
2945 tree odr_duplicate (tree decl, bool has_defn);
2947 public:
2948 /* Return the next decl to postprocess, or NULL. */
2949 tree post_process ()
2951 return post_decls.length () ? post_decls.pop () : NULL_TREE;
2953 private:
2954 /* Register DECL for postprocessing. */
2955 void post_process (tree decl)
2957 post_decls.safe_push (decl);
2960 private:
2961 void assert_definition (tree, bool installing);
2964 trees_in::trees_in (module_state *state)
2965 :parent (), state (state), unused (0)
2967 duplicates = NULL;
2968 back_refs.create (500);
2969 post_decls.create (0);
2972 trees_in::~trees_in ()
2974 delete (duplicates);
2975 back_refs.release ();
2976 post_decls.release ();
2979 /* Tree stream writer. */
2980 class trees_out : public bytes_out {
2981 typedef bytes_out parent;
2983 private:
2984 module_state *state; /* The module we are writing. */
2985 ptr_int_hash_map tree_map; /* Trees to references */
2986 depset::hash *dep_hash; /* Dependency table. */
2987 int ref_num; /* Back reference number. */
2988 unsigned section;
2989 #if CHECKING_P
2990 int importedness; /* Checker that imports not occurring
2991 inappropriately. +ve imports ok,
2992 -ve imports not ok. */
2993 #endif
2995 public:
2996 trees_out (allocator *, module_state *, depset::hash &deps, unsigned sec = 0);
2997 ~trees_out ();
2999 private:
3000 void mark_trees ();
3001 void unmark_trees ();
3003 public:
3004 /* Hey, let's ignore the well known STL iterator idiom. */
3005 void begin ();
3006 unsigned end (elf_out *sink, unsigned name, unsigned *crc_ptr);
3007 void end ();
3009 public:
3010 enum tags
3012 tag_backref = -1, /* Upper bound on the backrefs. */
3013 tag_value = 0, /* Write by value. */
3014 tag_fixed /* Lower bound on the fixed trees. */
3017 public:
3018 bool is_key_order () const
3020 return dep_hash->is_key_order ();
3023 public:
3024 int insert (tree, walk_kind = WK_normal);
3026 private:
3027 void start (tree, bool = false);
3029 private:
3030 walk_kind ref_node (tree);
3031 public:
3032 int get_tag (tree);
3033 void set_importing (int i ATTRIBUTE_UNUSED)
3035 #if CHECKING_P
3036 importedness = i;
3037 #endif
3040 private:
3041 void core_bools (tree);
3042 void core_vals (tree);
3043 void lang_type_bools (tree);
3044 void lang_type_vals (tree);
3045 void lang_decl_bools (tree);
3046 void lang_decl_vals (tree);
3047 void lang_vals (tree);
3048 void tree_node_bools (tree);
3049 void tree_node_vals (tree);
3051 private:
3052 void chained_decls (tree);
3053 void vec_chained_decls (tree);
3054 void tree_vec (vec<tree, va_gc> *);
3055 void tree_pair_vec (vec<tree_pair_s, va_gc> *);
3056 void tree_list (tree, bool has_purpose);
3058 public:
3059 /* Mark a node for by-value walking. */
3060 void mark_by_value (tree);
3062 public:
3063 void tree_node (tree);
3065 private:
3066 void install_entity (tree decl, depset *);
3067 void tpl_parms (tree parms, unsigned &tpl_levels);
3068 void tpl_parms_fini (tree decl, unsigned tpl_levels);
3069 void fn_parms_fini (tree) {}
3070 unsigned add_indirect_tpl_parms (tree);
3071 public:
3072 void add_indirects (tree);
3073 void fn_parms_init (tree);
3074 void tpl_header (tree decl, unsigned *tpl_levels);
3076 public:
3077 merge_kind get_merge_kind (tree decl, depset *maybe_dep);
3078 tree decl_container (tree decl);
3079 void key_mergeable (int tag, merge_kind, tree decl, tree inner,
3080 tree container, depset *maybe_dep);
3081 void binfo_mergeable (tree binfo);
3083 private:
3084 bool decl_node (tree, walk_kind ref);
3085 void type_node (tree);
3086 void tree_value (tree);
3087 void tpl_parm_value (tree);
3089 public:
3090 void decl_value (tree, depset *);
3092 public:
3093 /* Serialize various definitions. */
3094 void write_definition (tree decl);
3095 void mark_declaration (tree decl, bool do_defn);
3097 private:
3098 void mark_function_def (tree decl);
3099 void mark_var_def (tree decl);
3100 void mark_class_def (tree decl);
3101 void mark_enum_def (tree decl);
3102 void mark_class_member (tree decl, bool do_defn = true);
3103 void mark_binfos (tree type);
3105 private:
3106 void write_var_def (tree decl);
3107 void write_function_def (tree decl);
3108 void write_class_def (tree decl);
3109 void write_enum_def (tree decl);
3111 private:
3112 static void assert_definition (tree);
3114 public:
3115 static void instrument ();
3117 private:
3118 /* Tree instrumentation. */
3119 static unsigned tree_val_count;
3120 static unsigned decl_val_count;
3121 static unsigned back_ref_count;
3122 static unsigned null_count;
3125 /* Instrumentation counters. */
3126 unsigned trees_out::tree_val_count;
3127 unsigned trees_out::decl_val_count;
3128 unsigned trees_out::back_ref_count;
3129 unsigned trees_out::null_count;
3131 trees_out::trees_out (allocator *mem, module_state *state, depset::hash &deps,
3132 unsigned section)
3133 :parent (mem), state (state), tree_map (500),
3134 dep_hash (&deps), ref_num (0), section (section)
3136 #if CHECKING_P
3137 importedness = 0;
3138 #endif
3141 trees_out::~trees_out ()
3145 /********************************************************************/
3146 /* Location. We're aware of the line-map concept and reproduce it
3147 here. Each imported module allocates a contiguous span of ordinary
3148 maps, and of macro maps. adhoc maps are serialized by contents,
3149 not pre-allocated. The scattered linemaps of a module are
3150 coalesced when writing. */
3153 /* I use half-open [first,second) ranges. */
3154 typedef std::pair<unsigned,unsigned> range_t;
3156 /* A range of locations. */
3157 typedef std::pair<location_t,location_t> loc_range_t;
3159 /* Spans of the line maps that are occupied by this TU. I.e. not
3160 within imports. Only extended when in an interface unit.
3161 Interval zero corresponds to the forced header linemap(s). This
3162 is a singleton object. */
3164 class loc_spans {
3165 public:
3166 /* An interval of line maps. The line maps here represent a contiguous
3167 non-imported range. */
3168 struct span {
3169 loc_range_t ordinary; /* Ordinary map location range. */
3170 loc_range_t macro; /* Macro map location range. */
3171 int ordinary_delta; /* Add to ordinary loc to get serialized loc. */
3172 int macro_delta; /* Likewise for macro loc. */
3175 private:
3176 vec<span> *spans;
3178 public:
3179 loc_spans ()
3180 /* Do not preallocate spans, as that causes
3181 --enable-detailed-mem-stats problems. */
3182 : spans (nullptr)
3185 ~loc_spans ()
3187 delete spans;
3190 public:
3191 span &operator[] (unsigned ix)
3193 return (*spans)[ix];
3195 unsigned length () const
3197 return spans->length ();
3200 public:
3201 bool init_p () const
3203 return spans != nullptr;
3205 /* Initializer. */
3206 void init (const line_maps *lmaps, const line_map_ordinary *map);
3208 /* Slightly skewed preprocessed files can cause us to miss an
3209 initialization in some places. Fallback initializer. */
3210 void maybe_init ()
3212 if (!init_p ())
3213 init (line_table, nullptr);
3216 public:
3217 enum {
3218 SPAN_RESERVED = 0, /* Reserved (fixed) locations. */
3219 SPAN_FIRST = 1, /* LWM of locations to stream */
3220 SPAN_MAIN = 2 /* Main file and onwards. */
3223 public:
3224 location_t main_start () const
3226 return (*spans)[SPAN_MAIN].ordinary.first;
3229 public:
3230 void open (location_t);
3231 void close ();
3233 public:
3234 /* Propagate imported linemaps to us, if needed. */
3235 bool maybe_propagate (module_state *import, location_t loc);
3237 public:
3238 const span *ordinary (location_t);
3239 const span *macro (location_t);
3242 static loc_spans spans;
3244 /* Information about ordinary locations we stream out. */
3245 struct ord_loc_info
3247 const line_map_ordinary *src; // line map we're based on
3248 unsigned offset; // offset to this line
3249 unsigned span; // number of locs we span
3250 unsigned remap; // serialization
3252 static int compare (const void *a_, const void *b_)
3254 auto *a = static_cast<const ord_loc_info *> (a_);
3255 auto *b = static_cast<const ord_loc_info *> (b_);
3257 if (a->src != b->src)
3258 return a->src < b->src ? -1 : +1;
3260 // Ensure no overlap
3261 gcc_checking_assert (a->offset + a->span <= b->offset
3262 || b->offset + b->span <= a->offset);
3264 gcc_checking_assert (a->offset != b->offset);
3265 return a->offset < b->offset ? -1 : +1;
3268 struct ord_loc_traits
3270 typedef ord_loc_info value_type;
3271 typedef value_type compare_type;
3273 static const bool empty_zero_p = false;
3275 static hashval_t hash (const value_type &v)
3277 auto h = pointer_hash<const line_map_ordinary>::hash (v.src);
3278 return iterative_hash_hashval_t (v.offset, h);
3280 static bool equal (const value_type &v, const compare_type p)
3282 return v.src == p.src && v.offset == p.offset;
3285 static void mark_empty (value_type &v)
3287 v.src = nullptr;
3289 static bool is_empty (value_type &v)
3291 return !v.src;
3294 static bool is_deleted (value_type &) { return false; }
3295 static void mark_deleted (value_type &) { gcc_unreachable (); }
3297 static void remove (value_type &) {}
3299 /* Table keyed by ord_loc_info, used for noting. */
3300 static hash_table<ord_loc_traits> *ord_loc_table;
3301 /* Sorted vector, used for writing. */
3302 static vec<ord_loc_info> *ord_loc_remap;
3304 /* Information about macro locations we stream out. */
3305 struct macro_loc_info
3307 const line_map_macro *src; // original expansion
3308 unsigned remap; // serialization
3310 static int compare (const void *a_, const void *b_)
3312 auto *a = static_cast<const macro_loc_info *> (a_);
3313 auto *b = static_cast<const macro_loc_info *> (b_);
3315 gcc_checking_assert (MAP_START_LOCATION (a->src)
3316 != MAP_START_LOCATION (b->src));
3317 if (MAP_START_LOCATION (a->src) < MAP_START_LOCATION (b->src))
3318 return -1;
3319 else
3320 return +1;
3323 struct macro_loc_traits
3325 typedef macro_loc_info value_type;
3326 typedef const line_map_macro *compare_type;
3328 static const bool empty_zero_p = false;
3330 static hashval_t hash (compare_type p)
3332 return pointer_hash<const line_map_macro>::hash (p);
3334 static hashval_t hash (const value_type &v)
3336 return hash (v.src);
3338 static bool equal (const value_type &v, const compare_type p)
3340 return v.src == p;
3343 static void mark_empty (value_type &v)
3345 v.src = nullptr;
3347 static bool is_empty (value_type &v)
3349 return !v.src;
3352 static bool is_deleted (value_type &) { return false; }
3353 static void mark_deleted (value_type &) { gcc_unreachable (); }
3355 static void remove (value_type &) {}
3357 /* Table keyed by line_map_macro, used for noting. */
3358 static hash_table<macro_loc_traits> *macro_loc_table;
3359 /* Sorted vector, used for writing. */
3360 static vec<macro_loc_info> *macro_loc_remap;
3362 /* Indirection to allow bsearching imports by ordinary location. */
3363 static vec<module_state *> *ool;
3365 /********************************************************************/
3366 /* Data needed by a module during the process of loading. */
3367 struct GTY(()) slurping {
3369 /* Remap import's module numbering to our numbering. Values are
3370 shifted by 1. Bit0 encodes if the import is direct. */
3371 vec<unsigned, va_heap, vl_embed> *
3372 GTY((skip)) remap; /* Module owner remapping. */
3374 elf_in *GTY((skip)) from; /* The elf loader. */
3376 /* This map is only for header imports themselves -- the global
3377 headers bitmap hold it for the current TU. */
3378 bitmap headers; /* Transitive set of direct imports, including
3379 self. Used for macro visibility and
3380 priority. */
3382 /* These objects point into the mmapped area, unless we're not doing
3383 that, or we got frozen or closed. In those cases they point to
3384 buffers we own. */
3385 bytes_in macro_defs; /* Macro definitions. */
3386 bytes_in macro_tbl; /* Macro table. */
3388 /* Location remapping. first->ordinary, second->macro. */
3389 range_t GTY((skip)) loc_deltas;
3391 unsigned current; /* Section currently being loaded. */
3392 unsigned remaining; /* Number of lazy sections yet to read. */
3393 unsigned lru; /* An LRU counter. */
3395 public:
3396 slurping (elf_in *);
3397 ~slurping ();
3399 public:
3400 /* Close the ELF file, if it's open. */
3401 void close ()
3403 if (from)
3405 from->end ();
3406 delete from;
3407 from = NULL;
3411 public:
3412 void release_macros ();
3414 public:
3415 void alloc_remap (unsigned size)
3417 gcc_assert (!remap);
3418 vec_safe_reserve (remap, size);
3419 for (unsigned ix = size; ix--;)
3420 remap->quick_push (0);
3422 unsigned remap_module (unsigned owner)
3424 if (owner < remap->length ())
3425 return (*remap)[owner] >> 1;
3426 return 0;
3429 public:
3430 /* GC allocation. But we must explicitly delete it. */
3431 static void *operator new (size_t x)
3433 return ggc_alloc_atomic (x);
3435 static void operator delete (void *p)
3437 ggc_free (p);
3441 slurping::slurping (elf_in *from)
3442 : remap (NULL), from (from),
3443 headers (BITMAP_GGC_ALLOC ()), macro_defs (), macro_tbl (),
3444 loc_deltas (0, 0),
3445 current (~0u), remaining (0), lru (0)
3449 slurping::~slurping ()
3451 vec_free (remap);
3452 remap = NULL;
3453 release_macros ();
3454 close ();
3457 void slurping::release_macros ()
3459 if (macro_defs.size)
3460 elf_in::release (from, macro_defs);
3461 if (macro_tbl.size)
3462 elf_in::release (from, macro_tbl);
3465 /* Flags for extensions that end up being streamed. */
3467 enum streamed_extensions {
3468 SE_OPENMP = 1 << 0,
3469 SE_BITS = 1
3472 /* Counter indices. */
3473 enum module_state_counts
3475 MSC_sec_lwm,
3476 MSC_sec_hwm,
3477 MSC_pendings,
3478 MSC_entities,
3479 MSC_namespaces,
3480 MSC_bindings,
3481 MSC_macros,
3482 MSC_inits,
3483 MSC_HWM
3486 /********************************************************************/
3487 struct module_state_config;
3489 /* Increasing levels of loadedness. */
3490 enum module_loadedness {
3491 ML_NONE, /* Not loaded. */
3492 ML_CONFIG, /* Config loaed. */
3493 ML_PREPROCESSOR, /* Preprocessor loaded. */
3494 ML_LANGUAGE, /* Language loaded. */
3497 /* Increasing levels of directness (toplevel) of import. */
3498 enum module_directness {
3499 MD_NONE, /* Not direct. */
3500 MD_PARTITION_DIRECT, /* Direct import of a partition. */
3501 MD_DIRECT, /* Direct import. */
3502 MD_PURVIEW_DIRECT, /* direct import in purview. */
3505 /* State of a particular module. */
3507 class GTY((chain_next ("%h.parent"), for_user)) module_state {
3508 public:
3509 /* We always import & export ourselves. */
3510 bitmap imports; /* Transitive modules we're importing. */
3511 bitmap exports; /* Subset of that, that we're exporting. */
3513 module_state *parent;
3514 tree name; /* Name of the module. */
3516 slurping *slurp; /* Data for loading. */
3518 const char *flatname; /* Flatname of module. */
3519 char *filename; /* CMI Filename */
3521 /* Indices into the entity_ary. */
3522 unsigned entity_lwm;
3523 unsigned entity_num;
3525 /* Location ranges for this module. adhoc-locs are decomposed, so
3526 don't have a range. */
3527 loc_range_t GTY((skip)) ordinary_locs;
3528 loc_range_t GTY((skip)) macro_locs; // [lwm,num)
3530 /* LOC is first set too the importing location. When initially
3531 loaded it refers to a module loc whose parent is the importing
3532 location. */
3533 location_t loc; /* Location referring to module itself. */
3534 unsigned crc; /* CRC we saw reading it in. */
3536 unsigned mod; /* Module owner number. */
3537 unsigned remap; /* Remapping during writing. */
3539 unsigned short subst; /* Mangle subst if !0. */
3541 /* How loaded this module is. */
3542 enum module_loadedness loadedness : 2;
3544 bool module_p : 1; /* /The/ module of this TU. */
3545 bool header_p : 1; /* Is a header unit. */
3546 bool interface_p : 1; /* An interface. */
3547 bool partition_p : 1; /* A partition. */
3549 /* How directly this module is imported. */
3550 enum module_directness directness : 2;
3552 bool exported_p : 1; /* directness != MD_NONE && exported. */
3553 bool cmi_noted_p : 1; /* We've told the user about the CMI, don't
3554 do it again */
3555 bool active_init_p : 1; /* This module's global initializer needs
3556 calling. */
3557 bool inform_cmi_p : 1; /* Inform of a read/write. */
3558 bool visited_p : 1; /* A walk-once flag. */
3559 /* Record extensions emitted or permitted. */
3560 unsigned extensions : SE_BITS;
3561 /* 14 bits used, 2 bits remain */
3563 public:
3564 module_state (tree name, module_state *, bool);
3565 ~module_state ();
3567 public:
3568 void release ()
3570 imports = exports = NULL;
3571 slurped ();
3573 void slurped ()
3575 delete slurp;
3576 slurp = NULL;
3578 elf_in *from () const
3580 return slurp->from;
3583 public:
3584 /* Kind of this module. */
3585 bool is_module () const
3587 return module_p;
3589 bool is_header () const
3591 return header_p;
3593 bool is_interface () const
3595 return interface_p;
3597 bool is_partition () const
3599 return partition_p;
3602 /* How this module is used in the current TU. */
3603 bool is_exported () const
3605 return exported_p;
3607 bool is_direct () const
3609 return directness >= MD_DIRECT;
3611 bool is_purview_direct () const
3613 return directness == MD_PURVIEW_DIRECT;
3615 bool is_partition_direct () const
3617 return directness == MD_PARTITION_DIRECT;
3620 public:
3621 /* Is this a real module? */
3622 bool has_location () const
3624 return loc != UNKNOWN_LOCATION;
3627 public:
3628 bool check_not_purview (location_t loc);
3630 public:
3631 void mangle (bool include_partition);
3633 public:
3634 void set_import (module_state const *, bool is_export);
3635 void announce (const char *) const;
3637 public:
3638 /* Read and write module. */
3639 void write_begin (elf_out *to, cpp_reader *,
3640 module_state_config &, unsigned &crc);
3641 void write_end (elf_out *to, cpp_reader *,
3642 module_state_config &, unsigned &crc);
3643 bool read_initial (cpp_reader *);
3644 bool read_preprocessor (bool);
3645 bool read_language (bool);
3647 public:
3648 /* Read a section. */
3649 bool load_section (unsigned snum, binding_slot *mslot);
3650 /* Lazily read a section. */
3651 bool lazy_load (unsigned index, binding_slot *mslot);
3653 public:
3654 /* Juggle a limited number of file numbers. */
3655 static void freeze_an_elf ();
3656 bool maybe_defrost ();
3658 public:
3659 void maybe_completed_reading ();
3660 bool check_read (bool outermost, bool ok);
3662 private:
3663 /* The README, for human consumption. */
3664 void write_readme (elf_out *to, cpp_reader *, const char *dialect);
3665 void write_env (elf_out *to);
3667 private:
3668 /* Import tables. */
3669 void write_imports (bytes_out &cfg, bool direct);
3670 unsigned read_imports (bytes_in &cfg, cpp_reader *, line_maps *maps);
3672 private:
3673 void write_imports (elf_out *to, unsigned *crc_ptr);
3674 bool read_imports (cpp_reader *, line_maps *);
3676 private:
3677 void write_partitions (elf_out *to, unsigned, unsigned *crc_ptr);
3678 bool read_partitions (unsigned);
3680 private:
3681 void write_config (elf_out *to, struct module_state_config &, unsigned crc);
3682 bool read_config (struct module_state_config &);
3683 static void write_counts (elf_out *to, unsigned [MSC_HWM], unsigned *crc_ptr);
3684 bool read_counts (unsigned *);
3686 public:
3687 void note_cmi_name ();
3689 private:
3690 static unsigned write_bindings (elf_out *to, vec<depset *> depsets,
3691 unsigned *crc_ptr);
3692 bool read_bindings (unsigned count, unsigned lwm, unsigned hwm);
3694 static void write_namespace (bytes_out &sec, depset *ns_dep);
3695 tree read_namespace (bytes_in &sec);
3697 void write_namespaces (elf_out *to, vec<depset *> spaces,
3698 unsigned, unsigned *crc_ptr);
3699 bool read_namespaces (unsigned);
3701 void intercluster_seed (trees_out &sec, unsigned index, depset *dep);
3702 unsigned write_cluster (elf_out *to, depset *depsets[], unsigned size,
3703 depset::hash &, unsigned *counts, unsigned *crc_ptr);
3704 bool read_cluster (unsigned snum);
3706 private:
3707 unsigned write_inits (elf_out *to, depset::hash &, unsigned *crc_ptr);
3708 bool read_inits (unsigned count);
3710 private:
3711 unsigned write_pendings (elf_out *to, vec<depset *> depsets,
3712 depset::hash &, unsigned *crc_ptr);
3713 bool read_pendings (unsigned count);
3715 private:
3716 void write_entities (elf_out *to, vec<depset *> depsets,
3717 unsigned count, unsigned *crc_ptr);
3718 bool read_entities (unsigned count, unsigned lwm, unsigned hwm);
3720 private:
3721 void write_init_maps ();
3722 range_t write_prepare_maps (module_state_config *, bool);
3723 bool read_prepare_maps (const module_state_config *);
3725 void write_ordinary_maps (elf_out *to, range_t &,
3726 bool, unsigned *crc_ptr);
3727 bool read_ordinary_maps (unsigned, unsigned);
3728 void write_macro_maps (elf_out *to, range_t &, unsigned *crc_ptr);
3729 bool read_macro_maps (unsigned);
3731 private:
3732 void write_define (bytes_out &, const cpp_macro *);
3733 cpp_macro *read_define (bytes_in &, cpp_reader *) const;
3734 vec<cpp_hashnode *> *prepare_macros (cpp_reader *);
3735 unsigned write_macros (elf_out *to, vec<cpp_hashnode *> *, unsigned *crc_ptr);
3736 bool read_macros ();
3737 void install_macros ();
3739 public:
3740 void import_macros ();
3742 public:
3743 static void undef_macro (cpp_reader *, location_t, cpp_hashnode *);
3744 static cpp_macro *deferred_macro (cpp_reader *, location_t, cpp_hashnode *);
3746 public:
3747 static bool note_location (location_t);
3748 static void write_location (bytes_out &, location_t);
3749 location_t read_location (bytes_in &) const;
3751 public:
3752 void set_flatname ();
3753 const char *get_flatname () const
3755 return flatname;
3757 location_t imported_from () const;
3759 public:
3760 void set_filename (const Cody::Packet &);
3761 bool do_import (cpp_reader *, bool outermost);
3764 /* Hash module state by name. This cannot be a member of
3765 module_state, because of GTY restrictions. We never delete from
3766 the hash table, but ggc_ptr_hash doesn't support that
3767 simplification. */
3769 struct module_state_hash : ggc_ptr_hash<module_state> {
3770 typedef std::pair<tree,uintptr_t> compare_type; /* {name,parent} */
3772 static inline hashval_t hash (const value_type m);
3773 static inline hashval_t hash (const compare_type &n);
3774 static inline bool equal (const value_type existing,
3775 const compare_type &candidate);
3778 module_state::module_state (tree name, module_state *parent, bool partition)
3779 : imports (BITMAP_GGC_ALLOC ()), exports (BITMAP_GGC_ALLOC ()),
3780 parent (parent), name (name), slurp (NULL),
3781 flatname (NULL), filename (NULL),
3782 entity_lwm (~0u >> 1), entity_num (0),
3783 ordinary_locs (0, 0), macro_locs (0, 0),
3784 loc (UNKNOWN_LOCATION),
3785 crc (0), mod (MODULE_UNKNOWN), remap (0), subst (0)
3787 loadedness = ML_NONE;
3789 module_p = header_p = interface_p = partition_p = false;
3791 directness = MD_NONE;
3792 exported_p = false;
3794 cmi_noted_p = false;
3795 active_init_p = false;
3797 partition_p = partition;
3799 inform_cmi_p = false;
3800 visited_p = false;
3802 extensions = 0;
3803 if (name && TREE_CODE (name) == STRING_CST)
3805 header_p = true;
3807 const char *string = TREE_STRING_POINTER (name);
3808 gcc_checking_assert (string[0] == '.'
3809 ? IS_DIR_SEPARATOR (string[1])
3810 : IS_ABSOLUTE_PATH (string));
3813 gcc_checking_assert (!(parent && header_p));
3816 module_state::~module_state ()
3818 release ();
3821 /* Hash module state. */
3822 static hashval_t
3823 module_name_hash (const_tree name)
3825 if (TREE_CODE (name) == STRING_CST)
3826 return htab_hash_string (TREE_STRING_POINTER (name));
3827 else
3828 return IDENTIFIER_HASH_VALUE (name);
3831 hashval_t
3832 module_state_hash::hash (const value_type m)
3834 hashval_t ph = pointer_hash<void>::hash
3835 (reinterpret_cast<void *> (reinterpret_cast<uintptr_t> (m->parent)
3836 | m->is_partition ()));
3837 hashval_t nh = module_name_hash (m->name);
3838 return iterative_hash_hashval_t (ph, nh);
3841 /* Hash a name. */
3842 hashval_t
3843 module_state_hash::hash (const compare_type &c)
3845 hashval_t ph = pointer_hash<void>::hash (reinterpret_cast<void *> (c.second));
3846 hashval_t nh = module_name_hash (c.first);
3848 return iterative_hash_hashval_t (ph, nh);
3851 bool
3852 module_state_hash::equal (const value_type existing,
3853 const compare_type &candidate)
3855 uintptr_t ep = (reinterpret_cast<uintptr_t> (existing->parent)
3856 | existing->is_partition ());
3857 if (ep != candidate.second)
3858 return false;
3860 /* Identifier comparison is by pointer. If the string_csts happen
3861 to be the same object, then they're equal too. */
3862 if (existing->name == candidate.first)
3863 return true;
3865 /* If neither are string csts, they can't be equal. */
3866 if (TREE_CODE (candidate.first) != STRING_CST
3867 || TREE_CODE (existing->name) != STRING_CST)
3868 return false;
3870 /* String equality. */
3871 if (TREE_STRING_LENGTH (existing->name)
3872 == TREE_STRING_LENGTH (candidate.first)
3873 && !memcmp (TREE_STRING_POINTER (existing->name),
3874 TREE_STRING_POINTER (candidate.first),
3875 TREE_STRING_LENGTH (existing->name)))
3876 return true;
3878 return false;
3881 /********************************************************************/
3882 /* Global state */
3884 /* Mapper name. */
3885 static const char *module_mapper_name;
3887 /* Deferred import queue (FIFO). */
3888 static vec<module_state *, va_heap, vl_embed> *pending_imports;
3890 /* CMI repository path and workspace. */
3891 static char *cmi_repo;
3892 static size_t cmi_repo_length;
3893 static char *cmi_path;
3894 static size_t cmi_path_alloc;
3896 /* Count of available and loaded clusters. */
3897 static unsigned available_clusters;
3898 static unsigned loaded_clusters;
3900 /* What the current TU is. */
3901 unsigned module_kind;
3903 /* Global trees. */
3904 static const std::pair<tree *, unsigned> global_tree_arys[] =
3906 std::pair<tree *, unsigned> (sizetype_tab, stk_type_kind_last),
3907 std::pair<tree *, unsigned> (integer_types, itk_none),
3908 std::pair<tree *, unsigned> (global_trees, TI_MODULE_HWM),
3909 std::pair<tree *, unsigned> (c_global_trees, CTI_MODULE_HWM),
3910 std::pair<tree *, unsigned> (cp_global_trees, CPTI_MODULE_HWM),
3911 std::pair<tree *, unsigned> (NULL, 0)
3913 static GTY(()) vec<tree, va_gc> *fixed_trees;
3914 static unsigned global_crc;
3916 /* Lazy loading can open many files concurrently, there are
3917 per-process limits on that. We pay attention to the process limit,
3918 and attempt to increase it when we run out. Otherwise we use an
3919 LRU scheme to figure out who to flush. Note that if the import
3920 graph /depth/ exceeds lazy_limit, we'll exceed the limit. */
3921 static unsigned lazy_lru; /* LRU counter. */
3922 static unsigned lazy_open; /* Number of open modules */
3923 static unsigned lazy_limit; /* Current limit of open modules. */
3924 static unsigned lazy_hard_limit; /* Hard limit on open modules. */
3925 /* Account for source, assembler and dump files & directory searches.
3926 We don't keep the source file's open, so we don't have to account
3927 for #include depth. I think dump files are opened and closed per
3928 pass, but ICBW. */
3929 #define LAZY_HEADROOM 15 /* File descriptor headroom. */
3931 /* Vector of module state. Indexed by OWNER. Has at least 2 slots. */
3932 static GTY(()) vec<module_state *, va_gc> *modules;
3934 /* Hash of module state, findable by {name, parent}. */
3935 static GTY(()) hash_table<module_state_hash> *modules_hash;
3937 /* Map of imported entities. We map DECL_UID to index of entity
3938 vector. */
3939 typedef hash_map<unsigned/*UID*/, unsigned/*index*/,
3940 simple_hashmap_traits<int_hash<unsigned,0>, unsigned>
3941 > entity_map_t;
3942 static entity_map_t *entity_map;
3943 /* Doesn't need GTYing, because any tree referenced here is also
3944 findable by, symbol table, specialization table, return type of
3945 reachable function. */
3946 static vec<binding_slot, va_heap, vl_embed> *entity_ary;
3948 /* Members entities of imported classes that are defined in this TU.
3949 These are where the entity's context is not from the current TU.
3950 We need to emit the definition (but not the enclosing class).
3952 We could find these by walking ALL the imported classes that we
3953 could provide a member definition. But that's expensive,
3954 especially when you consider lazy implicit member declarations,
3955 which could be ANY imported class. */
3956 static GTY(()) vec<tree, va_gc> *class_members;
3958 /* The same problem exists for class template partial
3959 specializations. Now that we have constraints, the invariant of
3960 expecting them in the instantiation table no longer holds. One of
3961 the constrained partial specializations will be there, but the
3962 others not so much. It's not even an unconstrained partial
3963 spacialization in the table :( so any partial template declaration
3964 is added to this list too. */
3965 static GTY(()) vec<tree, va_gc> *partial_specializations;
3967 /********************************************************************/
3969 /* Our module mapper (created lazily). */
3970 module_client *mapper;
3972 static module_client *make_mapper (location_t loc, class mkdeps *deps);
3973 inline module_client *get_mapper (location_t loc, class mkdeps *deps)
3975 auto *res = mapper;
3976 if (!res)
3977 res = make_mapper (loc, deps);
3978 return res;
3981 /********************************************************************/
3982 static tree
3983 get_clone_target (tree decl)
3985 tree target;
3987 if (TREE_CODE (decl) == TEMPLATE_DECL)
3989 tree res_orig = DECL_CLONED_FUNCTION (DECL_TEMPLATE_RESULT (decl));
3991 target = DECL_TI_TEMPLATE (res_orig);
3993 else
3994 target = DECL_CLONED_FUNCTION (decl);
3996 gcc_checking_assert (DECL_MAYBE_IN_CHARGE_CDTOR_P (target));
3998 return target;
4001 /* Like FOR_EACH_CLONE, but will walk cloned templates. */
4002 #define FOR_EVERY_CLONE(CLONE, FN) \
4003 if (!DECL_MAYBE_IN_CHARGE_CDTOR_P (FN)); \
4004 else \
4005 for (CLONE = DECL_CHAIN (FN); \
4006 CLONE && DECL_CLONED_FUNCTION_P (CLONE); \
4007 CLONE = DECL_CHAIN (CLONE))
4009 /* It'd be nice if USE_TEMPLATE was a field of template_info
4010 (a) it'd solve the enum case dealt with below,
4011 (b) both class templates and decl templates would store this in the
4012 same place
4013 (c) this function wouldn't need the by-ref arg, which is annoying. */
4015 static tree
4016 node_template_info (tree decl, int &use)
4018 tree ti = NULL_TREE;
4019 int use_tpl = -1;
4020 if (DECL_IMPLICIT_TYPEDEF_P (decl))
4022 tree type = TREE_TYPE (decl);
4024 ti = TYPE_TEMPLATE_INFO (type);
4025 if (ti)
4027 if (TYPE_LANG_SPECIFIC (type))
4028 use_tpl = CLASSTYPE_USE_TEMPLATE (type);
4029 else
4031 /* An enum, where we don't explicitly encode use_tpl.
4032 If the containing context (a type or a function), is
4033 an ({im,ex}plicit) instantiation, then this is too.
4034 If it's a partial or explicit specialization, then
4035 this is not!. */
4036 tree ctx = CP_DECL_CONTEXT (decl);
4037 if (TYPE_P (ctx))
4038 ctx = TYPE_NAME (ctx);
4039 node_template_info (ctx, use);
4040 use_tpl = use != 2 ? use : 0;
4044 else if (DECL_LANG_SPECIFIC (decl)
4045 && (VAR_P (decl)
4046 || TREE_CODE (decl) == TYPE_DECL
4047 || TREE_CODE (decl) == FUNCTION_DECL
4048 || TREE_CODE (decl) == FIELD_DECL
4049 || TREE_CODE (decl) == CONCEPT_DECL
4050 || TREE_CODE (decl) == TEMPLATE_DECL))
4052 use_tpl = DECL_USE_TEMPLATE (decl);
4053 ti = DECL_TEMPLATE_INFO (decl);
4056 use = use_tpl;
4057 return ti;
4060 /* Find the index in entity_ary for an imported DECL. It should
4061 always be there, but bugs can cause it to be missing, and that can
4062 crash the crash reporting -- let's not do that! When streaming
4063 out we place entities from this module there too -- with negated
4064 indices. */
4066 static unsigned
4067 import_entity_index (tree decl, bool null_ok = false)
4069 if (unsigned *slot = entity_map->get (DECL_UID (decl)))
4070 return *slot;
4072 gcc_checking_assert (null_ok);
4073 return ~(~0u >> 1);
4076 /* Find the module for an imported entity at INDEX in the entity ary.
4077 There must be one. */
4079 static module_state *
4080 import_entity_module (unsigned index)
4082 if (index > ~(~0u >> 1))
4083 /* This is an index for an exported entity. */
4084 return (*modules)[0];
4086 /* Do not include the current TU (not an off-by-one error). */
4087 unsigned pos = 1;
4088 unsigned len = modules->length () - pos;
4089 while (len)
4091 unsigned half = len / 2;
4092 module_state *probe = (*modules)[pos + half];
4093 if (index < probe->entity_lwm)
4094 len = half;
4095 else if (index < probe->entity_lwm + probe->entity_num)
4096 return probe;
4097 else
4099 pos += half + 1;
4100 len = len - (half + 1);
4103 gcc_unreachable ();
4107 /********************************************************************/
4108 /* A dumping machinery. */
4110 class dumper {
4111 public:
4112 enum {
4113 LOCATION = TDF_LINENO, /* -lineno:Source location streaming. */
4114 DEPEND = TDF_GRAPH, /* -graph:Dependency graph construction. */
4115 CLUSTER = TDF_BLOCKS, /* -blocks:Clusters. */
4116 TREE = TDF_UID, /* -uid:Tree streaming. */
4117 MERGE = TDF_ALIAS, /* -alias:Mergeable Entities. */
4118 ELF = TDF_ASMNAME, /* -asmname:Elf data. */
4119 MACRO = TDF_VOPS /* -vops:Macros. */
4122 private:
4123 struct impl {
4124 typedef vec<module_state *, va_heap, vl_embed> stack_t;
4126 FILE *stream; /* Dump stream. */
4127 unsigned indent; /* Local indentation. */
4128 bool bol; /* Beginning of line. */
4129 stack_t stack; /* Trailing array of module_state. */
4131 bool nested_name (tree); /* Dump a name following DECL_CONTEXT. */
4134 public:
4135 /* The dumper. */
4136 impl *dumps;
4137 dump_flags_t flags;
4139 public:
4140 /* Push/pop module state dumping. */
4141 unsigned push (module_state *);
4142 void pop (unsigned);
4144 public:
4145 /* Change local indentation. */
4146 void indent ()
4148 if (dumps)
4149 dumps->indent++;
4151 void outdent ()
4153 if (dumps)
4155 gcc_checking_assert (dumps->indent);
4156 dumps->indent--;
4160 public:
4161 /* Is dump enabled?. */
4162 bool operator () (int mask = 0)
4164 if (!dumps || !dumps->stream)
4165 return false;
4166 if (mask && !(mask & flags))
4167 return false;
4168 return true;
4170 /* Dump some information. */
4171 bool operator () (const char *, ...);
4174 /* The dumper. */
4175 static dumper dump = {0, dump_flags_t (0)};
4177 /* Push to dumping M. Return previous indentation level. */
4179 unsigned
4180 dumper::push (module_state *m)
4182 FILE *stream = NULL;
4183 if (!dumps || !dumps->stack.length ())
4185 stream = dump_begin (module_dump_id, &flags);
4186 if (!stream)
4187 return 0;
4190 if (!dumps || !dumps->stack.space (1))
4192 /* Create or extend the dump implementor. */
4193 unsigned current = dumps ? dumps->stack.length () : 0;
4194 unsigned count = current ? current * 2 : EXPERIMENT (1, 20);
4195 size_t alloc = (offsetof (impl, stack)
4196 + impl::stack_t::embedded_size (count));
4197 dumps = XRESIZEVAR (impl, dumps, alloc);
4198 dumps->stack.embedded_init (count, current);
4200 if (stream)
4201 dumps->stream = stream;
4203 unsigned n = dumps->indent;
4204 dumps->indent = 0;
4205 dumps->bol = true;
4206 dumps->stack.quick_push (m);
4207 if (m)
4209 module_state *from = NULL;
4211 if (dumps->stack.length () > 1)
4212 from = dumps->stack[dumps->stack.length () - 2];
4213 else
4214 dump ("");
4215 dump (from ? "Starting module %M (from %M)"
4216 : "Starting module %M", m, from);
4219 return n;
4222 /* Pop from dumping. Restore indentation to N. */
4224 void dumper::pop (unsigned n)
4226 if (!dumps)
4227 return;
4229 gcc_checking_assert (dump () && !dumps->indent);
4230 if (module_state *m = dumps->stack[dumps->stack.length () - 1])
4232 module_state *from = (dumps->stack.length () > 1
4233 ? dumps->stack[dumps->stack.length () - 2] : NULL);
4234 dump (from ? "Finishing module %M (returning to %M)"
4235 : "Finishing module %M", m, from);
4237 dumps->stack.pop ();
4238 dumps->indent = n;
4239 if (!dumps->stack.length ())
4241 dump_end (module_dump_id, dumps->stream);
4242 dumps->stream = NULL;
4246 /* Dump a nested name for arbitrary tree T. Sometimes it won't have a
4247 name. */
4249 bool
4250 dumper::impl::nested_name (tree t)
4252 tree ti = NULL_TREE;
4253 int origin = -1;
4254 tree name = NULL_TREE;
4256 if (t && TREE_CODE (t) == TREE_BINFO)
4257 t = BINFO_TYPE (t);
4259 if (t && TYPE_P (t))
4260 t = TYPE_NAME (t);
4262 if (t && DECL_P (t))
4264 if (t == global_namespace || DECL_TEMPLATE_PARM_P (t))
4266 else if (tree ctx = DECL_CONTEXT (t))
4267 if (TREE_CODE (ctx) == TRANSLATION_UNIT_DECL
4268 || nested_name (ctx))
4269 fputs ("::", stream);
4271 int use_tpl;
4272 ti = node_template_info (t, use_tpl);
4273 if (ti && TREE_CODE (TI_TEMPLATE (ti)) == TEMPLATE_DECL
4274 && (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == t))
4275 t = TI_TEMPLATE (ti);
4276 tree not_tmpl = t;
4277 if (TREE_CODE (t) == TEMPLATE_DECL)
4279 fputs ("template ", stream);
4280 not_tmpl = DECL_TEMPLATE_RESULT (t);
4283 if (not_tmpl
4284 && DECL_P (not_tmpl)
4285 && DECL_LANG_SPECIFIC (not_tmpl)
4286 && DECL_MODULE_IMPORT_P (not_tmpl))
4288 /* We need to be careful here, so as to not explode on
4289 inconsistent data -- we're probably debugging, because
4290 Something Is Wrong. */
4291 unsigned index = import_entity_index (t, true);
4292 if (!(index & ~(~0u >> 1)))
4293 origin = import_entity_module (index)->mod;
4294 else if (index > ~(~0u >> 1))
4295 /* An imported partition member that we're emitting. */
4296 origin = 0;
4297 else
4298 origin = -2;
4301 name = DECL_NAME (t) ? DECL_NAME (t)
4302 : HAS_DECL_ASSEMBLER_NAME_P (t) ? DECL_ASSEMBLER_NAME_RAW (t)
4303 : NULL_TREE;
4305 else
4306 name = t;
4308 if (name)
4309 switch (TREE_CODE (name))
4311 default:
4312 fputs ("#unnamed#", stream);
4313 break;
4315 case IDENTIFIER_NODE:
4316 fwrite (IDENTIFIER_POINTER (name), 1, IDENTIFIER_LENGTH (name), stream);
4317 break;
4319 case INTEGER_CST:
4320 print_hex (wi::to_wide (name), stream);
4321 break;
4323 case STRING_CST:
4324 /* If TREE_TYPE is NULL, this is a raw string. */
4325 fwrite (TREE_STRING_POINTER (name), 1,
4326 TREE_STRING_LENGTH (name) - (TREE_TYPE (name) != NULL_TREE),
4327 stream);
4328 break;
4330 else
4331 fputs ("#null#", stream);
4333 if (origin >= 0)
4335 const module_state *module = (*modules)[origin];
4336 fprintf (stream, "@%s:%d", !module ? "" : !module->name ? "(unnamed)"
4337 : module->get_flatname (), origin);
4339 else if (origin == -2)
4340 fprintf (stream, "@???");
4342 if (ti)
4344 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (ti));
4345 fputs ("<", stream);
4346 if (args)
4347 for (int ix = 0; ix != TREE_VEC_LENGTH (args); ix++)
4349 if (ix)
4350 fputs (",", stream);
4351 nested_name (TREE_VEC_ELT (args, ix));
4353 fputs (">", stream);
4356 return true;
4359 /* Formatted dumping. FORMAT begins with '+' do not emit a trailing
4360 new line. (Normally it is appended.)
4361 Escapes:
4362 %C - tree_code
4363 %I - identifier
4364 %M - module_state
4365 %N - name -- DECL_NAME
4366 %P - context:name pair
4367 %R - unsigned:unsigned ratio
4368 %S - symbol -- DECL_ASSEMBLER_NAME
4369 %U - long unsigned
4370 %V - version
4371 --- the following are printf-like, but without its flexibility
4372 %d - decimal int
4373 %p - pointer
4374 %s - string
4375 %u - unsigned int
4376 %x - hex int
4378 We do not implement the printf modifiers. */
4380 bool
4381 dumper::operator () (const char *format, ...)
4383 if (!(*this) ())
4384 return false;
4386 bool no_nl = format[0] == '+';
4387 format += no_nl;
4389 if (dumps->bol)
4391 /* Module import indent. */
4392 if (unsigned depth = dumps->stack.length () - 1)
4394 const char *prefix = ">>>>";
4395 fprintf (dumps->stream, (depth <= strlen (prefix)
4396 ? &prefix[strlen (prefix) - depth]
4397 : ">.%d.>"), depth);
4400 /* Local indent. */
4401 if (unsigned indent = dumps->indent)
4403 const char *prefix = " ";
4404 fprintf (dumps->stream, (indent <= strlen (prefix)
4405 ? &prefix[strlen (prefix) - indent]
4406 : " .%d. "), indent);
4408 dumps->bol = false;
4411 va_list args;
4412 va_start (args, format);
4413 while (const char *esc = strchr (format, '%'))
4415 fwrite (format, 1, (size_t)(esc - format), dumps->stream);
4416 format = ++esc;
4417 switch (*format++)
4419 default:
4420 gcc_unreachable ();
4422 case '%':
4423 fputc ('%', dumps->stream);
4424 break;
4426 case 'C': /* Code */
4428 tree_code code = (tree_code)va_arg (args, unsigned);
4429 fputs (get_tree_code_name (code), dumps->stream);
4431 break;
4433 case 'I': /* Identifier. */
4435 tree t = va_arg (args, tree);
4436 dumps->nested_name (t);
4438 break;
4440 case 'M': /* Module. */
4442 const char *str = "(none)";
4443 if (module_state *m = va_arg (args, module_state *))
4445 if (!m->has_location ())
4446 str = "(detached)";
4447 else
4448 str = m->get_flatname ();
4450 fputs (str, dumps->stream);
4452 break;
4454 case 'N': /* Name. */
4456 tree t = va_arg (args, tree);
4457 while (t && TREE_CODE (t) == OVERLOAD)
4458 t = OVL_FUNCTION (t);
4459 fputc ('\'', dumps->stream);
4460 dumps->nested_name (t);
4461 fputc ('\'', dumps->stream);
4463 break;
4465 case 'P': /* Pair. */
4467 tree ctx = va_arg (args, tree);
4468 tree name = va_arg (args, tree);
4469 fputc ('\'', dumps->stream);
4470 dumps->nested_name (ctx);
4471 if (ctx && ctx != global_namespace)
4472 fputs ("::", dumps->stream);
4473 dumps->nested_name (name);
4474 fputc ('\'', dumps->stream);
4476 break;
4478 case 'R': /* Ratio */
4480 unsigned a = va_arg (args, unsigned);
4481 unsigned b = va_arg (args, unsigned);
4482 fprintf (dumps->stream, "%.1f", (float) a / (b + !b));
4484 break;
4486 case 'S': /* Symbol name */
4488 tree t = va_arg (args, tree);
4489 if (t && TYPE_P (t))
4490 t = TYPE_NAME (t);
4491 if (t && HAS_DECL_ASSEMBLER_NAME_P (t)
4492 && DECL_ASSEMBLER_NAME_SET_P (t))
4494 fputc ('(', dumps->stream);
4495 fputs (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (t)),
4496 dumps->stream);
4497 fputc (')', dumps->stream);
4500 break;
4502 case 'U': /* long unsigned. */
4504 unsigned long u = va_arg (args, unsigned long);
4505 fprintf (dumps->stream, "%lu", u);
4507 break;
4509 case 'V': /* Verson. */
4511 unsigned v = va_arg (args, unsigned);
4512 verstr_t string;
4514 version2string (v, string);
4515 fputs (string, dumps->stream);
4517 break;
4519 case 'c': /* Character. */
4521 int c = va_arg (args, int);
4522 fputc (c, dumps->stream);
4524 break;
4526 case 'd': /* Decimal Int. */
4528 int d = va_arg (args, int);
4529 fprintf (dumps->stream, "%d", d);
4531 break;
4533 case 'p': /* Pointer. */
4535 void *p = va_arg (args, void *);
4536 fprintf (dumps->stream, "%p", p);
4538 break;
4540 case 's': /* String. */
4542 const char *s = va_arg (args, char *);
4543 gcc_checking_assert (s);
4544 fputs (s, dumps->stream);
4546 break;
4548 case 'u': /* Unsigned. */
4550 unsigned u = va_arg (args, unsigned);
4551 fprintf (dumps->stream, "%u", u);
4553 break;
4555 case 'x': /* Hex. */
4557 unsigned x = va_arg (args, unsigned);
4558 fprintf (dumps->stream, "%x", x);
4560 break;
4563 fputs (format, dumps->stream);
4564 va_end (args);
4565 if (!no_nl)
4567 dumps->bol = true;
4568 fputc ('\n', dumps->stream);
4570 return true;
4573 struct note_def_cache_hasher : ggc_cache_ptr_hash<tree_node>
4575 static int keep_cache_entry (tree t)
4577 if (!CHECKING_P)
4578 /* GTY is unfortunately not clever enough to conditionalize
4579 this. */
4580 gcc_unreachable ();
4582 if (ggc_marked_p (t))
4583 return -1;
4585 unsigned n = dump.push (NULL);
4586 /* This might or might not be an error. We should note its
4587 dropping whichever. */
4588 dump () && dump ("Dropping %N from note_defs table", t);
4589 dump.pop (n);
4591 return 0;
4595 /* We should stream each definition at most once.
4596 This needs to be a cache because there are cases where a definition
4597 ends up being not retained, and we need to drop those so we don't
4598 get confused if memory is reallocated. */
4599 typedef hash_table<note_def_cache_hasher> note_defs_table_t;
4600 static GTY((cache)) note_defs_table_t *note_defs;
4602 void
4603 trees_in::assert_definition (tree decl ATTRIBUTE_UNUSED,
4604 bool installing ATTRIBUTE_UNUSED)
4606 #if CHECKING_P
4607 tree *slot = note_defs->find_slot (decl, installing ? INSERT : NO_INSERT);
4608 tree not_tmpl = STRIP_TEMPLATE (decl);
4609 if (installing)
4611 /* We must be inserting for the first time. */
4612 gcc_assert (!*slot);
4613 *slot = decl;
4615 else
4616 /* If this is not the mergeable entity, it should not be in the
4617 table. If it is a non-global-module mergeable entity, it
4618 should be in the table. Global module entities could have been
4619 defined textually in the current TU and so might or might not
4620 be present. */
4621 gcc_assert (!is_duplicate (decl)
4622 ? !slot
4623 : (slot
4624 || !DECL_LANG_SPECIFIC (not_tmpl)
4625 || !DECL_MODULE_PURVIEW_P (not_tmpl)
4626 || (!DECL_MODULE_IMPORT_P (not_tmpl)
4627 && header_module_p ())));
4629 if (not_tmpl != decl)
4630 gcc_assert (!note_defs->find_slot (not_tmpl, NO_INSERT));
4631 #endif
4634 void
4635 trees_out::assert_definition (tree decl ATTRIBUTE_UNUSED)
4637 #if CHECKING_P
4638 tree *slot = note_defs->find_slot (decl, INSERT);
4639 gcc_assert (!*slot);
4640 *slot = decl;
4641 if (TREE_CODE (decl) == TEMPLATE_DECL)
4642 gcc_assert (!note_defs->find_slot (DECL_TEMPLATE_RESULT (decl), NO_INSERT));
4643 #endif
4646 /********************************************************************/
4647 static bool
4648 noisy_p ()
4650 if (quiet_flag)
4651 return false;
4653 pp_needs_newline (global_dc->printer) = true;
4654 diagnostic_set_last_function (global_dc, (diagnostic_info *) NULL);
4656 return true;
4659 /* Set the cmi repo. Strip trailing '/', '.' becomes NULL. */
4661 static void
4662 set_cmi_repo (const char *r)
4664 XDELETEVEC (cmi_repo);
4665 XDELETEVEC (cmi_path);
4666 cmi_path_alloc = 0;
4668 cmi_repo = NULL;
4669 cmi_repo_length = 0;
4671 if (!r || !r[0])
4672 return;
4674 size_t len = strlen (r);
4675 cmi_repo = XNEWVEC (char, len + 1);
4676 memcpy (cmi_repo, r, len + 1);
4678 if (len > 1 && IS_DIR_SEPARATOR (cmi_repo[len-1]))
4679 len--;
4680 if (len == 1 && cmi_repo[0] == '.')
4681 len--;
4682 cmi_repo[len] = 0;
4683 cmi_repo_length = len;
4686 /* TO is a repo-relative name. Provide one that we may use from where
4687 we are. */
4689 static const char *
4690 maybe_add_cmi_prefix (const char *to, size_t *len_p = NULL)
4692 size_t len = len_p || cmi_repo_length ? strlen (to) : 0;
4694 if (cmi_repo_length && !IS_ABSOLUTE_PATH (to))
4696 if (cmi_path_alloc < cmi_repo_length + len + 2)
4698 XDELETEVEC (cmi_path);
4699 cmi_path_alloc = cmi_repo_length + len * 2 + 2;
4700 cmi_path = XNEWVEC (char, cmi_path_alloc);
4702 memcpy (cmi_path, cmi_repo, cmi_repo_length);
4703 cmi_path[cmi_repo_length] = DIR_SEPARATOR;
4706 memcpy (&cmi_path[cmi_repo_length + 1], to, len + 1);
4707 len += cmi_repo_length + 1;
4708 to = cmi_path;
4711 if (len_p)
4712 *len_p = len;
4714 return to;
4717 /* Try and create the directories of PATH. */
4719 static void
4720 create_dirs (char *path)
4722 /* Try and create the missing directories. */
4723 for (char *base = path; *base; base++)
4724 if (IS_DIR_SEPARATOR (*base))
4726 char sep = *base;
4727 *base = 0;
4728 int failed = mkdir (path, S_IRWXU | S_IRWXG | S_IRWXO);
4729 dump () && dump ("Mkdir ('%s') errno:=%u", path, failed ? errno : 0);
4730 *base = sep;
4731 if (failed
4732 /* Maybe racing with another creator (of a *different*
4733 module). */
4734 && errno != EEXIST)
4735 break;
4739 /* Given a CLASSTYPE_DECL_LIST VALUE get the template friend decl,
4740 if that's what this is. */
4742 static tree
4743 friend_from_decl_list (tree frnd)
4745 tree res = frnd;
4747 if (TREE_CODE (frnd) != TEMPLATE_DECL)
4749 tree tmpl = NULL_TREE;
4750 if (TYPE_P (frnd))
4752 res = TYPE_NAME (frnd);
4753 if (CLASS_TYPE_P (frnd)
4754 && CLASSTYPE_TEMPLATE_INFO (frnd))
4755 tmpl = CLASSTYPE_TI_TEMPLATE (frnd);
4757 else if (DECL_TEMPLATE_INFO (frnd))
4759 tmpl = DECL_TI_TEMPLATE (frnd);
4760 if (TREE_CODE (tmpl) != TEMPLATE_DECL)
4761 tmpl = NULL_TREE;
4764 if (tmpl && DECL_TEMPLATE_RESULT (tmpl) == res)
4765 res = tmpl;
4768 return res;
4771 static tree
4772 find_enum_member (tree ctx, tree name)
4774 for (tree values = TYPE_VALUES (ctx);
4775 values; values = TREE_CHAIN (values))
4776 if (DECL_NAME (TREE_VALUE (values)) == name)
4777 return TREE_VALUE (values);
4779 return NULL_TREE;
4782 /********************************************************************/
4783 /* Instrumentation gathered writing bytes. */
4785 void
4786 bytes_out::instrument ()
4788 dump ("Wrote %u bytes in %u blocks", lengths[3], spans[3]);
4789 dump ("Wrote %u bits in %u bytes", lengths[0] + lengths[1], lengths[2]);
4790 for (unsigned ix = 0; ix < 2; ix++)
4791 dump (" %u %s spans of %R bits", spans[ix],
4792 ix ? "one" : "zero", lengths[ix], spans[ix]);
4793 dump (" %u blocks with %R bits padding", spans[2],
4794 lengths[2] * 8 - (lengths[0] + lengths[1]), spans[2]);
4797 /* Instrumentation gathered writing trees. */
4798 void
4799 trees_out::instrument ()
4801 if (dump (""))
4803 bytes_out::instrument ();
4804 dump ("Wrote:");
4805 dump (" %u decl trees", decl_val_count);
4806 dump (" %u other trees", tree_val_count);
4807 dump (" %u back references", back_ref_count);
4808 dump (" %u null trees", null_count);
4812 /* Setup and teardown for a tree walk. */
4814 void
4815 trees_out::begin ()
4817 gcc_assert (!streaming_p () || !tree_map.elements ());
4819 mark_trees ();
4820 if (streaming_p ())
4821 parent::begin ();
4824 unsigned
4825 trees_out::end (elf_out *sink, unsigned name, unsigned *crc_ptr)
4827 gcc_checking_assert (streaming_p ());
4829 unmark_trees ();
4830 return parent::end (sink, name, crc_ptr);
4833 void
4834 trees_out::end ()
4836 gcc_assert (!streaming_p ());
4838 unmark_trees ();
4839 /* Do not parent::end -- we weren't streaming. */
4842 void
4843 trees_out::mark_trees ()
4845 if (size_t size = tree_map.elements ())
4847 /* This isn't our first rodeo, destroy and recreate the
4848 tree_map. I'm a bad bad man. Use the previous size as a
4849 guess for the next one (so not all bad). */
4850 tree_map.~ptr_int_hash_map ();
4851 new (&tree_map) ptr_int_hash_map (size);
4854 /* Install the fixed trees, with +ve references. */
4855 unsigned limit = fixed_trees->length ();
4856 for (unsigned ix = 0; ix != limit; ix++)
4858 tree val = (*fixed_trees)[ix];
4859 bool existed = tree_map.put (val, ix + tag_fixed);
4860 gcc_checking_assert (!TREE_VISITED (val) && !existed);
4861 TREE_VISITED (val) = true;
4864 ref_num = 0;
4867 /* Unmark the trees we encountered */
4869 void
4870 trees_out::unmark_trees ()
4872 ptr_int_hash_map::iterator end (tree_map.end ());
4873 for (ptr_int_hash_map::iterator iter (tree_map.begin ()); iter != end; ++iter)
4875 tree node = reinterpret_cast<tree> ((*iter).first);
4876 int ref = (*iter).second;
4877 /* We should have visited the node, and converted its mergeable
4878 reference to a regular reference. */
4879 gcc_checking_assert (TREE_VISITED (node)
4880 && (ref <= tag_backref || ref >= tag_fixed));
4881 TREE_VISITED (node) = false;
4885 /* Mark DECL for by-value walking. We do this by inserting it into
4886 the tree map with a reference of zero. May be called multiple
4887 times on the same node. */
4889 void
4890 trees_out::mark_by_value (tree decl)
4892 gcc_checking_assert (DECL_P (decl)
4893 /* Enum consts are INTEGER_CSTS. */
4894 || TREE_CODE (decl) == INTEGER_CST
4895 || TREE_CODE (decl) == TREE_BINFO);
4897 if (TREE_VISITED (decl))
4898 /* Must already be forced or fixed. */
4899 gcc_checking_assert (*tree_map.get (decl) >= tag_value);
4900 else
4902 bool existed = tree_map.put (decl, tag_value);
4903 gcc_checking_assert (!existed);
4904 TREE_VISITED (decl) = true;
4909 trees_out::get_tag (tree t)
4911 gcc_checking_assert (TREE_VISITED (t));
4912 return *tree_map.get (t);
4915 /* Insert T into the map, return its tag number. */
4918 trees_out::insert (tree t, walk_kind walk)
4920 gcc_checking_assert (walk != WK_normal || !TREE_VISITED (t));
4921 int tag = --ref_num;
4922 bool existed;
4923 int &slot = tree_map.get_or_insert (t, &existed);
4924 gcc_checking_assert (TREE_VISITED (t) == existed
4925 && (!existed
4926 || (walk == WK_value && slot == tag_value)));
4927 TREE_VISITED (t) = true;
4928 slot = tag;
4930 return tag;
4933 /* Insert T into the backreference array. Return its back reference
4934 number. */
4937 trees_in::insert (tree t)
4939 gcc_checking_assert (t || get_overrun ());
4940 back_refs.safe_push (t);
4941 return -(int)back_refs.length ();
4944 /* A chained set of decls. */
4946 void
4947 trees_out::chained_decls (tree decls)
4949 for (; decls; decls = DECL_CHAIN (decls))
4951 if (VAR_OR_FUNCTION_DECL_P (decls)
4952 && DECL_LOCAL_DECL_P (decls))
4954 /* Make sure this is the first encounter, and mark for
4955 walk-by-value. */
4956 gcc_checking_assert (!TREE_VISITED (decls)
4957 && !DECL_TEMPLATE_INFO (decls));
4958 mark_by_value (decls);
4960 tree_node (decls);
4962 tree_node (NULL_TREE);
4965 tree
4966 trees_in::chained_decls ()
4968 tree decls = NULL_TREE;
4969 for (tree *chain = &decls;;)
4970 if (tree decl = tree_node ())
4972 if (!DECL_P (decl) || DECL_CHAIN (decl))
4974 set_overrun ();
4975 break;
4977 *chain = decl;
4978 chain = &DECL_CHAIN (decl);
4980 else
4981 break;
4983 return decls;
4986 /* A vector of decls following DECL_CHAIN. */
4988 void
4989 trees_out::vec_chained_decls (tree decls)
4991 if (streaming_p ())
4993 unsigned len = 0;
4995 for (tree decl = decls; decl; decl = DECL_CHAIN (decl))
4996 len++;
4997 u (len);
5000 for (tree decl = decls; decl; decl = DECL_CHAIN (decl))
5002 if (DECL_IMPLICIT_TYPEDEF_P (decl)
5003 && TYPE_NAME (TREE_TYPE (decl)) != decl)
5004 /* An anonynmous struct with a typedef name. An odd thing to
5005 write. */
5006 tree_node (NULL_TREE);
5007 else
5008 tree_node (decl);
5012 vec<tree, va_heap> *
5013 trees_in::vec_chained_decls ()
5015 vec<tree, va_heap> *v = NULL;
5017 if (unsigned len = u ())
5019 vec_alloc (v, len);
5021 for (unsigned ix = 0; ix < len; ix++)
5023 tree decl = tree_node ();
5024 if (decl && !DECL_P (decl))
5026 set_overrun ();
5027 break;
5029 v->quick_push (decl);
5032 if (get_overrun ())
5034 vec_free (v);
5035 v = NULL;
5039 return v;
5042 /* A vector of trees. */
5044 void
5045 trees_out::tree_vec (vec<tree, va_gc> *v)
5047 unsigned len = vec_safe_length (v);
5048 if (streaming_p ())
5049 u (len);
5050 for (unsigned ix = 0; ix != len; ix++)
5051 tree_node ((*v)[ix]);
5054 vec<tree, va_gc> *
5055 trees_in::tree_vec ()
5057 vec<tree, va_gc> *v = NULL;
5058 if (unsigned len = u ())
5060 vec_alloc (v, len);
5061 for (unsigned ix = 0; ix != len; ix++)
5062 v->quick_push (tree_node ());
5064 return v;
5067 /* A vector of tree pairs. */
5069 void
5070 trees_out::tree_pair_vec (vec<tree_pair_s, va_gc> *v)
5072 unsigned len = vec_safe_length (v);
5073 if (streaming_p ())
5074 u (len);
5075 if (len)
5076 for (unsigned ix = 0; ix != len; ix++)
5078 tree_pair_s const &s = (*v)[ix];
5079 tree_node (s.purpose);
5080 tree_node (s.value);
5084 vec<tree_pair_s, va_gc> *
5085 trees_in::tree_pair_vec ()
5087 vec<tree_pair_s, va_gc> *v = NULL;
5088 if (unsigned len = u ())
5090 vec_alloc (v, len);
5091 for (unsigned ix = 0; ix != len; ix++)
5093 tree_pair_s s;
5094 s.purpose = tree_node ();
5095 s.value = tree_node ();
5096 v->quick_push (s);
5099 return v;
5102 void
5103 trees_out::tree_list (tree list, bool has_purpose)
5105 for (; list; list = TREE_CHAIN (list))
5107 gcc_checking_assert (TREE_VALUE (list));
5108 tree_node (TREE_VALUE (list));
5109 if (has_purpose)
5110 tree_node (TREE_PURPOSE (list));
5112 tree_node (NULL_TREE);
5115 tree
5116 trees_in::tree_list (bool has_purpose)
5118 tree res = NULL_TREE;
5120 for (tree *chain = &res; tree value = tree_node ();
5121 chain = &TREE_CHAIN (*chain))
5123 tree purpose = has_purpose ? tree_node () : NULL_TREE;
5124 *chain = build_tree_list (purpose, value);
5127 return res;
5129 /* Start tree write. Write information to allocate the receiving
5130 node. */
5132 void
5133 trees_out::start (tree t, bool code_streamed)
5135 if (TYPE_P (t))
5137 enum tree_code code = TREE_CODE (t);
5138 gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
5139 /* All these types are TYPE_NON_COMMON. */
5140 gcc_checking_assert (code == RECORD_TYPE
5141 || code == UNION_TYPE
5142 || code == ENUMERAL_TYPE
5143 || code == TEMPLATE_TYPE_PARM
5144 || code == TEMPLATE_TEMPLATE_PARM
5145 || code == BOUND_TEMPLATE_TEMPLATE_PARM);
5148 if (!code_streamed)
5149 u (TREE_CODE (t));
5151 switch (TREE_CODE (t))
5153 default:
5154 if (VL_EXP_CLASS_P (t))
5155 u (VL_EXP_OPERAND_LENGTH (t));
5156 break;
5158 case INTEGER_CST:
5159 u (TREE_INT_CST_NUNITS (t));
5160 u (TREE_INT_CST_EXT_NUNITS (t));
5161 break;
5163 case OMP_CLAUSE:
5164 state->extensions |= SE_OPENMP;
5165 u (OMP_CLAUSE_CODE (t));
5166 break;
5168 case STRING_CST:
5169 str (TREE_STRING_POINTER (t), TREE_STRING_LENGTH (t));
5170 break;
5172 case VECTOR_CST:
5173 u (VECTOR_CST_LOG2_NPATTERNS (t));
5174 u (VECTOR_CST_NELTS_PER_PATTERN (t));
5175 break;
5177 case TREE_BINFO:
5178 u (BINFO_N_BASE_BINFOS (t));
5179 break;
5181 case TREE_VEC:
5182 u (TREE_VEC_LENGTH (t));
5183 break;
5185 case FIXED_CST:
5186 case POLY_INT_CST:
5187 gcc_unreachable (); /* Not supported in C++. */
5188 break;
5190 case IDENTIFIER_NODE:
5191 case SSA_NAME:
5192 case TARGET_MEM_REF:
5193 case TRANSLATION_UNIT_DECL:
5194 /* We shouldn't meet these. */
5195 gcc_unreachable ();
5196 break;
5200 /* Start tree read. Allocate the receiving node. */
5202 tree
5203 trees_in::start (unsigned code)
5205 tree t = NULL_TREE;
5207 if (!code)
5208 code = u ();
5210 switch (code)
5212 default:
5213 if (code >= MAX_TREE_CODES)
5215 fail:
5216 set_overrun ();
5217 return NULL_TREE;
5219 else if (TREE_CODE_CLASS (code) == tcc_vl_exp)
5221 unsigned ops = u ();
5222 t = build_vl_exp (tree_code (code), ops);
5224 else
5225 t = make_node (tree_code (code));
5226 break;
5228 case INTEGER_CST:
5230 unsigned n = u ();
5231 unsigned e = u ();
5232 t = make_int_cst (n, e);
5234 break;
5236 case OMP_CLAUSE:
5238 if (!(state->extensions & SE_OPENMP))
5239 goto fail;
5241 unsigned omp_code = u ();
5242 t = build_omp_clause (UNKNOWN_LOCATION, omp_clause_code (omp_code));
5244 break;
5246 case STRING_CST:
5248 size_t l;
5249 const char *chars = str (&l);
5250 t = build_string (l, chars);
5252 break;
5254 case VECTOR_CST:
5256 unsigned log2_npats = u ();
5257 unsigned elts_per = u ();
5258 t = make_vector (log2_npats, elts_per);
5260 break;
5262 case TREE_BINFO:
5263 t = make_tree_binfo (u ());
5264 break;
5266 case TREE_VEC:
5267 t = make_tree_vec (u ());
5268 break;
5270 case FIXED_CST:
5271 case IDENTIFIER_NODE:
5272 case POLY_INT_CST:
5273 case SSA_NAME:
5274 case TARGET_MEM_REF:
5275 case TRANSLATION_UNIT_DECL:
5276 goto fail;
5279 return t;
5282 /* The structure streamers access the raw fields, because the
5283 alternative, of using the accessor macros can require using
5284 different accessors for the same underlying field, depending on the
5285 tree code. That's both confusing and annoying. */
5287 /* Read & write the core boolean flags. */
5289 void
5290 trees_out::core_bools (tree t)
5292 #define WB(X) (b (X))
5293 tree_code code = TREE_CODE (t);
5295 WB (t->base.side_effects_flag);
5296 WB (t->base.constant_flag);
5297 WB (t->base.addressable_flag);
5298 WB (t->base.volatile_flag);
5299 WB (t->base.readonly_flag);
5300 /* base.asm_written_flag is a property of the current TU's use of
5301 this decl. */
5302 WB (t->base.nowarning_flag);
5303 /* base.visited read as zero (it's set for writer, because that's
5304 how we mark nodes). */
5305 /* base.used_flag is not streamed. Readers may set TREE_USED of
5306 decls they use. */
5307 WB (t->base.nothrow_flag);
5308 WB (t->base.static_flag);
5309 if (TREE_CODE_CLASS (code) != tcc_type)
5310 /* This is TYPE_CACHED_VALUES_P for types. */
5311 WB (t->base.public_flag);
5312 WB (t->base.private_flag);
5313 WB (t->base.protected_flag);
5314 WB (t->base.deprecated_flag);
5315 WB (t->base.default_def_flag);
5317 switch (code)
5319 case CALL_EXPR:
5320 case INTEGER_CST:
5321 case SSA_NAME:
5322 case TARGET_MEM_REF:
5323 case TREE_VEC:
5324 /* These use different base.u fields. */
5325 break;
5327 default:
5328 WB (t->base.u.bits.lang_flag_0);
5329 bool flag_1 = t->base.u.bits.lang_flag_1;
5330 if (!flag_1)
5332 else if (code == TEMPLATE_INFO)
5333 /* This is TI_PENDING_TEMPLATE_FLAG, not relevant to reader. */
5334 flag_1 = false;
5335 else if (code == VAR_DECL)
5337 /* This is DECL_INITIALIZED_P. */
5338 if (TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
5339 /* We'll set this when reading the definition. */
5340 flag_1 = false;
5342 WB (flag_1);
5343 WB (t->base.u.bits.lang_flag_2);
5344 WB (t->base.u.bits.lang_flag_3);
5345 WB (t->base.u.bits.lang_flag_4);
5346 WB (t->base.u.bits.lang_flag_5);
5347 WB (t->base.u.bits.lang_flag_6);
5348 WB (t->base.u.bits.saturating_flag);
5349 WB (t->base.u.bits.unsigned_flag);
5350 WB (t->base.u.bits.packed_flag);
5351 WB (t->base.u.bits.user_align);
5352 WB (t->base.u.bits.nameless_flag);
5353 WB (t->base.u.bits.atomic_flag);
5354 break;
5357 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
5359 WB (t->type_common.no_force_blk_flag);
5360 WB (t->type_common.needs_constructing_flag);
5361 WB (t->type_common.transparent_aggr_flag);
5362 WB (t->type_common.restrict_flag);
5363 WB (t->type_common.string_flag);
5364 WB (t->type_common.lang_flag_0);
5365 WB (t->type_common.lang_flag_1);
5366 WB (t->type_common.lang_flag_2);
5367 WB (t->type_common.lang_flag_3);
5368 WB (t->type_common.lang_flag_4);
5369 WB (t->type_common.lang_flag_5);
5370 WB (t->type_common.lang_flag_6);
5371 WB (t->type_common.typeless_storage);
5374 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5376 WB (t->decl_common.nonlocal_flag);
5377 WB (t->decl_common.virtual_flag);
5378 WB (t->decl_common.ignored_flag);
5379 WB (t->decl_common.abstract_flag);
5380 WB (t->decl_common.artificial_flag);
5381 WB (t->decl_common.preserve_flag);
5382 WB (t->decl_common.debug_expr_is_from);
5383 WB (t->decl_common.lang_flag_0);
5384 WB (t->decl_common.lang_flag_1);
5385 WB (t->decl_common.lang_flag_2);
5386 WB (t->decl_common.lang_flag_3);
5387 WB (t->decl_common.lang_flag_4);
5388 WB (t->decl_common.lang_flag_5);
5389 WB (t->decl_common.lang_flag_6);
5390 WB (t->decl_common.lang_flag_7);
5391 WB (t->decl_common.lang_flag_8);
5392 WB (t->decl_common.decl_flag_0);
5395 /* DECL_EXTERNAL -> decl_flag_1
5396 == it is defined elsewhere
5397 DECL_NOT_REALLY_EXTERN -> base.not_really_extern
5398 == that was a lie, it is here */
5400 bool is_external = t->decl_common.decl_flag_1;
5401 if (!is_external)
5402 /* decl_flag_1 is DECL_EXTERNAL. Things we emit here, might
5403 well be external from the POV of an importer. */
5404 // FIXME: Do we need to know if this is a TEMPLATE_RESULT --
5405 // a flag from the caller?
5406 switch (code)
5408 default:
5409 break;
5411 case VAR_DECL:
5412 if (TREE_PUBLIC (t)
5413 && !(TREE_STATIC (t)
5414 && DECL_FUNCTION_SCOPE_P (t)
5415 && DECL_DECLARED_INLINE_P (DECL_CONTEXT (t)))
5416 && !DECL_VAR_DECLARED_INLINE_P (t))
5417 is_external = true;
5418 break;
5420 case FUNCTION_DECL:
5421 if (TREE_PUBLIC (t)
5422 && !DECL_DECLARED_INLINE_P (t))
5423 is_external = true;
5424 break;
5426 WB (is_external);
5429 WB (t->decl_common.decl_flag_2);
5430 WB (t->decl_common.decl_flag_3);
5431 WB (t->decl_common.not_gimple_reg_flag);
5432 WB (t->decl_common.decl_by_reference_flag);
5433 WB (t->decl_common.decl_read_flag);
5434 WB (t->decl_common.decl_nonshareable_flag);
5435 WB (t->decl_common.decl_not_flexarray);
5438 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
5440 WB (t->decl_with_vis.defer_output);
5441 WB (t->decl_with_vis.hard_register);
5442 WB (t->decl_with_vis.common_flag);
5443 WB (t->decl_with_vis.in_text_section);
5444 WB (t->decl_with_vis.in_constant_pool);
5445 WB (t->decl_with_vis.dllimport_flag);
5446 WB (t->decl_with_vis.weak_flag);
5447 WB (t->decl_with_vis.seen_in_bind_expr);
5448 WB (t->decl_with_vis.comdat_flag);
5449 WB (t->decl_with_vis.visibility_specified);
5450 WB (t->decl_with_vis.init_priority_p);
5451 WB (t->decl_with_vis.shadowed_for_var_p);
5452 WB (t->decl_with_vis.cxx_constructor);
5453 WB (t->decl_with_vis.cxx_destructor);
5454 WB (t->decl_with_vis.final);
5455 WB (t->decl_with_vis.regdecl_flag);
5458 if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
5460 WB (t->function_decl.static_ctor_flag);
5461 WB (t->function_decl.static_dtor_flag);
5462 WB (t->function_decl.uninlinable);
5463 WB (t->function_decl.possibly_inlined);
5464 WB (t->function_decl.novops_flag);
5465 WB (t->function_decl.returns_twice_flag);
5466 WB (t->function_decl.malloc_flag);
5467 WB (t->function_decl.declared_inline_flag);
5468 WB (t->function_decl.no_inline_warning_flag);
5469 WB (t->function_decl.no_instrument_function_entry_exit);
5470 WB (t->function_decl.no_limit_stack);
5471 WB (t->function_decl.disregard_inline_limits);
5472 WB (t->function_decl.pure_flag);
5473 WB (t->function_decl.looping_const_or_pure_flag);
5475 WB (t->function_decl.has_debug_args_flag);
5476 WB (t->function_decl.versioned_function);
5478 /* decl_type is a (misnamed) 2 bit discriminator. */
5479 unsigned kind = t->function_decl.decl_type;
5480 WB ((kind >> 0) & 1);
5481 WB ((kind >> 1) & 1);
5483 #undef WB
5486 bool
5487 trees_in::core_bools (tree t)
5489 #define RB(X) ((X) = b ())
5490 tree_code code = TREE_CODE (t);
5492 RB (t->base.side_effects_flag);
5493 RB (t->base.constant_flag);
5494 RB (t->base.addressable_flag);
5495 RB (t->base.volatile_flag);
5496 RB (t->base.readonly_flag);
5497 /* base.asm_written_flag is not streamed. */
5498 RB (t->base.nowarning_flag);
5499 /* base.visited is not streamed. */
5500 /* base.used_flag is not streamed. */
5501 RB (t->base.nothrow_flag);
5502 RB (t->base.static_flag);
5503 if (TREE_CODE_CLASS (code) != tcc_type)
5504 RB (t->base.public_flag);
5505 RB (t->base.private_flag);
5506 RB (t->base.protected_flag);
5507 RB (t->base.deprecated_flag);
5508 RB (t->base.default_def_flag);
5510 switch (code)
5512 case CALL_EXPR:
5513 case INTEGER_CST:
5514 case SSA_NAME:
5515 case TARGET_MEM_REF:
5516 case TREE_VEC:
5517 /* These use different base.u fields. */
5518 break;
5520 default:
5521 RB (t->base.u.bits.lang_flag_0);
5522 RB (t->base.u.bits.lang_flag_1);
5523 RB (t->base.u.bits.lang_flag_2);
5524 RB (t->base.u.bits.lang_flag_3);
5525 RB (t->base.u.bits.lang_flag_4);
5526 RB (t->base.u.bits.lang_flag_5);
5527 RB (t->base.u.bits.lang_flag_6);
5528 RB (t->base.u.bits.saturating_flag);
5529 RB (t->base.u.bits.unsigned_flag);
5530 RB (t->base.u.bits.packed_flag);
5531 RB (t->base.u.bits.user_align);
5532 RB (t->base.u.bits.nameless_flag);
5533 RB (t->base.u.bits.atomic_flag);
5534 break;
5537 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
5539 RB (t->type_common.no_force_blk_flag);
5540 RB (t->type_common.needs_constructing_flag);
5541 RB (t->type_common.transparent_aggr_flag);
5542 RB (t->type_common.restrict_flag);
5543 RB (t->type_common.string_flag);
5544 RB (t->type_common.lang_flag_0);
5545 RB (t->type_common.lang_flag_1);
5546 RB (t->type_common.lang_flag_2);
5547 RB (t->type_common.lang_flag_3);
5548 RB (t->type_common.lang_flag_4);
5549 RB (t->type_common.lang_flag_5);
5550 RB (t->type_common.lang_flag_6);
5551 RB (t->type_common.typeless_storage);
5554 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5556 RB (t->decl_common.nonlocal_flag);
5557 RB (t->decl_common.virtual_flag);
5558 RB (t->decl_common.ignored_flag);
5559 RB (t->decl_common.abstract_flag);
5560 RB (t->decl_common.artificial_flag);
5561 RB (t->decl_common.preserve_flag);
5562 RB (t->decl_common.debug_expr_is_from);
5563 RB (t->decl_common.lang_flag_0);
5564 RB (t->decl_common.lang_flag_1);
5565 RB (t->decl_common.lang_flag_2);
5566 RB (t->decl_common.lang_flag_3);
5567 RB (t->decl_common.lang_flag_4);
5568 RB (t->decl_common.lang_flag_5);
5569 RB (t->decl_common.lang_flag_6);
5570 RB (t->decl_common.lang_flag_7);
5571 RB (t->decl_common.lang_flag_8);
5572 RB (t->decl_common.decl_flag_0);
5573 RB (t->decl_common.decl_flag_1);
5574 RB (t->decl_common.decl_flag_2);
5575 RB (t->decl_common.decl_flag_3);
5576 RB (t->decl_common.not_gimple_reg_flag);
5577 RB (t->decl_common.decl_by_reference_flag);
5578 RB (t->decl_common.decl_read_flag);
5579 RB (t->decl_common.decl_nonshareable_flag);
5580 RB (t->decl_common.decl_not_flexarray);
5583 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
5585 RB (t->decl_with_vis.defer_output);
5586 RB (t->decl_with_vis.hard_register);
5587 RB (t->decl_with_vis.common_flag);
5588 RB (t->decl_with_vis.in_text_section);
5589 RB (t->decl_with_vis.in_constant_pool);
5590 RB (t->decl_with_vis.dllimport_flag);
5591 RB (t->decl_with_vis.weak_flag);
5592 RB (t->decl_with_vis.seen_in_bind_expr);
5593 RB (t->decl_with_vis.comdat_flag);
5594 RB (t->decl_with_vis.visibility_specified);
5595 RB (t->decl_with_vis.init_priority_p);
5596 RB (t->decl_with_vis.shadowed_for_var_p);
5597 RB (t->decl_with_vis.cxx_constructor);
5598 RB (t->decl_with_vis.cxx_destructor);
5599 RB (t->decl_with_vis.final);
5600 RB (t->decl_with_vis.regdecl_flag);
5603 if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL))
5605 RB (t->function_decl.static_ctor_flag);
5606 RB (t->function_decl.static_dtor_flag);
5607 RB (t->function_decl.uninlinable);
5608 RB (t->function_decl.possibly_inlined);
5609 RB (t->function_decl.novops_flag);
5610 RB (t->function_decl.returns_twice_flag);
5611 RB (t->function_decl.malloc_flag);
5612 RB (t->function_decl.declared_inline_flag);
5613 RB (t->function_decl.no_inline_warning_flag);
5614 RB (t->function_decl.no_instrument_function_entry_exit);
5615 RB (t->function_decl.no_limit_stack);
5616 RB (t->function_decl.disregard_inline_limits);
5617 RB (t->function_decl.pure_flag);
5618 RB (t->function_decl.looping_const_or_pure_flag);
5620 RB (t->function_decl.has_debug_args_flag);
5621 RB (t->function_decl.versioned_function);
5623 /* decl_type is a (misnamed) 2 bit discriminator. */
5624 unsigned kind = 0;
5625 kind |= unsigned (b ()) << 0;
5626 kind |= unsigned (b ()) << 1;
5627 t->function_decl.decl_type = function_decl_type (kind);
5629 #undef RB
5630 return !get_overrun ();
5633 void
5634 trees_out::lang_decl_bools (tree t)
5636 #define WB(X) (b (X))
5637 const struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
5639 WB (lang->u.base.language == lang_cplusplus);
5640 WB ((lang->u.base.use_template >> 0) & 1);
5641 WB ((lang->u.base.use_template >> 1) & 1);
5642 /* Do not write lang->u.base.not_really_extern, importer will set
5643 when reading the definition (if any). */
5644 WB (lang->u.base.initialized_in_class);
5645 WB (lang->u.base.threadprivate_or_deleted_p);
5646 /* Do not write lang->u.base.anticipated_p, it is a property of the
5647 current TU. */
5648 WB (lang->u.base.friend_or_tls);
5649 WB (lang->u.base.unknown_bound_p);
5650 /* Do not write lang->u.base.odr_used, importer will recalculate if
5651 they do ODR use this decl. */
5652 WB (lang->u.base.concept_p);
5653 WB (lang->u.base.var_declared_inline_p);
5654 WB (lang->u.base.dependent_init_p);
5655 /* When building a header unit, everthing is marked as purview, (so
5656 we know which decls to write). But when we import them we do not
5657 want to mark them as in module purview. */
5658 WB (lang->u.base.module_purview_p && !header_module_p ());
5659 WB (lang->u.base.module_attach_p);
5660 if (VAR_OR_FUNCTION_DECL_P (t))
5661 WB (lang->u.base.module_keyed_decls_p);
5662 switch (lang->u.base.selector)
5664 default:
5665 gcc_unreachable ();
5667 case lds_fn: /* lang_decl_fn. */
5668 WB (lang->u.fn.global_ctor_p);
5669 WB (lang->u.fn.global_dtor_p);
5670 WB (lang->u.fn.static_function);
5671 WB (lang->u.fn.pure_virtual);
5672 WB (lang->u.fn.defaulted_p);
5673 WB (lang->u.fn.has_in_charge_parm_p);
5674 WB (lang->u.fn.has_vtt_parm_p);
5675 /* There shouldn't be a pending inline at this point. */
5676 gcc_assert (!lang->u.fn.pending_inline_p);
5677 WB (lang->u.fn.nonconverting);
5678 WB (lang->u.fn.thunk_p);
5679 WB (lang->u.fn.this_thunk_p);
5680 /* Do not stream lang->u.hidden_friend_p, it is a property of
5681 the TU. */
5682 WB (lang->u.fn.omp_declare_reduction_p);
5683 WB (lang->u.fn.has_dependent_explicit_spec_p);
5684 WB (lang->u.fn.immediate_fn_p);
5685 WB (lang->u.fn.maybe_deleted);
5686 /* We do not stream lang->u.fn.implicit_constexpr. */
5687 WB (lang->u.fn.escalated_p);
5688 WB (lang->u.fn.xobj_func);
5689 goto lds_min;
5691 case lds_decomp: /* lang_decl_decomp. */
5692 /* No bools. */
5693 goto lds_min;
5695 case lds_min: /* lang_decl_min. */
5696 lds_min:
5697 /* No bools. */
5698 break;
5700 case lds_ns: /* lang_decl_ns. */
5701 /* No bools. */
5702 break;
5704 case lds_parm: /* lang_decl_parm. */
5705 /* No bools. */
5706 break;
5708 #undef WB
5711 bool
5712 trees_in::lang_decl_bools (tree t)
5714 #define RB(X) ((X) = b ())
5715 struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
5717 lang->u.base.language = b () ? lang_cplusplus : lang_c;
5718 unsigned v;
5719 v = b () << 0;
5720 v |= b () << 1;
5721 lang->u.base.use_template = v;
5722 /* lang->u.base.not_really_extern is not streamed. */
5723 RB (lang->u.base.initialized_in_class);
5724 RB (lang->u.base.threadprivate_or_deleted_p);
5725 /* lang->u.base.anticipated_p is not streamed. */
5726 RB (lang->u.base.friend_or_tls);
5727 RB (lang->u.base.unknown_bound_p);
5728 /* lang->u.base.odr_used is not streamed. */
5729 RB (lang->u.base.concept_p);
5730 RB (lang->u.base.var_declared_inline_p);
5731 RB (lang->u.base.dependent_init_p);
5732 RB (lang->u.base.module_purview_p);
5733 RB (lang->u.base.module_attach_p);
5734 if (VAR_OR_FUNCTION_DECL_P (t))
5735 RB (lang->u.base.module_keyed_decls_p);
5736 switch (lang->u.base.selector)
5738 default:
5739 gcc_unreachable ();
5741 case lds_fn: /* lang_decl_fn. */
5742 RB (lang->u.fn.global_ctor_p);
5743 RB (lang->u.fn.global_dtor_p);
5744 RB (lang->u.fn.static_function);
5745 RB (lang->u.fn.pure_virtual);
5746 RB (lang->u.fn.defaulted_p);
5747 RB (lang->u.fn.has_in_charge_parm_p);
5748 RB (lang->u.fn.has_vtt_parm_p);
5749 RB (lang->u.fn.nonconverting);
5750 RB (lang->u.fn.thunk_p);
5751 RB (lang->u.fn.this_thunk_p);
5752 /* lang->u.fn.hidden_friend_p is not streamed. */
5753 RB (lang->u.fn.omp_declare_reduction_p);
5754 RB (lang->u.fn.has_dependent_explicit_spec_p);
5755 RB (lang->u.fn.immediate_fn_p);
5756 RB (lang->u.fn.maybe_deleted);
5757 /* We do not stream lang->u.fn.implicit_constexpr. */
5758 RB (lang->u.fn.escalated_p);
5759 RB (lang->u.fn.xobj_func);
5760 goto lds_min;
5762 case lds_decomp: /* lang_decl_decomp. */
5763 /* No bools. */
5764 goto lds_min;
5766 case lds_min: /* lang_decl_min. */
5767 lds_min:
5768 /* No bools. */
5769 break;
5771 case lds_ns: /* lang_decl_ns. */
5772 /* No bools. */
5773 break;
5775 case lds_parm: /* lang_decl_parm. */
5776 /* No bools. */
5777 break;
5779 #undef RB
5780 return !get_overrun ();
5783 void
5784 trees_out::lang_type_bools (tree t)
5786 #define WB(X) (b (X))
5787 const struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
5789 WB (lang->has_type_conversion);
5790 WB (lang->has_copy_ctor);
5791 WB (lang->has_default_ctor);
5792 WB (lang->const_needs_init);
5793 WB (lang->ref_needs_init);
5794 WB (lang->has_const_copy_assign);
5795 WB ((lang->use_template >> 0) & 1);
5796 WB ((lang->use_template >> 1) & 1);
5798 WB (lang->has_mutable);
5799 WB (lang->com_interface);
5800 WB (lang->non_pod_class);
5801 WB (lang->nearly_empty_p);
5802 WB (lang->user_align);
5803 WB (lang->has_copy_assign);
5804 WB (lang->has_new);
5805 WB (lang->has_array_new);
5807 WB ((lang->gets_delete >> 0) & 1);
5808 WB ((lang->gets_delete >> 1) & 1);
5809 // Interfaceness is recalculated upon reading. May have to revisit?
5810 // How do dllexport and dllimport interact across a module?
5811 // lang->interface_only
5812 // lang->interface_unknown
5813 WB (lang->contains_empty_class_p);
5814 WB (lang->anon_aggr);
5815 WB (lang->non_zero_init);
5816 WB (lang->empty_p);
5818 WB (lang->vec_new_uses_cookie);
5819 WB (lang->declared_class);
5820 WB (lang->diamond_shaped);
5821 WB (lang->repeated_base);
5822 gcc_assert (!lang->being_defined);
5823 // lang->debug_requested
5824 WB (lang->fields_readonly);
5825 WB (lang->ptrmemfunc_flag);
5827 WB (lang->lazy_default_ctor);
5828 WB (lang->lazy_copy_ctor);
5829 WB (lang->lazy_copy_assign);
5830 WB (lang->lazy_destructor);
5831 WB (lang->has_const_copy_ctor);
5832 WB (lang->has_complex_copy_ctor);
5833 WB (lang->has_complex_copy_assign);
5834 WB (lang->non_aggregate);
5836 WB (lang->has_complex_dflt);
5837 WB (lang->has_list_ctor);
5838 WB (lang->non_std_layout);
5839 WB (lang->is_literal);
5840 WB (lang->lazy_move_ctor);
5841 WB (lang->lazy_move_assign);
5842 WB (lang->has_complex_move_ctor);
5843 WB (lang->has_complex_move_assign);
5845 WB (lang->has_constexpr_ctor);
5846 WB (lang->unique_obj_representations);
5847 WB (lang->unique_obj_representations_set);
5848 #undef WB
5851 bool
5852 trees_in::lang_type_bools (tree t)
5854 #define RB(X) ((X) = b ())
5855 struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
5857 RB (lang->has_type_conversion);
5858 RB (lang->has_copy_ctor);
5859 RB (lang->has_default_ctor);
5860 RB (lang->const_needs_init);
5861 RB (lang->ref_needs_init);
5862 RB (lang->has_const_copy_assign);
5863 unsigned v;
5864 v = b () << 0;
5865 v |= b () << 1;
5866 lang->use_template = v;
5868 RB (lang->has_mutable);
5869 RB (lang->com_interface);
5870 RB (lang->non_pod_class);
5871 RB (lang->nearly_empty_p);
5872 RB (lang->user_align);
5873 RB (lang->has_copy_assign);
5874 RB (lang->has_new);
5875 RB (lang->has_array_new);
5877 v = b () << 0;
5878 v |= b () << 1;
5879 lang->gets_delete = v;
5880 // lang->interface_only
5881 // lang->interface_unknown
5882 lang->interface_unknown = true; // Redetermine interface
5883 RB (lang->contains_empty_class_p);
5884 RB (lang->anon_aggr);
5885 RB (lang->non_zero_init);
5886 RB (lang->empty_p);
5888 RB (lang->vec_new_uses_cookie);
5889 RB (lang->declared_class);
5890 RB (lang->diamond_shaped);
5891 RB (lang->repeated_base);
5892 gcc_assert (!lang->being_defined);
5893 gcc_assert (!lang->debug_requested);
5894 RB (lang->fields_readonly);
5895 RB (lang->ptrmemfunc_flag);
5897 RB (lang->lazy_default_ctor);
5898 RB (lang->lazy_copy_ctor);
5899 RB (lang->lazy_copy_assign);
5900 RB (lang->lazy_destructor);
5901 RB (lang->has_const_copy_ctor);
5902 RB (lang->has_complex_copy_ctor);
5903 RB (lang->has_complex_copy_assign);
5904 RB (lang->non_aggregate);
5906 RB (lang->has_complex_dflt);
5907 RB (lang->has_list_ctor);
5908 RB (lang->non_std_layout);
5909 RB (lang->is_literal);
5910 RB (lang->lazy_move_ctor);
5911 RB (lang->lazy_move_assign);
5912 RB (lang->has_complex_move_ctor);
5913 RB (lang->has_complex_move_assign);
5915 RB (lang->has_constexpr_ctor);
5916 RB (lang->unique_obj_representations);
5917 RB (lang->unique_obj_representations_set);
5918 #undef RB
5919 return !get_overrun ();
5922 /* Read & write the core values and pointers. */
5924 void
5925 trees_out::core_vals (tree t)
5927 #define WU(X) (u (X))
5928 #define WT(X) (tree_node (X))
5929 tree_code code = TREE_CODE (t);
5931 /* First by shape of the tree. */
5933 if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL))
5935 /* Write this early, for better log information. */
5936 WT (t->decl_minimal.name);
5937 if (!DECL_TEMPLATE_PARM_P (t))
5938 WT (t->decl_minimal.context);
5940 if (state)
5941 state->write_location (*this, t->decl_minimal.locus);
5944 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
5946 /* The only types we write also have TYPE_NON_COMMON. */
5947 gcc_checking_assert (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON));
5949 /* We only stream the main variant. */
5950 gcc_checking_assert (TYPE_MAIN_VARIANT (t) == t);
5952 /* Stream the name & context first, for better log information */
5953 WT (t->type_common.name);
5954 WT (t->type_common.context);
5956 /* By construction we want to make sure we have the canonical
5957 and main variants already in the type table, so emit them
5958 now. */
5959 WT (t->type_common.main_variant);
5961 tree canonical = t->type_common.canonical;
5962 if (canonical && DECL_TEMPLATE_PARM_P (TYPE_NAME (t)))
5963 /* We do not want to wander into different templates.
5964 Reconstructed on stream in. */
5965 canonical = t;
5966 WT (canonical);
5968 /* type_common.next_variant is internally manipulated. */
5969 /* type_common.pointer_to, type_common.reference_to. */
5971 if (streaming_p ())
5973 WU (t->type_common.precision);
5974 WU (t->type_common.contains_placeholder_bits);
5975 WU (t->type_common.mode);
5976 WU (t->type_common.align);
5979 if (!RECORD_OR_UNION_CODE_P (code))
5981 WT (t->type_common.size);
5982 WT (t->type_common.size_unit);
5984 WT (t->type_common.attributes);
5986 WT (t->type_common.common.chain); /* TYPE_STUB_DECL. */
5989 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
5991 if (streaming_p ())
5993 WU (t->decl_common.mode);
5994 WU (t->decl_common.off_align);
5995 WU (t->decl_common.align);
5998 /* For templates these hold instantiation (partial and/or
5999 specialization) information. */
6000 if (code != TEMPLATE_DECL)
6002 WT (t->decl_common.size);
6003 WT (t->decl_common.size_unit);
6006 WT (t->decl_common.attributes);
6007 // FIXME: Does this introduce cross-decl links? For instance
6008 // from instantiation to the template. If so, we'll need more
6009 // deduplication logic. I think we'll need to walk the blocks
6010 // of the owning function_decl's abstract origin in tandem, to
6011 // generate the locating data needed?
6012 WT (t->decl_common.abstract_origin);
6015 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
6017 WT (t->decl_with_vis.assembler_name);
6018 if (streaming_p ())
6019 WU (t->decl_with_vis.visibility);
6022 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON))
6024 if (code == ENUMERAL_TYPE)
6026 /* These fields get set even for opaque enums that lack a
6027 definition, so we stream them directly for each ENUMERAL_TYPE.
6028 We stream TYPE_VALUES as part of the definition. */
6029 WT (t->type_non_common.maxval);
6030 WT (t->type_non_common.minval);
6032 /* Records and unions hold FIELDS, VFIELD & BINFO on these
6033 things. */
6034 else if (!RECORD_OR_UNION_CODE_P (code))
6036 // FIXME: These are from tpl_parm_value's 'type' writing.
6037 // Perhaps it should just be doing them directly?
6038 gcc_checking_assert (code == TEMPLATE_TYPE_PARM
6039 || code == TEMPLATE_TEMPLATE_PARM
6040 || code == BOUND_TEMPLATE_TEMPLATE_PARM);
6041 gcc_checking_assert (!TYPE_CACHED_VALUES_P (t));
6042 WT (t->type_non_common.values);
6043 WT (t->type_non_common.maxval);
6044 WT (t->type_non_common.minval);
6047 WT (t->type_non_common.lang_1);
6050 if (CODE_CONTAINS_STRUCT (code, TS_EXP))
6052 if (state)
6053 state->write_location (*this, t->exp.locus);
6055 /* Walk in forward order, as (for instance) REQUIRES_EXPR has a
6056 bunch of unscoped parms on its first operand. It's safer to
6057 create those in order. */
6058 bool vl = TREE_CODE_CLASS (code) == tcc_vl_exp;
6059 for (unsigned limit = (vl ? VL_EXP_OPERAND_LENGTH (t)
6060 : TREE_OPERAND_LENGTH (t)),
6061 ix = unsigned (vl); ix != limit; ix++)
6062 WT (TREE_OPERAND (t, ix));
6064 else
6065 /* The CODE_CONTAINS tables were inaccurate when I started. */
6066 gcc_checking_assert (TREE_CODE_CLASS (code) != tcc_expression
6067 && TREE_CODE_CLASS (code) != tcc_binary
6068 && TREE_CODE_CLASS (code) != tcc_unary
6069 && TREE_CODE_CLASS (code) != tcc_reference
6070 && TREE_CODE_CLASS (code) != tcc_comparison
6071 && TREE_CODE_CLASS (code) != tcc_statement
6072 && TREE_CODE_CLASS (code) != tcc_vl_exp);
6074 /* Then by CODE. Special cases and/or 1:1 tree shape
6075 correspondance. */
6076 switch (code)
6078 default:
6079 break;
6081 case ARGUMENT_PACK_SELECT: /* Transient during instantiation. */
6082 case DEFERRED_PARSE: /* Expanded upon completion of
6083 outermost class. */
6084 case IDENTIFIER_NODE: /* Streamed specially. */
6085 case BINDING_VECTOR: /* Only in namespace-scope symbol
6086 table. */
6087 case SSA_NAME:
6088 case TRANSLATION_UNIT_DECL: /* There is only one, it is a
6089 global_tree. */
6090 case USERDEF_LITERAL: /* Expanded during parsing. */
6091 gcc_unreachable (); /* Should never meet. */
6093 /* Constants. */
6094 case COMPLEX_CST:
6095 WT (TREE_REALPART (t));
6096 WT (TREE_IMAGPART (t));
6097 break;
6099 case FIXED_CST:
6100 gcc_unreachable (); /* Not supported in C++. */
6102 case INTEGER_CST:
6103 if (streaming_p ())
6105 unsigned num = TREE_INT_CST_EXT_NUNITS (t);
6106 for (unsigned ix = 0; ix != num; ix++)
6107 wu (TREE_INT_CST_ELT (t, ix));
6109 break;
6111 case POLY_INT_CST:
6112 gcc_unreachable (); /* Not supported in C++. */
6114 case REAL_CST:
6115 if (streaming_p ())
6116 buf (TREE_REAL_CST_PTR (t), sizeof (real_value));
6117 break;
6119 case STRING_CST:
6120 /* Streamed during start. */
6121 break;
6123 case VECTOR_CST:
6124 for (unsigned ix = vector_cst_encoded_nelts (t); ix--;)
6125 WT (VECTOR_CST_ENCODED_ELT (t, ix));
6126 break;
6128 /* Decls. */
6129 case VAR_DECL:
6130 if (DECL_CONTEXT (t)
6131 && TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
6132 break;
6133 /* FALLTHROUGH */
6135 case RESULT_DECL:
6136 case PARM_DECL:
6137 if (DECL_HAS_VALUE_EXPR_P (t))
6138 WT (DECL_VALUE_EXPR (t));
6139 /* FALLTHROUGH */
6141 case CONST_DECL:
6142 case IMPORTED_DECL:
6143 WT (t->decl_common.initial);
6144 break;
6146 case FIELD_DECL:
6147 WT (t->field_decl.offset);
6148 WT (t->field_decl.bit_field_type);
6149 WT (t->field_decl.qualifier); /* bitfield unit. */
6150 WT (t->field_decl.bit_offset);
6151 WT (t->field_decl.fcontext);
6152 WT (t->decl_common.initial);
6153 break;
6155 case LABEL_DECL:
6156 if (streaming_p ())
6158 WU (t->label_decl.label_decl_uid);
6159 WU (t->label_decl.eh_landing_pad_nr);
6161 break;
6163 case FUNCTION_DECL:
6164 if (streaming_p ())
6166 /* Builtins can be streamed by value when a header declares
6167 them. */
6168 WU (DECL_BUILT_IN_CLASS (t));
6169 if (DECL_BUILT_IN_CLASS (t) != NOT_BUILT_IN)
6170 WU (DECL_UNCHECKED_FUNCTION_CODE (t));
6173 WT (t->function_decl.personality);
6174 WT (t->function_decl.function_specific_target);
6175 WT (t->function_decl.function_specific_optimization);
6176 WT (t->function_decl.vindex);
6178 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
6179 WT (lookup_explicit_specifier (t));
6180 break;
6182 case USING_DECL:
6183 /* USING_DECL_DECLS */
6184 WT (t->decl_common.initial);
6185 /* FALLTHROUGH */
6187 case TYPE_DECL:
6188 /* USING_DECL: USING_DECL_SCOPE */
6189 /* TYPE_DECL: DECL_ORIGINAL_TYPE */
6190 WT (t->decl_non_common.result);
6191 break;
6193 /* Miscellaneous common nodes. */
6194 case BLOCK:
6195 if (state)
6197 state->write_location (*this, t->block.locus);
6198 state->write_location (*this, t->block.end_locus);
6201 /* DECL_LOCAL_DECL_P decls are first encountered here and
6202 streamed by value. */
6203 chained_decls (t->block.vars);
6204 /* nonlocalized_vars is a middle-end thing. */
6205 WT (t->block.subblocks);
6206 WT (t->block.supercontext);
6207 // FIXME: As for decl's abstract_origin, does this introduce crosslinks?
6208 WT (t->block.abstract_origin);
6209 /* fragment_origin, fragment_chain are middle-end things. */
6210 WT (t->block.chain);
6211 /* nonlocalized_vars, block_num & die are middle endy/debug
6212 things. */
6213 break;
6215 case CALL_EXPR:
6216 if (streaming_p ())
6217 WU (t->base.u.ifn);
6218 break;
6220 case CONSTRUCTOR:
6221 // This must be streamed /after/ we've streamed the type,
6222 // because it can directly refer to elements of the type. Eg,
6223 // FIELD_DECLs of a RECORD_TYPE.
6224 break;
6226 case OMP_CLAUSE:
6228 /* The ompcode is serialized in start. */
6229 if (streaming_p ())
6230 WU (t->omp_clause.subcode.map_kind);
6231 if (state)
6232 state->write_location (*this, t->omp_clause.locus);
6234 unsigned len = omp_clause_num_ops[OMP_CLAUSE_CODE (t)];
6235 for (unsigned ix = 0; ix != len; ix++)
6236 WT (t->omp_clause.ops[ix]);
6238 break;
6240 case STATEMENT_LIST:
6241 for (tree stmt : tsi_range (t))
6242 if (stmt)
6243 WT (stmt);
6244 WT (NULL_TREE);
6245 break;
6247 case OPTIMIZATION_NODE:
6248 case TARGET_OPTION_NODE:
6249 // FIXME: Our representation for these two nodes is a cache of
6250 // the resulting set of options. Not a record of the options
6251 // that got changed by a particular attribute or pragma. Should
6252 // we record that, or should we record the diff from the command
6253 // line options? The latter seems the right behaviour, but is
6254 // (a) harder, and I guess could introduce strangeness if the
6255 // importer has set some incompatible set of optimization flags?
6256 gcc_unreachable ();
6257 break;
6259 case TREE_BINFO:
6261 WT (t->binfo.common.chain);
6262 WT (t->binfo.offset);
6263 WT (t->binfo.inheritance);
6264 WT (t->binfo.vptr_field);
6266 WT (t->binfo.vtable);
6267 WT (t->binfo.virtuals);
6268 WT (t->binfo.vtt_subvtt);
6269 WT (t->binfo.vtt_vptr);
6271 tree_vec (BINFO_BASE_ACCESSES (t));
6272 unsigned num = vec_safe_length (BINFO_BASE_ACCESSES (t));
6273 for (unsigned ix = 0; ix != num; ix++)
6274 WT (BINFO_BASE_BINFO (t, ix));
6276 break;
6278 case TREE_LIST:
6279 WT (t->list.purpose);
6280 WT (t->list.value);
6281 WT (t->list.common.chain);
6282 break;
6284 case TREE_VEC:
6285 for (unsigned ix = TREE_VEC_LENGTH (t); ix--;)
6286 WT (TREE_VEC_ELT (t, ix));
6287 /* We stash NON_DEFAULT_TEMPLATE_ARGS_COUNT on TREE_CHAIN! */
6288 gcc_checking_assert (!t->type_common.common.chain
6289 || (TREE_CODE (t->type_common.common.chain)
6290 == INTEGER_CST));
6291 WT (t->type_common.common.chain);
6292 break;
6294 /* C++-specific nodes ... */
6295 case BASELINK:
6296 WT (((lang_tree_node *)t)->baselink.binfo);
6297 WT (((lang_tree_node *)t)->baselink.functions);
6298 WT (((lang_tree_node *)t)->baselink.access_binfo);
6299 break;
6301 case CONSTRAINT_INFO:
6302 WT (((lang_tree_node *)t)->constraint_info.template_reqs);
6303 WT (((lang_tree_node *)t)->constraint_info.declarator_reqs);
6304 WT (((lang_tree_node *)t)->constraint_info.associated_constr);
6305 break;
6307 case DEFERRED_NOEXCEPT:
6308 WT (((lang_tree_node *)t)->deferred_noexcept.pattern);
6309 WT (((lang_tree_node *)t)->deferred_noexcept.args);
6310 break;
6312 case LAMBDA_EXPR:
6313 WT (((lang_tree_node *)t)->lambda_expression.capture_list);
6314 WT (((lang_tree_node *)t)->lambda_expression.this_capture);
6315 WT (((lang_tree_node *)t)->lambda_expression.extra_scope);
6316 /* pending_proxies is a parse-time thing. */
6317 gcc_assert (!((lang_tree_node *)t)->lambda_expression.pending_proxies);
6318 if (state)
6319 state->write_location
6320 (*this, ((lang_tree_node *)t)->lambda_expression.locus);
6321 if (streaming_p ())
6323 WU (((lang_tree_node *)t)->lambda_expression.default_capture_mode);
6324 WU (((lang_tree_node *)t)->lambda_expression.discriminator_scope);
6325 WU (((lang_tree_node *)t)->lambda_expression.discriminator_sig);
6327 break;
6329 case OVERLOAD:
6330 WT (((lang_tree_node *)t)->overload.function);
6331 WT (t->common.chain);
6332 break;
6334 case PTRMEM_CST:
6335 WT (((lang_tree_node *)t)->ptrmem.member);
6336 break;
6338 case STATIC_ASSERT:
6339 WT (((lang_tree_node *)t)->static_assertion.condition);
6340 WT (((lang_tree_node *)t)->static_assertion.message);
6341 if (state)
6342 state->write_location
6343 (*this, ((lang_tree_node *)t)->static_assertion.location);
6344 break;
6346 case TEMPLATE_DECL:
6347 /* Streamed with the template_decl node itself. */
6348 gcc_checking_assert
6349 (TREE_VISITED (((lang_tree_node *)t)->template_decl.arguments));
6350 gcc_checking_assert
6351 (TREE_VISITED (((lang_tree_node *)t)->template_decl.result)
6352 || dep_hash->find_dependency (t)->is_alias_tmpl_inst ());
6353 if (DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (t))
6354 WT (DECL_CHAIN (t));
6355 break;
6357 case TEMPLATE_INFO:
6359 WT (((lang_tree_node *)t)->template_info.tmpl);
6360 WT (((lang_tree_node *)t)->template_info.args);
6361 WT (((lang_tree_node *)t)->template_info.partial);
6363 const auto *ac = (((lang_tree_node *)t)
6364 ->template_info.deferred_access_checks);
6365 unsigned len = vec_safe_length (ac);
6366 if (streaming_p ())
6367 u (len);
6368 if (len)
6370 for (unsigned ix = 0; ix != len; ix++)
6372 const auto &m = (*ac)[ix];
6373 WT (m.binfo);
6374 WT (m.decl);
6375 WT (m.diag_decl);
6376 if (state)
6377 state->write_location (*this, m.loc);
6381 break;
6383 case TEMPLATE_PARM_INDEX:
6384 if (streaming_p ())
6386 WU (((lang_tree_node *)t)->tpi.index);
6387 WU (((lang_tree_node *)t)->tpi.level);
6388 WU (((lang_tree_node *)t)->tpi.orig_level);
6390 WT (((lang_tree_node *)t)->tpi.decl);
6391 /* TEMPLATE_PARM_DESCENDANTS (AKA TREE_CHAIN) is an internal
6392 cache, do not stream. */
6393 break;
6395 case TRAIT_EXPR:
6396 WT (((lang_tree_node *)t)->trait_expression.type1);
6397 WT (((lang_tree_node *)t)->trait_expression.type2);
6398 if (streaming_p ())
6399 WU (((lang_tree_node *)t)->trait_expression.kind);
6400 break;
6403 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
6405 /* We want to stream the type of a expression-like nodes /after/
6406 we've streamed the operands. The type often contains (bits
6407 of the) types of the operands, and with things like decltype
6408 and noexcept in play, we really want to stream the decls
6409 defining the type before we try and stream the type on its
6410 own. Otherwise we can find ourselves trying to read in a
6411 decl, when we're already partially reading in a component of
6412 its type. And that's bad. */
6413 tree type = t->typed.type;
6414 unsigned prec = 0;
6416 switch (code)
6418 default:
6419 break;
6421 case TEMPLATE_DECL:
6422 /* We fill in the template's type separately. */
6423 type = NULL_TREE;
6424 break;
6426 case TYPE_DECL:
6427 if (DECL_ORIGINAL_TYPE (t) && t == TYPE_NAME (type))
6428 /* This is a typedef. We set its type separately. */
6429 type = NULL_TREE;
6430 break;
6432 case ENUMERAL_TYPE:
6433 if (type && !ENUM_FIXED_UNDERLYING_TYPE_P (t))
6435 /* Type is a restricted range integer type derived from the
6436 integer_types. Find the right one. */
6437 prec = TYPE_PRECISION (type);
6438 tree name = DECL_NAME (TYPE_NAME (type));
6440 for (unsigned itk = itk_none; itk--;)
6441 if (integer_types[itk]
6442 && DECL_NAME (TYPE_NAME (integer_types[itk])) == name)
6444 type = integer_types[itk];
6445 break;
6447 gcc_assert (type != t->typed.type);
6449 break;
6452 WT (type);
6453 if (prec && streaming_p ())
6454 WU (prec);
6457 if (TREE_CODE (t) == CONSTRUCTOR)
6459 unsigned len = vec_safe_length (t->constructor.elts);
6460 if (streaming_p ())
6461 WU (len);
6462 if (len)
6463 for (unsigned ix = 0; ix != len; ix++)
6465 const constructor_elt &elt = (*t->constructor.elts)[ix];
6467 WT (elt.index);
6468 WT (elt.value);
6472 #undef WT
6473 #undef WU
6476 // Streaming in a reference to a decl can cause that decl to be
6477 // TREE_USED, which is the mark_used behaviour we need most of the
6478 // time. The trees_in::unused can be incremented to inhibit this,
6479 // which is at least needed for vtables.
6481 bool
6482 trees_in::core_vals (tree t)
6484 #define RU(X) ((X) = u ())
6485 #define RUC(T,X) ((X) = T (u ()))
6486 #define RT(X) ((X) = tree_node ())
6487 #define RTU(X) ((X) = tree_node (true))
6488 tree_code code = TREE_CODE (t);
6490 /* First by tree shape. */
6491 if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL))
6493 RT (t->decl_minimal.name);
6494 if (!DECL_TEMPLATE_PARM_P (t))
6495 RT (t->decl_minimal.context);
6497 /* Don't zap the locus just yet, we don't record it correctly
6498 and thus lose all location information. */
6499 t->decl_minimal.locus = state->read_location (*this);
6502 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON))
6504 RT (t->type_common.name);
6505 RT (t->type_common.context);
6507 RT (t->type_common.main_variant);
6508 RT (t->type_common.canonical);
6510 /* type_common.next_variant is internally manipulated. */
6511 /* type_common.pointer_to, type_common.reference_to. */
6513 RU (t->type_common.precision);
6514 RU (t->type_common.contains_placeholder_bits);
6515 RUC (machine_mode, t->type_common.mode);
6516 RU (t->type_common.align);
6518 if (!RECORD_OR_UNION_CODE_P (code))
6520 RT (t->type_common.size);
6521 RT (t->type_common.size_unit);
6523 RT (t->type_common.attributes);
6525 RT (t->type_common.common.chain); /* TYPE_STUB_DECL. */
6528 if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON))
6530 RUC (machine_mode, t->decl_common.mode);
6531 RU (t->decl_common.off_align);
6532 RU (t->decl_common.align);
6534 if (code != TEMPLATE_DECL)
6536 RT (t->decl_common.size);
6537 RT (t->decl_common.size_unit);
6540 RT (t->decl_common.attributes);
6541 RT (t->decl_common.abstract_origin);
6544 if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS))
6546 RT (t->decl_with_vis.assembler_name);
6547 RUC (symbol_visibility, t->decl_with_vis.visibility);
6550 if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON))
6552 if (code == ENUMERAL_TYPE)
6554 /* These fields get set even for opaque enums that lack a
6555 definition, so we stream them directly for each ENUMERAL_TYPE.
6556 We stream TYPE_VALUES as part of the definition. */
6557 RT (t->type_non_common.maxval);
6558 RT (t->type_non_common.minval);
6560 /* Records and unions hold FIELDS, VFIELD & BINFO on these
6561 things. */
6562 else if (!RECORD_OR_UNION_CODE_P (code))
6564 /* This is not clobbering TYPE_CACHED_VALUES, because this
6565 is a type that doesn't have any. */
6566 gcc_checking_assert (!TYPE_CACHED_VALUES_P (t));
6567 RT (t->type_non_common.values);
6568 RT (t->type_non_common.maxval);
6569 RT (t->type_non_common.minval);
6572 RT (t->type_non_common.lang_1);
6575 if (CODE_CONTAINS_STRUCT (code, TS_EXP))
6577 t->exp.locus = state->read_location (*this);
6579 bool vl = TREE_CODE_CLASS (code) == tcc_vl_exp;
6580 for (unsigned limit = (vl ? VL_EXP_OPERAND_LENGTH (t)
6581 : TREE_OPERAND_LENGTH (t)),
6582 ix = unsigned (vl); ix != limit; ix++)
6583 RTU (TREE_OPERAND (t, ix));
6586 /* Then by CODE. Special cases and/or 1:1 tree shape
6587 correspondance. */
6588 switch (code)
6590 default:
6591 break;
6593 case ARGUMENT_PACK_SELECT:
6594 case DEFERRED_PARSE:
6595 case IDENTIFIER_NODE:
6596 case BINDING_VECTOR:
6597 case SSA_NAME:
6598 case TRANSLATION_UNIT_DECL:
6599 case USERDEF_LITERAL:
6600 return false; /* Should never meet. */
6602 /* Constants. */
6603 case COMPLEX_CST:
6604 RT (TREE_REALPART (t));
6605 RT (TREE_IMAGPART (t));
6606 break;
6608 case FIXED_CST:
6609 /* Not suported in C++. */
6610 return false;
6612 case INTEGER_CST:
6614 unsigned num = TREE_INT_CST_EXT_NUNITS (t);
6615 for (unsigned ix = 0; ix != num; ix++)
6616 TREE_INT_CST_ELT (t, ix) = wu ();
6618 break;
6620 case POLY_INT_CST:
6621 /* Not suported in C++. */
6622 return false;
6624 case REAL_CST:
6625 if (const void *bytes = buf (sizeof (real_value)))
6626 memcpy (TREE_REAL_CST_PTR (t), bytes, sizeof (real_value));
6627 break;
6629 case STRING_CST:
6630 /* Streamed during start. */
6631 break;
6633 case VECTOR_CST:
6634 for (unsigned ix = vector_cst_encoded_nelts (t); ix--;)
6635 RT (VECTOR_CST_ENCODED_ELT (t, ix));
6636 break;
6638 /* Decls. */
6639 case VAR_DECL:
6640 if (DECL_CONTEXT (t)
6641 && TREE_CODE (DECL_CONTEXT (t)) != FUNCTION_DECL)
6642 break;
6643 /* FALLTHROUGH */
6645 case RESULT_DECL:
6646 case PARM_DECL:
6647 if (DECL_HAS_VALUE_EXPR_P (t))
6649 /* The DECL_VALUE hash table is a cache, thus if we're
6650 reading a duplicate (which we end up discarding), the
6651 value expr will also be cleaned up at the next gc. */
6652 tree val = tree_node ();
6653 SET_DECL_VALUE_EXPR (t, val);
6655 /* FALLTHROUGH */
6657 case CONST_DECL:
6658 case IMPORTED_DECL:
6659 RT (t->decl_common.initial);
6660 break;
6662 case FIELD_DECL:
6663 RT (t->field_decl.offset);
6664 RT (t->field_decl.bit_field_type);
6665 RT (t->field_decl.qualifier);
6666 RT (t->field_decl.bit_offset);
6667 RT (t->field_decl.fcontext);
6668 RT (t->decl_common.initial);
6669 break;
6671 case LABEL_DECL:
6672 RU (t->label_decl.label_decl_uid);
6673 RU (t->label_decl.eh_landing_pad_nr);
6674 break;
6676 case FUNCTION_DECL:
6678 unsigned bltin = u ();
6679 t->function_decl.built_in_class = built_in_class (bltin);
6680 if (bltin != NOT_BUILT_IN)
6682 bltin = u ();
6683 DECL_UNCHECKED_FUNCTION_CODE (t) = built_in_function (bltin);
6686 RT (t->function_decl.personality);
6687 RT (t->function_decl.function_specific_target);
6688 RT (t->function_decl.function_specific_optimization);
6689 RT (t->function_decl.vindex);
6691 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
6693 tree spec;
6694 RT (spec);
6695 store_explicit_specifier (t, spec);
6698 break;
6700 case USING_DECL:
6701 /* USING_DECL_DECLS */
6702 RT (t->decl_common.initial);
6703 /* FALLTHROUGH */
6705 case TYPE_DECL:
6706 /* USING_DECL: USING_DECL_SCOPE */
6707 /* TYPE_DECL: DECL_ORIGINAL_TYPE */
6708 RT (t->decl_non_common.result);
6709 break;
6711 /* Miscellaneous common nodes. */
6712 case BLOCK:
6713 t->block.locus = state->read_location (*this);
6714 t->block.end_locus = state->read_location (*this);
6715 t->block.vars = chained_decls ();
6716 /* nonlocalized_vars is middle-end. */
6717 RT (t->block.subblocks);
6718 RT (t->block.supercontext);
6719 RT (t->block.abstract_origin);
6720 /* fragment_origin, fragment_chain are middle-end. */
6721 RT (t->block.chain);
6722 /* nonlocalized_vars, block_num, die are middle endy/debug
6723 things. */
6724 break;
6726 case CALL_EXPR:
6727 RUC (internal_fn, t->base.u.ifn);
6728 break;
6730 case CONSTRUCTOR:
6731 // Streamed after the node's type.
6732 break;
6734 case OMP_CLAUSE:
6736 RU (t->omp_clause.subcode.map_kind);
6737 t->omp_clause.locus = state->read_location (*this);
6739 unsigned len = omp_clause_num_ops[OMP_CLAUSE_CODE (t)];
6740 for (unsigned ix = 0; ix != len; ix++)
6741 RT (t->omp_clause.ops[ix]);
6743 break;
6745 case STATEMENT_LIST:
6747 tree_stmt_iterator iter = tsi_start (t);
6748 for (tree stmt; RT (stmt);)
6749 tsi_link_after (&iter, stmt, TSI_CONTINUE_LINKING);
6751 break;
6753 case OPTIMIZATION_NODE:
6754 case TARGET_OPTION_NODE:
6755 /* Not yet implemented, see trees_out::core_vals. */
6756 gcc_unreachable ();
6757 break;
6759 case TREE_BINFO:
6760 RT (t->binfo.common.chain);
6761 RT (t->binfo.offset);
6762 RT (t->binfo.inheritance);
6763 RT (t->binfo.vptr_field);
6765 /* Do not mark the vtables as USED in the address expressions
6766 here. */
6767 unused++;
6768 RT (t->binfo.vtable);
6769 RT (t->binfo.virtuals);
6770 RT (t->binfo.vtt_subvtt);
6771 RT (t->binfo.vtt_vptr);
6772 unused--;
6774 BINFO_BASE_ACCESSES (t) = tree_vec ();
6775 if (!get_overrun ())
6777 unsigned num = vec_safe_length (BINFO_BASE_ACCESSES (t));
6778 for (unsigned ix = 0; ix != num; ix++)
6779 BINFO_BASE_APPEND (t, tree_node ());
6781 break;
6783 case TREE_LIST:
6784 RT (t->list.purpose);
6785 RT (t->list.value);
6786 RT (t->list.common.chain);
6787 break;
6789 case TREE_VEC:
6790 for (unsigned ix = TREE_VEC_LENGTH (t); ix--;)
6791 RT (TREE_VEC_ELT (t, ix));
6792 RT (t->type_common.common.chain);
6793 break;
6795 /* C++-specific nodes ... */
6796 case BASELINK:
6797 RT (((lang_tree_node *)t)->baselink.binfo);
6798 RTU (((lang_tree_node *)t)->baselink.functions);
6799 RT (((lang_tree_node *)t)->baselink.access_binfo);
6800 break;
6802 case CONSTRAINT_INFO:
6803 RT (((lang_tree_node *)t)->constraint_info.template_reqs);
6804 RT (((lang_tree_node *)t)->constraint_info.declarator_reqs);
6805 RT (((lang_tree_node *)t)->constraint_info.associated_constr);
6806 break;
6808 case DEFERRED_NOEXCEPT:
6809 RT (((lang_tree_node *)t)->deferred_noexcept.pattern);
6810 RT (((lang_tree_node *)t)->deferred_noexcept.args);
6811 break;
6813 case LAMBDA_EXPR:
6814 RT (((lang_tree_node *)t)->lambda_expression.capture_list);
6815 RT (((lang_tree_node *)t)->lambda_expression.this_capture);
6816 RT (((lang_tree_node *)t)->lambda_expression.extra_scope);
6817 /* lambda_expression.pending_proxies is NULL */
6818 ((lang_tree_node *)t)->lambda_expression.locus
6819 = state->read_location (*this);
6820 RUC (cp_lambda_default_capture_mode_type,
6821 ((lang_tree_node *)t)->lambda_expression.default_capture_mode);
6822 RU (((lang_tree_node *)t)->lambda_expression.discriminator_scope);
6823 RU (((lang_tree_node *)t)->lambda_expression.discriminator_sig);
6824 break;
6826 case OVERLOAD:
6827 RT (((lang_tree_node *)t)->overload.function);
6828 RT (t->common.chain);
6829 break;
6831 case PTRMEM_CST:
6832 RT (((lang_tree_node *)t)->ptrmem.member);
6833 break;
6835 case STATIC_ASSERT:
6836 RT (((lang_tree_node *)t)->static_assertion.condition);
6837 RT (((lang_tree_node *)t)->static_assertion.message);
6838 ((lang_tree_node *)t)->static_assertion.location
6839 = state->read_location (*this);
6840 break;
6842 case TEMPLATE_DECL:
6843 /* Streamed when reading the raw template decl itself. */
6844 gcc_assert (((lang_tree_node *)t)->template_decl.arguments);
6845 gcc_assert (((lang_tree_node *)t)->template_decl.result);
6846 if (DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (t))
6847 RT (DECL_CHAIN (t));
6848 break;
6850 case TEMPLATE_INFO:
6851 RT (((lang_tree_node *)t)->template_info.tmpl);
6852 RT (((lang_tree_node *)t)->template_info.args);
6853 RT (((lang_tree_node *)t)->template_info.partial);
6854 if (unsigned len = u ())
6856 auto &ac = (((lang_tree_node *)t)
6857 ->template_info.deferred_access_checks);
6858 vec_alloc (ac, len);
6859 for (unsigned ix = 0; ix != len; ix++)
6861 deferred_access_check m;
6863 RT (m.binfo);
6864 RT (m.decl);
6865 RT (m.diag_decl);
6866 m.loc = state->read_location (*this);
6867 ac->quick_push (m);
6870 break;
6872 case TEMPLATE_PARM_INDEX:
6873 RU (((lang_tree_node *)t)->tpi.index);
6874 RU (((lang_tree_node *)t)->tpi.level);
6875 RU (((lang_tree_node *)t)->tpi.orig_level);
6876 RT (((lang_tree_node *)t)->tpi.decl);
6877 break;
6879 case TRAIT_EXPR:
6880 RT (((lang_tree_node *)t)->trait_expression.type1);
6881 RT (((lang_tree_node *)t)->trait_expression.type2);
6882 RUC (cp_trait_kind, ((lang_tree_node *)t)->trait_expression.kind);
6883 break;
6886 if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
6888 tree type = tree_node ();
6890 if (type && code == ENUMERAL_TYPE && !ENUM_FIXED_UNDERLYING_TYPE_P (t))
6892 unsigned precision = u ();
6894 type = build_distinct_type_copy (type);
6895 TYPE_PRECISION (type) = precision;
6896 set_min_and_max_values_for_integral_type (type, precision,
6897 TYPE_SIGN (type));
6900 if (code != TEMPLATE_DECL)
6901 t->typed.type = type;
6904 if (TREE_CODE (t) == CONSTRUCTOR)
6905 if (unsigned len = u ())
6907 vec_alloc (t->constructor.elts, len);
6908 for (unsigned ix = 0; ix != len; ix++)
6910 constructor_elt elt;
6912 RT (elt.index);
6913 RTU (elt.value);
6914 t->constructor.elts->quick_push (elt);
6918 #undef RT
6919 #undef RM
6920 #undef RU
6921 return !get_overrun ();
6924 void
6925 trees_out::lang_decl_vals (tree t)
6927 const struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
6928 #define WU(X) (u (X))
6929 #define WT(X) (tree_node (X))
6930 /* Module index already written. */
6931 switch (lang->u.base.selector)
6933 default:
6934 gcc_unreachable ();
6936 case lds_fn: /* lang_decl_fn. */
6937 if (streaming_p ())
6939 if (DECL_NAME (t) && IDENTIFIER_OVL_OP_P (DECL_NAME (t)))
6940 WU (lang->u.fn.ovl_op_code);
6943 if (DECL_CLASS_SCOPE_P (t))
6944 WT (lang->u.fn.context);
6946 if (lang->u.fn.thunk_p)
6948 /* The thunked-to function. */
6949 WT (lang->u.fn.befriending_classes);
6950 if (streaming_p ())
6951 wi (lang->u.fn.u5.fixed_offset);
6953 else if (decl_tls_wrapper_p (t))
6954 /* The wrapped variable. */
6955 WT (lang->u.fn.befriending_classes);
6956 else
6957 WT (lang->u.fn.u5.cloned_function);
6959 if (FNDECL_USED_AUTO (t))
6960 WT (lang->u.fn.u.saved_auto_return_type);
6962 goto lds_min;
6964 case lds_decomp: /* lang_decl_decomp. */
6965 WT (lang->u.decomp.base);
6966 goto lds_min;
6968 case lds_min: /* lang_decl_min. */
6969 lds_min:
6970 WT (lang->u.min.template_info);
6972 tree access = lang->u.min.access;
6974 /* DECL_ACCESS needs to be maintained by the definition of the
6975 (derived) class that changes the access. The other users
6976 of DECL_ACCESS need to write it here. */
6977 if (!DECL_THUNK_P (t)
6978 && (DECL_CONTEXT (t) && TYPE_P (DECL_CONTEXT (t))))
6979 access = NULL_TREE;
6981 WT (access);
6983 break;
6985 case lds_ns: /* lang_decl_ns. */
6986 break;
6988 case lds_parm: /* lang_decl_parm. */
6989 if (streaming_p ())
6991 WU (lang->u.parm.level);
6992 WU (lang->u.parm.index);
6994 break;
6996 #undef WU
6997 #undef WT
7000 bool
7001 trees_in::lang_decl_vals (tree t)
7003 struct lang_decl *lang = DECL_LANG_SPECIFIC (t);
7004 #define RU(X) ((X) = u ())
7005 #define RT(X) ((X) = tree_node ())
7007 /* Module index already read. */
7008 switch (lang->u.base.selector)
7010 default:
7011 gcc_unreachable ();
7013 case lds_fn: /* lang_decl_fn. */
7014 if (DECL_NAME (t) && IDENTIFIER_OVL_OP_P (DECL_NAME (t)))
7016 unsigned code = u ();
7018 /* Check consistency. */
7019 if (code >= OVL_OP_MAX
7020 || (ovl_op_info[IDENTIFIER_ASSIGN_OP_P (DECL_NAME (t))][code]
7021 .ovl_op_code) == OVL_OP_ERROR_MARK)
7022 set_overrun ();
7023 else
7024 lang->u.fn.ovl_op_code = code;
7027 if (DECL_CLASS_SCOPE_P (t))
7028 RT (lang->u.fn.context);
7030 if (lang->u.fn.thunk_p)
7032 RT (lang->u.fn.befriending_classes);
7033 lang->u.fn.u5.fixed_offset = wi ();
7035 else if (decl_tls_wrapper_p (t))
7036 RT (lang->u.fn.befriending_classes);
7037 else
7038 RT (lang->u.fn.u5.cloned_function);
7040 if (FNDECL_USED_AUTO (t))
7041 RT (lang->u.fn.u.saved_auto_return_type);
7042 goto lds_min;
7044 case lds_decomp: /* lang_decl_decomp. */
7045 RT (lang->u.decomp.base);
7046 goto lds_min;
7048 case lds_min: /* lang_decl_min. */
7049 lds_min:
7050 RT (lang->u.min.template_info);
7051 RT (lang->u.min.access);
7052 break;
7054 case lds_ns: /* lang_decl_ns. */
7055 break;
7057 case lds_parm: /* lang_decl_parm. */
7058 RU (lang->u.parm.level);
7059 RU (lang->u.parm.index);
7060 break;
7062 #undef RU
7063 #undef RT
7064 return !get_overrun ();
7067 /* Most of the value contents of lang_type is streamed in
7068 define_class. */
7070 void
7071 trees_out::lang_type_vals (tree t)
7073 const struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
7074 #define WU(X) (u (X))
7075 #define WT(X) (tree_node (X))
7076 if (streaming_p ())
7077 WU (lang->align);
7078 #undef WU
7079 #undef WT
7082 bool
7083 trees_in::lang_type_vals (tree t)
7085 struct lang_type *lang = TYPE_LANG_SPECIFIC (t);
7086 #define RU(X) ((X) = u ())
7087 #define RT(X) ((X) = tree_node ())
7088 RU (lang->align);
7089 #undef RU
7090 #undef RT
7091 return !get_overrun ();
7094 /* Write out the bools of T, including information about any
7095 LANG_SPECIFIC information. Including allocation of any lang
7096 specific object. */
7098 void
7099 trees_out::tree_node_bools (tree t)
7101 gcc_checking_assert (streaming_p ());
7103 /* We should never stream a namespace. */
7104 gcc_checking_assert (TREE_CODE (t) != NAMESPACE_DECL
7105 || DECL_NAMESPACE_ALIAS (t));
7107 core_bools (t);
7109 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7111 case tcc_declaration:
7113 bool specific = DECL_LANG_SPECIFIC (t) != NULL;
7114 b (specific);
7115 if (specific && VAR_P (t))
7116 b (DECL_DECOMPOSITION_P (t));
7117 if (specific)
7118 lang_decl_bools (t);
7120 break;
7122 case tcc_type:
7124 bool specific = (TYPE_MAIN_VARIANT (t) == t
7125 && TYPE_LANG_SPECIFIC (t) != NULL);
7126 gcc_assert (TYPE_LANG_SPECIFIC (t)
7127 == TYPE_LANG_SPECIFIC (TYPE_MAIN_VARIANT (t)));
7129 b (specific);
7130 if (specific)
7131 lang_type_bools (t);
7133 break;
7135 default:
7136 break;
7139 bflush ();
7142 bool
7143 trees_in::tree_node_bools (tree t)
7145 bool ok = core_bools (t);
7147 if (ok)
7148 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7150 case tcc_declaration:
7151 if (b ())
7153 bool decomp = VAR_P (t) && b ();
7155 ok = maybe_add_lang_decl_raw (t, decomp);
7156 if (ok)
7157 ok = lang_decl_bools (t);
7159 break;
7161 case tcc_type:
7162 if (b ())
7164 ok = maybe_add_lang_type_raw (t);
7165 if (ok)
7166 ok = lang_type_bools (t);
7168 break;
7170 default:
7171 break;
7174 bflush ();
7175 if (!ok || get_overrun ())
7176 return false;
7178 return true;
7182 /* Write out the lang-specifc vals of node T. */
7184 void
7185 trees_out::lang_vals (tree t)
7187 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7189 case tcc_declaration:
7190 if (DECL_LANG_SPECIFIC (t))
7191 lang_decl_vals (t);
7192 break;
7194 case tcc_type:
7195 if (TYPE_MAIN_VARIANT (t) == t && TYPE_LANG_SPECIFIC (t))
7196 lang_type_vals (t);
7197 break;
7199 default:
7200 break;
7204 bool
7205 trees_in::lang_vals (tree t)
7207 bool ok = true;
7209 switch (TREE_CODE_CLASS (TREE_CODE (t)))
7211 case tcc_declaration:
7212 if (DECL_LANG_SPECIFIC (t))
7213 ok = lang_decl_vals (t);
7214 break;
7216 case tcc_type:
7217 if (TYPE_LANG_SPECIFIC (t))
7218 ok = lang_type_vals (t);
7219 else
7220 TYPE_LANG_SPECIFIC (t) = TYPE_LANG_SPECIFIC (TYPE_MAIN_VARIANT (t));
7221 break;
7223 default:
7224 break;
7227 return ok;
7230 /* Write out the value fields of node T. */
7232 void
7233 trees_out::tree_node_vals (tree t)
7235 core_vals (t);
7236 lang_vals (t);
7239 bool
7240 trees_in::tree_node_vals (tree t)
7242 bool ok = core_vals (t);
7243 if (ok)
7244 ok = lang_vals (t);
7246 return ok;
7250 /* If T is a back reference, fixed reference or NULL, write out its
7251 code and return WK_none. Otherwise return WK_value if we must write
7252 by value, or WK_normal otherwise. */
7254 walk_kind
7255 trees_out::ref_node (tree t)
7257 if (!t)
7259 if (streaming_p ())
7261 /* NULL_TREE -> tt_null. */
7262 null_count++;
7263 i (tt_null);
7265 return WK_none;
7268 if (!TREE_VISITED (t))
7269 return WK_normal;
7271 /* An already-visited tree. It must be in the map. */
7272 int val = get_tag (t);
7274 if (val == tag_value)
7275 /* An entry we should walk into. */
7276 return WK_value;
7278 const char *kind;
7280 if (val <= tag_backref)
7282 /* Back reference -> -ve number */
7283 if (streaming_p ())
7284 i (val);
7285 kind = "backref";
7287 else if (val >= tag_fixed)
7289 /* Fixed reference -> tt_fixed */
7290 val -= tag_fixed;
7291 if (streaming_p ())
7292 i (tt_fixed), u (val);
7293 kind = "fixed";
7296 if (streaming_p ())
7298 back_ref_count++;
7299 dump (dumper::TREE)
7300 && dump ("Wrote %s:%d %C:%N%S", kind, val, TREE_CODE (t), t, t);
7302 return WK_none;
7305 tree
7306 trees_in::back_ref (int tag)
7308 tree res = NULL_TREE;
7310 if (tag < 0 && unsigned (~tag) < back_refs.length ())
7311 res = back_refs[~tag];
7313 if (!res
7314 /* Checking TREE_CODE is a dereference, so we know this is not a
7315 wild pointer. Checking the code provides evidence we've not
7316 corrupted something. */
7317 || TREE_CODE (res) >= MAX_TREE_CODES)
7318 set_overrun ();
7319 else
7320 dump (dumper::TREE) && dump ("Read backref:%d found %C:%N%S", tag,
7321 TREE_CODE (res), res, res);
7322 return res;
7325 unsigned
7326 trees_out::add_indirect_tpl_parms (tree parms)
7328 unsigned len = 0;
7329 for (; parms; parms = TREE_CHAIN (parms), len++)
7331 if (TREE_VISITED (parms))
7332 break;
7334 int tag = insert (parms);
7335 if (streaming_p ())
7336 dump (dumper::TREE)
7337 && dump ("Indirect:%d template's parameter %u %C:%N",
7338 tag, len, TREE_CODE (parms), parms);
7341 if (streaming_p ())
7342 u (len);
7344 return len;
7347 unsigned
7348 trees_in::add_indirect_tpl_parms (tree parms)
7350 unsigned len = u ();
7351 for (unsigned ix = 0; ix != len; parms = TREE_CHAIN (parms), ix++)
7353 int tag = insert (parms);
7354 dump (dumper::TREE)
7355 && dump ("Indirect:%d template's parameter %u %C:%N",
7356 tag, ix, TREE_CODE (parms), parms);
7359 return len;
7362 /* We've just found DECL by name. Insert nodes that come with it, but
7363 cannot be found by name, so we'll not accidentally walk into them. */
7365 void
7366 trees_out::add_indirects (tree decl)
7368 unsigned count = 0;
7370 // FIXME:OPTIMIZATION We'll eventually want default fn parms of
7371 // templates and perhaps default template parms too. The former can
7372 // be referenced from instantiations (as they are lazily
7373 // instantiated). Also (deferred?) exception specifications of
7374 // templates. See the note about PARM_DECLs in trees_out::decl_node.
7375 tree inner = decl;
7376 if (TREE_CODE (decl) == TEMPLATE_DECL)
7378 count += add_indirect_tpl_parms (DECL_TEMPLATE_PARMS (decl));
7380 inner = DECL_TEMPLATE_RESULT (decl);
7381 int tag = insert (inner);
7382 if (streaming_p ())
7383 dump (dumper::TREE)
7384 && dump ("Indirect:%d template's result %C:%N",
7385 tag, TREE_CODE (inner), inner);
7386 count++;
7389 if (TREE_CODE (inner) == TYPE_DECL)
7391 /* Make sure the type is in the map too. Otherwise we get
7392 different RECORD_TYPEs for the same type, and things go
7393 south. */
7394 tree type = TREE_TYPE (inner);
7395 gcc_checking_assert (DECL_ORIGINAL_TYPE (inner)
7396 || TYPE_NAME (type) == inner);
7397 int tag = insert (type);
7398 if (streaming_p ())
7399 dump (dumper::TREE) && dump ("Indirect:%d decl's type %C:%N", tag,
7400 TREE_CODE (type), type);
7401 count++;
7404 if (streaming_p ())
7406 u (count);
7407 dump (dumper::TREE) && dump ("Inserted %u indirects", count);
7411 bool
7412 trees_in::add_indirects (tree decl)
7414 unsigned count = 0;
7416 tree inner = decl;
7417 if (TREE_CODE (inner) == TEMPLATE_DECL)
7419 count += add_indirect_tpl_parms (DECL_TEMPLATE_PARMS (decl));
7421 inner = DECL_TEMPLATE_RESULT (decl);
7422 int tag = insert (inner);
7423 dump (dumper::TREE)
7424 && dump ("Indirect:%d templates's result %C:%N", tag,
7425 TREE_CODE (inner), inner);
7426 count++;
7429 if (TREE_CODE (inner) == TYPE_DECL)
7431 tree type = TREE_TYPE (inner);
7432 gcc_checking_assert (DECL_ORIGINAL_TYPE (inner)
7433 || TYPE_NAME (type) == inner);
7434 int tag = insert (type);
7435 dump (dumper::TREE)
7436 && dump ("Indirect:%d decl's type %C:%N", tag, TREE_CODE (type), type);
7437 count++;
7440 dump (dumper::TREE) && dump ("Inserted %u indirects", count);
7441 return count == u ();
7444 /* Stream a template parameter. There are 4.5 kinds of parameter:
7445 a) Template - TEMPLATE_DECL->TYPE_DECL->TEMPLATE_TEMPLATE_PARM
7446 TEMPLATE_TYPE_PARM_INDEX TPI
7447 b) Type - TYPE_DECL->TEMPLATE_TYPE_PARM TEMPLATE_TYPE_PARM_INDEX TPI
7448 c.1) NonTYPE - PARM_DECL DECL_INITIAL TPI We meet this first
7449 c.2) NonTYPE - CONST_DECL DECL_INITIAL Same TPI
7450 d) BoundTemplate - TYPE_DECL->BOUND_TEMPLATE_TEMPLATE_PARM
7451 TEMPLATE_TYPE_PARM_INDEX->TPI
7452 TEMPLATE_TEMPLATE_PARM_INFO->TEMPLATE_INFO
7454 All of these point to a TEMPLATE_PARM_INDEX, and #B also has a TEMPLATE_INFO
7457 void
7458 trees_out::tpl_parm_value (tree parm)
7460 gcc_checking_assert (DECL_P (parm) && DECL_TEMPLATE_PARM_P (parm));
7462 int parm_tag = insert (parm);
7463 if (streaming_p ())
7465 i (tt_tpl_parm);
7466 dump (dumper::TREE) && dump ("Writing template parm:%d %C:%N",
7467 parm_tag, TREE_CODE (parm), parm);
7468 start (parm);
7469 tree_node_bools (parm);
7472 tree inner = parm;
7473 if (TREE_CODE (inner) == TEMPLATE_DECL)
7475 inner = DECL_TEMPLATE_RESULT (inner);
7476 int inner_tag = insert (inner);
7477 if (streaming_p ())
7479 dump (dumper::TREE) && dump ("Writing inner template parm:%d %C:%N",
7480 inner_tag, TREE_CODE (inner), inner);
7481 start (inner);
7482 tree_node_bools (inner);
7486 tree type = NULL_TREE;
7487 if (TREE_CODE (inner) == TYPE_DECL)
7489 type = TREE_TYPE (inner);
7490 int type_tag = insert (type);
7491 if (streaming_p ())
7493 dump (dumper::TREE) && dump ("Writing template parm type:%d %C:%N",
7494 type_tag, TREE_CODE (type), type);
7495 start (type);
7496 tree_node_bools (type);
7500 if (inner != parm)
7502 /* This is a template-template parameter. */
7503 unsigned tpl_levels = 0;
7504 tpl_header (parm, &tpl_levels);
7505 tpl_parms_fini (parm, tpl_levels);
7508 tree_node_vals (parm);
7509 if (inner != parm)
7510 tree_node_vals (inner);
7511 if (type)
7513 tree_node_vals (type);
7514 if (DECL_NAME (inner) == auto_identifier
7515 || DECL_NAME (inner) == decltype_auto_identifier)
7517 /* Placeholder auto. */
7518 tree_node (DECL_INITIAL (inner));
7519 tree_node (DECL_SIZE_UNIT (inner));
7523 if (streaming_p ())
7524 dump (dumper::TREE) && dump ("Wrote template parm:%d %C:%N",
7525 parm_tag, TREE_CODE (parm), parm);
7528 tree
7529 trees_in::tpl_parm_value ()
7531 tree parm = start ();
7532 if (!parm || !tree_node_bools (parm))
7533 return NULL_TREE;
7535 int parm_tag = insert (parm);
7536 dump (dumper::TREE) && dump ("Reading template parm:%d %C:%N",
7537 parm_tag, TREE_CODE (parm), parm);
7539 tree inner = parm;
7540 if (TREE_CODE (inner) == TEMPLATE_DECL)
7542 inner = start ();
7543 if (!inner || !tree_node_bools (inner))
7544 return NULL_TREE;
7545 int inner_tag = insert (inner);
7546 dump (dumper::TREE) && dump ("Reading inner template parm:%d %C:%N",
7547 inner_tag, TREE_CODE (inner), inner);
7548 DECL_TEMPLATE_RESULT (parm) = inner;
7551 tree type = NULL_TREE;
7552 if (TREE_CODE (inner) == TYPE_DECL)
7554 type = start ();
7555 if (!type || !tree_node_bools (type))
7556 return NULL_TREE;
7557 int type_tag = insert (type);
7558 dump (dumper::TREE) && dump ("Reading template parm type:%d %C:%N",
7559 type_tag, TREE_CODE (type), type);
7561 TREE_TYPE (inner) = TREE_TYPE (parm) = type;
7562 TYPE_NAME (type) = parm;
7565 if (inner != parm)
7567 /* A template template parameter. */
7568 unsigned tpl_levels = 0;
7569 tpl_header (parm, &tpl_levels);
7570 tpl_parms_fini (parm, tpl_levels);
7573 tree_node_vals (parm);
7574 if (inner != parm)
7575 tree_node_vals (inner);
7576 if (type)
7578 tree_node_vals (type);
7579 if (DECL_NAME (inner) == auto_identifier
7580 || DECL_NAME (inner) == decltype_auto_identifier)
7582 /* Placeholder auto. */
7583 DECL_INITIAL (inner) = tree_node ();
7584 DECL_SIZE_UNIT (inner) = tree_node ();
7586 if (TYPE_CANONICAL (type))
7588 gcc_checking_assert (TYPE_CANONICAL (type) == type);
7589 TYPE_CANONICAL (type) = canonical_type_parameter (type);
7593 dump (dumper::TREE) && dump ("Read template parm:%d %C:%N",
7594 parm_tag, TREE_CODE (parm), parm);
7596 return parm;
7599 void
7600 trees_out::install_entity (tree decl, depset *dep)
7602 gcc_checking_assert (streaming_p ());
7604 /* Write the entity index, so we can insert it as soon as we
7605 know this is new. */
7606 u (dep ? dep->cluster + 1 : 0);
7607 if (CHECKING_P && dep)
7609 /* Add it to the entity map, such that we can tell it is
7610 part of us. */
7611 bool existed;
7612 unsigned *slot = &entity_map->get_or_insert
7613 (DECL_UID (decl), &existed);
7614 if (existed)
7615 /* If it existed, it should match. */
7616 gcc_checking_assert (decl == (*entity_ary)[*slot]);
7617 *slot = ~dep->cluster;
7621 bool
7622 trees_in::install_entity (tree decl)
7624 unsigned entity_index = u ();
7625 if (!entity_index)
7626 return false;
7628 if (entity_index > state->entity_num)
7630 set_overrun ();
7631 return false;
7634 /* Insert the real decl into the entity ary. */
7635 unsigned ident = state->entity_lwm + entity_index - 1;
7636 (*entity_ary)[ident] = decl;
7638 /* And into the entity map, if it's not already there. */
7639 tree not_tmpl = STRIP_TEMPLATE (decl);
7640 if (!DECL_LANG_SPECIFIC (not_tmpl)
7641 || !DECL_MODULE_ENTITY_P (not_tmpl))
7643 retrofit_lang_decl (not_tmpl);
7644 DECL_MODULE_ENTITY_P (not_tmpl) = true;
7646 /* Insert into the entity hash (it cannot already be there). */
7647 bool existed;
7648 unsigned &slot = entity_map->get_or_insert (DECL_UID (decl), &existed);
7649 gcc_checking_assert (!existed);
7650 slot = ident;
7653 return true;
7656 static bool has_definition (tree decl);
7658 /* DECL is a decl node that must be written by value. DEP is the
7659 decl's depset. */
7661 void
7662 trees_out::decl_value (tree decl, depset *dep)
7664 /* We should not be writing clones or template parms. */
7665 gcc_checking_assert (DECL_P (decl)
7666 && !DECL_CLONED_FUNCTION_P (decl)
7667 && !DECL_TEMPLATE_PARM_P (decl));
7669 /* We should never be writing non-typedef ptrmemfuncs by value. */
7670 gcc_checking_assert (TREE_CODE (decl) != TYPE_DECL
7671 || DECL_ORIGINAL_TYPE (decl)
7672 || !TYPE_PTRMEMFUNC_P (TREE_TYPE (decl)));
7674 merge_kind mk = get_merge_kind (decl, dep);
7676 if (CHECKING_P)
7678 /* Never start in the middle of a template. */
7679 int use_tpl = -1;
7680 if (tree ti = node_template_info (decl, use_tpl))
7681 gcc_checking_assert (TREE_CODE (TI_TEMPLATE (ti)) == OVERLOAD
7682 || TREE_CODE (TI_TEMPLATE (ti)) == FIELD_DECL
7683 || (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti))
7684 != decl));
7687 if (streaming_p ())
7689 /* A new node -> tt_decl. */
7690 decl_val_count++;
7691 i (tt_decl);
7692 u (mk);
7693 start (decl);
7695 if (mk != MK_unique)
7697 if (!(mk & MK_template_mask) && !state->is_header ())
7699 /* Tell the importer whether this is a global module entity,
7700 or a module entity. This bool merges into the next block
7701 of bools. Sneaky. */
7702 tree o = get_originating_module_decl (decl);
7703 bool is_attached = false;
7705 tree not_tmpl = STRIP_TEMPLATE (o);
7706 if (DECL_LANG_SPECIFIC (not_tmpl)
7707 && DECL_MODULE_ATTACH_P (not_tmpl))
7708 is_attached = true;
7710 b (is_attached);
7712 b (dep && dep->has_defn ());
7714 tree_node_bools (decl);
7717 int tag = insert (decl, WK_value);
7718 if (streaming_p ())
7719 dump (dumper::TREE)
7720 && dump ("Writing %s:%d %C:%N%S", merge_kind_name[mk], tag,
7721 TREE_CODE (decl), decl, decl);
7723 tree inner = decl;
7724 int inner_tag = 0;
7725 if (TREE_CODE (decl) == TEMPLATE_DECL)
7727 inner = DECL_TEMPLATE_RESULT (decl);
7728 inner_tag = insert (inner, WK_value);
7730 if (streaming_p ())
7732 int code = TREE_CODE (inner);
7733 u (code);
7734 start (inner, true);
7735 tree_node_bools (inner);
7736 dump (dumper::TREE)
7737 && dump ("Writing %s:%d %C:%N%S", merge_kind_name[mk], inner_tag,
7738 TREE_CODE (inner), inner, inner);
7742 tree type = NULL_TREE;
7743 int type_tag = 0;
7744 tree stub_decl = NULL_TREE;
7745 int stub_tag = 0;
7746 if (TREE_CODE (inner) == TYPE_DECL)
7748 type = TREE_TYPE (inner);
7749 bool has_type = (type == TYPE_MAIN_VARIANT (type)
7750 && TYPE_NAME (type) == inner);
7752 if (streaming_p ())
7753 u (has_type ? TREE_CODE (type) : 0);
7755 if (has_type)
7757 type_tag = insert (type, WK_value);
7758 if (streaming_p ())
7760 start (type, true);
7761 tree_node_bools (type);
7762 dump (dumper::TREE)
7763 && dump ("Writing type:%d %C:%N", type_tag,
7764 TREE_CODE (type), type);
7767 stub_decl = TYPE_STUB_DECL (type);
7768 bool has_stub = inner != stub_decl;
7769 if (streaming_p ())
7770 u (has_stub ? TREE_CODE (stub_decl) : 0);
7771 if (has_stub)
7773 stub_tag = insert (stub_decl);
7774 if (streaming_p ())
7776 start (stub_decl, true);
7777 tree_node_bools (stub_decl);
7778 dump (dumper::TREE)
7779 && dump ("Writing stub_decl:%d %C:%N", stub_tag,
7780 TREE_CODE (stub_decl), stub_decl);
7783 else
7784 stub_decl = NULL_TREE;
7786 else
7787 /* Regular typedef. */
7788 type = NULL_TREE;
7791 /* Stream the container, we want it correctly canonicalized before
7792 we start emitting keys for this decl. */
7793 tree container = decl_container (decl);
7795 unsigned tpl_levels = 0;
7796 if (decl != inner)
7797 tpl_header (decl, &tpl_levels);
7798 if (TREE_CODE (inner) == FUNCTION_DECL)
7799 fn_parms_init (inner);
7801 /* Now write out the merging information, and then really
7802 install the tag values. */
7803 key_mergeable (tag, mk, decl, inner, container, dep);
7805 if (streaming_p ())
7806 dump (dumper::MERGE)
7807 && dump ("Wrote:%d's %s merge key %C:%N", tag,
7808 merge_kind_name[mk], TREE_CODE (decl), decl);
7810 if (TREE_CODE (inner) == FUNCTION_DECL)
7811 fn_parms_fini (inner);
7813 if (!is_key_order ())
7814 tree_node_vals (decl);
7816 if (inner_tag)
7818 if (!is_key_order ())
7819 tree_node_vals (inner);
7820 tpl_parms_fini (decl, tpl_levels);
7823 if (type && !is_key_order ())
7825 tree_node_vals (type);
7826 if (stub_decl)
7827 tree_node_vals (stub_decl);
7830 if (!is_key_order ())
7832 if (mk & MK_template_mask
7833 || mk == MK_partial
7834 || mk == MK_friend_spec)
7836 if (mk != MK_partial)
7838 // FIXME: We should make use of the merge-key by
7839 // exposing it outside of key_mergeable. But this gets
7840 // the job done.
7841 auto *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
7843 if (streaming_p ())
7844 u (get_mergeable_specialization_flags (entry->tmpl, decl));
7845 tree_node (entry->tmpl);
7846 tree_node (entry->args);
7848 else
7850 tree ti = get_template_info (inner);
7851 tree_node (TI_TEMPLATE (ti));
7852 tree_node (TI_ARGS (ti));
7855 tree_node (get_constraints (decl));
7858 if (streaming_p ())
7860 /* Do not stray outside this section. */
7861 gcc_checking_assert (!dep || dep->section == dep_hash->section);
7863 /* Write the entity index, so we can insert it as soon as we
7864 know this is new. */
7865 install_entity (decl, dep);
7868 if (VAR_OR_FUNCTION_DECL_P (inner)
7869 && DECL_LANG_SPECIFIC (inner)
7870 && DECL_MODULE_KEYED_DECLS_P (inner)
7871 && !is_key_order ())
7873 /* Stream the keyed entities. */
7874 auto *attach_vec = keyed_table->get (inner);
7875 unsigned num = attach_vec->length ();
7876 if (streaming_p ())
7877 u (num);
7878 for (unsigned ix = 0; ix != num; ix++)
7880 tree attached = (*attach_vec)[ix];
7881 tree_node (attached);
7882 if (streaming_p ())
7883 dump (dumper::MERGE)
7884 && dump ("Written %d[%u] attached decl %N", tag, ix, attached);
7888 bool is_typedef = false;
7889 if (!type && TREE_CODE (inner) == TYPE_DECL)
7891 tree t = TREE_TYPE (inner);
7892 unsigned tdef_flags = 0;
7893 if (DECL_ORIGINAL_TYPE (inner)
7894 && TYPE_NAME (TREE_TYPE (inner)) == inner)
7896 tdef_flags |= 1;
7897 if (TYPE_STRUCTURAL_EQUALITY_P (t)
7898 && TYPE_DEPENDENT_P_VALID (t)
7899 && TYPE_DEPENDENT_P (t))
7900 tdef_flags |= 2;
7902 if (streaming_p ())
7903 u (tdef_flags);
7905 if (tdef_flags & 1)
7907 /* A typedef type. */
7908 int type_tag = insert (t);
7909 if (streaming_p ())
7910 dump (dumper::TREE)
7911 && dump ("Cloned:%d %s %C:%N", type_tag,
7912 tdef_flags & 2 ? "depalias" : "typedef",
7913 TREE_CODE (t), t);
7915 is_typedef = true;
7919 if (streaming_p () && DECL_MAYBE_IN_CHARGE_CDTOR_P (decl))
7921 bool cloned_p
7922 = (DECL_CHAIN (decl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
7923 bool needs_vtt_parm_p
7924 = (cloned_p && CLASSTYPE_VBASECLASSES (DECL_CONTEXT (decl)));
7925 bool omit_inherited_parms_p
7926 = (cloned_p && DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)
7927 && base_ctor_omit_inherited_parms (decl));
7928 unsigned flags = (int (cloned_p) << 0
7929 | int (needs_vtt_parm_p) << 1
7930 | int (omit_inherited_parms_p) << 2);
7931 u (flags);
7932 dump (dumper::TREE) && dump ("CDTOR %N is %scloned",
7933 decl, cloned_p ? "" : "not ");
7936 if (streaming_p () && VAR_P (decl) && CP_DECL_THREAD_LOCAL_P (decl))
7937 u (decl_tls_model (decl));
7939 if (streaming_p ())
7940 dump (dumper::TREE) && dump ("Written decl:%d %C:%N", tag,
7941 TREE_CODE (decl), decl);
7943 if (NAMESPACE_SCOPE_P (inner))
7944 gcc_checking_assert (!dep == (VAR_OR_FUNCTION_DECL_P (inner)
7945 && DECL_LOCAL_DECL_P (inner)));
7946 else if ((TREE_CODE (inner) == TYPE_DECL
7947 && !is_typedef
7948 && TYPE_NAME (TREE_TYPE (inner)) == inner)
7949 || TREE_CODE (inner) == FUNCTION_DECL)
7951 bool write_defn = !dep && has_definition (decl);
7952 if (streaming_p ())
7953 u (write_defn);
7954 if (write_defn)
7955 write_definition (decl);
7959 tree
7960 trees_in::decl_value ()
7962 int tag = 0;
7963 bool is_attached = false;
7964 bool has_defn = false;
7965 unsigned mk_u = u ();
7966 if (mk_u >= MK_hwm || !merge_kind_name[mk_u])
7968 set_overrun ();
7969 return NULL_TREE;
7972 unsigned saved_unused = unused;
7973 unused = 0;
7975 merge_kind mk = merge_kind (mk_u);
7977 tree decl = start ();
7978 if (decl)
7980 if (mk != MK_unique)
7982 if (!(mk & MK_template_mask) && !state->is_header ())
7983 /* See note in trees_out about where this bool is sequenced. */
7984 is_attached = b ();
7986 has_defn = b ();
7989 if (!tree_node_bools (decl))
7990 decl = NULL_TREE;
7993 /* Insert into map. */
7994 tag = insert (decl);
7995 if (decl)
7996 dump (dumper::TREE)
7997 && dump ("Reading:%d %C", tag, TREE_CODE (decl));
7999 tree inner = decl;
8000 int inner_tag = 0;
8001 if (decl && TREE_CODE (decl) == TEMPLATE_DECL)
8003 int code = u ();
8004 inner = start (code);
8005 if (inner && tree_node_bools (inner))
8006 DECL_TEMPLATE_RESULT (decl) = inner;
8007 else
8008 decl = NULL_TREE;
8010 inner_tag = insert (inner);
8011 if (decl)
8012 dump (dumper::TREE)
8013 && dump ("Reading:%d %C", inner_tag, TREE_CODE (inner));
8016 tree type = NULL_TREE;
8017 int type_tag = 0;
8018 tree stub_decl = NULL_TREE;
8019 int stub_tag = 0;
8020 if (decl && TREE_CODE (inner) == TYPE_DECL)
8022 if (unsigned type_code = u ())
8024 type = start (type_code);
8025 if (type && tree_node_bools (type))
8027 TREE_TYPE (inner) = type;
8028 TYPE_NAME (type) = inner;
8030 else
8031 decl = NULL_TREE;
8033 type_tag = insert (type);
8034 if (decl)
8035 dump (dumper::TREE)
8036 && dump ("Reading type:%d %C", type_tag, TREE_CODE (type));
8038 if (unsigned stub_code = u ())
8040 stub_decl = start (stub_code);
8041 if (stub_decl && tree_node_bools (stub_decl))
8043 TREE_TYPE (stub_decl) = type;
8044 TYPE_STUB_DECL (type) = stub_decl;
8046 else
8047 decl = NULL_TREE;
8049 stub_tag = insert (stub_decl);
8050 if (decl)
8051 dump (dumper::TREE)
8052 && dump ("Reading stub_decl:%d %C", stub_tag,
8053 TREE_CODE (stub_decl));
8058 if (!decl)
8060 bail:
8061 if (inner_tag != 0)
8062 back_refs[~inner_tag] = NULL_TREE;
8063 if (type_tag != 0)
8064 back_refs[~type_tag] = NULL_TREE;
8065 if (stub_tag != 0)
8066 back_refs[~stub_tag] = NULL_TREE;
8067 if (tag != 0)
8068 back_refs[~tag] = NULL_TREE;
8069 set_overrun ();
8070 /* Bail. */
8071 unused = saved_unused;
8072 return NULL_TREE;
8075 /* Read the container, to ensure it's already been streamed in. */
8076 tree container = decl_container ();
8077 unsigned tpl_levels = 0;
8079 /* Figure out if this decl is already known about. */
8080 int parm_tag = 0;
8082 if (decl != inner)
8083 if (!tpl_header (decl, &tpl_levels))
8084 goto bail;
8085 if (TREE_CODE (inner) == FUNCTION_DECL)
8086 parm_tag = fn_parms_init (inner);
8088 tree existing = key_mergeable (tag, mk, decl, inner, type, container,
8089 is_attached);
8090 tree existing_inner = existing;
8091 if (existing)
8093 if (existing == error_mark_node)
8094 goto bail;
8096 if (TREE_CODE (STRIP_TEMPLATE (existing)) == TYPE_DECL)
8098 tree etype = TREE_TYPE (existing);
8099 if (TYPE_LANG_SPECIFIC (etype)
8100 && COMPLETE_TYPE_P (etype)
8101 && !CLASSTYPE_MEMBER_VEC (etype))
8102 /* Give it a member vec, we're likely gonna be looking
8103 inside it. */
8104 set_class_bindings (etype, -1);
8107 /* Install the existing decl into the back ref array. */
8108 register_duplicate (decl, existing);
8109 back_refs[~tag] = existing;
8110 if (inner_tag != 0)
8112 existing_inner = DECL_TEMPLATE_RESULT (existing);
8113 back_refs[~inner_tag] = existing_inner;
8116 if (type_tag != 0)
8118 tree existing_type = TREE_TYPE (existing);
8119 back_refs[~type_tag] = existing_type;
8120 if (stub_tag != 0)
8121 back_refs[~stub_tag] = TYPE_STUB_DECL (existing_type);
8125 if (parm_tag)
8126 fn_parms_fini (parm_tag, inner, existing_inner, has_defn);
8128 if (!tree_node_vals (decl))
8129 goto bail;
8131 if (inner_tag)
8133 gcc_checking_assert (DECL_TEMPLATE_RESULT (decl) == inner);
8135 if (!tree_node_vals (inner))
8136 goto bail;
8138 if (!tpl_parms_fini (decl, tpl_levels))
8139 goto bail;
8142 if (type && (!tree_node_vals (type)
8143 || (stub_decl && !tree_node_vals (stub_decl))))
8144 goto bail;
8146 spec_entry spec;
8147 unsigned spec_flags = 0;
8148 if (mk & MK_template_mask
8149 || mk == MK_partial
8150 || mk == MK_friend_spec)
8152 if (mk == MK_partial)
8153 spec_flags = 2;
8154 else
8155 spec_flags = u ();
8157 spec.tmpl = tree_node ();
8158 spec.args = tree_node ();
8160 /* Hold constraints on the spec field, for a short while. */
8161 spec.spec = tree_node ();
8163 dump (dumper::TREE) && dump ("Read:%d %C:%N", tag, TREE_CODE (decl), decl);
8165 existing = back_refs[~tag];
8166 bool installed = install_entity (existing);
8167 bool is_new = existing == decl;
8169 if (VAR_OR_FUNCTION_DECL_P (inner)
8170 && DECL_LANG_SPECIFIC (inner)
8171 && DECL_MODULE_KEYED_DECLS_P (inner))
8173 /* Read and maybe install the attached entities. */
8174 bool existed;
8175 auto &set = keyed_table->get_or_insert (STRIP_TEMPLATE (existing),
8176 &existed);
8177 unsigned num = u ();
8178 if (is_new == existed)
8179 set_overrun ();
8180 if (is_new)
8181 set.reserve (num);
8182 for (unsigned ix = 0; !get_overrun () && ix != num; ix++)
8184 tree attached = tree_node ();
8185 dump (dumper::MERGE)
8186 && dump ("Read %d[%u] %s attached decl %N", tag, ix,
8187 is_new ? "new" : "matched", attached);
8188 if (is_new)
8189 set.quick_push (attached);
8190 else if (set[ix] != attached)
8191 set_overrun ();
8195 /* Regular typedefs will have a NULL TREE_TYPE at this point. */
8196 unsigned tdef_flags = 0;
8197 bool is_typedef = false;
8198 if (!type && TREE_CODE (inner) == TYPE_DECL)
8200 tdef_flags = u ();
8201 if (tdef_flags & 1)
8202 is_typedef = true;
8205 if (is_new)
8207 /* A newly discovered node. */
8208 if (TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl))
8209 /* Mark this identifier as naming a virtual function --
8210 lookup_overrides relies on this optimization. */
8211 IDENTIFIER_VIRTUAL_P (DECL_NAME (decl)) = true;
8213 if (installed)
8215 /* Mark the entity as imported. */
8216 retrofit_lang_decl (inner);
8217 DECL_MODULE_IMPORT_P (inner) = true;
8220 if (spec.spec)
8221 set_constraints (decl, spec.spec);
8223 if (TREE_CODE (decl) == INTEGER_CST && !TREE_OVERFLOW (decl))
8225 decl = cache_integer_cst (decl, true);
8226 back_refs[~tag] = decl;
8229 if (is_typedef)
8231 /* Frob it to be ready for cloning. */
8232 TREE_TYPE (inner) = DECL_ORIGINAL_TYPE (inner);
8233 DECL_ORIGINAL_TYPE (inner) = NULL_TREE;
8234 set_underlying_type (inner);
8235 if (tdef_flags & 2)
8237 /* Match instantiate_alias_template's handling. */
8238 tree type = TREE_TYPE (inner);
8239 TYPE_DEPENDENT_P (type) = true;
8240 TYPE_DEPENDENT_P_VALID (type) = true;
8241 SET_TYPE_STRUCTURAL_EQUALITY (type);
8245 if (inner_tag)
8246 /* Set the TEMPLATE_DECL's type. */
8247 TREE_TYPE (decl) = TREE_TYPE (inner);
8249 /* Add to specialization tables now that constraints etc are
8250 added. */
8251 if (mk == MK_partial)
8253 bool is_type = TREE_CODE (inner) == TYPE_DECL;
8254 spec.spec = is_type ? type : inner;
8255 add_mergeable_specialization (!is_type, false,
8256 &spec, decl, spec_flags);
8258 else if (mk & MK_template_mask)
8260 bool is_type = !(mk & MK_tmpl_decl_mask);
8261 spec.spec = is_type ? type : mk & MK_tmpl_tmpl_mask ? inner : decl;
8262 add_mergeable_specialization (!is_type,
8263 !is_type && mk & MK_tmpl_alias_mask,
8264 &spec, decl, spec_flags);
8267 if (NAMESPACE_SCOPE_P (decl)
8268 && (mk == MK_named || mk == MK_unique
8269 || mk == MK_enum || mk == MK_friend_spec)
8270 && !(VAR_OR_FUNCTION_DECL_P (decl) && DECL_LOCAL_DECL_P (decl)))
8271 add_module_namespace_decl (CP_DECL_CONTEXT (decl), decl);
8273 if (DECL_ARTIFICIAL (decl)
8274 && TREE_CODE (decl) == FUNCTION_DECL
8275 && !DECL_TEMPLATE_INFO (decl)
8276 && DECL_CONTEXT (decl) && TYPE_P (DECL_CONTEXT (decl))
8277 && TYPE_SIZE (DECL_CONTEXT (decl))
8278 && !DECL_THUNK_P (decl))
8279 /* A new implicit member function, when the class is
8280 complete. This means the importee declared it, and
8281 we must now add it to the class. Note that implicit
8282 member fns of template instantiations do not themselves
8283 look like templates. */
8284 if (!install_implicit_member (inner))
8285 set_overrun ();
8287 /* When importing a TLS wrapper from a header unit, we haven't
8288 actually emitted its definition yet. Remember it so we can
8289 do this later. */
8290 if (state->is_header ()
8291 && decl_tls_wrapper_p (decl))
8292 note_vague_linkage_fn (decl);
8294 else
8296 /* DECL is the to-be-discarded decl. Its internal pointers will
8297 be to the EXISTING's structure. Frob it to point to its
8298 own other structures, so loading its definition will alter
8299 it, and not the existing decl. */
8300 dump (dumper::MERGE) && dump ("Deduping %N", existing);
8302 if (inner_tag)
8303 DECL_TEMPLATE_RESULT (decl) = inner;
8305 if (type)
8307 /* Point at the to-be-discarded type & decl. */
8308 TYPE_NAME (type) = inner;
8309 TREE_TYPE (inner) = type;
8311 TYPE_STUB_DECL (type) = stub_decl ? stub_decl : inner;
8312 if (stub_decl)
8313 TREE_TYPE (stub_decl) = type;
8316 if (inner_tag)
8317 /* Set the TEMPLATE_DECL's type. */
8318 TREE_TYPE (decl) = TREE_TYPE (inner);
8320 if (!is_matching_decl (existing, decl, is_typedef))
8321 unmatched_duplicate (existing);
8323 if (TREE_CODE (inner) == FUNCTION_DECL)
8325 tree e_inner = STRIP_TEMPLATE (existing);
8326 for (auto parm = DECL_ARGUMENTS (inner);
8327 parm; parm = DECL_CHAIN (parm))
8328 DECL_CONTEXT (parm) = e_inner;
8331 /* And our result is the existing node. */
8332 decl = existing;
8335 if (mk == MK_friend_spec)
8337 tree e = match_mergeable_specialization (true, &spec);
8338 if (!e)
8340 spec.spec = inner;
8341 add_mergeable_specialization (true, false, &spec, decl, spec_flags);
8343 else if (e != existing)
8344 set_overrun ();
8347 if (is_typedef)
8349 /* Insert the type into the array now. */
8350 tag = insert (TREE_TYPE (decl));
8351 dump (dumper::TREE)
8352 && dump ("Cloned:%d typedef %C:%N",
8353 tag, TREE_CODE (TREE_TYPE (decl)), TREE_TYPE (decl));
8356 unused = saved_unused;
8358 if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl))
8360 unsigned flags = u ();
8362 if (is_new)
8364 bool cloned_p = flags & 1;
8365 dump (dumper::TREE) && dump ("CDTOR %N is %scloned",
8366 decl, cloned_p ? "" : "not ");
8367 if (cloned_p)
8368 build_cdtor_clones (decl, flags & 2, flags & 4,
8369 /* Update the member vec, if there is
8370 one (we're in a different cluster
8371 to the class defn). */
8372 CLASSTYPE_MEMBER_VEC (DECL_CONTEXT (decl)));
8376 if (VAR_P (decl) && CP_DECL_THREAD_LOCAL_P (decl))
8378 enum tls_model model = tls_model (u ());
8379 if (is_new)
8380 set_decl_tls_model (decl, model);
8383 if (!NAMESPACE_SCOPE_P (inner)
8384 && ((TREE_CODE (inner) == TYPE_DECL
8385 && !is_typedef
8386 && TYPE_NAME (TREE_TYPE (inner)) == inner)
8387 || TREE_CODE (inner) == FUNCTION_DECL)
8388 && u ())
8389 read_definition (decl);
8391 return decl;
8394 /* DECL is an unnameable member of CTX. Return a suitable identifying
8395 index. */
8397 static unsigned
8398 get_field_ident (tree ctx, tree decl)
8400 gcc_checking_assert (TREE_CODE (decl) == USING_DECL
8401 || !DECL_NAME (decl)
8402 || IDENTIFIER_ANON_P (DECL_NAME (decl)));
8404 unsigned ix = 0;
8405 for (tree fields = TYPE_FIELDS (ctx);
8406 fields; fields = DECL_CHAIN (fields))
8408 if (fields == decl)
8409 return ix;
8411 if (DECL_CONTEXT (fields) == ctx
8412 && (TREE_CODE (fields) == USING_DECL
8413 || (TREE_CODE (fields) == FIELD_DECL
8414 && (!DECL_NAME (fields)
8415 || IDENTIFIER_ANON_P (DECL_NAME (fields))))))
8416 /* Count this field. */
8417 ix++;
8419 gcc_unreachable ();
8422 static tree
8423 lookup_field_ident (tree ctx, unsigned ix)
8425 for (tree fields = TYPE_FIELDS (ctx);
8426 fields; fields = DECL_CHAIN (fields))
8427 if (DECL_CONTEXT (fields) == ctx
8428 && (TREE_CODE (fields) == USING_DECL
8429 || (TREE_CODE (fields) == FIELD_DECL
8430 && (!DECL_NAME (fields)
8431 || IDENTIFIER_ANON_P (DECL_NAME (fields))))))
8432 if (!ix--)
8433 return fields;
8435 return NULL_TREE;
8438 /* Reference DECL. REF indicates the walk kind we are performing.
8439 Return true if we should write this decl by value. */
8441 bool
8442 trees_out::decl_node (tree decl, walk_kind ref)
8444 gcc_checking_assert (DECL_P (decl) && !DECL_TEMPLATE_PARM_P (decl)
8445 && DECL_CONTEXT (decl));
8447 if (ref == WK_value)
8449 depset *dep = dep_hash->find_dependency (decl);
8450 decl_value (decl, dep);
8451 return false;
8454 switch (TREE_CODE (decl))
8456 default:
8457 break;
8459 case FUNCTION_DECL:
8460 gcc_checking_assert (!DECL_LOCAL_DECL_P (decl));
8461 break;
8463 case RESULT_DECL:
8464 /* Unlike PARM_DECLs, RESULT_DECLs are only generated and
8465 referenced when we're inside the function itself. */
8466 return true;
8468 case PARM_DECL:
8470 if (streaming_p ())
8471 i (tt_parm);
8472 tree_node (DECL_CONTEXT (decl));
8473 if (streaming_p ())
8475 /* That must have put this in the map. */
8476 walk_kind ref = ref_node (decl);
8477 if (ref != WK_none)
8478 // FIXME:OPTIMIZATION We can wander into bits of the
8479 // template this was instantiated from. For instance
8480 // deferred noexcept and default parms. Currently we'll
8481 // end up cloning those bits of tree. It would be nice
8482 // to reference those specific nodes. I think putting
8483 // those things in the map when we reference their
8484 // template by name. See the note in add_indirects.
8485 return true;
8487 dump (dumper::TREE)
8488 && dump ("Wrote %s reference %N",
8489 TREE_CODE (decl) == PARM_DECL ? "parameter" : "result",
8490 decl);
8493 return false;
8495 case IMPORTED_DECL:
8496 /* This describes a USING_DECL to the ME's debug machinery. It
8497 originates from the fortran FE, and has nothing to do with
8498 C++ modules. */
8499 return true;
8501 case LABEL_DECL:
8502 return true;
8504 case CONST_DECL:
8506 /* If I end up cloning enum decls, implementing C++20 using
8507 E::v, this will need tweaking. */
8508 if (streaming_p ())
8509 i (tt_enum_decl);
8510 tree ctx = DECL_CONTEXT (decl);
8511 gcc_checking_assert (TREE_CODE (ctx) == ENUMERAL_TYPE);
8512 tree_node (ctx);
8513 tree_node (DECL_NAME (decl));
8515 int tag = insert (decl);
8516 if (streaming_p ())
8517 dump (dumper::TREE)
8518 && dump ("Wrote enum decl:%d %C:%N", tag, TREE_CODE (decl), decl);
8519 return false;
8521 break;
8523 case USING_DECL:
8524 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
8525 break;
8526 /* FALLTHROUGH */
8528 case FIELD_DECL:
8530 if (streaming_p ())
8531 i (tt_data_member);
8533 tree ctx = DECL_CONTEXT (decl);
8534 tree_node (ctx);
8536 tree name = NULL_TREE;
8538 if (TREE_CODE (decl) == USING_DECL)
8540 else
8542 name = DECL_NAME (decl);
8543 if (name && IDENTIFIER_ANON_P (name))
8544 name = NULL_TREE;
8547 tree_node (name);
8548 if (!name && streaming_p ())
8550 unsigned ix = get_field_ident (ctx, decl);
8551 u (ix);
8554 int tag = insert (decl);
8555 if (streaming_p ())
8556 dump (dumper::TREE)
8557 && dump ("Wrote member:%d %C:%N", tag, TREE_CODE (decl), decl);
8558 return false;
8560 break;
8562 case VAR_DECL:
8563 gcc_checking_assert (!DECL_LOCAL_DECL_P (decl));
8564 if (DECL_VTABLE_OR_VTT_P (decl))
8566 /* VTT or VTABLE, they are all on the vtables list. */
8567 tree ctx = CP_DECL_CONTEXT (decl);
8568 tree vtable = CLASSTYPE_VTABLES (ctx);
8569 for (unsigned ix = 0; ; vtable = DECL_CHAIN (vtable), ix++)
8570 if (vtable == decl)
8572 gcc_checking_assert (DECL_VIRTUAL_P (decl));
8573 if (streaming_p ())
8575 u (tt_vtable);
8576 u (ix);
8577 dump (dumper::TREE)
8578 && dump ("Writing vtable %N[%u]", ctx, ix);
8580 tree_node (ctx);
8581 return false;
8583 gcc_unreachable ();
8586 if (DECL_TINFO_P (decl))
8588 tinfo:
8589 /* A typeinfo, tt_tinfo_typedef or tt_tinfo_var. */
8590 bool is_var = VAR_P (decl);
8591 tree type = TREE_TYPE (decl);
8592 unsigned ix = get_pseudo_tinfo_index (type);
8593 if (streaming_p ())
8595 i (is_var ? tt_tinfo_var : tt_tinfo_typedef);
8596 u (ix);
8599 if (is_var)
8601 /* We also need the type it is for and mangled name, so
8602 the reader doesn't need to complete the type (which
8603 would break section ordering). The type it is for is
8604 stashed on the name's TREE_TYPE. */
8605 tree name = DECL_NAME (decl);
8606 tree_node (name);
8607 type = TREE_TYPE (name);
8608 tree_node (type);
8611 int tag = insert (decl);
8612 if (streaming_p ())
8613 dump (dumper::TREE)
8614 && dump ("Wrote tinfo_%s:%d %u %N", is_var ? "var" : "type",
8615 tag, ix, type);
8617 if (!is_var)
8619 tag = insert (type);
8620 if (streaming_p ())
8621 dump (dumper::TREE)
8622 && dump ("Wrote tinfo_type:%d %u %N", tag, ix, type);
8624 return false;
8627 if (DECL_NTTP_OBJECT_P (decl))
8629 /* A NTTP parm object. */
8630 if (streaming_p ())
8631 i (tt_nttp_var);
8632 tree_node (tparm_object_argument (decl));
8633 tree_node (DECL_NAME (decl));
8634 int tag = insert (decl);
8635 if (streaming_p ())
8636 dump (dumper::TREE)
8637 && dump ("Wrote nttp object:%d %N", tag, DECL_NAME (decl));
8638 return false;
8641 break;
8643 case TYPE_DECL:
8644 if (DECL_TINFO_P (decl))
8645 goto tinfo;
8646 break;
8649 if (DECL_THUNK_P (decl))
8651 /* Thunks are similar to binfos -- write the thunked-to decl and
8652 then thunk-specific key info. */
8653 if (streaming_p ())
8655 i (tt_thunk);
8656 i (THUNK_FIXED_OFFSET (decl));
8659 tree target = decl;
8660 while (DECL_THUNK_P (target))
8661 target = THUNK_TARGET (target);
8662 tree_node (target);
8663 tree_node (THUNK_VIRTUAL_OFFSET (decl));
8664 int tag = insert (decl);
8665 if (streaming_p ())
8666 dump (dumper::TREE)
8667 && dump ("Wrote:%d thunk %N to %N", tag, DECL_NAME (decl), target);
8668 return false;
8671 if (DECL_CLONED_FUNCTION_P (decl))
8673 tree target = get_clone_target (decl);
8674 if (streaming_p ())
8675 i (tt_clone_ref);
8677 tree_node (target);
8678 tree_node (DECL_NAME (decl));
8679 if (DECL_VIRTUAL_P (decl))
8680 tree_node (DECL_VINDEX (decl));
8681 int tag = insert (decl);
8682 if (streaming_p ())
8683 dump (dumper::TREE)
8684 && dump ("Wrote:%d clone %N of %N", tag, DECL_NAME (decl), target);
8685 return false;
8688 /* Everything left should be a thing that is in the entity table.
8689 Mostly things that can be defined outside of their (original
8690 declaration) context. */
8691 gcc_checking_assert (TREE_CODE (decl) == TEMPLATE_DECL
8692 || VAR_P (decl)
8693 || TREE_CODE (decl) == FUNCTION_DECL
8694 || TREE_CODE (decl) == TYPE_DECL
8695 || TREE_CODE (decl) == USING_DECL
8696 || TREE_CODE (decl) == CONCEPT_DECL
8697 || TREE_CODE (decl) == NAMESPACE_DECL);
8699 int use_tpl = -1;
8700 tree ti = node_template_info (decl, use_tpl);
8701 tree tpl = NULL_TREE;
8703 /* If this is the TEMPLATE_DECL_RESULT of a TEMPLATE_DECL, get the
8704 TEMPLATE_DECL. Note TI_TEMPLATE is not a TEMPLATE_DECL for
8705 (some) friends, so we need to check that. */
8706 // FIXME: Should local friend template specializations be by value?
8707 // They don't get idents so we'll never know they're imported, but I
8708 // think we can only reach them from the TU that defines the
8709 // befriending class?
8710 if (ti && TREE_CODE (TI_TEMPLATE (ti)) == TEMPLATE_DECL
8711 && DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == decl)
8713 tpl = TI_TEMPLATE (ti);
8714 partial_template:
8715 if (streaming_p ())
8717 i (tt_template);
8718 dump (dumper::TREE)
8719 && dump ("Writing implicit template %C:%N%S",
8720 TREE_CODE (tpl), tpl, tpl);
8722 tree_node (tpl);
8724 /* Streaming TPL caused us to visit DECL and maybe its type. */
8725 gcc_checking_assert (TREE_VISITED (decl));
8726 if (DECL_IMPLICIT_TYPEDEF_P (decl))
8727 gcc_checking_assert (TREE_VISITED (TREE_TYPE (decl)));
8728 return false;
8731 tree ctx = CP_DECL_CONTEXT (decl);
8732 depset *dep = NULL;
8733 if (streaming_p ())
8734 dep = dep_hash->find_dependency (decl);
8735 else if (TREE_CODE (ctx) != FUNCTION_DECL
8736 || TREE_CODE (decl) == TEMPLATE_DECL
8737 || (dep_hash->sneakoscope && DECL_IMPLICIT_TYPEDEF_P (decl))
8738 || (DECL_LANG_SPECIFIC (decl)
8739 && DECL_MODULE_IMPORT_P (decl)))
8741 auto kind = (TREE_CODE (decl) == NAMESPACE_DECL
8742 && !DECL_NAMESPACE_ALIAS (decl)
8743 ? depset::EK_NAMESPACE : depset::EK_DECL);
8744 dep = dep_hash->add_dependency (decl, kind);
8747 if (!dep)
8749 /* Some internal entity of context. Do by value. */
8750 decl_value (decl, NULL);
8751 return false;
8754 if (dep->get_entity_kind () == depset::EK_REDIRECT)
8756 /* The DECL_TEMPLATE_RESULT of a partial specialization.
8757 Write the partial specialization's template. */
8758 depset *redirect = dep->deps[0];
8759 gcc_checking_assert (redirect->get_entity_kind () == depset::EK_PARTIAL);
8760 tpl = redirect->get_entity ();
8761 goto partial_template;
8764 if (streaming_p ())
8766 /* Locate the entity. */
8767 unsigned index = dep->cluster;
8768 unsigned import = 0;
8770 if (dep->is_import ())
8771 import = dep->section;
8772 else if (CHECKING_P)
8773 /* It should be what we put there. */
8774 gcc_checking_assert (index == ~import_entity_index (decl));
8776 #if CHECKING_P
8777 gcc_assert (!import || importedness >= 0);
8778 #endif
8779 i (tt_entity);
8780 u (import);
8781 u (index);
8784 int tag = insert (decl);
8785 if (streaming_p () && dump (dumper::TREE))
8787 char const *kind = "import";
8788 module_state *from = (*modules)[0];
8789 if (dep->is_import ())
8790 /* Rediscover the unremapped index. */
8791 from = import_entity_module (import_entity_index (decl));
8792 else
8794 tree o = get_originating_module_decl (decl);
8795 o = STRIP_TEMPLATE (o);
8796 kind = (DECL_LANG_SPECIFIC (o) && DECL_MODULE_PURVIEW_P (o)
8797 ? "purview" : "GMF");
8799 dump ("Wrote %s:%d %C:%N@%M", kind,
8800 tag, TREE_CODE (decl), decl, from);
8803 add_indirects (decl);
8805 return false;
8808 void
8809 trees_out::type_node (tree type)
8811 gcc_assert (TYPE_P (type));
8813 tree root = (TYPE_NAME (type)
8814 ? TREE_TYPE (TYPE_NAME (type)) : TYPE_MAIN_VARIANT (type));
8816 if (type != root)
8818 if (streaming_p ())
8819 i (tt_variant_type);
8820 tree_node (root);
8822 int flags = -1;
8824 if (TREE_CODE (type) == FUNCTION_TYPE
8825 || TREE_CODE (type) == METHOD_TYPE)
8827 int quals = type_memfn_quals (type);
8828 int rquals = type_memfn_rqual (type);
8829 tree raises = TYPE_RAISES_EXCEPTIONS (type);
8830 bool late = TYPE_HAS_LATE_RETURN_TYPE (type);
8832 if (raises != TYPE_RAISES_EXCEPTIONS (root)
8833 || rquals != type_memfn_rqual (root)
8834 || quals != type_memfn_quals (root)
8835 || late != TYPE_HAS_LATE_RETURN_TYPE (root))
8836 flags = rquals | (int (late) << 2) | (quals << 3);
8838 else
8840 if (TYPE_USER_ALIGN (type))
8841 flags = TYPE_ALIGN_RAW (type);
8844 if (streaming_p ())
8845 i (flags);
8847 if (flags < 0)
8849 else if (TREE_CODE (type) == FUNCTION_TYPE
8850 || TREE_CODE (type) == METHOD_TYPE)
8852 tree raises = TYPE_RAISES_EXCEPTIONS (type);
8853 if (raises == TYPE_RAISES_EXCEPTIONS (root))
8854 raises = error_mark_node;
8855 tree_node (raises);
8858 tree_node (TYPE_ATTRIBUTES (type));
8860 if (streaming_p ())
8862 /* Qualifiers. */
8863 int rquals = cp_type_quals (root);
8864 int quals = cp_type_quals (type);
8865 if (quals == rquals)
8866 quals = -1;
8867 i (quals);
8870 if (ref_node (type) != WK_none)
8872 int tag = insert (type);
8873 if (streaming_p ())
8875 i (0);
8876 dump (dumper::TREE)
8877 && dump ("Wrote:%d variant type %C", tag, TREE_CODE (type));
8880 return;
8883 if (tree name = TYPE_NAME (type))
8884 if ((TREE_CODE (name) == TYPE_DECL && DECL_ORIGINAL_TYPE (name))
8885 || DECL_TEMPLATE_PARM_P (name)
8886 || TREE_CODE (type) == RECORD_TYPE
8887 || TREE_CODE (type) == UNION_TYPE
8888 || TREE_CODE (type) == ENUMERAL_TYPE)
8890 /* We can meet template parms that we didn't meet in the
8891 tpl_parms walk, because we're referring to a derived type
8892 that was previously constructed from equivalent template
8893 parms. */
8894 if (streaming_p ())
8896 i (tt_typedef_type);
8897 dump (dumper::TREE)
8898 && dump ("Writing %stypedef %C:%N",
8899 DECL_IMPLICIT_TYPEDEF_P (name) ? "implicit " : "",
8900 TREE_CODE (name), name);
8902 tree_node (name);
8903 if (streaming_p ())
8904 dump (dumper::TREE) && dump ("Wrote typedef %C:%N%S",
8905 TREE_CODE (name), name, name);
8906 gcc_checking_assert (TREE_VISITED (type));
8907 return;
8910 if (TYPE_PTRMEMFUNC_P (type))
8912 /* This is a distinct type node, masquerading as a structure. */
8913 tree fn_type = TYPE_PTRMEMFUNC_FN_TYPE (type);
8914 if (streaming_p ())
8915 i (tt_ptrmem_type);
8916 tree_node (fn_type);
8917 int tag = insert (type);
8918 if (streaming_p ())
8919 dump (dumper::TREE) && dump ("Written:%d ptrmem type", tag);
8920 return;
8923 if (streaming_p ())
8925 u (tt_derived_type);
8926 u (TREE_CODE (type));
8929 tree_node (TREE_TYPE (type));
8930 switch (TREE_CODE (type))
8932 default:
8933 /* We should never meet a type here that is indescribable in
8934 terms of other types. */
8935 gcc_unreachable ();
8937 case ARRAY_TYPE:
8938 tree_node (TYPE_DOMAIN (type));
8939 if (streaming_p ())
8940 /* Dependent arrays are constructed with TYPE_DEPENENT_P
8941 already set. */
8942 u (TYPE_DEPENDENT_P (type));
8943 break;
8945 case COMPLEX_TYPE:
8946 /* No additional data. */
8947 break;
8949 case BOOLEAN_TYPE:
8950 /* A non-standard boolean type. */
8951 if (streaming_p ())
8952 u (TYPE_PRECISION (type));
8953 break;
8955 case INTEGER_TYPE:
8956 if (TREE_TYPE (type))
8958 /* A range type (representing an array domain). */
8959 tree_node (TYPE_MIN_VALUE (type));
8960 tree_node (TYPE_MAX_VALUE (type));
8962 else
8964 /* A new integral type (representing a bitfield). */
8965 if (streaming_p ())
8967 unsigned prec = TYPE_PRECISION (type);
8968 bool unsigned_p = TYPE_UNSIGNED (type);
8970 u ((prec << 1) | unsigned_p);
8973 break;
8975 case METHOD_TYPE:
8976 case FUNCTION_TYPE:
8978 gcc_checking_assert (type_memfn_rqual (type) == REF_QUAL_NONE);
8980 tree arg_types = TYPE_ARG_TYPES (type);
8981 if (TREE_CODE (type) == METHOD_TYPE)
8983 tree_node (TREE_TYPE (TREE_VALUE (arg_types)));
8984 arg_types = TREE_CHAIN (arg_types);
8986 tree_node (arg_types);
8988 break;
8990 case OFFSET_TYPE:
8991 tree_node (TYPE_OFFSET_BASETYPE (type));
8992 break;
8994 case POINTER_TYPE:
8995 /* No additional data. */
8996 break;
8998 case REFERENCE_TYPE:
8999 if (streaming_p ())
9000 u (TYPE_REF_IS_RVALUE (type));
9001 break;
9003 case DECLTYPE_TYPE:
9004 case TYPEOF_TYPE:
9005 case DEPENDENT_OPERATOR_TYPE:
9006 tree_node (TYPE_VALUES_RAW (type));
9007 if (TREE_CODE (type) == DECLTYPE_TYPE)
9008 /* We stash a whole bunch of things into decltype's
9009 flags. */
9010 if (streaming_p ())
9011 tree_node_bools (type);
9012 break;
9014 case TRAIT_TYPE:
9015 tree_node (TRAIT_TYPE_KIND_RAW (type));
9016 tree_node (TRAIT_TYPE_TYPE1 (type));
9017 tree_node (TRAIT_TYPE_TYPE2 (type));
9018 break;
9020 case TYPE_ARGUMENT_PACK:
9021 /* No additional data. */
9022 break;
9024 case TYPE_PACK_EXPANSION:
9025 if (streaming_p ())
9026 u (PACK_EXPANSION_LOCAL_P (type));
9027 tree_node (PACK_EXPANSION_PARAMETER_PACKS (type));
9028 tree_node (PACK_EXPANSION_EXTRA_ARGS (type));
9029 break;
9031 case TYPENAME_TYPE:
9033 tree_node (TYPE_CONTEXT (type));
9034 tree_node (DECL_NAME (TYPE_NAME (type)));
9035 tree_node (TYPENAME_TYPE_FULLNAME (type));
9036 if (streaming_p ())
9038 enum tag_types tag_type = none_type;
9039 if (TYPENAME_IS_ENUM_P (type))
9040 tag_type = enum_type;
9041 else if (TYPENAME_IS_CLASS_P (type))
9042 tag_type = class_type;
9043 u (int (tag_type));
9046 break;
9048 case UNBOUND_CLASS_TEMPLATE:
9050 tree decl = TYPE_NAME (type);
9051 tree_node (DECL_CONTEXT (decl));
9052 tree_node (DECL_NAME (decl));
9053 tree_node (DECL_TEMPLATE_PARMS (decl));
9055 break;
9057 case VECTOR_TYPE:
9058 if (streaming_p ())
9060 poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (type);
9061 /* to_constant asserts that only coeff[0] is of interest. */
9062 wu (static_cast<unsigned HOST_WIDE_INT> (nunits.to_constant ()));
9064 break;
9067 /* We may have met the type during emitting the above. */
9068 if (ref_node (type) != WK_none)
9070 int tag = insert (type);
9071 if (streaming_p ())
9073 i (0);
9074 dump (dumper::TREE)
9075 && dump ("Wrote:%d derived type %C", tag, TREE_CODE (type));
9079 return;
9082 /* T is (mostly*) a non-mergeable node that must be written by value.
9083 The mergeable case is a BINFO, which are as-if DECLSs. */
9085 void
9086 trees_out::tree_value (tree t)
9088 /* We should never be writing a type by value. tree_type should
9089 have streamed it, or we're going via its TYPE_DECL. */
9090 gcc_checking_assert (!TYPE_P (t));
9092 if (DECL_P (t))
9093 /* No template, type, var or function, except anonymous
9094 non-context vars. */
9095 gcc_checking_assert ((TREE_CODE (t) != TEMPLATE_DECL
9096 && TREE_CODE (t) != TYPE_DECL
9097 && (TREE_CODE (t) != VAR_DECL
9098 || (!DECL_NAME (t) && !DECL_CONTEXT (t)))
9099 && TREE_CODE (t) != FUNCTION_DECL));
9101 if (streaming_p ())
9103 /* A new node -> tt_node. */
9104 tree_val_count++;
9105 i (tt_node);
9106 start (t);
9107 tree_node_bools (t);
9110 if (TREE_CODE (t) == TREE_BINFO)
9111 /* Binfos are decl-like and need merging information. */
9112 binfo_mergeable (t);
9114 int tag = insert (t, WK_value);
9115 if (streaming_p ())
9116 dump (dumper::TREE)
9117 && dump ("Writing tree:%d %C:%N", tag, TREE_CODE (t), t);
9119 tree_node_vals (t);
9121 if (streaming_p ())
9122 dump (dumper::TREE) && dump ("Written tree:%d %C:%N", tag, TREE_CODE (t), t);
9125 tree
9126 trees_in::tree_value ()
9128 tree t = start ();
9129 if (!t || !tree_node_bools (t))
9130 return NULL_TREE;
9132 tree existing = t;
9133 if (TREE_CODE (t) == TREE_BINFO)
9135 tree type;
9136 unsigned ix = binfo_mergeable (&type);
9137 if (TYPE_BINFO (type))
9139 /* We already have a definition, this must be a duplicate. */
9140 dump (dumper::MERGE)
9141 && dump ("Deduping binfo %N[%u]", type, ix);
9142 existing = TYPE_BINFO (type);
9143 while (existing && ix--)
9144 existing = TREE_CHAIN (existing);
9145 if (existing)
9146 register_duplicate (t, existing);
9147 else
9148 /* Error, mismatch -- diagnose in read_class_def's
9149 checking. */
9150 existing = t;
9154 /* Insert into map. */
9155 int tag = insert (existing);
9156 dump (dumper::TREE)
9157 && dump ("Reading tree:%d %C", tag, TREE_CODE (t));
9159 if (!tree_node_vals (t))
9161 back_refs[~tag] = NULL_TREE;
9162 set_overrun ();
9163 /* Bail. */
9164 return NULL_TREE;
9167 dump (dumper::TREE) && dump ("Read tree:%d %C:%N", tag, TREE_CODE (t), t);
9169 if (TREE_CODE (existing) == INTEGER_CST && !TREE_OVERFLOW (existing))
9171 existing = cache_integer_cst (t, true);
9172 back_refs[~tag] = existing;
9175 return existing;
9178 /* Stream out tree node T. We automatically create local back
9179 references, which is essentially a single pass lisp
9180 self-referential structure pretty-printer. */
9182 void
9183 trees_out::tree_node (tree t)
9185 dump.indent ();
9186 walk_kind ref = ref_node (t);
9187 if (ref == WK_none)
9188 goto done;
9190 if (ref != WK_normal)
9191 goto skip_normal;
9193 if (TREE_CODE (t) == IDENTIFIER_NODE)
9195 /* An identifier node -> tt_id, tt_conv_id, tt_anon_id, tt_lambda_id. */
9196 int code = tt_id;
9197 if (IDENTIFIER_ANON_P (t))
9198 code = IDENTIFIER_LAMBDA_P (t) ? tt_lambda_id : tt_anon_id;
9199 else if (IDENTIFIER_CONV_OP_P (t))
9200 code = tt_conv_id;
9202 if (streaming_p ())
9203 i (code);
9205 if (code == tt_conv_id)
9207 tree type = TREE_TYPE (t);
9208 gcc_checking_assert (type || t == conv_op_identifier);
9209 tree_node (type);
9211 else if (code == tt_id && streaming_p ())
9212 str (IDENTIFIER_POINTER (t), IDENTIFIER_LENGTH (t));
9214 int tag = insert (t);
9215 if (streaming_p ())
9217 /* We know the ordering of the 4 id tags. */
9218 static const char *const kinds[] =
9219 {"", "conv_op ", "anon ", "lambda "};
9220 dump (dumper::TREE)
9221 && dump ("Written:%d %sidentifier:%N", tag,
9222 kinds[code - tt_id],
9223 code == tt_conv_id ? TREE_TYPE (t) : t);
9225 goto done;
9228 if (TREE_CODE (t) == TREE_BINFO)
9230 /* A BINFO -> tt_binfo.
9231 We must do this by reference. We stream the binfo tree
9232 itself when streaming its owning RECORD_TYPE. That we got
9233 here means the dominating type is not in this SCC. */
9234 if (streaming_p ())
9235 i (tt_binfo);
9236 binfo_mergeable (t);
9237 gcc_checking_assert (!TREE_VISITED (t));
9238 int tag = insert (t);
9239 if (streaming_p ())
9240 dump (dumper::TREE) && dump ("Inserting binfo:%d %N", tag, t);
9241 goto done;
9244 if (TREE_CODE (t) == INTEGER_CST
9245 && !TREE_OVERFLOW (t)
9246 && TREE_CODE (TREE_TYPE (t)) == ENUMERAL_TYPE)
9248 /* An integral constant of enumeral type. See if it matches one
9249 of the enumeration values. */
9250 for (tree values = TYPE_VALUES (TREE_TYPE (t));
9251 values; values = TREE_CHAIN (values))
9253 tree decl = TREE_VALUE (values);
9254 if (tree_int_cst_equal (DECL_INITIAL (decl), t))
9256 if (streaming_p ())
9257 u (tt_enum_value);
9258 tree_node (decl);
9259 dump (dumper::TREE) && dump ("Written enum value %N", decl);
9260 goto done;
9263 /* It didn't match. We'll write it a an explicit INTEGER_CST
9264 node. */
9267 if (TYPE_P (t))
9269 type_node (t);
9270 goto done;
9273 if (DECL_P (t))
9275 if (DECL_TEMPLATE_PARM_P (t))
9277 tpl_parm_value (t);
9278 goto done;
9281 if (!DECL_CONTEXT (t))
9283 /* There are a few cases of decls with no context. We'll write
9284 these by value, but first assert they are cases we expect. */
9285 gcc_checking_assert (ref == WK_normal);
9286 switch (TREE_CODE (t))
9288 default: gcc_unreachable ();
9290 case LABEL_DECL:
9291 /* CASE_LABEL_EXPRs contain uncontexted LABEL_DECLs. */
9292 gcc_checking_assert (!DECL_NAME (t));
9293 break;
9295 case VAR_DECL:
9296 /* AGGR_INIT_EXPRs cons up anonymous uncontexted VAR_DECLs. */
9297 gcc_checking_assert (!DECL_NAME (t)
9298 && DECL_ARTIFICIAL (t));
9299 break;
9301 case PARM_DECL:
9302 /* REQUIRES_EXPRs have a tree list of uncontexted
9303 PARM_DECLS. It'd be nice if they had a
9304 distinguishing flag to double check. */
9305 break;
9307 goto by_value;
9311 skip_normal:
9312 if (DECL_P (t) && !decl_node (t, ref))
9313 goto done;
9315 /* Otherwise by value */
9316 by_value:
9317 tree_value (t);
9319 done:
9320 /* And, breath out. */
9321 dump.outdent ();
9324 /* Stream in a tree node. */
9326 tree
9327 trees_in::tree_node (bool is_use)
9329 if (get_overrun ())
9330 return NULL_TREE;
9332 dump.indent ();
9333 int tag = i ();
9334 tree res = NULL_TREE;
9335 switch (tag)
9337 default:
9338 /* backref, pull it out of the map. */
9339 res = back_ref (tag);
9340 break;
9342 case tt_null:
9343 /* NULL_TREE. */
9344 break;
9346 case tt_fixed:
9347 /* A fixed ref, find it in the fixed_ref array. */
9349 unsigned fix = u ();
9350 if (fix < (*fixed_trees).length ())
9352 res = (*fixed_trees)[fix];
9353 dump (dumper::TREE) && dump ("Read fixed:%u %C:%N%S", fix,
9354 TREE_CODE (res), res, res);
9357 if (!res)
9358 set_overrun ();
9360 break;
9362 case tt_parm:
9364 tree fn = tree_node ();
9365 if (fn && TREE_CODE (fn) == FUNCTION_DECL)
9366 res = tree_node ();
9367 if (res)
9368 dump (dumper::TREE)
9369 && dump ("Read %s reference %N",
9370 TREE_CODE (res) == PARM_DECL ? "parameter" : "result",
9371 res);
9373 break;
9375 case tt_node:
9376 /* A new node. Stream it in. */
9377 res = tree_value ();
9378 break;
9380 case tt_decl:
9381 /* A new decl. Stream it in. */
9382 res = decl_value ();
9383 break;
9385 case tt_tpl_parm:
9386 /* A template parameter. Stream it in. */
9387 res = tpl_parm_value ();
9388 break;
9390 case tt_id:
9391 /* An identifier node. */
9393 size_t l;
9394 const char *chars = str (&l);
9395 res = get_identifier_with_length (chars, l);
9396 int tag = insert (res);
9397 dump (dumper::TREE)
9398 && dump ("Read identifier:%d %N", tag, res);
9400 break;
9402 case tt_conv_id:
9403 /* A conversion operator. Get the type and recreate the
9404 identifier. */
9406 tree type = tree_node ();
9407 if (!get_overrun ())
9409 res = type ? make_conv_op_name (type) : conv_op_identifier;
9410 int tag = insert (res);
9411 dump (dumper::TREE)
9412 && dump ("Created conv_op:%d %S for %N", tag, res, type);
9415 break;
9417 case tt_anon_id:
9418 case tt_lambda_id:
9419 /* An anonymous or lambda id. */
9421 res = make_anon_name ();
9422 if (tag == tt_lambda_id)
9423 IDENTIFIER_LAMBDA_P (res) = true;
9424 int tag = insert (res);
9425 dump (dumper::TREE)
9426 && dump ("Read %s identifier:%d %N",
9427 IDENTIFIER_LAMBDA_P (res) ? "lambda" : "anon", tag, res);
9429 break;
9431 case tt_typedef_type:
9432 res = tree_node ();
9433 if (res)
9435 dump (dumper::TREE)
9436 && dump ("Read %stypedef %C:%N",
9437 DECL_IMPLICIT_TYPEDEF_P (res) ? "implicit " : "",
9438 TREE_CODE (res), res);
9439 res = TREE_TYPE (res);
9441 break;
9443 case tt_derived_type:
9444 /* A type derived from some other type. */
9446 enum tree_code code = tree_code (u ());
9447 res = tree_node ();
9449 switch (code)
9451 default:
9452 set_overrun ();
9453 break;
9455 case ARRAY_TYPE:
9457 tree domain = tree_node ();
9458 int dep = u ();
9459 if (!get_overrun ())
9460 res = build_cplus_array_type (res, domain, dep);
9462 break;
9464 case COMPLEX_TYPE:
9465 if (!get_overrun ())
9466 res = build_complex_type (res);
9467 break;
9469 case BOOLEAN_TYPE:
9471 unsigned precision = u ();
9472 if (!get_overrun ())
9473 res = build_nonstandard_boolean_type (precision);
9475 break;
9477 case INTEGER_TYPE:
9478 if (res)
9480 /* A range type (representing an array domain). */
9481 tree min = tree_node ();
9482 tree max = tree_node ();
9484 if (!get_overrun ())
9485 res = build_range_type (res, min, max);
9487 else
9489 /* A new integral type (representing a bitfield). */
9490 unsigned enc = u ();
9491 if (!get_overrun ())
9492 res = build_nonstandard_integer_type (enc >> 1, enc & 1);
9494 break;
9496 case FUNCTION_TYPE:
9497 case METHOD_TYPE:
9499 tree klass = code == METHOD_TYPE ? tree_node () : NULL_TREE;
9500 tree args = tree_node ();
9501 if (!get_overrun ())
9503 if (klass)
9504 res = build_method_type_directly (klass, res, args);
9505 else
9506 res = build_function_type (res, args);
9509 break;
9511 case OFFSET_TYPE:
9513 tree base = tree_node ();
9514 if (!get_overrun ())
9515 res = build_offset_type (base, res);
9517 break;
9519 case POINTER_TYPE:
9520 if (!get_overrun ())
9521 res = build_pointer_type (res);
9522 break;
9524 case REFERENCE_TYPE:
9526 bool rval = bool (u ());
9527 if (!get_overrun ())
9528 res = cp_build_reference_type (res, rval);
9530 break;
9532 case DECLTYPE_TYPE:
9533 case TYPEOF_TYPE:
9534 case DEPENDENT_OPERATOR_TYPE:
9536 tree expr = tree_node ();
9537 if (!get_overrun ())
9539 res = cxx_make_type (code);
9540 TYPE_VALUES_RAW (res) = expr;
9541 if (code == DECLTYPE_TYPE)
9542 tree_node_bools (res);
9543 SET_TYPE_STRUCTURAL_EQUALITY (res);
9546 break;
9548 case TRAIT_TYPE:
9550 tree kind = tree_node ();
9551 tree type1 = tree_node ();
9552 tree type2 = tree_node ();
9553 if (!get_overrun ())
9555 res = cxx_make_type (TRAIT_TYPE);
9556 TRAIT_TYPE_KIND_RAW (res) = kind;
9557 TRAIT_TYPE_TYPE1 (res) = type1;
9558 TRAIT_TYPE_TYPE2 (res) = type2;
9559 SET_TYPE_STRUCTURAL_EQUALITY (res);
9562 break;
9564 case TYPE_ARGUMENT_PACK:
9565 if (!get_overrun ())
9567 tree pack = cxx_make_type (TYPE_ARGUMENT_PACK);
9568 ARGUMENT_PACK_ARGS (pack) = res;
9569 res = pack;
9571 break;
9573 case TYPE_PACK_EXPANSION:
9575 bool local = u ();
9576 tree param_packs = tree_node ();
9577 tree extra_args = tree_node ();
9578 if (!get_overrun ())
9580 tree expn = cxx_make_type (TYPE_PACK_EXPANSION);
9581 SET_TYPE_STRUCTURAL_EQUALITY (expn);
9582 PACK_EXPANSION_PATTERN (expn) = res;
9583 PACK_EXPANSION_PARAMETER_PACKS (expn) = param_packs;
9584 PACK_EXPANSION_EXTRA_ARGS (expn) = extra_args;
9585 PACK_EXPANSION_LOCAL_P (expn) = local;
9586 res = expn;
9589 break;
9591 case TYPENAME_TYPE:
9593 tree ctx = tree_node ();
9594 tree name = tree_node ();
9595 tree fullname = tree_node ();
9596 enum tag_types tag_type = tag_types (u ());
9598 if (!get_overrun ())
9599 res = build_typename_type (ctx, name, fullname, tag_type);
9601 break;
9603 case UNBOUND_CLASS_TEMPLATE:
9605 tree ctx = tree_node ();
9606 tree name = tree_node ();
9607 tree parms = tree_node ();
9609 if (!get_overrun ())
9610 res = make_unbound_class_template_raw (ctx, name, parms);
9612 break;
9614 case VECTOR_TYPE:
9616 unsigned HOST_WIDE_INT nunits = wu ();
9617 if (!get_overrun ())
9618 res = build_vector_type (res, static_cast<poly_int64> (nunits));
9620 break;
9623 int tag = i ();
9624 if (!tag)
9626 tag = insert (res);
9627 if (res)
9628 dump (dumper::TREE)
9629 && dump ("Created:%d derived type %C", tag, code);
9631 else
9632 res = back_ref (tag);
9634 break;
9636 case tt_variant_type:
9637 /* Variant of some type. */
9639 res = tree_node ();
9640 int flags = i ();
9641 if (get_overrun ())
9643 else if (flags < 0)
9644 /* No change. */;
9645 else if (TREE_CODE (res) == FUNCTION_TYPE
9646 || TREE_CODE (res) == METHOD_TYPE)
9648 cp_ref_qualifier rqual = cp_ref_qualifier (flags & 3);
9649 bool late = (flags >> 2) & 1;
9650 cp_cv_quals quals = cp_cv_quals (flags >> 3);
9652 tree raises = tree_node ();
9653 if (raises == error_mark_node)
9654 raises = TYPE_RAISES_EXCEPTIONS (res);
9656 res = build_cp_fntype_variant (res, rqual, raises, late);
9657 if (TREE_CODE (res) == FUNCTION_TYPE)
9658 res = apply_memfn_quals (res, quals, rqual);
9660 else
9662 res = build_aligned_type (res, (1u << flags) >> 1);
9663 TYPE_USER_ALIGN (res) = true;
9666 if (tree attribs = tree_node ())
9667 res = cp_build_type_attribute_variant (res, attribs);
9669 int quals = i ();
9670 if (quals >= 0 && !get_overrun ())
9671 res = cp_build_qualified_type (res, quals);
9673 int tag = i ();
9674 if (!tag)
9676 tag = insert (res);
9677 if (res)
9678 dump (dumper::TREE)
9679 && dump ("Created:%d variant type %C", tag, TREE_CODE (res));
9681 else
9682 res = back_ref (tag);
9684 break;
9686 case tt_tinfo_var:
9687 case tt_tinfo_typedef:
9688 /* A tinfo var or typedef. */
9690 bool is_var = tag == tt_tinfo_var;
9691 unsigned ix = u ();
9692 tree type = NULL_TREE;
9694 if (is_var)
9696 tree name = tree_node ();
9697 type = tree_node ();
9699 if (!get_overrun ())
9700 res = get_tinfo_decl_direct (type, name, int (ix));
9702 else
9704 if (!get_overrun ())
9706 type = get_pseudo_tinfo_type (ix);
9707 res = TYPE_NAME (type);
9710 if (res)
9712 int tag = insert (res);
9713 dump (dumper::TREE)
9714 && dump ("Created tinfo_%s:%d %S:%u for %N",
9715 is_var ? "var" : "decl", tag, res, ix, type);
9716 if (!is_var)
9718 tag = insert (type);
9719 dump (dumper::TREE)
9720 && dump ("Created tinfo_type:%d %u %N", tag, ix, type);
9724 break;
9726 case tt_ptrmem_type:
9727 /* A pointer to member function. */
9729 tree type = tree_node ();
9730 if (type && TREE_CODE (type) == POINTER_TYPE
9731 && TREE_CODE (TREE_TYPE (type)) == METHOD_TYPE)
9733 res = build_ptrmemfunc_type (type);
9734 int tag = insert (res);
9735 dump (dumper::TREE) && dump ("Created:%d ptrmem type", tag);
9737 else
9738 set_overrun ();
9740 break;
9742 case tt_nttp_var:
9743 /* An NTTP object. */
9745 tree init = tree_node ();
9746 tree name = tree_node ();
9747 if (!get_overrun ())
9749 res = get_template_parm_object (init, name);
9750 int tag = insert (res);
9751 dump (dumper::TREE)
9752 && dump ("Created nttp object:%d %N", tag, name);
9755 break;
9757 case tt_enum_value:
9758 /* An enum const value. */
9760 if (tree decl = tree_node ())
9762 dump (dumper::TREE) && dump ("Read enum value %N", decl);
9763 res = DECL_INITIAL (decl);
9766 if (!res)
9767 set_overrun ();
9769 break;
9771 case tt_enum_decl:
9772 /* An enum decl. */
9774 tree ctx = tree_node ();
9775 tree name = tree_node ();
9777 if (!get_overrun ()
9778 && TREE_CODE (ctx) == ENUMERAL_TYPE)
9779 res = find_enum_member (ctx, name);
9781 if (!res)
9782 set_overrun ();
9783 else
9785 int tag = insert (res);
9786 dump (dumper::TREE)
9787 && dump ("Read enum decl:%d %C:%N", tag, TREE_CODE (res), res);
9790 break;
9792 case tt_data_member:
9793 /* A data member. */
9795 tree ctx = tree_node ();
9796 tree name = tree_node ();
9798 if (!get_overrun ()
9799 && RECORD_OR_UNION_TYPE_P (ctx))
9801 if (name)
9802 res = lookup_class_binding (ctx, name);
9803 else
9804 res = lookup_field_ident (ctx, u ());
9806 if (!res
9807 || TREE_CODE (res) != FIELD_DECL
9808 || DECL_CONTEXT (res) != ctx)
9809 res = NULL_TREE;
9812 if (!res)
9813 set_overrun ();
9814 else
9816 int tag = insert (res);
9817 dump (dumper::TREE)
9818 && dump ("Read member:%d %C:%N", tag, TREE_CODE (res), res);
9821 break;
9823 case tt_binfo:
9824 /* A BINFO. Walk the tree of the dominating type. */
9826 tree type;
9827 unsigned ix = binfo_mergeable (&type);
9828 if (type)
9830 res = TYPE_BINFO (type);
9831 for (; ix && res; res = TREE_CHAIN (res))
9832 ix--;
9833 if (!res)
9834 set_overrun ();
9837 if (get_overrun ())
9838 break;
9840 /* Insert binfo into backreferences. */
9841 tag = insert (res);
9842 dump (dumper::TREE) && dump ("Read binfo:%d %N", tag, res);
9844 break;
9846 case tt_vtable:
9848 unsigned ix = u ();
9849 tree ctx = tree_node ();
9850 dump (dumper::TREE) && dump ("Reading vtable %N[%u]", ctx, ix);
9851 if (TREE_CODE (ctx) == RECORD_TYPE && TYPE_LANG_SPECIFIC (ctx))
9852 for (res = CLASSTYPE_VTABLES (ctx); res; res = DECL_CHAIN (res))
9853 if (!ix--)
9854 break;
9855 if (!res)
9856 set_overrun ();
9858 break;
9860 case tt_thunk:
9862 int fixed = i ();
9863 tree target = tree_node ();
9864 tree virt = tree_node ();
9866 for (tree thunk = DECL_THUNKS (target);
9867 thunk; thunk = DECL_CHAIN (thunk))
9868 if (THUNK_FIXED_OFFSET (thunk) == fixed
9869 && !THUNK_VIRTUAL_OFFSET (thunk) == !virt
9870 && (!virt
9871 || tree_int_cst_equal (virt, THUNK_VIRTUAL_OFFSET (thunk))))
9873 res = thunk;
9874 break;
9877 int tag = insert (res);
9878 if (res)
9879 dump (dumper::TREE)
9880 && dump ("Read:%d thunk %N to %N", tag, DECL_NAME (res), target);
9881 else
9882 set_overrun ();
9884 break;
9886 case tt_clone_ref:
9888 tree target = tree_node ();
9889 tree name = tree_node ();
9891 if (DECL_P (target) && DECL_MAYBE_IN_CHARGE_CDTOR_P (target))
9893 tree clone;
9894 FOR_EVERY_CLONE (clone, target)
9895 if (DECL_NAME (clone) == name)
9897 res = clone;
9898 break;
9902 /* A clone might have a different vtable entry. */
9903 if (res && DECL_VIRTUAL_P (res))
9904 DECL_VINDEX (res) = tree_node ();
9906 if (!res)
9907 set_overrun ();
9908 int tag = insert (res);
9909 if (res)
9910 dump (dumper::TREE)
9911 && dump ("Read:%d clone %N of %N", tag, DECL_NAME (res), target);
9912 else
9913 set_overrun ();
9915 break;
9917 case tt_entity:
9918 /* Index into the entity table. Perhaps not loaded yet! */
9920 unsigned origin = state->slurp->remap_module (u ());
9921 unsigned ident = u ();
9922 module_state *from = (*modules)[origin];
9924 if (!origin || ident >= from->entity_num)
9925 set_overrun ();
9926 if (!get_overrun ())
9928 binding_slot *slot = &(*entity_ary)[from->entity_lwm + ident];
9929 if (slot->is_lazy ())
9930 if (!from->lazy_load (ident, slot))
9931 set_overrun ();
9932 res = *slot;
9935 if (res)
9937 const char *kind = (origin != state->mod ? "Imported" : "Named");
9938 int tag = insert (res);
9939 dump (dumper::TREE)
9940 && dump ("%s:%d %C:%N@%M", kind, tag, TREE_CODE (res),
9941 res, (*modules)[origin]);
9943 if (!add_indirects (res))
9945 set_overrun ();
9946 res = NULL_TREE;
9950 break;
9952 case tt_template:
9953 /* A template. */
9954 if (tree tpl = tree_node ())
9956 res = DECL_TEMPLATE_RESULT (tpl);
9957 dump (dumper::TREE)
9958 && dump ("Read template %C:%N", TREE_CODE (res), res);
9960 break;
9963 if (is_use && !unused && res && DECL_P (res) && !TREE_USED (res))
9965 /* Mark decl used as mark_used does -- we cannot call
9966 mark_used in the middle of streaming, we only need a subset
9967 of its functionality. */
9968 TREE_USED (res) = true;
9970 /* And for structured bindings also the underlying decl. */
9971 if (DECL_DECOMPOSITION_P (res) && DECL_DECOMP_BASE (res))
9972 TREE_USED (DECL_DECOMP_BASE (res)) = true;
9974 if (DECL_CLONED_FUNCTION_P (res))
9975 TREE_USED (DECL_CLONED_FUNCTION (res)) = true;
9978 dump.outdent ();
9979 return res;
9982 void
9983 trees_out::tpl_parms (tree parms, unsigned &tpl_levels)
9985 if (!parms)
9986 return;
9988 if (TREE_VISITED (parms))
9990 ref_node (parms);
9991 return;
9994 tpl_parms (TREE_CHAIN (parms), tpl_levels);
9996 tree vec = TREE_VALUE (parms);
9997 unsigned len = TREE_VEC_LENGTH (vec);
9998 /* Depth. */
9999 int tag = insert (parms);
10000 if (streaming_p ())
10002 i (len + 1);
10003 dump (dumper::TREE)
10004 && dump ("Writing template parms:%d level:%N length:%d",
10005 tag, TREE_PURPOSE (parms), len);
10007 tree_node (TREE_PURPOSE (parms));
10009 for (unsigned ix = 0; ix != len; ix++)
10011 tree parm = TREE_VEC_ELT (vec, ix);
10012 tree decl = TREE_VALUE (parm);
10014 gcc_checking_assert (DECL_TEMPLATE_PARM_P (decl));
10015 if (CHECKING_P)
10016 switch (TREE_CODE (decl))
10018 default: gcc_unreachable ();
10020 case TEMPLATE_DECL:
10021 gcc_assert ((TREE_CODE (TREE_TYPE (decl)) == TEMPLATE_TEMPLATE_PARM)
10022 && (TREE_CODE (DECL_TEMPLATE_RESULT (decl)) == TYPE_DECL)
10023 && (TYPE_NAME (TREE_TYPE (decl)) == decl));
10024 break;
10026 case TYPE_DECL:
10027 gcc_assert ((TREE_CODE (TREE_TYPE (decl)) == TEMPLATE_TYPE_PARM)
10028 && (TYPE_NAME (TREE_TYPE (decl)) == decl));
10029 break;
10031 case PARM_DECL:
10032 gcc_assert ((TREE_CODE (DECL_INITIAL (decl)) == TEMPLATE_PARM_INDEX)
10033 && (TREE_CODE (TEMPLATE_PARM_DECL (DECL_INITIAL (decl)))
10034 == CONST_DECL)
10035 && (DECL_TEMPLATE_PARM_P
10036 (TEMPLATE_PARM_DECL (DECL_INITIAL (decl)))));
10037 break;
10040 tree_node (decl);
10041 tree_node (TEMPLATE_PARM_CONSTRAINTS (parm));
10044 tpl_levels++;
10047 tree
10048 trees_in::tpl_parms (unsigned &tpl_levels)
10050 tree parms = NULL_TREE;
10052 while (int len = i ())
10054 if (len < 0)
10056 parms = back_ref (len);
10057 continue;
10060 len -= 1;
10061 parms = tree_cons (NULL_TREE, NULL_TREE, parms);
10062 int tag = insert (parms);
10063 TREE_PURPOSE (parms) = tree_node ();
10065 dump (dumper::TREE)
10066 && dump ("Reading template parms:%d level:%N length:%d",
10067 tag, TREE_PURPOSE (parms), len);
10069 tree vec = make_tree_vec (len);
10070 for (int ix = 0; ix != len; ix++)
10072 tree decl = tree_node ();
10073 if (!decl)
10074 return NULL_TREE;
10076 tree parm = build_tree_list (NULL, decl);
10077 TEMPLATE_PARM_CONSTRAINTS (parm) = tree_node ();
10079 TREE_VEC_ELT (vec, ix) = parm;
10082 TREE_VALUE (parms) = vec;
10083 tpl_levels++;
10086 return parms;
10089 void
10090 trees_out::tpl_parms_fini (tree tmpl, unsigned tpl_levels)
10092 for (tree parms = DECL_TEMPLATE_PARMS (tmpl);
10093 tpl_levels--; parms = TREE_CHAIN (parms))
10095 tree vec = TREE_VALUE (parms);
10097 tree_node (TREE_TYPE (vec));
10098 for (unsigned ix = TREE_VEC_LENGTH (vec); ix--;)
10100 tree parm = TREE_VEC_ELT (vec, ix);
10101 tree dflt = TREE_PURPOSE (parm);
10102 tree_node (dflt);
10104 if (streaming_p ())
10106 tree decl = TREE_VALUE (parm);
10107 if (TREE_CODE (decl) == TEMPLATE_DECL)
10109 tree ctx = DECL_CONTEXT (decl);
10110 tree inner = DECL_TEMPLATE_RESULT (decl);
10111 tree tpi = (TREE_CODE (inner) == TYPE_DECL
10112 ? TEMPLATE_TYPE_PARM_INDEX (TREE_TYPE (decl))
10113 : DECL_INITIAL (inner));
10114 bool original = (TEMPLATE_PARM_LEVEL (tpi)
10115 == TEMPLATE_PARM_ORIG_LEVEL (tpi));
10116 /* Original template template parms have a context
10117 of their owning template. Reduced ones do not. */
10118 gcc_checking_assert (original ? ctx == tmpl : !ctx);
10125 bool
10126 trees_in::tpl_parms_fini (tree tmpl, unsigned tpl_levels)
10128 for (tree parms = DECL_TEMPLATE_PARMS (tmpl);
10129 tpl_levels--; parms = TREE_CHAIN (parms))
10131 tree vec = TREE_VALUE (parms);
10133 TREE_TYPE (vec) = tree_node ();
10134 for (unsigned ix = TREE_VEC_LENGTH (vec); ix--;)
10136 tree parm = TREE_VEC_ELT (vec, ix);
10137 tree dflt = tree_node ();
10138 if (get_overrun ())
10139 return false;
10140 TREE_PURPOSE (parm) = dflt;
10142 tree decl = TREE_VALUE (parm);
10143 if (TREE_CODE (decl) == TEMPLATE_DECL)
10145 tree inner = DECL_TEMPLATE_RESULT (decl);
10146 tree tpi = (TREE_CODE (inner) == TYPE_DECL
10147 ? TEMPLATE_TYPE_PARM_INDEX (TREE_TYPE (decl))
10148 : DECL_INITIAL (inner));
10149 bool original = (TEMPLATE_PARM_LEVEL (tpi)
10150 == TEMPLATE_PARM_ORIG_LEVEL (tpi));
10151 /* Original template template parms have a context
10152 of their owning template. Reduced ones do not. */
10153 if (original)
10154 DECL_CONTEXT (decl) = tmpl;
10158 return true;
10161 /* PARMS is a LIST, one node per level.
10162 TREE_VALUE is a TREE_VEC of parm info for that level.
10163 each ELT is a TREE_LIST
10164 TREE_VALUE is PARM_DECL, TYPE_DECL or TEMPLATE_DECL
10165 TREE_PURPOSE is the default value. */
10167 void
10168 trees_out::tpl_header (tree tpl, unsigned *tpl_levels)
10170 tree parms = DECL_TEMPLATE_PARMS (tpl);
10171 tpl_parms (parms, *tpl_levels);
10173 /* Mark end. */
10174 if (streaming_p ())
10175 u (0);
10177 if (*tpl_levels)
10178 tree_node (TEMPLATE_PARMS_CONSTRAINTS (parms));
10181 bool
10182 trees_in::tpl_header (tree tpl, unsigned *tpl_levels)
10184 tree parms = tpl_parms (*tpl_levels);
10185 if (!parms)
10186 return false;
10188 DECL_TEMPLATE_PARMS (tpl) = parms;
10190 if (*tpl_levels)
10191 TEMPLATE_PARMS_CONSTRAINTS (parms) = tree_node ();
10193 return true;
10196 /* Stream skeleton parm nodes, with their flags, type & parm indices.
10197 All the parms will have consecutive tags. */
10199 void
10200 trees_out::fn_parms_init (tree fn)
10202 /* First init them. */
10203 int base_tag = ref_num - 1;
10204 int ix = 0;
10205 for (tree parm = DECL_ARGUMENTS (fn);
10206 parm; parm = DECL_CHAIN (parm), ix++)
10208 if (streaming_p ())
10210 start (parm);
10211 tree_node_bools (parm);
10213 int tag = insert (parm);
10214 gcc_checking_assert (base_tag - ix == tag);
10216 /* Mark the end. */
10217 if (streaming_p ())
10218 u (0);
10220 /* Now stream their contents. */
10221 ix = 0;
10222 for (tree parm = DECL_ARGUMENTS (fn);
10223 parm; parm = DECL_CHAIN (parm), ix++)
10225 if (streaming_p ())
10226 dump (dumper::TREE)
10227 && dump ("Writing parm:%d %u (%N) of %N",
10228 base_tag - ix, ix, parm, fn);
10229 tree_node_vals (parm);
10232 if (!streaming_p ())
10234 /* We must walk contract attrs so the dependency graph is complete. */
10235 for (tree contract = DECL_CONTRACTS (fn);
10236 contract;
10237 contract = CONTRACT_CHAIN (contract))
10238 tree_node (contract);
10241 /* Write a reference to contracts pre/post functions, if any, to avoid
10242 regenerating them in importers. */
10243 tree_node (DECL_PRE_FN (fn));
10244 tree_node (DECL_POST_FN (fn));
10247 /* Build skeleton parm nodes, read their flags, type & parm indices. */
10250 trees_in::fn_parms_init (tree fn)
10252 int base_tag = ~(int)back_refs.length ();
10254 tree *parm_ptr = &DECL_ARGUMENTS (fn);
10255 int ix = 0;
10256 for (; int code = u (); ix++)
10258 tree parm = start (code);
10259 if (!tree_node_bools (parm))
10260 return 0;
10262 int tag = insert (parm);
10263 gcc_checking_assert (base_tag - ix == tag);
10264 *parm_ptr = parm;
10265 parm_ptr = &DECL_CHAIN (parm);
10268 ix = 0;
10269 for (tree parm = DECL_ARGUMENTS (fn);
10270 parm; parm = DECL_CHAIN (parm), ix++)
10272 dump (dumper::TREE)
10273 && dump ("Reading parm:%d %u (%N) of %N",
10274 base_tag - ix, ix, parm, fn);
10275 if (!tree_node_vals (parm))
10276 return 0;
10279 /* Reload references to contract functions, if any. */
10280 tree pre_fn = tree_node ();
10281 tree post_fn = tree_node ();
10282 set_contract_functions (fn, pre_fn, post_fn);
10284 return base_tag;
10287 /* Read the remaining parm node data. Replace with existing (if
10288 non-null) in the map. */
10290 void
10291 trees_in::fn_parms_fini (int tag, tree fn, tree existing, bool is_defn)
10293 tree existing_parm = existing ? DECL_ARGUMENTS (existing) : NULL_TREE;
10294 tree parms = DECL_ARGUMENTS (fn);
10295 unsigned ix = 0;
10296 for (tree parm = parms; parm; parm = DECL_CHAIN (parm), ix++)
10298 if (existing_parm)
10300 if (is_defn && !DECL_SAVED_TREE (existing))
10302 /* If we're about to become the definition, set the
10303 names of the parms from us. */
10304 DECL_NAME (existing_parm) = DECL_NAME (parm);
10305 DECL_SOURCE_LOCATION (existing_parm) = DECL_SOURCE_LOCATION (parm);
10308 back_refs[~tag] = existing_parm;
10309 existing_parm = DECL_CHAIN (existing_parm);
10311 tag--;
10315 /* DEP is the depset of some decl we're streaming by value. Determine
10316 the merging behaviour. */
10318 merge_kind
10319 trees_out::get_merge_kind (tree decl, depset *dep)
10321 if (!dep)
10323 if (VAR_OR_FUNCTION_DECL_P (decl))
10325 /* Any var or function with template info should have DEP. */
10326 gcc_checking_assert (!DECL_LANG_SPECIFIC (decl)
10327 || !DECL_TEMPLATE_INFO (decl));
10328 if (DECL_LOCAL_DECL_P (decl))
10329 return MK_unique;
10332 /* Either unique, or some member of a class that cannot have an
10333 out-of-class definition. For instance a FIELD_DECL. */
10334 tree ctx = CP_DECL_CONTEXT (decl);
10335 if (TREE_CODE (ctx) == FUNCTION_DECL)
10337 /* USING_DECLs and NAMESPACE_DECLs cannot have DECL_TEMPLATE_INFO --
10338 this isn't permitting them to have one. */
10339 gcc_checking_assert (TREE_CODE (decl) == USING_DECL
10340 || TREE_CODE (decl) == NAMESPACE_DECL
10341 || !DECL_LANG_SPECIFIC (decl)
10342 || !DECL_TEMPLATE_INFO (decl));
10344 return MK_unique;
10347 if (TREE_CODE (decl) == TEMPLATE_DECL
10348 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
10349 return MK_local_friend;
10351 gcc_checking_assert (TYPE_P (ctx));
10352 if (TREE_CODE (decl) == USING_DECL)
10353 return MK_field;
10355 if (TREE_CODE (decl) == FIELD_DECL)
10357 if (DECL_NAME (decl))
10359 /* Anonymous FIELD_DECLs have a NULL name. */
10360 gcc_checking_assert (!IDENTIFIER_ANON_P (DECL_NAME (decl)));
10361 return MK_named;
10364 if (!DECL_NAME (decl)
10365 && !RECORD_OR_UNION_TYPE_P (TREE_TYPE (decl))
10366 && !DECL_BIT_FIELD_REPRESENTATIVE (decl))
10368 /* The underlying storage unit for a bitfield. We do not
10369 need to dedup it, because it's only reachable through
10370 the bitfields it represents. And those are deduped. */
10371 // FIXME: Is that assertion correct -- do we ever fish it
10372 // out and put it in an expr?
10373 gcc_checking_assert ((TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
10374 ? TREE_CODE (TREE_TYPE (TREE_TYPE (decl)))
10375 : TREE_CODE (TREE_TYPE (decl)))
10376 == INTEGER_TYPE);
10377 return MK_unique;
10380 return MK_field;
10383 if (TREE_CODE (decl) == CONST_DECL)
10384 return MK_named;
10386 if (TREE_CODE (decl) == VAR_DECL
10387 && DECL_VTABLE_OR_VTT_P (decl))
10388 return MK_vtable;
10390 if (DECL_THUNK_P (decl))
10391 /* Thunks are unique-enough, because they're only referenced
10392 from the vtable. And that's either new (so we want the
10393 thunks), or it's a duplicate (so it will be dropped). */
10394 return MK_unique;
10396 /* There should be no other cases. */
10397 gcc_unreachable ();
10400 gcc_checking_assert (TREE_CODE (decl) != FIELD_DECL
10401 && TREE_CODE (decl) != USING_DECL
10402 && TREE_CODE (decl) != CONST_DECL);
10404 if (is_key_order ())
10406 /* When doing the mergeablilty graph, there's an indirection to
10407 the actual depset. */
10408 gcc_assert (dep->is_special ());
10409 dep = dep->deps[0];
10412 gcc_checking_assert (decl == dep->get_entity ());
10414 merge_kind mk = MK_named;
10415 switch (dep->get_entity_kind ())
10417 default:
10418 gcc_unreachable ();
10420 case depset::EK_PARTIAL:
10421 mk = MK_partial;
10422 break;
10424 case depset::EK_DECL:
10426 tree ctx = CP_DECL_CONTEXT (decl);
10428 switch (TREE_CODE (ctx))
10430 default:
10431 gcc_unreachable ();
10433 case FUNCTION_DECL:
10434 // FIXME: This can occur for (a) voldemorty TYPE_DECLS
10435 // (which are returned from a function), or (b)
10436 // block-scope class definitions in template functions.
10437 // These are as unique as the containing function. While
10438 // on read-back we can discover if the CTX was a
10439 // duplicate, we don't have a mechanism to get from the
10440 // existing CTX to the existing version of this decl.
10441 gcc_checking_assert
10442 (DECL_IMPLICIT_TYPEDEF_P (STRIP_TEMPLATE (decl)));
10444 mk = MK_unique;
10445 break;
10447 case RECORD_TYPE:
10448 case UNION_TYPE:
10449 case NAMESPACE_DECL:
10450 if (DECL_NAME (decl) == as_base_identifier)
10452 mk = MK_as_base;
10453 break;
10456 /* A lambda may have a class as its context, even though it
10457 isn't a member in the traditional sense; see the test
10458 g++.dg/modules/lambda-6_a.C. */
10459 if (DECL_IMPLICIT_TYPEDEF_P (STRIP_TEMPLATE (decl))
10460 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
10461 if (tree scope
10462 = LAMBDA_EXPR_EXTRA_SCOPE (CLASSTYPE_LAMBDA_EXPR
10463 (TREE_TYPE (decl))))
10464 if (TREE_CODE (scope) == VAR_DECL
10465 && DECL_MODULE_KEYED_DECLS_P (scope))
10467 mk = MK_keyed;
10468 break;
10471 if (RECORD_OR_UNION_TYPE_P (ctx))
10473 if (IDENTIFIER_ANON_P (DECL_NAME (decl)))
10474 mk = MK_field;
10475 break;
10478 if (TREE_CODE (decl) == TEMPLATE_DECL
10479 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
10480 mk = MK_local_friend;
10481 else if (IDENTIFIER_ANON_P (DECL_NAME (decl)))
10483 if (DECL_IMPLICIT_TYPEDEF_P (decl)
10484 && UNSCOPED_ENUM_P (TREE_TYPE (decl))
10485 && TYPE_VALUES (TREE_TYPE (decl)))
10486 /* Keyed by first enum value, and underlying type. */
10487 mk = MK_enum;
10488 else
10489 /* No way to merge it, it is an ODR land-mine. */
10490 mk = MK_unique;
10494 break;
10496 case depset::EK_SPECIALIZATION:
10498 gcc_checking_assert (dep->is_special ());
10500 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
10501 /* An block-scope classes of templates are themselves
10502 templates. */
10503 gcc_checking_assert (DECL_IMPLICIT_TYPEDEF_P (decl));
10505 if (dep->is_friend_spec ())
10506 mk = MK_friend_spec;
10507 else if (dep->is_type_spec ())
10508 mk = MK_type_spec;
10509 else if (dep->is_alias ())
10510 mk = MK_alias_spec;
10511 else
10512 mk = MK_decl_spec;
10514 if (TREE_CODE (decl) == TEMPLATE_DECL)
10516 spec_entry *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
10517 if (TREE_CODE (entry->spec) != TEMPLATE_DECL)
10518 mk = merge_kind (mk | MK_tmpl_tmpl_mask);
10521 break;
10524 return mk;
10528 /* The container of DECL -- not necessarily its context! */
10530 tree
10531 trees_out::decl_container (tree decl)
10533 int use_tpl;
10534 tree tpl = NULL_TREE;
10535 if (tree template_info = node_template_info (decl, use_tpl))
10536 tpl = TI_TEMPLATE (template_info);
10537 if (tpl == decl)
10538 tpl = nullptr;
10540 /* Stream the template we're instantiated from. */
10541 tree_node (tpl);
10543 tree container = NULL_TREE;
10544 if (TREE_CODE (decl) == TEMPLATE_DECL
10545 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
10546 container = DECL_CHAIN (decl);
10547 else
10548 container = CP_DECL_CONTEXT (decl);
10550 if (TYPE_P (container))
10551 container = TYPE_NAME (container);
10553 tree_node (container);
10555 return container;
10558 tree
10559 trees_in::decl_container ()
10561 /* The maybe-template. */
10562 (void)tree_node ();
10564 tree container = tree_node ();
10566 return container;
10569 /* Write out key information about a mergeable DEP. Does not write
10570 the contents of DEP itself. The context has already been
10571 written. The container has already been streamed. */
10573 void
10574 trees_out::key_mergeable (int tag, merge_kind mk, tree decl, tree inner,
10575 tree container, depset *dep)
10577 if (dep && is_key_order ())
10579 gcc_checking_assert (dep->is_special ());
10580 dep = dep->deps[0];
10583 if (streaming_p ())
10584 dump (dumper::MERGE)
10585 && dump ("Writing:%d's %s merge key (%s) %C:%N", tag, merge_kind_name[mk],
10586 dep ? dep->entity_kind_name () : "contained",
10587 TREE_CODE (decl), decl);
10589 /* Now write the locating information. */
10590 if (mk & MK_template_mask)
10592 /* Specializations are located via their originating template,
10593 and the set of template args they specialize. */
10594 gcc_checking_assert (dep && dep->is_special ());
10595 spec_entry *entry = reinterpret_cast <spec_entry *> (dep->deps[0]);
10597 tree_node (entry->tmpl);
10598 tree_node (entry->args);
10599 if (mk & MK_tmpl_decl_mask)
10600 if (flag_concepts && TREE_CODE (inner) == VAR_DECL)
10602 /* Variable template partial specializations might need
10603 constraints (see spec_hasher::equal). It's simpler to
10604 write NULL when we don't need them. */
10605 tree constraints = NULL_TREE;
10607 if (uses_template_parms (entry->args))
10608 constraints = get_constraints (inner);
10609 tree_node (constraints);
10612 if (CHECKING_P)
10614 /* Make sure we can locate the decl. */
10615 tree existing = match_mergeable_specialization
10616 (bool (mk & MK_tmpl_decl_mask), entry);
10618 gcc_assert (existing);
10619 if (mk & MK_tmpl_decl_mask)
10621 if (mk & MK_tmpl_alias_mask)
10622 /* It should be in both tables. */
10623 gcc_checking_assert
10624 (same_type_p (match_mergeable_specialization (false, entry),
10625 TREE_TYPE (existing)));
10626 if (mk & MK_tmpl_tmpl_mask)
10627 existing = DECL_TI_TEMPLATE (existing);
10629 else
10631 if (mk & MK_tmpl_tmpl_mask)
10632 existing = CLASSTYPE_TI_TEMPLATE (existing);
10633 else
10634 existing = TYPE_NAME (existing);
10637 /* The walkabout should have found ourselves. */
10638 gcc_checking_assert (TREE_CODE (decl) == TYPE_DECL
10639 ? same_type_p (TREE_TYPE (decl),
10640 TREE_TYPE (existing))
10641 : existing == decl);
10644 else if (mk != MK_unique)
10646 merge_key key;
10647 tree name = DECL_NAME (decl);
10649 switch (mk)
10651 default:
10652 gcc_unreachable ();
10654 case MK_named:
10655 case MK_friend_spec:
10656 if (IDENTIFIER_CONV_OP_P (name))
10657 name = conv_op_identifier;
10659 if (TREE_CODE (inner) == FUNCTION_DECL)
10661 /* Functions are distinguished by parameter types. */
10662 tree fn_type = TREE_TYPE (inner);
10664 key.ref_q = type_memfn_rqual (fn_type);
10665 key.args = TYPE_ARG_TYPES (fn_type);
10667 if (tree reqs = get_constraints (inner))
10669 if (cxx_dialect < cxx20)
10670 reqs = CI_ASSOCIATED_CONSTRAINTS (reqs);
10671 else
10672 reqs = CI_DECLARATOR_REQS (reqs);
10673 key.constraints = reqs;
10676 if (IDENTIFIER_CONV_OP_P (name)
10677 || (decl != inner
10678 && !(name == fun_identifier
10679 /* In case the user names something _FUN */
10680 && LAMBDA_TYPE_P (DECL_CONTEXT (inner)))))
10681 /* And a function template, or conversion operator needs
10682 the return type. Except for the _FUN thunk of a
10683 generic lambda, which has a recursive decl_type'd
10684 return type. */
10685 // FIXME: What if the return type is a voldemort?
10686 key.ret = fndecl_declared_return_type (inner);
10688 break;
10690 case MK_field:
10692 unsigned ix = 0;
10693 if (TREE_CODE (inner) != FIELD_DECL)
10694 name = NULL_TREE;
10695 else
10696 gcc_checking_assert (!name || !IDENTIFIER_ANON_P (name));
10698 for (tree field = TYPE_FIELDS (TREE_TYPE (container));
10699 ; field = DECL_CHAIN (field))
10701 tree finner = STRIP_TEMPLATE (field);
10702 if (TREE_CODE (finner) == TREE_CODE (inner))
10704 if (finner == inner)
10705 break;
10706 ix++;
10709 key.index = ix;
10711 break;
10713 case MK_vtable:
10715 tree vtable = CLASSTYPE_VTABLES (TREE_TYPE (container));
10716 for (unsigned ix = 0; ; vtable = DECL_CHAIN (vtable), ix++)
10717 if (vtable == decl)
10719 key.index = ix;
10720 break;
10722 name = NULL_TREE;
10724 break;
10726 case MK_as_base:
10727 gcc_checking_assert
10728 (decl == TYPE_NAME (CLASSTYPE_AS_BASE (TREE_TYPE (container))));
10729 break;
10731 case MK_local_friend:
10733 /* Find by index on the class's DECL_LIST */
10734 unsigned ix = 0;
10735 for (tree decls = CLASSTYPE_DECL_LIST (TREE_CHAIN (decl));
10736 decls; decls = TREE_CHAIN (decls))
10737 if (!TREE_PURPOSE (decls))
10739 tree frnd = friend_from_decl_list (TREE_VALUE (decls));
10740 if (frnd == decl)
10741 break;
10742 ix++;
10744 key.index = ix;
10745 name = NULL_TREE;
10747 break;
10749 case MK_enum:
10751 /* Anonymous enums are located by their first identifier,
10752 and underlying type. */
10753 tree type = TREE_TYPE (decl);
10755 gcc_checking_assert (UNSCOPED_ENUM_P (type));
10756 /* Using the type name drops the bit precision we might
10757 have been using on the enum. */
10758 key.ret = TYPE_NAME (ENUM_UNDERLYING_TYPE (type));
10759 if (tree values = TYPE_VALUES (type))
10760 name = DECL_NAME (TREE_VALUE (values));
10762 break;
10764 case MK_keyed:
10766 gcc_checking_assert (LAMBDA_TYPE_P (TREE_TYPE (inner)));
10767 tree scope = LAMBDA_EXPR_EXTRA_SCOPE (CLASSTYPE_LAMBDA_EXPR
10768 (TREE_TYPE (inner)));
10769 gcc_checking_assert (TREE_CODE (scope) == VAR_DECL);
10770 auto *root = keyed_table->get (scope);
10771 unsigned ix = root->length ();
10772 /* If we don't find it, we'll write a really big number
10773 that the reader will ignore. */
10774 while (ix--)
10775 if ((*root)[ix] == inner)
10776 break;
10778 /* Use the keyed-to decl as the 'name'. */
10779 name = scope;
10780 key.index = ix;
10782 break;
10784 case MK_partial:
10786 tree ti = get_template_info (inner);
10787 key.constraints = get_constraints (inner);
10788 key.ret = TI_TEMPLATE (ti);
10789 key.args = TI_ARGS (ti);
10791 break;
10794 tree_node (name);
10795 if (streaming_p ())
10797 unsigned code = (key.ref_q << 0) | (key.index << 2);
10798 u (code);
10801 if (mk == MK_enum)
10802 tree_node (key.ret);
10803 else if (mk == MK_partial
10804 || (mk == MK_named && inner
10805 && TREE_CODE (inner) == FUNCTION_DECL))
10807 tree_node (key.ret);
10808 tree arg = key.args;
10809 if (mk == MK_named)
10810 while (arg && arg != void_list_node)
10812 tree_node (TREE_VALUE (arg));
10813 arg = TREE_CHAIN (arg);
10815 tree_node (arg);
10816 tree_node (key.constraints);
10821 /* DECL is a new declaration that may be duplicated in OVL. Use RET &
10822 ARGS to find its clone, or NULL. If DECL's DECL_NAME is NULL, this
10823 has been found by a proxy. It will be an enum type located by its
10824 first member.
10826 We're conservative with matches, so ambiguous decls will be
10827 registered as different, then lead to a lookup error if the two
10828 modules are both visible. Perhaps we want to do something similar
10829 to duplicate decls to get ODR errors on loading? We already have
10830 some special casing for namespaces. */
10832 static tree
10833 check_mergeable_decl (merge_kind mk, tree decl, tree ovl, merge_key const &key)
10835 tree found = NULL_TREE;
10836 for (ovl_iterator iter (ovl); !found && iter; ++iter)
10838 tree match = *iter;
10840 tree d_inner = decl;
10841 tree m_inner = match;
10843 again:
10844 if (TREE_CODE (d_inner) != TREE_CODE (m_inner))
10846 if (TREE_CODE (match) == NAMESPACE_DECL
10847 && !DECL_NAMESPACE_ALIAS (match))
10848 /* Namespaces are never overloaded. */
10849 found = match;
10851 continue;
10854 switch (TREE_CODE (d_inner))
10856 case TEMPLATE_DECL:
10857 if (template_heads_equivalent_p (d_inner, m_inner))
10859 d_inner = DECL_TEMPLATE_RESULT (d_inner);
10860 m_inner = DECL_TEMPLATE_RESULT (m_inner);
10861 if (d_inner == error_mark_node
10862 && TYPE_DECL_ALIAS_P (m_inner))
10864 found = match;
10865 break;
10867 goto again;
10869 break;
10871 case FUNCTION_DECL:
10872 if (tree m_type = TREE_TYPE (m_inner))
10873 if ((!key.ret
10874 || same_type_p (key.ret, fndecl_declared_return_type (m_inner)))
10875 && type_memfn_rqual (m_type) == key.ref_q
10876 && compparms (key.args, TYPE_ARG_TYPES (m_type))
10877 /* Reject if old is a "C" builtin and new is not "C".
10878 Matches decls_match behaviour. */
10879 && (!DECL_IS_UNDECLARED_BUILTIN (m_inner)
10880 || !DECL_EXTERN_C_P (m_inner)
10881 || DECL_EXTERN_C_P (d_inner))
10882 /* Reject if one is a different member of a
10883 guarded/pre/post fn set. */
10884 && (!flag_contracts
10885 || (DECL_IS_PRE_FN_P (d_inner)
10886 == DECL_IS_PRE_FN_P (m_inner)))
10887 && (!flag_contracts
10888 || (DECL_IS_POST_FN_P (d_inner)
10889 == DECL_IS_POST_FN_P (m_inner))))
10891 tree m_reqs = get_constraints (m_inner);
10892 if (m_reqs)
10894 if (cxx_dialect < cxx20)
10895 m_reqs = CI_ASSOCIATED_CONSTRAINTS (m_reqs);
10896 else
10897 m_reqs = CI_DECLARATOR_REQS (m_reqs);
10900 if (cp_tree_equal (key.constraints, m_reqs))
10901 found = match;
10903 break;
10905 case TYPE_DECL:
10906 if (DECL_IMPLICIT_TYPEDEF_P (d_inner)
10907 == DECL_IMPLICIT_TYPEDEF_P (m_inner))
10909 if (!IDENTIFIER_ANON_P (DECL_NAME (m_inner)))
10910 return match;
10911 else if (mk == MK_enum
10912 && (TYPE_NAME (ENUM_UNDERLYING_TYPE (TREE_TYPE (m_inner)))
10913 == key.ret))
10914 found = match;
10916 break;
10918 default:
10919 found = match;
10920 break;
10924 return found;
10927 /* DECL, INNER & TYPE are a skeleton set of nodes for a decl. Only
10928 the bools have been filled in. Read its merging key and merge it.
10929 Returns the existing decl if there is one. */
10931 tree
10932 trees_in::key_mergeable (int tag, merge_kind mk, tree decl, tree inner,
10933 tree type, tree container, bool is_attached)
10935 const char *kind = "new";
10936 tree existing = NULL_TREE;
10938 if (mk & MK_template_mask)
10940 // FIXME: We could stream the specialization hash?
10941 spec_entry spec;
10942 spec.tmpl = tree_node ();
10943 spec.args = tree_node ();
10945 if (get_overrun ())
10946 return error_mark_node;
10948 DECL_NAME (decl) = DECL_NAME (spec.tmpl);
10949 DECL_CONTEXT (decl) = DECL_CONTEXT (spec.tmpl);
10950 DECL_NAME (inner) = DECL_NAME (decl);
10951 DECL_CONTEXT (inner) = DECL_CONTEXT (decl);
10953 tree constr = NULL_TREE;
10954 bool is_decl = mk & MK_tmpl_decl_mask;
10955 if (is_decl)
10957 if (flag_concepts && TREE_CODE (inner) == VAR_DECL)
10959 constr = tree_node ();
10960 if (constr)
10961 set_constraints (inner, constr);
10963 spec.spec = (mk & MK_tmpl_tmpl_mask) ? inner : decl;
10965 else
10966 spec.spec = type;
10967 existing = match_mergeable_specialization (is_decl, &spec);
10968 if (constr)
10969 /* We'll add these back later, if this is the new decl. */
10970 remove_constraints (inner);
10972 if (!existing)
10973 ; /* We'll add to the table once read. */
10974 else if (mk & MK_tmpl_decl_mask)
10976 /* A declaration specialization. */
10977 if (mk & MK_tmpl_tmpl_mask)
10978 existing = DECL_TI_TEMPLATE (existing);
10980 else
10982 /* A type specialization. */
10983 if (mk & MK_tmpl_tmpl_mask)
10984 existing = CLASSTYPE_TI_TEMPLATE (existing);
10985 else
10986 existing = TYPE_NAME (existing);
10989 else if (mk == MK_unique)
10990 kind = "unique";
10991 else
10993 tree name = tree_node ();
10995 merge_key key;
10996 unsigned code = u ();
10997 key.ref_q = cp_ref_qualifier ((code >> 0) & 3);
10998 key.index = code >> 2;
11000 if (mk == MK_enum)
11001 key.ret = tree_node ();
11002 else if (mk == MK_partial
11003 || ((mk == MK_named || mk == MK_friend_spec)
11004 && TREE_CODE (inner) == FUNCTION_DECL))
11006 key.ret = tree_node ();
11007 tree arg, *arg_ptr = &key.args;
11008 while ((arg = tree_node ())
11009 && arg != void_list_node
11010 && mk != MK_partial)
11012 *arg_ptr = tree_cons (NULL_TREE, arg, NULL_TREE);
11013 arg_ptr = &TREE_CHAIN (*arg_ptr);
11015 *arg_ptr = arg;
11016 key.constraints = tree_node ();
11019 if (get_overrun ())
11020 return error_mark_node;
11022 if (mk < MK_indirect_lwm)
11024 DECL_NAME (decl) = name;
11025 DECL_CONTEXT (decl) = FROB_CONTEXT (container);
11027 DECL_NAME (inner) = DECL_NAME (decl);
11028 DECL_CONTEXT (inner) = DECL_CONTEXT (decl);
11030 if (mk == MK_partial)
11032 for (tree spec = DECL_TEMPLATE_SPECIALIZATIONS (key.ret);
11033 spec; spec = TREE_CHAIN (spec))
11035 tree tmpl = TREE_VALUE (spec);
11036 tree ti = get_template_info (tmpl);
11037 if (template_args_equal (key.args, TI_ARGS (ti))
11038 && cp_tree_equal (key.constraints,
11039 get_constraints
11040 (DECL_TEMPLATE_RESULT (tmpl))))
11042 existing = tmpl;
11043 break;
11047 else
11048 switch (TREE_CODE (container))
11050 default:
11051 gcc_unreachable ();
11053 case NAMESPACE_DECL:
11054 if (mk == MK_keyed)
11056 if (DECL_LANG_SPECIFIC (name)
11057 && VAR_OR_FUNCTION_DECL_P (name)
11058 && DECL_MODULE_KEYED_DECLS_P (name))
11059 if (auto *set = keyed_table->get (name))
11060 if (key.index < set->length ())
11062 existing = (*set)[key.index];
11063 if (existing)
11065 gcc_checking_assert
11066 (DECL_IMPLICIT_TYPEDEF_P (existing));
11067 if (inner != decl)
11068 existing
11069 = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (existing));
11073 else if (is_attached
11074 && !(state->is_module () || state->is_partition ()))
11075 kind = "unique";
11076 else
11078 gcc_checking_assert (mk == MK_named || mk == MK_enum);
11079 tree mvec;
11080 tree *vslot = mergeable_namespace_slots (container, name,
11081 is_attached, &mvec);
11082 existing = check_mergeable_decl (mk, decl, *vslot, key);
11083 if (!existing)
11084 add_mergeable_namespace_entity (vslot, decl);
11085 else
11087 /* Note that we now have duplicates to deal with in
11088 name lookup. */
11089 if (is_attached)
11090 BINDING_VECTOR_PARTITION_DUPS_P (mvec) = true;
11091 else
11092 BINDING_VECTOR_GLOBAL_DUPS_P (mvec) = true;
11095 break;
11097 case FUNCTION_DECL:
11098 // FIXME: What about a voldemort? how do we find what it
11099 // duplicates? Do we have to number vmorts relative to
11100 // their containing function? But how would that work
11101 // when matching an in-TU declaration?
11102 kind = "unique";
11103 break;
11105 case TYPE_DECL:
11106 if (is_attached && !(state->is_module () || state->is_partition ())
11107 /* Implicit member functions can come from
11108 anywhere. */
11109 && !(DECL_ARTIFICIAL (decl)
11110 && TREE_CODE (decl) == FUNCTION_DECL
11111 && !DECL_THUNK_P (decl)))
11112 kind = "unique";
11113 else
11115 tree ctx = TREE_TYPE (container);
11117 /* For some reason templated enumeral types are not marked
11118 as COMPLETE_TYPE_P, even though they have members.
11119 This may well be a bug elsewhere. */
11120 if (TREE_CODE (ctx) == ENUMERAL_TYPE)
11121 existing = find_enum_member (ctx, name);
11122 else if (COMPLETE_TYPE_P (ctx))
11124 switch (mk)
11126 default:
11127 gcc_unreachable ();
11129 case MK_named:
11130 existing = lookup_class_binding (ctx, name);
11131 if (existing)
11133 tree inner = decl;
11134 if (TREE_CODE (inner) == TEMPLATE_DECL
11135 && !DECL_MEMBER_TEMPLATE_P (inner))
11136 inner = DECL_TEMPLATE_RESULT (inner);
11138 existing = check_mergeable_decl
11139 (mk, inner, existing, key);
11141 if (!existing && DECL_ALIAS_TEMPLATE_P (decl))
11142 {} // FIXME: Insert into specialization
11143 // tables, we'll need the arguments for that!
11145 break;
11147 case MK_field:
11149 unsigned ix = key.index;
11150 for (tree field = TYPE_FIELDS (ctx);
11151 field; field = DECL_CHAIN (field))
11153 tree finner = STRIP_TEMPLATE (field);
11154 if (TREE_CODE (finner) == TREE_CODE (inner))
11155 if (!ix--)
11157 existing = field;
11158 break;
11162 break;
11164 case MK_vtable:
11166 unsigned ix = key.index;
11167 for (tree vtable = CLASSTYPE_VTABLES (ctx);
11168 vtable; vtable = DECL_CHAIN (vtable))
11169 if (!ix--)
11171 existing = vtable;
11172 break;
11175 break;
11177 case MK_as_base:
11179 tree as_base = CLASSTYPE_AS_BASE (ctx);
11180 if (as_base && as_base != ctx)
11181 existing = TYPE_NAME (as_base);
11183 break;
11185 case MK_local_friend:
11187 unsigned ix = key.index;
11188 for (tree decls = CLASSTYPE_DECL_LIST (ctx);
11189 decls; decls = TREE_CHAIN (decls))
11190 if (!TREE_PURPOSE (decls) && !ix--)
11192 existing
11193 = friend_from_decl_list (TREE_VALUE (decls));
11194 break;
11197 break;
11200 if (existing && mk < MK_indirect_lwm && mk != MK_partial
11201 && TREE_CODE (decl) == TEMPLATE_DECL
11202 && !DECL_MEMBER_TEMPLATE_P (decl))
11204 tree ti;
11205 if (DECL_IMPLICIT_TYPEDEF_P (existing))
11206 ti = TYPE_TEMPLATE_INFO (TREE_TYPE (existing));
11207 else
11208 ti = DECL_TEMPLATE_INFO (existing);
11209 existing = TI_TEMPLATE (ti);
11216 dump (dumper::MERGE)
11217 && dump ("Read:%d's %s merge key (%s) %C:%N", tag, merge_kind_name[mk],
11218 existing ? "matched" : kind, TREE_CODE (decl), decl);
11220 return existing;
11223 void
11224 trees_out::binfo_mergeable (tree binfo)
11226 tree dom = binfo;
11227 while (tree parent = BINFO_INHERITANCE_CHAIN (dom))
11228 dom = parent;
11229 tree type = BINFO_TYPE (dom);
11230 gcc_checking_assert (TYPE_BINFO (type) == dom);
11231 tree_node (type);
11232 if (streaming_p ())
11234 unsigned ix = 0;
11235 for (; dom != binfo; dom = TREE_CHAIN (dom))
11236 ix++;
11237 u (ix);
11241 unsigned
11242 trees_in::binfo_mergeable (tree *type)
11244 *type = tree_node ();
11245 return u ();
11248 /* DECL is a just streamed mergeable decl that should match EXISTING. Check
11249 it does and issue an appropriate diagnostic if not. Merge any
11250 bits from DECL to EXISTING. This is stricter matching than
11251 decls_match, because we can rely on ODR-sameness, and we cannot use
11252 decls_match because it can cause instantiations of constraints. */
11254 bool
11255 trees_in::is_matching_decl (tree existing, tree decl, bool is_typedef)
11257 // FIXME: We should probably do some duplicate decl-like stuff here
11258 // (beware, default parms should be the same?) Can we just call
11259 // duplicate_decls and teach it how to handle the module-specific
11260 // permitted/required duplications?
11262 // We know at this point that the decls have matched by key, so we
11263 // can elide some of the checking
11264 gcc_checking_assert (TREE_CODE (existing) == TREE_CODE (decl));
11266 tree d_inner = decl;
11267 tree e_inner = existing;
11268 if (TREE_CODE (decl) == TEMPLATE_DECL)
11270 d_inner = DECL_TEMPLATE_RESULT (d_inner);
11271 e_inner = DECL_TEMPLATE_RESULT (e_inner);
11272 gcc_checking_assert (TREE_CODE (e_inner) == TREE_CODE (d_inner));
11275 if (TREE_CODE (d_inner) == FUNCTION_DECL)
11277 tree e_ret = fndecl_declared_return_type (existing);
11278 tree d_ret = fndecl_declared_return_type (decl);
11280 if (decl != d_inner && DECL_NAME (d_inner) == fun_identifier
11281 && LAMBDA_TYPE_P (DECL_CONTEXT (d_inner)))
11282 /* This has a recursive type that will compare different. */;
11283 else if (!same_type_p (d_ret, e_ret))
11284 goto mismatch;
11286 tree e_type = TREE_TYPE (e_inner);
11287 tree d_type = TREE_TYPE (d_inner);
11289 if (DECL_EXTERN_C_P (d_inner) != DECL_EXTERN_C_P (e_inner))
11290 goto mismatch;
11292 for (tree e_args = TYPE_ARG_TYPES (e_type),
11293 d_args = TYPE_ARG_TYPES (d_type);
11294 e_args != d_args && (e_args || d_args);
11295 e_args = TREE_CHAIN (e_args), d_args = TREE_CHAIN (d_args))
11297 if (!(e_args && d_args))
11298 goto mismatch;
11300 if (!same_type_p (TREE_VALUE (d_args), TREE_VALUE (e_args)))
11301 goto mismatch;
11303 // FIXME: Check default values
11306 /* If EXISTING has an undeduced or uninstantiated exception
11307 specification, but DECL does not, propagate the exception
11308 specification. Otherwise we end up asserting or trying to
11309 instantiate it in the middle of loading. */
11310 tree e_spec = TYPE_RAISES_EXCEPTIONS (e_type);
11311 tree d_spec = TYPE_RAISES_EXCEPTIONS (d_type);
11312 if (DEFERRED_NOEXCEPT_SPEC_P (e_spec))
11314 if (!DEFERRED_NOEXCEPT_SPEC_P (d_spec)
11315 || (UNEVALUATED_NOEXCEPT_SPEC_P (e_spec)
11316 && !UNEVALUATED_NOEXCEPT_SPEC_P (d_spec)))
11318 dump (dumper::MERGE)
11319 && dump ("Propagating instantiated noexcept to %N", existing);
11320 TREE_TYPE (existing) = d_type;
11322 /* Propagate to existing clones. */
11323 tree clone;
11324 FOR_EACH_CLONE (clone, existing)
11326 if (TREE_TYPE (clone) == e_type)
11327 TREE_TYPE (clone) = d_type;
11328 else
11329 TREE_TYPE (clone)
11330 = build_exception_variant (TREE_TYPE (clone), d_spec);
11334 else if (!DEFERRED_NOEXCEPT_SPEC_P (d_spec)
11335 && !comp_except_specs (d_spec, e_spec, ce_type))
11336 goto mismatch;
11338 else if (is_typedef)
11340 if (!DECL_ORIGINAL_TYPE (e_inner)
11341 || !same_type_p (DECL_ORIGINAL_TYPE (d_inner),
11342 DECL_ORIGINAL_TYPE (e_inner)))
11343 goto mismatch;
11345 /* Using cp_tree_equal because we can meet TYPE_ARGUMENT_PACKs
11346 here. I suspect the entities that directly do that are things
11347 that shouldn't go to duplicate_decls (FIELD_DECLs etc). */
11348 else if (!cp_tree_equal (TREE_TYPE (decl), TREE_TYPE (existing)))
11350 mismatch:
11351 if (DECL_IS_UNDECLARED_BUILTIN (existing))
11352 /* Just like duplicate_decls, presum the user knows what
11353 they're doing in overriding a builtin. */
11354 TREE_TYPE (existing) = TREE_TYPE (decl);
11355 else
11357 // FIXME:QOI Might be template specialization from a module,
11358 // not necessarily global module
11359 error_at (DECL_SOURCE_LOCATION (decl),
11360 "conflicting global module declaration %#qD", decl);
11361 inform (DECL_SOURCE_LOCATION (existing),
11362 "existing declaration %#qD", existing);
11363 return false;
11367 if (DECL_IS_UNDECLARED_BUILTIN (existing)
11368 && !DECL_IS_UNDECLARED_BUILTIN (decl))
11370 /* We're matching a builtin that the user has yet to declare.
11371 We are the one! This is very much duplicate-decl
11372 shenanigans. */
11373 DECL_SOURCE_LOCATION (existing) = DECL_SOURCE_LOCATION (decl);
11374 if (TREE_CODE (decl) != TYPE_DECL)
11376 /* Propagate exceptions etc. */
11377 TREE_TYPE (existing) = TREE_TYPE (decl);
11378 TREE_NOTHROW (existing) = TREE_NOTHROW (decl);
11380 /* This is actually an import! */
11381 DECL_MODULE_IMPORT_P (existing) = true;
11383 /* Yay, sliced! */
11384 existing->base = decl->base;
11386 if (TREE_CODE (decl) == FUNCTION_DECL)
11388 /* Ew :( */
11389 memcpy (&existing->decl_common.size,
11390 &decl->decl_common.size,
11391 (offsetof (tree_decl_common, pt_uid)
11392 - offsetof (tree_decl_common, size)));
11393 auto bltin_class = DECL_BUILT_IN_CLASS (decl);
11394 existing->function_decl.built_in_class = bltin_class;
11395 auto fncode = DECL_UNCHECKED_FUNCTION_CODE (decl);
11396 DECL_UNCHECKED_FUNCTION_CODE (existing) = fncode;
11397 if (existing->function_decl.built_in_class == BUILT_IN_NORMAL)
11399 if (builtin_decl_explicit_p (built_in_function (fncode)))
11400 switch (fncode)
11402 case BUILT_IN_STPCPY:
11403 set_builtin_decl_implicit_p
11404 (built_in_function (fncode), true);
11405 break;
11406 default:
11407 set_builtin_decl_declared_p
11408 (built_in_function (fncode), true);
11409 break;
11411 copy_attributes_to_builtin (decl);
11416 if (VAR_OR_FUNCTION_DECL_P (decl)
11417 && DECL_TEMPLATE_INSTANTIATED (decl))
11418 /* Don't instantiate again! */
11419 DECL_TEMPLATE_INSTANTIATED (existing) = true;
11421 if (TREE_CODE (d_inner) == FUNCTION_DECL
11422 && DECL_DECLARED_INLINE_P (d_inner))
11423 DECL_DECLARED_INLINE_P (e_inner) = true;
11424 if (!DECL_EXTERNAL (d_inner))
11425 DECL_EXTERNAL (e_inner) = false;
11427 // FIXME: Check default tmpl and fn parms here
11429 return true;
11432 /* FN is an implicit member function that we've discovered is new to
11433 the class. Add it to the TYPE_FIELDS chain and the method vector.
11434 Reset the appropriate classtype lazy flag. */
11436 bool
11437 trees_in::install_implicit_member (tree fn)
11439 tree ctx = DECL_CONTEXT (fn);
11440 tree name = DECL_NAME (fn);
11441 /* We know these are synthesized, so the set of expected prototypes
11442 is quite restricted. We're not validating correctness, just
11443 distinguishing beteeen the small set of possibilities. */
11444 tree parm_type = TREE_VALUE (FUNCTION_FIRST_USER_PARMTYPE (fn));
11445 if (IDENTIFIER_CTOR_P (name))
11447 if (CLASSTYPE_LAZY_DEFAULT_CTOR (ctx)
11448 && VOID_TYPE_P (parm_type))
11449 CLASSTYPE_LAZY_DEFAULT_CTOR (ctx) = false;
11450 else if (!TYPE_REF_P (parm_type))
11451 return false;
11452 else if (CLASSTYPE_LAZY_COPY_CTOR (ctx)
11453 && !TYPE_REF_IS_RVALUE (parm_type))
11454 CLASSTYPE_LAZY_COPY_CTOR (ctx) = false;
11455 else if (CLASSTYPE_LAZY_MOVE_CTOR (ctx))
11456 CLASSTYPE_LAZY_MOVE_CTOR (ctx) = false;
11457 else
11458 return false;
11460 else if (IDENTIFIER_DTOR_P (name))
11462 if (CLASSTYPE_LAZY_DESTRUCTOR (ctx))
11463 CLASSTYPE_LAZY_DESTRUCTOR (ctx) = false;
11464 else
11465 return false;
11466 if (DECL_VIRTUAL_P (fn))
11467 /* A virtual dtor should have been created when the class
11468 became complete. */
11469 return false;
11471 else if (name == assign_op_identifier)
11473 if (!TYPE_REF_P (parm_type))
11474 return false;
11475 else if (CLASSTYPE_LAZY_COPY_ASSIGN (ctx)
11476 && !TYPE_REF_IS_RVALUE (parm_type))
11477 CLASSTYPE_LAZY_COPY_ASSIGN (ctx) = false;
11478 else if (CLASSTYPE_LAZY_MOVE_ASSIGN (ctx))
11479 CLASSTYPE_LAZY_MOVE_ASSIGN (ctx) = false;
11480 else
11481 return false;
11483 else
11484 return false;
11486 dump (dumper::MERGE) && dump ("Adding implicit member %N", fn);
11488 DECL_CHAIN (fn) = TYPE_FIELDS (ctx);
11489 TYPE_FIELDS (ctx) = fn;
11491 add_method (ctx, fn, false);
11493 /* Propagate TYPE_FIELDS. */
11494 fixup_type_variants (ctx);
11496 return true;
11499 /* Return non-zero if DECL has a definition that would be interesting to
11500 write out. */
11502 static bool
11503 has_definition (tree decl)
11505 bool is_tmpl = TREE_CODE (decl) == TEMPLATE_DECL;
11506 if (is_tmpl)
11507 decl = DECL_TEMPLATE_RESULT (decl);
11509 switch (TREE_CODE (decl))
11511 default:
11512 break;
11514 case FUNCTION_DECL:
11515 if (!DECL_SAVED_TREE (decl))
11516 /* Not defined. */
11517 break;
11519 if (DECL_DECLARED_INLINE_P (decl))
11520 return true;
11522 if (DECL_THIS_STATIC (decl)
11523 && (header_module_p ()
11524 || (!DECL_LANG_SPECIFIC (decl) || !DECL_MODULE_PURVIEW_P (decl))))
11525 /* GM static function. */
11526 return true;
11528 if (DECL_TEMPLATE_INFO (decl))
11530 int use_tpl = DECL_USE_TEMPLATE (decl);
11532 // FIXME: Partial specializations have definitions too.
11533 if (use_tpl < 2)
11534 return true;
11536 break;
11538 case TYPE_DECL:
11540 tree type = TREE_TYPE (decl);
11541 if (type == TYPE_MAIN_VARIANT (type)
11542 && decl == TYPE_NAME (type)
11543 && (TREE_CODE (type) == ENUMERAL_TYPE
11544 ? TYPE_VALUES (type) : TYPE_FIELDS (type)))
11545 return true;
11547 break;
11549 case VAR_DECL:
11550 if (DECL_LANG_SPECIFIC (decl)
11551 && DECL_TEMPLATE_INFO (decl))
11552 return DECL_INITIAL (decl);
11553 else
11555 if (!DECL_INITIALIZED_P (decl))
11556 return false;
11558 if (header_module_p ()
11559 || (!DECL_LANG_SPECIFIC (decl) || !DECL_MODULE_PURVIEW_P (decl)))
11560 /* GM static variable. */
11561 return true;
11563 if (!TREE_CONSTANT (decl))
11564 return false;
11566 return true;
11568 break;
11570 case CONCEPT_DECL:
11571 if (DECL_INITIAL (decl))
11572 return true;
11574 break;
11577 return false;
11580 uintptr_t *
11581 trees_in::find_duplicate (tree existing)
11583 if (!duplicates)
11584 return NULL;
11586 return duplicates->get (existing);
11589 /* We're starting to read a duplicate DECL. EXISTING is the already
11590 known node. */
11592 void
11593 trees_in::register_duplicate (tree decl, tree existing)
11595 if (!duplicates)
11596 duplicates = new duplicate_hash_map (40);
11598 bool existed;
11599 uintptr_t &slot = duplicates->get_or_insert (existing, &existed);
11600 gcc_checking_assert (!existed);
11601 slot = reinterpret_cast<uintptr_t> (decl);
11604 /* We've read a definition of MAYBE_EXISTING. If not a duplicate,
11605 return MAYBE_EXISTING (into which the definition should be
11606 installed). Otherwise return NULL if already known bad, or the
11607 duplicate we read (for ODR checking, or extracting additional merge
11608 information). */
11610 tree
11611 trees_in::odr_duplicate (tree maybe_existing, bool has_defn)
11613 tree res = NULL_TREE;
11615 if (uintptr_t *dup = find_duplicate (maybe_existing))
11617 if (!(*dup & 1))
11618 res = reinterpret_cast<tree> (*dup);
11620 else
11621 res = maybe_existing;
11623 assert_definition (maybe_existing, res && !has_defn);
11625 // FIXME: We probably need to return the template, so that the
11626 // template header can be checked?
11627 return res ? STRIP_TEMPLATE (res) : NULL_TREE;
11630 /* The following writer functions rely on the current behaviour of
11631 depset::hash::add_dependency making the decl and defn depset nodes
11632 depend on eachother. That way we don't have to worry about seeding
11633 the tree map with named decls that cannot be looked up by name (I.e
11634 template and function parms). We know the decl and definition will
11635 be in the same cluster, which is what we want. */
11637 void
11638 trees_out::write_function_def (tree decl)
11640 tree_node (DECL_RESULT (decl));
11641 tree_node (DECL_INITIAL (decl));
11642 tree_node (DECL_SAVED_TREE (decl));
11643 tree_node (DECL_FRIEND_CONTEXT (decl));
11645 constexpr_fundef *cexpr = retrieve_constexpr_fundef (decl);
11647 if (streaming_p ())
11648 u (cexpr != nullptr);
11649 if (cexpr)
11651 chained_decls (cexpr->parms);
11652 tree_node (cexpr->result);
11653 tree_node (cexpr->body);
11656 if (streaming_p ())
11658 unsigned flags = 0;
11660 if (DECL_NOT_REALLY_EXTERN (decl))
11661 flags |= 1;
11663 u (flags);
11667 void
11668 trees_out::mark_function_def (tree)
11672 bool
11673 trees_in::read_function_def (tree decl, tree maybe_template)
11675 dump () && dump ("Reading function definition %N", decl);
11676 tree result = tree_node ();
11677 tree initial = tree_node ();
11678 tree saved = tree_node ();
11679 tree context = tree_node ();
11680 constexpr_fundef cexpr;
11682 tree maybe_dup = odr_duplicate (maybe_template, DECL_SAVED_TREE (decl));
11683 bool installing = maybe_dup && !DECL_SAVED_TREE (decl);
11685 if (u ())
11687 cexpr.parms = chained_decls ();
11688 cexpr.result = tree_node ();
11689 cexpr.body = tree_node ();
11690 cexpr.decl = decl;
11692 else
11693 cexpr.decl = NULL_TREE;
11695 unsigned flags = u ();
11697 if (get_overrun ())
11698 return NULL_TREE;
11700 if (installing)
11702 DECL_NOT_REALLY_EXTERN (decl) = flags & 1;
11703 DECL_RESULT (decl) = result;
11704 DECL_INITIAL (decl) = initial;
11705 DECL_SAVED_TREE (decl) = saved;
11707 if (context)
11708 SET_DECL_FRIEND_CONTEXT (decl, context);
11709 if (cexpr.decl)
11710 register_constexpr_fundef (cexpr);
11711 post_process (maybe_template);
11713 else if (maybe_dup)
11715 // FIXME:QOI Check matching defn
11718 return true;
11721 /* Also for CONCEPT_DECLs. */
11723 void
11724 trees_out::write_var_def (tree decl)
11726 tree init = DECL_INITIAL (decl);
11727 tree_node (init);
11728 if (!init)
11730 tree dyn_init = NULL_TREE;
11732 /* We only need to write initializers in header modules. */
11733 if (header_module_p () && DECL_NONTRIVIALLY_INITIALIZED_P (decl))
11735 dyn_init = value_member (decl,
11736 CP_DECL_THREAD_LOCAL_P (decl)
11737 ? tls_aggregates : static_aggregates);
11738 gcc_checking_assert (dyn_init);
11739 /* Mark it so write_inits knows this is needed. */
11740 TREE_LANG_FLAG_0 (dyn_init) = true;
11741 dyn_init = TREE_PURPOSE (dyn_init);
11743 tree_node (dyn_init);
11747 void
11748 trees_out::mark_var_def (tree)
11752 bool
11753 trees_in::read_var_def (tree decl, tree maybe_template)
11755 /* Do not mark the virtual table entries as used. */
11756 bool vtable = VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl);
11757 unused += vtable;
11758 tree init = tree_node ();
11759 tree dyn_init = init ? NULL_TREE : tree_node ();
11760 unused -= vtable;
11762 if (get_overrun ())
11763 return false;
11765 bool initialized = (VAR_P (decl) ? bool (DECL_INITIALIZED_P (decl))
11766 : bool (DECL_INITIAL (decl)));
11767 tree maybe_dup = odr_duplicate (maybe_template, initialized);
11768 bool installing = maybe_dup && !initialized;
11769 if (installing)
11771 if (DECL_EXTERNAL (decl))
11772 DECL_NOT_REALLY_EXTERN (decl) = true;
11773 if (VAR_P (decl))
11775 DECL_INITIALIZED_P (decl) = true;
11776 if (maybe_dup && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (maybe_dup))
11777 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
11779 DECL_INITIAL (decl) = init;
11780 if (!dyn_init)
11782 else if (CP_DECL_THREAD_LOCAL_P (decl))
11783 tls_aggregates = tree_cons (dyn_init, decl, tls_aggregates);
11784 else
11785 static_aggregates = tree_cons (dyn_init, decl, static_aggregates);
11787 else if (maybe_dup)
11789 // FIXME:QOI Check matching defn
11792 return true;
11795 /* If MEMBER doesn't have an independent life outside the class,
11796 return it (or its TEMPLATE_DECL). Otherwise NULL. */
11798 static tree
11799 member_owned_by_class (tree member)
11801 gcc_assert (DECL_P (member));
11803 /* Clones are owned by their origin. */
11804 if (DECL_CLONED_FUNCTION_P (member))
11805 return NULL;
11807 if (TREE_CODE (member) == FIELD_DECL)
11808 /* FIELD_DECLS can have template info in some cases. We always
11809 want the FIELD_DECL though, as there's never a TEMPLATE_DECL
11810 wrapping them. */
11811 return member;
11813 int use_tpl = -1;
11814 if (tree ti = node_template_info (member, use_tpl))
11816 // FIXME: Don't bail on things that CANNOT have their own
11817 // template header. No, make sure they're in the same cluster.
11818 if (use_tpl > 0)
11819 return NULL_TREE;
11821 if (DECL_TEMPLATE_RESULT (TI_TEMPLATE (ti)) == member)
11822 member = TI_TEMPLATE (ti);
11824 return member;
11827 void
11828 trees_out::write_class_def (tree defn)
11830 gcc_assert (DECL_P (defn));
11831 if (streaming_p ())
11832 dump () && dump ("Writing class definition %N", defn);
11834 tree type = TREE_TYPE (defn);
11835 tree_node (TYPE_SIZE (type));
11836 tree_node (TYPE_SIZE_UNIT (type));
11837 tree_node (TYPE_VFIELD (type));
11838 tree_node (TYPE_BINFO (type));
11840 vec_chained_decls (TYPE_FIELDS (type));
11842 /* Every class but __as_base has a type-specific. */
11843 gcc_checking_assert (!TYPE_LANG_SPECIFIC (type) == IS_FAKE_BASE_TYPE (type));
11845 if (TYPE_LANG_SPECIFIC (type))
11848 vec<tree, va_gc> *v = CLASSTYPE_MEMBER_VEC (type);
11849 if (!v)
11851 gcc_checking_assert (!streaming_p ());
11852 /* Force a class vector. */
11853 v = set_class_bindings (type, -1);
11854 gcc_checking_assert (v);
11857 unsigned len = v->length ();
11858 if (streaming_p ())
11859 u (len);
11860 for (unsigned ix = 0; ix != len; ix++)
11862 tree m = (*v)[ix];
11863 if (TREE_CODE (m) == TYPE_DECL
11864 && DECL_ARTIFICIAL (m)
11865 && TYPE_STUB_DECL (TREE_TYPE (m)) == m)
11866 /* This is a using-decl for a type, or an anonymous
11867 struct (maybe with a typedef name). Write the type. */
11868 m = TREE_TYPE (m);
11869 tree_node (m);
11872 tree_node (CLASSTYPE_LAMBDA_EXPR (type));
11874 /* TYPE_CONTAINS_VPTR_P looks at the vbase vector, which the
11875 reader won't know at this point. */
11876 int has_vptr = TYPE_CONTAINS_VPTR_P (type);
11878 if (streaming_p ())
11880 unsigned nvbases = vec_safe_length (CLASSTYPE_VBASECLASSES (type));
11881 u (nvbases);
11882 i (has_vptr);
11885 if (has_vptr)
11887 tree_vec (CLASSTYPE_PURE_VIRTUALS (type));
11888 tree_pair_vec (CLASSTYPE_VCALL_INDICES (type));
11889 tree_node (CLASSTYPE_KEY_METHOD (type));
11893 if (TYPE_LANG_SPECIFIC (type))
11895 tree_node (CLASSTYPE_PRIMARY_BINFO (type));
11897 tree as_base = CLASSTYPE_AS_BASE (type);
11898 if (as_base)
11899 as_base = TYPE_NAME (as_base);
11900 tree_node (as_base);
11902 /* Write the vtables. */
11903 tree vtables = CLASSTYPE_VTABLES (type);
11904 vec_chained_decls (vtables);
11905 for (; vtables; vtables = TREE_CHAIN (vtables))
11906 write_definition (vtables);
11908 /* Write the friend classes. */
11909 tree_list (CLASSTYPE_FRIEND_CLASSES (type), false);
11911 /* Write the friend functions. */
11912 for (tree friends = DECL_FRIENDLIST (defn);
11913 friends; friends = TREE_CHAIN (friends))
11915 /* Name of these friends. */
11916 tree_node (TREE_PURPOSE (friends));
11917 tree_list (TREE_VALUE (friends), false);
11919 /* End of friend fns. */
11920 tree_node (NULL_TREE);
11922 /* Write the decl list. */
11923 tree_list (CLASSTYPE_DECL_LIST (type), true);
11925 if (TYPE_CONTAINS_VPTR_P (type))
11927 /* Write the thunks. */
11928 for (tree decls = TYPE_FIELDS (type);
11929 decls; decls = DECL_CHAIN (decls))
11930 if (TREE_CODE (decls) == FUNCTION_DECL
11931 && DECL_VIRTUAL_P (decls)
11932 && DECL_THUNKS (decls))
11934 tree_node (decls);
11935 /* Thunks are always unique, so chaining is ok. */
11936 chained_decls (DECL_THUNKS (decls));
11938 tree_node (NULL_TREE);
11943 void
11944 trees_out::mark_class_member (tree member, bool do_defn)
11946 gcc_assert (DECL_P (member));
11948 member = member_owned_by_class (member);
11949 if (member)
11950 mark_declaration (member, do_defn && has_definition (member));
11953 void
11954 trees_out::mark_class_def (tree defn)
11956 gcc_assert (DECL_P (defn));
11957 tree type = TREE_TYPE (defn);
11958 /* Mark the class members that are not type-decls and cannot have
11959 independent definitions. */
11960 for (tree member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
11961 if (TREE_CODE (member) == FIELD_DECL
11962 || TREE_CODE (member) == USING_DECL
11963 /* A cloned enum-decl from 'using enum unrelated;' */
11964 || (TREE_CODE (member) == CONST_DECL
11965 && DECL_CONTEXT (member) == type))
11967 mark_class_member (member);
11968 if (TREE_CODE (member) == FIELD_DECL)
11969 if (tree repr = DECL_BIT_FIELD_REPRESENTATIVE (member))
11970 /* If we're marking a class template definition, then
11971 this'll contain the width (as set by grokbitfield)
11972 instead of a decl. */
11973 if (DECL_P (repr))
11974 mark_declaration (repr, false);
11977 /* Mark the binfo hierarchy. */
11978 for (tree child = TYPE_BINFO (type); child; child = TREE_CHAIN (child))
11979 mark_by_value (child);
11981 if (TYPE_LANG_SPECIFIC (type))
11983 for (tree vtable = CLASSTYPE_VTABLES (type);
11984 vtable; vtable = TREE_CHAIN (vtable))
11985 mark_declaration (vtable, true);
11987 if (TYPE_CONTAINS_VPTR_P (type))
11988 /* Mark the thunks, they belong to the class definition,
11989 /not/ the thunked-to function. */
11990 for (tree decls = TYPE_FIELDS (type);
11991 decls; decls = DECL_CHAIN (decls))
11992 if (TREE_CODE (decls) == FUNCTION_DECL)
11993 for (tree thunks = DECL_THUNKS (decls);
11994 thunks; thunks = DECL_CHAIN (thunks))
11995 mark_declaration (thunks, false);
11999 /* Nop sorting, needed for resorting the member vec. */
12001 static void
12002 nop (void *, void *, void *)
12006 bool
12007 trees_in::read_class_def (tree defn, tree maybe_template)
12009 gcc_assert (DECL_P (defn));
12010 dump () && dump ("Reading class definition %N", defn);
12011 tree type = TREE_TYPE (defn);
12012 tree size = tree_node ();
12013 tree size_unit = tree_node ();
12014 tree vfield = tree_node ();
12015 tree binfo = tree_node ();
12016 vec<tree, va_gc> *vbase_vec = NULL;
12017 vec<tree, va_gc> *member_vec = NULL;
12018 vec<tree, va_gc> *pure_virts = NULL;
12019 vec<tree_pair_s, va_gc> *vcall_indices = NULL;
12020 tree key_method = NULL_TREE;
12021 tree lambda = NULL_TREE;
12023 /* Read the fields. */
12024 vec<tree, va_heap> *fields = vec_chained_decls ();
12026 if (TYPE_LANG_SPECIFIC (type))
12028 if (unsigned len = u ())
12030 vec_alloc (member_vec, len);
12031 for (unsigned ix = 0; ix != len; ix++)
12033 tree m = tree_node ();
12034 if (get_overrun ())
12035 break;
12036 if (TYPE_P (m))
12037 m = TYPE_STUB_DECL (m);
12038 member_vec->quick_push (m);
12041 lambda = tree_node ();
12043 if (!get_overrun ())
12045 unsigned nvbases = u ();
12046 if (nvbases)
12048 vec_alloc (vbase_vec, nvbases);
12049 for (tree child = binfo; child; child = TREE_CHAIN (child))
12050 if (BINFO_VIRTUAL_P (child))
12051 vbase_vec->quick_push (child);
12055 if (!get_overrun ())
12057 int has_vptr = i ();
12058 if (has_vptr)
12060 pure_virts = tree_vec ();
12061 vcall_indices = tree_pair_vec ();
12062 key_method = tree_node ();
12067 tree maybe_dup = odr_duplicate (maybe_template, TYPE_SIZE (type));
12068 bool installing = maybe_dup && !TYPE_SIZE (type);
12069 if (installing)
12071 if (DECL_EXTERNAL (defn) && TYPE_LANG_SPECIFIC (type))
12073 /* We don't deal with not-really-extern, because, for a
12074 module you want the import to be the interface, and for a
12075 header-unit, you're doing it wrong. */
12076 CLASSTYPE_INTERFACE_UNKNOWN (type) = false;
12077 CLASSTYPE_INTERFACE_ONLY (type) = true;
12080 if (maybe_dup != defn)
12082 // FIXME: This is needed on other defns too, almost
12083 // duplicate-decl like? See is_matching_decl too.
12084 /* Copy flags from the duplicate. */
12085 tree type_dup = TREE_TYPE (maybe_dup);
12087 /* Core pieces. */
12088 TYPE_MODE_RAW (type) = TYPE_MODE_RAW (type_dup);
12089 SET_DECL_MODE (defn, DECL_MODE (maybe_dup));
12090 TREE_ADDRESSABLE (type) = TREE_ADDRESSABLE (type_dup);
12091 DECL_SIZE (defn) = DECL_SIZE (maybe_dup);
12092 DECL_SIZE_UNIT (defn) = DECL_SIZE_UNIT (maybe_dup);
12093 DECL_ALIGN_RAW (defn) = DECL_ALIGN_RAW (maybe_dup);
12094 DECL_WARN_IF_NOT_ALIGN_RAW (defn)
12095 = DECL_WARN_IF_NOT_ALIGN_RAW (maybe_dup);
12096 DECL_USER_ALIGN (defn) = DECL_USER_ALIGN (maybe_dup);
12098 /* C++ pieces. */
12099 TYPE_POLYMORPHIC_P (type) = TYPE_POLYMORPHIC_P (type_dup);
12100 TYPE_HAS_USER_CONSTRUCTOR (type)
12101 = TYPE_HAS_USER_CONSTRUCTOR (type_dup);
12102 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
12103 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type_dup);
12105 if (auto ls = TYPE_LANG_SPECIFIC (type_dup))
12107 if (TYPE_LANG_SPECIFIC (type))
12109 CLASSTYPE_BEFRIENDING_CLASSES (type_dup)
12110 = CLASSTYPE_BEFRIENDING_CLASSES (type);
12111 if (!ANON_AGGR_TYPE_P (type))
12112 CLASSTYPE_TYPEINFO_VAR (type_dup)
12113 = CLASSTYPE_TYPEINFO_VAR (type);
12115 for (tree v = type; v; v = TYPE_NEXT_VARIANT (v))
12116 TYPE_LANG_SPECIFIC (v) = ls;
12120 TYPE_SIZE (type) = size;
12121 TYPE_SIZE_UNIT (type) = size_unit;
12123 if (fields)
12125 tree *chain = &TYPE_FIELDS (type);
12126 unsigned len = fields->length ();
12127 for (unsigned ix = 0; ix != len; ix++)
12129 tree decl = (*fields)[ix];
12131 if (!decl)
12133 /* An anonymous struct with typedef name. */
12134 tree tdef = (*fields)[ix+1];
12135 decl = TYPE_STUB_DECL (TREE_TYPE (tdef));
12136 gcc_checking_assert (IDENTIFIER_ANON_P (DECL_NAME (decl))
12137 && decl != tdef);
12140 gcc_checking_assert (!*chain == !DECL_CLONED_FUNCTION_P (decl));
12141 *chain = decl;
12142 chain = &DECL_CHAIN (decl);
12144 if (TREE_CODE (decl) == FIELD_DECL
12145 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12146 ANON_AGGR_TYPE_FIELD
12147 (TYPE_MAIN_VARIANT (TREE_TYPE (decl))) = decl;
12149 if (TREE_CODE (decl) == USING_DECL
12150 && TREE_CODE (USING_DECL_SCOPE (decl)) == RECORD_TYPE)
12152 /* Reconstruct DECL_ACCESS. */
12153 tree decls = USING_DECL_DECLS (decl);
12154 tree access = declared_access (decl);
12156 for (ovl_iterator iter (decls); iter; ++iter)
12158 tree d = *iter;
12160 retrofit_lang_decl (d);
12161 tree list = DECL_ACCESS (d);
12163 if (!purpose_member (type, list))
12164 DECL_ACCESS (d) = tree_cons (type, access, list);
12170 TYPE_VFIELD (type) = vfield;
12171 TYPE_BINFO (type) = binfo;
12173 if (TYPE_LANG_SPECIFIC (type))
12175 CLASSTYPE_LAMBDA_EXPR (type) = lambda;
12177 CLASSTYPE_MEMBER_VEC (type) = member_vec;
12178 CLASSTYPE_PURE_VIRTUALS (type) = pure_virts;
12179 CLASSTYPE_VCALL_INDICES (type) = vcall_indices;
12181 CLASSTYPE_KEY_METHOD (type) = key_method;
12183 CLASSTYPE_VBASECLASSES (type) = vbase_vec;
12185 /* Resort the member vector. */
12186 resort_type_member_vec (member_vec, NULL, nop, NULL);
12189 else if (maybe_dup)
12191 // FIXME:QOI Check matching defn
12194 if (TYPE_LANG_SPECIFIC (type))
12196 tree primary = tree_node ();
12197 tree as_base = tree_node ();
12199 if (as_base)
12200 as_base = TREE_TYPE (as_base);
12202 /* Read the vtables. */
12203 vec<tree, va_heap> *vtables = vec_chained_decls ();
12204 if (vtables)
12206 unsigned len = vtables->length ();
12207 for (unsigned ix = 0; ix != len; ix++)
12209 tree vtable = (*vtables)[ix];
12210 read_var_def (vtable, vtable);
12214 tree friend_classes = tree_list (false);
12215 tree friend_functions = NULL_TREE;
12216 for (tree *chain = &friend_functions;
12217 tree name = tree_node (); chain = &TREE_CHAIN (*chain))
12219 tree val = tree_list (false);
12220 *chain = build_tree_list (name, val);
12222 tree decl_list = tree_list (true);
12224 if (installing)
12226 CLASSTYPE_PRIMARY_BINFO (type) = primary;
12227 CLASSTYPE_AS_BASE (type) = as_base;
12229 if (vtables)
12231 if (!CLASSTYPE_KEY_METHOD (type)
12232 /* Sneaky user may have defined it inline
12233 out-of-class. */
12234 || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type)))
12235 vec_safe_push (keyed_classes, type);
12236 unsigned len = vtables->length ();
12237 tree *chain = &CLASSTYPE_VTABLES (type);
12238 for (unsigned ix = 0; ix != len; ix++)
12240 tree vtable = (*vtables)[ix];
12241 gcc_checking_assert (!*chain);
12242 *chain = vtable;
12243 chain = &DECL_CHAIN (vtable);
12246 CLASSTYPE_FRIEND_CLASSES (type) = friend_classes;
12247 DECL_FRIENDLIST (defn) = friend_functions;
12248 CLASSTYPE_DECL_LIST (type) = decl_list;
12250 for (; friend_classes; friend_classes = TREE_CHAIN (friend_classes))
12252 tree f = TREE_VALUE (friend_classes);
12254 if (CLASS_TYPE_P (f))
12256 CLASSTYPE_BEFRIENDING_CLASSES (f)
12257 = tree_cons (NULL_TREE, type,
12258 CLASSTYPE_BEFRIENDING_CLASSES (f));
12259 dump () && dump ("Class %N befriending %C:%N",
12260 type, TREE_CODE (f), f);
12264 for (; friend_functions;
12265 friend_functions = TREE_CHAIN (friend_functions))
12266 for (tree friend_decls = TREE_VALUE (friend_functions);
12267 friend_decls; friend_decls = TREE_CHAIN (friend_decls))
12269 tree f = TREE_VALUE (friend_decls);
12271 DECL_BEFRIENDING_CLASSES (f)
12272 = tree_cons (NULL_TREE, type, DECL_BEFRIENDING_CLASSES (f));
12273 dump () && dump ("Class %N befriending %C:%N",
12274 type, TREE_CODE (f), f);
12278 if (TYPE_CONTAINS_VPTR_P (type))
12279 /* Read and install the thunks. */
12280 while (tree vfunc = tree_node ())
12282 tree thunks = chained_decls ();
12283 if (installing)
12284 SET_DECL_THUNKS (vfunc, thunks);
12287 vec_free (vtables);
12290 /* Propagate to all variants. */
12291 if (installing)
12292 fixup_type_variants (type);
12294 /* IS_FAKE_BASE_TYPE is inaccurate at this point, because if this is
12295 the fake base, we've not hooked it into the containing class's
12296 data structure yet. Fortunately it has a unique name. */
12297 if (installing
12298 && DECL_NAME (defn) != as_base_identifier
12299 && (!CLASSTYPE_TEMPLATE_INFO (type)
12300 || !uses_template_parms (TI_ARGS (CLASSTYPE_TEMPLATE_INFO (type)))))
12301 /* Emit debug info. It'd be nice to know if the interface TU
12302 already emitted this. */
12303 rest_of_type_compilation (type, !LOCAL_CLASS_P (type));
12305 vec_free (fields);
12307 return !get_overrun ();
12310 void
12311 trees_out::write_enum_def (tree decl)
12313 tree type = TREE_TYPE (decl);
12315 tree_node (TYPE_VALUES (type));
12316 /* Note that we stream TYPE_MIN/MAX_VALUE directly as part of the
12317 ENUMERAL_TYPE. */
12320 void
12321 trees_out::mark_enum_def (tree decl)
12323 tree type = TREE_TYPE (decl);
12325 for (tree values = TYPE_VALUES (type); values; values = TREE_CHAIN (values))
12327 tree cst = TREE_VALUE (values);
12328 mark_by_value (cst);
12329 /* We must mark the init to avoid circularity in tt_enum_int. */
12330 if (tree init = DECL_INITIAL (cst))
12331 if (TREE_CODE (init) == INTEGER_CST)
12332 mark_by_value (init);
12336 bool
12337 trees_in::read_enum_def (tree defn, tree maybe_template)
12339 tree type = TREE_TYPE (defn);
12340 tree values = tree_node ();
12342 if (get_overrun ())
12343 return false;
12345 tree maybe_dup = odr_duplicate (maybe_template, TYPE_VALUES (type));
12346 bool installing = maybe_dup && !TYPE_VALUES (type);
12348 if (installing)
12350 TYPE_VALUES (type) = values;
12351 /* Note that we stream TYPE_MIN/MAX_VALUE directly as part of the
12352 ENUMERAL_TYPE. */
12354 rest_of_type_compilation (type, DECL_NAMESPACE_SCOPE_P (defn));
12356 else if (maybe_dup)
12358 tree known = TYPE_VALUES (type);
12359 for (; known && values;
12360 known = TREE_CHAIN (known), values = TREE_CHAIN (values))
12362 tree known_decl = TREE_VALUE (known);
12363 tree new_decl = TREE_VALUE (values);
12365 if (DECL_NAME (known_decl) != DECL_NAME (new_decl))
12366 break;
12368 new_decl = maybe_duplicate (new_decl);
12370 if (!cp_tree_equal (DECL_INITIAL (known_decl),
12371 DECL_INITIAL (new_decl)))
12372 break;
12375 if (known || values)
12377 error_at (DECL_SOURCE_LOCATION (maybe_dup),
12378 "definition of %qD does not match", maybe_dup);
12379 inform (DECL_SOURCE_LOCATION (defn),
12380 "existing definition %qD", defn);
12382 tree known_decl = NULL_TREE, new_decl = NULL_TREE;
12384 if (known)
12385 known_decl = TREE_VALUE (known);
12386 if (values)
12387 new_decl = maybe_duplicate (TREE_VALUE (values));
12389 if (known_decl && new_decl)
12391 inform (DECL_SOURCE_LOCATION (new_decl),
12392 "... this enumerator %qD", new_decl);
12393 inform (DECL_SOURCE_LOCATION (known_decl),
12394 "enumerator %qD does not match ...", known_decl);
12396 else if (known_decl || new_decl)
12398 tree extra = known_decl ? known_decl : new_decl;
12399 inform (DECL_SOURCE_LOCATION (extra),
12400 "additional enumerators beginning with %qD", extra);
12402 else
12403 inform (DECL_SOURCE_LOCATION (maybe_dup),
12404 "enumeration range differs");
12406 /* Mark it bad. */
12407 unmatched_duplicate (maybe_template);
12411 return true;
12414 /* Write out the body of DECL. See above circularity note. */
12416 void
12417 trees_out::write_definition (tree decl)
12419 if (streaming_p ())
12421 assert_definition (decl);
12422 dump ()
12423 && dump ("Writing definition %C:%N", TREE_CODE (decl), decl);
12425 else
12426 dump (dumper::DEPEND)
12427 && dump ("Depending definition %C:%N", TREE_CODE (decl), decl);
12429 again:
12430 switch (TREE_CODE (decl))
12432 default:
12433 gcc_unreachable ();
12435 case TEMPLATE_DECL:
12436 decl = DECL_TEMPLATE_RESULT (decl);
12437 goto again;
12439 case FUNCTION_DECL:
12440 write_function_def (decl);
12441 break;
12443 case TYPE_DECL:
12445 tree type = TREE_TYPE (decl);
12446 gcc_assert (TYPE_MAIN_VARIANT (type) == type
12447 && TYPE_NAME (type) == decl);
12448 if (TREE_CODE (type) == ENUMERAL_TYPE)
12449 write_enum_def (decl);
12450 else
12451 write_class_def (decl);
12453 break;
12455 case VAR_DECL:
12456 case CONCEPT_DECL:
12457 write_var_def (decl);
12458 break;
12462 /* Mark a declaration for by-value walking. If DO_DEFN is true, mark
12463 its body too. */
12465 void
12466 trees_out::mark_declaration (tree decl, bool do_defn)
12468 mark_by_value (decl);
12470 if (TREE_CODE (decl) == TEMPLATE_DECL)
12471 decl = DECL_TEMPLATE_RESULT (decl);
12473 if (!do_defn)
12474 return;
12476 switch (TREE_CODE (decl))
12478 default:
12479 gcc_unreachable ();
12481 case FUNCTION_DECL:
12482 mark_function_def (decl);
12483 break;
12485 case TYPE_DECL:
12487 tree type = TREE_TYPE (decl);
12488 gcc_assert (TYPE_MAIN_VARIANT (type) == type
12489 && TYPE_NAME (type) == decl);
12490 if (TREE_CODE (type) == ENUMERAL_TYPE)
12491 mark_enum_def (decl);
12492 else
12493 mark_class_def (decl);
12495 break;
12497 case VAR_DECL:
12498 case CONCEPT_DECL:
12499 mark_var_def (decl);
12500 break;
12504 /* Read in the body of DECL. See above circularity note. */
12506 bool
12507 trees_in::read_definition (tree decl)
12509 dump () && dump ("Reading definition %C %N", TREE_CODE (decl), decl);
12511 tree maybe_template = decl;
12513 again:
12514 switch (TREE_CODE (decl))
12516 default:
12517 break;
12519 case TEMPLATE_DECL:
12520 decl = DECL_TEMPLATE_RESULT (decl);
12521 goto again;
12523 case FUNCTION_DECL:
12524 return read_function_def (decl, maybe_template);
12526 case TYPE_DECL:
12528 tree type = TREE_TYPE (decl);
12529 gcc_assert (TYPE_MAIN_VARIANT (type) == type
12530 && TYPE_NAME (type) == decl);
12531 if (TREE_CODE (type) == ENUMERAL_TYPE)
12532 return read_enum_def (decl, maybe_template);
12533 else
12534 return read_class_def (decl, maybe_template);
12536 break;
12538 case VAR_DECL:
12539 case CONCEPT_DECL:
12540 return read_var_def (decl, maybe_template);
12543 return false;
12546 /* Lookup an maybe insert a slot for depset for KEY. */
12548 depset **
12549 depset::hash::entity_slot (tree entity, bool insert)
12551 traits::compare_type key (entity, NULL);
12552 depset **slot = find_slot_with_hash (key, traits::hash (key),
12553 insert ? INSERT : NO_INSERT);
12555 return slot;
12558 depset **
12559 depset::hash::binding_slot (tree ctx, tree name, bool insert)
12561 traits::compare_type key (ctx, name);
12562 depset **slot = find_slot_with_hash (key, traits::hash (key),
12563 insert ? INSERT : NO_INSERT);
12565 return slot;
12568 depset *
12569 depset::hash::find_dependency (tree decl)
12571 depset **slot = entity_slot (decl, false);
12573 return slot ? *slot : NULL;
12576 depset *
12577 depset::hash::find_binding (tree ctx, tree name)
12579 depset **slot = binding_slot (ctx, name, false);
12581 return slot ? *slot : NULL;
12584 /* DECL is a newly discovered dependency. Create the depset, if it
12585 doesn't already exist. Add it to the worklist if so.
12587 DECL will be an OVL_USING_P OVERLOAD, if it's from a binding that's
12588 a using decl.
12590 We do not have to worry about adding the same dependency more than
12591 once. First it's harmless, but secondly the TREE_VISITED marking
12592 prevents us wanting to do it anyway. */
12594 depset *
12595 depset::hash::make_dependency (tree decl, entity_kind ek)
12597 /* Make sure we're being told consistent information. */
12598 gcc_checking_assert ((ek == EK_NAMESPACE)
12599 == (TREE_CODE (decl) == NAMESPACE_DECL
12600 && !DECL_NAMESPACE_ALIAS (decl)));
12601 gcc_checking_assert (ek != EK_BINDING && ek != EK_REDIRECT);
12602 gcc_checking_assert (TREE_CODE (decl) != FIELD_DECL
12603 && (TREE_CODE (decl) != USING_DECL
12604 || TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL));
12605 gcc_checking_assert (!is_key_order ());
12606 if (ek == EK_USING)
12607 gcc_checking_assert (TREE_CODE (decl) == OVERLOAD);
12609 if (TREE_CODE (decl) == TEMPLATE_DECL)
12610 /* The template should have copied these from its result decl. */
12611 gcc_checking_assert (DECL_MODULE_EXPORT_P (decl)
12612 == DECL_MODULE_EXPORT_P (DECL_TEMPLATE_RESULT (decl)));
12614 depset **slot = entity_slot (decl, true);
12615 depset *dep = *slot;
12616 bool for_binding = ek == EK_FOR_BINDING;
12618 if (!dep)
12620 if ((DECL_IMPLICIT_TYPEDEF_P (decl)
12621 /* ... not an enum, for instance. */
12622 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (decl))
12623 && TYPE_LANG_SPECIFIC (TREE_TYPE (decl))
12624 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
12625 || (VAR_P (decl)
12626 && DECL_LANG_SPECIFIC (decl)
12627 && DECL_USE_TEMPLATE (decl) == 2))
12629 /* A partial or explicit specialization. Partial
12630 specializations might not be in the hash table, because
12631 there can be multiple differently-constrained variants.
12633 template<typename T> class silly;
12634 template<typename T> requires true class silly {};
12636 We need to find them, insert their TEMPLATE_DECL in the
12637 dep_hash, and then convert the dep we just found into a
12638 redirect. */
12640 tree ti = get_template_info (decl);
12641 tree tmpl = TI_TEMPLATE (ti);
12642 tree partial = NULL_TREE;
12643 for (tree spec = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
12644 spec; spec = TREE_CHAIN (spec))
12645 if (DECL_TEMPLATE_RESULT (TREE_VALUE (spec)) == decl)
12647 partial = TREE_VALUE (spec);
12648 break;
12651 if (partial)
12653 /* Eagerly create an empty redirect. The following
12654 make_dependency call could cause hash reallocation,
12655 and invalidate slot's value. */
12656 depset *redirect = make_entity (decl, EK_REDIRECT);
12658 /* Redirects are never reached -- always snap to their target. */
12659 redirect->set_flag_bit<DB_UNREACHED_BIT> ();
12661 *slot = redirect;
12663 depset *tmpl_dep = make_dependency (partial, EK_PARTIAL);
12664 gcc_checking_assert (tmpl_dep->get_entity_kind () == EK_PARTIAL);
12666 redirect->deps.safe_push (tmpl_dep);
12668 return redirect;
12672 bool has_def = ek != EK_USING && has_definition (decl);
12673 if (ek > EK_BINDING)
12674 ek = EK_DECL;
12676 /* The only OVERLOADS we should see are USING decls from
12677 bindings. */
12678 *slot = dep = make_entity (decl, ek, has_def);
12680 if (TREE_CODE (decl) == TEMPLATE_DECL)
12682 if (DECL_ALIAS_TEMPLATE_P (decl) && DECL_TEMPLATE_INFO (decl))
12683 dep->set_flag_bit<DB_ALIAS_TMPL_INST_BIT> ();
12684 else if (CHECKING_P)
12685 /* The template_result should otherwise not be in the
12686 table, or be an empty redirect (created above). */
12687 if (auto *eslot = entity_slot (DECL_TEMPLATE_RESULT (decl), false))
12688 gcc_checking_assert ((*eslot)->get_entity_kind () == EK_REDIRECT
12689 && !(*eslot)->deps.length ());
12692 if (ek != EK_USING)
12694 tree not_tmpl = STRIP_TEMPLATE (decl);
12696 if (DECL_LANG_SPECIFIC (not_tmpl)
12697 && DECL_MODULE_IMPORT_P (not_tmpl))
12699 /* Store the module number and index in cluster/section,
12700 so we don't have to look them up again. */
12701 unsigned index = import_entity_index (decl);
12702 module_state *from = import_entity_module (index);
12703 /* Remap will be zero for imports from partitions, which
12704 we want to treat as-if declared in this TU. */
12705 if (from->remap)
12707 dep->cluster = index - from->entity_lwm;
12708 dep->section = from->remap;
12709 dep->set_flag_bit<DB_IMPORTED_BIT> ();
12713 if (ek == EK_DECL
12714 && !dep->is_import ()
12715 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL
12716 && !(TREE_CODE (decl) == TEMPLATE_DECL
12717 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl)))
12719 tree ctx = CP_DECL_CONTEXT (decl);
12721 if (!TREE_PUBLIC (ctx))
12722 /* Member of internal namespace. */
12723 dep->set_flag_bit<DB_IS_INTERNAL_BIT> ();
12724 else if (VAR_OR_FUNCTION_DECL_P (not_tmpl)
12725 && DECL_THIS_STATIC (not_tmpl))
12727 /* An internal decl. This is ok in a GM entity. */
12728 if (!(header_module_p ()
12729 || !DECL_LANG_SPECIFIC (not_tmpl)
12730 || !DECL_MODULE_PURVIEW_P (not_tmpl)))
12731 dep->set_flag_bit<DB_IS_INTERNAL_BIT> ();
12736 if (!dep->is_import ())
12737 worklist.safe_push (dep);
12740 dump (dumper::DEPEND)
12741 && dump ("%s on %s %C:%N found",
12742 ek == EK_REDIRECT ? "Redirect"
12743 : for_binding ? "Binding" : "Dependency",
12744 dep->entity_kind_name (), TREE_CODE (decl), decl);
12746 return dep;
12749 /* DEP is a newly discovered dependency. Append it to current's
12750 depset. */
12752 void
12753 depset::hash::add_dependency (depset *dep)
12755 gcc_checking_assert (current && !is_key_order ());
12756 current->deps.safe_push (dep);
12758 if (dep->is_internal () && !current->is_internal ())
12759 current->set_flag_bit<DB_REFS_INTERNAL_BIT> ();
12761 if (current->get_entity_kind () == EK_USING
12762 && DECL_IMPLICIT_TYPEDEF_P (dep->get_entity ())
12763 && TREE_CODE (TREE_TYPE (dep->get_entity ())) == ENUMERAL_TYPE)
12765 /* CURRENT is an unwrapped using-decl and DECL is an enum's
12766 implicit typedef. Is CURRENT a member of the enum? */
12767 tree c_decl = OVL_FUNCTION (current->get_entity ());
12769 if (TREE_CODE (c_decl) == CONST_DECL
12770 && (current->deps[0]->get_entity ()
12771 == CP_DECL_CONTEXT (dep->get_entity ())))
12772 /* Make DECL depend on CURRENT. */
12773 dep->deps.safe_push (current);
12776 if (dep->is_unreached ())
12778 /* The dependency is reachable now. */
12779 reached_unreached = true;
12780 dep->clear_flag_bit<DB_UNREACHED_BIT> ();
12781 dump (dumper::DEPEND)
12782 && dump ("Reaching unreached %s %C:%N", dep->entity_kind_name (),
12783 TREE_CODE (dep->get_entity ()), dep->get_entity ());
12787 depset *
12788 depset::hash::add_dependency (tree decl, entity_kind ek)
12790 depset *dep;
12792 if (is_key_order ())
12794 dep = find_dependency (decl);
12795 if (dep)
12797 current->deps.safe_push (dep);
12798 dump (dumper::MERGE)
12799 && dump ("Key dependency on %s %C:%N found",
12800 dep->entity_kind_name (), TREE_CODE (decl), decl);
12802 else
12804 /* It's not a mergeable decl, look for it in the original
12805 table. */
12806 dep = chain->find_dependency (decl);
12807 gcc_checking_assert (dep);
12810 else
12812 dep = make_dependency (decl, ek);
12813 if (dep->get_entity_kind () != EK_REDIRECT)
12814 add_dependency (dep);
12817 return dep;
12820 void
12821 depset::hash::add_namespace_context (depset *dep, tree ns)
12823 depset *ns_dep = make_dependency (ns, depset::EK_NAMESPACE);
12824 dep->deps.safe_push (ns_dep);
12826 /* Mark it as special if imported so we don't walk connect when
12827 SCCing. */
12828 if (!dep->is_binding () && ns_dep->is_import ())
12829 dep->set_special ();
12832 struct add_binding_data
12834 tree ns;
12835 bitmap partitions;
12836 depset *binding;
12837 depset::hash *hash;
12838 bool met_namespace;
12841 /* Return true if we are, or contain something that is exported. */
12843 bool
12844 depset::hash::add_binding_entity (tree decl, WMB_Flags flags, void *data_)
12846 auto data = static_cast <add_binding_data *> (data_);
12848 if (!(TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl)))
12850 tree inner = decl;
12852 if (TREE_CODE (inner) == CONST_DECL
12853 && TREE_CODE (DECL_CONTEXT (inner)) == ENUMERAL_TYPE)
12854 inner = TYPE_NAME (DECL_CONTEXT (inner));
12855 else if (TREE_CODE (inner) == TEMPLATE_DECL)
12856 inner = DECL_TEMPLATE_RESULT (inner);
12858 if ((!DECL_LANG_SPECIFIC (inner) || !DECL_MODULE_PURVIEW_P (inner))
12859 && !(flags & (WMB_Using | WMB_Export)))
12860 /* Ignore global module fragment entities unless explicitly
12861 exported with a using declaration. */
12862 return false;
12864 if (VAR_OR_FUNCTION_DECL_P (inner)
12865 && DECL_THIS_STATIC (inner))
12867 if (!header_module_p ())
12868 /* Ignore internal-linkage entitites. */
12869 return false;
12872 if ((TREE_CODE (decl) == VAR_DECL
12873 || TREE_CODE (decl) == TYPE_DECL)
12874 && DECL_TINFO_P (decl))
12875 /* Ignore TINFO things. */
12876 return false;
12878 if (TREE_CODE (decl) == VAR_DECL && DECL_NTTP_OBJECT_P (decl))
12879 /* Ignore NTTP objects. */
12880 return false;
12882 if (!(flags & WMB_Using) && CP_DECL_CONTEXT (decl) != data->ns)
12884 /* A using that lost its wrapper or an unscoped enum
12885 constant. */
12886 flags = WMB_Flags (flags | WMB_Using);
12887 if (DECL_MODULE_EXPORT_P (TREE_CODE (decl) == CONST_DECL
12888 ? TYPE_NAME (TREE_TYPE (decl))
12889 : STRIP_TEMPLATE (decl)))
12890 flags = WMB_Flags (flags | WMB_Export);
12893 if (!data->binding)
12894 /* No binding to check. */;
12895 else if (flags & WMB_Using)
12897 /* Look in the binding to see if we already have this
12898 using. */
12899 for (unsigned ix = data->binding->deps.length (); --ix;)
12901 depset *d = data->binding->deps[ix];
12902 if (d->get_entity_kind () == EK_USING
12903 && OVL_FUNCTION (d->get_entity ()) == decl)
12905 if (!(flags & WMB_Hidden))
12906 d->clear_hidden_binding ();
12907 if (flags & WMB_Export)
12908 OVL_EXPORT_P (d->get_entity ()) = true;
12909 return bool (flags & WMB_Export);
12913 else if (flags & WMB_Dups)
12915 /* Look in the binding to see if we already have this decl. */
12916 for (unsigned ix = data->binding->deps.length (); --ix;)
12918 depset *d = data->binding->deps[ix];
12919 if (d->get_entity () == decl)
12921 if (!(flags & WMB_Hidden))
12922 d->clear_hidden_binding ();
12923 return false;
12928 /* We're adding something. */
12929 if (!data->binding)
12931 data->binding = make_binding (data->ns, DECL_NAME (decl));
12932 data->hash->add_namespace_context (data->binding, data->ns);
12934 depset **slot = data->hash->binding_slot (data->ns,
12935 DECL_NAME (decl), true);
12936 gcc_checking_assert (!*slot);
12937 *slot = data->binding;
12940 /* Make sure nobody left a tree visited lying about. */
12941 gcc_checking_assert (!TREE_VISITED (decl));
12943 if (flags & WMB_Using)
12945 decl = ovl_make (decl, NULL_TREE);
12946 if (flags & WMB_Export)
12947 OVL_EXPORT_P (decl) = true;
12950 depset *dep = data->hash->make_dependency
12951 (decl, flags & WMB_Using ? EK_USING : EK_FOR_BINDING);
12952 if (flags & WMB_Hidden)
12953 dep->set_hidden_binding ();
12954 data->binding->deps.safe_push (dep);
12955 /* Binding and contents are mutually dependent. */
12956 dep->deps.safe_push (data->binding);
12958 return (flags & WMB_Using
12959 ? flags & WMB_Export : DECL_MODULE_EXPORT_P (decl));
12961 else if (DECL_NAME (decl) && !data->met_namespace)
12963 /* Namespace, walk exactly once. */
12964 gcc_checking_assert (TREE_PUBLIC (decl));
12965 data->met_namespace = true;
12966 if (data->hash->add_namespace_entities (decl, data->partitions))
12968 /* It contains an exported thing, so it is exported. */
12969 gcc_checking_assert (DECL_MODULE_PURVIEW_P (decl));
12970 DECL_MODULE_EXPORT_P (decl) = true;
12973 if (DECL_MODULE_PURVIEW_P (decl))
12975 data->hash->make_dependency (decl, depset::EK_NAMESPACE);
12977 return DECL_MODULE_EXPORT_P (decl);
12981 return false;
12984 /* Recursively find all the namespace bindings of NS. Add a depset
12985 for every binding that contains an export or module-linkage entity.
12986 Add a defining depset for every such decl that we need to write a
12987 definition. Such defining depsets depend on the binding depset.
12988 Returns true if we contain something exported. */
12990 bool
12991 depset::hash::add_namespace_entities (tree ns, bitmap partitions)
12993 dump () && dump ("Looking for writables in %N", ns);
12994 dump.indent ();
12996 unsigned count = 0;
12997 add_binding_data data;
12998 data.ns = ns;
12999 data.partitions = partitions;
13000 data.hash = this;
13002 hash_table<named_decl_hash>::iterator end
13003 (DECL_NAMESPACE_BINDINGS (ns)->end ());
13004 for (hash_table<named_decl_hash>::iterator iter
13005 (DECL_NAMESPACE_BINDINGS (ns)->begin ()); iter != end; ++iter)
13007 data.binding = nullptr;
13008 data.met_namespace = false;
13009 if (walk_module_binding (*iter, partitions, add_binding_entity, &data))
13010 count++;
13013 if (count)
13014 dump () && dump ("Found %u entries", count);
13015 dump.outdent ();
13017 return count != 0;
13020 void
13021 depset::hash::add_partial_entities (vec<tree, va_gc> *partial_classes)
13023 for (unsigned ix = 0; ix != partial_classes->length (); ix++)
13025 tree inner = (*partial_classes)[ix];
13027 depset *dep = make_dependency (inner, depset::EK_DECL);
13029 if (dep->get_entity_kind () == depset::EK_REDIRECT)
13030 /* We should have recorded the template as a partial
13031 specialization. */
13032 gcc_checking_assert (dep->deps[0]->get_entity_kind ()
13033 == depset::EK_PARTIAL);
13034 else
13035 /* It was an explicit specialization, not a partial one. */
13036 gcc_checking_assert (dep->get_entity_kind ()
13037 == depset::EK_SPECIALIZATION);
13041 /* Add the members of imported classes that we defined in this TU.
13042 This will also include lazily created implicit member function
13043 declarations. (All others will be definitions.) */
13045 void
13046 depset::hash::add_class_entities (vec<tree, va_gc> *class_members)
13048 for (unsigned ix = 0; ix != class_members->length (); ix++)
13050 tree defn = (*class_members)[ix];
13051 depset *dep = make_dependency (defn, EK_INNER_DECL);
13053 if (dep->get_entity_kind () == EK_REDIRECT)
13054 dep = dep->deps[0];
13056 /* Only non-instantiations need marking as members. */
13057 if (dep->get_entity_kind () == EK_DECL)
13058 dep->set_flag_bit <DB_IS_MEMBER_BIT> ();
13062 /* We add the partial & explicit specializations, and the explicit
13063 instantiations. */
13065 static void
13066 specialization_add (bool decl_p, spec_entry *entry, void *data_)
13068 vec<spec_entry *> *data = reinterpret_cast <vec<spec_entry *> *> (data_);
13070 if (!decl_p)
13072 /* We exclusively use decls to locate things. Make sure there's
13073 no mismatch between the two specialization tables we keep.
13074 pt.cc optimizes instantiation lookup using a complicated
13075 heuristic. We don't attempt to replicate that algorithm, but
13076 observe its behaviour and reproduce it upon read back. */
13078 gcc_checking_assert (DECL_ALIAS_TEMPLATE_P (entry->tmpl)
13079 || TREE_CODE (entry->spec) == ENUMERAL_TYPE
13080 || DECL_CLASS_TEMPLATE_P (entry->tmpl));
13082 /* Only alias templates can appear in both tables (and
13083 if they're in the type table they must also be in the decl
13084 table). */
13085 gcc_checking_assert
13086 (!match_mergeable_specialization (true, entry)
13087 == !DECL_ALIAS_TEMPLATE_P (entry->tmpl));
13089 else if (VAR_OR_FUNCTION_DECL_P (entry->spec))
13090 gcc_checking_assert (!DECL_LOCAL_DECL_P (entry->spec));
13092 data->safe_push (entry);
13095 /* Arbitrary stable comparison. */
13097 static int
13098 specialization_cmp (const void *a_, const void *b_)
13100 const spec_entry *ea = *reinterpret_cast<const spec_entry *const *> (a_);
13101 const spec_entry *eb = *reinterpret_cast<const spec_entry *const *> (b_);
13103 if (ea == eb)
13104 return 0;
13106 tree a = ea->spec;
13107 tree b = eb->spec;
13108 if (TYPE_P (a))
13110 a = TYPE_NAME (a);
13111 b = TYPE_NAME (b);
13114 if (a == b)
13115 /* This can happen with friend specializations. Just order by
13116 entry address. See note in depset_cmp. */
13117 return ea < eb ? -1 : +1;
13119 return DECL_UID (a) < DECL_UID (b) ? -1 : +1;
13122 /* We add all kinds of specialializations. Implicit specializations
13123 should only streamed and walked if they are reachable from
13124 elsewhere. Hence the UNREACHED flag. This is making the
13125 assumption that it is cheaper to reinstantiate them on demand
13126 elsewhere, rather than stream them in when we instantiate their
13127 general template. Also, if we do stream them, we can only do that
13128 if they are not internal (which they can become if they themselves
13129 touch an internal entity?). */
13131 void
13132 depset::hash::add_specializations (bool decl_p)
13134 vec<spec_entry *> data;
13135 data.create (100);
13136 walk_specializations (decl_p, specialization_add, &data);
13137 data.qsort (specialization_cmp);
13138 while (data.length ())
13140 spec_entry *entry = data.pop ();
13141 tree spec = entry->spec;
13142 int use_tpl = 0;
13143 bool is_alias = false;
13144 bool is_friend = false;
13146 if (decl_p && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (entry->tmpl))
13147 /* A friend of a template. This is keyed to the
13148 instantiation. */
13149 is_friend = true;
13151 if (!decl_p && DECL_ALIAS_TEMPLATE_P (entry->tmpl))
13153 spec = TYPE_NAME (spec);
13154 is_alias = true;
13157 if (decl_p || is_alias)
13159 if (tree ti = DECL_TEMPLATE_INFO (spec))
13161 tree tmpl = TI_TEMPLATE (ti);
13163 use_tpl = DECL_USE_TEMPLATE (spec);
13164 if (spec == DECL_TEMPLATE_RESULT (tmpl))
13166 spec = tmpl;
13167 gcc_checking_assert (DECL_USE_TEMPLATE (spec) == use_tpl);
13169 else if (is_friend)
13171 if (TI_TEMPLATE (ti) != entry->tmpl
13172 || !template_args_equal (TI_ARGS (ti), entry->tmpl))
13173 goto template_friend;
13176 else
13178 template_friend:;
13179 gcc_checking_assert (is_friend);
13180 /* This is a friend of a template class, but not the one
13181 that generated entry->spec itself (i.e. it's an
13182 equivalent clone). We do not need to record
13183 this. */
13184 continue;
13187 else
13189 if (TREE_CODE (spec) == ENUMERAL_TYPE)
13191 tree ctx = DECL_CONTEXT (TYPE_NAME (spec));
13193 if (TYPE_P (ctx))
13194 use_tpl = CLASSTYPE_USE_TEMPLATE (ctx);
13195 else
13196 use_tpl = DECL_USE_TEMPLATE (ctx);
13198 else
13199 use_tpl = CLASSTYPE_USE_TEMPLATE (spec);
13201 tree ti = TYPE_TEMPLATE_INFO (spec);
13202 tree tmpl = TI_TEMPLATE (ti);
13204 spec = TYPE_NAME (spec);
13205 if (spec == DECL_TEMPLATE_RESULT (tmpl))
13207 spec = tmpl;
13208 use_tpl = DECL_USE_TEMPLATE (spec);
13212 bool needs_reaching = false;
13213 if (use_tpl == 1)
13214 /* Implicit instantiations only walked if we reach them. */
13215 needs_reaching = true;
13216 else if (!DECL_LANG_SPECIFIC (spec)
13217 || !DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (spec)))
13218 /* Likewise, GMF explicit or partial specializations. */
13219 needs_reaching = true;
13221 #if false && CHECKING_P
13222 /* The instantiation isn't always on
13223 DECL_TEMPLATE_INSTANTIATIONS, */
13224 // FIXME: we probably need to remember this information?
13225 /* Verify the specialization is on the
13226 DECL_TEMPLATE_INSTANTIATIONS of the template. */
13227 for (tree cons = DECL_TEMPLATE_INSTANTIATIONS (entry->tmpl);
13228 cons; cons = TREE_CHAIN (cons))
13229 if (TREE_VALUE (cons) == entry->spec)
13231 gcc_assert (entry->args == TREE_PURPOSE (cons));
13232 goto have_spec;
13234 gcc_unreachable ();
13235 have_spec:;
13236 #endif
13238 /* Make sure nobody left a tree visited lying about. */
13239 gcc_checking_assert (!TREE_VISITED (spec));
13240 depset *dep = make_dependency (spec, depset::EK_SPECIALIZATION);
13241 if (dep->is_special ())
13243 /* An already located specialization, this must be the TYPE
13244 corresponding to an alias_decl we found in the decl
13245 table. */
13246 spec_entry *other = reinterpret_cast <spec_entry *> (dep->deps[0]);
13247 gcc_checking_assert (!decl_p && is_alias && !dep->is_type_spec ());
13248 gcc_checking_assert (other->tmpl == entry->tmpl
13249 && template_args_equal (other->args, entry->args)
13250 && TREE_TYPE (other->spec) == entry->spec);
13251 dep->set_flag_bit<DB_ALIAS_SPEC_BIT> ();
13253 else
13255 gcc_checking_assert (decl_p || !is_alias);
13256 if (dep->get_entity_kind () == depset::EK_REDIRECT)
13257 dep = dep->deps[0];
13258 else if (dep->get_entity_kind () == depset::EK_SPECIALIZATION)
13260 dep->set_special ();
13261 dep->deps.safe_push (reinterpret_cast<depset *> (entry));
13262 if (!decl_p)
13263 dep->set_flag_bit<DB_TYPE_SPEC_BIT> ();
13266 if (needs_reaching)
13267 dep->set_flag_bit<DB_UNREACHED_BIT> ();
13268 if (is_friend)
13269 dep->set_flag_bit<DB_FRIEND_SPEC_BIT> ();
13272 data.release ();
13275 /* Add a depset into the mergeable hash. */
13277 void
13278 depset::hash::add_mergeable (depset *mergeable)
13280 gcc_checking_assert (is_key_order ());
13281 entity_kind ek = mergeable->get_entity_kind ();
13282 tree decl = mergeable->get_entity ();
13283 gcc_checking_assert (ek < EK_DIRECT_HWM);
13285 depset **slot = entity_slot (decl, true);
13286 gcc_checking_assert (!*slot);
13287 depset *dep = make_entity (decl, ek);
13288 *slot = dep;
13290 worklist.safe_push (dep);
13292 /* So we can locate the mergeable depset this depset refers to,
13293 mark the first dep. */
13294 dep->set_special ();
13295 dep->deps.safe_push (mergeable);
13298 /* Find the innermost-namespace scope of DECL, and that
13299 namespace-scope decl. */
13301 tree
13302 find_pending_key (tree decl, tree *decl_p = nullptr)
13304 tree ns = decl;
13307 decl = ns;
13308 ns = CP_DECL_CONTEXT (ns);
13309 if (TYPE_P (ns))
13310 ns = TYPE_NAME (ns);
13312 while (TREE_CODE (ns) != NAMESPACE_DECL);
13314 if (decl_p)
13315 *decl_p = decl;
13317 return ns;
13320 /* Iteratively find dependencies. During the walk we may find more
13321 entries on the same binding that need walking. */
13323 void
13324 depset::hash::find_dependencies (module_state *module)
13326 trees_out walker (NULL, module, *this);
13327 vec<depset *> unreached;
13328 unreached.create (worklist.length ());
13330 for (;;)
13332 reached_unreached = false;
13333 while (worklist.length ())
13335 depset *item = worklist.pop ();
13337 gcc_checking_assert (!item->is_binding ());
13338 if (item->is_unreached ())
13339 unreached.quick_push (item);
13340 else
13342 current = item;
13343 tree decl = current->get_entity ();
13344 dump (is_key_order () ? dumper::MERGE : dumper::DEPEND)
13345 && dump ("Dependencies of %s %C:%N",
13346 is_key_order () ? "key-order"
13347 : current->entity_kind_name (), TREE_CODE (decl), decl);
13348 dump.indent ();
13349 walker.begin ();
13350 if (current->get_entity_kind () == EK_USING)
13351 walker.tree_node (OVL_FUNCTION (decl));
13352 else if (TREE_VISITED (decl))
13353 /* A global tree. */;
13354 else if (item->get_entity_kind () == EK_NAMESPACE)
13356 module->note_location (DECL_SOURCE_LOCATION (decl));
13357 add_namespace_context (current, CP_DECL_CONTEXT (decl));
13359 else
13361 walker.mark_declaration (decl, current->has_defn ());
13363 if (!walker.is_key_order ()
13364 && (item->get_entity_kind () == EK_SPECIALIZATION
13365 || item->get_entity_kind () == EK_PARTIAL
13366 || (item->get_entity_kind () == EK_DECL
13367 && item->is_member ())))
13369 tree ns = find_pending_key (decl, nullptr);
13370 add_namespace_context (item, ns);
13373 // FIXME: Perhaps p1815 makes this redundant? Or at
13374 // least simplifies it. Voldemort types are only
13375 // ever emissable when containing (inline) function
13376 // definition is emitted?
13377 /* Turn the Sneakoscope on when depending the decl. */
13378 sneakoscope = true;
13379 walker.decl_value (decl, current);
13380 sneakoscope = false;
13381 if (current->has_defn ())
13382 walker.write_definition (decl);
13384 walker.end ();
13386 if (!walker.is_key_order ()
13387 && TREE_CODE (decl) == TEMPLATE_DECL
13388 && !DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
13389 /* Mark all the explicit & partial specializations as
13390 reachable. */
13391 for (tree cons = DECL_TEMPLATE_INSTANTIATIONS (decl);
13392 cons; cons = TREE_CHAIN (cons))
13394 tree spec = TREE_VALUE (cons);
13395 if (TYPE_P (spec))
13396 spec = TYPE_NAME (spec);
13397 int use_tpl;
13398 node_template_info (spec, use_tpl);
13399 if (use_tpl & 2)
13401 depset *spec_dep = find_dependency (spec);
13402 if (spec_dep->get_entity_kind () == EK_REDIRECT)
13403 spec_dep = spec_dep->deps[0];
13404 if (spec_dep->is_unreached ())
13406 reached_unreached = true;
13407 spec_dep->clear_flag_bit<DB_UNREACHED_BIT> ();
13408 dump (dumper::DEPEND)
13409 && dump ("Reaching unreached specialization"
13410 " %C:%N", TREE_CODE (spec), spec);
13415 dump.outdent ();
13416 current = NULL;
13420 if (!reached_unreached)
13421 break;
13423 /* It's possible the we reached the unreached before we
13424 processed it in the above loop, so we'll be doing this an
13425 extra time. However, to avoid that we have to do some
13426 bit shuffling that also involves a scan of the list.
13427 Swings & roundabouts I guess. */
13428 std::swap (worklist, unreached);
13431 unreached.release ();
13434 /* Compare two entries of a single binding. TYPE_DECL before
13435 non-exported before exported. */
13437 static int
13438 binding_cmp (const void *a_, const void *b_)
13440 depset *a = *(depset *const *)a_;
13441 depset *b = *(depset *const *)b_;
13443 tree a_ent = a->get_entity ();
13444 tree b_ent = b->get_entity ();
13445 gcc_checking_assert (a_ent != b_ent
13446 && !a->is_binding ()
13447 && !b->is_binding ());
13449 /* Implicit typedefs come first. */
13450 bool a_implicit = DECL_IMPLICIT_TYPEDEF_P (a_ent);
13451 bool b_implicit = DECL_IMPLICIT_TYPEDEF_P (b_ent);
13452 if (a_implicit || b_implicit)
13454 /* A binding with two implicit type decls? That's unpossible! */
13455 gcc_checking_assert (!(a_implicit && b_implicit));
13456 return a_implicit ? -1 : +1; /* Implicit first. */
13459 /* Hidden before non-hidden. */
13460 bool a_hidden = a->is_hidden ();
13461 bool b_hidden = b->is_hidden ();
13462 if (a_hidden != b_hidden)
13463 return a_hidden ? -1 : +1;
13465 bool a_using = a->get_entity_kind () == depset::EK_USING;
13466 bool a_export;
13467 if (a_using)
13469 a_export = OVL_EXPORT_P (a_ent);
13470 a_ent = OVL_FUNCTION (a_ent);
13472 else
13473 a_export = DECL_MODULE_EXPORT_P (TREE_CODE (a_ent) == CONST_DECL
13474 ? TYPE_NAME (TREE_TYPE (a_ent))
13475 : STRIP_TEMPLATE (a_ent));
13477 bool b_using = b->get_entity_kind () == depset::EK_USING;
13478 bool b_export;
13479 if (b_using)
13481 b_export = OVL_EXPORT_P (b_ent);
13482 b_ent = OVL_FUNCTION (b_ent);
13484 else
13485 b_export = DECL_MODULE_EXPORT_P (TREE_CODE (b_ent) == CONST_DECL
13486 ? TYPE_NAME (TREE_TYPE (b_ent))
13487 : STRIP_TEMPLATE (b_ent));
13489 /* Non-exports before exports. */
13490 if (a_export != b_export)
13491 return a_export ? +1 : -1;
13493 /* At this point we don't care, but want a stable sort. */
13495 if (a_using != b_using)
13496 /* using first. */
13497 return a_using? -1 : +1;
13499 return DECL_UID (a_ent) < DECL_UID (b_ent) ? -1 : +1;
13502 /* Sort the bindings, issue errors about bad internal refs. */
13504 bool
13505 depset::hash::finalize_dependencies ()
13507 bool ok = true;
13508 depset::hash::iterator end (this->end ());
13509 for (depset::hash::iterator iter (begin ()); iter != end; ++iter)
13511 depset *dep = *iter;
13512 if (dep->is_binding ())
13514 /* Keep the containing namespace dep first. */
13515 gcc_checking_assert (dep->deps.length () > 1
13516 && (dep->deps[0]->get_entity_kind ()
13517 == EK_NAMESPACE)
13518 && (dep->deps[0]->get_entity ()
13519 == dep->get_entity ()));
13520 if (dep->deps.length () > 2)
13521 gcc_qsort (&dep->deps[1], dep->deps.length () - 1,
13522 sizeof (dep->deps[1]), binding_cmp);
13524 else if (dep->refs_internal ())
13526 for (unsigned ix = dep->deps.length (); ix--;)
13528 depset *rdep = dep->deps[ix];
13529 if (rdep->is_internal ())
13531 // FIXME:QOI Better location information? We're
13532 // losing, so it doesn't matter about efficiency
13533 tree decl = dep->get_entity ();
13534 error_at (DECL_SOURCE_LOCATION (decl),
13535 "%q#D references internal linkage entity %q#D",
13536 decl, rdep->get_entity ());
13537 break;
13540 ok = false;
13544 return ok;
13547 /* Core of TARJAN's algorithm to find Strongly Connected Components
13548 within a graph. See https://en.wikipedia.org/wiki/
13549 Tarjan%27s_strongly_connected_components_algorithm for details.
13551 We use depset::section as lowlink. Completed nodes have
13552 depset::cluster containing the cluster number, with the top
13553 bit set.
13555 A useful property is that the output vector is a reverse
13556 topological sort of the resulting DAG. In our case that means
13557 dependent SCCs are found before their dependers. We make use of
13558 that property. */
13560 void
13561 depset::tarjan::connect (depset *v)
13563 gcc_checking_assert (v->is_binding ()
13564 || !(v->is_unreached () || v->is_import ()));
13566 v->cluster = v->section = ++index;
13567 stack.safe_push (v);
13569 /* Walk all our dependencies, ignore a first marked slot */
13570 for (unsigned ix = v->is_special (); ix != v->deps.length (); ix++)
13572 depset *dep = v->deps[ix];
13574 if (dep->is_binding () || !dep->is_import ())
13576 unsigned lwm = dep->cluster;
13578 if (!dep->cluster)
13580 /* A new node. Connect it. */
13581 connect (dep);
13582 lwm = dep->section;
13585 if (dep->section && v->section > lwm)
13586 v->section = lwm;
13590 if (v->section == v->cluster)
13592 /* Root of a new SCC. Push all the members onto the result list. */
13593 unsigned num = v->cluster;
13594 depset *p;
13597 p = stack.pop ();
13598 p->cluster = num;
13599 p->section = 0;
13600 result.quick_push (p);
13602 while (p != v);
13606 /* Compare two depsets. The specific ordering is unimportant, we're
13607 just trying to get consistency. */
13609 static int
13610 depset_cmp (const void *a_, const void *b_)
13612 depset *a = *(depset *const *)a_;
13613 depset *b = *(depset *const *)b_;
13615 depset::entity_kind a_kind = a->get_entity_kind ();
13616 depset::entity_kind b_kind = b->get_entity_kind ();
13618 if (a_kind != b_kind)
13619 /* Different entity kinds, order by that. */
13620 return a_kind < b_kind ? -1 : +1;
13622 tree a_decl = a->get_entity ();
13623 tree b_decl = b->get_entity ();
13624 if (a_kind == depset::EK_USING)
13626 /* If one is a using, the other must be too. */
13627 a_decl = OVL_FUNCTION (a_decl);
13628 b_decl = OVL_FUNCTION (b_decl);
13631 if (a_decl != b_decl)
13632 /* Different entities, order by their UID. */
13633 return DECL_UID (a_decl) < DECL_UID (b_decl) ? -1 : +1;
13635 if (a_kind == depset::EK_BINDING)
13637 /* Both are bindings. Order by identifier hash. */
13638 gcc_checking_assert (a->get_name () != b->get_name ());
13639 return (IDENTIFIER_HASH_VALUE (a->get_name ())
13640 < IDENTIFIER_HASH_VALUE (b->get_name ())
13641 ? -1 : +1);
13644 /* They are the same decl. This can happen with two using decls
13645 pointing to the same target. The best we can aim for is
13646 consistently telling qsort how to order them. Hopefully we'll
13647 never have to debug a case that depends on this. Oh, who am I
13648 kidding? Good luck. */
13649 gcc_checking_assert (a_kind == depset::EK_USING);
13651 /* Order by depset address. Not the best, but it is something. */
13652 return a < b ? -1 : +1;
13655 /* Sort the clusters in SCC such that those that depend on one another
13656 are placed later. */
13658 // FIXME: I am not convinced this is needed and, if needed,
13659 // sufficient. We emit the decls in this order but that emission
13660 // could walk into later decls (from the body of the decl, or default
13661 // arg-like things). Why doesn't that walk do the right thing? And
13662 // if it DTRT why do we need to sort here -- won't things naturally
13663 // work? I think part of the issue is that when we're going to refer
13664 // to an entity by name, and that entity is in the same cluster as us,
13665 // we need to actually walk that entity, if we've not already walked
13666 // it.
13667 static void
13668 sort_cluster (depset::hash *original, depset *scc[], unsigned size)
13670 depset::hash table (size, original);
13672 dump.indent ();
13674 /* Place bindings last, usings before that. It's not strictly
13675 necessary, but it does make things neater. Says Mr OCD. */
13676 unsigned bind_lwm = size;
13677 unsigned use_lwm = size;
13678 for (unsigned ix = 0; ix != use_lwm;)
13680 depset *dep = scc[ix];
13681 switch (dep->get_entity_kind ())
13683 case depset::EK_BINDING:
13684 /* Move to end. No increment. Notice this could be moving
13685 a using decl, which we'll then move again. */
13686 if (--bind_lwm != ix)
13688 scc[ix] = scc[bind_lwm];
13689 scc[bind_lwm] = dep;
13691 if (use_lwm > bind_lwm)
13693 use_lwm--;
13694 break;
13696 /* We must have copied a using, so move it too. */
13697 dep = scc[ix];
13698 gcc_checking_assert (dep->get_entity_kind () == depset::EK_USING);
13699 /* FALLTHROUGH */
13701 case depset::EK_USING:
13702 if (--use_lwm != ix)
13704 scc[ix] = scc[use_lwm];
13705 scc[use_lwm] = dep;
13707 break;
13709 case depset::EK_DECL:
13710 case depset::EK_SPECIALIZATION:
13711 case depset::EK_PARTIAL:
13712 table.add_mergeable (dep);
13713 ix++;
13714 break;
13716 default:
13717 gcc_unreachable ();
13721 gcc_checking_assert (use_lwm <= bind_lwm);
13722 dump (dumper::MERGE) && dump ("Ordering %u/%u depsets", use_lwm, size);
13724 table.find_dependencies (nullptr);
13726 vec<depset *> order = table.connect ();
13727 gcc_checking_assert (order.length () == use_lwm);
13729 /* Now rewrite entries [0,lwm), in the dependency order we
13730 discovered. Usually each entity is in its own cluster. Rarely,
13731 we can get multi-entity clusters, in which case all but one must
13732 only be reached from within the cluster. This happens for
13733 something like:
13735 template<typename T>
13736 auto Foo (const T &arg) -> TPL<decltype (arg)>;
13738 The instantiation of TPL will be in the specialization table, and
13739 refer to Foo via arg. But we can only get to that specialization
13740 from Foo's declaration, so we only need to treat Foo as mergable
13741 (We'll do structural comparison of TPL<decltype (arg)>).
13743 Finding the single cluster entry dep is very tricky and
13744 expensive. Let's just not do that. It's harmless in this case
13745 anyway. */
13746 unsigned pos = 0;
13747 unsigned cluster = ~0u;
13748 for (unsigned ix = 0; ix != order.length (); ix++)
13750 gcc_checking_assert (order[ix]->is_special ());
13751 depset *dep = order[ix]->deps[0];
13752 scc[pos++] = dep;
13753 dump (dumper::MERGE)
13754 && dump ("Mergeable %u is %N%s", ix, dep->get_entity (),
13755 order[ix]->cluster == cluster ? " (tight)" : "");
13756 cluster = order[ix]->cluster;
13759 gcc_checking_assert (pos == use_lwm);
13761 order.release ();
13762 dump (dumper::MERGE) && dump ("Ordered %u keys", pos);
13763 dump.outdent ();
13766 /* Reduce graph to SCCS clusters. SCCS will be populated with the
13767 depsets in dependency order. Each depset's CLUSTER field contains
13768 its cluster number. Each SCC has a unique cluster number, and are
13769 contiguous in SCCS. Cluster numbers are otherwise arbitrary. */
13771 vec<depset *>
13772 depset::hash::connect ()
13774 tarjan connector (size ());
13775 vec<depset *> deps;
13776 deps.create (size ());
13777 iterator end (this->end ());
13778 for (iterator iter (begin ()); iter != end; ++iter)
13780 depset *item = *iter;
13782 entity_kind kind = item->get_entity_kind ();
13783 if (kind == EK_BINDING
13784 || !(kind == EK_REDIRECT
13785 || item->is_unreached ()
13786 || item->is_import ()))
13787 deps.quick_push (item);
13790 /* Iteration over the hash table is an unspecified ordering. While
13791 that has advantages, it causes 2 problems. Firstly repeatable
13792 builds are tricky. Secondly creating testcases that check
13793 dependencies are correct by making sure a bad ordering would
13794 happen if that was wrong. */
13795 deps.qsort (depset_cmp);
13797 while (deps.length ())
13799 depset *v = deps.pop ();
13800 dump (dumper::CLUSTER) &&
13801 (v->is_binding ()
13802 ? dump ("Connecting binding %P", v->get_entity (), v->get_name ())
13803 : dump ("Connecting %s %s %C:%N",
13804 is_key_order () ? "key-order"
13805 : !v->has_defn () ? "declaration" : "definition",
13806 v->entity_kind_name (), TREE_CODE (v->get_entity ()),
13807 v->get_entity ()));
13808 if (!v->cluster)
13809 connector.connect (v);
13812 deps.release ();
13813 return connector.result;
13816 /* Initialize location spans. */
13818 void
13819 loc_spans::init (const line_maps *lmaps, const line_map_ordinary *map)
13821 gcc_checking_assert (!init_p ());
13822 spans = new vec<span> ();
13823 spans->reserve (20);
13825 span interval;
13826 interval.ordinary.first = 0;
13827 interval.macro.second = MAX_LOCATION_T + 1;
13828 interval.ordinary_delta = interval.macro_delta = 0;
13830 /* A span for reserved fixed locs. */
13831 interval.ordinary.second
13832 = MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0));
13833 interval.macro.first = interval.macro.second;
13834 dump (dumper::LOCATION)
13835 && dump ("Fixed span %u ordinary:[%u,%u) macro:[%u,%u)", spans->length (),
13836 interval.ordinary.first, interval.ordinary.second,
13837 interval.macro.first, interval.macro.second);
13838 spans->quick_push (interval);
13840 /* A span for command line & forced headers. */
13841 interval.ordinary.first = interval.ordinary.second;
13842 interval.macro.second = interval.macro.first;
13843 if (map)
13845 interval.ordinary.second = map->start_location;
13846 interval.macro.first = LINEMAPS_MACRO_LOWEST_LOCATION (lmaps);
13848 dump (dumper::LOCATION)
13849 && dump ("Pre span %u ordinary:[%u,%u) macro:[%u,%u)", spans->length (),
13850 interval.ordinary.first, interval.ordinary.second,
13851 interval.macro.first, interval.macro.second);
13852 spans->quick_push (interval);
13854 /* Start an interval for the main file. */
13855 interval.ordinary.first = interval.ordinary.second;
13856 interval.macro.second = interval.macro.first;
13857 dump (dumper::LOCATION)
13858 && dump ("Main span %u ordinary:[%u,*) macro:[*,%u)", spans->length (),
13859 interval.ordinary.first, interval.macro.second);
13860 spans->quick_push (interval);
13863 /* Reopen the span, if we want the about-to-be-inserted set of maps to
13864 be propagated in our own location table. I.e. we are the primary
13865 interface and we're importing a partition. */
13867 bool
13868 loc_spans::maybe_propagate (module_state *import, location_t hwm)
13870 bool opened = (module_interface_p () && !module_partition_p ()
13871 && import->is_partition ());
13872 if (opened)
13873 open (hwm);
13874 return opened;
13877 /* Open a new linemap interval. The just-created ordinary map is the
13878 first map of the interval. */
13880 void
13881 loc_spans::open (location_t hwm)
13883 span interval;
13884 interval.ordinary.first = interval.ordinary.second = hwm;
13885 interval.macro.first = interval.macro.second
13886 = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
13887 interval.ordinary_delta = interval.macro_delta = 0;
13888 dump (dumper::LOCATION)
13889 && dump ("Opening span %u ordinary:[%u,... macro:...,%u)",
13890 spans->length (), interval.ordinary.first,
13891 interval.macro.second);
13892 if (spans->length ())
13894 /* No overlapping! */
13895 auto &last = spans->last ();
13896 gcc_checking_assert (interval.ordinary.first >= last.ordinary.second);
13897 gcc_checking_assert (interval.macro.second <= last.macro.first);
13899 spans->safe_push (interval);
13902 /* Close out the current linemap interval. The last maps are within
13903 the interval. */
13905 void
13906 loc_spans::close ()
13908 span &interval = spans->last ();
13910 interval.ordinary.second
13911 = ((line_table->highest_location + (1 << line_table->default_range_bits))
13912 & ~((1u << line_table->default_range_bits) - 1));
13913 interval.macro.first = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
13914 dump (dumper::LOCATION)
13915 && dump ("Closing span %u ordinary:[%u,%u) macro:[%u,%u)",
13916 spans->length () - 1,
13917 interval.ordinary.first,interval.ordinary.second,
13918 interval.macro.first, interval.macro.second);
13921 /* Given an ordinary location LOC, return the lmap_interval it resides
13922 in. NULL if it is not in an interval. */
13924 const loc_spans::span *
13925 loc_spans::ordinary (location_t loc)
13927 unsigned len = spans->length ();
13928 unsigned pos = 0;
13929 while (len)
13931 unsigned half = len / 2;
13932 const span &probe = (*spans)[pos + half];
13933 if (loc < probe.ordinary.first)
13934 len = half;
13935 else if (loc < probe.ordinary.second)
13936 return &probe;
13937 else
13939 pos += half + 1;
13940 len = len - (half + 1);
13943 return NULL;
13946 /* Likewise, given a macro location LOC, return the lmap interval it
13947 resides in. */
13949 const loc_spans::span *
13950 loc_spans::macro (location_t loc)
13952 unsigned len = spans->length ();
13953 unsigned pos = 0;
13954 while (len)
13956 unsigned half = len / 2;
13957 const span &probe = (*spans)[pos + half];
13958 if (loc >= probe.macro.second)
13959 len = half;
13960 else if (loc >= probe.macro.first)
13961 return &probe;
13962 else
13964 pos += half + 1;
13965 len = len - (half + 1);
13968 return NULL;
13971 /* Return the ordinary location closest to FROM. */
13973 static location_t
13974 ordinary_loc_of (line_maps *lmaps, location_t from)
13976 while (!IS_ORDINARY_LOC (from))
13978 if (IS_ADHOC_LOC (from))
13979 from = get_location_from_adhoc_loc (lmaps, from);
13980 if (from >= LINEMAPS_MACRO_LOWEST_LOCATION (lmaps))
13982 /* Find the ordinary location nearest FROM. */
13983 const line_map *map = linemap_lookup (lmaps, from);
13984 const line_map_macro *mac_map = linemap_check_macro (map);
13985 from = mac_map->get_expansion_point_location ();
13988 return from;
13991 static module_state **
13992 get_module_slot (tree name, module_state *parent, bool partition, bool insert)
13994 module_state_hash::compare_type ct (name, uintptr_t (parent) | partition);
13995 hashval_t hv = module_state_hash::hash (ct);
13997 return modules_hash->find_slot_with_hash (ct, hv, insert ? INSERT : NO_INSERT);
14000 static module_state *
14001 get_primary (module_state *parent)
14003 while (parent->is_partition ())
14004 parent = parent->parent;
14006 if (!parent->name)
14007 // Implementation unit has null name
14008 parent = parent->parent;
14010 return parent;
14013 /* Find or create module NAME & PARENT in the hash table. */
14015 module_state *
14016 get_module (tree name, module_state *parent, bool partition)
14018 if (partition)
14020 if (!parent)
14021 parent = get_primary ((*modules)[0]);
14023 if (!parent->is_partition () && !parent->flatname)
14024 parent->set_flatname ();
14027 module_state **slot = get_module_slot (name, parent, partition, true);
14028 module_state *state = *slot;
14029 if (!state)
14031 state = (new (ggc_alloc<module_state> ())
14032 module_state (name, parent, partition));
14033 *slot = state;
14035 return state;
14038 /* Process string name PTR into a module_state. */
14040 static module_state *
14041 get_module (const char *ptr)
14043 /* On DOS based file systems, there is an ambiguity with A:B which can be
14044 interpreted as a module Module:Partition or Drive:PATH. Interpret strings
14045 which clearly starts as pathnames as header-names and everything else is
14046 treated as a (possibly malformed) named moduled. */
14047 if (IS_DIR_SEPARATOR (ptr[ptr[0] == '.']) // ./FOO or /FOO
14048 #if HAVE_DOS_BASED_FILE_SYSTEM
14049 || (HAS_DRIVE_SPEC (ptr) && IS_DIR_SEPARATOR (ptr[2])) // A:/FOO
14050 #endif
14051 || false)
14052 /* A header name. */
14053 return get_module (build_string (strlen (ptr), ptr));
14055 bool partition = false;
14056 module_state *mod = NULL;
14058 for (const char *probe = ptr;; probe++)
14059 if (!*probe || *probe == '.' || *probe == ':')
14061 if (probe == ptr)
14062 return NULL;
14064 mod = get_module (get_identifier_with_length (ptr, probe - ptr),
14065 mod, partition);
14066 ptr = probe;
14067 if (*ptr == ':')
14069 if (partition)
14070 return NULL;
14071 partition = true;
14074 if (!*ptr++)
14075 break;
14077 else if (!(ISALPHA (*probe) || *probe == '_'
14078 || (probe != ptr && ISDIGIT (*probe))))
14079 return NULL;
14081 return mod;
14084 /* Create a new mapper connecting to OPTION. */
14086 module_client *
14087 make_mapper (location_t loc, class mkdeps *deps)
14089 timevar_start (TV_MODULE_MAPPER);
14090 const char *option = module_mapper_name;
14091 if (!option)
14092 option = getenv ("CXX_MODULE_MAPPER");
14094 mapper = module_client::open_module_client
14095 (loc, option, deps, &set_cmi_repo,
14096 (save_decoded_options[0].opt_index == OPT_SPECIAL_program_name)
14097 && save_decoded_options[0].arg != progname
14098 ? save_decoded_options[0].arg : nullptr);
14100 timevar_stop (TV_MODULE_MAPPER);
14102 return mapper;
14105 static unsigned lazy_snum;
14107 static bool
14108 recursive_lazy (unsigned snum = ~0u)
14110 if (lazy_snum)
14112 error_at (input_location, "recursive lazy load");
14113 return true;
14116 lazy_snum = snum;
14117 return false;
14120 /* If THIS is the current purview, issue an import error and return false. */
14122 bool
14123 module_state::check_not_purview (location_t from)
14125 module_state *imp = (*modules)[0];
14126 if (imp && !imp->name)
14127 imp = imp->parent;
14128 if (imp == this)
14130 /* Cannot import the current module. */
14131 error_at (from, "cannot import module in its own purview");
14132 inform (loc, "module %qs declared here", get_flatname ());
14133 return false;
14135 return true;
14138 /* Module name substitutions. */
14139 static vec<module_state *,va_heap> substs;
14141 void
14142 module_state::mangle (bool include_partition)
14144 if (subst)
14145 mangle_module_substitution (subst);
14146 else
14148 if (parent)
14149 parent->mangle (include_partition);
14150 if (include_partition || !is_partition ())
14152 // Partitions are significant for global initializer
14153 // functions
14154 bool partition = is_partition () && !parent->is_partition ();
14155 subst = mangle_module_component (name, partition);
14156 substs.safe_push (this);
14161 void
14162 mangle_module (int mod, bool include_partition)
14164 module_state *imp = (*modules)[mod];
14166 gcc_checking_assert (!imp->is_header ());
14168 if (!imp->name)
14169 /* Set when importing the primary module interface. */
14170 imp = imp->parent;
14172 imp->mangle (include_partition);
14175 /* Clean up substitutions. */
14176 void
14177 mangle_module_fini ()
14179 while (substs.length ())
14180 substs.pop ()->subst = 0;
14183 /* Announce WHAT about the module. */
14185 void
14186 module_state::announce (const char *what) const
14188 if (noisy_p ())
14190 fprintf (stderr, " %s:%s", what, get_flatname ());
14191 fflush (stderr);
14195 /* A human-readable README section. The contents of this section to
14196 not contribute to the CRC, so the contents can change per
14197 compilation. That allows us to embed CWD, hostname, build time and
14198 what not. It is a STRTAB that may be extracted with:
14199 readelf -pgnu.c++.README $(module).gcm */
14201 void
14202 module_state::write_readme (elf_out *to, cpp_reader *reader, const char *dialect)
14204 bytes_out readme (to);
14206 readme.begin (false);
14208 readme.printf ("GNU C++ %s",
14209 is_header () ? "header unit"
14210 : !is_partition () ? "primary interface"
14211 : is_interface () ? "interface partition"
14212 : "internal partition");
14214 /* Compiler's version. */
14215 readme.printf ("compiler: %s", version_string);
14217 /* Module format version. */
14218 verstr_t string;
14219 version2string (MODULE_VERSION, string);
14220 readme.printf ("version: %s", string);
14222 /* Module information. */
14223 readme.printf ("module: %s", get_flatname ());
14224 readme.printf ("source: %s", main_input_filename);
14225 readme.printf ("dialect: %s", dialect);
14226 if (extensions)
14227 readme.printf ("extensions: %s",
14228 extensions & SE_OPENMP ? "-fopenmp" : "");
14230 /* The following fields could be expected to change between
14231 otherwise identical compilations. Consider a distributed build
14232 system. We should have a way of overriding that. */
14233 if (char *cwd = getcwd (NULL, 0))
14235 readme.printf ("cwd: %s", cwd);
14236 free (cwd);
14238 readme.printf ("repository: %s", cmi_repo ? cmi_repo : ".");
14239 #if NETWORKING
14241 char hostname[64];
14242 if (!gethostname (hostname, sizeof (hostname)))
14243 readme.printf ("host: %s", hostname);
14245 #endif
14247 /* This of course will change! */
14248 time_t stampy;
14249 auto kind = cpp_get_date (reader, &stampy);
14250 if (kind != CPP_time_kind::UNKNOWN)
14252 struct tm *time;
14254 time = gmtime (&stampy);
14255 readme.print_time ("build", time, "UTC");
14257 if (kind == CPP_time_kind::DYNAMIC)
14259 time = localtime (&stampy);
14260 readme.print_time ("local", time,
14261 #if defined (__USE_MISC) || defined (__USE_BSD) /* Is there a better way? */
14262 time->tm_zone
14263 #else
14265 #endif
14271 /* Its direct imports. */
14272 for (unsigned ix = 1; ix < modules->length (); ix++)
14274 module_state *state = (*modules)[ix];
14276 if (state->is_direct ())
14277 readme.printf ("%s: %s %s", state->exported_p ? "export" : "import",
14278 state->get_flatname (), state->filename);
14281 readme.end (to, to->name (MOD_SNAME_PFX ".README"), NULL);
14284 /* Sort environment var names in reverse order. */
14286 static int
14287 env_var_cmp (const void *a_, const void *b_)
14289 const unsigned char *a = *(const unsigned char *const *)a_;
14290 const unsigned char *b = *(const unsigned char *const *)b_;
14292 for (unsigned ix = 0; ; ix++)
14294 bool a_end = !a[ix] || a[ix] == '=';
14295 if (a[ix] == b[ix])
14297 if (a_end)
14298 break;
14300 else
14302 bool b_end = !b[ix] || b[ix] == '=';
14304 if (!a_end && !b_end)
14305 return a[ix] < b[ix] ? +1 : -1;
14306 if (a_end && b_end)
14307 break;
14308 return a_end ? +1 : -1;
14312 return 0;
14315 /* Write the environment. It is a STRTAB that may be extracted with:
14316 readelf -pgnu.c++.ENV $(module).gcm */
14318 void
14319 module_state::write_env (elf_out *to)
14321 vec<const char *> vars;
14322 vars.create (20);
14324 extern char **environ;
14325 while (const char *var = environ[vars.length ()])
14326 vars.safe_push (var);
14327 vars.qsort (env_var_cmp);
14329 bytes_out env (to);
14330 env.begin (false);
14331 while (vars.length ())
14332 env.printf ("%s", vars.pop ());
14333 env.end (to, to->name (MOD_SNAME_PFX ".ENV"), NULL);
14335 vars.release ();
14338 /* Write the direct or indirect imports.
14341 u:index
14342 s:name
14343 u32:crc
14344 s:filename (direct)
14345 u:exported (direct)
14346 } imports[N]
14349 void
14350 module_state::write_imports (bytes_out &sec, bool direct)
14352 unsigned count = 0;
14354 for (unsigned ix = 1; ix < modules->length (); ix++)
14356 module_state *imp = (*modules)[ix];
14358 if (imp->remap && imp->is_direct () == direct)
14359 count++;
14362 gcc_assert (!direct || count);
14364 sec.u (count);
14365 for (unsigned ix = 1; ix < modules->length (); ix++)
14367 module_state *imp = (*modules)[ix];
14369 if (imp->remap && imp->is_direct () == direct)
14371 dump () && dump ("Writing %simport:%u->%u %M (crc=%x)",
14372 !direct ? "indirect "
14373 : imp->exported_p ? "exported " : "",
14374 ix, imp->remap, imp, imp->crc);
14375 sec.u (imp->remap);
14376 sec.str (imp->get_flatname ());
14377 sec.u32 (imp->crc);
14378 if (direct)
14380 write_location (sec, imp->imported_from ());
14381 sec.str (imp->filename);
14382 int exportedness = 0;
14383 if (imp->exported_p)
14384 exportedness = +1;
14385 else if (!imp->is_purview_direct ())
14386 exportedness = -1;
14387 sec.i (exportedness);
14393 /* READER, LMAPS != NULL == direct imports,
14394 == NUL == indirect imports. */
14396 unsigned
14397 module_state::read_imports (bytes_in &sec, cpp_reader *reader, line_maps *lmaps)
14399 unsigned count = sec.u ();
14400 unsigned loaded = 0;
14402 while (count--)
14404 unsigned ix = sec.u ();
14405 if (ix >= slurp->remap->length () || !ix || (*slurp->remap)[ix])
14407 sec.set_overrun ();
14408 break;
14411 const char *name = sec.str (NULL);
14412 module_state *imp = get_module (name);
14413 unsigned crc = sec.u32 ();
14414 int exportedness = 0;
14416 /* If the import is a partition, it must be the same primary
14417 module as this TU. */
14418 if (imp && imp->is_partition () &&
14419 (!named_module_p ()
14420 || (get_primary ((*modules)[0]) != get_primary (imp))))
14421 imp = NULL;
14423 if (!imp)
14424 sec.set_overrun ();
14425 if (sec.get_overrun ())
14426 break;
14428 if (lmaps)
14430 /* A direct import, maybe load it. */
14431 location_t floc = read_location (sec);
14432 const char *fname = sec.str (NULL);
14433 exportedness = sec.i ();
14435 if (sec.get_overrun ())
14436 break;
14438 if (!imp->check_not_purview (loc))
14439 continue;
14441 if (imp->loadedness == ML_NONE)
14443 imp->loc = floc;
14444 imp->crc = crc;
14445 if (!imp->get_flatname ())
14446 imp->set_flatname ();
14448 unsigned n = dump.push (imp);
14450 if (!imp->filename && fname)
14451 imp->filename = xstrdup (fname);
14453 if (imp->is_partition ())
14454 dump () && dump ("Importing elided partition %M", imp);
14456 if (!imp->do_import (reader, false))
14457 imp = NULL;
14458 dump.pop (n);
14459 if (!imp)
14460 continue;
14463 if (is_partition ())
14465 if (!imp->is_direct ())
14466 imp->directness = MD_PARTITION_DIRECT;
14467 if (exportedness > 0)
14468 imp->exported_p = true;
14471 else
14473 /* An indirect import, find it, it should already be here. */
14474 if (imp->loadedness == ML_NONE)
14476 error_at (loc, "indirect import %qs is not already loaded", name);
14477 continue;
14481 if (imp->crc != crc)
14482 error_at (loc, "import %qs has CRC mismatch", imp->get_flatname ());
14484 (*slurp->remap)[ix] = (imp->mod << 1) | (lmaps != NULL);
14486 if (lmaps && exportedness >= 0)
14487 set_import (imp, bool (exportedness));
14488 dump () && dump ("Found %simport:%u %M->%u", !lmaps ? "indirect "
14489 : exportedness > 0 ? "exported "
14490 : exportedness < 0 ? "gmf" : "", ix, imp,
14491 imp->mod);
14492 loaded++;
14495 return loaded;
14498 /* Write the import table to MOD_SNAME_PFX.imp. */
14500 void
14501 module_state::write_imports (elf_out *to, unsigned *crc_ptr)
14503 dump () && dump ("Writing imports");
14504 dump.indent ();
14506 bytes_out sec (to);
14507 sec.begin ();
14509 write_imports (sec, true);
14510 write_imports (sec, false);
14512 sec.end (to, to->name (MOD_SNAME_PFX ".imp"), crc_ptr);
14513 dump.outdent ();
14516 bool
14517 module_state::read_imports (cpp_reader *reader, line_maps *lmaps)
14519 bytes_in sec;
14521 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".imp"))
14522 return false;
14524 dump () && dump ("Reading %u imports", slurp->remap->length () - 1);
14525 dump.indent ();
14527 /* Read the imports. */
14528 unsigned direct = read_imports (sec, reader, lmaps);
14529 unsigned indirect = read_imports (sec, NULL, NULL);
14530 if (direct + indirect + 1 != slurp->remap->length ())
14531 from ()->set_error (elf::E_BAD_IMPORT);
14533 dump.outdent ();
14534 if (!sec.end (from ()))
14535 return false;
14536 return true;
14539 /* We're the primary module interface, but have partitions. Document
14540 them so that non-partition module implementation units know which
14541 have already been loaded. */
14543 void
14544 module_state::write_partitions (elf_out *to, unsigned count, unsigned *crc_ptr)
14546 dump () && dump ("Writing %u elided partitions", count);
14547 dump.indent ();
14549 bytes_out sec (to);
14550 sec.begin ();
14552 for (unsigned ix = 1; ix != modules->length (); ix++)
14554 module_state *imp = (*modules)[ix];
14555 if (imp->is_partition ())
14557 dump () && dump ("Writing elided partition %M (crc=%x)",
14558 imp, imp->crc);
14559 sec.str (imp->get_flatname ());
14560 sec.u32 (imp->crc);
14561 write_location (sec, imp->is_direct ()
14562 ? imp->imported_from () : UNKNOWN_LOCATION);
14563 sec.str (imp->filename);
14567 sec.end (to, to->name (MOD_SNAME_PFX ".prt"), crc_ptr);
14568 dump.outdent ();
14571 bool
14572 module_state::read_partitions (unsigned count)
14574 bytes_in sec;
14575 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".prt"))
14576 return false;
14578 dump () && dump ("Reading %u elided partitions", count);
14579 dump.indent ();
14581 while (count--)
14583 const char *name = sec.str (NULL);
14584 unsigned crc = sec.u32 ();
14585 location_t floc = read_location (sec);
14586 const char *fname = sec.str (NULL);
14588 if (sec.get_overrun ())
14589 break;
14591 dump () && dump ("Reading elided partition %s (crc=%x)", name, crc);
14593 module_state *imp = get_module (name);
14594 if (!imp /* Partition should be ... */
14595 || !imp->is_partition () /* a partition ... */
14596 || imp->loadedness != ML_NONE /* that is not yet loaded ... */
14597 || get_primary (imp) != this) /* whose primary is this. */
14599 sec.set_overrun ();
14600 break;
14603 if (!imp->has_location ())
14604 imp->loc = floc;
14605 imp->crc = crc;
14606 if (!imp->filename && fname[0])
14607 imp->filename = xstrdup (fname);
14610 dump.outdent ();
14611 if (!sec.end (from ()))
14612 return false;
14613 return true;
14616 /* Data for config reading and writing. */
14617 struct module_state_config {
14618 const char *dialect_str;
14619 unsigned num_imports;
14620 unsigned num_partitions;
14621 unsigned num_entities;
14622 unsigned ordinary_locs;
14623 unsigned macro_locs;
14624 unsigned loc_range_bits;
14625 unsigned active_init;
14627 public:
14628 module_state_config ()
14629 :dialect_str (get_dialect ()),
14630 num_imports (0), num_partitions (0), num_entities (0),
14631 ordinary_locs (0), macro_locs (0), loc_range_bits (0),
14632 active_init (0)
14636 static void release ()
14638 XDELETEVEC (dialect);
14639 dialect = NULL;
14642 private:
14643 static const char *get_dialect ();
14644 static char *dialect;
14647 char *module_state_config::dialect;
14649 /* Generate a string of the significant compilation options.
14650 Generally assume the user knows what they're doing, in the same way
14651 that object files can be mixed. */
14653 const char *
14654 module_state_config::get_dialect ()
14656 if (!dialect)
14657 dialect = concat (get_cxx_dialect_name (cxx_dialect),
14658 /* C++ implies these, only show if disabled. */
14659 flag_exceptions ? "" : "/no-exceptions",
14660 flag_rtti ? "" : "/no-rtti",
14661 flag_new_inheriting_ctors ? "" : "/old-inheriting-ctors",
14662 /* C++ 20 implies concepts. */
14663 cxx_dialect < cxx20 && flag_concepts ? "/concepts" : "",
14664 flag_coroutines ? "/coroutines" : "",
14665 flag_module_implicit_inline ? "/implicit-inline" : "",
14666 flag_contracts ? "/contracts" : "",
14667 NULL);
14669 return dialect;
14672 /* Contents of a cluster. */
14673 enum cluster_tag {
14674 ct_decl, /* A decl. */
14675 ct_defn, /* A definition. */
14676 ct_bind, /* A binding. */
14677 ct_hwm
14680 /* Binding modifiers. */
14681 enum ct_bind_flags
14683 cbf_export = 0x1, /* An exported decl. */
14684 cbf_hidden = 0x2, /* A hidden (friend) decl. */
14685 cbf_using = 0x4, /* A using decl. */
14686 cbf_wrapped = 0x8, /* ... that is wrapped. */
14689 /* DEP belongs to a different cluster, seed it to prevent
14690 unfortunately timed duplicate import. */
14691 // FIXME: QOI For inter-cluster references we could just only pick
14692 // one entity from an earlier cluster. Even better track
14693 // dependencies between earlier clusters
14695 void
14696 module_state::intercluster_seed (trees_out &sec, unsigned index_hwm, depset *dep)
14698 if (dep->is_import ()
14699 || dep->cluster < index_hwm)
14701 tree ent = dep->get_entity ();
14702 if (!TREE_VISITED (ent))
14704 sec.tree_node (ent);
14705 dump (dumper::CLUSTER)
14706 && dump ("Seeded %s %N",
14707 dep->is_import () ? "import" : "intercluster", ent);
14712 /* Write the cluster of depsets in SCC[0-SIZE).
14713 dep->section -> section number
14714 dep->cluster -> entity number
14717 unsigned
14718 module_state::write_cluster (elf_out *to, depset *scc[], unsigned size,
14719 depset::hash &table, unsigned *counts,
14720 unsigned *crc_ptr)
14722 dump () && dump ("Writing section:%u %u depsets", table.section, size);
14723 dump.indent ();
14725 trees_out sec (to, this, table, table.section);
14726 sec.begin ();
14727 unsigned index_lwm = counts[MSC_entities];
14729 /* Determine entity numbers, mark for writing. */
14730 dump (dumper::CLUSTER) && dump ("Cluster members:") && (dump.indent (), true);
14731 for (unsigned ix = 0; ix != size; ix++)
14733 depset *b = scc[ix];
14735 switch (b->get_entity_kind ())
14737 default:
14738 gcc_unreachable ();
14740 case depset::EK_BINDING:
14742 dump (dumper::CLUSTER)
14743 && dump ("[%u]=%s %P", ix, b->entity_kind_name (),
14744 b->get_entity (), b->get_name ());
14745 depset *ns_dep = b->deps[0];
14746 gcc_checking_assert (ns_dep->get_entity_kind ()
14747 == depset::EK_NAMESPACE
14748 && ns_dep->get_entity () == b->get_entity ());
14749 for (unsigned jx = b->deps.length (); --jx;)
14751 depset *dep = b->deps[jx];
14752 // We could be declaring something that is also a
14753 // (merged) import
14754 gcc_checking_assert (dep->is_import ()
14755 || TREE_VISITED (dep->get_entity ())
14756 || (dep->get_entity_kind ()
14757 == depset::EK_USING));
14760 break;
14762 case depset::EK_DECL:
14763 case depset::EK_SPECIALIZATION:
14764 case depset::EK_PARTIAL:
14765 b->cluster = counts[MSC_entities]++;
14766 sec.mark_declaration (b->get_entity (), b->has_defn ());
14767 /* FALLTHROUGH */
14769 case depset::EK_USING:
14770 gcc_checking_assert (!b->is_import ()
14771 && !b->is_unreached ());
14772 dump (dumper::CLUSTER)
14773 && dump ("[%u]=%s %s %N", ix, b->entity_kind_name (),
14774 b->has_defn () ? "definition" : "declaration",
14775 b->get_entity ());
14776 break;
14779 dump (dumper::CLUSTER) && (dump.outdent (), true);
14781 /* Ensure every out-of-cluster decl is referenced before we start
14782 streaming. We must do both imports *and* earlier clusters,
14783 because the latter could reach into the former and cause a
14784 duplicate loop. */
14785 sec.set_importing (+1);
14786 for (unsigned ix = 0; ix != size; ix++)
14788 depset *b = scc[ix];
14789 for (unsigned jx = b->is_special (); jx != b->deps.length (); jx++)
14791 depset *dep = b->deps[jx];
14793 if (dep->is_binding ())
14795 for (unsigned ix = dep->deps.length (); --ix;)
14797 depset *bind = dep->deps[ix];
14798 if (bind->get_entity_kind () == depset::EK_USING)
14799 bind = bind->deps[1];
14801 intercluster_seed (sec, index_lwm, bind);
14803 /* Also check the namespace itself. */
14804 dep = dep->deps[0];
14807 intercluster_seed (sec, index_lwm, dep);
14810 sec.tree_node (NULL_TREE);
14811 /* We're done importing now. */
14812 sec.set_importing (-1);
14814 /* Write non-definitions. */
14815 for (unsigned ix = 0; ix != size; ix++)
14817 depset *b = scc[ix];
14818 tree decl = b->get_entity ();
14819 switch (b->get_entity_kind ())
14821 default:
14822 gcc_unreachable ();
14823 break;
14825 case depset::EK_BINDING:
14827 gcc_assert (TREE_CODE (decl) == NAMESPACE_DECL);
14828 dump () && dump ("Depset:%u binding %C:%P", ix, TREE_CODE (decl),
14829 decl, b->get_name ());
14830 sec.u (ct_bind);
14831 sec.tree_node (decl);
14832 sec.tree_node (b->get_name ());
14834 /* Write in reverse order, so reading will see the exports
14835 first, thus building the overload chain will be
14836 optimized. */
14837 for (unsigned jx = b->deps.length (); --jx;)
14839 depset *dep = b->deps[jx];
14840 tree bound = dep->get_entity ();
14841 unsigned flags = 0;
14842 if (dep->get_entity_kind () == depset::EK_USING)
14844 tree ovl = bound;
14845 bound = OVL_FUNCTION (bound);
14846 if (!(TREE_CODE (bound) == CONST_DECL
14847 && UNSCOPED_ENUM_P (TREE_TYPE (bound))
14848 && decl == TYPE_NAME (TREE_TYPE (bound))))
14850 /* An unscope enumerator in its enumeration's
14851 scope is not a using. */
14852 flags |= cbf_using;
14853 if (OVL_USING_P (ovl))
14854 flags |= cbf_wrapped;
14856 if (OVL_EXPORT_P (ovl))
14857 flags |= cbf_export;
14859 else
14861 /* An implicit typedef must be at one. */
14862 gcc_assert (!DECL_IMPLICIT_TYPEDEF_P (bound) || jx == 1);
14863 if (dep->is_hidden ())
14864 flags |= cbf_hidden;
14865 else if (DECL_MODULE_EXPORT_P (STRIP_TEMPLATE (bound)))
14866 flags |= cbf_export;
14869 gcc_checking_assert (DECL_P (bound));
14871 sec.i (flags);
14872 sec.tree_node (bound);
14875 /* Terminate the list. */
14876 sec.i (-1);
14878 break;
14880 case depset::EK_USING:
14881 dump () && dump ("Depset:%u %s %C:%N", ix, b->entity_kind_name (),
14882 TREE_CODE (decl), decl);
14883 break;
14885 case depset::EK_SPECIALIZATION:
14886 case depset::EK_PARTIAL:
14887 case depset::EK_DECL:
14888 dump () && dump ("Depset:%u %s entity:%u %C:%N", ix,
14889 b->entity_kind_name (), b->cluster,
14890 TREE_CODE (decl), decl);
14892 sec.u (ct_decl);
14893 sec.tree_node (decl);
14895 dump () && dump ("Wrote declaration entity:%u %C:%N",
14896 b->cluster, TREE_CODE (decl), decl);
14897 break;
14901 depset *namer = NULL;
14903 /* Write out definitions */
14904 for (unsigned ix = 0; ix != size; ix++)
14906 depset *b = scc[ix];
14907 tree decl = b->get_entity ();
14908 switch (b->get_entity_kind ())
14910 default:
14911 break;
14913 case depset::EK_SPECIALIZATION:
14914 case depset::EK_PARTIAL:
14915 case depset::EK_DECL:
14916 if (!namer)
14917 namer = b;
14919 if (b->has_defn ())
14921 sec.u (ct_defn);
14922 sec.tree_node (decl);
14923 dump () && dump ("Writing definition %N", decl);
14924 sec.write_definition (decl);
14926 if (!namer->has_defn ())
14927 namer = b;
14929 break;
14933 /* We don't find the section by name. Use depset's decl's name for
14934 human friendliness. */
14935 unsigned name = 0;
14936 tree naming_decl = NULL_TREE;
14937 if (namer)
14939 naming_decl = namer->get_entity ();
14940 if (namer->get_entity_kind () == depset::EK_USING)
14941 /* This unfortunately names the section from the target of the
14942 using decl. But the name is only a guide, so Do Not Care. */
14943 naming_decl = OVL_FUNCTION (naming_decl);
14944 if (DECL_IMPLICIT_TYPEDEF_P (naming_decl))
14945 /* Lose any anonymousness. */
14946 naming_decl = TYPE_NAME (TREE_TYPE (naming_decl));
14947 name = to->qualified_name (naming_decl, namer->has_defn ());
14950 unsigned bytes = sec.pos;
14951 unsigned snum = sec.end (to, name, crc_ptr);
14953 for (unsigned ix = size; ix--;)
14954 gcc_checking_assert (scc[ix]->section == snum);
14956 dump.outdent ();
14957 dump () && dump ("Wrote section:%u named-by:%N", table.section, naming_decl);
14959 return bytes;
14962 /* Read a cluster from section SNUM. */
14964 bool
14965 module_state::read_cluster (unsigned snum)
14967 trees_in sec (this);
14969 if (!sec.begin (loc, from (), snum))
14970 return false;
14972 dump () && dump ("Reading section:%u", snum);
14973 dump.indent ();
14975 /* We care about structural equality. */
14976 comparing_dependent_aliases++;
14978 /* First seed the imports. */
14979 while (tree import = sec.tree_node ())
14980 dump (dumper::CLUSTER) && dump ("Seeded import %N", import);
14982 while (!sec.get_overrun () && sec.more_p ())
14984 unsigned ct = sec.u ();
14985 switch (ct)
14987 default:
14988 sec.set_overrun ();
14989 break;
14991 case ct_bind:
14992 /* A set of namespace bindings. */
14994 tree ns = sec.tree_node ();
14995 tree name = sec.tree_node ();
14996 tree decls = NULL_TREE;
14997 tree visible = NULL_TREE;
14998 tree type = NULL_TREE;
14999 bool dedup = false;
15001 /* We rely on the bindings being in the reverse order of
15002 the resulting overload set. */
15003 for (;;)
15005 int flags = sec.i ();
15006 if (flags < 0)
15007 break;
15009 if ((flags & cbf_hidden)
15010 && (flags & (cbf_using | cbf_export)))
15011 sec.set_overrun ();
15013 tree decl = sec.tree_node ();
15014 if (sec.get_overrun ())
15015 break;
15017 if (decls && TREE_CODE (decl) == TYPE_DECL)
15019 /* Stat hack. */
15020 if (type || !DECL_IMPLICIT_TYPEDEF_P (decl))
15021 sec.set_overrun ();
15022 type = decl;
15024 else
15026 if (decls
15027 || (flags & (cbf_hidden | cbf_wrapped))
15028 || DECL_FUNCTION_TEMPLATE_P (decl))
15030 decls = ovl_make (decl, decls);
15031 if (flags & cbf_using)
15033 dedup = true;
15034 OVL_USING_P (decls) = true;
15035 if (flags & cbf_export)
15036 OVL_EXPORT_P (decls) = true;
15039 if (flags & cbf_hidden)
15040 OVL_HIDDEN_P (decls) = true;
15041 else if (dedup)
15042 OVL_DEDUP_P (decls) = true;
15044 else
15045 decls = decl;
15047 if (flags & cbf_export
15048 || (!(flags & cbf_hidden)
15049 && (is_module () || is_partition ())))
15050 visible = decls;
15054 if (!decls)
15055 sec.set_overrun ();
15057 if (sec.get_overrun ())
15058 break; /* Bail. */
15060 dump () && dump ("Binding of %P", ns, name);
15061 if (!set_module_binding (ns, name, mod,
15062 is_header () ? -1
15063 : is_module () || is_partition () ? 1
15064 : 0,
15065 decls, type, visible))
15066 sec.set_overrun ();
15068 break;
15070 case ct_decl:
15071 /* A decl. */
15073 tree decl = sec.tree_node ();
15074 dump () && dump ("Read declaration of %N", decl);
15076 break;
15078 case ct_defn:
15080 tree decl = sec.tree_node ();
15081 dump () && dump ("Reading definition of %N", decl);
15082 sec.read_definition (decl);
15084 break;
15088 /* When lazy loading is in effect, we can be in the middle of
15089 parsing or instantiating a function. Save it away.
15090 push_function_context does too much work. */
15091 tree old_cfd = current_function_decl;
15092 struct function *old_cfun = cfun;
15093 while (tree decl = sec.post_process ())
15095 bool abstract = false;
15096 if (TREE_CODE (decl) == TEMPLATE_DECL)
15098 abstract = true;
15099 decl = DECL_TEMPLATE_RESULT (decl);
15102 current_function_decl = decl;
15103 allocate_struct_function (decl, abstract);
15104 cfun->language = ggc_cleared_alloc<language_function> ();
15105 cfun->language->base.x_stmt_tree.stmts_are_full_exprs_p = 1;
15107 if (abstract)
15109 else if (DECL_ABSTRACT_P (decl))
15110 vec_safe_push (post_load_decls, decl);
15111 else
15113 bool aggr = aggregate_value_p (DECL_RESULT (decl), decl);
15114 #ifdef PCC_STATIC_STRUCT_RETURN
15115 cfun->returns_pcc_struct = aggr;
15116 #endif
15117 cfun->returns_struct = aggr;
15119 if (DECL_COMDAT (decl))
15120 // FIXME: Comdat grouping?
15121 comdat_linkage (decl);
15122 note_vague_linkage_fn (decl);
15123 cgraph_node::finalize_function (decl, true);
15127 /* Look, function.cc's interface to cfun does too much for us, we
15128 just need to restore the old value. I do not want to go
15129 redesigning that API right now. */
15130 #undef cfun
15131 cfun = old_cfun;
15132 current_function_decl = old_cfd;
15133 comparing_dependent_aliases--;
15135 dump.outdent ();
15136 dump () && dump ("Read section:%u", snum);
15138 loaded_clusters++;
15140 if (!sec.end (from ()))
15141 return false;
15143 return true;
15146 void
15147 module_state::write_namespace (bytes_out &sec, depset *dep)
15149 unsigned ns_num = dep->cluster;
15150 unsigned ns_import = 0;
15152 if (dep->is_import ())
15153 ns_import = dep->section;
15154 else if (dep->get_entity () != global_namespace)
15155 ns_num++;
15157 sec.u (ns_import);
15158 sec.u (ns_num);
15161 tree
15162 module_state::read_namespace (bytes_in &sec)
15164 unsigned ns_import = sec.u ();
15165 unsigned ns_num = sec.u ();
15166 tree ns = NULL_TREE;
15168 if (ns_import || ns_num)
15170 if (!ns_import)
15171 ns_num--;
15173 if (unsigned origin = slurp->remap_module (ns_import))
15175 module_state *from = (*modules)[origin];
15176 if (ns_num < from->entity_num)
15178 binding_slot &slot = (*entity_ary)[from->entity_lwm + ns_num];
15180 if (!slot.is_lazy ())
15181 ns = slot;
15184 else
15185 sec.set_overrun ();
15187 else
15188 ns = global_namespace;
15190 return ns;
15193 /* SPACES is a sorted vector of namespaces. Write out the namespaces
15194 to MOD_SNAME_PFX.nms section. */
15196 void
15197 module_state::write_namespaces (elf_out *to, vec<depset *> spaces,
15198 unsigned num, unsigned *crc_p)
15200 dump () && dump ("Writing namespaces");
15201 dump.indent ();
15203 bytes_out sec (to);
15204 sec.begin ();
15206 for (unsigned ix = 0; ix != num; ix++)
15208 depset *b = spaces[ix];
15209 tree ns = b->get_entity ();
15211 gcc_checking_assert (TREE_CODE (ns) == NAMESPACE_DECL);
15212 /* P1815 may have something to say about this. */
15213 gcc_checking_assert (TREE_PUBLIC (ns));
15215 unsigned flags = 0;
15216 if (TREE_PUBLIC (ns))
15217 flags |= 1;
15218 if (DECL_NAMESPACE_INLINE_P (ns))
15219 flags |= 2;
15220 if (DECL_MODULE_PURVIEW_P (ns))
15221 flags |= 4;
15222 if (DECL_MODULE_EXPORT_P (ns))
15223 flags |= 8;
15225 dump () && dump ("Writing namespace:%u %N%s%s%s%s",
15226 b->cluster, ns,
15227 flags & 1 ? ", public" : "",
15228 flags & 2 ? ", inline" : "",
15229 flags & 4 ? ", purview" : "",
15230 flags & 8 ? ", export" : "");
15231 sec.u (b->cluster);
15232 sec.u (to->name (DECL_NAME (ns)));
15233 write_namespace (sec, b->deps[0]);
15235 sec.u (flags);
15236 write_location (sec, DECL_SOURCE_LOCATION (ns));
15239 sec.end (to, to->name (MOD_SNAME_PFX ".nms"), crc_p);
15240 dump.outdent ();
15243 /* Read the namespace hierarchy from MOD_SNAME_PFX.namespace. Fill in
15244 SPACES from that data. */
15246 bool
15247 module_state::read_namespaces (unsigned num)
15249 bytes_in sec;
15251 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".nms"))
15252 return false;
15254 dump () && dump ("Reading namespaces");
15255 dump.indent ();
15257 for (unsigned ix = 0; ix != num; ix++)
15259 unsigned entity_index = sec.u ();
15260 unsigned name = sec.u ();
15262 tree parent = read_namespace (sec);
15264 /* See comment in write_namespace about why not bits. */
15265 unsigned flags = sec.u ();
15266 location_t src_loc = read_location (sec);
15268 if (entity_index >= entity_num
15269 || !parent
15270 || (flags & 0xc) == 0x8)
15271 sec.set_overrun ();
15272 if (sec.get_overrun ())
15273 break;
15275 tree id = name ? get_identifier (from ()->name (name)) : NULL_TREE;
15277 dump () && dump ("Read namespace:%u %P%s%s%s%s",
15278 entity_index, parent, id,
15279 flags & 1 ? ", public" : "",
15280 flags & 2 ? ", inline" : "",
15281 flags & 4 ? ", purview" : "",
15282 flags & 8 ? ", export" : "");
15283 bool visible_p = ((flags & 8)
15284 || ((flags & 1)
15285 && (flags & 4)
15286 && (is_partition () || is_module ())));
15287 tree inner = add_imported_namespace (parent, id, src_loc, mod,
15288 bool (flags & 2), visible_p);
15289 if (!inner)
15291 sec.set_overrun ();
15292 break;
15295 if (is_partition ())
15297 if (flags & 4)
15298 DECL_MODULE_PURVIEW_P (inner) = true;
15299 if (flags & 8)
15300 DECL_MODULE_EXPORT_P (inner) = true;
15303 /* Install the namespace. */
15304 (*entity_ary)[entity_lwm + entity_index] = inner;
15305 if (DECL_MODULE_IMPORT_P (inner))
15307 bool existed;
15308 unsigned *slot = &entity_map->get_or_insert
15309 (DECL_UID (inner), &existed);
15310 if (existed)
15311 /* If it existed, it should match. */
15312 gcc_checking_assert (inner == (*entity_ary)[*slot]);
15313 else
15314 *slot = entity_lwm + entity_index;
15317 dump.outdent ();
15318 if (!sec.end (from ()))
15319 return false;
15320 return true;
15323 /* Write the binding TABLE to MOD_SNAME_PFX.bnd */
15325 unsigned
15326 module_state::write_bindings (elf_out *to, vec<depset *> sccs, unsigned *crc_p)
15328 dump () && dump ("Writing binding table");
15329 dump.indent ();
15331 unsigned num = 0;
15332 bytes_out sec (to);
15333 sec.begin ();
15335 for (unsigned ix = 0; ix != sccs.length (); ix++)
15337 depset *b = sccs[ix];
15338 if (b->is_binding ())
15340 tree ns = b->get_entity ();
15341 dump () && dump ("Bindings %P section:%u", ns, b->get_name (),
15342 b->section);
15343 sec.u (to->name (b->get_name ()));
15344 write_namespace (sec, b->deps[0]);
15345 sec.u (b->section);
15346 num++;
15350 sec.end (to, to->name (MOD_SNAME_PFX ".bnd"), crc_p);
15351 dump.outdent ();
15353 return num;
15356 /* Read the binding table from MOD_SNAME_PFX.bind. */
15358 bool
15359 module_state::read_bindings (unsigned num, unsigned lwm, unsigned hwm)
15361 bytes_in sec;
15363 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".bnd"))
15364 return false;
15366 dump () && dump ("Reading binding table");
15367 dump.indent ();
15368 for (; !sec.get_overrun () && num--;)
15370 const char *name = from ()->name (sec.u ());
15371 tree ns = read_namespace (sec);
15372 unsigned snum = sec.u ();
15374 if (!ns || !name || (snum - lwm) >= (hwm - lwm))
15375 sec.set_overrun ();
15376 if (!sec.get_overrun ())
15378 tree id = get_identifier (name);
15379 dump () && dump ("Bindings %P section:%u", ns, id, snum);
15380 if (mod && !import_module_binding (ns, id, mod, snum))
15381 break;
15385 dump.outdent ();
15386 if (!sec.end (from ()))
15387 return false;
15388 return true;
15391 /* Write the entity table to MOD_SNAME_PFX.ent
15393 Each entry is a section number. */
15395 void
15396 module_state::write_entities (elf_out *to, vec<depset *> depsets,
15397 unsigned count, unsigned *crc_p)
15399 dump () && dump ("Writing entities");
15400 dump.indent ();
15402 bytes_out sec (to);
15403 sec.begin ();
15405 unsigned current = 0;
15406 for (unsigned ix = 0; ix < depsets.length (); ix++)
15408 depset *d = depsets[ix];
15410 switch (d->get_entity_kind ())
15412 default:
15413 break;
15415 case depset::EK_NAMESPACE:
15416 if (!d->is_import () && d->get_entity () != global_namespace)
15418 gcc_checking_assert (d->cluster == current);
15419 current++;
15420 sec.u (0);
15422 break;
15424 case depset::EK_DECL:
15425 case depset::EK_SPECIALIZATION:
15426 case depset::EK_PARTIAL:
15427 gcc_checking_assert (!d->is_unreached ()
15428 && !d->is_import ()
15429 && d->cluster == current
15430 && d->section);
15431 current++;
15432 sec.u (d->section);
15433 break;
15436 gcc_assert (count == current);
15437 sec.end (to, to->name (MOD_SNAME_PFX ".ent"), crc_p);
15438 dump.outdent ();
15441 bool
15442 module_state::read_entities (unsigned count, unsigned lwm, unsigned hwm)
15444 trees_in sec (this);
15446 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".ent"))
15447 return false;
15449 dump () && dump ("Reading entities");
15450 dump.indent ();
15452 for (binding_slot *slot = entity_ary->begin () + entity_lwm; count--; slot++)
15454 unsigned snum = sec.u ();
15455 if (snum && (snum - lwm) >= (hwm - lwm))
15456 sec.set_overrun ();
15457 if (sec.get_overrun ())
15458 break;
15460 if (snum)
15461 slot->set_lazy (snum << 2);
15464 dump.outdent ();
15465 if (!sec.end (from ()))
15466 return false;
15467 return true;
15470 /* Write the pending table to MOD_SNAME_PFX.pnd
15472 The pending table holds information about clusters that need to be
15473 loaded because they contain information about something that is not
15474 found by namespace-scope lookup.
15476 The three cases are:
15478 (a) Template (maybe-partial) specializations that we have
15479 instantiated or defined. When an importer needs to instantiate
15480 that template, they /must have/ the partial, explicit & extern
15481 specializations available. If they have the other specializations
15482 available, they'll have less work to do. Thus, when we're about to
15483 instantiate FOO, we have to be able to ask 'are there any
15484 specialization of FOO in our imports?'.
15486 (b) (Maybe-implicit) member functions definitions. A class could
15487 be defined in one header, and an inline member defined in a
15488 different header (this occurs in the STL). Similarly, like the
15489 specialization case, an implicit member function could have been
15490 'instantiated' in one module, and it'd be nice to not have to
15491 reinstantiate it in another.
15493 (c) A member classes completed elsewhere. A member class could be
15494 declared in one header and defined in another. We need to know to
15495 load the class definition before looking in it. This turns out to
15496 be a specific case of #b, so we can treat these the same. But it
15497 does highlight an issue -- there could be an intermediate import
15498 between the outermost containing namespace-scope class and the
15499 innermost being-defined member class. This is actually possible
15500 with all of these cases, so be aware -- we're not just talking of
15501 one level of import to get to the innermost namespace.
15503 This gets complicated fast, it took me multiple attempts to even
15504 get something remotely working. Partially because I focussed on
15505 optimizing what I think turns out to be a smaller problem, given
15506 the known need to do the more general case *anyway*. I document
15507 the smaller problem, because it does appear to be the natural way
15508 to do it. It's trap!
15510 **** THE TRAP
15512 Let's refer to the primary template or the containing class as the
15513 KEY. And the specialization or member as the PENDING-ENTITY. (To
15514 avoid having to say those mouthfuls all the time.)
15516 In either case, we have an entity and we need some way of mapping
15517 that to a set of entities that need to be loaded before we can
15518 proceed with whatever processing of the entity we were going to do.
15520 We need to link the key to the pending-entity in some way. Given a
15521 key, tell me the pending-entities I need to have loaded. However
15522 we tie the key to the pending-entity must not rely on the key being
15523 loaded -- that'd defeat the lazy loading scheme.
15525 As the key will be an import in we know its entity number (either
15526 because we imported it, or we're writing it out too). Thus we can
15527 generate a map of key-indices to pending-entities. The
15528 pending-entity indices will be into our span of the entity table,
15529 and thus allow them to be lazily loaded. The key index will be
15530 into another slot of the entity table. Notice that this checking
15531 could be expensive, we don't want to iterate over a bunch of
15532 pending-entity indices (across multiple imports), every time we're
15533 about do to the thing with the key. We need to quickly determine
15534 'definitely nothing needed'.
15536 That's almost good enough, except that key indices are not unique
15537 in a couple of cases :( Specifically the Global Module or a module
15538 partition can result in multiple modules assigning an entity index
15539 for the key. The decl-merging on loading will detect that so we
15540 only have one Key loaded, and in the entity hash it'll indicate the
15541 entity index of first load. Which might be different to how we
15542 know it. Notice this is restricted to GM entities or this-module
15543 entities. Foreign imports cannot have this.
15545 We can simply resolve this in the direction of how this module
15546 referred to the key to how the importer knows it. Look in the
15547 entity table slot that we nominate, maybe lazy load it, and then
15548 lookup the resultant entity in the entity hash to learn how the
15549 importer knows it.
15551 But we need to go in the other direction :( Given the key, find all
15552 the index-aliases of that key. We can partially solve that by
15553 adding an alias hash table. Whenever we load a merged decl, add or
15554 augment a mapping from the entity (or its entity-index) to the
15555 newly-discovered index. Then when we look for pending entities of
15556 a key, we also iterate over this aliases this mapping provides.
15558 But that requires the alias to be loaded. And that's not
15559 necessarily true.
15561 *** THE SIMPLER WAY
15563 The remaining fixed thing we have is the innermost namespace
15564 containing the ultimate namespace-scope container of the key and
15565 the name of that container (which might be the key itself). I.e. a
15566 namespace-decl/identifier/module tuple. Let's call this the
15567 top-key. We'll discover that the module is not important here,
15568 because of cross-module possibilities mentioned in case #c above.
15569 We can't markup namespace-binding slots. The best we can do is
15570 mark the binding vector with 'there's something here', and have
15571 another map from namespace/identifier pairs to a vector of pending
15572 entity indices.
15574 Maintain a pending-entity map. This is keyed by top-key, and
15575 maps to a vector of pending-entity indices. On the binding vector
15576 have flags saying whether the pending-name-entity map has contents.
15577 (We might want to further extend the key to be GM-vs-Partition and
15578 specialization-vs-member, but let's not get ahead of ourselves.)
15580 For every key-like entity, find the outermost namespace-scope
15581 name. Use that to lookup in the pending-entity map and then make
15582 sure the specified entities are loaded.
15584 An optimization might be to have a flag in each key-entity saying
15585 that its top key might be in the entity table. It's not clear to
15586 me how to set that flag cheaply -- cheaper than just looking.
15588 FIXME: It'd be nice to have a bit in decls to tell us whether to
15589 even try this. We can have a 'already done' flag, that we set when
15590 we've done KLASS's lazy pendings. When we import a module that
15591 registers pendings on the same top-key as KLASS we need to clear
15592 the flag. A recursive walk of the top-key clearing the bit will
15593 suffice. Plus we only need to recurse on classes that have the bit
15594 set. (That means we need to set the bit on parents of KLASS here,
15595 don't forget.) However, first: correctness, second: efficiency. */
15597 unsigned
15598 module_state::write_pendings (elf_out *to, vec<depset *> depsets,
15599 depset::hash &table, unsigned *crc_p)
15601 dump () && dump ("Writing pending-entities");
15602 dump.indent ();
15604 trees_out sec (to, this, table);
15605 sec.begin ();
15607 unsigned count = 0;
15608 tree cache_ns = NULL_TREE;
15609 tree cache_id = NULL_TREE;
15610 unsigned cache_section = ~0;
15611 for (unsigned ix = 0; ix < depsets.length (); ix++)
15613 depset *d = depsets[ix];
15615 if (d->is_binding ())
15616 continue;
15618 if (d->is_import ())
15619 continue;
15621 if (!(d->get_entity_kind () == depset::EK_SPECIALIZATION
15622 || d->get_entity_kind () == depset::EK_PARTIAL
15623 || (d->get_entity_kind () == depset::EK_DECL && d->is_member ())))
15624 continue;
15626 tree key_decl = nullptr;
15627 tree key_ns = find_pending_key (d->get_entity (), &key_decl);
15628 tree key_name = DECL_NAME (key_decl);
15630 if (IDENTIFIER_ANON_P (key_name))
15632 gcc_checking_assert (IDENTIFIER_LAMBDA_P (key_name));
15633 if (tree attached = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (key_decl)))
15634 key_name = DECL_NAME (attached);
15635 else
15637 /* There's nothing to attach it to. Must
15638 always reinstantiate. */
15639 dump ()
15640 && dump ("Unattached lambda %N[%u] section:%u",
15641 d->get_entity_kind () == depset::EK_DECL
15642 ? "Member" : "Specialization", d->get_entity (),
15643 d->cluster, d->section);
15644 continue;
15648 char const *also = "";
15649 if (d->section == cache_section
15650 && key_ns == cache_ns
15651 && key_name == cache_id)
15652 /* Same section & key as previous, no need to repeat ourselves. */
15653 also = "also ";
15654 else
15656 cache_ns = key_ns;
15657 cache_id = key_name;
15658 cache_section = d->section;
15659 gcc_checking_assert (table.find_dependency (cache_ns));
15660 sec.tree_node (cache_ns);
15661 sec.tree_node (cache_id);
15662 sec.u (d->cluster);
15663 count++;
15665 dump () && dump ("Pending %s %N entity:%u section:%u %skeyed to %P",
15666 d->get_entity_kind () == depset::EK_DECL
15667 ? "member" : "specialization", d->get_entity (),
15668 d->cluster, cache_section, also, cache_ns, cache_id);
15670 sec.end (to, to->name (MOD_SNAME_PFX ".pnd"), crc_p);
15671 dump.outdent ();
15673 return count;
15676 bool
15677 module_state::read_pendings (unsigned count)
15679 trees_in sec (this);
15681 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".pnd"))
15682 return false;
15684 dump () && dump ("Reading %u pendings", count);
15685 dump.indent ();
15687 for (unsigned ix = 0; ix != count; ix++)
15689 pending_key key;
15690 unsigned index;
15692 key.ns = sec.tree_node ();
15693 key.id = sec.tree_node ();
15694 index = sec.u ();
15696 if (!key.ns || !key.id
15697 || !(TREE_CODE (key.ns) == NAMESPACE_DECL
15698 && !DECL_NAMESPACE_ALIAS (key.ns))
15699 || !identifier_p (key.id)
15700 || index >= entity_num)
15701 sec.set_overrun ();
15703 if (sec.get_overrun ())
15704 break;
15706 dump () && dump ("Pending:%u keyed to %P", index, key.ns, key.id);
15708 index += entity_lwm;
15709 auto &vec = pending_table->get_or_insert (key);
15710 vec.safe_push (index);
15713 dump.outdent ();
15714 if (!sec.end (from ()))
15715 return false;
15716 return true;
15719 /* Read & write locations. */
15720 enum loc_kind {
15721 LK_ORDINARY,
15722 LK_MACRO,
15723 LK_IMPORT_ORDINARY,
15724 LK_IMPORT_MACRO,
15725 LK_ADHOC,
15726 LK_RESERVED,
15729 static const module_state *
15730 module_for_ordinary_loc (location_t loc)
15732 unsigned pos = 0;
15733 unsigned len = ool->length () - pos;
15735 while (len)
15737 unsigned half = len / 2;
15738 module_state *probe = (*ool)[pos + half];
15739 if (loc < probe->ordinary_locs.first)
15740 len = half;
15741 else if (loc < probe->ordinary_locs.first + probe->ordinary_locs.second)
15742 return probe;
15743 else
15745 pos += half + 1;
15746 len = len - (half + 1);
15750 return nullptr;
15753 static const module_state *
15754 module_for_macro_loc (location_t loc)
15756 unsigned pos = 1;
15757 unsigned len = modules->length () - pos;
15759 while (len)
15761 unsigned half = len / 2;
15762 module_state *probe = (*modules)[pos + half];
15763 if (loc < probe->macro_locs.first)
15765 pos += half + 1;
15766 len = len - (half + 1);
15768 else if (loc >= probe->macro_locs.first + probe->macro_locs.second)
15769 len = half;
15770 else
15771 return probe;
15774 return NULL;
15777 location_t
15778 module_state::imported_from () const
15780 location_t from = loc;
15781 line_map_ordinary const *fmap
15782 = linemap_check_ordinary (linemap_lookup (line_table, from));
15784 if (MAP_MODULE_P (fmap))
15785 from = linemap_included_from (fmap);
15787 return from;
15790 /* Note that LOC will need writing. This allows us to prune locations
15791 that are not needed. */
15793 bool
15794 module_state::note_location (location_t loc)
15796 bool added = false;
15797 if (!macro_loc_table && !ord_loc_table)
15799 else if (loc < RESERVED_LOCATION_COUNT)
15801 else if (IS_ADHOC_LOC (loc))
15803 location_t locus = get_location_from_adhoc_loc (line_table, loc);
15804 note_location (locus);
15805 source_range range = get_range_from_loc (line_table, loc);
15806 if (range.m_start != locus)
15807 note_location (range.m_start);
15808 note_location (range.m_finish);
15810 else if (loc >= LINEMAPS_MACRO_LOWEST_LOCATION (line_table))
15812 if (spans.macro (loc))
15814 const line_map *map = linemap_lookup (line_table, loc);
15815 const line_map_macro *mac_map = linemap_check_macro (map);
15816 hashval_t hv = macro_loc_traits::hash (mac_map);
15817 macro_loc_info *slot
15818 = macro_loc_table->find_slot_with_hash (mac_map, hv, INSERT);
15819 if (!slot->src)
15821 slot->src = mac_map;
15822 slot->remap = 0;
15823 // Expansion locations could themselves be from a
15824 // macro, we need to note them all.
15825 note_location (mac_map->m_expansion);
15826 gcc_checking_assert (mac_map->n_tokens);
15827 location_t tloc = UNKNOWN_LOCATION;
15828 for (unsigned ix = mac_map->n_tokens * 2; ix--;)
15829 if (mac_map->macro_locations[ix] != tloc)
15831 tloc = mac_map->macro_locations[ix];
15832 note_location (tloc);
15834 added = true;
15838 else if (IS_ORDINARY_LOC (loc))
15840 if (spans.ordinary (loc))
15842 const line_map *map = linemap_lookup (line_table, loc);
15843 const line_map_ordinary *ord_map = linemap_check_ordinary (map);
15844 ord_loc_info lkup;
15845 lkup.src = ord_map;
15846 lkup.span = 1 << ord_map->m_column_and_range_bits;
15847 lkup.offset = (loc - MAP_START_LOCATION (ord_map)) & ~(lkup.span - 1);
15848 lkup.remap = 0;
15849 ord_loc_info *slot = (ord_loc_table->find_slot_with_hash
15850 (lkup, ord_loc_traits::hash (lkup), INSERT));
15851 if (!slot->src)
15853 *slot = lkup;
15854 added = true;
15858 else
15859 gcc_unreachable ();
15860 return added;
15863 /* If we're not streaming, record that we need location LOC.
15864 Otherwise stream it. */
15866 void
15867 module_state::write_location (bytes_out &sec, location_t loc)
15869 if (!sec.streaming_p ())
15871 note_location (loc);
15872 return;
15875 if (loc < RESERVED_LOCATION_COUNT)
15877 dump (dumper::LOCATION) && dump ("Reserved location %u", unsigned (loc));
15878 sec.u (LK_RESERVED + loc);
15880 else if (IS_ADHOC_LOC (loc))
15882 dump (dumper::LOCATION) && dump ("Adhoc location");
15883 sec.u (LK_ADHOC);
15884 location_t locus = get_location_from_adhoc_loc (line_table, loc);
15885 write_location (sec, locus);
15886 source_range range = get_range_from_loc (line_table, loc);
15887 if (range.m_start == locus)
15888 /* Compress. */
15889 range.m_start = UNKNOWN_LOCATION;
15890 write_location (sec, range.m_start);
15891 write_location (sec, range.m_finish);
15892 unsigned discriminator = get_discriminator_from_adhoc_loc (line_table, loc);
15893 sec.u (discriminator);
15895 else if (loc >= LINEMAPS_MACRO_LOWEST_LOCATION (line_table))
15897 const macro_loc_info *info = nullptr;
15898 unsigned offset = 0;
15899 if (unsigned hwm = macro_loc_remap->length ())
15901 info = macro_loc_remap->begin ();
15902 while (hwm != 1)
15904 unsigned mid = hwm / 2;
15905 if (MAP_START_LOCATION (info[mid].src) <= loc)
15907 info += mid;
15908 hwm -= mid;
15910 else
15911 hwm = mid;
15913 offset = loc - MAP_START_LOCATION (info->src);
15914 if (offset > info->src->n_tokens)
15915 info = nullptr;
15918 gcc_checking_assert (bool (info) == bool (spans.macro (loc)));
15920 if (info)
15922 offset += info->remap;
15923 sec.u (LK_MACRO);
15924 sec.u (offset);
15925 dump (dumper::LOCATION)
15926 && dump ("Macro location %u output %u", loc, offset);
15928 else if (const module_state *import = module_for_macro_loc (loc))
15930 unsigned off = loc - import->macro_locs.first;
15931 sec.u (LK_IMPORT_MACRO);
15932 sec.u (import->remap);
15933 sec.u (off);
15934 dump (dumper::LOCATION)
15935 && dump ("Imported macro location %u output %u:%u",
15936 loc, import->remap, off);
15938 else
15939 gcc_unreachable ();
15941 else if (IS_ORDINARY_LOC (loc))
15943 const ord_loc_info *info = nullptr;
15944 unsigned offset = 0;
15945 if (unsigned hwm = ord_loc_remap->length ())
15947 info = ord_loc_remap->begin ();
15948 while (hwm != 1)
15950 unsigned mid = hwm / 2;
15951 if (MAP_START_LOCATION (info[mid].src) + info[mid].offset <= loc)
15953 info += mid;
15954 hwm -= mid;
15956 else
15957 hwm = mid;
15959 offset = loc - MAP_START_LOCATION (info->src) - info->offset;
15960 if (offset > info->span)
15961 info = nullptr;
15964 gcc_checking_assert (bool (info) == bool (spans.ordinary (loc)));
15966 if (info)
15968 offset += info->remap;
15969 sec.u (LK_ORDINARY);
15970 sec.u (offset);
15972 dump (dumper::LOCATION)
15973 && dump ("Ordinary location %u output %u", loc, offset);
15975 else if (const module_state *import = module_for_ordinary_loc (loc))
15977 unsigned off = loc - import->ordinary_locs.first;
15978 sec.u (LK_IMPORT_ORDINARY);
15979 sec.u (import->remap);
15980 sec.u (off);
15981 dump (dumper::LOCATION)
15982 && dump ("Imported ordinary location %u output %u:%u",
15983 import->remap, import->remap, off);
15985 else
15986 gcc_unreachable ();
15988 else
15989 gcc_unreachable ();
15992 location_t
15993 module_state::read_location (bytes_in &sec) const
15995 location_t locus = UNKNOWN_LOCATION;
15996 unsigned kind = sec.u ();
15997 switch (kind)
15999 default:
16001 if (kind < LK_RESERVED + RESERVED_LOCATION_COUNT)
16002 locus = location_t (kind - LK_RESERVED);
16003 else
16004 sec.set_overrun ();
16005 dump (dumper::LOCATION)
16006 && dump ("Reserved location %u", unsigned (locus));
16008 break;
16010 case LK_ADHOC:
16012 dump (dumper::LOCATION) && dump ("Adhoc location");
16013 locus = read_location (sec);
16014 source_range range;
16015 range.m_start = read_location (sec);
16016 if (range.m_start == UNKNOWN_LOCATION)
16017 range.m_start = locus;
16018 range.m_finish = read_location (sec);
16019 unsigned discriminator = sec.u ();
16020 if (locus != loc && range.m_start != loc && range.m_finish != loc)
16021 locus = line_table->get_or_create_combined_loc (locus, range,
16022 nullptr, discriminator);
16024 break;
16026 case LK_MACRO:
16028 unsigned off = sec.u ();
16030 if (macro_locs.second)
16032 if (off < macro_locs.second)
16033 locus = off + macro_locs.first;
16034 else
16035 sec.set_overrun ();
16037 else
16038 locus = loc;
16039 dump (dumper::LOCATION)
16040 && dump ("Macro %u becoming %u", off, locus);
16042 break;
16044 case LK_ORDINARY:
16046 unsigned off = sec.u ();
16047 if (ordinary_locs.second)
16049 if (off < ordinary_locs.second)
16050 locus = off + ordinary_locs.first;
16051 else
16052 sec.set_overrun ();
16054 else
16055 locus = loc;
16057 dump (dumper::LOCATION)
16058 && dump ("Ordinary location %u becoming %u", off, locus);
16060 break;
16062 case LK_IMPORT_MACRO:
16063 case LK_IMPORT_ORDINARY:
16065 unsigned mod = sec.u ();
16066 unsigned off = sec.u ();
16067 const module_state *import = NULL;
16069 if (!mod && !slurp->remap)
16070 /* This is an early read of a partition location during the
16071 read of our ordinary location map. */
16072 import = this;
16073 else
16075 mod = slurp->remap_module (mod);
16076 if (!mod)
16077 sec.set_overrun ();
16078 else
16079 import = (*modules)[mod];
16082 if (import)
16084 if (kind == LK_IMPORT_MACRO)
16086 if (!import->macro_locs.second)
16087 locus = import->loc;
16088 else if (off < import->macro_locs.second)
16089 locus = off + import->macro_locs.first;
16090 else
16091 sec.set_overrun ();
16093 else
16095 if (!import->ordinary_locs.second)
16096 locus = import->loc;
16097 else if (off < import->ordinary_locs.second)
16098 locus = import->ordinary_locs.first + off;
16099 else
16100 sec.set_overrun ();
16104 break;
16107 return locus;
16110 /* Allocate hash tables to record needed locations. */
16112 void
16113 module_state::write_init_maps ()
16115 macro_loc_table = new hash_table<macro_loc_traits> (EXPERIMENT (1, 400));
16116 ord_loc_table = new hash_table<ord_loc_traits> (EXPERIMENT (1, 400));
16119 /* Prepare the span adjustments. We prune unneeded locations -- at
16120 this point every needed location must have been seen by
16121 note_location. */
16123 range_t
16124 module_state::write_prepare_maps (module_state_config *cfg, bool has_partitions)
16126 dump () && dump ("Preparing locations");
16127 dump.indent ();
16129 dump () && dump ("Reserved locations [%u,%u) macro [%u,%u)",
16130 spans[loc_spans::SPAN_RESERVED].ordinary.first,
16131 spans[loc_spans::SPAN_RESERVED].ordinary.second,
16132 spans[loc_spans::SPAN_RESERVED].macro.first,
16133 spans[loc_spans::SPAN_RESERVED].macro.second);
16135 range_t info {0, 0};
16137 // Sort the noted lines.
16138 vec_alloc (ord_loc_remap, ord_loc_table->size ());
16139 for (auto iter = ord_loc_table->begin (), end = ord_loc_table->end ();
16140 iter != end; ++iter)
16141 ord_loc_remap->quick_push (*iter);
16142 ord_loc_remap->qsort (&ord_loc_info::compare);
16144 // Note included-from maps.
16145 bool added = false;
16146 const line_map_ordinary *current = nullptr;
16147 for (auto iter = ord_loc_remap->begin (), end = ord_loc_remap->end ();
16148 iter != end; ++iter)
16149 if (iter->src != current)
16151 current = iter->src;
16152 for (auto probe = current;
16153 auto from = linemap_included_from (probe);
16154 probe = linemap_check_ordinary (linemap_lookup (line_table, from)))
16156 if (has_partitions)
16158 // Partition locations need to elide their module map
16159 // entry.
16160 probe
16161 = linemap_check_ordinary (linemap_lookup (line_table, from));
16162 if (MAP_MODULE_P (probe))
16163 from = linemap_included_from (probe);
16166 if (!note_location (from))
16167 break;
16168 added = true;
16171 if (added)
16173 // Reconstruct the line array as we added items to the hash table.
16174 vec_free (ord_loc_remap);
16175 vec_alloc (ord_loc_remap, ord_loc_table->size ());
16176 for (auto iter = ord_loc_table->begin (), end = ord_loc_table->end ();
16177 iter != end; ++iter)
16178 ord_loc_remap->quick_push (*iter);
16179 ord_loc_remap->qsort (&ord_loc_info::compare);
16181 delete ord_loc_table;
16182 ord_loc_table = nullptr;
16184 // Merge (sufficiently) adjacent spans, and calculate remapping.
16185 constexpr unsigned adjacency = 2; // Allow 2 missing lines.
16186 auto begin = ord_loc_remap->begin (), end = ord_loc_remap->end ();
16187 auto dst = begin;
16188 unsigned offset = 0, range_bits = 0;
16189 ord_loc_info *base = nullptr;
16190 for (auto iter = begin; iter != end; ++iter)
16192 if (base && iter->src == base->src)
16194 if (base->offset + base->span +
16195 ((adjacency << base->src->m_column_and_range_bits)
16196 // If there are few c&r bits, allow further separation.
16197 | (adjacency << 4))
16198 >= iter->offset)
16200 // Merge.
16201 offset -= base->span;
16202 base->span = iter->offset + iter->span - base->offset;
16203 offset += base->span;
16204 continue;
16207 else if (range_bits < iter->src->m_range_bits)
16208 range_bits = iter->src->m_range_bits;
16210 offset += ((1u << iter->src->m_range_bits) - 1);
16211 offset &= ~((1u << iter->src->m_range_bits) - 1);
16212 iter->remap = offset;
16213 offset += iter->span;
16214 base = dst;
16215 *dst++ = *iter;
16217 ord_loc_remap->truncate (dst - begin);
16219 info.first = ord_loc_remap->length ();
16220 cfg->ordinary_locs = offset;
16221 cfg->loc_range_bits = range_bits;
16222 dump () && dump ("Ordinary maps:%u locs:%u range_bits:%u",
16223 info.first, cfg->ordinary_locs,
16224 cfg->loc_range_bits);
16226 // Remap the macro locations.
16227 vec_alloc (macro_loc_remap, macro_loc_table->size ());
16228 for (auto iter = macro_loc_table->begin (), end = macro_loc_table->end ();
16229 iter != end; ++iter)
16230 macro_loc_remap->quick_push (*iter);
16231 delete macro_loc_table;
16232 macro_loc_table = nullptr;
16234 macro_loc_remap->qsort (&macro_loc_info::compare);
16235 offset = 0;
16236 for (auto iter = macro_loc_remap->begin (), end = macro_loc_remap->end ();
16237 iter != end; ++iter)
16239 auto mac = iter->src;
16240 iter->remap = offset;
16241 offset += mac->n_tokens;
16243 info.second = macro_loc_remap->length ();
16244 cfg->macro_locs = offset;
16246 dump () && dump ("Macro maps:%u locs:%u", info.second, cfg->macro_locs);
16248 dump.outdent ();
16250 // If we have no ordinary locs, we must also have no macro locs.
16251 gcc_checking_assert (cfg->ordinary_locs || !cfg->macro_locs);
16253 return info;
16256 bool
16257 module_state::read_prepare_maps (const module_state_config *cfg)
16259 location_t ordinary = line_table->highest_location + 1;
16260 ordinary += cfg->ordinary_locs;
16262 location_t macro = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
16263 macro -= cfg->macro_locs;
16265 if (ordinary < LINE_MAP_MAX_LOCATION_WITH_COLS
16266 && macro >= LINE_MAP_MAX_LOCATION)
16267 /* OK, we have enough locations. */
16268 return true;
16270 ordinary_locs.first = ordinary_locs.second = 0;
16271 macro_locs.first = macro_locs.second = 0;
16273 static bool informed = false;
16274 if (!informed)
16276 /* Just give the notice once. */
16277 informed = true;
16278 inform (loc, "unable to represent further imported source locations");
16281 return false;
16284 /* Write & read the location maps. Not called if there are no
16285 locations. */
16287 void
16288 module_state::write_ordinary_maps (elf_out *to, range_t &info,
16289 bool has_partitions, unsigned *crc_p)
16291 dump () && dump ("Writing ordinary location maps");
16292 dump.indent ();
16294 vec<const char *> filenames;
16295 filenames.create (20);
16297 /* Determine the unique filenames. */
16298 const line_map_ordinary *current = nullptr;
16299 for (auto iter = ord_loc_remap->begin (), end = ord_loc_remap->end ();
16300 iter != end; ++iter)
16301 if (iter->src != current)
16303 current = iter->src;
16304 const char *fname = ORDINARY_MAP_FILE_NAME (iter->src);
16306 /* We should never find a module linemap in an interval. */
16307 gcc_checking_assert (!MAP_MODULE_P (iter->src));
16309 /* We expect very few filenames, so just an array.
16310 (Not true when headers are still in play :() */
16311 for (unsigned jx = filenames.length (); jx--;)
16313 const char *name = filenames[jx];
16314 if (0 == strcmp (name, fname))
16316 /* Reset the linemap's name, because for things like
16317 preprocessed input we could have multiple instances
16318 of the same name, and we'd rather not percolate
16319 that. */
16320 const_cast<line_map_ordinary *> (iter->src)->to_file = name;
16321 fname = NULL;
16322 break;
16325 if (fname)
16326 filenames.safe_push (fname);
16329 bytes_out sec (to);
16330 sec.begin ();
16332 /* Write the filenames. */
16333 unsigned len = filenames.length ();
16334 sec.u (len);
16335 dump () && dump ("%u source file names", len);
16336 for (unsigned ix = 0; ix != len; ix++)
16338 const char *fname = filenames[ix];
16339 dump (dumper::LOCATION) && dump ("Source file[%u]=%s", ix, fname);
16340 sec.str (fname);
16343 sec.u (info.first); /* Num maps. */
16344 const ord_loc_info *base = nullptr;
16345 for (auto iter = ord_loc_remap->begin (), end = ord_loc_remap->end ();
16346 iter != end; ++iter)
16348 dump (dumper::LOCATION)
16349 && dump ("Span:%u ordinary [%u+%u,+%u)->[%u,+%u)",
16350 iter - ord_loc_remap->begin (),
16351 MAP_START_LOCATION (iter->src), iter->offset, iter->span,
16352 iter->remap, iter->span);
16354 if (!base || iter->src != base->src)
16355 base = iter;
16356 sec.u (iter->offset - base->offset);
16357 if (base == iter)
16359 sec.u (iter->src->sysp);
16360 sec.u (iter->src->m_range_bits);
16361 sec.u (iter->src->m_column_and_range_bits - iter->src->m_range_bits);
16363 const char *fname = ORDINARY_MAP_FILE_NAME (iter->src);
16364 for (unsigned ix = 0; ix != filenames.length (); ix++)
16365 if (filenames[ix] == fname)
16367 sec.u (ix);
16368 break;
16370 unsigned line = ORDINARY_MAP_STARTING_LINE_NUMBER (iter->src);
16371 line += iter->offset >> iter->src->m_column_and_range_bits;
16372 sec.u (line);
16374 sec.u (iter->remap);
16375 if (base == iter)
16377 /* Write the included from location, which means reading it
16378 while reading in the ordinary maps. So we'd better not
16379 be getting ahead of ourselves. */
16380 location_t from = linemap_included_from (iter->src);
16381 gcc_checking_assert (from < MAP_START_LOCATION (iter->src));
16382 if (from != UNKNOWN_LOCATION && has_partitions)
16384 /* A partition's span will have a from pointing at a
16385 MODULE_INC. Find that map's from. */
16386 line_map_ordinary const *fmap
16387 = linemap_check_ordinary (linemap_lookup (line_table, from));
16388 if (MAP_MODULE_P (fmap))
16389 from = linemap_included_from (fmap);
16391 write_location (sec, from);
16395 filenames.release ();
16397 sec.end (to, to->name (MOD_SNAME_PFX ".olm"), crc_p);
16398 dump.outdent ();
16401 void
16402 module_state::write_macro_maps (elf_out *to, range_t &info, unsigned *crc_p)
16404 dump () && dump ("Writing macro location maps");
16405 dump.indent ();
16407 bytes_out sec (to);
16408 sec.begin ();
16410 dump () && dump ("Macro maps:%u", info.second);
16411 sec.u (info.second);
16413 unsigned macro_num = 0;
16414 for (auto iter = macro_loc_remap->end (), begin = macro_loc_remap->begin ();
16415 iter-- != begin;)
16417 auto mac = iter->src;
16418 sec.u (iter->remap);
16419 sec.u (mac->n_tokens);
16420 sec.cpp_node (mac->macro);
16421 write_location (sec, mac->m_expansion);
16422 const location_t *locs = mac->macro_locations;
16423 /* There are lots of identical runs. */
16424 location_t prev = UNKNOWN_LOCATION;
16425 unsigned count = 0;
16426 unsigned runs = 0;
16427 for (unsigned jx = mac->n_tokens * 2; jx--;)
16429 location_t tok_loc = locs[jx];
16430 if (tok_loc == prev)
16432 count++;
16433 continue;
16435 runs++;
16436 sec.u (count);
16437 count = 1;
16438 prev = tok_loc;
16439 write_location (sec, tok_loc);
16441 sec.u (count);
16442 dump (dumper::LOCATION)
16443 && dump ("Macro:%u %I %u/%u*2 locations [%u,%u)->%u",
16444 macro_num, identifier (mac->macro),
16445 runs, mac->n_tokens,
16446 MAP_START_LOCATION (mac),
16447 MAP_START_LOCATION (mac) + mac->n_tokens,
16448 iter->remap);
16449 macro_num++;
16451 gcc_assert (macro_num == info.second);
16453 sec.end (to, to->name (MOD_SNAME_PFX ".mlm"), crc_p);
16454 dump.outdent ();
16457 bool
16458 module_state::read_ordinary_maps (unsigned num_ord_locs, unsigned range_bits)
16460 bytes_in sec;
16462 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".olm"))
16463 return false;
16464 dump () && dump ("Reading ordinary location maps");
16465 dump.indent ();
16467 /* Read the filename table. */
16468 unsigned len = sec.u ();
16469 dump () && dump ("%u source file names", len);
16470 vec<const char *> filenames;
16471 filenames.create (len);
16472 for (unsigned ix = 0; ix != len; ix++)
16474 size_t l;
16475 const char *buf = sec.str (&l);
16476 char *fname = XNEWVEC (char, l + 1);
16477 memcpy (fname, buf, l + 1);
16478 dump (dumper::LOCATION) && dump ("Source file[%u]=%s", ix, fname);
16479 /* We leak these names into the line-map table. But it
16480 doesn't own them. */
16481 filenames.quick_push (fname);
16484 unsigned num_ordinary = sec.u ();
16485 dump () && dump ("Ordinary maps:%u, range_bits:%u", num_ordinary, range_bits);
16487 location_t offset = line_table->highest_location + 1;
16488 offset += ((1u << range_bits) - 1);
16489 offset &= ~((1u << range_bits) - 1);
16490 ordinary_locs.first = offset;
16492 bool propagated = spans.maybe_propagate (this, offset);
16493 line_map_ordinary *maps = static_cast<line_map_ordinary *>
16494 (line_map_new_raw (line_table, false, num_ordinary));
16496 const line_map_ordinary *base = nullptr;
16497 for (unsigned ix = 0; ix != num_ordinary && !sec.get_overrun (); ix++)
16499 line_map_ordinary *map = &maps[ix];
16501 unsigned offset = sec.u ();
16502 if (!offset)
16504 map->reason = LC_RENAME;
16505 map->sysp = sec.u ();
16506 map->m_range_bits = sec.u ();
16507 map->m_column_and_range_bits = sec.u () + map->m_range_bits;
16508 unsigned fnum = sec.u ();
16509 map->to_file = (fnum < filenames.length () ? filenames[fnum] : "");
16510 map->to_line = sec.u ();
16511 base = map;
16513 else
16515 *map = *base;
16516 map->to_line += offset >> map->m_column_and_range_bits;
16518 unsigned remap = sec.u ();
16519 map->start_location = remap + ordinary_locs.first;
16520 if (base == map)
16522 /* Root the outermost map at our location. */
16523 ordinary_locs.second = remap;
16524 location_t from = read_location (sec);
16525 map->included_from = from != UNKNOWN_LOCATION ? from : loc;
16529 ordinary_locs.second = num_ord_locs;
16530 /* highest_location is the one handed out, not the next one to
16531 hand out. */
16532 line_table->highest_location = ordinary_locs.first + ordinary_locs.second - 1;
16534 if (line_table->highest_location >= LINE_MAP_MAX_LOCATION_WITH_COLS)
16535 /* We shouldn't run out of locations, as we checked before
16536 starting. */
16537 sec.set_overrun ();
16538 dump () && dump ("Ordinary location [%u,+%u)",
16539 ordinary_locs.first, ordinary_locs.second);
16541 if (propagated)
16542 spans.close ();
16544 filenames.release ();
16546 dump.outdent ();
16547 if (!sec.end (from ()))
16548 return false;
16550 return true;
16553 bool
16554 module_state::read_macro_maps (unsigned num_macro_locs)
16556 bytes_in sec;
16558 if (!sec.begin (loc, from (), MOD_SNAME_PFX ".mlm"))
16559 return false;
16560 dump () && dump ("Reading macro location maps");
16561 dump.indent ();
16563 unsigned num_macros = sec.u ();
16564 dump () && dump ("Macro maps:%u locs:%u", num_macros, num_macro_locs);
16566 bool propagated = spans.maybe_propagate (this,
16567 line_table->highest_location + 1);
16569 location_t offset = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
16570 macro_locs.second = num_macro_locs;
16571 macro_locs.first = offset - num_macro_locs;
16573 dump () && dump ("Macro loc delta %d", offset);
16574 dump () && dump ("Macro locations [%u,%u)",
16575 macro_locs.first, macro_locs.second);
16577 for (unsigned ix = 0; ix != num_macros && !sec.get_overrun (); ix++)
16579 unsigned offset = sec.u ();
16580 unsigned n_tokens = sec.u ();
16581 cpp_hashnode *node = sec.cpp_node ();
16582 location_t exp_loc = read_location (sec);
16584 const line_map_macro *macro
16585 = linemap_enter_macro (line_table, node, exp_loc, n_tokens);
16586 if (!macro)
16587 /* We shouldn't run out of locations, as we checked that we
16588 had enough before starting. */
16589 break;
16590 gcc_checking_assert (MAP_START_LOCATION (macro)
16591 == offset + macro_locs.first);
16593 location_t *locs = macro->macro_locations;
16594 location_t tok_loc = UNKNOWN_LOCATION;
16595 unsigned count = sec.u ();
16596 unsigned runs = 0;
16597 for (unsigned jx = macro->n_tokens * 2; jx-- && !sec.get_overrun ();)
16599 while (!count-- && !sec.get_overrun ())
16601 runs++;
16602 tok_loc = read_location (sec);
16603 count = sec.u ();
16605 locs[jx] = tok_loc;
16607 if (count)
16608 sec.set_overrun ();
16609 dump (dumper::LOCATION)
16610 && dump ("Macro:%u %I %u/%u*2 locations [%u,%u)",
16611 ix, identifier (node), runs, n_tokens,
16612 MAP_START_LOCATION (macro),
16613 MAP_START_LOCATION (macro) + n_tokens);
16616 dump () && dump ("Macro location lwm:%u", macro_locs.first);
16617 if (propagated)
16618 spans.close ();
16620 dump.outdent ();
16621 if (!sec.end (from ()))
16622 return false;
16624 return true;
16627 /* Serialize the definition of MACRO. */
16629 void
16630 module_state::write_define (bytes_out &sec, const cpp_macro *macro)
16632 sec.u (macro->count);
16634 sec.b (macro->fun_like);
16635 sec.b (macro->variadic);
16636 sec.b (macro->syshdr);
16637 sec.bflush ();
16639 write_location (sec, macro->line);
16640 if (macro->fun_like)
16642 sec.u (macro->paramc);
16643 const cpp_hashnode *const *parms = macro->parm.params;
16644 for (unsigned ix = 0; ix != macro->paramc; ix++)
16645 sec.cpp_node (parms[ix]);
16648 unsigned len = 0;
16649 for (unsigned ix = 0; ix != macro->count; ix++)
16651 const cpp_token *token = &macro->exp.tokens[ix];
16652 write_location (sec, token->src_loc);
16653 sec.u (token->type);
16654 sec.u (token->flags);
16655 switch (cpp_token_val_index (token))
16657 default:
16658 gcc_unreachable ();
16660 case CPP_TOKEN_FLD_ARG_NO:
16661 /* An argument reference. */
16662 sec.u (token->val.macro_arg.arg_no);
16663 sec.cpp_node (token->val.macro_arg.spelling);
16664 break;
16666 case CPP_TOKEN_FLD_NODE:
16667 /* An identifier. */
16668 sec.cpp_node (token->val.node.node);
16669 if (token->val.node.spelling == token->val.node.node)
16670 /* The spelling will usually be the same. so optimize
16671 that. */
16672 sec.str (NULL, 0);
16673 else
16674 sec.cpp_node (token->val.node.spelling);
16675 break;
16677 case CPP_TOKEN_FLD_NONE:
16678 break;
16680 case CPP_TOKEN_FLD_STR:
16681 /* A string, number or comment. Not always NUL terminated,
16682 we stream out in a single contatenation with embedded
16683 NULs as that's a safe default. */
16684 len += token->val.str.len + 1;
16685 sec.u (token->val.str.len);
16686 break;
16688 case CPP_TOKEN_FLD_SOURCE:
16689 case CPP_TOKEN_FLD_TOKEN_NO:
16690 case CPP_TOKEN_FLD_PRAGMA:
16691 /* These do not occur inside a macro itself. */
16692 gcc_unreachable ();
16696 if (len)
16698 char *ptr = reinterpret_cast<char *> (sec.buf (len));
16699 len = 0;
16700 for (unsigned ix = 0; ix != macro->count; ix++)
16702 const cpp_token *token = &macro->exp.tokens[ix];
16703 if (cpp_token_val_index (token) == CPP_TOKEN_FLD_STR)
16705 memcpy (ptr + len, token->val.str.text,
16706 token->val.str.len);
16707 len += token->val.str.len;
16708 ptr[len++] = 0;
16714 /* Read a macro definition. */
16716 cpp_macro *
16717 module_state::read_define (bytes_in &sec, cpp_reader *reader) const
16719 unsigned count = sec.u ();
16720 /* We rely on knowing cpp_reader's hash table is ident_hash, and
16721 its subobject allocator is stringpool_ggc_alloc and that is just
16722 a wrapper for ggc_alloc_atomic. */
16723 cpp_macro *macro
16724 = (cpp_macro *)ggc_alloc_atomic (sizeof (cpp_macro)
16725 + sizeof (cpp_token) * (count - !!count));
16726 memset (macro, 0, sizeof (cpp_macro) + sizeof (cpp_token) * (count - !!count));
16728 macro->count = count;
16729 macro->kind = cmk_macro;
16730 macro->imported_p = true;
16732 macro->fun_like = sec.b ();
16733 macro->variadic = sec.b ();
16734 macro->syshdr = sec.b ();
16735 sec.bflush ();
16737 macro->line = read_location (sec);
16739 if (macro->fun_like)
16741 unsigned paramc = sec.u ();
16742 cpp_hashnode **params
16743 = (cpp_hashnode **)ggc_alloc_atomic (sizeof (cpp_hashnode *) * paramc);
16744 macro->paramc = paramc;
16745 macro->parm.params = params;
16746 for (unsigned ix = 0; ix != paramc; ix++)
16747 params[ix] = sec.cpp_node ();
16750 unsigned len = 0;
16751 for (unsigned ix = 0; ix != count && !sec.get_overrun (); ix++)
16753 cpp_token *token = &macro->exp.tokens[ix];
16754 token->src_loc = read_location (sec);
16755 token->type = cpp_ttype (sec.u ());
16756 token->flags = sec.u ();
16757 switch (cpp_token_val_index (token))
16759 default:
16760 sec.set_overrun ();
16761 break;
16763 case CPP_TOKEN_FLD_ARG_NO:
16764 /* An argument reference. */
16766 unsigned arg_no = sec.u ();
16767 if (arg_no - 1 >= macro->paramc)
16768 sec.set_overrun ();
16769 token->val.macro_arg.arg_no = arg_no;
16770 token->val.macro_arg.spelling = sec.cpp_node ();
16772 break;
16774 case CPP_TOKEN_FLD_NODE:
16775 /* An identifier. */
16776 token->val.node.node = sec.cpp_node ();
16777 token->val.node.spelling = sec.cpp_node ();
16778 if (!token->val.node.spelling)
16779 token->val.node.spelling = token->val.node.node;
16780 break;
16782 case CPP_TOKEN_FLD_NONE:
16783 break;
16785 case CPP_TOKEN_FLD_STR:
16786 /* A string, number or comment. */
16787 token->val.str.len = sec.u ();
16788 len += token->val.str.len + 1;
16789 break;
16793 if (len)
16794 if (const char *ptr = reinterpret_cast<const char *> (sec.buf (len)))
16796 /* There should be a final NUL. */
16797 if (ptr[len-1])
16798 sec.set_overrun ();
16799 /* cpp_alloc_token_string will add a final NUL. */
16800 const unsigned char *buf
16801 = cpp_alloc_token_string (reader, (const unsigned char *)ptr, len - 1);
16802 len = 0;
16803 for (unsigned ix = 0; ix != count && !sec.get_overrun (); ix++)
16805 cpp_token *token = &macro->exp.tokens[ix];
16806 if (cpp_token_val_index (token) == CPP_TOKEN_FLD_STR)
16808 token->val.str.text = buf + len;
16809 len += token->val.str.len;
16810 if (buf[len++])
16811 sec.set_overrun ();
16816 if (sec.get_overrun ())
16817 return NULL;
16818 return macro;
16821 /* Exported macro data. */
16822 struct GTY(()) macro_export {
16823 cpp_macro *def;
16824 location_t undef_loc;
16826 macro_export ()
16827 :def (NULL), undef_loc (UNKNOWN_LOCATION)
16832 /* Imported macro data. */
16833 class macro_import {
16834 public:
16835 struct slot {
16836 #if defined (WORDS_BIGENDIAN) && SIZEOF_VOID_P == 8
16837 int offset;
16838 #endif
16839 /* We need to ensure we don't use the LSB for representation, as
16840 that's the union discriminator below. */
16841 unsigned bits;
16843 #if !(defined (WORDS_BIGENDIAN) && SIZEOF_VOID_P == 8)
16844 int offset;
16845 #endif
16847 public:
16848 enum Layout {
16849 L_DEF = 1,
16850 L_UNDEF = 2,
16851 L_BOTH = 3,
16852 L_MODULE_SHIFT = 2
16855 public:
16856 /* Not a regular ctor, because we put it in a union, and that's
16857 not allowed in C++ 98. */
16858 static slot ctor (unsigned module, unsigned defness)
16860 gcc_checking_assert (defness);
16861 slot s;
16862 s.bits = defness | (module << L_MODULE_SHIFT);
16863 s.offset = -1;
16864 return s;
16867 public:
16868 unsigned get_defness () const
16870 return bits & L_BOTH;
16872 unsigned get_module () const
16874 return bits >> L_MODULE_SHIFT;
16876 void become_undef ()
16878 bits &= ~unsigned (L_DEF);
16879 bits |= unsigned (L_UNDEF);
16883 private:
16884 typedef vec<slot, va_heap, vl_embed> ary_t;
16885 union either {
16886 /* Discriminated by bits 0|1 != 0. The expected case is that
16887 there will be exactly one slot per macro, hence the effort of
16888 packing that. */
16889 ary_t *ary;
16890 slot single;
16891 } u;
16893 public:
16894 macro_import ()
16896 u.ary = NULL;
16899 private:
16900 bool single_p () const
16902 return u.single.bits & slot::L_BOTH;
16904 bool occupied_p () const
16906 return u.ary != NULL;
16909 public:
16910 unsigned length () const
16912 gcc_checking_assert (occupied_p ());
16913 return single_p () ? 1 : u.ary->length ();
16915 slot &operator[] (unsigned ix)
16917 gcc_checking_assert (occupied_p ());
16918 if (single_p ())
16920 gcc_checking_assert (!ix);
16921 return u.single;
16923 else
16924 return (*u.ary)[ix];
16927 public:
16928 slot &exported ();
16929 slot &append (unsigned module, unsigned defness);
16932 /* O is a new import to append to the list for. If we're an empty
16933 set, initialize us. */
16935 macro_import::slot &
16936 macro_import::append (unsigned module, unsigned defness)
16938 if (!occupied_p ())
16940 u.single = slot::ctor (module, defness);
16941 return u.single;
16943 else
16945 bool single = single_p ();
16946 ary_t *m = single ? NULL : u.ary;
16947 vec_safe_reserve (m, 1 + single);
16948 if (single)
16949 m->quick_push (u.single);
16950 u.ary = m;
16951 return *u.ary->quick_push (slot::ctor (module, defness));
16955 /* We're going to export something. Make sure the first import slot
16956 is us. */
16958 macro_import::slot &
16959 macro_import::exported ()
16961 if (occupied_p () && !(*this)[0].get_module ())
16963 slot &res = (*this)[0];
16964 res.bits |= slot::L_DEF;
16965 return res;
16968 slot *a = &append (0, slot::L_DEF);
16969 if (!single_p ())
16971 slot &f = (*this)[0];
16972 std::swap (f, *a);
16973 a = &f;
16975 return *a;
16978 /* The import (&exported) macros. cpp_hasnode's deferred field
16979 indexes this array (offset by 1, so zero means 'not present'. */
16981 static vec<macro_import, va_heap, vl_embed> *macro_imports;
16983 /* The exported macros. A macro_import slot's zeroth element's offset
16984 indexes this array. If the zeroth slot is not for module zero,
16985 there is no export. */
16987 static GTY(()) vec<macro_export, va_gc> *macro_exports;
16989 /* The reachable set of header imports from this TU. */
16991 static GTY(()) bitmap headers;
16993 /* Get the (possibly empty) macro imports for NODE. */
16995 static macro_import &
16996 get_macro_imports (cpp_hashnode *node)
16998 if (node->deferred)
16999 return (*macro_imports)[node->deferred - 1];
17001 vec_safe_reserve (macro_imports, 1);
17002 node->deferred = macro_imports->length () + 1;
17003 return *vec_safe_push (macro_imports, macro_import ());
17006 /* Get the macro export for export EXP of NODE. */
17008 static macro_export &
17009 get_macro_export (macro_import::slot &slot)
17011 if (slot.offset >= 0)
17012 return (*macro_exports)[slot.offset];
17014 vec_safe_reserve (macro_exports, 1);
17015 slot.offset = macro_exports->length ();
17016 return *macro_exports->quick_push (macro_export ());
17019 /* If NODE is an exportable macro, add it to the export set. */
17021 static int
17022 maybe_add_macro (cpp_reader *, cpp_hashnode *node, void *data_)
17024 bool exporting = false;
17026 if (cpp_user_macro_p (node))
17027 if (cpp_macro *macro = node->value.macro)
17028 /* Ignore imported, builtins, command line and forced header macros. */
17029 if (!macro->imported_p
17030 && !macro->lazy && macro->line >= spans.main_start ())
17032 gcc_checking_assert (macro->kind == cmk_macro);
17033 /* I don't want to deal with this corner case, that I suspect is
17034 a devil's advocate reading of the standard. */
17035 gcc_checking_assert (!macro->extra_tokens);
17037 macro_import::slot &slot = get_macro_imports (node).exported ();
17038 macro_export &exp = get_macro_export (slot);
17039 exp.def = macro;
17040 exporting = true;
17043 if (!exporting && node->deferred)
17045 macro_import &imports = (*macro_imports)[node->deferred - 1];
17046 macro_import::slot &slot = imports[0];
17047 if (!slot.get_module ())
17049 gcc_checking_assert (slot.get_defness ());
17050 exporting = true;
17054 if (exporting)
17055 static_cast<vec<cpp_hashnode *> *> (data_)->safe_push (node);
17057 return 1; /* Don't stop. */
17060 /* Order cpp_hashnodes A_ and B_ by their exported macro locations. */
17062 static int
17063 macro_loc_cmp (const void *a_, const void *b_)
17065 const cpp_hashnode *node_a = *(const cpp_hashnode *const *)a_;
17066 macro_import &import_a = (*macro_imports)[node_a->deferred - 1];
17067 const macro_export &export_a = (*macro_exports)[import_a[0].offset];
17068 location_t loc_a = export_a.def ? export_a.def->line : export_a.undef_loc;
17070 const cpp_hashnode *node_b = *(const cpp_hashnode *const *)b_;
17071 macro_import &import_b = (*macro_imports)[node_b->deferred - 1];
17072 const macro_export &export_b = (*macro_exports)[import_b[0].offset];
17073 location_t loc_b = export_b.def ? export_b.def->line : export_b.undef_loc;
17075 if (loc_a < loc_b)
17076 return +1;
17077 else if (loc_a > loc_b)
17078 return -1;
17079 else
17080 return 0;
17083 /* Gather the macro definitions and undefinitions that we will need to
17084 write out. */
17086 vec<cpp_hashnode *> *
17087 module_state::prepare_macros (cpp_reader *reader)
17089 vec<cpp_hashnode *> *macros;
17090 vec_alloc (macros, 100);
17092 cpp_forall_identifiers (reader, maybe_add_macro, macros);
17094 dump (dumper::MACRO) && dump ("No more than %u macros", macros->length ());
17096 macros->qsort (macro_loc_cmp);
17098 // Note the locations.
17099 for (unsigned ix = macros->length (); ix--;)
17101 cpp_hashnode *node = (*macros)[ix];
17102 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
17103 macro_export &mac = (*macro_exports)[slot.offset];
17105 if (IDENTIFIER_KEYWORD_P (identifier (node)))
17106 continue;
17108 if (mac.undef_loc != UNKNOWN_LOCATION)
17109 note_location (mac.undef_loc);
17110 if (mac.def)
17112 note_location (mac.def->line);
17113 for (unsigned ix = 0; ix != mac.def->count; ix++)
17114 note_location (mac.def->exp.tokens[ix].src_loc);
17118 return macros;
17121 /* Write out the exported defines. This is two sections, one
17122 containing the definitions, the other a table of node names. */
17124 unsigned
17125 module_state::write_macros (elf_out *to, vec<cpp_hashnode *> *macros,
17126 unsigned *crc_p)
17128 dump () && dump ("Writing macros");
17129 dump.indent ();
17131 /* Write the defs */
17132 bytes_out sec (to);
17133 sec.begin ();
17135 unsigned count = 0;
17136 for (unsigned ix = macros->length (); ix--;)
17138 cpp_hashnode *node = (*macros)[ix];
17139 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
17140 gcc_assert (!slot.get_module () && slot.get_defness ());
17142 macro_export &mac = (*macro_exports)[slot.offset];
17143 gcc_assert (!!(slot.get_defness () & macro_import::slot::L_UNDEF)
17144 == (mac.undef_loc != UNKNOWN_LOCATION)
17145 && !!(slot.get_defness () & macro_import::slot::L_DEF)
17146 == (mac.def != NULL));
17148 if (IDENTIFIER_KEYWORD_P (identifier (node)))
17150 warning_at (mac.def->line, 0,
17151 "not exporting %<#define %E%> as it is a keyword",
17152 identifier (node));
17153 slot.offset = 0;
17154 continue;
17157 count++;
17158 slot.offset = sec.pos;
17159 dump (dumper::MACRO)
17160 && dump ("Writing macro %s%s%s %I at %u",
17161 slot.get_defness () & macro_import::slot::L_UNDEF
17162 ? "#undef" : "",
17163 slot.get_defness () == macro_import::slot::L_BOTH
17164 ? " & " : "",
17165 slot.get_defness () & macro_import::slot::L_DEF
17166 ? "#define" : "",
17167 identifier (node), slot.offset);
17168 if (mac.undef_loc != UNKNOWN_LOCATION)
17169 write_location (sec, mac.undef_loc);
17170 if (mac.def)
17171 write_define (sec, mac.def);
17173 if (count)
17174 // We may have ended on a tokenless macro with a very short
17175 // location, that will cause problems reading its bit flags.
17176 sec.u (0);
17177 sec.end (to, to->name (MOD_SNAME_PFX ".def"), crc_p);
17179 if (count)
17181 /* Write the table. */
17182 bytes_out sec (to);
17183 sec.begin ();
17184 sec.u (count);
17186 for (unsigned ix = macros->length (); ix--;)
17188 const cpp_hashnode *node = (*macros)[ix];
17189 macro_import::slot &slot = (*macro_imports)[node->deferred - 1][0];
17191 if (slot.offset)
17193 sec.cpp_node (node);
17194 sec.u (slot.get_defness ());
17195 sec.u (slot.offset);
17198 sec.end (to, to->name (MOD_SNAME_PFX ".mac"), crc_p);
17201 dump.outdent ();
17202 return count;
17205 bool
17206 module_state::read_macros ()
17208 /* Get the def section. */
17209 if (!slurp->macro_defs.begin (loc, from (), MOD_SNAME_PFX ".def"))
17210 return false;
17212 /* Get the tbl section, if there are defs. */
17213 if (slurp->macro_defs.more_p ()
17214 && !slurp->macro_tbl.begin (loc, from (), MOD_SNAME_PFX ".mac"))
17215 return false;
17217 return true;
17220 /* Install the macro name table. */
17222 void
17223 module_state::install_macros ()
17225 bytes_in &sec = slurp->macro_tbl;
17226 if (!sec.size)
17227 return;
17229 dump () && dump ("Reading macro table %M", this);
17230 dump.indent ();
17232 unsigned count = sec.u ();
17233 dump () && dump ("%u macros", count);
17234 while (count--)
17236 cpp_hashnode *node = sec.cpp_node ();
17237 macro_import &imp = get_macro_imports (node);
17238 unsigned flags = sec.u () & macro_import::slot::L_BOTH;
17239 if (!flags)
17240 sec.set_overrun ();
17242 if (sec.get_overrun ())
17243 break;
17245 macro_import::slot &slot = imp.append (mod, flags);
17246 slot.offset = sec.u ();
17248 dump (dumper::MACRO)
17249 && dump ("Read %s macro %s%s%s %I at %u",
17250 imp.length () > 1 ? "add" : "new",
17251 flags & macro_import::slot::L_UNDEF ? "#undef" : "",
17252 flags == macro_import::slot::L_BOTH ? " & " : "",
17253 flags & macro_import::slot::L_DEF ? "#define" : "",
17254 identifier (node), slot.offset);
17256 /* We'll leak an imported definition's TOKEN_FLD_STR's data
17257 here. But that only happens when we've had to resolve the
17258 deferred macro before this import -- why are you doing
17259 that? */
17260 if (cpp_macro *cur = cpp_set_deferred_macro (node))
17261 if (!cur->imported_p)
17263 macro_import::slot &slot = imp.exported ();
17264 macro_export &exp = get_macro_export (slot);
17265 exp.def = cur;
17266 dump (dumper::MACRO)
17267 && dump ("Saving current #define %I", identifier (node));
17271 /* We're now done with the table. */
17272 elf_in::release (slurp->from, sec);
17274 dump.outdent ();
17277 /* Import the transitive macros. */
17279 void
17280 module_state::import_macros ()
17282 bitmap_ior_into (headers, slurp->headers);
17284 bitmap_iterator bititer;
17285 unsigned bitnum;
17286 EXECUTE_IF_SET_IN_BITMAP (slurp->headers, 0, bitnum, bititer)
17287 (*modules)[bitnum]->install_macros ();
17290 /* NODE is being undefined at LOC. Record it in the export table, if
17291 necessary. */
17293 void
17294 module_state::undef_macro (cpp_reader *, location_t loc, cpp_hashnode *node)
17296 if (!node->deferred)
17297 /* The macro is not imported, so our undef is irrelevant. */
17298 return;
17300 unsigned n = dump.push (NULL);
17302 macro_import::slot &slot = (*macro_imports)[node->deferred - 1].exported ();
17303 macro_export &exp = get_macro_export (slot);
17305 exp.undef_loc = loc;
17306 slot.become_undef ();
17307 exp.def = NULL;
17309 dump (dumper::MACRO) && dump ("Recording macro #undef %I", identifier (node));
17311 dump.pop (n);
17314 /* NODE is a deferred macro node. Determine the definition and return
17315 it, with NULL if undefined. May issue diagnostics.
17317 This can leak memory, when merging declarations -- the string
17318 contents (TOKEN_FLD_STR) of each definition are allocated in
17319 unreclaimable cpp objstack. Only one will win. However, I do not
17320 expect this to be common -- mostly macros have a single point of
17321 definition. Perhaps we could restore the objstack to its position
17322 after the first imported definition (if that wins)? The macros
17323 themselves are GC'd. */
17325 cpp_macro *
17326 module_state::deferred_macro (cpp_reader *reader, location_t loc,
17327 cpp_hashnode *node)
17329 macro_import &imports = (*macro_imports)[node->deferred - 1];
17331 unsigned n = dump.push (NULL);
17332 dump (dumper::MACRO) && dump ("Deferred macro %I", identifier (node));
17334 bitmap visible (BITMAP_GGC_ALLOC ());
17336 if (!((imports[0].get_defness () & macro_import::slot::L_UNDEF)
17337 && !imports[0].get_module ()))
17339 /* Calculate the set of visible header imports. */
17340 bitmap_copy (visible, headers);
17341 for (unsigned ix = imports.length (); ix--;)
17343 const macro_import::slot &slot = imports[ix];
17344 unsigned mod = slot.get_module ();
17345 if ((slot.get_defness () & macro_import::slot::L_UNDEF)
17346 && bitmap_bit_p (visible, mod))
17348 bitmap arg = mod ? (*modules)[mod]->slurp->headers : headers;
17349 bitmap_and_compl_into (visible, arg);
17350 bitmap_set_bit (visible, mod);
17354 bitmap_set_bit (visible, 0);
17356 /* Now find the macros that are still visible. */
17357 bool failed = false;
17358 cpp_macro *def = NULL;
17359 vec<macro_export> defs;
17360 defs.create (imports.length ());
17361 for (unsigned ix = imports.length (); ix--;)
17363 const macro_import::slot &slot = imports[ix];
17364 unsigned mod = slot.get_module ();
17365 if (bitmap_bit_p (visible, mod))
17367 macro_export *pushed = NULL;
17368 if (mod)
17370 const module_state *imp = (*modules)[mod];
17371 bytes_in &sec = imp->slurp->macro_defs;
17372 if (!sec.get_overrun ())
17374 dump (dumper::MACRO)
17375 && dump ("Reading macro %s%s%s %I module %M at %u",
17376 slot.get_defness () & macro_import::slot::L_UNDEF
17377 ? "#undef" : "",
17378 slot.get_defness () == macro_import::slot::L_BOTH
17379 ? " & " : "",
17380 slot.get_defness () & macro_import::slot::L_DEF
17381 ? "#define" : "",
17382 identifier (node), imp, slot.offset);
17383 sec.random_access (slot.offset);
17385 macro_export exp;
17386 if (slot.get_defness () & macro_import::slot::L_UNDEF)
17387 exp.undef_loc = imp->read_location (sec);
17388 if (slot.get_defness () & macro_import::slot::L_DEF)
17389 exp.def = imp->read_define (sec, reader);
17390 if (sec.get_overrun ())
17391 error_at (loc, "macro definitions of %qE corrupted",
17392 imp->name);
17393 else
17394 pushed = defs.quick_push (exp);
17397 else
17398 pushed = defs.quick_push ((*macro_exports)[slot.offset]);
17399 if (pushed && pushed->def)
17401 if (!def)
17402 def = pushed->def;
17403 else if (cpp_compare_macros (def, pushed->def))
17404 failed = true;
17409 if (failed)
17411 /* If LOC is the first loc, this is the end of file check, which
17412 is a warning. */
17413 if (loc == MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0)))
17414 warning_at (loc, OPT_Winvalid_imported_macros,
17415 "inconsistent imported macro definition %qE",
17416 identifier (node));
17417 else
17418 error_at (loc, "inconsistent imported macro definition %qE",
17419 identifier (node));
17420 for (unsigned ix = defs.length (); ix--;)
17422 macro_export &exp = defs[ix];
17423 if (exp.undef_loc)
17424 inform (exp.undef_loc, "%<#undef %E%>", identifier (node));
17425 if (exp.def)
17426 inform (exp.def->line, "%<#define %s%>",
17427 cpp_macro_definition (reader, node, exp.def));
17429 def = NULL;
17432 defs.release ();
17434 dump.pop (n);
17436 return def;
17439 /* Stream the static aggregates. Sadly some headers (ahem:
17440 iostream) contain static vars, and rely on them to run global
17441 ctors. */
17442 unsigned
17443 module_state::write_inits (elf_out *to, depset::hash &table, unsigned *crc_ptr)
17445 if (!static_aggregates && !tls_aggregates)
17446 return 0;
17448 dump () && dump ("Writing initializers");
17449 dump.indent ();
17451 static_aggregates = nreverse (static_aggregates);
17452 tls_aggregates = nreverse (tls_aggregates);
17454 unsigned count = 0;
17455 trees_out sec (to, this, table, ~0u);
17456 sec.begin ();
17458 tree list = static_aggregates;
17459 for (int passes = 0; passes != 2; passes++)
17461 for (tree init = list; init; init = TREE_CHAIN (init), count++)
17462 if (TREE_LANG_FLAG_0 (init))
17464 tree decl = TREE_VALUE (init);
17466 dump ("Initializer:%u for %N", count, decl);
17467 sec.tree_node (decl);
17470 list = tls_aggregates;
17473 sec.end (to, to->name (MOD_SNAME_PFX ".ini"), crc_ptr);
17474 dump.outdent ();
17476 return count;
17479 /* We have to defer some post-load processing until we've completed
17480 reading, because they can cause more reading. */
17482 static void
17483 post_load_processing ()
17485 /* We mustn't cause a GC, our caller should have arranged for that
17486 not to happen. */
17487 gcc_checking_assert (function_depth);
17489 if (!post_load_decls)
17490 return;
17492 tree old_cfd = current_function_decl;
17493 struct function *old_cfun = cfun;
17494 while (post_load_decls->length ())
17496 tree decl = post_load_decls->pop ();
17498 dump () && dump ("Post-load processing of %N", decl);
17500 gcc_checking_assert (DECL_ABSTRACT_P (decl));
17501 /* Cloning can cause loading -- specifically operator delete for
17502 the deleting dtor. */
17503 maybe_clone_body (decl);
17506 cfun = old_cfun;
17507 current_function_decl = old_cfd;
17510 bool
17511 module_state::read_inits (unsigned count)
17513 trees_in sec (this);
17514 if (!sec.begin (loc, from (), from ()->find (MOD_SNAME_PFX ".ini")))
17515 return false;
17516 dump () && dump ("Reading %u initializers", count);
17517 dump.indent ();
17519 lazy_snum = ~0u;
17520 for (unsigned ix = 0; ix != count; ix++)
17522 /* Merely referencing the decl causes its initializer to be read
17523 and added to the correct list. */
17524 tree decl = sec.tree_node ();
17526 if (sec.get_overrun ())
17527 break;
17528 if (decl)
17529 dump ("Initializer:%u for %N", count, decl);
17531 lazy_snum = 0;
17532 post_load_processing ();
17533 dump.outdent ();
17534 if (!sec.end (from ()))
17535 return false;
17536 return true;
17539 void
17540 module_state::write_counts (elf_out *to, unsigned counts[MSC_HWM],
17541 unsigned *crc_ptr)
17543 bytes_out cfg (to);
17545 cfg.begin ();
17547 for (unsigned ix = MSC_HWM; ix--;)
17548 cfg.u (counts[ix]);
17550 if (dump ())
17552 dump ("Cluster sections are [%u,%u)",
17553 counts[MSC_sec_lwm], counts[MSC_sec_hwm]);
17554 dump ("Bindings %u", counts[MSC_bindings]);
17555 dump ("Pendings %u", counts[MSC_pendings]);
17556 dump ("Entities %u", counts[MSC_entities]);
17557 dump ("Namespaces %u", counts[MSC_namespaces]);
17558 dump ("Macros %u", counts[MSC_macros]);
17559 dump ("Initializers %u", counts[MSC_inits]);
17562 cfg.end (to, to->name (MOD_SNAME_PFX ".cnt"), crc_ptr);
17565 bool
17566 module_state::read_counts (unsigned counts[MSC_HWM])
17568 bytes_in cfg;
17570 if (!cfg.begin (loc, from (), MOD_SNAME_PFX ".cnt"))
17571 return false;
17573 for (unsigned ix = MSC_HWM; ix--;)
17574 counts[ix] = cfg.u ();
17576 if (dump ())
17578 dump ("Declaration sections are [%u,%u)",
17579 counts[MSC_sec_lwm], counts[MSC_sec_hwm]);
17580 dump ("Bindings %u", counts[MSC_bindings]);
17581 dump ("Pendings %u", counts[MSC_pendings]);
17582 dump ("Entities %u", counts[MSC_entities]);
17583 dump ("Namespaces %u", counts[MSC_namespaces]);
17584 dump ("Macros %u", counts[MSC_macros]);
17585 dump ("Initializers %u", counts[MSC_inits]);
17588 return cfg.end (from ());
17591 /* Tool configuration: MOD_SNAME_PFX .config
17593 This is data that confirms current state (or fails). */
17595 void
17596 module_state::write_config (elf_out *to, module_state_config &config,
17597 unsigned inner_crc)
17599 bytes_out cfg (to);
17601 cfg.begin ();
17603 /* Write version and inner crc as u32 values, for easier
17604 debug inspection. */
17605 dump () && dump ("Writing version=%V, inner_crc=%x",
17606 MODULE_VERSION, inner_crc);
17607 cfg.u32 (unsigned (MODULE_VERSION));
17608 cfg.u32 (inner_crc);
17610 cfg.u (to->name (is_header () ? "" : get_flatname ()));
17612 /* Configuration. */
17613 dump () && dump ("Writing target='%s', host='%s'",
17614 TARGET_MACHINE, HOST_MACHINE);
17615 unsigned target = to->name (TARGET_MACHINE);
17616 unsigned host = (!strcmp (TARGET_MACHINE, HOST_MACHINE)
17617 ? target : to->name (HOST_MACHINE));
17618 cfg.u (target);
17619 cfg.u (host);
17621 cfg.str (config.dialect_str);
17622 cfg.u (extensions);
17624 /* Global tree information. We write the globals crc separately,
17625 rather than mix it directly into the overall crc, as it is used
17626 to ensure data match between instances of the compiler, not
17627 integrity of the file. */
17628 dump () && dump ("Writing globals=%u, crc=%x",
17629 fixed_trees->length (), global_crc);
17630 cfg.u (fixed_trees->length ());
17631 cfg.u32 (global_crc);
17633 if (is_partition ())
17634 cfg.u (is_interface ());
17636 cfg.u (config.num_imports);
17637 cfg.u (config.num_partitions);
17638 cfg.u (config.num_entities);
17640 cfg.u (config.ordinary_locs);
17641 cfg.u (config.macro_locs);
17642 cfg.u (config.loc_range_bits);
17644 cfg.u (config.active_init);
17646 /* Now generate CRC, we'll have incorporated the inner CRC because
17647 of its serialization above. */
17648 cfg.end (to, to->name (MOD_SNAME_PFX ".cfg"), &crc);
17649 dump () && dump ("Writing CRC=%x", crc);
17652 void
17653 module_state::note_cmi_name ()
17655 if (!cmi_noted_p && filename)
17657 cmi_noted_p = true;
17658 inform (loc, "compiled module file is %qs",
17659 maybe_add_cmi_prefix (filename));
17663 bool
17664 module_state::read_config (module_state_config &config)
17666 bytes_in cfg;
17668 if (!cfg.begin (loc, from (), MOD_SNAME_PFX ".cfg"))
17669 return false;
17671 /* Check version. */
17672 unsigned my_ver = MODULE_VERSION;
17673 unsigned their_ver = cfg.u32 ();
17674 dump () && dump (my_ver == their_ver ? "Version %V"
17675 : "Expecting %V found %V", my_ver, their_ver);
17676 if (their_ver != my_ver)
17678 /* The compiler versions differ. Close enough? */
17679 verstr_t my_string, their_string;
17681 version2string (my_ver, my_string);
17682 version2string (their_ver, their_string);
17684 /* Reject when either is non-experimental or when experimental
17685 major versions differ. */
17686 bool reject_p = ((!IS_EXPERIMENTAL (my_ver)
17687 || !IS_EXPERIMENTAL (their_ver)
17688 || MODULE_MAJOR (my_ver) != MODULE_MAJOR (their_ver))
17689 /* The 'I know what I'm doing' switch. */
17690 && !flag_module_version_ignore);
17691 bool inform_p = true;
17692 if (reject_p)
17694 cfg.set_overrun ();
17695 error_at (loc, "compiled module is %sversion %s",
17696 IS_EXPERIMENTAL (their_ver) ? "experimental " : "",
17697 their_string);
17699 else
17700 inform_p = warning_at (loc, 0, "compiled module is %sversion %s",
17701 IS_EXPERIMENTAL (their_ver) ? "experimental " : "",
17702 their_string);
17704 if (inform_p)
17706 inform (loc, "compiler is %sversion %s%s%s",
17707 IS_EXPERIMENTAL (my_ver) ? "experimental " : "",
17708 my_string,
17709 reject_p ? "" : flag_module_version_ignore
17710 ? ", be it on your own head!" : ", close enough?",
17711 reject_p ? "" : " \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf");
17712 note_cmi_name ();
17715 if (reject_p)
17716 goto done;
17719 /* We wrote the inner crc merely to merge it, so simply read it
17720 back and forget it. */
17721 cfg.u32 ();
17723 /* Check module name. */
17725 const char *their_name = from ()->name (cfg.u ());
17726 const char *our_name = "";
17728 if (!is_header ())
17729 our_name = get_flatname ();
17731 /* Header units can be aliased, so name checking is
17732 inappropriate. */
17733 if (0 != strcmp (their_name, our_name))
17735 error_at (loc,
17736 their_name[0] && our_name[0] ? G_("module %qs found")
17737 : their_name[0]
17738 ? G_("header module expected, module %qs found")
17739 : G_("module %qs expected, header module found"),
17740 their_name[0] ? their_name : our_name);
17741 cfg.set_overrun ();
17742 goto done;
17746 /* Check the CRC after the above sanity checks, so that the user is
17747 clued in. */
17749 unsigned e_crc = crc;
17750 crc = cfg.get_crc ();
17751 dump () && dump ("Reading CRC=%x", crc);
17752 if (!is_direct () && crc != e_crc)
17754 error_at (loc, "module %qs CRC mismatch", get_flatname ());
17755 cfg.set_overrun ();
17756 goto done;
17760 /* Check target & host. */
17762 const char *their_target = from ()->name (cfg.u ());
17763 const char *their_host = from ()->name (cfg.u ());
17764 dump () && dump ("Read target='%s', host='%s'", their_target, their_host);
17765 if (strcmp (their_target, TARGET_MACHINE)
17766 || strcmp (their_host, HOST_MACHINE))
17768 error_at (loc, "target & host is %qs:%qs, expected %qs:%qs",
17769 their_target, TARGET_MACHINE, their_host, HOST_MACHINE);
17770 cfg.set_overrun ();
17771 goto done;
17775 /* Check compilation dialect. This must match. */
17777 const char *their_dialect = cfg.str ();
17778 if (strcmp (their_dialect, config.dialect_str))
17780 error_at (loc, "language dialect differs %qs, expected %qs",
17781 their_dialect, config.dialect_str);
17782 cfg.set_overrun ();
17783 goto done;
17787 /* Check for extensions. If they set any, we must have them set
17788 too. */
17790 unsigned ext = cfg.u ();
17791 unsigned allowed = (flag_openmp ? SE_OPENMP : 0);
17793 if (unsigned bad = ext & ~allowed)
17795 if (bad & SE_OPENMP)
17796 error_at (loc, "module contains OpenMP, use %<-fopenmp%> to enable");
17797 cfg.set_overrun ();
17798 goto done;
17800 extensions = ext;
17803 /* Check global trees. */
17805 unsigned their_fixed_length = cfg.u ();
17806 unsigned their_fixed_crc = cfg.u32 ();
17807 dump () && dump ("Read globals=%u, crc=%x",
17808 their_fixed_length, their_fixed_crc);
17809 if (!flag_preprocess_only
17810 && (their_fixed_length != fixed_trees->length ()
17811 || their_fixed_crc != global_crc))
17813 error_at (loc, "fixed tree mismatch");
17814 cfg.set_overrun ();
17815 goto done;
17819 /* All non-partitions are interfaces. */
17820 interface_p = !is_partition () || cfg.u ();
17822 config.num_imports = cfg.u ();
17823 config.num_partitions = cfg.u ();
17824 config.num_entities = cfg.u ();
17826 config.ordinary_locs = cfg.u ();
17827 config.macro_locs = cfg.u ();
17828 config.loc_range_bits = cfg.u ();
17830 config.active_init = cfg.u ();
17832 done:
17833 return cfg.end (from ());
17836 /* Comparator for ordering the Ordered Ordinary Location array. */
17838 static int
17839 ool_cmp (const void *a_, const void *b_)
17841 auto *a = *static_cast<const module_state *const *> (a_);
17842 auto *b = *static_cast<const module_state *const *> (b_);
17843 if (a == b)
17844 return 0;
17845 else if (a->ordinary_locs.first < b->ordinary_locs.first)
17846 return -1;
17847 else
17848 return +1;
17851 /* Use ELROND format to record the following sections:
17852 qualified-names : binding value(s)
17853 MOD_SNAME_PFX.README : human readable, strings
17854 MOD_SNAME_PFX.ENV : environment strings, strings
17855 MOD_SNAME_PFX.nms : namespace hierarchy
17856 MOD_SNAME_PFX.bnd : binding table
17857 MOD_SNAME_PFX.spc : specialization table
17858 MOD_SNAME_PFX.imp : import table
17859 MOD_SNAME_PFX.ent : entity table
17860 MOD_SNAME_PFX.prt : partitions table
17861 MOD_SNAME_PFX.olm : ordinary line maps
17862 MOD_SNAME_PFX.mlm : macro line maps
17863 MOD_SNAME_PFX.def : macro definitions
17864 MOD_SNAME_PFX.mac : macro index
17865 MOD_SNAME_PFX.ini : inits
17866 MOD_SNAME_PFX.cnt : counts
17867 MOD_SNAME_PFX.cfg : config data
17870 void
17871 module_state::write_begin (elf_out *to, cpp_reader *reader,
17872 module_state_config &config, unsigned &crc)
17874 /* Figure out remapped module numbers, which might elide
17875 partitions. */
17876 bitmap partitions = NULL;
17877 if (!is_header () && !is_partition ())
17878 partitions = BITMAP_GGC_ALLOC ();
17879 write_init_maps ();
17881 unsigned mod_hwm = 1;
17882 for (unsigned ix = 1; ix != modules->length (); ix++)
17884 module_state *imp = (*modules)[ix];
17886 /* Promote any non-partition direct import from a partition, unless
17887 we're a partition. */
17888 if (!is_partition () && !imp->is_partition ()
17889 && imp->is_partition_direct ())
17890 imp->directness = MD_PURVIEW_DIRECT;
17892 /* Write any import that is not a partition, unless we're a
17893 partition. */
17894 if (!partitions || !imp->is_partition ())
17895 imp->remap = mod_hwm++;
17896 else
17898 dump () && dump ("Partition %M %u", imp, ix);
17899 bitmap_set_bit (partitions, ix);
17900 imp->remap = 0;
17901 /* All interface partitions must be exported. */
17902 if (imp->is_interface () && !bitmap_bit_p (exports, imp->mod))
17904 error_at (imp->loc, "interface partition is not exported");
17905 bitmap_set_bit (exports, imp->mod);
17908 /* All the partition entities should have been loaded when
17909 loading the partition. */
17910 if (CHECKING_P)
17911 for (unsigned jx = 0; jx != imp->entity_num; jx++)
17913 binding_slot *slot = &(*entity_ary)[imp->entity_lwm + jx];
17914 gcc_checking_assert (!slot->is_lazy ());
17918 if (imp->is_direct () && (imp->remap || imp->is_partition ()))
17919 note_location (imp->imported_from ());
17922 if (partitions && bitmap_empty_p (partitions))
17923 /* No partitions present. */
17924 partitions = nullptr;
17926 /* Find the set of decls we must write out. */
17927 depset::hash table (DECL_NAMESPACE_BINDINGS (global_namespace)->size () * 8);
17928 /* Add the specializations before the writables, so that we can
17929 detect injected friend specializations. */
17930 table.add_specializations (true);
17931 table.add_specializations (false);
17932 if (partial_specializations)
17934 table.add_partial_entities (partial_specializations);
17935 partial_specializations = NULL;
17937 table.add_namespace_entities (global_namespace, partitions);
17938 if (class_members)
17940 table.add_class_entities (class_members);
17941 class_members = NULL;
17944 /* Now join everything up. */
17945 table.find_dependencies (this);
17947 if (!table.finalize_dependencies ())
17949 to->set_error ();
17950 return;
17953 #if CHECKING_P
17954 /* We're done verifying at-most once reading, reset to verify
17955 at-most once writing. */
17956 note_defs = note_defs_table_t::create_ggc (1000);
17957 #endif
17959 /* Determine Strongy Connected Components. */
17960 vec<depset *> sccs = table.connect ();
17962 vec_alloc (ool, modules->length ());
17963 for (unsigned ix = modules->length (); --ix;)
17965 auto *import = (*modules)[ix];
17966 if (import->loadedness > ML_NONE
17967 && !(partitions && bitmap_bit_p (partitions, import->mod)))
17968 ool->quick_push (import);
17970 ool->qsort (ool_cmp);
17972 vec<cpp_hashnode *> *macros = nullptr;
17973 if (is_header ())
17974 macros = prepare_macros (reader);
17976 config.num_imports = mod_hwm;
17977 config.num_partitions = modules->length () - mod_hwm;
17978 auto map_info = write_prepare_maps (&config, bool (config.num_partitions));
17979 unsigned counts[MSC_HWM];
17980 memset (counts, 0, sizeof (counts));
17982 /* depset::cluster is the cluster number,
17983 depset::section is unspecified scratch value.
17985 The following loops make use of the tarjan property that
17986 dependencies will be earlier in the SCCS array. */
17988 /* This first loop determines the number of depsets in each SCC, and
17989 also the number of namespaces we're dealing with. During the
17990 loop, the meaning of a couple of depset fields now change:
17992 depset::cluster -> size_of cluster, if first of cluster & !namespace
17993 depset::section -> section number of cluster (if !namespace). */
17995 unsigned n_spaces = 0;
17996 counts[MSC_sec_lwm] = counts[MSC_sec_hwm] = to->get_section_limit ();
17997 for (unsigned size, ix = 0; ix < sccs.length (); ix += size)
17999 depset **base = &sccs[ix];
18001 if (base[0]->get_entity_kind () == depset::EK_NAMESPACE)
18003 n_spaces++;
18004 size = 1;
18006 else
18008 /* Count the members in this cluster. */
18009 for (size = 1; ix + size < sccs.length (); size++)
18010 if (base[size]->cluster != base[0]->cluster)
18011 break;
18013 for (unsigned jx = 0; jx != size; jx++)
18015 /* Set the section number. */
18016 base[jx]->cluster = ~(~0u >> 1); /* A bad value. */
18017 base[jx]->section = counts[MSC_sec_hwm];
18020 /* Save the size in the first member's cluster slot. */
18021 base[0]->cluster = size;
18023 counts[MSC_sec_hwm]++;
18027 /* Write the clusters. Namespace decls are put in the spaces array.
18028 The meaning of depset::cluster changes to provide the
18029 unnamed-decl count of the depset's decl (and remains zero for
18030 non-decls and non-unnamed). */
18031 unsigned bytes = 0;
18032 vec<depset *> spaces;
18033 spaces.create (n_spaces);
18035 for (unsigned size, ix = 0; ix < sccs.length (); ix += size)
18037 depset **base = &sccs[ix];
18039 if (base[0]->get_entity_kind () == depset::EK_NAMESPACE)
18041 tree decl = base[0]->get_entity ();
18042 if (decl == global_namespace)
18043 base[0]->cluster = 0;
18044 else if (!base[0]->is_import ())
18046 base[0]->cluster = counts[MSC_entities]++;
18047 spaces.quick_push (base[0]);
18048 counts[MSC_namespaces]++;
18049 if (CHECKING_P)
18051 /* Add it to the entity map, such that we can tell it is
18052 part of us. */
18053 bool existed;
18054 unsigned *slot = &entity_map->get_or_insert
18055 (DECL_UID (decl), &existed);
18056 if (existed)
18057 /* It must have come from a partition. */
18058 gcc_checking_assert
18059 (import_entity_module (*slot)->is_partition ());
18060 *slot = ~base[0]->cluster;
18062 dump (dumper::CLUSTER) && dump ("Cluster namespace %N", decl);
18064 size = 1;
18066 else
18068 size = base[0]->cluster;
18070 /* Cluster is now used to number entities. */
18071 base[0]->cluster = ~(~0u >> 1); /* A bad value. */
18073 sort_cluster (&table, base, size);
18075 /* Record the section for consistency checking during stream
18076 out -- we don't want to start writing decls in different
18077 sections. */
18078 table.section = base[0]->section;
18079 bytes += write_cluster (to, base, size, table, counts, &crc);
18080 table.section = 0;
18084 /* depset::cluster - entity number (on entities)
18085 depset::section - cluster number */
18086 /* We'd better have written as many sections and found as many
18087 namespaces as we predicted. */
18088 gcc_assert (counts[MSC_sec_hwm] == to->get_section_limit ()
18089 && spaces.length () == counts[MSC_namespaces]);
18091 /* Write the entitites. None happens if we contain namespaces or
18092 nothing. */
18093 config.num_entities = counts[MSC_entities];
18094 if (counts[MSC_entities])
18095 write_entities (to, sccs, counts[MSC_entities], &crc);
18097 /* Write the namespaces. */
18098 if (counts[MSC_namespaces])
18099 write_namespaces (to, spaces, counts[MSC_namespaces], &crc);
18101 /* Write the bindings themselves. */
18102 counts[MSC_bindings] = write_bindings (to, sccs, &crc);
18104 /* Write the unnamed. */
18105 counts[MSC_pendings] = write_pendings (to, sccs, table, &crc);
18107 /* Write the import table. */
18108 if (config.num_imports > 1)
18109 write_imports (to, &crc);
18111 /* Write elided partition table. */
18112 if (config.num_partitions)
18113 write_partitions (to, config.num_partitions, &crc);
18115 /* Write the line maps. */
18116 if (config.ordinary_locs)
18117 write_ordinary_maps (to, map_info, bool (config.num_partitions), &crc);
18118 if (config.macro_locs)
18119 write_macro_maps (to, map_info, &crc);
18121 if (is_header ())
18123 counts[MSC_macros] = write_macros (to, macros, &crc);
18124 counts[MSC_inits] = write_inits (to, table, &crc);
18125 vec_free (macros);
18128 unsigned clusters = counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
18129 dump () && dump ("Wrote %u clusters, average %u bytes/cluster",
18130 clusters, (bytes + clusters / 2) / (clusters + !clusters));
18131 trees_out::instrument ();
18133 write_counts (to, counts, &crc);
18135 spaces.release ();
18136 sccs.release ();
18138 vec_free (macro_loc_remap);
18139 vec_free (ord_loc_remap);
18140 vec_free (ool);
18142 // FIXME:QOI: Have a command line switch to control more detailed
18143 // information (which might leak data you do not want to leak).
18144 // Perhaps (some of) the write_readme contents should also be
18145 // so-controlled.
18146 if (false)
18147 write_env (to);
18150 // Finish module writing after we've emitted all dynamic initializers.
18152 void
18153 module_state::write_end (elf_out *to, cpp_reader *reader,
18154 module_state_config &config, unsigned &crc)
18156 /* And finish up. */
18157 write_config (to, config, crc);
18159 /* Human-readable info. */
18160 write_readme (to, reader, config.dialect_str);
18162 dump () && dump ("Wrote %u sections", to->get_section_limit ());
18165 /* Initial read of a CMI. Checks config, loads up imports and line
18166 maps. */
18168 bool
18169 module_state::read_initial (cpp_reader *reader)
18171 module_state_config config;
18172 bool ok = true;
18174 if (ok && !from ()->begin (loc))
18175 ok = false;
18177 if (ok && !read_config (config))
18178 ok = false;
18180 bool have_locs = ok && read_prepare_maps (&config);
18182 /* Ordinary maps before the imports. */
18183 if (!(have_locs && config.ordinary_locs))
18184 ordinary_locs.first = line_table->highest_location + 1;
18185 else if (!read_ordinary_maps (config.ordinary_locs, config.loc_range_bits))
18186 ok = false;
18188 /* Allocate the REMAP vector. */
18189 slurp->alloc_remap (config.num_imports);
18191 if (ok)
18193 /* Read the import table. Decrement current to stop this CMI
18194 from being evicted during the import. */
18195 slurp->current--;
18196 if (config.num_imports > 1 && !read_imports (reader, line_table))
18197 ok = false;
18198 slurp->current++;
18201 /* Read the elided partition table, if we're the primary partition. */
18202 if (ok && config.num_partitions && is_module ()
18203 && !read_partitions (config.num_partitions))
18204 ok = false;
18206 /* Determine the module's number. */
18207 gcc_checking_assert (mod == MODULE_UNKNOWN);
18208 gcc_checking_assert (this != (*modules)[0]);
18211 /* Allocate space in the entities array now -- that array must be
18212 monotonically in step with the modules array. */
18213 entity_lwm = vec_safe_length (entity_ary);
18214 entity_num = config.num_entities;
18215 gcc_checking_assert (modules->length () == 1
18216 || modules->last ()->entity_lwm <= entity_lwm);
18217 vec_safe_reserve (entity_ary, config.num_entities);
18219 binding_slot slot;
18220 slot.u.binding = NULL_TREE;
18221 for (unsigned count = config.num_entities; count--;)
18222 entity_ary->quick_push (slot);
18225 /* We'll run out of other resources before we run out of module
18226 indices. */
18227 mod = modules->length ();
18228 vec_safe_push (modules, this);
18230 /* We always import and export ourselves. */
18231 bitmap_set_bit (imports, mod);
18232 bitmap_set_bit (exports, mod);
18234 if (ok)
18235 (*slurp->remap)[0] = mod << 1;
18236 dump () && dump ("Assigning %M module number %u", this, mod);
18238 /* We should not have been frozen during the importing done by
18239 read_config. */
18240 gcc_assert (!from ()->is_frozen ());
18242 /* Macro maps after the imports. */
18243 if (!(ok && have_locs && config.macro_locs))
18244 macro_locs.first = LINEMAPS_MACRO_LOWEST_LOCATION (line_table);
18245 else if (!read_macro_maps (config.macro_locs))
18246 ok = false;
18248 /* Note whether there's an active initializer. */
18249 active_init_p = !is_header () && bool (config.active_init);
18251 gcc_assert (slurp->current == ~0u);
18252 return ok;
18255 /* Read a preprocessor state. */
18257 bool
18258 module_state::read_preprocessor (bool outermost)
18260 gcc_checking_assert (is_header () && slurp
18261 && slurp->remap_module (0) == mod);
18263 if (loadedness == ML_PREPROCESSOR)
18264 return !(from () && from ()->get_error ());
18266 bool ok = true;
18268 /* Read direct header imports. */
18269 unsigned len = slurp->remap->length ();
18270 for (unsigned ix = 1; ok && ix != len; ix++)
18272 unsigned map = (*slurp->remap)[ix];
18273 if (map & 1)
18275 module_state *import = (*modules)[map >> 1];
18276 if (import->is_header ())
18278 ok = import->read_preprocessor (false);
18279 bitmap_ior_into (slurp->headers, import->slurp->headers);
18284 /* Record as a direct header. */
18285 if (ok)
18286 bitmap_set_bit (slurp->headers, mod);
18288 if (ok && !read_macros ())
18289 ok = false;
18291 loadedness = ML_PREPROCESSOR;
18292 announce ("macros");
18294 if (flag_preprocess_only)
18295 /* We're done with the string table. */
18296 from ()->release ();
18298 return check_read (outermost, ok);
18301 /* Read language state. */
18303 bool
18304 module_state::read_language (bool outermost)
18306 gcc_checking_assert (!lazy_snum);
18308 if (loadedness == ML_LANGUAGE)
18309 return !(slurp && from () && from ()->get_error ());
18311 gcc_checking_assert (slurp && slurp->current == ~0u
18312 && slurp->remap_module (0) == mod);
18314 bool ok = true;
18316 /* Read direct imports. */
18317 unsigned len = slurp->remap->length ();
18318 for (unsigned ix = 1; ok && ix != len; ix++)
18320 unsigned map = (*slurp->remap)[ix];
18321 if (map & 1)
18323 module_state *import = (*modules)[map >> 1];
18324 if (!import->read_language (false))
18325 ok = false;
18329 unsigned counts[MSC_HWM];
18331 if (ok && !read_counts (counts))
18332 ok = false;
18334 function_depth++; /* Prevent unexpected GCs. */
18336 if (ok && counts[MSC_entities] != entity_num)
18337 ok = false;
18338 if (ok && counts[MSC_entities]
18339 && !read_entities (counts[MSC_entities],
18340 counts[MSC_sec_lwm], counts[MSC_sec_hwm]))
18341 ok = false;
18343 /* Read the namespace hierarchy. */
18344 if (ok && counts[MSC_namespaces]
18345 && !read_namespaces (counts[MSC_namespaces]))
18346 ok = false;
18348 if (ok && !read_bindings (counts[MSC_bindings],
18349 counts[MSC_sec_lwm], counts[MSC_sec_hwm]))
18350 ok = false;
18352 /* And unnamed. */
18353 if (ok && counts[MSC_pendings] && !read_pendings (counts[MSC_pendings]))
18354 ok = false;
18356 if (ok)
18358 slurp->remaining = counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
18359 available_clusters += counts[MSC_sec_hwm] - counts[MSC_sec_lwm];
18362 if (!flag_module_lazy
18363 || (is_partition ()
18364 && module_interface_p ()
18365 && !module_partition_p ()))
18367 /* Read the sections in forward order, so that dependencies are read
18368 first. See note about tarjan_connect. */
18369 ggc_collect ();
18371 lazy_snum = ~0u;
18373 unsigned hwm = counts[MSC_sec_hwm];
18374 for (unsigned ix = counts[MSC_sec_lwm]; ok && ix != hwm; ix++)
18375 if (!load_section (ix, NULL))
18377 ok = false;
18378 break;
18380 lazy_snum = 0;
18381 post_load_processing ();
18383 ggc_collect ();
18385 if (ok && CHECKING_P)
18386 for (unsigned ix = 0; ix != entity_num; ix++)
18387 gcc_assert (!(*entity_ary)[ix + entity_lwm].is_lazy ());
18390 // If the import is a header-unit, we need to register initializers
18391 // of any static objects it contains (looking at you _Ioinit).
18392 // Notice, the ordering of these initializers will be that of a
18393 // dynamic initializer at this point in the current TU. (Other
18394 // instances of these objects in other TUs will be initialized as
18395 // part of that TU's global initializers.)
18396 if (ok && counts[MSC_inits] && !read_inits (counts[MSC_inits]))
18397 ok = false;
18399 function_depth--;
18401 announce (flag_module_lazy ? "lazy" : "imported");
18402 loadedness = ML_LANGUAGE;
18404 gcc_assert (slurp->current == ~0u);
18406 /* We're done with the string table. */
18407 from ()->release ();
18409 return check_read (outermost, ok);
18412 bool
18413 module_state::maybe_defrost ()
18415 bool ok = true;
18416 if (from ()->is_frozen ())
18418 if (lazy_open >= lazy_limit)
18419 freeze_an_elf ();
18420 dump () && dump ("Defrosting '%s'", filename);
18421 ok = from ()->defrost (maybe_add_cmi_prefix (filename));
18422 lazy_open++;
18425 return ok;
18428 /* Load section SNUM, dealing with laziness. It doesn't matter if we
18429 have multiple concurrent loads, because we do not use TREE_VISITED
18430 when reading back in. */
18432 bool
18433 module_state::load_section (unsigned snum, binding_slot *mslot)
18435 if (from ()->get_error ())
18436 return false;
18438 if (snum >= slurp->current)
18439 from ()->set_error (elf::E_BAD_LAZY);
18440 else if (maybe_defrost ())
18442 unsigned old_current = slurp->current;
18443 slurp->current = snum;
18444 slurp->lru = 0; /* Do not swap out. */
18445 slurp->remaining--;
18446 read_cluster (snum);
18447 slurp->lru = ++lazy_lru;
18448 slurp->current = old_current;
18451 if (mslot && mslot->is_lazy ())
18453 /* Oops, the section didn't set this slot. */
18454 from ()->set_error (elf::E_BAD_DATA);
18455 *mslot = NULL_TREE;
18458 bool ok = !from ()->get_error ();
18459 if (!ok)
18461 error_at (loc, "failed to read compiled module cluster %u: %s",
18462 snum, from ()->get_error (filename));
18463 note_cmi_name ();
18466 maybe_completed_reading ();
18468 return ok;
18471 void
18472 module_state::maybe_completed_reading ()
18474 if (loadedness == ML_LANGUAGE && slurp->current == ~0u && !slurp->remaining)
18476 lazy_open--;
18477 /* We no longer need the macros, all tokenizing has been done. */
18478 slurp->release_macros ();
18480 from ()->end ();
18481 slurp->close ();
18482 slurped ();
18486 /* After a reading operation, make sure things are still ok. If not,
18487 emit an error and clean up. */
18489 bool
18490 module_state::check_read (bool outermost, bool ok)
18492 gcc_checking_assert (!outermost || slurp->current == ~0u);
18494 if (!ok)
18495 from ()->set_error ();
18497 if (int e = from ()->get_error ())
18499 error_at (loc, "failed to read compiled module: %s",
18500 from ()->get_error (filename));
18501 note_cmi_name ();
18503 if (e == EMFILE
18504 || e == ENFILE
18505 #if MAPPED_READING
18506 || e == ENOMEM
18507 #endif
18508 || false)
18509 inform (loc, "consider using %<-fno-module-lazy%>,"
18510 " increasing %<-param-lazy-modules=%u%> value,"
18511 " or increasing the per-process file descriptor limit",
18512 param_lazy_modules);
18513 else if (e == ENOENT)
18514 inform (loc, "imports must be built before being imported");
18516 if (outermost)
18517 fatal_error (loc, "returning to the gate for a mechanical issue");
18519 ok = false;
18522 maybe_completed_reading ();
18524 return ok;
18527 /* Return the IDENTIFIER_NODE naming module IX. This is the name
18528 including dots. */
18530 char const *
18531 module_name (unsigned ix, bool header_ok)
18533 if (modules)
18535 module_state *imp = (*modules)[ix];
18537 if (ix && !imp->name)
18538 imp = imp->parent;
18540 if (header_ok || !imp->is_header ())
18541 return imp->get_flatname ();
18544 return NULL;
18547 /* Return the bitmap describing what modules are imported. Remember,
18548 we always import ourselves. */
18550 bitmap
18551 get_import_bitmap ()
18553 return (*modules)[0]->imports;
18556 /* Return the visible imports and path of instantiation for an
18557 instantiation at TINST. If TINST is nullptr, we're not in an
18558 instantiation, and thus will return the visible imports of the
18559 current TU (and NULL *PATH_MAP_P). We cache the information on
18560 the tinst level itself. */
18562 static bitmap
18563 path_of_instantiation (tinst_level *tinst, bitmap *path_map_p)
18565 gcc_checking_assert (modules_p ());
18567 if (!tinst)
18569 /* Not inside an instantiation, just the regular case. */
18570 *path_map_p = nullptr;
18571 return get_import_bitmap ();
18574 if (!tinst->path)
18576 /* Calculate. */
18577 bitmap visible = path_of_instantiation (tinst->next, path_map_p);
18578 bitmap path_map = *path_map_p;
18580 if (!path_map)
18582 path_map = BITMAP_GGC_ALLOC ();
18583 bitmap_set_bit (path_map, 0);
18586 tree decl = tinst->tldcl;
18587 if (TREE_CODE (decl) == TREE_LIST)
18588 decl = TREE_PURPOSE (decl);
18589 if (TYPE_P (decl))
18590 decl = TYPE_NAME (decl);
18592 if (unsigned mod = get_originating_module (decl))
18593 if (!bitmap_bit_p (path_map, mod))
18595 /* This is brand new information! */
18596 bitmap new_path = BITMAP_GGC_ALLOC ();
18597 bitmap_copy (new_path, path_map);
18598 bitmap_set_bit (new_path, mod);
18599 path_map = new_path;
18601 bitmap imports = (*modules)[mod]->imports;
18602 if (bitmap_intersect_compl_p (imports, visible))
18604 /* IMPORTS contains additional modules to VISIBLE. */
18605 bitmap new_visible = BITMAP_GGC_ALLOC ();
18607 bitmap_ior (new_visible, visible, imports);
18608 visible = new_visible;
18612 tinst->path = path_map;
18613 tinst->visible = visible;
18616 *path_map_p = tinst->path;
18617 return tinst->visible;
18620 /* Return the bitmap describing what modules are visible along the
18621 path of instantiation. If we're not an instantiation, this will be
18622 the visible imports of the TU. *PATH_MAP_P is filled in with the
18623 modules owning the instantiation path -- we see the module-linkage
18624 entities of those modules. */
18626 bitmap
18627 visible_instantiation_path (bitmap *path_map_p)
18629 if (!modules_p ())
18630 return NULL;
18632 return path_of_instantiation (current_instantiation (), path_map_p);
18635 /* We've just directly imported IMPORT. Update our import/export
18636 bitmaps. IS_EXPORT is true if we're reexporting the OTHER. */
18638 void
18639 module_state::set_import (module_state const *import, bool is_export)
18641 gcc_checking_assert (this != import);
18643 /* We see IMPORT's exports (which includes IMPORT). If IMPORT is
18644 the primary interface or a partition we'll see its imports. */
18645 bitmap_ior_into (imports, import->is_module () || import->is_partition ()
18646 ? import->imports : import->exports);
18648 if (is_export)
18649 /* We'll export OTHER's exports. */
18650 bitmap_ior_into (exports, import->exports);
18653 /* Return the declaring entity of DECL. That is the decl determining
18654 how to decorate DECL with module information. Returns NULL_TREE if
18655 it's the global module. */
18657 tree
18658 get_originating_module_decl (tree decl)
18660 /* An enumeration constant. */
18661 if (TREE_CODE (decl) == CONST_DECL
18662 && DECL_CONTEXT (decl)
18663 && (TREE_CODE (DECL_CONTEXT (decl)) == ENUMERAL_TYPE))
18664 decl = TYPE_NAME (DECL_CONTEXT (decl));
18665 else if (TREE_CODE (decl) == FIELD_DECL
18666 || TREE_CODE (decl) == USING_DECL)
18668 decl = DECL_CONTEXT (decl);
18669 if (TREE_CODE (decl) != FUNCTION_DECL)
18670 decl = TYPE_NAME (decl);
18673 gcc_checking_assert (TREE_CODE (decl) == TEMPLATE_DECL
18674 || TREE_CODE (decl) == FUNCTION_DECL
18675 || TREE_CODE (decl) == TYPE_DECL
18676 || TREE_CODE (decl) == VAR_DECL
18677 || TREE_CODE (decl) == CONCEPT_DECL
18678 || TREE_CODE (decl) == NAMESPACE_DECL);
18680 for (;;)
18682 /* Uninstantiated template friends are owned by the befriending
18683 class -- not their context. */
18684 if (TREE_CODE (decl) == TEMPLATE_DECL
18685 && DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (decl))
18686 decl = TYPE_NAME (DECL_CHAIN (decl));
18688 int use;
18689 if (tree ti = node_template_info (decl, use))
18691 decl = TI_TEMPLATE (ti);
18692 if (TREE_CODE (decl) != TEMPLATE_DECL)
18694 /* A friend template specialization. */
18695 gcc_checking_assert (OVL_P (decl));
18696 return global_namespace;
18699 else
18701 tree ctx = CP_DECL_CONTEXT (decl);
18702 if (TREE_CODE (ctx) == NAMESPACE_DECL)
18703 break;
18705 if (TYPE_P (ctx))
18707 ctx = TYPE_NAME (ctx);
18708 if (!ctx)
18710 /* Some kind of internal type. */
18711 gcc_checking_assert (DECL_ARTIFICIAL (decl));
18712 return global_namespace;
18715 decl = ctx;
18719 return decl;
18723 get_originating_module (tree decl, bool for_mangle)
18725 tree owner = get_originating_module_decl (decl);
18726 tree not_tmpl = STRIP_TEMPLATE (owner);
18728 if (!DECL_LANG_SPECIFIC (not_tmpl))
18729 return for_mangle ? -1 : 0;
18731 if (for_mangle && !DECL_MODULE_ATTACH_P (not_tmpl))
18732 return -1;
18734 int mod = !DECL_MODULE_IMPORT_P (not_tmpl) ? 0 : get_importing_module (owner);
18735 gcc_checking_assert (!for_mangle || !(*modules)[mod]->is_header ());
18736 return mod;
18739 unsigned
18740 get_importing_module (tree decl, bool flexible)
18742 unsigned index = import_entity_index (decl, flexible);
18743 if (index == ~(~0u >> 1))
18744 return -1;
18745 module_state *module = import_entity_module (index);
18747 return module->mod;
18750 /* Is it permissible to redeclare DECL. */
18752 bool
18753 module_may_redeclare (tree decl)
18755 for (;;)
18757 tree ctx = CP_DECL_CONTEXT (decl);
18758 if (TREE_CODE (ctx) == NAMESPACE_DECL)
18759 // Found the namespace-scope decl.
18760 break;
18761 if (!CLASS_TYPE_P (ctx))
18762 // We've met a non-class scope. Such a thing is not
18763 // reopenable, so we must be ok.
18764 return true;
18765 decl = TYPE_NAME (ctx);
18768 tree not_tmpl = STRIP_TEMPLATE (decl);
18770 int use_tpl = 0;
18771 if (node_template_info (not_tmpl, use_tpl) && use_tpl)
18772 // Specializations of any kind can be redeclared anywhere.
18773 // FIXME: Should we be checking this in more places on the scope chain?
18774 return true;
18776 if (!DECL_LANG_SPECIFIC (not_tmpl) || !DECL_MODULE_ATTACH_P (not_tmpl))
18777 // Decl is attached to global module. Current scope needs to be too.
18778 return !module_attach_p ();
18780 module_state *me = (*modules)[0];
18781 module_state *them = me;
18783 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_IMPORT_P (not_tmpl))
18785 /* We can be given the TEMPLATE_RESULT. We want the
18786 TEMPLATE_DECL. */
18787 int use_tpl = -1;
18788 if (tree ti = node_template_info (decl, use_tpl))
18790 tree tmpl = TI_TEMPLATE (ti);
18791 if (use_tpl == 2)
18793 /* A partial specialization. Find that specialization's
18794 template_decl. */
18795 for (tree list = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
18796 list; list = TREE_CHAIN (list))
18797 if (DECL_TEMPLATE_RESULT (TREE_VALUE (list)) == decl)
18799 decl = TREE_VALUE (list);
18800 break;
18803 else if (DECL_TEMPLATE_RESULT (tmpl) == decl)
18804 decl = tmpl;
18806 unsigned index = import_entity_index (decl);
18807 them = import_entity_module (index);
18810 // Decl is attached to named module. Current scope needs to be
18811 // attaching to the same module.
18812 if (!module_attach_p ())
18813 return false;
18815 // Both attached to named module.
18816 if (me == them)
18817 return true;
18819 return me && get_primary (them) == get_primary (me);
18822 /* DECL is being created by this TU. Record it came from here. We
18823 record module purview, so we can see if partial or explicit
18824 specialization needs to be written out, even though its purviewness
18825 comes from the most general template. */
18827 void
18828 set_instantiating_module (tree decl)
18830 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
18831 || VAR_P (decl)
18832 || TREE_CODE (decl) == TYPE_DECL
18833 || TREE_CODE (decl) == CONCEPT_DECL
18834 || TREE_CODE (decl) == TEMPLATE_DECL
18835 || (TREE_CODE (decl) == NAMESPACE_DECL
18836 && DECL_NAMESPACE_ALIAS (decl)));
18838 if (!modules_p ())
18839 return;
18841 decl = STRIP_TEMPLATE (decl);
18843 if (!DECL_LANG_SPECIFIC (decl) && module_purview_p ())
18844 retrofit_lang_decl (decl);
18846 if (DECL_LANG_SPECIFIC (decl))
18848 DECL_MODULE_PURVIEW_P (decl) = module_purview_p ();
18849 /* If this was imported, we'll still be in the entity_hash. */
18850 DECL_MODULE_IMPORT_P (decl) = false;
18854 /* If DECL is a class member, whose class is not defined in this TU
18855 (it was imported), remember this decl. */
18857 void
18858 set_defining_module (tree decl)
18860 gcc_checking_assert (!DECL_LANG_SPECIFIC (decl)
18861 || !DECL_MODULE_IMPORT_P (decl));
18863 if (module_has_cmi_p ())
18865 tree ctx = DECL_CONTEXT (decl);
18866 if (ctx
18867 && (TREE_CODE (ctx) == RECORD_TYPE || TREE_CODE (ctx) == UNION_TYPE)
18868 && DECL_LANG_SPECIFIC (TYPE_NAME (ctx))
18869 && DECL_MODULE_IMPORT_P (TYPE_NAME (ctx)))
18871 /* This entity's context is from an import. We may need to
18872 record this entity to make sure we emit it in the CMI.
18873 Template specializations are in the template hash tables,
18874 so we don't need to record them here as well. */
18875 int use_tpl = -1;
18876 tree ti = node_template_info (decl, use_tpl);
18877 if (use_tpl <= 0)
18879 if (ti)
18881 gcc_checking_assert (!use_tpl);
18882 /* Get to the TEMPLATE_DECL. */
18883 decl = TI_TEMPLATE (ti);
18886 /* Record it on the class_members list. */
18887 vec_safe_push (class_members, decl);
18890 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18891 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
18892 /* This is a partial or explicit specialization. */
18893 vec_safe_push (partial_specializations, decl);
18897 void
18898 set_originating_module (tree decl, bool friend_p ATTRIBUTE_UNUSED)
18900 set_instantiating_module (decl);
18902 if (!DECL_NAMESPACE_SCOPE_P (decl))
18903 return;
18905 gcc_checking_assert (friend_p || decl == get_originating_module_decl (decl));
18907 if (module_attach_p ())
18909 retrofit_lang_decl (decl);
18910 DECL_MODULE_ATTACH_P (decl) = true;
18913 if (!module_exporting_p ())
18914 return;
18916 // FIXME: Check ill-formed linkage
18917 DECL_MODULE_EXPORT_P (decl) = true;
18920 /* DECL is keyed to CTX for odr purposes. */
18922 void
18923 maybe_key_decl (tree ctx, tree decl)
18925 if (!modules_p ())
18926 return;
18928 // FIXME: For now just deal with lambdas attached to var decls.
18929 // This might be sufficient?
18930 if (TREE_CODE (ctx) != VAR_DECL)
18931 return;
18933 if (!keyed_table)
18934 keyed_table = new keyed_map_t (EXPERIMENT (1, 400));
18936 auto &vec = keyed_table->get_or_insert (ctx);
18937 if (!vec.length ())
18939 retrofit_lang_decl (ctx);
18940 DECL_MODULE_KEYED_DECLS_P (ctx) = true;
18942 vec.safe_push (decl);
18945 /* Create the flat name string. It is simplest to have it handy. */
18947 void
18948 module_state::set_flatname ()
18950 gcc_checking_assert (!flatname);
18951 if (parent)
18953 auto_vec<tree,5> ids;
18954 size_t len = 0;
18955 char const *primary = NULL;
18956 size_t pfx_len = 0;
18958 for (module_state *probe = this;
18959 probe;
18960 probe = probe->parent)
18961 if (is_partition () && !probe->is_partition ())
18963 primary = probe->get_flatname ();
18964 pfx_len = strlen (primary);
18965 break;
18967 else
18969 ids.safe_push (probe->name);
18970 len += IDENTIFIER_LENGTH (probe->name) + 1;
18973 char *flat = XNEWVEC (char, pfx_len + len + is_partition ());
18974 flatname = flat;
18976 if (primary)
18978 memcpy (flat, primary, pfx_len);
18979 flat += pfx_len;
18980 *flat++ = ':';
18983 for (unsigned len = 0; ids.length ();)
18985 if (len)
18986 flat[len++] = '.';
18987 tree elt = ids.pop ();
18988 unsigned l = IDENTIFIER_LENGTH (elt);
18989 memcpy (flat + len, IDENTIFIER_POINTER (elt), l + 1);
18990 len += l;
18993 else if (is_header ())
18994 flatname = TREE_STRING_POINTER (name);
18995 else
18996 flatname = IDENTIFIER_POINTER (name);
18999 /* Read the CMI file for a module. */
19001 bool
19002 module_state::do_import (cpp_reader *reader, bool outermost)
19004 gcc_assert (global_namespace == current_scope () && loadedness == ML_NONE);
19006 loc = linemap_module_loc (line_table, loc, get_flatname ());
19008 if (lazy_open >= lazy_limit)
19009 freeze_an_elf ();
19011 int fd = -1;
19012 int e = ENOENT;
19013 if (filename)
19015 const char *file = maybe_add_cmi_prefix (filename);
19016 dump () && dump ("CMI is %s", file);
19017 if (note_module_cmi_yes || inform_cmi_p)
19018 inform (loc, "reading CMI %qs", file);
19019 /* Add the CMI file to the dependency tracking. */
19020 if (cpp_get_deps (reader))
19021 deps_add_dep (cpp_get_deps (reader), file);
19022 fd = open (file, O_RDONLY | O_CLOEXEC | O_BINARY);
19023 e = errno;
19026 gcc_checking_assert (!slurp);
19027 slurp = new slurping (new elf_in (fd, e));
19029 bool ok = true;
19030 if (!from ()->get_error ())
19032 announce ("importing");
19033 loadedness = ML_CONFIG;
19034 lazy_open++;
19035 ok = read_initial (reader);
19036 slurp->lru = ++lazy_lru;
19039 gcc_assert (slurp->current == ~0u);
19041 return check_read (outermost, ok);
19044 /* Attempt to increase the file descriptor limit. */
19046 static bool
19047 try_increase_lazy (unsigned want)
19049 gcc_checking_assert (lazy_open >= lazy_limit);
19051 /* If we're increasing, saturate at hard limit. */
19052 if (want > lazy_hard_limit && lazy_limit < lazy_hard_limit)
19053 want = lazy_hard_limit;
19055 #if HAVE_SETRLIMIT
19056 if ((!lazy_limit || !param_lazy_modules)
19057 && lazy_hard_limit
19058 && want <= lazy_hard_limit)
19060 struct rlimit rlimit;
19061 rlimit.rlim_cur = want + LAZY_HEADROOM;
19062 rlimit.rlim_max = lazy_hard_limit + LAZY_HEADROOM;
19063 if (!setrlimit (RLIMIT_NOFILE, &rlimit))
19064 lazy_limit = want;
19066 #endif
19068 return lazy_open < lazy_limit;
19071 /* Pick a victim module to freeze its reader. */
19073 void
19074 module_state::freeze_an_elf ()
19076 if (try_increase_lazy (lazy_open * 2))
19077 return;
19079 module_state *victim = NULL;
19080 for (unsigned ix = modules->length (); ix--;)
19082 module_state *candidate = (*modules)[ix];
19083 if (candidate && candidate->slurp && candidate->slurp->lru
19084 && candidate->from ()->is_freezable ()
19085 && (!victim || victim->slurp->lru > candidate->slurp->lru))
19086 victim = candidate;
19089 if (victim)
19091 dump () && dump ("Freezing '%s'", victim->filename);
19092 if (victim->slurp->macro_defs.size)
19093 /* Save the macro definitions to a buffer. */
19094 victim->from ()->preserve (victim->slurp->macro_defs);
19095 if (victim->slurp->macro_tbl.size)
19096 /* Save the macro definitions to a buffer. */
19097 victim->from ()->preserve (victim->slurp->macro_tbl);
19098 victim->from ()->freeze ();
19099 lazy_open--;
19101 else
19102 dump () && dump ("No module available for freezing");
19105 /* Load the lazy slot *MSLOT, INDEX'th slot of the module. */
19107 bool
19108 module_state::lazy_load (unsigned index, binding_slot *mslot)
19110 unsigned n = dump.push (this);
19112 gcc_checking_assert (function_depth);
19114 unsigned cookie = mslot->get_lazy ();
19115 unsigned snum = cookie >> 2;
19116 dump () && dump ("Loading entity %M[%u] section:%u", this, index, snum);
19118 bool ok = load_section (snum, mslot);
19120 dump.pop (n);
19122 return ok;
19125 /* Load MOD's binding for NS::ID into *MSLOT. *MSLOT contains the
19126 lazy cookie. OUTER is true if this is the outermost lazy, (used
19127 for diagnostics). */
19129 void
19130 lazy_load_binding (unsigned mod, tree ns, tree id, binding_slot *mslot)
19132 int count = errorcount + warningcount;
19134 timevar_start (TV_MODULE_IMPORT);
19136 /* Make sure lazy loading from a template context behaves as if
19137 from a non-template context. */
19138 processing_template_decl_sentinel ptds;
19140 /* Stop GC happening, even in outermost loads (because our caller
19141 could well be building up a lookup set). */
19142 function_depth++;
19144 gcc_checking_assert (mod);
19145 module_state *module = (*modules)[mod];
19146 unsigned n = dump.push (module);
19148 unsigned snum = mslot->get_lazy ();
19149 dump () && dump ("Lazily binding %P@%N section:%u", ns, id,
19150 module->name, snum);
19152 bool ok = !recursive_lazy (snum);
19153 if (ok)
19155 ok = module->load_section (snum, mslot);
19156 lazy_snum = 0;
19157 post_load_processing ();
19160 dump.pop (n);
19162 function_depth--;
19164 timevar_stop (TV_MODULE_IMPORT);
19166 if (!ok)
19167 fatal_error (input_location,
19168 module->is_header ()
19169 ? G_("failed to load binding %<%E%s%E%>")
19170 : G_("failed to load binding %<%E%s%E@%s%>"),
19171 ns, &"::"[ns == global_namespace ? 2 : 0], id,
19172 module->get_flatname ());
19174 if (count != errorcount + warningcount)
19175 inform (input_location,
19176 module->is_header ()
19177 ? G_("during load of binding %<%E%s%E%>")
19178 : G_("during load of binding %<%E%s%E@%s%>"),
19179 ns, &"::"[ns == global_namespace ? 2 : 0], id,
19180 module->get_flatname ());
19183 /* Load any pending entities keyed to the top-key of DECL. */
19185 void
19186 lazy_load_pendings (tree decl)
19188 /* Make sure lazy loading from a template context behaves as if
19189 from a non-template context. */
19190 processing_template_decl_sentinel ptds;
19192 tree key_decl;
19193 pending_key key;
19194 key.ns = find_pending_key (decl, &key_decl);
19195 key.id = DECL_NAME (key_decl);
19197 auto *pending_vec = pending_table ? pending_table->get (key) : nullptr;
19198 if (!pending_vec)
19199 return;
19201 int count = errorcount + warningcount;
19203 timevar_start (TV_MODULE_IMPORT);
19204 bool ok = !recursive_lazy ();
19205 if (ok)
19207 function_depth++; /* Prevent GC */
19208 unsigned n = dump.push (NULL);
19209 dump () && dump ("Reading %u pending entities keyed to %P",
19210 pending_vec->length (), key.ns, key.id);
19211 for (unsigned ix = pending_vec->length (); ix--;)
19213 unsigned index = (*pending_vec)[ix];
19214 binding_slot *slot = &(*entity_ary)[index];
19216 if (slot->is_lazy ())
19218 module_state *import = import_entity_module (index);
19219 if (!import->lazy_load (index - import->entity_lwm, slot))
19220 ok = false;
19222 else if (dump ())
19224 module_state *import = import_entity_module (index);
19225 dump () && dump ("Entity %M[%u] already loaded",
19226 import, index - import->entity_lwm);
19230 pending_table->remove (key);
19231 dump.pop (n);
19232 lazy_snum = 0;
19233 post_load_processing ();
19234 function_depth--;
19237 timevar_stop (TV_MODULE_IMPORT);
19239 if (!ok)
19240 fatal_error (input_location, "failed to load pendings for %<%E%s%E%>",
19241 key.ns, &"::"[key.ns == global_namespace ? 2 : 0], key.id);
19243 if (count != errorcount + warningcount)
19244 inform (input_location, "during load of pendings for %<%E%s%E%>",
19245 key.ns, &"::"[key.ns == global_namespace ? 2 : 0], key.id);
19248 static void
19249 direct_import (module_state *import, cpp_reader *reader)
19251 timevar_start (TV_MODULE_IMPORT);
19252 unsigned n = dump.push (import);
19254 gcc_checking_assert (import->is_direct () && import->has_location ());
19255 if (import->loadedness == ML_NONE)
19256 if (!import->do_import (reader, true))
19257 gcc_unreachable ();
19259 if (import->loadedness < ML_LANGUAGE)
19261 if (!keyed_table)
19262 keyed_table = new keyed_map_t (EXPERIMENT (1, 400));
19263 import->read_language (true);
19266 (*modules)[0]->set_import (import, import->exported_p);
19268 dump.pop (n);
19269 timevar_stop (TV_MODULE_IMPORT);
19272 /* Import module IMPORT. */
19274 void
19275 import_module (module_state *import, location_t from_loc, bool exporting_p,
19276 tree, cpp_reader *reader)
19278 if (!import->check_not_purview (from_loc))
19279 return;
19281 if (!import->is_header () && current_lang_depth ())
19282 /* Only header units should appear inside language
19283 specifications. The std doesn't specify this, but I think
19284 that's an error in resolving US 033, because language linkage
19285 is also our escape clause to getting things into the global
19286 module, so we don't want to confuse things by having to think
19287 about whether 'extern "C++" { import foo; }' puts foo's
19288 contents into the global module all of a sudden. */
19289 warning (0, "import of named module %qs inside language-linkage block",
19290 import->get_flatname ());
19292 if (exporting_p || module_exporting_p ())
19293 import->exported_p = true;
19295 if (import->loadedness != ML_NONE)
19297 from_loc = ordinary_loc_of (line_table, from_loc);
19298 linemap_module_reparent (line_table, import->loc, from_loc);
19300 gcc_checking_assert (!import->module_p);
19301 gcc_checking_assert (import->is_direct () && import->has_location ());
19303 direct_import (import, reader);
19306 /* Declare the name of the current module to be NAME. EXPORTING_p is
19307 true if this TU is the exporting module unit. */
19309 void
19310 declare_module (module_state *module, location_t from_loc, bool exporting_p,
19311 tree, cpp_reader *reader)
19313 gcc_assert (global_namespace == current_scope ());
19315 module_state *current = (*modules)[0];
19316 if (module_purview_p () || module->loadedness > ML_CONFIG)
19318 error_at (from_loc, module_purview_p ()
19319 ? G_("module already declared")
19320 : G_("module already imported"));
19321 if (module_purview_p ())
19322 module = current;
19323 inform (module->loc, module_purview_p ()
19324 ? G_("module %qs declared here")
19325 : G_("module %qs imported here"),
19326 module->get_flatname ());
19327 return;
19330 gcc_checking_assert (module->module_p);
19331 gcc_checking_assert (module->is_direct () && module->has_location ());
19333 /* Yer a module, 'arry. */
19334 module_kind = module->is_header () ? MK_HEADER : MK_NAMED | MK_ATTACH;
19336 // Even in header units, we consider the decls to be purview
19337 module_kind |= MK_PURVIEW;
19339 if (module->is_partition ())
19340 module_kind |= MK_PARTITION;
19341 if (exporting_p)
19343 module->interface_p = true;
19344 module_kind |= MK_INTERFACE;
19347 if (module_has_cmi_p ())
19349 /* Copy the importing information we may have already done. We
19350 do not need to separate out the imports that only happen in
19351 the GMF, inspite of what the literal wording of the std
19352 might imply. See p2191, the core list had a discussion
19353 where the module implementors agreed that the GMF of a named
19354 module is invisible to importers. */
19355 module->imports = current->imports;
19357 module->mod = 0;
19358 (*modules)[0] = module;
19360 else
19362 module->interface_p = true;
19363 current->parent = module; /* So mangler knows module identity. */
19364 direct_import (module, reader);
19368 /* Return true IFF we must emit a module global initializer function
19369 (which will be called by importers' init code). */
19371 bool
19372 module_global_init_needed ()
19374 return module_has_cmi_p () && !header_module_p ();
19377 /* Calculate which, if any, import initializers need calling. */
19379 bool
19380 module_determine_import_inits ()
19382 if (!modules || header_module_p ())
19383 return false;
19385 /* Prune active_init_p. We need the same bitmap allocation
19386 scheme as for the imports member. */
19387 function_depth++; /* Disable GC. */
19388 bitmap covered_imports (BITMAP_GGC_ALLOC ());
19390 bool any = false;
19392 /* Because indirect imports are before their direct import, and
19393 we're scanning the array backwards, we only need one pass! */
19394 for (unsigned ix = modules->length (); --ix;)
19396 module_state *import = (*modules)[ix];
19398 if (!import->active_init_p)
19400 else if (bitmap_bit_p (covered_imports, ix))
19401 import->active_init_p = false;
19402 else
19404 /* Everything this imports is therefore handled by its
19405 initializer, so doesn't need initializing by us. */
19406 bitmap_ior_into (covered_imports, import->imports);
19407 any = true;
19410 function_depth--;
19412 return any;
19415 /* Emit calls to each direct import's global initializer. Including
19416 direct imports of directly imported header units. The initializers
19417 of (static) entities in header units will be called by their
19418 importing modules (for the instance contained within that), or by
19419 the current TU (for the instances we've brought in). Of course
19420 such header unit behaviour is evil, but iostream went through that
19421 door some time ago. */
19423 void
19424 module_add_import_initializers ()
19426 if (!modules || header_module_p ())
19427 return;
19429 tree fntype = build_function_type (void_type_node, void_list_node);
19430 releasing_vec args; // There are no args
19432 for (unsigned ix = modules->length (); --ix;)
19434 module_state *import = (*modules)[ix];
19435 if (import->active_init_p)
19437 tree name = mangle_module_global_init (ix);
19438 tree fndecl = build_lang_decl (FUNCTION_DECL, name, fntype);
19440 DECL_CONTEXT (fndecl) = FROB_CONTEXT (global_namespace);
19441 SET_DECL_ASSEMBLER_NAME (fndecl, name);
19442 TREE_PUBLIC (fndecl) = true;
19443 determine_visibility (fndecl);
19445 tree call = cp_build_function_call_vec (fndecl, &args,
19446 tf_warning_or_error);
19447 finish_expr_stmt (call);
19452 /* NAME & LEN are a preprocessed header name, possibly including the
19453 surrounding "" or <> characters. Return the raw string name of the
19454 module to which it refers. This will be an absolute path, or begin
19455 with ./, so it is immediately distinguishable from a (non-header
19456 unit) module name. If READER is non-null, ask the preprocessor to
19457 locate the header to which it refers using the appropriate include
19458 path. Note that we do never do \ processing of the string, as that
19459 matches the preprocessor's behaviour. */
19461 static const char *
19462 canonicalize_header_name (cpp_reader *reader, location_t loc, bool unquoted,
19463 const char *str, size_t &len_r)
19465 size_t len = len_r;
19466 static char *buf = 0;
19467 static size_t alloc = 0;
19469 if (!unquoted)
19471 gcc_checking_assert (len >= 2
19472 && ((reader && str[0] == '<' && str[len-1] == '>')
19473 || (str[0] == '"' && str[len-1] == '"')));
19474 str += 1;
19475 len -= 2;
19478 if (reader)
19480 gcc_assert (!unquoted);
19482 if (len >= alloc)
19484 alloc = len + 1;
19485 buf = XRESIZEVEC (char, buf, alloc);
19487 memcpy (buf, str, len);
19488 buf[len] = 0;
19490 if (const char *hdr
19491 = cpp_probe_header_unit (reader, buf, str[-1] == '<', loc))
19493 len = strlen (hdr);
19494 str = hdr;
19496 else
19497 str = buf;
19500 if (!(str[0] == '.' ? IS_DIR_SEPARATOR (str[1]) : IS_ABSOLUTE_PATH (str)))
19502 /* Prepend './' */
19503 if (len + 3 > alloc)
19505 alloc = len + 3;
19506 buf = XRESIZEVEC (char, buf, alloc);
19509 buf[0] = '.';
19510 buf[1] = DIR_SEPARATOR;
19511 memmove (buf + 2, str, len);
19512 len += 2;
19513 buf[len] = 0;
19514 str = buf;
19517 len_r = len;
19518 return str;
19521 /* Set the CMI name from a cody packet. Issue an error if
19522 ill-formed. */
19524 void module_state::set_filename (const Cody::Packet &packet)
19526 gcc_checking_assert (!filename);
19527 if (packet.GetCode () == Cody::Client::PC_PATHNAME)
19528 filename = xstrdup (packet.GetString ().c_str ());
19529 else
19531 gcc_checking_assert (packet.GetCode () == Cody::Client::PC_ERROR);
19532 error_at (loc, "unknown Compiled Module Interface: %s",
19533 packet.GetString ().c_str ());
19537 /* Figure out whether to treat HEADER as an include or an import. */
19539 static char *
19540 maybe_translate_include (cpp_reader *reader, line_maps *lmaps, location_t loc,
19541 const char *path)
19543 if (!modules_p ())
19545 /* Turn off. */
19546 cpp_get_callbacks (reader)->translate_include = NULL;
19547 return nullptr;
19550 if (!spans.init_p ())
19551 /* Before the main file, don't divert. */
19552 return nullptr;
19554 dump.push (NULL);
19556 dump () && dump ("Checking include translation '%s'", path);
19557 auto *mapper = get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
19559 size_t len = strlen (path);
19560 path = canonicalize_header_name (NULL, loc, true, path, len);
19561 auto packet = mapper->IncludeTranslate (path, Cody::Flags::None, len);
19562 int xlate = false;
19563 if (packet.GetCode () == Cody::Client::PC_BOOL)
19564 xlate = -int (packet.GetInteger ());
19565 else if (packet.GetCode () == Cody::Client::PC_PATHNAME)
19567 /* Record the CMI name for when we do the import. */
19568 module_state *import = get_module (build_string (len, path));
19569 import->set_filename (packet);
19570 xlate = +1;
19572 else
19574 gcc_checking_assert (packet.GetCode () == Cody::Client::PC_ERROR);
19575 error_at (loc, "cannot determine %<#include%> translation of %s: %s",
19576 path, packet.GetString ().c_str ());
19579 bool note = false;
19580 if (note_include_translate_yes && xlate > 1)
19581 note = true;
19582 else if (note_include_translate_no && xlate == 0)
19583 note = true;
19584 else if (note_includes)
19585 /* We do not expect the note_includes vector to be large, so O(N)
19586 iteration. */
19587 for (unsigned ix = note_includes->length (); !note && ix--;)
19588 if (!strcmp ((*note_includes)[ix], path))
19589 note = true;
19591 if (note)
19592 inform (loc, xlate
19593 ? G_("include %qs translated to import")
19594 : G_("include %qs processed textually") , path);
19596 dump () && dump (xlate ? "Translating include to import"
19597 : "Keeping include as include");
19598 dump.pop (0);
19600 if (!(xlate > 0))
19601 return nullptr;
19603 /* Create the translation text. */
19604 loc = ordinary_loc_of (lmaps, loc);
19605 const line_map_ordinary *map
19606 = linemap_check_ordinary (linemap_lookup (lmaps, loc));
19607 unsigned col = SOURCE_COLUMN (map, loc);
19608 col -= (col != 0); /* Columns are 1-based. */
19610 unsigned alloc = len + col + 60;
19611 char *res = XNEWVEC (char, alloc);
19613 strcpy (res, "__import");
19614 unsigned actual = 8;
19615 if (col > actual)
19617 /* Pad out so the filename appears at the same position. */
19618 memset (res + actual, ' ', col - actual);
19619 actual = col;
19621 /* No need to encode characters, that's not how header names are
19622 handled. */
19623 actual += snprintf (res + actual, alloc - actual,
19624 "\"%s\" [[__translated]];\n", path);
19625 gcc_checking_assert (actual < alloc);
19627 /* cpplib will delete the buffer. */
19628 return res;
19631 static void
19632 begin_header_unit (cpp_reader *reader)
19634 /* Set the module header name from the main_input_filename. */
19635 const char *main = main_input_filename;
19636 size_t len = strlen (main);
19637 main = canonicalize_header_name (NULL, 0, true, main, len);
19638 module_state *module = get_module (build_string (len, main));
19640 preprocess_module (module, cpp_main_loc (reader), false, false, true, reader);
19643 /* We've just properly entered the main source file. I.e. after the
19644 command line, builtins and forced headers. Record the line map and
19645 location of this map. Note we may be called more than once. The
19646 first call sticks. */
19648 void
19649 module_begin_main_file (cpp_reader *reader, line_maps *lmaps,
19650 const line_map_ordinary *map)
19652 gcc_checking_assert (lmaps == line_table);
19653 if (modules_p () && !spans.init_p ())
19655 unsigned n = dump.push (NULL);
19656 spans.init (lmaps, map);
19657 dump.pop (n);
19658 if (flag_header_unit && !cpp_get_options (reader)->preprocessed)
19660 /* Tell the preprocessor this is an include file. */
19661 cpp_retrofit_as_include (reader);
19662 begin_header_unit (reader);
19667 /* Process the pending_import queue, making sure we know the
19668 filenames. */
19670 static void
19671 name_pending_imports (cpp_reader *reader)
19673 auto *mapper = get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
19675 if (!vec_safe_length (pending_imports))
19676 /* Not doing anything. */
19677 return;
19679 timevar_start (TV_MODULE_MAPPER);
19681 auto n = dump.push (NULL);
19682 dump () && dump ("Resolving direct import names");
19683 bool want_deps = (bool (mapper->get_flags () & Cody::Flags::NameOnly)
19684 || cpp_get_deps (reader));
19685 bool any = false;
19687 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
19689 module_state *module = (*pending_imports)[ix];
19690 gcc_checking_assert (module->is_direct ());
19691 if (!module->filename && !module->visited_p)
19693 bool export_p = (module->module_p
19694 && (module->is_partition () || module->exported_p));
19696 Cody::Flags flags = Cody::Flags::None;
19697 if (flag_preprocess_only
19698 && !(module->is_header () && !export_p))
19700 if (!want_deps)
19701 continue;
19702 flags = Cody::Flags::NameOnly;
19705 if (!any)
19707 any = true;
19708 mapper->Cork ();
19710 if (export_p)
19711 mapper->ModuleExport (module->get_flatname (), flags);
19712 else
19713 mapper->ModuleImport (module->get_flatname (), flags);
19714 module->visited_p = true;
19718 if (any)
19720 auto response = mapper->Uncork ();
19721 auto r_iter = response.begin ();
19722 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
19724 module_state *module = (*pending_imports)[ix];
19725 if (module->visited_p)
19727 module->visited_p = false;
19728 gcc_checking_assert (!module->filename);
19730 module->set_filename (*r_iter);
19731 ++r_iter;
19736 dump.pop (n);
19738 timevar_stop (TV_MODULE_MAPPER);
19741 /* We've just lexed a module-specific control line for MODULE. Mark
19742 the module as a direct import, and possibly load up its macro
19743 state. Returns the primary module, if this is a module
19744 declaration. */
19745 /* Perhaps we should offer a preprocessing mode where we read the
19746 directives from the header unit, rather than require the header's
19747 CMI. */
19749 module_state *
19750 preprocess_module (module_state *module, location_t from_loc,
19751 bool in_purview, bool is_import, bool is_export,
19752 cpp_reader *reader)
19754 if (!is_import)
19756 if (module->loc)
19757 /* It's already been mentioned, so ignore its module-ness. */
19758 is_import = true;
19759 else
19761 /* Record it is the module. */
19762 module->module_p = true;
19763 if (is_export)
19765 module->exported_p = true;
19766 module->interface_p = true;
19771 if (module->directness < MD_DIRECT + in_purview)
19773 /* Mark as a direct import. */
19774 module->directness = module_directness (MD_DIRECT + in_purview);
19776 /* Set the location to be most informative for users. */
19777 from_loc = ordinary_loc_of (line_table, from_loc);
19778 if (module->loadedness != ML_NONE)
19779 linemap_module_reparent (line_table, module->loc, from_loc);
19780 else
19782 module->loc = from_loc;
19783 if (!module->flatname)
19784 module->set_flatname ();
19788 auto desired = ML_CONFIG;
19789 if (is_import
19790 && module->is_header ()
19791 && (!cpp_get_options (reader)->preprocessed
19792 || cpp_get_options (reader)->directives_only))
19793 /* We need preprocessor state now. */
19794 desired = ML_PREPROCESSOR;
19796 if (!is_import || module->loadedness < desired)
19798 vec_safe_push (pending_imports, module);
19800 if (desired == ML_PREPROCESSOR)
19802 unsigned n = dump.push (NULL);
19804 dump () && dump ("Reading %M preprocessor state", module);
19805 name_pending_imports (reader);
19807 /* Preserve the state of the line-map. */
19808 unsigned pre_hwm = LINEMAPS_ORDINARY_USED (line_table);
19810 /* We only need to close the span, if we're going to emit a
19811 CMI. But that's a little tricky -- our token scanner
19812 needs to be smarter -- and this isn't much state.
19813 Remember, we've not parsed anything at this point, so
19814 our module state flags are inadequate. */
19815 spans.maybe_init ();
19816 spans.close ();
19818 timevar_start (TV_MODULE_IMPORT);
19820 /* Load the config of each pending import -- we must assign
19821 module numbers monotonically. */
19822 for (unsigned ix = 0; ix != pending_imports->length (); ix++)
19824 auto *import = (*pending_imports)[ix];
19825 if (!(import->module_p
19826 && (import->is_partition () || import->exported_p))
19827 && import->loadedness == ML_NONE
19828 && (import->is_header () || !flag_preprocess_only))
19830 unsigned n = dump.push (import);
19831 import->do_import (reader, true);
19832 dump.pop (n);
19835 vec_free (pending_imports);
19837 /* Restore the line-map state. */
19838 spans.open (linemap_module_restore (line_table, pre_hwm));
19840 /* Now read the preprocessor state of this particular
19841 import. */
19842 if (module->loadedness == ML_CONFIG
19843 && module->read_preprocessor (true))
19844 module->import_macros ();
19846 timevar_stop (TV_MODULE_IMPORT);
19848 dump.pop (n);
19852 return is_import ? NULL : get_primary (module);
19855 /* We've completed phase-4 translation. Emit any dependency
19856 information for the not-yet-loaded direct imports, and fill in
19857 their file names. We'll have already loaded up the direct header
19858 unit wavefront. */
19860 void
19861 preprocessed_module (cpp_reader *reader)
19863 unsigned n = dump.push (NULL);
19865 dump () && dump ("Completed phase-4 (tokenization) processing");
19867 name_pending_imports (reader);
19868 vec_free (pending_imports);
19870 spans.maybe_init ();
19871 spans.close ();
19873 using iterator = hash_table<module_state_hash>::iterator;
19874 if (mkdeps *deps = cpp_get_deps (reader))
19876 /* Walk the module hash, informing the dependency machinery. */
19877 iterator end = modules_hash->end ();
19878 for (iterator iter = modules_hash->begin (); iter != end; ++iter)
19880 module_state *module = *iter;
19882 if (module->is_direct ())
19884 if (module->is_module ()
19885 && (module->is_interface () || module->is_partition ()))
19886 deps_add_module_target (deps, module->get_flatname (),
19887 maybe_add_cmi_prefix (module->filename),
19888 module->is_header (),
19889 module->is_exported ());
19890 else
19891 deps_add_module_dep (deps, module->get_flatname ());
19896 if (flag_header_unit && !flag_preprocess_only)
19898 /* Find the main module -- remember, it's not yet in the module
19899 array. */
19900 iterator end = modules_hash->end ();
19901 for (iterator iter = modules_hash->begin (); iter != end; ++iter)
19903 module_state *module = *iter;
19904 if (module->is_module ())
19906 declare_module (module, cpp_main_loc (reader), true, NULL, reader);
19907 module_kind |= MK_EXPORTING;
19908 break;
19913 dump.pop (n);
19916 /* VAL is a global tree, add it to the global vec if it is
19917 interesting. Add some of its targets, if they too are
19918 interesting. We do not add identifiers, as they can be re-found
19919 via the identifier hash table. There is a cost to the number of
19920 global trees. */
19922 static int
19923 maybe_add_global (tree val, unsigned &crc)
19925 int v = 0;
19927 if (val && !(identifier_p (val) || TREE_VISITED (val)))
19929 TREE_VISITED (val) = true;
19930 crc = crc32_unsigned (crc, fixed_trees->length ());
19931 vec_safe_push (fixed_trees, val);
19932 v++;
19934 if (CODE_CONTAINS_STRUCT (TREE_CODE (val), TS_TYPED))
19935 v += maybe_add_global (TREE_TYPE (val), crc);
19936 if (CODE_CONTAINS_STRUCT (TREE_CODE (val), TS_TYPE_COMMON))
19937 v += maybe_add_global (TYPE_NAME (val), crc);
19940 return v;
19943 /* Initialize module state. Create the hash table, determine the
19944 global trees. Create the module for current TU. */
19946 void
19947 init_modules (cpp_reader *reader)
19949 /* PCH should not be reachable because of lang-specs, but the
19950 user could have overriden that. */
19951 if (pch_file)
19952 fatal_error (input_location,
19953 "C++ modules are incompatible with precompiled headers");
19955 if (cpp_get_options (reader)->traditional)
19956 fatal_error (input_location,
19957 "C++ modules are incompatible with traditional preprocessing");
19959 if (flag_preprocess_only)
19961 cpp_options *cpp_opts = cpp_get_options (reader);
19962 if (flag_no_output
19963 || (cpp_opts->deps.style != DEPS_NONE
19964 && !cpp_opts->deps.need_preprocessor_output))
19966 warning (0, flag_dump_macros == 'M'
19967 ? G_("macro debug output may be incomplete with modules")
19968 : G_("module dependencies require preprocessing"));
19969 if (cpp_opts->deps.style != DEPS_NONE)
19970 inform (input_location, "you should use the %<-%s%> option",
19971 cpp_opts->deps.style == DEPS_SYSTEM ? "MD" : "MMD");
19975 /* :: is always exported. */
19976 DECL_MODULE_EXPORT_P (global_namespace) = true;
19978 modules_hash = hash_table<module_state_hash>::create_ggc (31);
19979 vec_safe_reserve (modules, 20);
19981 /* Create module for current TU. */
19982 module_state *current
19983 = new (ggc_alloc<module_state> ()) module_state (NULL_TREE, NULL, false);
19984 current->mod = 0;
19985 bitmap_set_bit (current->imports, 0);
19986 modules->quick_push (current);
19988 gcc_checking_assert (!fixed_trees);
19990 headers = BITMAP_GGC_ALLOC ();
19992 if (note_includes)
19993 /* Canonicalize header names. */
19994 for (unsigned ix = 0; ix != note_includes->length (); ix++)
19996 const char *hdr = (*note_includes)[ix];
19997 size_t len = strlen (hdr);
19999 bool system = hdr[0] == '<';
20000 bool user = hdr[0] == '"';
20001 bool delimed = system || user;
20003 if (len <= (delimed ? 2 : 0)
20004 || (delimed && hdr[len-1] != (system ? '>' : '"')))
20005 error ("invalid header name %qs", hdr);
20007 hdr = canonicalize_header_name (delimed ? reader : NULL,
20008 0, !delimed, hdr, len);
20009 char *path = XNEWVEC (char, len + 1);
20010 memcpy (path, hdr, len);
20011 path[len] = 0;
20013 (*note_includes)[ix] = path;
20016 if (note_cmis)
20017 /* Canonicalize & mark module names. */
20018 for (unsigned ix = 0; ix != note_cmis->length (); ix++)
20020 const char *name = (*note_cmis)[ix];
20021 size_t len = strlen (name);
20023 bool is_system = name[0] == '<';
20024 bool is_user = name[0] == '"';
20025 bool is_pathname = false;
20026 if (!(is_system || is_user))
20027 for (unsigned ix = len; !is_pathname && ix--;)
20028 is_pathname = IS_DIR_SEPARATOR (name[ix]);
20029 if (is_system || is_user || is_pathname)
20031 if (len <= (is_pathname ? 0 : 2)
20032 || (!is_pathname && name[len-1] != (is_system ? '>' : '"')))
20034 error ("invalid header name %qs", name);
20035 continue;
20037 else
20038 name = canonicalize_header_name (is_pathname ? nullptr : reader,
20039 0, is_pathname, name, len);
20041 if (auto module = get_module (name))
20042 module->inform_cmi_p = 1;
20043 else
20044 error ("invalid module name %qs", name);
20047 dump.push (NULL);
20049 /* Determine lazy handle bound. */
20051 unsigned limit = 1000;
20052 #if HAVE_GETRLIMIT
20053 struct rlimit rlimit;
20054 if (!getrlimit (RLIMIT_NOFILE, &rlimit))
20056 lazy_hard_limit = (rlimit.rlim_max < 1000000
20057 ? unsigned (rlimit.rlim_max) : 1000000);
20058 lazy_hard_limit = (lazy_hard_limit > LAZY_HEADROOM
20059 ? lazy_hard_limit - LAZY_HEADROOM : 0);
20060 if (rlimit.rlim_cur < limit)
20061 limit = unsigned (rlimit.rlim_cur);
20063 #endif
20064 limit = limit > LAZY_HEADROOM ? limit - LAZY_HEADROOM : 1;
20066 if (unsigned parm = param_lazy_modules)
20068 if (parm <= limit || !lazy_hard_limit || !try_increase_lazy (parm))
20069 lazy_limit = parm;
20071 else
20072 lazy_limit = limit;
20075 if (dump ())
20077 verstr_t ver;
20078 version2string (MODULE_VERSION, ver);
20079 dump ("Source: %s", main_input_filename);
20080 dump ("Compiler: %s", version_string);
20081 dump ("Modules: %s", ver);
20082 dump ("Checking: %s",
20083 #if CHECKING_P
20084 "checking"
20085 #elif ENABLE_ASSERT_CHECKING
20086 "asserting"
20087 #else
20088 "release"
20089 #endif
20091 dump ("Compiled by: "
20092 #ifdef __GNUC__
20093 "GCC %d.%d, %s", __GNUC__, __GNUC_MINOR__,
20094 #ifdef __OPTIMIZE__
20095 "optimizing"
20096 #else
20097 "not optimizing"
20098 #endif
20099 #else
20100 "not GCC"
20101 #endif
20103 dump ("Reading: %s", MAPPED_READING ? "mmap" : "fileio");
20104 dump ("Writing: %s", MAPPED_WRITING ? "mmap" : "fileio");
20105 dump ("Lazy limit: %u", lazy_limit);
20106 dump ("Lazy hard limit: %u", lazy_hard_limit);
20107 dump ("");
20110 /* Construct the global tree array. This is an array of unique
20111 global trees (& types). Do this now, rather than lazily, as
20112 some global trees are lazily created and we don't want that to
20113 mess with our syndrome of fixed trees. */
20114 unsigned crc = 0;
20115 vec_alloc (fixed_trees, 200);
20117 dump () && dump ("+Creating globals");
20118 /* Insert the TRANSLATION_UNIT_DECL. */
20119 TREE_VISITED (DECL_CONTEXT (global_namespace)) = true;
20120 fixed_trees->quick_push (DECL_CONTEXT (global_namespace));
20121 for (unsigned jx = 0; global_tree_arys[jx].first; jx++)
20123 const tree *ptr = global_tree_arys[jx].first;
20124 unsigned limit = global_tree_arys[jx].second;
20126 for (unsigned ix = 0; ix != limit; ix++, ptr++)
20128 !(ix & 31) && dump ("") && dump ("+\t%u:%u:", jx, ix);
20129 unsigned v = maybe_add_global (*ptr, crc);
20130 dump () && dump ("+%u", v);
20133 global_crc = crc32_unsigned (crc, fixed_trees->length ());
20134 dump ("") && dump ("Created %u unique globals, crc=%x",
20135 fixed_trees->length (), global_crc);
20136 for (unsigned ix = fixed_trees->length (); ix--;)
20137 TREE_VISITED ((*fixed_trees)[ix]) = false;
20139 dump.pop (0);
20141 if (!flag_module_lazy)
20142 /* Get the mapper now, if we're not being lazy. */
20143 get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
20145 if (!flag_preprocess_only)
20147 pending_table = new pending_map_t (EXPERIMENT (1, 400));
20148 entity_map = new entity_map_t (EXPERIMENT (1, 400));
20149 vec_safe_reserve (entity_ary, EXPERIMENT (1, 400));
20152 #if CHECKING_P
20153 note_defs = note_defs_table_t::create_ggc (1000);
20154 #endif
20156 if (flag_header_unit && cpp_get_options (reader)->preprocessed)
20157 begin_header_unit (reader);
20159 /* Collect here to make sure things are tagged correctly (when
20160 aggressively GC'd). */
20161 ggc_collect ();
20164 /* If NODE is a deferred macro, load it. */
20166 static int
20167 load_macros (cpp_reader *reader, cpp_hashnode *node, void *)
20169 location_t main_loc
20170 = MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (line_table, 0));
20172 if (cpp_user_macro_p (node)
20173 && !node->value.macro)
20175 cpp_macro *macro = cpp_get_deferred_macro (reader, node, main_loc);
20176 dump () && dump ("Loaded macro #%s %I",
20177 macro ? "define" : "undef", identifier (node));
20180 return 1;
20183 /* At the end of tokenizing, we no longer need the macro tables of
20184 imports. But the user might have requested some checking. */
20186 void
20187 maybe_check_all_macros (cpp_reader *reader)
20189 if (!warn_imported_macros)
20190 return;
20192 /* Force loading of any remaining deferred macros. This will
20193 produce diagnostics if they are ill-formed. */
20194 unsigned n = dump.push (NULL);
20195 cpp_forall_identifiers (reader, load_macros, NULL);
20196 dump.pop (n);
20199 // State propagated from finish_module_processing to fini_modules
20201 struct module_processing_cookie
20203 elf_out out;
20204 module_state_config config;
20205 char *cmi_name;
20206 char *tmp_name;
20207 unsigned crc;
20208 bool began;
20210 module_processing_cookie (char *cmi, char *tmp, int fd, int e)
20211 : out (fd, e), cmi_name (cmi), tmp_name (tmp), crc (0), began (false)
20214 ~module_processing_cookie ()
20216 XDELETEVEC (tmp_name);
20217 XDELETEVEC (cmi_name);
20221 /* Write the CMI, if we're a module interface. */
20223 void *
20224 finish_module_processing (cpp_reader *reader)
20226 module_processing_cookie *cookie = nullptr;
20228 if (header_module_p ())
20229 module_kind &= ~MK_EXPORTING;
20231 if (!modules || !(*modules)[0]->name)
20233 if (flag_module_only)
20234 warning (0, "%<-fmodule-only%> used for non-interface");
20236 else if (!flag_syntax_only)
20238 int fd = -1;
20239 int e = -1;
20241 timevar_start (TV_MODULE_EXPORT);
20243 /* Force a valid but empty line map at the end. This simplifies
20244 the line table preparation and writing logic. */
20245 linemap_add (line_table, LC_ENTER, false, "", 0);
20247 /* We write to a tmpname, and then atomically rename. */
20248 char *cmi_name = NULL;
20249 char *tmp_name = NULL;
20250 module_state *state = (*modules)[0];
20252 unsigned n = dump.push (state);
20253 state->announce ("creating");
20254 if (state->filename)
20256 size_t len = 0;
20257 cmi_name = xstrdup (maybe_add_cmi_prefix (state->filename, &len));
20258 tmp_name = XNEWVEC (char, len + 3);
20259 memcpy (tmp_name, cmi_name, len);
20260 strcpy (&tmp_name[len], "~");
20262 if (!errorcount)
20263 for (unsigned again = 2; ; again--)
20265 fd = open (tmp_name,
20266 O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY,
20267 S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
20268 e = errno;
20269 if (fd >= 0 || !again || e != ENOENT)
20270 break;
20271 create_dirs (tmp_name);
20273 if (note_module_cmi_yes || state->inform_cmi_p)
20274 inform (state->loc, "writing CMI %qs", cmi_name);
20275 dump () && dump ("CMI is %s", cmi_name);
20278 cookie = new module_processing_cookie (cmi_name, tmp_name, fd, e);
20280 if (errorcount)
20281 warning_at (state->loc, 0, "not writing module %qs due to errors",
20282 state->get_flatname ());
20283 else if (cookie->out.begin ())
20285 cookie->began = true;
20286 auto loc = input_location;
20287 /* So crashes finger-point the module decl. */
20288 input_location = state->loc;
20289 state->write_begin (&cookie->out, reader, cookie->config, cookie->crc);
20290 input_location = loc;
20293 dump.pop (n);
20294 timevar_stop (TV_MODULE_EXPORT);
20296 ggc_collect ();
20299 if (modules)
20301 unsigned n = dump.push (NULL);
20302 dump () && dump ("Imported %u modules", modules->length () - 1);
20303 dump () && dump ("Containing %u clusters", available_clusters);
20304 dump () && dump ("Loaded %u clusters (%u%%)", loaded_clusters,
20305 (loaded_clusters * 100 + available_clusters / 2) /
20306 (available_clusters + !available_clusters));
20307 dump.pop (n);
20310 return cookie;
20313 // Do the final emission of a module. At this point we know whether
20314 // the module static initializer is a NOP or not.
20316 static void
20317 late_finish_module (cpp_reader *reader, module_processing_cookie *cookie,
20318 bool init_fn_non_empty)
20320 timevar_start (TV_MODULE_EXPORT);
20322 module_state *state = (*modules)[0];
20323 unsigned n = dump.push (state);
20324 state->announce ("finishing");
20326 cookie->config.active_init = init_fn_non_empty;
20327 if (cookie->began)
20328 state->write_end (&cookie->out, reader, cookie->config, cookie->crc);
20330 if (cookie->out.end () && cookie->cmi_name)
20332 /* Some OS's do not replace NEWNAME if it already exists.
20333 This'll have a race condition in erroneous concurrent
20334 builds. */
20335 unlink (cookie->cmi_name);
20336 if (rename (cookie->tmp_name, cookie->cmi_name))
20338 dump () && dump ("Rename ('%s','%s') errno=%u",
20339 cookie->tmp_name, cookie->cmi_name, errno);
20340 cookie->out.set_error (errno);
20344 if (cookie->out.get_error () && cookie->began)
20346 error_at (state->loc, "failed to write compiled module: %s",
20347 cookie->out.get_error (state->filename));
20348 state->note_cmi_name ();
20351 if (!errorcount)
20353 auto *mapper = get_mapper (cpp_main_loc (reader), cpp_get_deps (reader));
20354 mapper->ModuleCompiled (state->get_flatname ());
20356 else if (cookie->cmi_name)
20358 /* We failed, attempt to erase all evidence we even tried. */
20359 unlink (cookie->tmp_name);
20360 unlink (cookie->cmi_name);
20363 delete cookie;
20364 dump.pop (n);
20365 timevar_stop (TV_MODULE_EXPORT);
20368 void
20369 fini_modules (cpp_reader *reader, void *cookie, bool has_inits)
20371 if (cookie)
20372 late_finish_module (reader,
20373 static_cast<module_processing_cookie *> (cookie),
20374 has_inits);
20376 /* We're done with the macro tables now. */
20377 vec_free (macro_exports);
20378 vec_free (macro_imports);
20379 headers = NULL;
20381 /* We're now done with everything but the module names. */
20382 set_cmi_repo (NULL);
20383 if (mapper)
20385 timevar_start (TV_MODULE_MAPPER);
20386 module_client::close_module_client (0, mapper);
20387 mapper = nullptr;
20388 timevar_stop (TV_MODULE_MAPPER);
20390 module_state_config::release ();
20392 #if CHECKING_P
20393 note_defs = NULL;
20394 #endif
20396 if (modules)
20397 for (unsigned ix = modules->length (); --ix;)
20398 if (module_state *state = (*modules)[ix])
20399 state->release ();
20401 /* No need to lookup modules anymore. */
20402 modules_hash = NULL;
20404 /* Or entity array. We still need the entity map to find import numbers. */
20405 vec_free (entity_ary);
20406 entity_ary = NULL;
20408 /* Or remember any pending entities. */
20409 delete pending_table;
20410 pending_table = NULL;
20412 /* Or any keys -- Let it go! */
20413 delete keyed_table;
20414 keyed_table = NULL;
20416 /* Allow a GC, we've possibly made much data unreachable. */
20417 ggc_collect ();
20420 /* If CODE is a module option, handle it & return true. Otherwise
20421 return false. For unknown reasons I cannot get the option
20422 generation machinery to set fmodule-mapper or -fmodule-header to
20423 make a string type option variable. */
20425 bool
20426 handle_module_option (unsigned code, const char *str, int)
20428 auto hdr = CMS_header;
20430 switch (opt_code (code))
20432 case OPT_fmodule_mapper_:
20433 module_mapper_name = str;
20434 return true;
20436 case OPT_fmodule_header_:
20438 if (!strcmp (str, "user"))
20439 hdr = CMS_user;
20440 else if (!strcmp (str, "system"))
20441 hdr = CMS_system;
20442 else
20443 error ("unknown header kind %qs", str);
20445 /* Fallthrough. */
20447 case OPT_fmodule_header:
20448 flag_header_unit = hdr;
20449 flag_modules = 1;
20450 return true;
20452 case OPT_flang_info_include_translate_:
20453 vec_safe_push (note_includes, str);
20454 return true;
20456 case OPT_flang_info_module_cmi_:
20457 vec_safe_push (note_cmis, str);
20458 return true;
20460 default:
20461 return false;
20465 /* Set preprocessor callbacks and options for modules. */
20467 void
20468 module_preprocess_options (cpp_reader *reader)
20470 gcc_checking_assert (!lang_hooks.preprocess_undef);
20471 if (modules_p ())
20473 auto *cb = cpp_get_callbacks (reader);
20475 cb->translate_include = maybe_translate_include;
20476 cb->user_deferred_macro = module_state::deferred_macro;
20477 if (flag_header_unit)
20479 /* If the preprocessor hook is already in use, that
20480 implementation will call the undef langhook. */
20481 if (cb->undef)
20482 lang_hooks.preprocess_undef = module_state::undef_macro;
20483 else
20484 cb->undef = module_state::undef_macro;
20486 auto *opt = cpp_get_options (reader);
20487 opt->module_directives = true;
20488 opt->main_search = cpp_main_search (flag_header_unit);
20492 #include "gt-cp-module.h"