struct / union in initializer, RFE #901.
[sdcc.git] / sdcc / support / cpp / gcc / ggc-common.cc
blob4236267230fd0033b136958b068cf61404ce7110
1 /* Simple garbage collection for the GNU compiler.
2 Copyright (C) 1999-2022 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* Generic garbage collection (GC) functions and data, not specific to
21 any particular GC implementation. */
23 #include "config.h"
24 #define INCLUDE_MALLOC_H
25 #include "system.h"
26 #include "coretypes.h"
27 #include "timevar.h"
28 #include "diagnostic-core.h"
29 #include "ggc-internal.h"
30 #include "hosthooks.h"
31 #include "plugin.h"
32 #include "options.h"
34 /* When true, protect the contents of the identifier hash table. */
35 bool ggc_protect_identifiers = true;
37 /* Statistics about the allocation. */
38 static ggc_statistics *ggc_stats;
40 struct traversal_state;
42 #if 0 // sdcpp
43 static int compare_ptr_data (const void *, const void *);
44 static void relocate_ptrs (void *, void *, void *);
45 static void write_pch_globals (const struct ggc_root_tab * const *tab,
46 struct traversal_state *state);
47 #endif // sdcpp
49 /* Maintain global roots that are preserved during GC. */
51 /* This extra vector of dynamically registered root_tab-s is used by
52 ggc_mark_roots and gives the ability to dynamically add new GGC root
53 tables, for instance from some plugins; this vector is on the heap
54 since it is used by GGC internally. */
55 typedef const struct ggc_root_tab *const_ggc_root_tab_t;
56 static vec<const_ggc_root_tab_t> extra_root_vec;
58 /* Dynamically register a new GGC root table RT. This is useful for
59 plugins. */
61 void
62 ggc_register_root_tab (const struct ggc_root_tab* rt)
64 if (rt)
65 extra_root_vec.safe_push (rt);
68 /* Mark all the roots in the table RT. */
70 static void
71 ggc_mark_root_tab (const_ggc_root_tab_t rt)
73 size_t i;
75 for ( ; rt->base != NULL; rt++)
76 for (i = 0; i < rt->nelt; i++)
77 (*rt->cb) (*(void **) ((char *)rt->base + rt->stride * i));
80 /* Iterate through all registered roots and mark each element. */
82 void
83 ggc_mark_roots (void)
85 const struct ggc_root_tab *const *rt;
86 const_ggc_root_tab_t rtp, rti;
87 size_t i;
89 for (rt = gt_ggc_deletable_rtab; *rt; rt++)
90 for (rti = *rt; rti->base != NULL; rti++)
91 memset (rti->base, 0, rti->stride);
93 for (rt = gt_ggc_rtab; *rt; rt++)
94 ggc_mark_root_tab (*rt);
96 FOR_EACH_VEC_ELT (extra_root_vec, i, rtp)
97 ggc_mark_root_tab (rtp);
99 if (ggc_protect_identifiers)
100 ggc_mark_stringpool ();
102 gt_clear_caches ();
104 if (! ggc_protect_identifiers)
105 ggc_purge_stringpool ();
107 /* Some plugins may call ggc_set_mark from here. */
108 invoke_plugin_callbacks (PLUGIN_GGC_MARKING, NULL);
111 /* Allocate a block of memory, then clear it. */
112 void *
113 ggc_internal_cleared_alloc (size_t size, void (*f)(void *), size_t s, size_t n
114 MEM_STAT_DECL)
116 void *buf = ggc_internal_alloc (size, f, s, n PASS_MEM_STAT);
117 memset (buf, 0, size);
118 return buf;
121 /* Resize a block of memory, possibly re-allocating it. */
122 void *
123 ggc_realloc (void *x, size_t size MEM_STAT_DECL)
125 void *r;
126 size_t old_size;
128 if (x == NULL)
129 return ggc_internal_alloc (size PASS_MEM_STAT);
131 old_size = ggc_get_size (x);
133 if (size <= old_size)
135 /* Mark the unwanted memory as unaccessible. We also need to make
136 the "new" size accessible, since ggc_get_size returns the size of
137 the pool, not the size of the individually allocated object, the
138 size which was previously made accessible. Unfortunately, we
139 don't know that previously allocated size. Without that
140 knowledge we have to lose some initialization-tracking for the
141 old parts of the object. An alternative is to mark the whole
142 old_size as reachable, but that would lose tracking of writes
143 after the end of the object (by small offsets). Discard the
144 handle to avoid handle leak. */
145 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS ((char *) x + size,
146 old_size - size));
147 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (x, size));
148 return x;
151 r = ggc_internal_alloc (size PASS_MEM_STAT);
153 /* Since ggc_get_size returns the size of the pool, not the size of the
154 individually allocated object, we'd access parts of the old object
155 that were marked invalid with the memcpy below. We lose a bit of the
156 initialization-tracking since some of it may be uninitialized. */
157 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (x, old_size));
159 memcpy (r, x, old_size);
161 /* The old object is not supposed to be used anymore. */
162 ggc_free (x);
164 return r;
167 void *
168 ggc_cleared_alloc_htab_ignore_args (size_t c ATTRIBUTE_UNUSED,
169 size_t n ATTRIBUTE_UNUSED)
171 gcc_assert (c * n == sizeof (struct htab));
172 return ggc_cleared_alloc<htab> ();
175 /* TODO: once we actually use type information in GGC, create a new tag
176 gt_gcc_ptr_array and use it for pointer arrays. */
177 void *
178 ggc_cleared_alloc_ptr_array_two_args (size_t c, size_t n)
180 gcc_assert (sizeof (PTR *) == n);
181 return ggc_cleared_vec_alloc<PTR *> (c);
184 /* These are for splay_tree_new_ggc. */
185 void *
186 ggc_splay_alloc (int sz, void *nl)
188 gcc_assert (!nl);
189 return ggc_internal_alloc (sz);
192 void
193 ggc_splay_dont_free (void * x ATTRIBUTE_UNUSED, void *nl)
195 gcc_assert (!nl);
198 void
199 ggc_print_common_statistics (FILE *stream ATTRIBUTE_UNUSED,
200 ggc_statistics *stats)
202 /* Set the pointer so that during collection we will actually gather
203 the statistics. */
204 ggc_stats = stats;
206 /* Then do one collection to fill in the statistics. */
207 ggc_collect ();
209 /* At present, we don't really gather any interesting statistics. */
211 /* Don't gather statistics any more. */
212 ggc_stats = NULL;
215 /* Functions for saving and restoring GCable memory to disk. */
217 struct ptr_data
219 void *obj;
220 void *note_ptr_cookie;
221 gt_note_pointers note_ptr_fn;
222 gt_handle_reorder reorder_fn;
223 size_t size;
224 void *new_addr;
227 #define POINTER_HASH(x) (hashval_t)((intptr_t)x >> 3)
229 /* Helper for hashing saving_htab. */
231 struct saving_hasher : free_ptr_hash <ptr_data>
233 typedef void *compare_type;
234 static inline hashval_t hash (const ptr_data *);
235 static inline bool equal (const ptr_data *, const void *);
238 inline hashval_t
239 saving_hasher::hash (const ptr_data *p)
241 return POINTER_HASH (p->obj);
244 inline bool
245 saving_hasher::equal (const ptr_data *p1, const void *p2)
247 return p1->obj == p2;
250 static hash_table<saving_hasher> *saving_htab;
251 static vec<void *> callback_vec;
252 // sdcpp static vec<void *> reloc_addrs_vec;
254 /* Register an object in the hash table. */
256 #if 0 // sdcpp
258 gt_pch_note_object (void *obj, void *note_ptr_cookie,
259 gt_note_pointers note_ptr_fn)
261 struct ptr_data **slot;
263 if (obj == NULL || obj == (void *) 1)
264 return 0;
266 slot = (struct ptr_data **)
267 saving_htab->find_slot_with_hash (obj, POINTER_HASH (obj), INSERT);
268 if (*slot != NULL)
270 gcc_assert ((*slot)->note_ptr_fn == note_ptr_fn
271 && (*slot)->note_ptr_cookie == note_ptr_cookie);
272 return 0;
275 *slot = XCNEW (struct ptr_data);
276 (*slot)->obj = obj;
277 (*slot)->note_ptr_fn = note_ptr_fn;
278 (*slot)->note_ptr_cookie = note_ptr_cookie;
279 if (note_ptr_fn == gt_pch_p_S)
280 (*slot)->size = strlen ((const char *)obj) + 1;
281 else
282 (*slot)->size = ggc_get_size (obj);
283 return 1;
285 #endif // sdcpp
287 /* Register address of a callback pointer. */
288 void
289 gt_pch_note_callback (void *obj, void *base)
291 void *ptr;
292 memcpy (&ptr, obj, sizeof (void *));
293 if (ptr != NULL)
295 struct ptr_data *data
296 = (struct ptr_data *)
297 saving_htab->find_with_hash (base, POINTER_HASH (base));
298 gcc_assert (data);
299 callback_vec.safe_push ((char *) data->new_addr
300 + ((char *) obj - (char *) base));
304 /* Register an object in the hash table. */
306 #if 0 // sdcpp
307 void
308 gt_pch_note_reorder (void *obj, void *note_ptr_cookie,
309 gt_handle_reorder reorder_fn)
311 struct ptr_data *data;
313 if (obj == NULL || obj == (void *) 1)
314 return;
316 data = (struct ptr_data *)
317 saving_htab->find_with_hash (obj, POINTER_HASH (obj));
318 gcc_assert (data && data->note_ptr_cookie == note_ptr_cookie);
320 data->reorder_fn = reorder_fn;
322 #endif // sdcpp
324 /* Handy state for the traversal functions. */
326 struct traversal_state
328 FILE *f;
329 struct ggc_pch_data *d;
330 size_t count;
331 struct ptr_data **ptrs;
332 size_t ptrs_i;
335 /* Callbacks for htab_traverse. */
338 ggc_call_count (ptr_data **slot, traversal_state *state)
340 struct ptr_data *d = *slot;
342 ggc_pch_count_object (state->d, d->obj, d->size,
343 d->note_ptr_fn == gt_pch_p_S);
344 state->count++;
345 return 1;
349 ggc_call_alloc (ptr_data **slot, traversal_state *state)
351 struct ptr_data *d = *slot;
353 d->new_addr = ggc_pch_alloc_object (state->d, d->obj, d->size,
354 d->note_ptr_fn == gt_pch_p_S);
355 state->ptrs[state->ptrs_i++] = d;
356 return 1;
359 /* Callback for qsort. */
361 #if 0 // sdcpp
362 static int
363 compare_ptr_data (const void *p1_p, const void *p2_p)
365 const struct ptr_data *const p1 = *(const struct ptr_data *const *)p1_p;
366 const struct ptr_data *const p2 = *(const struct ptr_data *const *)p2_p;
367 return (((size_t)p1->new_addr > (size_t)p2->new_addr)
368 - ((size_t)p1->new_addr < (size_t)p2->new_addr));
371 /* Callbacks for note_ptr_fn. */
373 static void
374 relocate_ptrs (void *ptr_p, void *real_ptr_p, void *state_p)
376 void **ptr = (void **)ptr_p;
377 struct traversal_state *state
378 = (struct traversal_state *)state_p;
379 struct ptr_data *result;
381 if (*ptr == NULL || *ptr == (void *)1)
382 return;
384 result = (struct ptr_data *)
385 saving_htab->find_with_hash (*ptr, POINTER_HASH (*ptr));
386 gcc_assert (result);
387 *ptr = result->new_addr;
388 if (ptr_p == real_ptr_p)
389 return;
390 if (real_ptr_p == NULL)
391 real_ptr_p = ptr_p;
392 gcc_assert (real_ptr_p >= state->ptrs[state->ptrs_i]->obj
393 && ((char *) real_ptr_p + sizeof (void *)
394 <= ((char *) state->ptrs[state->ptrs_i]->obj
395 + state->ptrs[state->ptrs_i]->size)));
396 void *addr
397 = (void *) ((char *) state->ptrs[state->ptrs_i]->new_addr
398 + ((char *) real_ptr_p
399 - (char *) state->ptrs[state->ptrs_i]->obj));
400 reloc_addrs_vec.safe_push (addr);
402 #endif // sdcpp
404 /* Write out, after relocation, the pointers in TAB. */
405 #if 0 // sdcpp
406 static void
407 write_pch_globals (const struct ggc_root_tab * const *tab,
408 struct traversal_state *state)
410 const struct ggc_root_tab *const *rt;
411 const struct ggc_root_tab *rti;
412 size_t i;
414 for (rt = tab; *rt; rt++)
415 for (rti = *rt; rti->base != NULL; rti++)
416 for (i = 0; i < rti->nelt; i++)
418 void *ptr = *(void **)((char *)rti->base + rti->stride * i);
419 struct ptr_data *new_ptr;
420 if (ptr == NULL || ptr == (void *)1)
422 if (fwrite (&ptr, sizeof (void *), 1, state->f)
423 != 1)
424 fatal_error (input_location, "cannot write PCH file: %m");
426 else
428 new_ptr = (struct ptr_data *)
429 saving_htab->find_with_hash (ptr, POINTER_HASH (ptr));
430 if (fwrite (&new_ptr->new_addr, sizeof (void *), 1, state->f)
431 != 1)
432 fatal_error (input_location, "cannot write PCH file: %m");
436 #endif // sdcpp
438 /* Callback for qsort. */
440 #if 0 // sdcpp
441 static int
442 compare_ptr (const void *p1_p, const void *p2_p)
444 void *p1 = *(void *const *)p1_p;
445 void *p2 = *(void *const *)p2_p;
446 return (((uintptr_t)p1 > (uintptr_t)p2)
447 - ((uintptr_t)p1 < (uintptr_t)p2));
449 #endif // sdcpp
451 /* Decode one uleb128 from P, return first byte after it, store
452 decoded value into *VAL. */
454 static unsigned char *
455 read_uleb128 (unsigned char *p, size_t *val)
457 unsigned int shift = 0;
458 unsigned char byte;
459 size_t result;
461 result = 0;
464 byte = *p++;
465 result |= ((size_t) byte & 0x7f) << shift;
466 shift += 7;
468 while (byte & 0x80);
470 *val = result;
471 return p;
474 /* Store VAL as uleb128 at P, return length in bytes. */
476 #if 0 // sdcpp
477 static size_t
478 write_uleb128 (unsigned char *p, size_t val)
480 size_t len = 0;
483 unsigned char byte = (val & 0x7f);
484 val >>= 7;
485 if (val != 0)
486 /* More bytes to follow. */
487 byte |= 0x80;
489 *p++ = byte;
490 ++len;
492 while (val != 0);
493 return len;
495 #endif // sdcpp
497 /* Hold the information we need to mmap the file back in. */
499 struct mmap_info
501 size_t offset;
502 size_t size;
503 void *preferred_base;
506 /* Write out the state of the compiler to F. */
508 void
509 gt_pch_save (FILE *f)
511 #if 1 // sdcpp
512 (void) f;
513 fprintf(stderr, "unreachable %s %d\n", __FILE__, __LINE__);
514 #else // sdcpp
515 const struct ggc_root_tab *const *rt;
516 const struct ggc_root_tab *rti;
517 size_t i;
518 struct traversal_state state;
519 char *this_object = NULL;
520 size_t this_object_size = 0;
521 struct mmap_info mmi;
522 const size_t mmap_offset_alignment = 0; // host_hooks.gt_pch_alloc_granularity ();
524 gt_pch_save_stringpool ();
526 timevar_push (TV_PCH_PTR_REALLOC);
527 saving_htab = new hash_table<saving_hasher> (50000);
529 for (rt = gt_ggc_rtab; *rt; rt++)
530 for (rti = *rt; rti->base != NULL; rti++)
531 for (i = 0; i < rti->nelt; i++)
532 (*rti->pchw)(*(void **)((char *)rti->base + rti->stride * i));
534 /* Prepare the objects for writing, determine addresses and such. */
535 state.f = f;
536 state.d = init_ggc_pch ();
537 state.count = 0;
538 saving_htab->traverse <traversal_state *, ggc_call_count> (&state);
540 mmi.size = ggc_pch_total_size (state.d);
542 /* Try to arrange things so that no relocation is necessary, but
543 don't try very hard. On most platforms, this will always work,
544 and on the rest it's a lot of work to do better.
545 (The extra work goes in HOST_HOOKS_GT_PCH_GET_ADDRESS and
546 HOST_HOOKS_GT_PCH_USE_ADDRESS.) */
547 fprintf(stderr, "incomplete %s %d\n", __FILE__, __LINE__);
548 // mmi.preferred_base = host_hooks.gt_pch_get_address (mmi.size, fileno (f));
549 /* If the host cannot supply any suitable address for this, we are stuck. */
550 if (mmi.preferred_base == NULL)
551 fatal_error (input_location,
552 "cannot write PCH file: required memory segment unavailable");
554 ggc_pch_this_base (state.d, mmi.preferred_base);
556 state.ptrs = XNEWVEC (struct ptr_data *, state.count);
557 state.ptrs_i = 0;
559 saving_htab->traverse <traversal_state *, ggc_call_alloc> (&state);
560 timevar_pop (TV_PCH_PTR_REALLOC);
562 timevar_push (TV_PCH_PTR_SORT);
563 qsort (state.ptrs, state.count, sizeof (*state.ptrs), compare_ptr_data);
564 timevar_pop (TV_PCH_PTR_SORT);
566 /* Write out all the scalar variables. */
567 for (rt = gt_pch_scalar_rtab; *rt; rt++)
568 for (rti = *rt; rti->base != NULL; rti++)
569 if (fwrite (rti->base, rti->stride, 1, f) != 1)
570 fatal_error (input_location, "cannot write PCH file: %m");
572 /* Write out all the global pointers, after translation. */
573 write_pch_globals (gt_ggc_rtab, &state);
575 /* Pad the PCH file so that the mmapped area starts on an allocation
576 granularity (usually page) boundary. */
578 long o;
579 o = ftell (state.f) + sizeof (mmi);
580 if (o == -1)
581 fatal_error (input_location, "cannot get position in PCH file: %m");
582 mmi.offset = mmap_offset_alignment - o % mmap_offset_alignment;
583 if (mmi.offset == mmap_offset_alignment)
584 mmi.offset = 0;
585 mmi.offset += o;
587 if (fwrite (&mmi, sizeof (mmi), 1, state.f) != 1)
588 fatal_error (input_location, "cannot write PCH file: %m");
589 if (mmi.offset != 0
590 && fseek (state.f, mmi.offset, SEEK_SET) != 0)
591 fatal_error (input_location, "cannot write padding to PCH file: %m");
593 ggc_pch_prepare_write (state.d, state.f);
595 #if defined ENABLE_VALGRIND_ANNOTATIONS && defined VALGRIND_GET_VBITS
596 vec<char> vbits = vNULL;
597 #endif
599 /* Actually write out the objects. */
600 for (i = 0; i < state.count; i++)
602 state.ptrs_i = i;
603 if (this_object_size < state.ptrs[i]->size)
605 this_object_size = state.ptrs[i]->size;
606 this_object = XRESIZEVAR (char, this_object, this_object_size);
608 #if defined ENABLE_VALGRIND_ANNOTATIONS && defined VALGRIND_GET_VBITS
609 /* obj might contain uninitialized bytes, e.g. in the trailing
610 padding of the object. Avoid warnings by making the memory
611 temporarily defined and then restoring previous state. */
612 int get_vbits = 0;
613 size_t valid_size = state.ptrs[i]->size;
614 if (__builtin_expect (RUNNING_ON_VALGRIND, 0))
616 if (vbits.length () < valid_size)
617 vbits.safe_grow (valid_size, true);
618 get_vbits = VALGRIND_GET_VBITS (state.ptrs[i]->obj,
619 vbits.address (), valid_size);
620 if (get_vbits == 3)
622 /* We assume that first part of obj is addressable, and
623 the rest is unaddressable. Find out where the boundary is
624 using binary search. */
625 size_t lo = 0, hi = valid_size;
626 while (hi > lo)
628 size_t mid = (lo + hi) / 2;
629 get_vbits = VALGRIND_GET_VBITS ((char *) state.ptrs[i]->obj
630 + mid, vbits.address (),
632 if (get_vbits == 3)
633 hi = mid;
634 else if (get_vbits == 1)
635 lo = mid + 1;
636 else
637 break;
639 if (get_vbits == 1 || get_vbits == 3)
641 valid_size = lo;
642 get_vbits = VALGRIND_GET_VBITS (state.ptrs[i]->obj,
643 vbits.address (),
644 valid_size);
647 if (get_vbits == 1)
648 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (state.ptrs[i]->obj,
649 state.ptrs[i]->size));
651 #endif
652 memcpy (this_object, state.ptrs[i]->obj, state.ptrs[i]->size);
653 if (state.ptrs[i]->reorder_fn != NULL)
654 state.ptrs[i]->reorder_fn (state.ptrs[i]->obj,
655 state.ptrs[i]->note_ptr_cookie,
656 relocate_ptrs, &state);
657 state.ptrs[i]->note_ptr_fn (state.ptrs[i]->obj,
658 state.ptrs[i]->note_ptr_cookie,
659 relocate_ptrs, &state);
660 ggc_pch_write_object (state.d, state.f, state.ptrs[i]->obj,
661 state.ptrs[i]->new_addr, state.ptrs[i]->size,
662 state.ptrs[i]->note_ptr_fn == gt_pch_p_S);
663 if (state.ptrs[i]->note_ptr_fn != gt_pch_p_S)
664 memcpy (state.ptrs[i]->obj, this_object, state.ptrs[i]->size);
665 #if defined ENABLE_VALGRIND_ANNOTATIONS && defined VALGRIND_GET_VBITS
666 if (__builtin_expect (get_vbits == 1, 0))
668 (void) VALGRIND_SET_VBITS (state.ptrs[i]->obj, vbits.address (),
669 valid_size);
670 if (valid_size != state.ptrs[i]->size)
671 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS ((char *)
672 state.ptrs[i]->obj
673 + valid_size,
674 state.ptrs[i]->size
675 - valid_size));
677 #endif
679 #if defined ENABLE_VALGRIND_ANNOTATIONS && defined VALGRIND_GET_VBITS
680 vbits.release ();
681 #endif
683 reloc_addrs_vec.qsort (compare_ptr);
685 size_t reloc_addrs_size = 0;
686 void *last_addr = NULL;
687 unsigned char uleb128_buf[sizeof (size_t) * 2];
688 for (void *addr : reloc_addrs_vec)
690 gcc_assert ((uintptr_t) addr >= (uintptr_t) mmi.preferred_base
691 && ((uintptr_t) addr + sizeof (void *)
692 < (uintptr_t) mmi.preferred_base + mmi.size));
693 if (addr == last_addr)
694 continue;
695 if (last_addr == NULL)
696 last_addr = mmi.preferred_base;
697 size_t diff = (uintptr_t) addr - (uintptr_t) last_addr;
698 reloc_addrs_size += write_uleb128 (uleb128_buf, diff);
699 last_addr = addr;
701 if (fwrite (&reloc_addrs_size, sizeof (reloc_addrs_size), 1, f) != 1)
702 fatal_error (input_location, "cannot write PCH file: %m");
703 last_addr = NULL;
704 for (void *addr : reloc_addrs_vec)
706 if (addr == last_addr)
707 continue;
708 if (last_addr == NULL)
709 last_addr = mmi.preferred_base;
710 size_t diff = (uintptr_t) addr - (uintptr_t) last_addr;
711 reloc_addrs_size = write_uleb128 (uleb128_buf, diff);
712 if (fwrite (uleb128_buf, 1, reloc_addrs_size, f) != reloc_addrs_size)
713 fatal_error (input_location, "cannot write PCH file: %m");
714 last_addr = addr;
717 ggc_pch_finish (state.d, state.f);
719 gt_pch_fixup_stringpool ();
721 unsigned num_callbacks = callback_vec.length ();
722 void (*pch_save) (FILE *) = &gt_pch_save;
723 if (fwrite (&pch_save, sizeof (pch_save), 1, f) != 1
724 || fwrite (&num_callbacks, sizeof (num_callbacks), 1, f) != 1
725 || (num_callbacks
726 && fwrite (callback_vec.address (), sizeof (void *), num_callbacks,
727 f) != num_callbacks))
728 fatal_error (input_location, "cannot write PCH file: %m");
730 XDELETE (state.ptrs);
731 XDELETE (this_object);
732 delete saving_htab;
733 saving_htab = NULL;
734 callback_vec.release ();
735 reloc_addrs_vec.release ();
736 #endif // sdcpp
739 /* Read the state of the compiler back in from F. */
741 void
742 gt_pch_restore (FILE *f)
744 const struct ggc_root_tab *const *rt;
745 const struct ggc_root_tab *rti;
746 size_t i;
747 struct mmap_info mmi;
748 int result;
750 /* We are about to reload the line maps along with the rest of the PCH
751 data, which means that the (loaded) ones cannot be guaranteed to be
752 in any valid state for reporting diagnostics that happen during the
753 load. Save the current table (and use it during the loading process
754 below). */
755 class line_maps *save_line_table = line_table;
757 /* Delete any deletable objects. This makes ggc_pch_read much
758 faster, as it can be sure that no GCable objects remain other
759 than the ones just read in. */
760 for (rt = gt_ggc_deletable_rtab; *rt; rt++)
761 for (rti = *rt; rti->base != NULL; rti++)
762 memset (rti->base, 0, rti->stride);
764 /* Read in all the scalar variables. */
765 for (rt = gt_pch_scalar_rtab; *rt; rt++)
766 for (rti = *rt; rti->base != NULL; rti++)
767 if (fread (rti->base, rti->stride, 1, f) != 1)
768 fatal_error (input_location, "cannot read PCH file: %m");
770 /* Read in all the global pointers, in 6 easy loops. */
771 bool error_reading_pointers = false;
772 for (rt = gt_ggc_rtab; *rt; rt++)
773 for (rti = *rt; rti->base != NULL; rti++)
774 for (i = 0; i < rti->nelt; i++)
775 if (fread ((char *)rti->base + rti->stride * i,
776 sizeof (void *), 1, f) != 1)
777 error_reading_pointers = true;
779 /* Stash the newly read-in line table pointer - it does not point to
780 anything meaningful yet, so swap the old one back in. */
781 class line_maps *new_line_table = line_table;
782 line_table = save_line_table;
783 if (error_reading_pointers)
784 fatal_error (input_location, "cannot read PCH file: %m");
786 if (fread (&mmi, sizeof (mmi), 1, f) != 1)
787 fatal_error (input_location, "cannot read PCH file: %m");
789 void *orig_preferred_base = mmi.preferred_base;
791 fprintf(stderr, "incomplete %s %d\n", __FILE__, __LINE__);
792 result = 0; // host_hooks.gt_pch_use_address (mmi.preferred_base, mmi.size,
793 // fileno (f), mmi.offset);
795 /* We could not mmap or otherwise allocate the required memory at the
796 address needed. */
797 if (result < 0)
799 sorry_at (input_location, "PCH allocation failure");
800 /* There is no point in continuing from here, we will only end up
801 with a crashed (most likely hanging) compiler. */
802 exit (-1);
805 /* (0) We allocated memory, but did not mmap the file, so we need to read
806 the data in manually. (>0) Otherwise the mmap succeed for the address
807 we wanted. */
808 if (result == 0)
810 if (fseek (f, mmi.offset, SEEK_SET) != 0
811 || fread (mmi.preferred_base, mmi.size, 1, f) != 1)
812 fatal_error (input_location, "cannot read PCH file: %m");
814 else if (fseek (f, mmi.offset + mmi.size, SEEK_SET) != 0)
815 fatal_error (input_location, "cannot read PCH file: %m");
817 size_t reloc_addrs_size;
818 if (fread (&reloc_addrs_size, sizeof (reloc_addrs_size), 1, f) != 1)
819 fatal_error (input_location, "cannot read PCH file: %m");
821 if (orig_preferred_base != mmi.preferred_base)
823 uintptr_t bias
824 = (uintptr_t) mmi.preferred_base - (uintptr_t) orig_preferred_base;
826 /* Adjust all the global pointers by bias. */
827 line_table = new_line_table;
828 for (rt = gt_ggc_rtab; *rt; rt++)
829 for (rti = *rt; rti->base != NULL; rti++)
830 for (i = 0; i < rti->nelt; i++)
832 char *addr = (char *)rti->base + rti->stride * i;
833 char *p;
834 memcpy (&p, addr, sizeof (void *));
835 if ((uintptr_t) p >= (uintptr_t) orig_preferred_base
836 && (uintptr_t) p < (uintptr_t) orig_preferred_base + mmi.size)
838 p = (char *) ((uintptr_t) p + bias);
839 memcpy (addr, &p, sizeof (void *));
842 new_line_table = line_table;
843 line_table = save_line_table;
845 /* And adjust all the pointers in the image by bias too. */
846 char *addr = (char *) mmi.preferred_base;
847 unsigned char uleb128_buf[4096], *uleb128_ptr = uleb128_buf;
848 while (reloc_addrs_size != 0)
850 size_t this_size
851 = MIN (reloc_addrs_size,
852 (size_t) (4096 - (uleb128_ptr - uleb128_buf)));
853 if (fread (uleb128_ptr, 1, this_size, f) != this_size)
854 fatal_error (input_location, "cannot read PCH file: %m");
855 unsigned char *uleb128_end = uleb128_ptr + this_size;
856 if (this_size != reloc_addrs_size)
857 uleb128_end -= 2 * sizeof (size_t);
858 uleb128_ptr = uleb128_buf;
859 while (uleb128_ptr < uleb128_end)
861 size_t diff;
862 uleb128_ptr = read_uleb128 (uleb128_ptr, &diff);
863 addr = (char *) ((uintptr_t) addr + diff);
865 char *p;
866 memcpy (&p, addr, sizeof (void *));
867 gcc_assert ((uintptr_t) p >= (uintptr_t) orig_preferred_base
868 && ((uintptr_t) p
869 < (uintptr_t) orig_preferred_base + mmi.size));
870 p = (char *) ((uintptr_t) p + bias);
871 memcpy (addr, &p, sizeof (void *));
873 reloc_addrs_size -= this_size;
874 if (reloc_addrs_size == 0)
875 break;
876 this_size = uleb128_end + 2 * sizeof (size_t) - uleb128_ptr;
877 memcpy (uleb128_buf, uleb128_ptr, this_size);
878 uleb128_ptr = uleb128_buf + this_size;
881 else if (fseek (f, (mmi.offset + mmi.size + sizeof (reloc_addrs_size)
882 + reloc_addrs_size), SEEK_SET) != 0)
883 fatal_error (input_location, "cannot read PCH file: %m");
885 ggc_pch_read (f, mmi.preferred_base);
887 void (*pch_save) (FILE *);
888 unsigned num_callbacks;
889 if (fread (&pch_save, sizeof (pch_save), 1, f) != 1
890 || fread (&num_callbacks, sizeof (num_callbacks), 1, f) != 1)
891 fatal_error (input_location, "cannot read PCH file: %m");
892 if (pch_save != &gt_pch_save)
894 uintptr_t binbias = (uintptr_t) &gt_pch_save - (uintptr_t) pch_save;
895 void **ptrs = XNEWVEC (void *, num_callbacks);
896 unsigned i;
897 uintptr_t bias
898 = (uintptr_t) mmi.preferred_base - (uintptr_t) orig_preferred_base;
900 if (fread (ptrs, sizeof (void *), num_callbacks, f) != num_callbacks)
901 fatal_error (input_location, "cannot read PCH file: %m");
902 for (i = 0; i < num_callbacks; ++i)
904 void *ptr = (void *) ((uintptr_t) ptrs[i] + bias);
905 memcpy (&pch_save, ptr, sizeof (pch_save));
906 pch_save = (void (*) (FILE *)) ((uintptr_t) pch_save + binbias);
907 memcpy (ptr, &pch_save, sizeof (pch_save));
909 XDELETE (ptrs);
911 else if (fseek (f, num_callbacks * sizeof (void *), SEEK_CUR) != 0)
912 fatal_error (input_location, "cannot read PCH file: %m");
914 gt_pch_restore_stringpool ();
916 /* Barring corruption of the PCH file, the restored line table should be
917 complete and usable. */
918 line_table = new_line_table;
921 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS when mmap is not present.
922 Select no address whatsoever, and let gt_pch_save choose what it will with
923 malloc, presumably. */
925 void *
926 default_gt_pch_get_address (size_t size ATTRIBUTE_UNUSED,
927 int fd ATTRIBUTE_UNUSED)
929 return NULL;
932 /* Default version of HOST_HOOKS_GT_PCH_USE_ADDRESS when mmap is not present.
933 Allocate SIZE bytes with malloc. Return 0 if the address we got is the
934 same as base, indicating that the memory has been allocated but needs to
935 be read in from the file. Return -1 if the address differs, to relocation
936 of the PCH file would be required. */
939 default_gt_pch_use_address (void *&base, size_t size, int fd ATTRIBUTE_UNUSED,
940 size_t offset ATTRIBUTE_UNUSED)
942 void *addr = xmalloc (size);
943 return (addr == base) - 1;
946 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS. Return the
947 alignment required for allocating virtual memory. Usually this is the
948 same as pagesize. */
950 size_t
951 default_gt_pch_alloc_granularity (void)
953 return getpagesize ();
956 #if HAVE_MMAP_FILE
957 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS when mmap is present.
958 We temporarily allocate SIZE bytes, and let the kernel place the data
959 wherever it will. If it worked, that's our spot, if not we're likely
960 to be in trouble. */
962 void *
963 mmap_gt_pch_get_address (size_t size, int fd)
965 void *ret;
967 ret = mmap (NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
968 if (ret == (void *) MAP_FAILED)
969 ret = NULL;
970 else
971 munmap ((caddr_t) ret, size);
973 return ret;
976 /* Default version of HOST_HOOKS_GT_PCH_USE_ADDRESS when mmap is present.
977 Map SIZE bytes of FD+OFFSET at BASE. Return 1 if we succeeded at
978 mapping the data at BASE, -1 if we couldn't.
980 This version assumes that the kernel honors the START operand of mmap
981 even without MAP_FIXED if START through START+SIZE are not currently
982 mapped with something. */
985 mmap_gt_pch_use_address (void *&base, size_t size, int fd, size_t offset)
987 void *addr;
989 /* We're called with size == 0 if we're not planning to load a PCH
990 file at all. This allows the hook to free any static space that
991 we might have allocated at link time. */
992 if (size == 0)
993 return -1;
995 addr = mmap ((caddr_t) base, size, PROT_READ | PROT_WRITE, MAP_PRIVATE,
996 fd, offset);
998 return addr == base ? 1 : -1;
1000 #endif /* HAVE_MMAP_FILE */
1002 #if !defined ENABLE_GC_CHECKING && !defined ENABLE_GC_ALWAYS_COLLECT
1004 /* Modify the bound based on rlimits. */
1005 static double
1006 ggc_rlimit_bound (double limit)
1008 #if defined(HAVE_GETRLIMIT)
1009 struct rlimit rlim;
1010 # if defined (RLIMIT_AS)
1011 /* RLIMIT_AS is what POSIX says is the limit on mmap. Presumably
1012 any OS which has RLIMIT_AS also has a working mmap that GCC will use. */
1013 if (getrlimit (RLIMIT_AS, &rlim) == 0
1014 && rlim.rlim_cur != (rlim_t) RLIM_INFINITY
1015 && rlim.rlim_cur < limit)
1016 limit = rlim.rlim_cur;
1017 # elif defined (RLIMIT_DATA)
1018 /* ... but some older OSs bound mmap based on RLIMIT_DATA, or we
1019 might be on an OS that has a broken mmap. (Others don't bound
1020 mmap at all, apparently.) */
1021 if (getrlimit (RLIMIT_DATA, &rlim) == 0
1022 && rlim.rlim_cur != (rlim_t) RLIM_INFINITY
1023 && rlim.rlim_cur < limit
1024 /* Darwin has this horribly bogus default setting of
1025 RLIMIT_DATA, to 6144Kb. No-one notices because RLIMIT_DATA
1026 appears to be ignored. Ignore such silliness. If a limit
1027 this small was actually effective for mmap, GCC wouldn't even
1028 start up. */
1029 && rlim.rlim_cur >= 8 * ONE_M)
1030 limit = rlim.rlim_cur;
1031 # endif /* RLIMIT_AS or RLIMIT_DATA */
1032 #endif /* HAVE_GETRLIMIT */
1034 return limit;
1037 /* Heuristic to set a default for GGC_MIN_EXPAND. */
1038 static int
1039 ggc_min_expand_heuristic (void)
1041 double min_expand = physmem_total ();
1043 /* Adjust for rlimits. */
1044 min_expand = ggc_rlimit_bound (min_expand);
1046 /* The heuristic is a percentage equal to 30% + 70%*(RAM/1GB), yielding
1047 a lower bound of 30% and an upper bound of 100% (when RAM >= 1GB). */
1048 min_expand /= ONE_G;
1049 min_expand *= 70;
1050 min_expand = MIN (min_expand, 70);
1051 min_expand += 30;
1053 return min_expand;
1056 /* Heuristic to set a default for GGC_MIN_HEAPSIZE. */
1057 static int
1058 ggc_min_heapsize_heuristic (void)
1060 double phys_kbytes = physmem_total ();
1061 double limit_kbytes = ggc_rlimit_bound (phys_kbytes * 2);
1063 phys_kbytes /= ONE_K; /* Convert to Kbytes. */
1064 limit_kbytes /= ONE_K;
1066 /* The heuristic is RAM/8, with a lower bound of 4M and an upper
1067 bound of 128M (when RAM >= 1GB). */
1068 phys_kbytes /= 8;
1070 #if defined(HAVE_GETRLIMIT) && defined (RLIMIT_RSS)
1071 /* Try not to overrun the RSS limit while doing garbage collection.
1072 The RSS limit is only advisory, so no margin is subtracted. */
1074 struct rlimit rlim;
1075 if (getrlimit (RLIMIT_RSS, &rlim) == 0
1076 && rlim.rlim_cur != (rlim_t) RLIM_INFINITY)
1077 phys_kbytes = MIN (phys_kbytes, rlim.rlim_cur / ONE_K);
1079 # endif
1081 /* Don't blindly run over our data limit; do GC at least when the
1082 *next* GC would be within 20Mb of the limit or within a quarter of
1083 the limit, whichever is larger. If GCC does hit the data limit,
1084 compilation will fail, so this tries to be conservative. */
1085 limit_kbytes = MAX (0, limit_kbytes - MAX (limit_kbytes / 4, 20 * ONE_K));
1086 limit_kbytes = (limit_kbytes * 100) / (110 + ggc_min_expand_heuristic ());
1087 phys_kbytes = MIN (phys_kbytes, limit_kbytes);
1089 phys_kbytes = MAX (phys_kbytes, 4 * ONE_K);
1090 phys_kbytes = MIN (phys_kbytes, 128 * ONE_K);
1092 return phys_kbytes;
1094 #endif
1096 void
1097 init_ggc_heuristics (void)
1099 #if !defined ENABLE_GC_CHECKING && !defined ENABLE_GC_ALWAYS_COLLECT
1100 param_ggc_min_expand = ggc_min_expand_heuristic ();
1101 param_ggc_min_heapsize = ggc_min_heapsize_heuristic ();
1102 #endif
1105 /* GGC memory usage. */
1106 class ggc_usage: public mem_usage
1108 public:
1109 /* Default constructor. */
1110 ggc_usage (): m_freed (0), m_collected (0), m_overhead (0) {}
1111 /* Constructor. */
1112 ggc_usage (size_t allocated, size_t times, size_t peak,
1113 size_t freed, size_t collected, size_t overhead)
1114 : mem_usage (allocated, times, peak),
1115 m_freed (freed), m_collected (collected), m_overhead (overhead) {}
1117 /* Equality operator. */
1118 inline bool
1119 operator== (const ggc_usage &second) const
1121 return (get_balance () == second.get_balance ()
1122 && m_peak == second.m_peak
1123 && m_times == second.m_times);
1126 /* Comparison operator. */
1127 inline bool
1128 operator< (const ggc_usage &second) const
1130 if (*this == second)
1131 return false;
1133 return (get_balance () == second.get_balance () ?
1134 (m_peak == second.m_peak ? m_times < second.m_times
1135 : m_peak < second.m_peak)
1136 : get_balance () < second.get_balance ());
1139 /* Register overhead of ALLOCATED and OVERHEAD bytes. */
1140 inline void
1141 register_overhead (size_t allocated, size_t overhead)
1143 m_allocated += allocated;
1144 m_overhead += overhead;
1145 m_times++;
1148 /* Release overhead of SIZE bytes. */
1149 inline void
1150 release_overhead (size_t size)
1152 m_freed += size;
1155 /* Sum the usage with SECOND usage. */
1156 ggc_usage
1157 operator+ (const ggc_usage &second)
1159 return ggc_usage (m_allocated + second.m_allocated,
1160 m_times + second.m_times,
1161 m_peak + second.m_peak,
1162 m_freed + second.m_freed,
1163 m_collected + second.m_collected,
1164 m_overhead + second.m_overhead);
1167 /* Dump usage with PREFIX, where TOTAL is sum of all rows. */
1168 inline void
1169 dump (const char *prefix, ggc_usage &total) const
1171 size_t balance = get_balance ();
1172 fprintf (stderr,
1173 "%-48s " PRsa (9) ":%5.1f%%" PRsa (9) ":%5.1f%%"
1174 PRsa (9) ":%5.1f%%" PRsa (9) ":%5.1f%%" PRsa (9) "\n",
1175 prefix,
1176 SIZE_AMOUNT (balance), get_percent (balance, total.get_balance ()),
1177 SIZE_AMOUNT (m_collected),
1178 get_percent (m_collected, total.m_collected),
1179 SIZE_AMOUNT (m_freed), get_percent (m_freed, total.m_freed),
1180 SIZE_AMOUNT (m_overhead),
1181 get_percent (m_overhead, total.m_overhead),
1182 SIZE_AMOUNT (m_times));
1185 /* Dump usage coupled to LOC location, where TOTAL is sum of all rows. */
1186 inline void
1187 dump (mem_location *loc, ggc_usage &total) const
1189 char *location_string = loc->to_string ();
1191 dump (location_string, total);
1193 free (location_string);
1196 /* Dump footer. */
1197 inline void
1198 dump_footer ()
1200 dump ("Total", *this);
1203 /* Get balance which is GGC allocation leak. */
1204 inline size_t
1205 get_balance () const
1207 return m_allocated + m_overhead - m_collected - m_freed;
1210 typedef std::pair<mem_location *, ggc_usage *> mem_pair_t;
1212 /* Compare wrapper used by qsort method. */
1213 static int
1214 compare (const void *first, const void *second)
1216 const mem_pair_t mem1 = *(const mem_pair_t *) first;
1217 const mem_pair_t mem2 = *(const mem_pair_t *) second;
1219 size_t balance1 = mem1.second->get_balance ();
1220 size_t balance2 = mem2.second->get_balance ();
1222 return balance1 == balance2 ? 0 : (balance1 < balance2 ? 1 : -1);
1225 /* Dump header with NAME. */
1226 static inline void
1227 dump_header (const char *name)
1229 fprintf (stderr, "%-48s %11s%17s%17s%16s%17s\n", name, "Leak", "Garbage",
1230 "Freed", "Overhead", "Times");
1233 /* Freed memory in bytes. */
1234 size_t m_freed;
1235 /* Collected memory in bytes. */
1236 size_t m_collected;
1237 /* Overhead memory in bytes. */
1238 size_t m_overhead;
1241 /* GCC memory description. */
1242 static mem_alloc_description<ggc_usage> ggc_mem_desc;
1244 /* Dump per-site memory statistics. */
1246 void
1247 dump_ggc_loc_statistics ()
1249 if (! GATHER_STATISTICS)
1250 return;
1252 ggc_collect (GGC_COLLECT_FORCE);
1254 ggc_mem_desc.dump (GGC_ORIGIN);
1257 /* Record ALLOCATED and OVERHEAD bytes to descriptor NAME:LINE (FUNCTION). */
1258 void
1259 ggc_record_overhead (size_t allocated, size_t overhead, void *ptr MEM_STAT_DECL)
1261 ggc_usage *usage = ggc_mem_desc.register_descriptor (ptr, GGC_ORIGIN, false
1262 FINAL_PASS_MEM_STAT);
1264 ggc_mem_desc.register_object_overhead (usage, allocated + overhead, ptr);
1265 usage->register_overhead (allocated, overhead);
1268 /* Notice that the pointer has been freed. */
1269 void
1270 ggc_free_overhead (void *ptr)
1272 ggc_mem_desc.release_object_overhead (ptr);
1275 /* After live values has been marked, walk all recorded pointers and see if
1276 they are still live. */
1277 void
1278 ggc_prune_overhead_list (void)
1280 typedef hash_map<const void *, std::pair<ggc_usage *, size_t > > map_t;
1282 map_t::iterator it = ggc_mem_desc.m_reverse_object_map->begin ();
1284 for (; it != ggc_mem_desc.m_reverse_object_map->end (); ++it)
1285 if (!ggc_marked_p ((*it).first))
1287 (*it).second.first->m_collected += (*it).second.second;
1288 ggc_mem_desc.m_reverse_object_map->remove ((*it).first);
1292 /* Print memory used by heap if this info is available. */
1294 void
1295 report_heap_memory_use ()
1297 #if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
1298 #ifdef HAVE_MALLINFO2
1299 #define MALLINFO_FN mallinfo2
1300 #else
1301 #define MALLINFO_FN mallinfo
1302 #endif
1303 if (!quiet_flag)
1304 fprintf (stderr, " {heap " PRsa (0) "}",
1305 SIZE_AMOUNT (MALLINFO_FN ().arena));
1306 #endif