OSDN Git Service

* cgraph.h (cgraph_dump_file): Declare.
[pf3gnuchains/gcc-fork.git] / gcc / lto / lto.c
1 /* Top-level LTO routines.
2    Copyright 2009, 2010 Free Software Foundation, Inc.
3    Contributed by CodeSourcery, 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 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "opts.h"
25 #include "toplev.h"
26 #include "tree.h"
27 #include "diagnostic-core.h"
28 #include "tm.h"
29 #include "libiberty.h"
30 #include "cgraph.h"
31 #include "ggc.h"
32 #include "tree-ssa-operands.h"
33 #include "tree-pass.h"
34 #include "langhooks.h"
35 #include "vec.h"
36 #include "bitmap.h"
37 #include "pointer-set.h"
38 #include "ipa-prop.h"
39 #include "common.h"
40 #include "debug.h"
41 #include "timevar.h"
42 #include "gimple.h"
43 #include "lto.h"
44 #include "lto-tree.h"
45 #include "lto-streamer.h"
46
47 /* This needs to be included after config.h.  Otherwise, _GNU_SOURCE will not
48    be defined in time to set __USE_GNU in the system headers, and strsignal
49    will not be declared.  */
50 #if HAVE_MMAP_FILE
51 #include <sys/mman.h>
52 #endif
53
54 /* Handle opening elf files on hosts, such as Windows, that may use 
55    text file handling that will break binary access.  */
56
57 #ifndef O_BINARY
58 # define O_BINARY 0
59 #endif
60
61 static GTY(()) tree first_personality_decl;
62
63
64 /* Read the constructors and inits.  */
65
66 static void
67 lto_materialize_constructors_and_inits (struct lto_file_decl_data * file_data)
68 {
69   size_t len;
70   const char *data = lto_get_section_data (file_data, 
71                                            LTO_section_static_initializer,
72                                            NULL, &len);
73   lto_input_constructors_and_inits (file_data, data);
74   lto_free_section_data (file_data, LTO_section_static_initializer, NULL,
75                          data, len);
76 }
77
78 /* Read the function body for the function associated with NODE.  */
79
80 static void
81 lto_materialize_function (struct cgraph_node *node)
82 {
83   tree decl;
84   struct lto_file_decl_data *file_data;
85   const char *data, *name;
86   size_t len;
87
88   /* Ignore clone nodes.  Read the body only from the original one.
89      We may find clone nodes during LTRANS after WPA has made inlining
90      decisions.  */
91   if (node->clone_of)
92     return;
93
94   decl = node->decl;
95   file_data = node->local.lto_file_data;
96   name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)); 
97
98   /* We may have renamed the declaration, e.g., a static function.  */
99   name = lto_get_decl_name_mapping (file_data, name);
100
101   data = lto_get_section_data (file_data, LTO_section_function_body,
102                                name, &len);
103   if (data)
104     {
105       gcc_assert (!DECL_IS_BUILTIN (decl));
106
107       /* This function has a definition.  */
108       TREE_STATIC (decl) = 1;
109
110       gcc_assert (DECL_STRUCT_FUNCTION (decl) == NULL);
111
112       /* Load the function body only if not operating in WPA mode.  In
113          WPA mode, the body of the function is not needed.  */
114       if (!flag_wpa)
115         {
116           allocate_struct_function (decl, false);
117           announce_function (decl);
118           lto_input_function_body (file_data, decl, data);
119           if (DECL_FUNCTION_PERSONALITY (decl) && !first_personality_decl)
120             first_personality_decl = DECL_FUNCTION_PERSONALITY (decl);
121           lto_stats.num_function_bodies++;
122         }
123
124       lto_free_section_data (file_data, LTO_section_function_body, name,
125                              data, len);
126       if (!flag_wpa)
127         ggc_collect ();
128     }
129   else
130     DECL_EXTERNAL (decl) = 1;
131
132   /* Let the middle end know about the function.  */
133   rest_of_decl_compilation (decl, 1, 0);
134 }
135
136
137 /* Decode the content of memory pointed to by DATA in the the
138    in decl state object STATE. DATA_IN points to a data_in structure for
139    decoding. Return the address after the decoded object in the input.  */
140
141 static const uint32_t *
142 lto_read_in_decl_state (struct data_in *data_in, const uint32_t *data,
143                         struct lto_in_decl_state *state)
144 {
145   uint32_t ix;
146   tree decl;
147   uint32_t i, j;
148   
149   ix = *data++;
150   decl = lto_streamer_cache_get (data_in->reader_cache, (int) ix);
151   if (TREE_CODE (decl) != FUNCTION_DECL)
152     {
153       gcc_assert (decl == void_type_node);
154       decl = NULL_TREE;
155     }
156   state->fn_decl = decl;
157
158   for (i = 0; i < LTO_N_DECL_STREAMS; i++)
159     {
160       uint32_t size = *data++;
161       tree *decls = GGC_NEWVEC (tree, size);
162
163       for (j = 0; j < size; j++)
164         {
165           decls[j] = lto_streamer_cache_get (data_in->reader_cache, data[j]);
166
167           /* Register every type in the global type table.  If the
168              type existed already, use the existing type.  */
169           if (TYPE_P (decls[j]))
170             decls[j] = gimple_register_type (decls[j]);
171         }
172
173       state->streams[i].size = size;
174       state->streams[i].trees = decls;
175       data += size;
176     }
177
178   return data;
179 }
180
181
182 /* Read all the symbols from buffer DATA, using descriptors in DECL_DATA.
183    RESOLUTIONS is the set of symbols picked by the linker (read from the
184    resolution file when the linker plugin is being used).  */
185
186 static void
187 lto_read_decls (struct lto_file_decl_data *decl_data, const void *data,
188                 VEC(ld_plugin_symbol_resolution_t,heap) *resolutions)
189 {
190   const struct lto_decl_header *header = (const struct lto_decl_header *) data;
191   const int32_t decl_offset = sizeof (struct lto_decl_header);
192   const int32_t main_offset = decl_offset + header->decl_state_size;
193   const int32_t string_offset = main_offset + header->main_size;
194   struct lto_input_block ib_main;
195   struct data_in *data_in;
196   unsigned int i;
197   const uint32_t *data_ptr, *data_end;
198   uint32_t num_decl_states;
199
200   LTO_INIT_INPUT_BLOCK (ib_main, (const char *) data + main_offset, 0,
201                         header->main_size);
202
203   data_in = lto_data_in_create (decl_data, (const char *) data + string_offset,
204                                 header->string_size, resolutions);
205
206   /* Read the global declarations and types.  */
207   while (ib_main.p < ib_main.len)
208     {
209       tree t = lto_input_tree (&ib_main, data_in);
210       gcc_assert (t && ib_main.p <= ib_main.len);
211     }
212
213   /* Read in lto_in_decl_state objects.  */
214   data_ptr = (const uint32_t *) ((const char*) data + decl_offset); 
215   data_end =
216      (const uint32_t *) ((const char*) data_ptr + header->decl_state_size);
217   num_decl_states = *data_ptr++;
218   
219   gcc_assert (num_decl_states > 0);
220   decl_data->global_decl_state = lto_new_in_decl_state ();
221   data_ptr = lto_read_in_decl_state (data_in, data_ptr,
222                                      decl_data->global_decl_state);
223
224   /* Read in per-function decl states and enter them in hash table.  */
225   decl_data->function_decl_states =
226     htab_create_ggc (37, lto_hash_in_decl_state, lto_eq_in_decl_state, NULL);
227
228   for (i = 1; i < num_decl_states; i++)
229     {
230       struct lto_in_decl_state *state = lto_new_in_decl_state ();
231       void **slot;
232
233       data_ptr = lto_read_in_decl_state (data_in, data_ptr, state);
234       slot = htab_find_slot (decl_data->function_decl_states, state, INSERT);
235       gcc_assert (*slot == NULL);
236       *slot = state;
237     }
238
239   if (data_ptr != data_end)
240     internal_error ("bytecode stream: garbage at the end of symbols section");
241   
242   /* Set the current decl state to be the global state. */
243   decl_data->current_decl_state = decl_data->global_decl_state;
244
245   lto_data_in_delete (data_in);
246 }
247
248 /* strtoll is not portable. */
249 int64_t
250 lto_parse_hex (const char *p) {
251   uint64_t ret = 0;
252   for (; *p != '\0'; ++p)
253     {
254       char c = *p;
255       unsigned char part;
256       ret <<= 4;
257       if (c >= '0' && c <= '9')
258         part = c - '0';
259       else if (c >= 'a' && c <= 'f')
260         part = c - 'a' + 10;
261       else if (c >= 'A' && c <= 'F')
262         part = c - 'A' + 10;
263       else
264         internal_error ("could not parse hex number");
265       ret |= part;
266     }
267   return ret;
268 }
269
270 /* Read resolution for file named FILE_NAME. The resolution is read from
271    RESOLUTION. An array with the symbol resolution is returned. The array
272    size is written to SIZE. */
273
274 static VEC(ld_plugin_symbol_resolution_t,heap) *
275 lto_resolution_read (FILE *resolution, lto_file *file)
276 {
277   /* We require that objects in the resolution file are in the same
278      order as the lto1 command line. */
279   unsigned int name_len;
280   char *obj_name;
281   unsigned int num_symbols;
282   unsigned int i;
283   VEC(ld_plugin_symbol_resolution_t,heap) *ret = NULL;
284   unsigned max_index = 0;
285
286   if (!resolution)
287     return NULL;
288
289   name_len = strlen (file->filename);
290   obj_name = XNEWVEC (char, name_len + 1);
291   fscanf (resolution, " ");   /* Read white space. */
292
293   fread (obj_name, sizeof (char), name_len, resolution);
294   obj_name[name_len] = '\0';
295   if (strcmp (obj_name, file->filename) != 0)
296     internal_error ("unexpected file name %s in linker resolution file. "
297                     "Expected %s", obj_name, file->filename);
298   if (file->offset != 0)
299     {
300       int t;
301       char offset_p[17];
302       int64_t offset;
303       t = fscanf (resolution, "@0x%16s", offset_p);
304       if (t != 1)
305         internal_error ("could not parse file offset");
306       offset = lto_parse_hex (offset_p);
307       if (offset != file->offset)
308         internal_error ("unexpected offset");
309     }
310
311   free (obj_name);
312
313   fscanf (resolution, "%u", &num_symbols);
314
315   for (i = 0; i < num_symbols; i++)
316     {
317       int t;
318       unsigned index;
319       char r_str[27];
320       enum ld_plugin_symbol_resolution r;
321       unsigned int j;
322       unsigned int lto_resolution_str_len =
323         sizeof (lto_resolution_str) / sizeof (char *);
324
325       t = fscanf (resolution, "%u %26s %*[^\n]\n", &index, r_str);
326       if (t != 2)
327         internal_error ("Invalid line in the resolution file.");
328       if (index > max_index)
329         max_index = index;
330
331       for (j = 0; j < lto_resolution_str_len; j++)
332         {
333           if (strcmp (lto_resolution_str[j], r_str) == 0)
334             {
335               r = (enum ld_plugin_symbol_resolution) j;
336               break;
337             }
338         }
339       if (j == lto_resolution_str_len)
340         internal_error ("Invalid resolution in the resolution file.");
341
342       VEC_safe_grow_cleared (ld_plugin_symbol_resolution_t, heap, ret,
343                              max_index + 1);
344       VEC_replace (ld_plugin_symbol_resolution_t, ret, index, r);
345     }
346
347   return ret;
348 }
349
350 /* Generate a TREE representation for all types and external decls
351    entities in FILE.  
352
353    Read all of the globals out of the file.  Then read the cgraph
354    and process the .o index into the cgraph nodes so that it can open
355    the .o file to load the functions and ipa information.   */
356
357 static struct lto_file_decl_data *
358 lto_file_read (lto_file *file, FILE *resolution_file)
359 {
360   struct lto_file_decl_data *file_data;
361   const char *data;
362   size_t len;
363   VEC(ld_plugin_symbol_resolution_t,heap) *resolutions;
364   
365   resolutions = lto_resolution_read (resolution_file, file);
366
367   file_data = GGC_NEW (struct lto_file_decl_data);
368   file_data->file_name = file->filename;
369   file_data->section_hash_table = lto_obj_build_section_table (file);
370   file_data->renaming_hash_table = lto_create_renaming_table ();
371
372   data = lto_get_section_data (file_data, LTO_section_decls, NULL, &len);
373   lto_read_decls (file_data, data, resolutions);
374   lto_free_section_data (file_data, LTO_section_decls, NULL, data, len);
375
376   return file_data;
377 }
378
379 #if HAVE_MMAP_FILE && HAVE_SYSCONF && defined _SC_PAGE_SIZE
380 #define LTO_MMAP_IO 1
381 #endif
382
383 #if LTO_MMAP_IO
384 /* Page size of machine is used for mmap and munmap calls.  */
385 static size_t page_mask;
386 #endif
387
388 /* Get the section data of length LEN from FILENAME starting at
389    OFFSET.  The data segment must be freed by the caller when the
390    caller is finished.  Returns NULL if all was not well.  */
391
392 static char *
393 lto_read_section_data (struct lto_file_decl_data *file_data,
394                        intptr_t offset, size_t len)
395 {
396   char *result;
397   static int fd = -1;
398   static char *fd_name;
399 #if LTO_MMAP_IO
400   intptr_t computed_len;
401   intptr_t computed_offset;
402   intptr_t diff;
403 #endif
404
405   /* Keep a single-entry file-descriptor cache.  The last file we
406      touched will get closed at exit.
407      ???  Eventually we want to add a more sophisticated larger cache
408      or rather fix function body streaming to not stream them in
409      practically random order.  */
410   if (fd != -1
411       && strcmp (fd_name, file_data->file_name) != 0)
412     {
413       free (fd_name);
414       close (fd);
415       fd = -1;
416     }
417   if (fd == -1)
418     {
419       fd_name = xstrdup (file_data->file_name);
420       fd = open (file_data->file_name, O_RDONLY|O_BINARY);
421       if (fd == -1)
422         return NULL;
423     }
424
425 #if LTO_MMAP_IO
426   if (!page_mask)
427     {
428       size_t page_size = sysconf (_SC_PAGE_SIZE);
429       page_mask = ~(page_size - 1);
430     }
431
432   computed_offset = offset & page_mask;
433   diff = offset - computed_offset;
434   computed_len = len + diff;
435
436   result = (char *) mmap (NULL, computed_len, PROT_READ, MAP_PRIVATE,
437                           fd, computed_offset);
438   if (result == MAP_FAILED)
439     return NULL;
440
441   return result + diff;
442 #else
443   result = (char *) xmalloc (len);
444   if (lseek (fd, offset, SEEK_SET) != offset
445       || read (fd, result, len) != (ssize_t) len)
446     {
447       free (result);
448       return NULL;
449     }
450
451   return result;
452 #endif
453 }    
454
455
456 /* Get the section data from FILE_DATA of SECTION_TYPE with NAME.
457    NAME will be NULL unless the section type is for a function
458    body.  */
459
460 static const char *
461 get_section_data (struct lto_file_decl_data *file_data,
462                       enum lto_section_type section_type,
463                       const char *name,
464                       size_t *len)
465 {
466   htab_t section_hash_table = file_data->section_hash_table;
467   struct lto_section_slot *f_slot;
468   struct lto_section_slot s_slot;
469   const char *section_name = lto_get_section_name (section_type, name);
470   char *data = NULL;
471
472   *len = 0;
473   s_slot.name = section_name;
474   f_slot = (struct lto_section_slot *) htab_find (section_hash_table, &s_slot);
475   if (f_slot)
476     {
477       data = lto_read_section_data (file_data, f_slot->start, f_slot->len);
478       *len = f_slot->len;
479     }
480
481   free (CONST_CAST (char *, section_name));
482   return data;
483 }
484
485
486 /* Free the section data from FILE_DATA of SECTION_TYPE with NAME that
487    starts at OFFSET and has LEN bytes.  */
488
489 static void
490 free_section_data (struct lto_file_decl_data *file_data ATTRIBUTE_UNUSED,
491                    enum lto_section_type section_type ATTRIBUTE_UNUSED,
492                    const char *name ATTRIBUTE_UNUSED,
493                    const char *offset, size_t len ATTRIBUTE_UNUSED)
494 {
495 #if LTO_MMAP_IO
496   intptr_t computed_len;
497   intptr_t computed_offset;
498   intptr_t diff;
499 #endif
500
501 #if LTO_MMAP_IO
502   computed_offset = ((intptr_t) offset) & page_mask;
503   diff = (intptr_t) offset - computed_offset;
504   computed_len = len + diff;
505
506   munmap ((caddr_t) computed_offset, computed_len);
507 #else
508   free (CONST_CAST(char *, offset));
509 #endif
510 }
511
512 /* Structure describing ltrans partitions.  */
513
514 struct GTY (()) ltrans_partition_def
515 {
516   cgraph_node_set cgraph_set;
517   varpool_node_set varpool_set;
518   const char * GTY ((skip)) name;
519   int insns;
520 };
521
522 typedef struct ltrans_partition_def *ltrans_partition;
523 DEF_VEC_P(ltrans_partition);
524 DEF_VEC_ALLOC_P(ltrans_partition,gc);
525
526 static GTY (()) VEC(ltrans_partition, gc) *ltrans_partitions;
527
528 /* Create new partition with name NAME.  */
529 static ltrans_partition
530 new_partition (const char *name)
531 {
532   ltrans_partition part = GGC_NEW (struct ltrans_partition_def);
533   part->cgraph_set = cgraph_node_set_new ();
534   part->varpool_set = varpool_node_set_new ();
535   part->name = name;
536   part->insns = 0;
537   VEC_safe_push (ltrans_partition, gc, ltrans_partitions, part);
538   return part;
539 }
540
541 /* Add NODE to partition as well as the inline callees into partition PART. */
542
543 static void
544 add_cgraph_node_to_partition (ltrans_partition part, struct cgraph_node *node)
545 {
546   struct cgraph_edge *e;
547   part->insns += node->local.inline_summary.self_size;
548   cgraph_node_set_add (part->cgraph_set, node);
549   for (e = node->callees; e; e = e->next_callee)
550     if (!e->inline_failed)
551       add_cgraph_node_to_partition (part, e->callee);
552 }
553
554 /* Group cgrah nodes by input files.  This is used mainly for testing
555    right now.  */
556
557 static void
558 lto_1_to_1_map (void)
559 {
560   struct cgraph_node *node;
561   struct varpool_node *vnode;
562   struct lto_file_decl_data *file_data;
563   struct pointer_map_t *pmap;
564   ltrans_partition partition;
565   void **slot;
566   int npartitions = 0;
567
568   timevar_push (TV_WHOPR_WPA);
569
570   pmap = pointer_map_create ();
571
572   for (node = cgraph_nodes; node; node = node->next)
573     {
574       /* We will get proper partition based on function they are inlined to.  */
575       if (node->global.inlined_to)
576         continue;
577       /* Nodes without a body do not need partitioning.  */
578       if (!node->analyzed)
579         continue;
580
581       file_data = node->local.lto_file_data;
582       gcc_assert (!node->same_body_alias && file_data);
583
584       slot = pointer_map_contains (pmap, file_data);
585       if (slot)
586         partition = (ltrans_partition) *slot;
587       else
588         {
589           partition = new_partition (file_data->file_name);
590           slot = pointer_map_insert (pmap, file_data);
591           *slot = partition;
592           npartitions++;
593         }
594
595       add_cgraph_node_to_partition (partition, node);
596     }
597
598   for (vnode = varpool_nodes; vnode; vnode = vnode->next)
599     {
600       if (vnode->alias || !vnode->needed)
601         continue;
602       slot = pointer_map_contains (pmap, file_data);
603       if (slot)
604         partition = (ltrans_partition) *slot;
605       else
606         {
607           partition = new_partition (file_data->file_name);
608           slot = pointer_map_insert (pmap, file_data);
609           *slot = partition;
610           npartitions++;
611         }
612
613       varpool_node_set_add (partition->varpool_set, vnode);
614     }
615
616   /* If the cgraph is empty, create one cgraph node set so that there is still
617      an output file for any variables that need to be exported in a DSO.  */
618   if (!npartitions)
619     new_partition ("empty");
620
621   pointer_map_destroy (pmap);
622
623   timevar_pop (TV_WHOPR_WPA);
624
625   lto_stats.num_cgraph_partitions += VEC_length (ltrans_partition, 
626                                                  ltrans_partitions);
627 }
628
629 /* Promote variable VNODE to be static.  */
630
631 static bool
632 promote_var (struct varpool_node *vnode)
633 {
634   if (TREE_PUBLIC (vnode->decl) || DECL_EXTERNAL (vnode->decl))
635     return false;
636   gcc_assert (flag_wpa);
637   TREE_PUBLIC (vnode->decl) = 1;
638   DECL_VISIBILITY (vnode->decl) = VISIBILITY_HIDDEN;
639   if (cgraph_dump_file)
640     fprintf (cgraph_dump_file,
641             "Promoting var as hidden: %s\n", varpool_node_name (vnode));
642   return true;
643 }
644
645 /* Promote function NODE to be static.  */
646
647 static bool
648 promote_fn (struct cgraph_node *node)
649 {
650   gcc_assert (flag_wpa);
651   if (TREE_PUBLIC (node->decl) || DECL_EXTERNAL (node->decl))
652     return false;
653   TREE_PUBLIC (node->decl) = 1;
654   DECL_VISIBILITY (node->decl) = VISIBILITY_HIDDEN;
655   if (node->same_body)
656     {
657       struct cgraph_node *alias;
658       for (alias = node->same_body;
659            alias; alias = alias->next)
660         {
661           TREE_PUBLIC (alias->decl) = 1;
662           DECL_VISIBILITY (alias->decl) = VISIBILITY_HIDDEN;
663         }
664     }
665   if (cgraph_dump_file)
666     fprintf (cgraph_dump_file,
667              "Promoting function as hidden: %s/%i\n",
668              cgraph_node_name (node), node->uid);
669   return true;
670 }
671
672 /* Find out all static decls that need to be promoted to global because
673    of cross file sharing.  This function must be run in the WPA mode after
674    all inlinees are added.  */
675
676 static void
677 lto_promote_cross_file_statics (void)
678 {
679   struct varpool_node *vnode;
680   unsigned i, n_sets;
681   cgraph_node_set set;
682   varpool_node_set vset;
683   cgraph_node_set_iterator csi;
684   varpool_node_set_iterator vsi;
685   VEC(varpool_node_ptr, heap) *promoted_initializers = NULL;
686   struct pointer_set_t *inserted = pointer_set_create ();
687
688   gcc_assert (flag_wpa);
689
690   n_sets = VEC_length (ltrans_partition, ltrans_partitions);
691   for (i = 0; i < n_sets; i++)
692     {
693       ltrans_partition part = VEC_index (ltrans_partition, ltrans_partitions, i);
694       set = part->cgraph_set;
695       vset = part->varpool_set;
696
697       /* If node has either address taken (and we have no clue from where)
698          or it is called from other partition, it needs to be globalized.  */
699       for (csi = csi_start (set); !csi_end_p (csi); csi_next (&csi))
700         {
701           struct cgraph_node *node = csi_node (csi);
702           if (node->local.externally_visible)
703             continue;
704           if (node->global.inlined_to)
705             continue;
706           if (!DECL_EXTERNAL (node->decl)
707               && (referenced_from_other_partition_p (&node->ref_list, set, vset)
708                   || reachable_from_other_partition_p (node, set)))
709             promote_fn (node);
710         }
711       for (vsi = vsi_start (vset); !vsi_end_p (vsi); vsi_next (&vsi))
712         {
713           vnode = vsi_node (vsi);
714           /* Constant pool references use internal labels and thus can not
715              be made global.  It is sensible to keep those ltrans local to
716              allow better optimization.  */
717           if (!DECL_IN_CONSTANT_POOL (vnode->decl)
718              && !vnode->externally_visible && vnode->analyzed
719              && referenced_from_other_partition_p (&vnode->ref_list,
720                                                    set, vset))
721             promote_var (vnode);
722         }
723
724       /* We export initializers of read-only var into each partition
725          referencing it.  Folding might take declarations from the
726          initializers and use it; so everything referenced from the
727          initializers needs can be accessed from this partition after
728          folding.
729
730          This means that we need to promote all variables and functions
731          referenced from all initializers from readonly vars referenced
732          from this partition that are not in this partition.
733          This needs to be done recursively.  */
734       for (vnode = varpool_nodes; vnode; vnode = vnode->next)
735         if ((TREE_READONLY (vnode->decl) || DECL_IN_CONSTANT_POOL (vnode->decl))
736             && DECL_INITIAL (vnode->decl)
737             && !varpool_node_in_set_p (vnode, vset)
738             && referenced_from_this_partition_p (&vnode->ref_list, set, vset)
739             && !pointer_set_insert (inserted, vnode))
740         VEC_safe_push (varpool_node_ptr, heap, promoted_initializers, vnode);
741       while (!VEC_empty (varpool_node_ptr, promoted_initializers))
742         {
743           int i;
744           struct ipa_ref *ref;
745
746           vnode = VEC_pop (varpool_node_ptr, promoted_initializers);
747           for (i = 0; ipa_ref_list_reference_iterate (&vnode->ref_list, i, ref); i++)
748             {
749               if (ref->refered_type == IPA_REF_CGRAPH)
750                 {
751                   struct cgraph_node *n = ipa_ref_node (ref);
752                   gcc_assert (!n->global.inlined_to);
753                   if (!n->local.externally_visible
754                       && !cgraph_node_in_set_p (n, set))
755                     promote_fn (n);
756                 }
757               else
758                 {
759                   struct varpool_node *v = ipa_ref_varpool_node (ref);
760                   if (varpool_node_in_set_p (v, vset))
761                     continue;
762                   /* Constant pool references use internal labels and thus can not
763                      be made global.  It is sensible to keep those ltrans local to
764                      allow better optimization.  */
765                   if (DECL_IN_CONSTANT_POOL (v->decl))
766                     {
767                       if (!pointer_set_insert (inserted, vnode))
768                         VEC_safe_push (varpool_node_ptr, heap,
769                                        promoted_initializers, v);
770                     }
771                   else if (!DECL_IN_CONSTANT_POOL (v->decl)
772                            && !v->externally_visible && v->analyzed)
773                     {
774                       if (promote_var (v)
775                           && DECL_INITIAL (v->decl) && TREE_READONLY (v->decl)
776                           && !pointer_set_insert (inserted, vnode))
777                         VEC_safe_push (varpool_node_ptr, heap,
778                                        promoted_initializers, v);
779                     }
780                 }
781             }
782         }
783     }
784   pointer_set_destroy (inserted);
785 }
786
787 static lto_file *current_lto_file;
788
789 /* Helper for qsort; compare partitions and return one with smaller size.
790    We sort from greatest to smallest so parallel build doesn't stale on the
791    longest compilation being executed too late.  */
792
793 static int
794 cmp_partitions (const void *a, const void *b)
795 {
796   const struct ltrans_partition_def *pa
797      = *(struct ltrans_partition_def *const *)a;
798   const struct ltrans_partition_def *pb
799      = *(struct ltrans_partition_def *const *)b;
800   return pb->insns - pa->insns;
801 }
802
803 /* Write all output files in WPA mode and the file with the list of
804    LTRANS units.  */
805
806 static void
807 lto_wpa_write_files (void)
808 {
809   unsigned i, n_sets;
810   lto_file *file;
811   cgraph_node_set set;
812   varpool_node_set vset;
813   ltrans_partition part;
814   FILE *ltrans_output_list_stream;
815   char *temp_filename;
816   size_t blen;
817
818   /* Open the LTRANS output list.  */
819   if (!ltrans_output_list)
820     fatal_error ("no LTRANS output list filename provided");
821   ltrans_output_list_stream = fopen (ltrans_output_list, "w");
822   if (ltrans_output_list_stream == NULL)
823     fatal_error ("opening LTRANS output list %s: %m", ltrans_output_list);
824
825   timevar_push (TV_WHOPR_WPA);
826
827   /* Include all inlined functions and determine what sets need to be
828      compiled by LTRANS.  After this loop, only those sets that
829      contain callgraph nodes from more than one file will need to be
830      compiled by LTRANS.  */
831   for (i = 0; VEC_iterate (ltrans_partition, ltrans_partitions, i, part); i++)
832     lto_stats.num_output_cgraph_nodes += VEC_length (cgraph_node_ptr,
833                                                      part->cgraph_set->nodes);
834
835   /* After adding all inlinees, find out statics that need to be promoted
836      to globals because of cross-file inlining.  */
837   lto_promote_cross_file_statics ();
838
839   timevar_pop (TV_WHOPR_WPA);
840
841   timevar_push (TV_WHOPR_WPA_IO);
842
843   /* Generate a prefix for the LTRANS unit files.  */
844   blen = strlen (ltrans_output_list);
845   temp_filename = (char *) xmalloc (blen + sizeof ("2147483648.o"));
846   strcpy (temp_filename, ltrans_output_list);
847   if (blen > sizeof (".out")
848       && strcmp (temp_filename + blen - sizeof (".out") + 1,
849                  ".out") == 0)
850     temp_filename[blen - sizeof (".out") + 1] = '\0';
851   blen = strlen (temp_filename);
852
853   n_sets = VEC_length (ltrans_partition, ltrans_partitions);
854   qsort (VEC_address (ltrans_partition, ltrans_partitions), n_sets,
855          sizeof (ltrans_partition), cmp_partitions);
856   for (i = 0; i < n_sets; i++)
857     {
858       size_t len;
859       ltrans_partition part = VEC_index (ltrans_partition, ltrans_partitions, i);
860
861       set = part->cgraph_set;
862       vset = part->varpool_set;
863
864       /* Write all the nodes in SET.  */
865       sprintf (temp_filename + blen, "%u.o", i);
866       file = lto_obj_file_open (temp_filename, true);
867       if (!file)
868         fatal_error ("lto_obj_file_open() failed");
869
870       if (!quiet_flag)
871         fprintf (stderr, " %s (%s %i insns)", temp_filename, part->name, part->insns);
872       if (cgraph_dump_file)
873         {
874           fprintf (cgraph_dump_file, "Writting partition %s to file %s, %i insns\n",
875                    part->name, temp_filename, part->insns);
876           fprintf (cgraph_dump_file, "cgraph nodes:");
877           dump_cgraph_node_set (cgraph_dump_file, set);
878           fprintf (cgraph_dump_file, "varpool nodes:");
879           dump_varpool_node_set (cgraph_dump_file, vset);
880         }
881       gcc_assert (cgraph_node_set_nonempty_p (set)
882                   || varpool_node_set_nonempty_p (vset) || !i);
883
884       lto_set_current_out_file (file);
885
886       ipa_write_optimization_summaries (set, vset);
887
888       lto_set_current_out_file (NULL);
889       lto_obj_file_close (file);
890
891       len = strlen (temp_filename);
892       if (fwrite (temp_filename, 1, len, ltrans_output_list_stream) < len
893           || fwrite ("\n", 1, 1, ltrans_output_list_stream) < 1)
894         fatal_error ("writing to LTRANS output list %s: %m",
895                      ltrans_output_list);
896     }
897
898   lto_stats.num_output_files += n_sets;
899
900   /* Close the LTRANS output list.  */
901   if (fclose (ltrans_output_list_stream))
902     fatal_error ("closing LTRANS output list %s: %m", ltrans_output_list);
903
904   timevar_pop (TV_WHOPR_WPA_IO);
905 }
906
907
908 typedef struct {
909   struct pointer_set_t *seen;
910 } lto_fixup_data_t;
911
912 #define LTO_FIXUP_SUBTREE(t) \
913   do \
914     walk_tree (&(t), lto_fixup_tree, data, NULL); \
915   while (0)
916
917 #define LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE(t) \
918   do \
919     { \
920       if (t) \
921         (t) = gimple_register_type (t); \
922       walk_tree (&(t), lto_fixup_tree, data, NULL); \
923     } \
924   while (0)
925
926 static tree lto_fixup_tree (tree *, int *, void *);
927
928 /* Return true if T does not need to be fixed up recursively.  */
929
930 static inline bool
931 no_fixup_p (tree t)
932 {
933   return (t == NULL
934           || CONSTANT_CLASS_P (t)
935           || TREE_CODE (t) == IDENTIFIER_NODE);
936 }
937
938 /* Fix up fields of a tree_common T.  DATA points to fix-up states.  */
939
940 static void
941 lto_fixup_common (tree t, void *data)
942 {
943   /* The following re-creates the TYPE_REFERENCE_TO and TYPE_POINTER_TO
944      lists.  We do not stream TYPE_REFERENCE_TO, TYPE_POINTER_TO or
945      TYPE_NEXT_PTR_TO and TYPE_NEXT_REF_TO.
946      First remove us from any pointer list we are on.  */
947   if (TREE_CODE (t) == POINTER_TYPE)
948     {
949       if (TYPE_POINTER_TO (TREE_TYPE (t)) == t)
950         TYPE_POINTER_TO (TREE_TYPE (t)) = TYPE_NEXT_PTR_TO (t);
951       else
952         {
953           tree tem = TYPE_POINTER_TO (TREE_TYPE (t));
954           while (tem && TYPE_NEXT_PTR_TO (tem) != t)
955             tem = TYPE_NEXT_PTR_TO (tem);
956           if (tem)
957             TYPE_NEXT_PTR_TO (tem) = TYPE_NEXT_PTR_TO (t);
958         }
959       TYPE_NEXT_PTR_TO (t) = NULL_TREE;
960     }
961   else if (TREE_CODE (t) == REFERENCE_TYPE)
962     {
963       if (TYPE_REFERENCE_TO (TREE_TYPE (t)) == t)
964         TYPE_REFERENCE_TO (TREE_TYPE (t)) = TYPE_NEXT_REF_TO (t);
965       else
966         {
967           tree tem = TYPE_REFERENCE_TO (TREE_TYPE (t));
968           while (tem && TYPE_NEXT_REF_TO (tem) != t)
969             tem = TYPE_NEXT_REF_TO (tem);
970           if (tem)
971             TYPE_NEXT_REF_TO (tem) = TYPE_NEXT_REF_TO (t);
972         }
973       TYPE_NEXT_REF_TO (t) = NULL_TREE;
974     }
975
976   /* Fixup our type.  */
977   LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TREE_TYPE (t));
978
979   /* Second put us on the list of pointers of the new pointed-to type
980      if we are a main variant.  This is done in lto_fixup_type after
981      fixing up our main variant.  */
982
983   /* This is not very efficient because we cannot do tail-recursion with
984      a long chain of trees. */
985   LTO_FIXUP_SUBTREE (TREE_CHAIN (t));
986 }
987
988 /* Fix up fields of a decl_minimal T.  DATA points to fix-up states.  */
989
990 static void
991 lto_fixup_decl_minimal (tree t, void *data)
992 {
993   lto_fixup_common (t, data);
994   LTO_FIXUP_SUBTREE (DECL_NAME (t));
995   LTO_FIXUP_SUBTREE (DECL_CONTEXT (t));
996 }
997
998 /* Fix up fields of a decl_common T.  DATA points to fix-up states.  */
999
1000 static void
1001 lto_fixup_decl_common (tree t, void *data)
1002 {
1003   lto_fixup_decl_minimal (t, data);
1004   LTO_FIXUP_SUBTREE (DECL_SIZE (t));
1005   LTO_FIXUP_SUBTREE (DECL_SIZE_UNIT (t));
1006   LTO_FIXUP_SUBTREE (DECL_INITIAL (t));
1007   LTO_FIXUP_SUBTREE (DECL_ATTRIBUTES (t));
1008   LTO_FIXUP_SUBTREE (DECL_ABSTRACT_ORIGIN (t));
1009 }
1010
1011 /* Fix up fields of a decl_with_vis T.  DATA points to fix-up states.  */
1012
1013 static void
1014 lto_fixup_decl_with_vis (tree t, void *data)
1015 {
1016   lto_fixup_decl_common (t, data);
1017
1018   /* Accessor macro has side-effects, use field-name here. */
1019   LTO_FIXUP_SUBTREE (t->decl_with_vis.assembler_name);
1020
1021   gcc_assert (no_fixup_p (DECL_SECTION_NAME (t)));
1022 }
1023
1024 /* Fix up fields of a decl_non_common T.  DATA points to fix-up states.  */
1025
1026 static void
1027 lto_fixup_decl_non_common (tree t, void *data)
1028 {
1029   lto_fixup_decl_with_vis (t, data);
1030   LTO_FIXUP_SUBTREE (DECL_ARGUMENT_FLD (t));
1031   LTO_FIXUP_SUBTREE (DECL_RESULT_FLD (t));
1032   LTO_FIXUP_SUBTREE (DECL_VINDEX (t));
1033
1034   /* SAVED_TREE should not cleared by now.  Also no accessor for base type. */
1035   gcc_assert (no_fixup_p (t->decl_non_common.saved_tree));
1036 }
1037
1038 /* Fix up fields of a decl_non_common T.  DATA points to fix-up states.  */
1039
1040 static void
1041 lto_fixup_function (tree t, void *data)
1042 {
1043   lto_fixup_decl_non_common (t, data);
1044   LTO_FIXUP_SUBTREE (DECL_FUNCTION_PERSONALITY (t));
1045 }
1046
1047 /* Fix up fields of a field_decl T.  DATA points to fix-up states.  */
1048
1049 static void
1050 lto_fixup_field_decl (tree t, void *data)
1051 {
1052   lto_fixup_decl_common (t, data);
1053   LTO_FIXUP_SUBTREE (DECL_FIELD_OFFSET (t));
1054   LTO_FIXUP_SUBTREE (DECL_BIT_FIELD_TYPE (t));
1055   LTO_FIXUP_SUBTREE (DECL_QUALIFIER (t));
1056   gcc_assert (no_fixup_p (DECL_FIELD_BIT_OFFSET (t)));
1057   LTO_FIXUP_SUBTREE (DECL_FCONTEXT (t));
1058 }
1059
1060 /* Fix up fields of a type T.  DATA points to fix-up states.  */
1061
1062 static void
1063 lto_fixup_type (tree t, void *data)
1064 {
1065   tree tem, mv;
1066
1067   lto_fixup_common (t, data);
1068   LTO_FIXUP_SUBTREE (TYPE_CACHED_VALUES (t));
1069   LTO_FIXUP_SUBTREE (TYPE_SIZE (t));
1070   LTO_FIXUP_SUBTREE (TYPE_SIZE_UNIT (t));
1071   LTO_FIXUP_SUBTREE (TYPE_ATTRIBUTES (t));
1072   LTO_FIXUP_SUBTREE (TYPE_NAME (t));
1073
1074   /* Accessors are for derived node types only. */
1075   if (!POINTER_TYPE_P (t))
1076     LTO_FIXUP_SUBTREE (t->type.minval);
1077   LTO_FIXUP_SUBTREE (t->type.maxval);
1078
1079   /* Accessor is for derived node types only. */
1080   LTO_FIXUP_SUBTREE (t->type.binfo);
1081
1082   if (TYPE_CONTEXT (t))
1083     {
1084       if (TYPE_P (TYPE_CONTEXT (t)))
1085         LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TYPE_CONTEXT (t));
1086       else
1087         LTO_FIXUP_SUBTREE (TYPE_CONTEXT (t));
1088     }
1089   LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TYPE_CANONICAL (t));
1090
1091   /* The following re-creates proper variant lists while fixing up
1092      the variant leaders.  We do not stream TYPE_NEXT_VARIANT so the
1093      variant list state before fixup is broken.  */
1094
1095   /* Remove us from our main variant list if we are not the variant leader.  */
1096   if (TYPE_MAIN_VARIANT (t) != t)
1097     {
1098       tem = TYPE_MAIN_VARIANT (t);
1099       while (tem && TYPE_NEXT_VARIANT (tem) != t)
1100         tem = TYPE_NEXT_VARIANT (tem);
1101       if (tem)
1102         TYPE_NEXT_VARIANT (tem) = TYPE_NEXT_VARIANT (t);
1103       TYPE_NEXT_VARIANT (t) = NULL_TREE;
1104     }
1105
1106   /* Query our new main variant.  */
1107   mv = gimple_register_type (TYPE_MAIN_VARIANT (t));
1108
1109   /* If we were the variant leader and we get replaced ourselves drop
1110      all variants from our list.  */
1111   if (TYPE_MAIN_VARIANT (t) == t
1112       && mv != t)
1113     {
1114       tem = t;
1115       while (tem)
1116         {
1117           tree tem2 = TYPE_NEXT_VARIANT (tem);
1118           TYPE_NEXT_VARIANT (tem) = NULL_TREE;
1119           tem = tem2;
1120         }
1121     }
1122
1123   /* If we are not our own variant leader link us into our new leaders
1124      variant list.  */
1125   if (mv != t)
1126     {
1127       TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (mv);
1128       TYPE_NEXT_VARIANT (mv) = t;
1129     }
1130
1131   /* Finally adjust our main variant and fix it up.  */
1132   TYPE_MAIN_VARIANT (t) = mv;
1133   LTO_FIXUP_SUBTREE (TYPE_MAIN_VARIANT (t));
1134
1135   /* As the second step of reconstructing the pointer chains put us
1136      on the list of pointers of the new pointed-to type
1137      if we are a main variant.  See lto_fixup_common for the first step.  */
1138   if (TREE_CODE (t) == POINTER_TYPE
1139       && TYPE_MAIN_VARIANT (t) == t)
1140     {
1141       TYPE_NEXT_PTR_TO (t) = TYPE_POINTER_TO (TREE_TYPE (t));
1142       TYPE_POINTER_TO (TREE_TYPE (t)) = t;
1143     }
1144   else if (TREE_CODE (t) == REFERENCE_TYPE
1145            && TYPE_MAIN_VARIANT (t) == t)
1146     {
1147       TYPE_NEXT_REF_TO (t) = TYPE_REFERENCE_TO (TREE_TYPE (t));
1148       TYPE_REFERENCE_TO (TREE_TYPE (t)) = t;
1149     }
1150 }
1151
1152 /* Fix up fields of a BINFO T.  DATA points to fix-up states.  */
1153
1154 static void
1155 lto_fixup_binfo (tree t, void *data)
1156 {
1157   unsigned HOST_WIDE_INT i, n;
1158   tree base, saved_base;
1159
1160   lto_fixup_common (t, data);
1161   gcc_assert (no_fixup_p (BINFO_OFFSET (t)));
1162   LTO_FIXUP_SUBTREE (BINFO_VTABLE (t));
1163   LTO_FIXUP_SUBTREE (BINFO_VIRTUALS (t));
1164   LTO_FIXUP_SUBTREE (BINFO_VPTR_FIELD (t));
1165   n = VEC_length (tree, BINFO_BASE_ACCESSES (t));
1166   for (i = 0; i < n; i++)
1167     {
1168       saved_base = base = BINFO_BASE_ACCESS (t, i);
1169       LTO_FIXUP_SUBTREE (base);
1170       if (base != saved_base)
1171         VEC_replace (tree, BINFO_BASE_ACCESSES (t), i, base);
1172     }
1173   LTO_FIXUP_SUBTREE (BINFO_INHERITANCE_CHAIN (t));
1174   LTO_FIXUP_SUBTREE (BINFO_SUBVTT_INDEX (t));
1175   LTO_FIXUP_SUBTREE (BINFO_VPTR_INDEX (t));
1176   n = BINFO_N_BASE_BINFOS (t);
1177   for (i = 0; i < n; i++)
1178     {
1179       saved_base = base = BINFO_BASE_BINFO (t, i);
1180       LTO_FIXUP_SUBTREE (base);
1181       if (base != saved_base)
1182         VEC_replace (tree, BINFO_BASE_BINFOS (t), i, base);
1183     }
1184 }
1185
1186 /* Fix up fields of a CONSTRUCTOR T.  DATA points to fix-up states.  */
1187
1188 static void
1189 lto_fixup_constructor (tree t, void *data)
1190 {
1191   unsigned HOST_WIDE_INT idx;
1192   constructor_elt *ce;
1193
1194   LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TREE_TYPE (t));
1195
1196   for (idx = 0;
1197        VEC_iterate(constructor_elt, CONSTRUCTOR_ELTS (t), idx, ce);
1198        idx++)
1199     {
1200       LTO_FIXUP_SUBTREE (ce->index);
1201       LTO_FIXUP_SUBTREE (ce->value);
1202     }
1203 }
1204
1205 /* A walk_tree callback used by lto_fixup_state. TP is the pointer to the
1206    current tree. WALK_SUBTREES indicates if the subtrees will be walked.
1207    DATA is a pointer set to record visited nodes. */
1208
1209 static tree
1210 lto_fixup_tree (tree *tp, int *walk_subtrees, void *data)
1211 {
1212   tree t;
1213   lto_fixup_data_t *fixup_data = (lto_fixup_data_t *) data;
1214   tree prevailing;
1215
1216   t = *tp;
1217   *walk_subtrees = 0;
1218   if (!t || pointer_set_contains (fixup_data->seen, t))
1219     return NULL;
1220
1221   if (TREE_CODE (t) == VAR_DECL || TREE_CODE (t) == FUNCTION_DECL)
1222     {
1223       prevailing = lto_symtab_prevailing_decl (t);
1224
1225       if (t != prevailing)
1226         {
1227            /* Also replace t with prevailing defintion.  We don't want to
1228               insert the other defintion in the seen set as we want to
1229               replace all instances of it.  */
1230           *tp = prevailing;
1231           t = prevailing;
1232         }
1233     }
1234   else if (TYPE_P (t))
1235     {
1236       /* Replace t with the prevailing type.  We don't want to insert the
1237          other type in the seen set as we want to replace all instances of it.  */
1238       t = gimple_register_type (t);
1239       *tp = t;
1240     }
1241
1242   if (pointer_set_insert (fixup_data->seen, t))
1243     return NULL;
1244
1245   /* walk_tree does not visit all reachable nodes that need to be fixed up.
1246      Hence we do special processing here for those kind of nodes. */
1247   switch (TREE_CODE (t))
1248     {
1249     case FIELD_DECL:
1250       lto_fixup_field_decl (t, data);
1251       break;
1252
1253     case LABEL_DECL:
1254     case CONST_DECL:
1255     case PARM_DECL:
1256     case RESULT_DECL:
1257     case IMPORTED_DECL:
1258       lto_fixup_decl_common (t, data);
1259       break;
1260
1261     case VAR_DECL:
1262       lto_fixup_decl_with_vis (t, data);
1263       break;    
1264
1265     case TYPE_DECL:
1266       lto_fixup_decl_non_common (t, data);
1267       break;
1268
1269     case FUNCTION_DECL:
1270       lto_fixup_function (t, data);
1271       break;
1272
1273     case TREE_BINFO:
1274       lto_fixup_binfo (t, data);
1275       break;
1276
1277     default:
1278       if (TYPE_P (t))
1279         lto_fixup_type (t, data);
1280       else if (TREE_CODE (t) == CONSTRUCTOR)
1281         lto_fixup_constructor (t, data);
1282       else if (CONSTANT_CLASS_P (t))
1283         LTO_REGISTER_TYPE_AND_FIXUP_SUBTREE (TREE_TYPE (t));
1284       else if (EXPR_P (t))
1285         {
1286           /* walk_tree only handles TREE_OPERANDs. Do the rest here.  */
1287           lto_fixup_common (t, data);
1288           LTO_FIXUP_SUBTREE (t->exp.block);
1289           *walk_subtrees = 1;
1290         }
1291       else
1292         {
1293           /* Let walk_tree handle sub-trees.  */
1294           *walk_subtrees = 1;
1295         }
1296     }
1297
1298   return NULL;
1299 }
1300
1301 /* Helper function of lto_fixup_decls. Walks the var and fn streams in STATE,
1302    replaces var and function decls with the corresponding prevailing def and
1303    records the old decl in the free-list in DATA. We also record visted nodes
1304    in the seen-set in DATA to avoid multiple visit for nodes that need not
1305    to be replaced.  */
1306
1307 static void
1308 lto_fixup_state (struct lto_in_decl_state *state, lto_fixup_data_t *data)
1309 {
1310   unsigned i, si;
1311   struct lto_tree_ref_table *table;
1312
1313   /* Although we only want to replace FUNCTION_DECLs and VAR_DECLs,
1314      we still need to walk from all DECLs to find the reachable
1315      FUNCTION_DECLs and VAR_DECLs.  */
1316   for (si = 0; si < LTO_N_DECL_STREAMS; si++)
1317     {
1318       table = &state->streams[si];
1319       for (i = 0; i < table->size; i++)
1320         walk_tree (table->trees + i, lto_fixup_tree, data, NULL);
1321     }
1322 }
1323
1324 /* A callback of htab_traverse. Just extract a state from SLOT and the
1325    lto_fixup_data_t object from AUX and calls lto_fixup_state. */
1326
1327 static int
1328 lto_fixup_state_aux (void **slot, void *aux)
1329 {
1330   struct lto_in_decl_state *state = (struct lto_in_decl_state *) *slot;
1331   lto_fixup_state (state, (lto_fixup_data_t *) aux);
1332   return 1;
1333 }
1334
1335 /* Fix the decls from all FILES. Replaces each decl with the corresponding
1336    prevailing one.  */
1337
1338 static void
1339 lto_fixup_decls (struct lto_file_decl_data **files)
1340 {
1341   unsigned int i;
1342   tree decl;
1343   struct pointer_set_t *seen = pointer_set_create ();
1344   lto_fixup_data_t data;
1345
1346   data.seen = seen;
1347   for (i = 0; files[i]; i++)
1348     {
1349       struct lto_file_decl_data *file = files[i];
1350       struct lto_in_decl_state *state = file->global_decl_state;
1351       lto_fixup_state (state, &data);
1352
1353       htab_traverse (file->function_decl_states, lto_fixup_state_aux, &data);
1354     }
1355
1356   for (i = 0; VEC_iterate (tree, lto_global_var_decls, i, decl); i++)
1357     {
1358       tree saved_decl = decl;
1359       walk_tree (&decl, lto_fixup_tree, &data, NULL);
1360       if (decl != saved_decl)
1361         VEC_replace (tree, lto_global_var_decls, i, decl);
1362     }
1363
1364   pointer_set_destroy (seen);
1365 }
1366
1367 /* Read the options saved from each file in the command line.  Called
1368    from lang_hooks.post_options which is called by process_options
1369    right before all the options are used to initialize the compiler.
1370    This assumes that decode_options has already run, so the
1371    num_in_fnames and in_fnames are properly set.
1372
1373    Note that this assumes that all the files had been compiled with
1374    the same options, which is not a good assumption.  In general,
1375    options ought to be read from all the files in the set and merged.
1376    However, it is still unclear what the merge rules should be.  */
1377
1378 void
1379 lto_read_all_file_options (void)
1380 {
1381   size_t i;
1382
1383   /* Clear any file options currently saved.  */
1384   lto_clear_file_options ();
1385
1386   /* Set the hooks to read ELF sections.  */
1387   lto_set_in_hooks (NULL, get_section_data, free_section_data);
1388   if (!quiet_flag)
1389     fprintf (stderr, "Reading command line options:");
1390
1391   for (i = 0; i < num_in_fnames; i++)
1392     {
1393       struct lto_file_decl_data *file_data;
1394       lto_file *file = lto_obj_file_open (in_fnames[i], false);
1395       if (!file)
1396         break;
1397       if (!quiet_flag)
1398         {
1399           fprintf (stderr, " %s", in_fnames[i]);
1400           fflush (stderr);
1401         }
1402
1403       file_data = XCNEW (struct lto_file_decl_data);
1404       file_data->file_name = file->filename;
1405       file_data->section_hash_table = lto_obj_build_section_table (file);
1406
1407       lto_read_file_options (file_data);
1408
1409       lto_obj_file_close (file);
1410       htab_delete (file_data->section_hash_table);
1411       free (file_data);
1412     }
1413
1414   /* Apply globally the options read from all the files.  */
1415   lto_reissue_options ();
1416 }
1417
1418 static GTY((length ("lto_stats.num_input_files + 1"))) struct lto_file_decl_data **all_file_decl_data;
1419
1420 /* Read all the symbols from the input files FNAMES.  NFILES is the
1421    number of files requested in the command line.  Instantiate a
1422    global call graph by aggregating all the sub-graphs found in each
1423    file.  */
1424
1425 static void
1426 read_cgraph_and_symbols (unsigned nfiles, const char **fnames)
1427 {
1428   unsigned int i, last_file_ix;
1429   FILE *resolution;
1430   struct cgraph_node *node;
1431
1432   lto_stats.num_input_files = nfiles;
1433
1434   timevar_push (TV_IPA_LTO_DECL_IO);
1435
1436   /* Set the hooks so that all of the ipa passes can read in their data.  */
1437   all_file_decl_data = GGC_CNEWVEC (struct lto_file_decl_data *, nfiles + 1);
1438   lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data);
1439
1440   /* Read the resolution file.  */
1441   resolution = NULL;
1442   if (resolution_file_name)
1443     {
1444       int t;
1445       unsigned num_objects;
1446
1447       resolution = fopen (resolution_file_name, "r");
1448       if (resolution == NULL)
1449         fatal_error ("could not open symbol resolution file: %m");
1450
1451       t = fscanf (resolution, "%u", &num_objects);
1452       gcc_assert (t == 1);
1453
1454       /* True, since the plugin splits the archives.  */
1455       gcc_assert (num_objects == nfiles);
1456     }
1457
1458   if (!quiet_flag)
1459     fprintf (stderr, "Reading object files:");
1460
1461   /* Read all of the object files specified on the command line.  */
1462   for (i = 0, last_file_ix = 0; i < nfiles; ++i)
1463     {
1464       struct lto_file_decl_data *file_data = NULL;
1465       if (!quiet_flag)
1466         {
1467           fprintf (stderr, " %s", fnames[i]);
1468           fflush (stderr);
1469         }
1470
1471       current_lto_file = lto_obj_file_open (fnames[i], false);
1472       if (!current_lto_file)
1473         break;
1474
1475       file_data = lto_file_read (current_lto_file, resolution);
1476       if (!file_data)
1477         break;
1478
1479       all_file_decl_data[last_file_ix++] = file_data;
1480
1481       lto_obj_file_close (current_lto_file);
1482       current_lto_file = NULL;
1483       /* ???  We'd want but can't ggc_collect () here as the type merging
1484          code in gimple.c uses hashtables that are not ggc aware.  */
1485     }
1486
1487   if (resolution_file_name)
1488     fclose (resolution);
1489
1490   all_file_decl_data[last_file_ix] = NULL;
1491
1492   /* Set the hooks so that all of the ipa passes can read in their data.  */
1493   lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data);
1494
1495   timevar_pop (TV_IPA_LTO_DECL_IO);
1496
1497   if (!quiet_flag)
1498     fprintf (stderr, "\nReading the callgraph\n");
1499
1500   timevar_push (TV_IPA_LTO_CGRAPH_IO);
1501   /* Read the callgraph.  */
1502   input_cgraph ();
1503   timevar_pop (TV_IPA_LTO_CGRAPH_IO);
1504
1505   if (!quiet_flag)
1506     fprintf (stderr, "Merging declarations\n");
1507
1508   timevar_push (TV_IPA_LTO_DECL_MERGE);
1509   /* Merge global decls.  */
1510   lto_symtab_merge_decls ();
1511
1512   /* Fixup all decls and types and free the type hash tables.  */
1513   lto_fixup_decls (all_file_decl_data);
1514   free_gimple_type_tables ();
1515   ggc_collect ();
1516
1517   timevar_pop (TV_IPA_LTO_DECL_MERGE);
1518   /* Each pass will set the appropriate timer.  */
1519
1520   if (!quiet_flag)
1521     fprintf (stderr, "Reading summaries\n");
1522
1523   /* Read the IPA summary data.  */
1524   if (flag_ltrans)
1525     ipa_read_optimization_summaries ();
1526   else
1527     ipa_read_summaries ();
1528
1529   /* Finally merge the cgraph according to the decl merging decisions.  */
1530   timevar_push (TV_IPA_LTO_CGRAPH_MERGE);
1531   lto_symtab_merge_cgraph_nodes ();
1532   ggc_collect ();
1533
1534   if (flag_ltrans)
1535     for (node = cgraph_nodes; node; node = node->next)
1536       {
1537         /* FIXME: ipa_transforms_to_apply holds list of passes that have optimization
1538            summaries computed and needs to apply changes.  At the moment WHOPR only
1539            supports inlining, so we can push it here by hand.  In future we need to stream
1540            this field into ltrans compilation.  */
1541         if (node->analyzed)
1542           VEC_safe_push (ipa_opt_pass, heap,
1543                          node->ipa_transforms_to_apply,
1544                          (ipa_opt_pass)&pass_ipa_inline);
1545       }
1546   lto_symtab_free ();
1547
1548   timevar_pop (TV_IPA_LTO_CGRAPH_MERGE);
1549
1550   timevar_push (TV_IPA_LTO_DECL_INIT_IO);
1551
1552   /* FIXME lto. This loop needs to be changed to use the pass manager to
1553      call the ipa passes directly.  */
1554   if (!seen_error ())
1555     for (i = 0; i < last_file_ix; i++)
1556       {
1557         struct lto_file_decl_data *file_data = all_file_decl_data [i];
1558         lto_materialize_constructors_and_inits (file_data);
1559       }
1560
1561   /* Indicate that the cgraph is built and ready.  */
1562   cgraph_function_flags_ready = true;
1563
1564   timevar_pop (TV_IPA_LTO_DECL_INIT_IO);
1565   ggc_free (all_file_decl_data);
1566   all_file_decl_data = NULL;
1567 }
1568
1569
1570 /* Materialize all the bodies for all the nodes in the callgraph.  */
1571
1572 static void
1573 materialize_cgraph (void)
1574 {
1575   tree decl;
1576   struct cgraph_node *node; 
1577   unsigned i;
1578   timevar_id_t lto_timer;
1579
1580   if (!quiet_flag)
1581     fprintf (stderr,
1582              flag_wpa ? "Materializing decls:" : "Reading function bodies:");
1583
1584
1585   /* Now that we have input the cgraph, we need to clear all of the aux
1586      nodes and read the functions if we are not running in WPA mode.  */
1587   timevar_push (TV_IPA_LTO_GIMPLE_IO);
1588
1589   for (node = cgraph_nodes; node; node = node->next)
1590     {
1591       /* Some cgraph nodes get created on the fly, and they don't need
1592          to be materialized.  For instance, nodes for nested functions
1593          where the parent function was not streamed out or builtin
1594          functions.  Additionally, builtin functions should not be
1595          materialized and may, in fact, cause confusion because there
1596          may be a regular function in the file whose assembler name
1597          matches that of the function.
1598          See gcc.c-torture/execute/20030125-1.c and
1599          gcc.c-torture/execute/921215-1.c.  */
1600       if (node->local.lto_file_data
1601           && !DECL_IS_BUILTIN (node->decl))
1602         {
1603           lto_materialize_function (node);
1604           lto_stats.num_input_cgraph_nodes++;
1605         }
1606     }
1607
1608   timevar_pop (TV_IPA_LTO_GIMPLE_IO);
1609
1610   /* Start the appropriate timer depending on the mode that we are
1611      operating in.  */
1612   lto_timer = (flag_wpa) ? TV_WHOPR_WPA
1613               : (flag_ltrans) ? TV_WHOPR_LTRANS
1614               : TV_LTO;
1615   timevar_push (lto_timer);
1616
1617   current_function_decl = NULL;
1618   set_cfun (NULL);
1619
1620   /* Inform the middle end about the global variables we have seen.  */
1621   for (i = 0; VEC_iterate (tree, lto_global_var_decls, i, decl); i++)
1622     rest_of_decl_compilation (decl, 1, 0);
1623
1624   if (!quiet_flag)
1625     fprintf (stderr, "\n");
1626
1627   timevar_pop (lto_timer);
1628 }
1629
1630
1631 /* Perform whole program analysis (WPA) on the callgraph and write out the
1632    optimization plan.  */
1633
1634 static void
1635 do_whole_program_analysis (void)
1636 {
1637   /* Note that since we are in WPA mode, materialize_cgraph will not
1638      actually read in all the function bodies.  It only materializes
1639      the decls and cgraph nodes so that analysis can be performed.  */
1640   materialize_cgraph ();
1641
1642   /* Reading in the cgraph uses different timers, start timing WPA now.  */
1643   timevar_push (TV_WHOPR_WPA);
1644
1645   if (pre_ipa_mem_report)
1646     {
1647       fprintf (stderr, "Memory consumption before IPA\n");
1648       dump_memory_report (false);
1649     }
1650
1651   if (cgraph_dump_file)
1652     {
1653       dump_cgraph (cgraph_dump_file);
1654       dump_varpool (cgraph_dump_file);
1655     }
1656
1657   cgraph_function_flags_ready = true;
1658   bitmap_obstack_initialize (NULL);
1659   ipa_register_cgraph_hooks ();
1660   cgraph_state = CGRAPH_STATE_IPA_SSA;
1661
1662   execute_ipa_pass_list (all_regular_ipa_passes);
1663
1664   if (cgraph_dump_file)
1665     {
1666       fprintf (cgraph_dump_file, "Optimized ");
1667       dump_cgraph (cgraph_dump_file);
1668       dump_varpool (cgraph_dump_file);
1669     }
1670   verify_cgraph ();
1671   bitmap_obstack_release (NULL);
1672
1673   /* We are about to launch the final LTRANS phase, stop the WPA timer.  */
1674   timevar_pop (TV_WHOPR_WPA);
1675
1676   lto_1_to_1_map ();
1677
1678   if (!quiet_flag)
1679     {
1680       fprintf (stderr, "\nStreaming out");
1681       fflush (stderr);
1682     }
1683   lto_wpa_write_files ();
1684   ggc_collect ();
1685   if (!quiet_flag)
1686     fprintf (stderr, "\n");
1687
1688   if (post_ipa_mem_report)
1689     {
1690       fprintf (stderr, "Memory consumption after IPA\n");
1691       dump_memory_report (false);
1692     }
1693
1694   /* Show the LTO report before launching LTRANS.  */
1695   if (flag_lto_report)
1696     print_lto_report ();
1697 }
1698
1699
1700 static GTY(()) tree lto_eh_personality_decl;
1701
1702 /* Return the LTO personality function decl.  */
1703
1704 tree
1705 lto_eh_personality (void)
1706 {
1707   if (!lto_eh_personality_decl)
1708     {
1709       /* Use the first personality DECL for our personality if we don't
1710          support multiple ones.  This ensures that we don't artificially
1711          create the need for them in a single-language program.  */
1712       if (first_personality_decl && !dwarf2out_do_cfi_asm ())
1713         lto_eh_personality_decl = first_personality_decl;
1714       else
1715         lto_eh_personality_decl = lhd_gcc_personality ();
1716     }
1717
1718   return lto_eh_personality_decl;
1719 }
1720
1721
1722 /* Main entry point for the GIMPLE front end.  This front end has
1723    three main personalities:
1724
1725    - LTO (-flto).  All the object files on the command line are
1726      loaded in memory and processed as a single translation unit.
1727      This is the traditional link-time optimization behavior.
1728
1729    - WPA (-fwpa).  Only the callgraph and summary information for
1730      files in the command file are loaded.  A single callgraph
1731      (without function bodies) is instantiated for the whole set of
1732      files.  IPA passes are only allowed to analyze the call graph
1733      and make transformation decisions.  The callgraph is
1734      partitioned, each partition is written to a new object file
1735      together with the transformation decisions.
1736
1737    - LTRANS (-fltrans).  Similar to -flto but it prevents the IPA
1738      summary files from running again.  Since WPA computed summary
1739      information and decided what transformations to apply, LTRANS
1740      simply applies them.  */
1741
1742 void
1743 lto_main (int debug_p ATTRIBUTE_UNUSED)
1744 {
1745   lto_init_reader ();
1746
1747   /* Read all the symbols and call graph from all the files in the
1748      command line.  */
1749   read_cgraph_and_symbols (num_in_fnames, in_fnames);
1750
1751   if (!seen_error ())
1752     {
1753       /* If WPA is enabled analyze the whole call graph and create an
1754          optimization plan.  Otherwise, read in all the function
1755          bodies and continue with optimization.  */
1756       if (flag_wpa)
1757         do_whole_program_analysis ();
1758       else
1759         {
1760           materialize_cgraph ();
1761
1762           /* Let the middle end know that we have read and merged all of
1763              the input files.  */ 
1764           cgraph_optimize ();
1765
1766           /* FIXME lto, if the processes spawned by WPA fail, we miss
1767              the chance to print WPA's report, so WPA will call
1768              print_lto_report before launching LTRANS.  If LTRANS was
1769              launched directly by the driver we would not need to do
1770              this.  */
1771           if (flag_lto_report)
1772             print_lto_report ();
1773         }
1774     }
1775 }
1776
1777 #include "gt-lto-lto.h"