OSDN Git Service

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