Define STAGE1_LIBS to link against libcl.a in stage1 on hpux.
[official-gcc.git] / gcc / ggc-common.c
blob32ba5be42b2e10511860927645c66d053710d172
1 /* Simple garbage collection for the GNU compiler.
2 Copyright (C) 1999-2021 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 static int compare_ptr_data (const void *, const void *);
43 static void relocate_ptrs (void *, void *);
44 static void write_pch_globals (const struct ggc_root_tab * const *tab,
45 struct traversal_state *state);
47 /* Maintain global roots that are preserved during GC. */
49 /* This extra vector of dynamically registered root_tab-s is used by
50 ggc_mark_roots and gives the ability to dynamically add new GGC root
51 tables, for instance from some plugins; this vector is on the heap
52 since it is used by GGC internally. */
53 typedef const struct ggc_root_tab *const_ggc_root_tab_t;
54 static vec<const_ggc_root_tab_t> extra_root_vec;
56 /* Dynamically register a new GGC root table RT. This is useful for
57 plugins. */
59 void
60 ggc_register_root_tab (const struct ggc_root_tab* rt)
62 if (rt)
63 extra_root_vec.safe_push (rt);
66 /* Mark all the roots in the table RT. */
68 static void
69 ggc_mark_root_tab (const_ggc_root_tab_t rt)
71 size_t i;
73 for ( ; rt->base != NULL; rt++)
74 for (i = 0; i < rt->nelt; i++)
75 (*rt->cb) (*(void **) ((char *)rt->base + rt->stride * i));
78 /* Iterate through all registered roots and mark each element. */
80 void
81 ggc_mark_roots (void)
83 const struct ggc_root_tab *const *rt;
84 const_ggc_root_tab_t rtp, rti;
85 size_t i;
87 for (rt = gt_ggc_deletable_rtab; *rt; rt++)
88 for (rti = *rt; rti->base != NULL; rti++)
89 memset (rti->base, 0, rti->stride);
91 for (rt = gt_ggc_rtab; *rt; rt++)
92 ggc_mark_root_tab (*rt);
94 FOR_EACH_VEC_ELT (extra_root_vec, i, rtp)
95 ggc_mark_root_tab (rtp);
97 if (ggc_protect_identifiers)
98 ggc_mark_stringpool ();
100 gt_clear_caches ();
102 if (! ggc_protect_identifiers)
103 ggc_purge_stringpool ();
105 /* Some plugins may call ggc_set_mark from here. */
106 invoke_plugin_callbacks (PLUGIN_GGC_MARKING, NULL);
109 /* Allocate a block of memory, then clear it. */
110 void *
111 ggc_internal_cleared_alloc (size_t size, void (*f)(void *), size_t s, size_t n
112 MEM_STAT_DECL)
114 void *buf = ggc_internal_alloc (size, f, s, n PASS_MEM_STAT);
115 memset (buf, 0, size);
116 return buf;
119 /* Resize a block of memory, possibly re-allocating it. */
120 void *
121 ggc_realloc (void *x, size_t size MEM_STAT_DECL)
123 void *r;
124 size_t old_size;
126 if (x == NULL)
127 return ggc_internal_alloc (size PASS_MEM_STAT);
129 old_size = ggc_get_size (x);
131 if (size <= old_size)
133 /* Mark the unwanted memory as unaccessible. We also need to make
134 the "new" size accessible, since ggc_get_size returns the size of
135 the pool, not the size of the individually allocated object, the
136 size which was previously made accessible. Unfortunately, we
137 don't know that previously allocated size. Without that
138 knowledge we have to lose some initialization-tracking for the
139 old parts of the object. An alternative is to mark the whole
140 old_size as reachable, but that would lose tracking of writes
141 after the end of the object (by small offsets). Discard the
142 handle to avoid handle leak. */
143 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS ((char *) x + size,
144 old_size - size));
145 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (x, size));
146 return x;
149 r = ggc_internal_alloc (size PASS_MEM_STAT);
151 /* Since ggc_get_size returns the size of the pool, not the size of the
152 individually allocated object, we'd access parts of the old object
153 that were marked invalid with the memcpy below. We lose a bit of the
154 initialization-tracking since some of it may be uninitialized. */
155 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (x, old_size));
157 memcpy (r, x, old_size);
159 /* The old object is not supposed to be used anymore. */
160 ggc_free (x);
162 return r;
165 void *
166 ggc_cleared_alloc_htab_ignore_args (size_t c ATTRIBUTE_UNUSED,
167 size_t n ATTRIBUTE_UNUSED)
169 gcc_assert (c * n == sizeof (struct htab));
170 return ggc_cleared_alloc<htab> ();
173 /* TODO: once we actually use type information in GGC, create a new tag
174 gt_gcc_ptr_array and use it for pointer arrays. */
175 void *
176 ggc_cleared_alloc_ptr_array_two_args (size_t c, size_t n)
178 gcc_assert (sizeof (PTR *) == n);
179 return ggc_cleared_vec_alloc<PTR *> (c);
182 /* These are for splay_tree_new_ggc. */
183 void *
184 ggc_splay_alloc (int sz, void *nl)
186 gcc_assert (!nl);
187 return ggc_internal_alloc (sz);
190 void
191 ggc_splay_dont_free (void * x ATTRIBUTE_UNUSED, void *nl)
193 gcc_assert (!nl);
196 void
197 ggc_print_common_statistics (FILE *stream ATTRIBUTE_UNUSED,
198 ggc_statistics *stats)
200 /* Set the pointer so that during collection we will actually gather
201 the statistics. */
202 ggc_stats = stats;
204 /* Then do one collection to fill in the statistics. */
205 ggc_collect ();
207 /* At present, we don't really gather any interesting statistics. */
209 /* Don't gather statistics any more. */
210 ggc_stats = NULL;
213 /* Functions for saving and restoring GCable memory to disk. */
215 struct ptr_data
217 void *obj;
218 void *note_ptr_cookie;
219 gt_note_pointers note_ptr_fn;
220 gt_handle_reorder reorder_fn;
221 size_t size;
222 void *new_addr;
225 #define POINTER_HASH(x) (hashval_t)((intptr_t)x >> 3)
227 /* Helper for hashing saving_htab. */
229 struct saving_hasher : free_ptr_hash <ptr_data>
231 typedef void *compare_type;
232 static inline hashval_t hash (const ptr_data *);
233 static inline bool equal (const ptr_data *, const void *);
236 inline hashval_t
237 saving_hasher::hash (const ptr_data *p)
239 return POINTER_HASH (p->obj);
242 inline bool
243 saving_hasher::equal (const ptr_data *p1, const void *p2)
245 return p1->obj == p2;
248 static hash_table<saving_hasher> *saving_htab;
250 /* Register an object in the hash table. */
253 gt_pch_note_object (void *obj, void *note_ptr_cookie,
254 gt_note_pointers note_ptr_fn)
256 struct ptr_data **slot;
258 if (obj == NULL || obj == (void *) 1)
259 return 0;
261 slot = (struct ptr_data **)
262 saving_htab->find_slot_with_hash (obj, POINTER_HASH (obj), INSERT);
263 if (*slot != NULL)
265 gcc_assert ((*slot)->note_ptr_fn == note_ptr_fn
266 && (*slot)->note_ptr_cookie == note_ptr_cookie);
267 return 0;
270 *slot = XCNEW (struct ptr_data);
271 (*slot)->obj = obj;
272 (*slot)->note_ptr_fn = note_ptr_fn;
273 (*slot)->note_ptr_cookie = note_ptr_cookie;
274 if (note_ptr_fn == gt_pch_p_S)
275 (*slot)->size = strlen ((const char *)obj) + 1;
276 else
277 (*slot)->size = ggc_get_size (obj);
278 return 1;
281 /* Register an object in the hash table. */
283 void
284 gt_pch_note_reorder (void *obj, void *note_ptr_cookie,
285 gt_handle_reorder reorder_fn)
287 struct ptr_data *data;
289 if (obj == NULL || obj == (void *) 1)
290 return;
292 data = (struct ptr_data *)
293 saving_htab->find_with_hash (obj, POINTER_HASH (obj));
294 gcc_assert (data && data->note_ptr_cookie == note_ptr_cookie);
296 data->reorder_fn = reorder_fn;
299 /* Handy state for the traversal functions. */
301 struct traversal_state
303 FILE *f;
304 struct ggc_pch_data *d;
305 size_t count;
306 struct ptr_data **ptrs;
307 size_t ptrs_i;
310 /* Callbacks for htab_traverse. */
313 ggc_call_count (ptr_data **slot, traversal_state *state)
315 struct ptr_data *d = *slot;
317 ggc_pch_count_object (state->d, d->obj, d->size,
318 d->note_ptr_fn == gt_pch_p_S);
319 state->count++;
320 return 1;
324 ggc_call_alloc (ptr_data **slot, traversal_state *state)
326 struct ptr_data *d = *slot;
328 d->new_addr = ggc_pch_alloc_object (state->d, d->obj, d->size,
329 d->note_ptr_fn == gt_pch_p_S);
330 state->ptrs[state->ptrs_i++] = d;
331 return 1;
334 /* Callback for qsort. */
336 static int
337 compare_ptr_data (const void *p1_p, const void *p2_p)
339 const struct ptr_data *const p1 = *(const struct ptr_data *const *)p1_p;
340 const struct ptr_data *const p2 = *(const struct ptr_data *const *)p2_p;
341 return (((size_t)p1->new_addr > (size_t)p2->new_addr)
342 - ((size_t)p1->new_addr < (size_t)p2->new_addr));
345 /* Callbacks for note_ptr_fn. */
347 static void
348 relocate_ptrs (void *ptr_p, void *state_p)
350 void **ptr = (void **)ptr_p;
351 struct traversal_state *state ATTRIBUTE_UNUSED
352 = (struct traversal_state *)state_p;
353 struct ptr_data *result;
355 if (*ptr == NULL || *ptr == (void *)1)
356 return;
358 result = (struct ptr_data *)
359 saving_htab->find_with_hash (*ptr, POINTER_HASH (*ptr));
360 gcc_assert (result);
361 *ptr = result->new_addr;
364 /* Write out, after relocation, the pointers in TAB. */
365 static void
366 write_pch_globals (const struct ggc_root_tab * const *tab,
367 struct traversal_state *state)
369 const struct ggc_root_tab *const *rt;
370 const struct ggc_root_tab *rti;
371 size_t i;
373 for (rt = tab; *rt; rt++)
374 for (rti = *rt; rti->base != NULL; rti++)
375 for (i = 0; i < rti->nelt; i++)
377 void *ptr = *(void **)((char *)rti->base + rti->stride * i);
378 struct ptr_data *new_ptr;
379 if (ptr == NULL || ptr == (void *)1)
381 if (fwrite (&ptr, sizeof (void *), 1, state->f)
382 != 1)
383 fatal_error (input_location, "cannot write PCH file: %m");
385 else
387 new_ptr = (struct ptr_data *)
388 saving_htab->find_with_hash (ptr, POINTER_HASH (ptr));
389 if (fwrite (&new_ptr->new_addr, sizeof (void *), 1, state->f)
390 != 1)
391 fatal_error (input_location, "cannot write PCH file: %m");
396 /* Hold the information we need to mmap the file back in. */
398 struct mmap_info
400 size_t offset;
401 size_t size;
402 void *preferred_base;
405 /* Write out the state of the compiler to F. */
407 void
408 gt_pch_save (FILE *f)
410 const struct ggc_root_tab *const *rt;
411 const struct ggc_root_tab *rti;
412 size_t i;
413 struct traversal_state state;
414 char *this_object = NULL;
415 size_t this_object_size = 0;
416 struct mmap_info mmi;
417 const size_t mmap_offset_alignment = host_hooks.gt_pch_alloc_granularity ();
419 gt_pch_save_stringpool ();
421 timevar_push (TV_PCH_PTR_REALLOC);
422 saving_htab = new hash_table<saving_hasher> (50000);
424 for (rt = gt_ggc_rtab; *rt; rt++)
425 for (rti = *rt; rti->base != NULL; rti++)
426 for (i = 0; i < rti->nelt; i++)
427 (*rti->pchw)(*(void **)((char *)rti->base + rti->stride * i));
429 /* Prepare the objects for writing, determine addresses and such. */
430 state.f = f;
431 state.d = init_ggc_pch ();
432 state.count = 0;
433 saving_htab->traverse <traversal_state *, ggc_call_count> (&state);
435 mmi.size = ggc_pch_total_size (state.d);
437 /* Try to arrange things so that no relocation is necessary, but
438 don't try very hard. On most platforms, this will always work,
439 and on the rest it's a lot of work to do better.
440 (The extra work goes in HOST_HOOKS_GT_PCH_GET_ADDRESS and
441 HOST_HOOKS_GT_PCH_USE_ADDRESS.) */
442 mmi.preferred_base = host_hooks.gt_pch_get_address (mmi.size, fileno (f));
444 ggc_pch_this_base (state.d, mmi.preferred_base);
446 state.ptrs = XNEWVEC (struct ptr_data *, state.count);
447 state.ptrs_i = 0;
449 saving_htab->traverse <traversal_state *, ggc_call_alloc> (&state);
450 timevar_pop (TV_PCH_PTR_REALLOC);
452 timevar_push (TV_PCH_PTR_SORT);
453 qsort (state.ptrs, state.count, sizeof (*state.ptrs), compare_ptr_data);
454 timevar_pop (TV_PCH_PTR_SORT);
456 /* Write out all the scalar variables. */
457 for (rt = gt_pch_scalar_rtab; *rt; rt++)
458 for (rti = *rt; rti->base != NULL; rti++)
459 if (fwrite (rti->base, rti->stride, 1, f) != 1)
460 fatal_error (input_location, "cannot write PCH file: %m");
462 /* Write out all the global pointers, after translation. */
463 write_pch_globals (gt_ggc_rtab, &state);
465 /* Pad the PCH file so that the mmapped area starts on an allocation
466 granularity (usually page) boundary. */
468 long o;
469 o = ftell (state.f) + sizeof (mmi);
470 if (o == -1)
471 fatal_error (input_location, "cannot get position in PCH file: %m");
472 mmi.offset = mmap_offset_alignment - o % mmap_offset_alignment;
473 if (mmi.offset == mmap_offset_alignment)
474 mmi.offset = 0;
475 mmi.offset += o;
477 if (fwrite (&mmi, sizeof (mmi), 1, state.f) != 1)
478 fatal_error (input_location, "cannot write PCH file: %m");
479 if (mmi.offset != 0
480 && fseek (state.f, mmi.offset, SEEK_SET) != 0)
481 fatal_error (input_location, "cannot write padding to PCH file: %m");
483 ggc_pch_prepare_write (state.d, state.f);
485 #if defined ENABLE_VALGRIND_ANNOTATIONS && defined VALGRIND_GET_VBITS
486 vec<char> vbits = vNULL;
487 #endif
489 /* Actually write out the objects. */
490 for (i = 0; i < state.count; i++)
492 if (this_object_size < state.ptrs[i]->size)
494 this_object_size = state.ptrs[i]->size;
495 this_object = XRESIZEVAR (char, this_object, this_object_size);
497 #if defined ENABLE_VALGRIND_ANNOTATIONS && defined VALGRIND_GET_VBITS
498 /* obj might contain uninitialized bytes, e.g. in the trailing
499 padding of the object. Avoid warnings by making the memory
500 temporarily defined and then restoring previous state. */
501 int get_vbits = 0;
502 size_t valid_size = state.ptrs[i]->size;
503 if (__builtin_expect (RUNNING_ON_VALGRIND, 0))
505 if (vbits.length () < valid_size)
506 vbits.safe_grow (valid_size, true);
507 get_vbits = VALGRIND_GET_VBITS (state.ptrs[i]->obj,
508 vbits.address (), valid_size);
509 if (get_vbits == 3)
511 /* We assume that first part of obj is addressable, and
512 the rest is unaddressable. Find out where the boundary is
513 using binary search. */
514 size_t lo = 0, hi = valid_size;
515 while (hi > lo)
517 size_t mid = (lo + hi) / 2;
518 get_vbits = VALGRIND_GET_VBITS ((char *) state.ptrs[i]->obj
519 + mid, vbits.address (),
521 if (get_vbits == 3)
522 hi = mid;
523 else if (get_vbits == 1)
524 lo = mid + 1;
525 else
526 break;
528 if (get_vbits == 1 || get_vbits == 3)
530 valid_size = lo;
531 get_vbits = VALGRIND_GET_VBITS (state.ptrs[i]->obj,
532 vbits.address (),
533 valid_size);
536 if (get_vbits == 1)
537 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (state.ptrs[i]->obj,
538 state.ptrs[i]->size));
540 #endif
541 memcpy (this_object, state.ptrs[i]->obj, state.ptrs[i]->size);
542 if (state.ptrs[i]->reorder_fn != NULL)
543 state.ptrs[i]->reorder_fn (state.ptrs[i]->obj,
544 state.ptrs[i]->note_ptr_cookie,
545 relocate_ptrs, &state);
546 state.ptrs[i]->note_ptr_fn (state.ptrs[i]->obj,
547 state.ptrs[i]->note_ptr_cookie,
548 relocate_ptrs, &state);
549 ggc_pch_write_object (state.d, state.f, state.ptrs[i]->obj,
550 state.ptrs[i]->new_addr, state.ptrs[i]->size,
551 state.ptrs[i]->note_ptr_fn == gt_pch_p_S);
552 if (state.ptrs[i]->note_ptr_fn != gt_pch_p_S)
553 memcpy (state.ptrs[i]->obj, this_object, state.ptrs[i]->size);
554 #if defined ENABLE_VALGRIND_ANNOTATIONS && defined VALGRIND_GET_VBITS
555 if (__builtin_expect (get_vbits == 1, 0))
557 (void) VALGRIND_SET_VBITS (state.ptrs[i]->obj, vbits.address (),
558 valid_size);
559 if (valid_size != state.ptrs[i]->size)
560 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS ((char *)
561 state.ptrs[i]->obj
562 + valid_size,
563 state.ptrs[i]->size
564 - valid_size));
566 #endif
568 #if defined ENABLE_VALGRIND_ANNOTATIONS && defined VALGRIND_GET_VBITS
569 vbits.release ();
570 #endif
572 ggc_pch_finish (state.d, state.f);
573 gt_pch_fixup_stringpool ();
575 XDELETE (state.ptrs);
576 XDELETE (this_object);
577 delete saving_htab;
578 saving_htab = NULL;
581 /* Read the state of the compiler back in from F. */
583 void
584 gt_pch_restore (FILE *f)
586 const struct ggc_root_tab *const *rt;
587 const struct ggc_root_tab *rti;
588 size_t i;
589 struct mmap_info mmi;
590 int result;
592 /* Delete any deletable objects. This makes ggc_pch_read much
593 faster, as it can be sure that no GCable objects remain other
594 than the ones just read in. */
595 for (rt = gt_ggc_deletable_rtab; *rt; rt++)
596 for (rti = *rt; rti->base != NULL; rti++)
597 memset (rti->base, 0, rti->stride);
599 /* Read in all the scalar variables. */
600 for (rt = gt_pch_scalar_rtab; *rt; rt++)
601 for (rti = *rt; rti->base != NULL; rti++)
602 if (fread (rti->base, rti->stride, 1, f) != 1)
603 fatal_error (input_location, "cannot read PCH file: %m");
605 /* Read in all the global pointers, in 6 easy loops. */
606 for (rt = gt_ggc_rtab; *rt; rt++)
607 for (rti = *rt; rti->base != NULL; rti++)
608 for (i = 0; i < rti->nelt; i++)
609 if (fread ((char *)rti->base + rti->stride * i,
610 sizeof (void *), 1, f) != 1)
611 fatal_error (input_location, "cannot read PCH file: %m");
613 if (fread (&mmi, sizeof (mmi), 1, f) != 1)
614 fatal_error (input_location, "cannot read PCH file: %m");
616 result = host_hooks.gt_pch_use_address (mmi.preferred_base, mmi.size,
617 fileno (f), mmi.offset);
618 if (result < 0)
619 fatal_error (input_location, "had to relocate PCH");
620 if (result == 0)
622 if (fseek (f, mmi.offset, SEEK_SET) != 0
623 || fread (mmi.preferred_base, mmi.size, 1, f) != 1)
624 fatal_error (input_location, "cannot read PCH file: %m");
626 else if (fseek (f, mmi.offset + mmi.size, SEEK_SET) != 0)
627 fatal_error (input_location, "cannot read PCH file: %m");
629 ggc_pch_read (f, mmi.preferred_base);
631 gt_pch_restore_stringpool ();
634 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS when mmap is not present.
635 Select no address whatsoever, and let gt_pch_save choose what it will with
636 malloc, presumably. */
638 void *
639 default_gt_pch_get_address (size_t size ATTRIBUTE_UNUSED,
640 int fd ATTRIBUTE_UNUSED)
642 return NULL;
645 /* Default version of HOST_HOOKS_GT_PCH_USE_ADDRESS when mmap is not present.
646 Allocate SIZE bytes with malloc. Return 0 if the address we got is the
647 same as base, indicating that the memory has been allocated but needs to
648 be read in from the file. Return -1 if the address differs, to relocation
649 of the PCH file would be required. */
652 default_gt_pch_use_address (void *base, size_t size, int fd ATTRIBUTE_UNUSED,
653 size_t offset ATTRIBUTE_UNUSED)
655 void *addr = xmalloc (size);
656 return (addr == base) - 1;
659 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS. Return the
660 alignment required for allocating virtual memory. Usually this is the
661 same as pagesize. */
663 size_t
664 default_gt_pch_alloc_granularity (void)
666 return getpagesize ();
669 #if HAVE_MMAP_FILE
670 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS when mmap is present.
671 We temporarily allocate SIZE bytes, and let the kernel place the data
672 wherever it will. If it worked, that's our spot, if not we're likely
673 to be in trouble. */
675 void *
676 mmap_gt_pch_get_address (size_t size, int fd)
678 void *ret;
680 ret = mmap (NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
681 if (ret == (void *) MAP_FAILED)
682 ret = NULL;
683 else
684 munmap ((caddr_t) ret, size);
686 return ret;
689 /* Default version of HOST_HOOKS_GT_PCH_USE_ADDRESS when mmap is present.
690 Map SIZE bytes of FD+OFFSET at BASE. Return 1 if we succeeded at
691 mapping the data at BASE, -1 if we couldn't.
693 This version assumes that the kernel honors the START operand of mmap
694 even without MAP_FIXED if START through START+SIZE are not currently
695 mapped with something. */
698 mmap_gt_pch_use_address (void *base, size_t size, int fd, size_t offset)
700 void *addr;
702 /* We're called with size == 0 if we're not planning to load a PCH
703 file at all. This allows the hook to free any static space that
704 we might have allocated at link time. */
705 if (size == 0)
706 return -1;
708 addr = mmap ((caddr_t) base, size, PROT_READ | PROT_WRITE, MAP_PRIVATE,
709 fd, offset);
711 return addr == base ? 1 : -1;
713 #endif /* HAVE_MMAP_FILE */
715 #if !defined ENABLE_GC_CHECKING && !defined ENABLE_GC_ALWAYS_COLLECT
717 /* Modify the bound based on rlimits. */
718 static double
719 ggc_rlimit_bound (double limit)
721 #if defined(HAVE_GETRLIMIT)
722 struct rlimit rlim;
723 # if defined (RLIMIT_AS)
724 /* RLIMIT_AS is what POSIX says is the limit on mmap. Presumably
725 any OS which has RLIMIT_AS also has a working mmap that GCC will use. */
726 if (getrlimit (RLIMIT_AS, &rlim) == 0
727 && rlim.rlim_cur != (rlim_t) RLIM_INFINITY
728 && rlim.rlim_cur < limit)
729 limit = rlim.rlim_cur;
730 # elif defined (RLIMIT_DATA)
731 /* ... but some older OSs bound mmap based on RLIMIT_DATA, or we
732 might be on an OS that has a broken mmap. (Others don't bound
733 mmap at all, apparently.) */
734 if (getrlimit (RLIMIT_DATA, &rlim) == 0
735 && rlim.rlim_cur != (rlim_t) RLIM_INFINITY
736 && rlim.rlim_cur < limit
737 /* Darwin has this horribly bogus default setting of
738 RLIMIT_DATA, to 6144Kb. No-one notices because RLIMIT_DATA
739 appears to be ignored. Ignore such silliness. If a limit
740 this small was actually effective for mmap, GCC wouldn't even
741 start up. */
742 && rlim.rlim_cur >= 8 * ONE_M)
743 limit = rlim.rlim_cur;
744 # endif /* RLIMIT_AS or RLIMIT_DATA */
745 #endif /* HAVE_GETRLIMIT */
747 return limit;
750 /* Heuristic to set a default for GGC_MIN_EXPAND. */
751 static int
752 ggc_min_expand_heuristic (void)
754 double min_expand = physmem_total ();
756 /* Adjust for rlimits. */
757 min_expand = ggc_rlimit_bound (min_expand);
759 /* The heuristic is a percentage equal to 30% + 70%*(RAM/1GB), yielding
760 a lower bound of 30% and an upper bound of 100% (when RAM >= 1GB). */
761 min_expand /= ONE_G;
762 min_expand *= 70;
763 min_expand = MIN (min_expand, 70);
764 min_expand += 30;
766 return min_expand;
769 /* Heuristic to set a default for GGC_MIN_HEAPSIZE. */
770 static int
771 ggc_min_heapsize_heuristic (void)
773 double phys_kbytes = physmem_total ();
774 double limit_kbytes = ggc_rlimit_bound (phys_kbytes * 2);
776 phys_kbytes /= ONE_K; /* Convert to Kbytes. */
777 limit_kbytes /= ONE_K;
779 /* The heuristic is RAM/8, with a lower bound of 4M and an upper
780 bound of 128M (when RAM >= 1GB). */
781 phys_kbytes /= 8;
783 #if defined(HAVE_GETRLIMIT) && defined (RLIMIT_RSS)
784 /* Try not to overrun the RSS limit while doing garbage collection.
785 The RSS limit is only advisory, so no margin is subtracted. */
787 struct rlimit rlim;
788 if (getrlimit (RLIMIT_RSS, &rlim) == 0
789 && rlim.rlim_cur != (rlim_t) RLIM_INFINITY)
790 phys_kbytes = MIN (phys_kbytes, rlim.rlim_cur / ONE_K);
792 # endif
794 /* Don't blindly run over our data limit; do GC at least when the
795 *next* GC would be within 20Mb of the limit or within a quarter of
796 the limit, whichever is larger. If GCC does hit the data limit,
797 compilation will fail, so this tries to be conservative. */
798 limit_kbytes = MAX (0, limit_kbytes - MAX (limit_kbytes / 4, 20 * ONE_K));
799 limit_kbytes = (limit_kbytes * 100) / (110 + ggc_min_expand_heuristic ());
800 phys_kbytes = MIN (phys_kbytes, limit_kbytes);
802 phys_kbytes = MAX (phys_kbytes, 4 * ONE_K);
803 phys_kbytes = MIN (phys_kbytes, 128 * ONE_K);
805 return phys_kbytes;
807 #endif
809 void
810 init_ggc_heuristics (void)
812 #if !defined ENABLE_GC_CHECKING && !defined ENABLE_GC_ALWAYS_COLLECT
813 param_ggc_min_expand = ggc_min_expand_heuristic ();
814 param_ggc_min_heapsize = ggc_min_heapsize_heuristic ();
815 #endif
818 /* GGC memory usage. */
819 class ggc_usage: public mem_usage
821 public:
822 /* Default constructor. */
823 ggc_usage (): m_freed (0), m_collected (0), m_overhead (0) {}
824 /* Constructor. */
825 ggc_usage (size_t allocated, size_t times, size_t peak,
826 size_t freed, size_t collected, size_t overhead)
827 : mem_usage (allocated, times, peak),
828 m_freed (freed), m_collected (collected), m_overhead (overhead) {}
830 /* Equality operator. */
831 inline bool
832 operator== (const ggc_usage &second) const
834 return (get_balance () == second.get_balance ()
835 && m_peak == second.m_peak
836 && m_times == second.m_times);
839 /* Comparison operator. */
840 inline bool
841 operator< (const ggc_usage &second) const
843 if (*this == second)
844 return false;
846 return (get_balance () == second.get_balance () ?
847 (m_peak == second.m_peak ? m_times < second.m_times
848 : m_peak < second.m_peak)
849 : get_balance () < second.get_balance ());
852 /* Register overhead of ALLOCATED and OVERHEAD bytes. */
853 inline void
854 register_overhead (size_t allocated, size_t overhead)
856 m_allocated += allocated;
857 m_overhead += overhead;
858 m_times++;
861 /* Release overhead of SIZE bytes. */
862 inline void
863 release_overhead (size_t size)
865 m_freed += size;
868 /* Sum the usage with SECOND usage. */
869 ggc_usage
870 operator+ (const ggc_usage &second)
872 return ggc_usage (m_allocated + second.m_allocated,
873 m_times + second.m_times,
874 m_peak + second.m_peak,
875 m_freed + second.m_freed,
876 m_collected + second.m_collected,
877 m_overhead + second.m_overhead);
880 /* Dump usage with PREFIX, where TOTAL is sum of all rows. */
881 inline void
882 dump (const char *prefix, ggc_usage &total) const
884 size_t balance = get_balance ();
885 fprintf (stderr,
886 "%-48s " PRsa (9) ":%5.1f%%" PRsa (9) ":%5.1f%%"
887 PRsa (9) ":%5.1f%%" PRsa (9) ":%5.1f%%" PRsa (9) "\n",
888 prefix,
889 SIZE_AMOUNT (balance), get_percent (balance, total.get_balance ()),
890 SIZE_AMOUNT (m_collected),
891 get_percent (m_collected, total.m_collected),
892 SIZE_AMOUNT (m_freed), get_percent (m_freed, total.m_freed),
893 SIZE_AMOUNT (m_overhead),
894 get_percent (m_overhead, total.m_overhead),
895 SIZE_AMOUNT (m_times));
898 /* Dump usage coupled to LOC location, where TOTAL is sum of all rows. */
899 inline void
900 dump (mem_location *loc, ggc_usage &total) const
902 char *location_string = loc->to_string ();
904 dump (location_string, total);
906 free (location_string);
909 /* Dump footer. */
910 inline void
911 dump_footer ()
913 dump ("Total", *this);
916 /* Get balance which is GGC allocation leak. */
917 inline size_t
918 get_balance () const
920 return m_allocated + m_overhead - m_collected - m_freed;
923 typedef std::pair<mem_location *, ggc_usage *> mem_pair_t;
925 /* Compare wrapper used by qsort method. */
926 static int
927 compare (const void *first, const void *second)
929 const mem_pair_t mem1 = *(const mem_pair_t *) first;
930 const mem_pair_t mem2 = *(const mem_pair_t *) second;
932 size_t balance1 = mem1.second->get_balance ();
933 size_t balance2 = mem2.second->get_balance ();
935 return balance1 == balance2 ? 0 : (balance1 < balance2 ? 1 : -1);
938 /* Dump header with NAME. */
939 static inline void
940 dump_header (const char *name)
942 fprintf (stderr, "%-48s %11s%17s%17s%16s%17s\n", name, "Leak", "Garbage",
943 "Freed", "Overhead", "Times");
946 /* Freed memory in bytes. */
947 size_t m_freed;
948 /* Collected memory in bytes. */
949 size_t m_collected;
950 /* Overhead memory in bytes. */
951 size_t m_overhead;
954 /* GCC memory description. */
955 static mem_alloc_description<ggc_usage> ggc_mem_desc;
957 /* Dump per-site memory statistics. */
959 void
960 dump_ggc_loc_statistics ()
962 if (! GATHER_STATISTICS)
963 return;
965 ggc_collect (GGC_COLLECT_FORCE);
967 ggc_mem_desc.dump (GGC_ORIGIN);
970 /* Record ALLOCATED and OVERHEAD bytes to descriptor NAME:LINE (FUNCTION). */
971 void
972 ggc_record_overhead (size_t allocated, size_t overhead, void *ptr MEM_STAT_DECL)
974 ggc_usage *usage = ggc_mem_desc.register_descriptor (ptr, GGC_ORIGIN, false
975 FINAL_PASS_MEM_STAT);
977 ggc_mem_desc.register_object_overhead (usage, allocated + overhead, ptr);
978 usage->register_overhead (allocated, overhead);
981 /* Notice that the pointer has been freed. */
982 void
983 ggc_free_overhead (void *ptr)
985 ggc_mem_desc.release_object_overhead (ptr);
988 /* After live values has been marked, walk all recorded pointers and see if
989 they are still live. */
990 void
991 ggc_prune_overhead_list (void)
993 typedef hash_map<const void *, std::pair<ggc_usage *, size_t > > map_t;
995 map_t::iterator it = ggc_mem_desc.m_reverse_object_map->begin ();
997 for (; it != ggc_mem_desc.m_reverse_object_map->end (); ++it)
998 if (!ggc_marked_p ((*it).first))
1000 (*it).second.first->m_collected += (*it).second.second;
1001 ggc_mem_desc.m_reverse_object_map->remove ((*it).first);
1005 /* Print memory used by heap if this info is available. */
1007 void
1008 report_heap_memory_use ()
1010 #if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
1011 #ifdef HAVE_MALLINFO2
1012 #define MALLINFO_FN mallinfo2
1013 #else
1014 #define MALLINFO_FN mallinfo
1015 #endif
1016 if (!quiet_flag)
1017 fprintf (stderr, " {heap " PRsa (0) "}",
1018 SIZE_AMOUNT (MALLINFO_FN ().arena));
1019 #endif