OSDN Git Service

2010-05-26 Richard Guenther <rguenther@suse.de>
[pf3gnuchains/gcc-fork.git] / gcc / ggc-common.c
1 /* Simple garbage collection for the GNU compiler.
2    Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
3    2009, 2010 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
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/>.  */
20
21 /* Generic garbage collection (GC) functions and data, not specific to
22    any particular GC implementation.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "hashtab.h"
28 #include "ggc.h"
29 #include "toplev.h"
30 #include "params.h"
31 #include "hosthooks.h"
32 #include "hosthooks-def.h"
33 #include "plugin.h"
34 #include "vec.h"
35 #include "timevar.h"
36
37 #ifdef HAVE_SYS_RESOURCE_H
38 # include <sys/resource.h>
39 #endif
40
41 #ifdef HAVE_MMAP_FILE
42 # include <sys/mman.h>
43 # ifdef HAVE_MINCORE
44 /* This is on Solaris.  */
45 #  include <sys/types.h>
46 # endif
47 #endif
48
49 #ifndef MAP_FAILED
50 # define MAP_FAILED ((void *)-1)
51 #endif
52
53 /* When set, ggc_collect will do collection.  */
54 bool ggc_force_collect;
55
56 /* When true, protect the contents of the identifier hash table.  */
57 bool ggc_protect_identifiers = true;
58
59 /* Statistics about the allocation.  */
60 static ggc_statistics *ggc_stats;
61
62 struct traversal_state;
63
64 static int ggc_htab_delete (void **, void *);
65 static hashval_t saving_htab_hash (const void *);
66 static int saving_htab_eq (const void *, const void *);
67 static int call_count (void **, void *);
68 static int call_alloc (void **, void *);
69 static int compare_ptr_data (const void *, const void *);
70 static void relocate_ptrs (void *, void *);
71 static void write_pch_globals (const struct ggc_root_tab * const *tab,
72                                struct traversal_state *state);
73
74 /* Maintain global roots that are preserved during GC.  */
75
76 /* Process a slot of an htab by deleting it if it has not been marked.  */
77
78 static int
79 ggc_htab_delete (void **slot, void *info)
80 {
81   const struct ggc_cache_tab *r = (const struct ggc_cache_tab *) info;
82
83   if (! (*r->marked_p) (*slot))
84     htab_clear_slot (*r->base, slot);
85   else
86     (*r->cb) (*slot);
87
88   return 1;
89 }
90
91
92 /* This extra vector of dynamically registered root_tab-s is used by
93    ggc_mark_roots and gives the ability to dynamically add new GGC root
94    tables, for instance from some plugins; this vector is on the heap
95    since it is used by GGC internally.  */
96 typedef const struct ggc_root_tab *const_ggc_root_tab_t;
97 DEF_VEC_P(const_ggc_root_tab_t);
98 DEF_VEC_ALLOC_P(const_ggc_root_tab_t, heap);
99 static VEC(const_ggc_root_tab_t, heap) *extra_root_vec;
100
101 /* Dynamically register a new GGC root table RT. This is useful for
102    plugins. */
103
104 void
105 ggc_register_root_tab (const struct ggc_root_tab* rt)
106 {
107   if (rt)
108     VEC_safe_push (const_ggc_root_tab_t, heap, extra_root_vec, rt);
109 }
110
111 /* This extra vector of dynamically registered cache_tab-s is used by
112    ggc_mark_roots and gives the ability to dynamically add new GGC cache
113    tables, for instance from some plugins; this vector is on the heap
114    since it is used by GGC internally.  */
115 typedef const struct ggc_cache_tab *const_ggc_cache_tab_t;
116 DEF_VEC_P(const_ggc_cache_tab_t);
117 DEF_VEC_ALLOC_P(const_ggc_cache_tab_t, heap);
118 static VEC(const_ggc_cache_tab_t, heap) *extra_cache_vec;
119
120 /* Dynamically register a new GGC cache table CT. This is useful for
121    plugins. */
122
123 void
124 ggc_register_cache_tab (const struct ggc_cache_tab* ct)
125 {
126   if (ct)
127     VEC_safe_push (const_ggc_cache_tab_t, heap, extra_cache_vec, ct);
128 }
129
130 /* Scan a hash table that has objects which are to be deleted if they are not
131    already marked.  */
132
133 static void
134 ggc_scan_cache_tab (const_ggc_cache_tab_t ctp)
135 {
136   const struct ggc_cache_tab *cti;
137
138   for (cti = ctp; cti->base != NULL; cti++)
139     if (*cti->base)
140       {
141         ggc_set_mark (*cti->base);
142         htab_traverse_noresize (*cti->base, ggc_htab_delete,
143                                 CONST_CAST (void *, (const void *)cti));
144         ggc_set_mark ((*cti->base)->entries);
145       }
146 }
147
148 /* Iterate through all registered roots and mark each element.  */
149
150 void
151 ggc_mark_roots (void)
152 {
153   const struct ggc_root_tab *const *rt;
154   const struct ggc_root_tab *rti;
155   const_ggc_root_tab_t rtp;
156   const struct ggc_cache_tab *const *ct;
157   const_ggc_cache_tab_t ctp;
158   size_t i;
159
160   for (rt = gt_ggc_deletable_rtab; *rt; rt++)
161     for (rti = *rt; rti->base != NULL; rti++)
162       memset (rti->base, 0, rti->stride);
163
164   for (rt = gt_ggc_rtab; *rt; rt++)
165     for (rti = *rt; rti->base != NULL; rti++)
166       for (i = 0; i < rti->nelt; i++)
167         (*rti->cb) (*(void **)((char *)rti->base + rti->stride * i));
168
169   for (i = 0; VEC_iterate (const_ggc_root_tab_t, extra_root_vec, i, rtp); i++)
170     {
171       for (rti = rtp; rti->base != NULL; rti++)
172         for (i = 0; i < rti->nelt; i++)
173           (*rti->cb) (*(void **) ((char *)rti->base + rti->stride * i));
174     }
175
176   if (ggc_protect_identifiers)
177     ggc_mark_stringpool ();
178
179   /* Now scan all hash tables that have objects which are to be deleted if
180      they are not already marked.  */
181   for (ct = gt_ggc_cache_rtab; *ct; ct++)
182     ggc_scan_cache_tab (*ct);
183
184   for (i = 0; VEC_iterate (const_ggc_cache_tab_t, extra_cache_vec, i, ctp); i++)
185     ggc_scan_cache_tab (ctp);
186
187   if (! ggc_protect_identifiers)
188     ggc_purge_stringpool ();
189
190   /* Some plugins may call ggc_set_mark from here.  */
191   invoke_plugin_callbacks (PLUGIN_GGC_MARKING, NULL);
192 }
193
194 /* Allocate a block of memory, then clear it.  */
195 void *
196 ggc_alloc_cleared_stat (size_t size MEM_STAT_DECL)
197 {
198   void *buf = ggc_alloc_stat (size PASS_MEM_STAT);
199   memset (buf, 0, size);
200   return buf;
201 }
202
203 /* Resize a block of memory, possibly re-allocating it.  */
204 void *
205 ggc_realloc_stat (void *x, size_t size MEM_STAT_DECL)
206 {
207   void *r;
208   size_t old_size;
209
210   if (x == NULL)
211     return ggc_alloc_stat (size PASS_MEM_STAT);
212
213   old_size = ggc_get_size (x);
214
215   if (size <= old_size)
216     {
217       /* Mark the unwanted memory as unaccessible.  We also need to make
218          the "new" size accessible, since ggc_get_size returns the size of
219          the pool, not the size of the individually allocated object, the
220          size which was previously made accessible.  Unfortunately, we
221          don't know that previously allocated size.  Without that
222          knowledge we have to lose some initialization-tracking for the
223          old parts of the object.  An alternative is to mark the whole
224          old_size as reachable, but that would lose tracking of writes
225          after the end of the object (by small offsets).  Discard the
226          handle to avoid handle leak.  */
227       VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS ((char *) x + size,
228                                                     old_size - size));
229       VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (x, size));
230       return x;
231     }
232
233   r = ggc_alloc_stat (size PASS_MEM_STAT);
234
235   /* Since ggc_get_size returns the size of the pool, not the size of the
236      individually allocated object, we'd access parts of the old object
237      that were marked invalid with the memcpy below.  We lose a bit of the
238      initialization-tracking since some of it may be uninitialized.  */
239   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (x, old_size));
240
241   memcpy (r, x, old_size);
242
243   /* The old object is not supposed to be used anymore.  */
244   ggc_free (x);
245
246   return r;
247 }
248
249 /* Like ggc_alloc_cleared, but performs a multiplication.  */
250 void *
251 ggc_calloc (size_t s1, size_t s2)
252 {
253   return ggc_alloc_cleared (s1 * s2);
254 }
255
256 /* These are for splay_tree_new_ggc.  */
257 void *
258 ggc_splay_alloc (int sz, void *nl)
259 {
260   gcc_assert (!nl);
261   return ggc_alloc (sz);
262 }
263
264 void
265 ggc_splay_dont_free (void * x ATTRIBUTE_UNUSED, void *nl)
266 {
267   gcc_assert (!nl);
268 }
269
270 /* Print statistics that are independent of the collector in use.  */
271 #define SCALE(x) ((unsigned long) ((x) < 1024*10 \
272                   ? (x) \
273                   : ((x) < 1024*1024*10 \
274                      ? (x) / 1024 \
275                      : (x) / (1024*1024))))
276 #define LABEL(x) ((x) < 1024*10 ? ' ' : ((x) < 1024*1024*10 ? 'k' : 'M'))
277
278 void
279 ggc_print_common_statistics (FILE *stream ATTRIBUTE_UNUSED,
280                              ggc_statistics *stats)
281 {
282   /* Set the pointer so that during collection we will actually gather
283      the statistics.  */
284   ggc_stats = stats;
285
286   /* Then do one collection to fill in the statistics.  */
287   ggc_collect ();
288
289   /* At present, we don't really gather any interesting statistics.  */
290
291   /* Don't gather statistics any more.  */
292   ggc_stats = NULL;
293 }
294 \f
295 /* Functions for saving and restoring GCable memory to disk.  */
296
297 static htab_t saving_htab;
298
299 struct ptr_data
300 {
301   void *obj;
302   void *note_ptr_cookie;
303   gt_note_pointers note_ptr_fn;
304   gt_handle_reorder reorder_fn;
305   size_t size;
306   void *new_addr;
307   enum gt_types_enum type;
308 };
309
310 #define POINTER_HASH(x) (hashval_t)((long)x >> 3)
311
312 /* Register an object in the hash table.  */
313
314 int
315 gt_pch_note_object (void *obj, void *note_ptr_cookie,
316                     gt_note_pointers note_ptr_fn,
317                     enum gt_types_enum type)
318 {
319   struct ptr_data **slot;
320
321   if (obj == NULL || obj == (void *) 1)
322     return 0;
323
324   slot = (struct ptr_data **)
325     htab_find_slot_with_hash (saving_htab, obj, POINTER_HASH (obj),
326                               INSERT);
327   if (*slot != NULL)
328     {
329       gcc_assert ((*slot)->note_ptr_fn == note_ptr_fn
330                   && (*slot)->note_ptr_cookie == note_ptr_cookie);
331       return 0;
332     }
333
334   *slot = XCNEW (struct ptr_data);
335   (*slot)->obj = obj;
336   (*slot)->note_ptr_fn = note_ptr_fn;
337   (*slot)->note_ptr_cookie = note_ptr_cookie;
338   if (note_ptr_fn == gt_pch_p_S)
339     (*slot)->size = strlen ((const char *)obj) + 1;
340   else
341     (*slot)->size = ggc_get_size (obj);
342   (*slot)->type = type;
343   return 1;
344 }
345
346 /* Register an object in the hash table.  */
347
348 void
349 gt_pch_note_reorder (void *obj, void *note_ptr_cookie,
350                      gt_handle_reorder reorder_fn)
351 {
352   struct ptr_data *data;
353
354   if (obj == NULL || obj == (void *) 1)
355     return;
356
357   data = (struct ptr_data *)
358     htab_find_with_hash (saving_htab, obj, POINTER_HASH (obj));
359   gcc_assert (data && data->note_ptr_cookie == note_ptr_cookie);
360
361   data->reorder_fn = reorder_fn;
362 }
363
364 /* Hash and equality functions for saving_htab, callbacks for htab_create.  */
365
366 static hashval_t
367 saving_htab_hash (const void *p)
368 {
369   return POINTER_HASH (((const struct ptr_data *)p)->obj);
370 }
371
372 static int
373 saving_htab_eq (const void *p1, const void *p2)
374 {
375   return ((const struct ptr_data *)p1)->obj == p2;
376 }
377
378 /* Handy state for the traversal functions.  */
379
380 struct traversal_state
381 {
382   FILE *f;
383   struct ggc_pch_data *d;
384   size_t count;
385   struct ptr_data **ptrs;
386   size_t ptrs_i;
387 };
388
389 /* Callbacks for htab_traverse.  */
390
391 static int
392 call_count (void **slot, void *state_p)
393 {
394   struct ptr_data *d = (struct ptr_data *)*slot;
395   struct traversal_state *state = (struct traversal_state *)state_p;
396
397   ggc_pch_count_object (state->d, d->obj, d->size,
398                         d->note_ptr_fn == gt_pch_p_S,
399                         d->type);
400   state->count++;
401   return 1;
402 }
403
404 static int
405 call_alloc (void **slot, void *state_p)
406 {
407   struct ptr_data *d = (struct ptr_data *)*slot;
408   struct traversal_state *state = (struct traversal_state *)state_p;
409
410   d->new_addr = ggc_pch_alloc_object (state->d, d->obj, d->size,
411                                       d->note_ptr_fn == gt_pch_p_S,
412                                       d->type);
413   state->ptrs[state->ptrs_i++] = d;
414   return 1;
415 }
416
417 /* Callback for qsort.  */
418
419 static int
420 compare_ptr_data (const void *p1_p, const void *p2_p)
421 {
422   const struct ptr_data *const p1 = *(const struct ptr_data *const *)p1_p;
423   const struct ptr_data *const p2 = *(const struct ptr_data *const *)p2_p;
424   return (((size_t)p1->new_addr > (size_t)p2->new_addr)
425           - ((size_t)p1->new_addr < (size_t)p2->new_addr));
426 }
427
428 /* Callbacks for note_ptr_fn.  */
429
430 static void
431 relocate_ptrs (void *ptr_p, void *state_p)
432 {
433   void **ptr = (void **)ptr_p;
434   struct traversal_state *state ATTRIBUTE_UNUSED
435     = (struct traversal_state *)state_p;
436   struct ptr_data *result;
437
438   if (*ptr == NULL || *ptr == (void *)1)
439     return;
440
441   result = (struct ptr_data *)
442     htab_find_with_hash (saving_htab, *ptr, POINTER_HASH (*ptr));
443   gcc_assert (result);
444   *ptr = result->new_addr;
445 }
446
447 /* Write out, after relocation, the pointers in TAB.  */
448 static void
449 write_pch_globals (const struct ggc_root_tab * const *tab,
450                    struct traversal_state *state)
451 {
452   const struct ggc_root_tab *const *rt;
453   const struct ggc_root_tab *rti;
454   size_t i;
455
456   for (rt = tab; *rt; rt++)
457     for (rti = *rt; rti->base != NULL; rti++)
458       for (i = 0; i < rti->nelt; i++)
459         {
460           void *ptr = *(void **)((char *)rti->base + rti->stride * i);
461           struct ptr_data *new_ptr;
462           if (ptr == NULL || ptr == (void *)1)
463             {
464               if (fwrite (&ptr, sizeof (void *), 1, state->f)
465                   != 1)
466                 fatal_error ("can't write PCH file: %m");
467             }
468           else
469             {
470               new_ptr = (struct ptr_data *)
471                 htab_find_with_hash (saving_htab, ptr, POINTER_HASH (ptr));
472               if (fwrite (&new_ptr->new_addr, sizeof (void *), 1, state->f)
473                   != 1)
474                 fatal_error ("can't write PCH file: %m");
475             }
476         }
477 }
478
479 /* Hold the information we need to mmap the file back in.  */
480
481 struct mmap_info
482 {
483   size_t offset;
484   size_t size;
485   void *preferred_base;
486 };
487
488 /* Write out the state of the compiler to F.  */
489
490 void
491 gt_pch_save (FILE *f)
492 {
493   const struct ggc_root_tab *const *rt;
494   const struct ggc_root_tab *rti;
495   size_t i;
496   struct traversal_state state;
497   char *this_object = NULL;
498   size_t this_object_size = 0;
499   struct mmap_info mmi;
500   const size_t mmap_offset_alignment = host_hooks.gt_pch_alloc_granularity();
501
502   gt_pch_save_stringpool ();
503
504   timevar_push (TV_PCH_PTR_REALLOC);
505   saving_htab = htab_create (50000, saving_htab_hash, saving_htab_eq, free);
506
507   for (rt = gt_ggc_rtab; *rt; rt++)
508     for (rti = *rt; rti->base != NULL; rti++)
509       for (i = 0; i < rti->nelt; i++)
510         (*rti->pchw)(*(void **)((char *)rti->base + rti->stride * i));
511
512   for (rt = gt_pch_cache_rtab; *rt; rt++)
513     for (rti = *rt; rti->base != NULL; rti++)
514       for (i = 0; i < rti->nelt; i++)
515         (*rti->pchw)(*(void **)((char *)rti->base + rti->stride * i));
516
517   /* Prepare the objects for writing, determine addresses and such.  */
518   state.f = f;
519   state.d = init_ggc_pch();
520   state.count = 0;
521   htab_traverse (saving_htab, call_count, &state);
522
523   mmi.size = ggc_pch_total_size (state.d);
524
525   /* Try to arrange things so that no relocation is necessary, but
526      don't try very hard.  On most platforms, this will always work,
527      and on the rest it's a lot of work to do better.
528      (The extra work goes in HOST_HOOKS_GT_PCH_GET_ADDRESS and
529      HOST_HOOKS_GT_PCH_USE_ADDRESS.)  */
530   mmi.preferred_base = host_hooks.gt_pch_get_address (mmi.size, fileno (f));
531
532   ggc_pch_this_base (state.d, mmi.preferred_base);
533
534   state.ptrs = XNEWVEC (struct ptr_data *, state.count);
535   state.ptrs_i = 0;
536
537   htab_traverse (saving_htab, call_alloc, &state);
538   timevar_pop (TV_PCH_PTR_REALLOC);
539
540   timevar_push (TV_PCH_PTR_SORT);
541   qsort (state.ptrs, state.count, sizeof (*state.ptrs), compare_ptr_data);
542   timevar_pop (TV_PCH_PTR_SORT);
543
544   /* Write out all the scalar variables.  */
545   for (rt = gt_pch_scalar_rtab; *rt; rt++)
546     for (rti = *rt; rti->base != NULL; rti++)
547       if (fwrite (rti->base, rti->stride, 1, f) != 1)
548         fatal_error ("can't write PCH file: %m");
549
550   /* Write out all the global pointers, after translation.  */
551   write_pch_globals (gt_ggc_rtab, &state);
552   write_pch_globals (gt_pch_cache_rtab, &state);
553
554   /* Pad the PCH file so that the mmapped area starts on an allocation
555      granularity (usually page) boundary.  */
556   {
557     long o;
558     o = ftell (state.f) + sizeof (mmi);
559     if (o == -1)
560       fatal_error ("can't get position in PCH file: %m");
561     mmi.offset = mmap_offset_alignment - o % mmap_offset_alignment;
562     if (mmi.offset == mmap_offset_alignment)
563       mmi.offset = 0;
564     mmi.offset += o;
565   }
566   if (fwrite (&mmi, sizeof (mmi), 1, state.f) != 1)
567     fatal_error ("can't write PCH file: %m");
568   if (mmi.offset != 0
569       && fseek (state.f, mmi.offset, SEEK_SET) != 0)
570     fatal_error ("can't write padding to PCH file: %m");
571
572   ggc_pch_prepare_write (state.d, state.f);
573
574   /* Actually write out the objects.  */
575   for (i = 0; i < state.count; i++)
576     {
577       if (this_object_size < state.ptrs[i]->size)
578         {
579           this_object_size = state.ptrs[i]->size;
580           this_object = XRESIZEVAR (char, this_object, this_object_size);
581         }
582       memcpy (this_object, state.ptrs[i]->obj, state.ptrs[i]->size);
583       if (state.ptrs[i]->reorder_fn != NULL)
584         state.ptrs[i]->reorder_fn (state.ptrs[i]->obj,
585                                    state.ptrs[i]->note_ptr_cookie,
586                                    relocate_ptrs, &state);
587       state.ptrs[i]->note_ptr_fn (state.ptrs[i]->obj,
588                                   state.ptrs[i]->note_ptr_cookie,
589                                   relocate_ptrs, &state);
590       ggc_pch_write_object (state.d, state.f, state.ptrs[i]->obj,
591                             state.ptrs[i]->new_addr, state.ptrs[i]->size,
592                             state.ptrs[i]->note_ptr_fn == gt_pch_p_S);
593       if (state.ptrs[i]->note_ptr_fn != gt_pch_p_S)
594         memcpy (state.ptrs[i]->obj, this_object, state.ptrs[i]->size);
595     }
596   ggc_pch_finish (state.d, state.f);
597   gt_pch_fixup_stringpool ();
598
599   free (state.ptrs);
600   htab_delete (saving_htab);
601 }
602
603 /* Read the state of the compiler back in from F.  */
604
605 void
606 gt_pch_restore (FILE *f)
607 {
608   const struct ggc_root_tab *const *rt;
609   const struct ggc_root_tab *rti;
610   size_t i;
611   struct mmap_info mmi;
612   int result;
613
614   /* Delete any deletable objects.  This makes ggc_pch_read much
615      faster, as it can be sure that no GCable objects remain other
616      than the ones just read in.  */
617   for (rt = gt_ggc_deletable_rtab; *rt; rt++)
618     for (rti = *rt; rti->base != NULL; rti++)
619       memset (rti->base, 0, rti->stride);
620
621   /* Read in all the scalar variables.  */
622   for (rt = gt_pch_scalar_rtab; *rt; rt++)
623     for (rti = *rt; rti->base != NULL; rti++)
624       if (fread (rti->base, rti->stride, 1, f) != 1)
625         fatal_error ("can't read PCH file: %m");
626
627   /* Read in all the global pointers, in 6 easy loops.  */
628   for (rt = gt_ggc_rtab; *rt; rt++)
629     for (rti = *rt; rti->base != NULL; rti++)
630       for (i = 0; i < rti->nelt; i++)
631         if (fread ((char *)rti->base + rti->stride * i,
632                    sizeof (void *), 1, f) != 1)
633           fatal_error ("can't read PCH file: %m");
634
635   for (rt = gt_pch_cache_rtab; *rt; rt++)
636     for (rti = *rt; rti->base != NULL; rti++)
637       for (i = 0; i < rti->nelt; i++)
638         if (fread ((char *)rti->base + rti->stride * i,
639                    sizeof (void *), 1, f) != 1)
640           fatal_error ("can't read PCH file: %m");
641
642   if (fread (&mmi, sizeof (mmi), 1, f) != 1)
643     fatal_error ("can't read PCH file: %m");
644
645   result = host_hooks.gt_pch_use_address (mmi.preferred_base, mmi.size,
646                                           fileno (f), mmi.offset);
647   if (result < 0)
648     fatal_error ("had to relocate PCH");
649   if (result == 0)
650     {
651       if (fseek (f, mmi.offset, SEEK_SET) != 0
652           || fread (mmi.preferred_base, mmi.size, 1, f) != 1)
653         fatal_error ("can't read PCH file: %m");
654     }
655   else if (fseek (f, mmi.offset + mmi.size, SEEK_SET) != 0)
656     fatal_error ("can't read PCH file: %m");
657
658   ggc_pch_read (f, mmi.preferred_base);
659
660   gt_pch_restore_stringpool ();
661 }
662
663 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS when mmap is not present.
664    Select no address whatsoever, and let gt_pch_save choose what it will with
665    malloc, presumably.  */
666
667 void *
668 default_gt_pch_get_address (size_t size ATTRIBUTE_UNUSED,
669                             int fd ATTRIBUTE_UNUSED)
670 {
671   return NULL;
672 }
673
674 /* Default version of HOST_HOOKS_GT_PCH_USE_ADDRESS when mmap is not present.
675    Allocate SIZE bytes with malloc.  Return 0 if the address we got is the
676    same as base, indicating that the memory has been allocated but needs to
677    be read in from the file.  Return -1 if the address differs, to relocation
678    of the PCH file would be required.  */
679
680 int
681 default_gt_pch_use_address (void *base, size_t size, int fd ATTRIBUTE_UNUSED,
682                             size_t offset ATTRIBUTE_UNUSED)
683 {
684   void *addr = xmalloc (size);
685   return (addr == base) - 1;
686 }
687
688 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS.   Return the
689    alignment required for allocating virtual memory. Usually this is the
690    same as pagesize.  */
691
692 size_t
693 default_gt_pch_alloc_granularity (void)
694 {
695   return getpagesize();
696 }
697
698 #if HAVE_MMAP_FILE
699 /* Default version of HOST_HOOKS_GT_PCH_GET_ADDRESS when mmap is present.
700    We temporarily allocate SIZE bytes, and let the kernel place the data
701    wherever it will.  If it worked, that's our spot, if not we're likely
702    to be in trouble.  */
703
704 void *
705 mmap_gt_pch_get_address (size_t size, int fd)
706 {
707   void *ret;
708
709   ret = mmap (NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
710   if (ret == (void *) MAP_FAILED)
711     ret = NULL;
712   else
713     munmap ((caddr_t) ret, size);
714
715   return ret;
716 }
717
718 /* Default version of HOST_HOOKS_GT_PCH_USE_ADDRESS when mmap is present.
719    Map SIZE bytes of FD+OFFSET at BASE.  Return 1 if we succeeded at
720    mapping the data at BASE, -1 if we couldn't.
721
722    This version assumes that the kernel honors the START operand of mmap
723    even without MAP_FIXED if START through START+SIZE are not currently
724    mapped with something.  */
725
726 int
727 mmap_gt_pch_use_address (void *base, size_t size, int fd, size_t offset)
728 {
729   void *addr;
730
731   /* We're called with size == 0 if we're not planning to load a PCH
732      file at all.  This allows the hook to free any static space that
733      we might have allocated at link time.  */
734   if (size == 0)
735     return -1;
736
737   addr = mmap ((caddr_t) base, size, PROT_READ | PROT_WRITE, MAP_PRIVATE,
738                fd, offset);
739
740   return addr == base ? 1 : -1;
741 }
742 #endif /* HAVE_MMAP_FILE */
743
744 #if !defined ENABLE_GC_CHECKING && !defined ENABLE_GC_ALWAYS_COLLECT
745
746 /* Modify the bound based on rlimits.  */
747 static double
748 ggc_rlimit_bound (double limit)
749 {
750 #if defined(HAVE_GETRLIMIT)
751   struct rlimit rlim;
752 # if defined (RLIMIT_AS)
753   /* RLIMIT_AS is what POSIX says is the limit on mmap.  Presumably
754      any OS which has RLIMIT_AS also has a working mmap that GCC will use.  */
755   if (getrlimit (RLIMIT_AS, &rlim) == 0
756       && rlim.rlim_cur != (rlim_t) RLIM_INFINITY
757       && rlim.rlim_cur < limit)
758     limit = rlim.rlim_cur;
759 # elif defined (RLIMIT_DATA)
760   /* ... but some older OSs bound mmap based on RLIMIT_DATA, or we
761      might be on an OS that has a broken mmap.  (Others don't bound
762      mmap at all, apparently.)  */
763   if (getrlimit (RLIMIT_DATA, &rlim) == 0
764       && rlim.rlim_cur != (rlim_t) RLIM_INFINITY
765       && rlim.rlim_cur < limit
766       /* Darwin has this horribly bogus default setting of
767          RLIMIT_DATA, to 6144Kb.  No-one notices because RLIMIT_DATA
768          appears to be ignored.  Ignore such silliness.  If a limit
769          this small was actually effective for mmap, GCC wouldn't even
770          start up.  */
771       && rlim.rlim_cur >= 8 * 1024 * 1024)
772     limit = rlim.rlim_cur;
773 # endif /* RLIMIT_AS or RLIMIT_DATA */
774 #endif /* HAVE_GETRLIMIT */
775
776   return limit;
777 }
778
779 /* Heuristic to set a default for GGC_MIN_EXPAND.  */
780 static int
781 ggc_min_expand_heuristic (void)
782 {
783   double min_expand = physmem_total();
784
785   /* Adjust for rlimits.  */
786   min_expand = ggc_rlimit_bound (min_expand);
787
788   /* The heuristic is a percentage equal to 30% + 70%*(RAM/1GB), yielding
789      a lower bound of 30% and an upper bound of 100% (when RAM >= 1GB).  */
790   min_expand /= 1024*1024*1024;
791   min_expand *= 70;
792   min_expand = MIN (min_expand, 70);
793   min_expand += 30;
794
795   return min_expand;
796 }
797
798 /* Heuristic to set a default for GGC_MIN_HEAPSIZE.  */
799 static int
800 ggc_min_heapsize_heuristic (void)
801 {
802   double phys_kbytes = physmem_total();
803   double limit_kbytes = ggc_rlimit_bound (phys_kbytes * 2);
804
805   phys_kbytes /= 1024; /* Convert to Kbytes.  */
806   limit_kbytes /= 1024;
807
808   /* The heuristic is RAM/8, with a lower bound of 4M and an upper
809      bound of 128M (when RAM >= 1GB).  */
810   phys_kbytes /= 8;
811
812 #if defined(HAVE_GETRLIMIT) && defined (RLIMIT_RSS)
813   /* Try not to overrun the RSS limit while doing garbage collection.
814      The RSS limit is only advisory, so no margin is subtracted.  */
815  {
816    struct rlimit rlim;
817    if (getrlimit (RLIMIT_RSS, &rlim) == 0
818        && rlim.rlim_cur != (rlim_t) RLIM_INFINITY)
819      phys_kbytes = MIN (phys_kbytes, rlim.rlim_cur / 1024);
820  }
821 # endif
822
823   /* Don't blindly run over our data limit; do GC at least when the
824      *next* GC would be within 20Mb of the limit or within a quarter of
825      the limit, whichever is larger.  If GCC does hit the data limit,
826      compilation will fail, so this tries to be conservative.  */
827   limit_kbytes = MAX (0, limit_kbytes - MAX (limit_kbytes / 4, 20 * 1024));
828   limit_kbytes = (limit_kbytes * 100) / (110 + ggc_min_expand_heuristic());
829   phys_kbytes = MIN (phys_kbytes, limit_kbytes);
830
831   phys_kbytes = MAX (phys_kbytes, 4 * 1024);
832   phys_kbytes = MIN (phys_kbytes, 128 * 1024);
833
834   return phys_kbytes;
835 }
836 #endif
837
838 void
839 init_ggc_heuristics (void)
840 {
841 #if !defined ENABLE_GC_CHECKING && !defined ENABLE_GC_ALWAYS_COLLECT
842   set_param_value ("ggc-min-expand", ggc_min_expand_heuristic());
843   set_param_value ("ggc-min-heapsize", ggc_min_heapsize_heuristic());
844 #endif
845 }
846
847 #ifdef GATHER_STATISTICS
848
849 /* Datastructure used to store per-call-site statistics.  */
850 struct loc_descriptor
851 {
852   const char *file;
853   int line;
854   const char *function;
855   int times;
856   size_t allocated;
857   size_t overhead;
858   size_t freed;
859   size_t collected;
860 };
861
862 /* Hashtable used for statistics.  */
863 static htab_t loc_hash;
864
865 /* Hash table helpers functions.  */
866 static hashval_t
867 hash_descriptor (const void *p)
868 {
869   const struct loc_descriptor *const d = (const struct loc_descriptor *) p;
870
871   return htab_hash_pointer (d->function) | d->line;
872 }
873
874 static int
875 eq_descriptor (const void *p1, const void *p2)
876 {
877   const struct loc_descriptor *const d = (const struct loc_descriptor *) p1;
878   const struct loc_descriptor *const d2 = (const struct loc_descriptor *) p2;
879
880   return (d->file == d2->file && d->line == d2->line
881           && d->function == d2->function);
882 }
883
884 /* Hashtable converting address of allocated field to loc descriptor.  */
885 static htab_t ptr_hash;
886 struct ptr_hash_entry
887 {
888   void *ptr;
889   struct loc_descriptor *loc;
890   size_t size;
891 };
892
893 /* Hash table helpers functions.  */
894 static hashval_t
895 hash_ptr (const void *p)
896 {
897   const struct ptr_hash_entry *const d = (const struct ptr_hash_entry *) p;
898
899   return htab_hash_pointer (d->ptr);
900 }
901
902 static int
903 eq_ptr (const void *p1, const void *p2)
904 {
905   const struct ptr_hash_entry *const p = (const struct ptr_hash_entry *) p1;
906
907   return (p->ptr == p2);
908 }
909
910 /* Return descriptor for given call site, create new one if needed.  */
911 static struct loc_descriptor *
912 loc_descriptor (const char *name, int line, const char *function)
913 {
914   struct loc_descriptor loc;
915   struct loc_descriptor **slot;
916
917   loc.file = name;
918   loc.line = line;
919   loc.function = function;
920   if (!loc_hash)
921     loc_hash = htab_create (10, hash_descriptor, eq_descriptor, NULL);
922
923   slot = (struct loc_descriptor **) htab_find_slot (loc_hash, &loc, INSERT);
924   if (*slot)
925     return *slot;
926   *slot = XCNEW (struct loc_descriptor);
927   (*slot)->file = name;
928   (*slot)->line = line;
929   (*slot)->function = function;
930   return *slot;
931 }
932
933 /* Record ALLOCATED and OVERHEAD bytes to descriptor NAME:LINE (FUNCTION).  */
934 void
935 ggc_record_overhead (size_t allocated, size_t overhead, void *ptr,
936                      const char *name, int line, const char *function)
937 {
938   struct loc_descriptor *loc = loc_descriptor (name, line, function);
939   struct ptr_hash_entry *p = XNEW (struct ptr_hash_entry);
940   PTR *slot;
941
942   p->ptr = ptr;
943   p->loc = loc;
944   p->size = allocated + overhead;
945   if (!ptr_hash)
946     ptr_hash = htab_create (10, hash_ptr, eq_ptr, NULL);
947   slot = htab_find_slot_with_hash (ptr_hash, ptr, htab_hash_pointer (ptr), INSERT);
948   gcc_assert (!*slot);
949   *slot = p;
950
951   loc->times++;
952   loc->allocated+=allocated;
953   loc->overhead+=overhead;
954 }
955
956 /* Helper function for prune_overhead_list.  See if SLOT is still marked and
957    remove it from hashtable if it is not.  */
958 static int
959 ggc_prune_ptr (void **slot, void *b ATTRIBUTE_UNUSED)
960 {
961   struct ptr_hash_entry *p = (struct ptr_hash_entry *) *slot;
962   if (!ggc_marked_p (p->ptr))
963     {
964       p->loc->collected += p->size;
965       htab_clear_slot (ptr_hash, slot);
966       free (p);
967     }
968   return 1;
969 }
970
971 /* After live values has been marked, walk all recorded pointers and see if
972    they are still live.  */
973 void
974 ggc_prune_overhead_list (void)
975 {
976   htab_traverse (ptr_hash, ggc_prune_ptr, NULL);
977 }
978
979 /* Notice that the pointer has been freed.  */
980 void
981 ggc_free_overhead (void *ptr)
982 {
983   PTR *slot = htab_find_slot_with_hash (ptr_hash, ptr, htab_hash_pointer (ptr),
984                                         NO_INSERT);
985   struct ptr_hash_entry *p;
986   /* The pointer might be not found if a PCH read happened between allocation
987      and ggc_free () call.  FIXME: account memory properly in the presence of
988      PCH. */
989   if (!slot)
990       return;
991   p = (struct ptr_hash_entry *) *slot;
992   p->loc->freed += p->size;
993   htab_clear_slot (ptr_hash, slot);
994   free (p);
995 }
996
997 /* Helper for qsort; sort descriptors by amount of memory consumed.  */
998 static int
999 final_cmp_statistic (const void *loc1, const void *loc2)
1000 {
1001   const struct loc_descriptor *const l1 =
1002     *(const struct loc_descriptor *const *) loc1;
1003   const struct loc_descriptor *const l2 =
1004     *(const struct loc_descriptor *const *) loc2;
1005   long diff;
1006   diff = ((long)(l1->allocated + l1->overhead - l1->freed) -
1007           (l2->allocated + l2->overhead - l2->freed));
1008   return diff > 0 ? 1 : diff < 0 ? -1 : 0;
1009 }
1010
1011 /* Helper for qsort; sort descriptors by amount of memory consumed.  */
1012 static int
1013 cmp_statistic (const void *loc1, const void *loc2)
1014 {
1015   const struct loc_descriptor *const l1 =
1016     *(const struct loc_descriptor *const *) loc1;
1017   const struct loc_descriptor *const l2 =
1018     *(const struct loc_descriptor *const *) loc2;
1019   long diff;
1020
1021   diff = ((long)(l1->allocated + l1->overhead - l1->freed - l1->collected) -
1022           (l2->allocated + l2->overhead - l2->freed - l2->collected));
1023   if (diff)
1024     return diff > 0 ? 1 : diff < 0 ? -1 : 0;
1025   diff =  ((long)(l1->allocated + l1->overhead - l1->freed) -
1026            (l2->allocated + l2->overhead - l2->freed));
1027   return diff > 0 ? 1 : diff < 0 ? -1 : 0;
1028 }
1029
1030 /* Collect array of the descriptors from hashtable.  */
1031 static struct loc_descriptor **loc_array;
1032 static int
1033 add_statistics (void **slot, void *b)
1034 {
1035   int *n = (int *)b;
1036   loc_array[*n] = (struct loc_descriptor *) *slot;
1037   (*n)++;
1038   return 1;
1039 }
1040
1041 /* Dump per-site memory statistics.  */
1042 #endif
1043 void
1044 dump_ggc_loc_statistics (bool final ATTRIBUTE_UNUSED)
1045 {
1046 #ifdef GATHER_STATISTICS
1047   int nentries = 0;
1048   char s[4096];
1049   size_t collected = 0, freed = 0, allocated = 0, overhead = 0, times = 0;
1050   int i;
1051
1052   ggc_force_collect = true;
1053   ggc_collect ();
1054
1055   loc_array = XCNEWVEC (struct loc_descriptor *, loc_hash->n_elements);
1056   fprintf (stderr, "-------------------------------------------------------\n");
1057   fprintf (stderr, "\n%-48s %10s       %10s       %10s       %10s       %10s\n",
1058            "source location", "Garbage", "Freed", "Leak", "Overhead", "Times");
1059   fprintf (stderr, "-------------------------------------------------------\n");
1060   htab_traverse (loc_hash, add_statistics, &nentries);
1061   qsort (loc_array, nentries, sizeof (*loc_array),
1062          final ? final_cmp_statistic : cmp_statistic);
1063   for (i = 0; i < nentries; i++)
1064     {
1065       struct loc_descriptor *d = loc_array[i];
1066       allocated += d->allocated;
1067       times += d->times;
1068       freed += d->freed;
1069       collected += d->collected;
1070       overhead += d->overhead;
1071     }
1072   for (i = 0; i < nentries; i++)
1073     {
1074       struct loc_descriptor *d = loc_array[i];
1075       if (d->allocated)
1076         {
1077           const char *s1 = d->file;
1078           const char *s2;
1079           while ((s2 = strstr (s1, "gcc/")))
1080             s1 = s2 + 4;
1081           sprintf (s, "%s:%i (%s)", s1, d->line, d->function);
1082           s[48] = 0;
1083           fprintf (stderr, "%-48s %10li:%4.1f%% %10li:%4.1f%% %10li:%4.1f%% %10li:%4.1f%% %10li\n", s,
1084                    (long)d->collected,
1085                    (d->collected) * 100.0 / collected,
1086                    (long)d->freed,
1087                    (d->freed) * 100.0 / freed,
1088                    (long)(d->allocated + d->overhead - d->freed - d->collected),
1089                    (d->allocated + d->overhead - d->freed - d->collected) * 100.0
1090                    / (allocated + overhead - freed - collected),
1091                    (long)d->overhead,
1092                    d->overhead * 100.0 / overhead,
1093                    (long)d->times);
1094         }
1095     }
1096   fprintf (stderr, "%-48s %10ld       %10ld       %10ld       %10ld       %10ld\n",
1097            "Total", (long)collected, (long)freed,
1098            (long)(allocated + overhead - freed - collected), (long)overhead,
1099            (long)times);
1100   fprintf (stderr, "%-48s %10s       %10s       %10s       %10s       %10s\n",
1101            "source location", "Garbage", "Freed", "Leak", "Overhead", "Times");
1102   fprintf (stderr, "-------------------------------------------------------\n");
1103   ggc_force_collect = false;
1104 #endif
1105 }