2015-09-25 Vladimir Makarov <vmakarov@redhat.com>
[official-gcc.git] / gcc / lto-wrapper.c
blobe13a82a28c8121200b949dee54d743cc098175e4
1 /* Wrapper to call lto. Used by collect2 and the linker plugin.
2 Copyright (C) 2009-2015 Free Software Foundation, Inc.
4 Factored out of collect2 by Rafael Espindola <espindola@google.com>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
23 /* This program is passed a gcc, a list of gcc arguments and a list of
24 object files containing IL. It scans the argument list to check if
25 we are in whopr mode or not modifies the arguments and needed and
26 prints a list of output files on stdout.
28 Example:
30 $ lto-wrapper gcc/xgcc -B gcc a.o b.o -o test -flto
32 The above will print something like
33 /tmp/ccwbQ8B2.lto.o
35 If WHOPR is used instead, more than one file might be produced
36 ./ccXj2DTk.lto.ltrans.o
37 ./ccCJuXGv.lto.ltrans.o
40 #include "config.h"
41 #include "system.h"
42 #include "coretypes.h"
43 #include "intl.h"
44 #include "diagnostic.h"
45 #include "obstack.h"
46 #include "opts.h"
47 #include "options.h"
48 #include "simple-object.h"
49 #include "lto-section-names.h"
50 #include "collect-utils.h"
52 /* Environment variable, used for passing the names of offload targets from GCC
53 driver to lto-wrapper. */
54 #define OFFLOAD_TARGET_NAMES_ENV "OFFLOAD_TARGET_NAMES"
56 enum lto_mode_d {
57 LTO_MODE_NONE, /* Not doing LTO. */
58 LTO_MODE_LTO, /* Normal LTO. */
59 LTO_MODE_WHOPR /* WHOPR. */
62 /* Current LTO mode. */
63 static enum lto_mode_d lto_mode = LTO_MODE_NONE;
65 static char *ltrans_output_file;
66 static char *flto_out;
67 static unsigned int nr;
68 static char **input_names;
69 static char **output_names;
70 static char **offload_names;
71 static const char *offloadbegin, *offloadend;
72 static char *makefile;
74 const char tool_name[] = "lto-wrapper";
76 /* Delete tempfiles. Called from utils_cleanup. */
78 void
79 tool_cleanup (bool)
81 unsigned int i;
83 if (ltrans_output_file)
84 maybe_unlink (ltrans_output_file);
85 if (flto_out)
86 maybe_unlink (flto_out);
87 if (makefile)
88 maybe_unlink (makefile);
89 for (i = 0; i < nr; ++i)
91 maybe_unlink (input_names[i]);
92 if (output_names[i])
93 maybe_unlink (output_names[i]);
97 static void
98 lto_wrapper_cleanup (void)
100 utils_cleanup (false);
103 /* Unlink a temporary LTRANS file unless requested otherwise. */
105 void
106 maybe_unlink (const char *file)
108 if (!save_temps)
110 if (unlink_if_ordinary (file)
111 && errno != ENOENT)
112 fatal_error (input_location, "deleting LTRANS file %s: %m", file);
114 else if (verbose)
115 fprintf (stderr, "[Leaving LTRANS %s]\n", file);
118 /* Template of LTRANS dumpbase suffix. */
119 #define DUMPBASE_SUFFIX ".ltrans18446744073709551615"
121 /* Create decoded options from the COLLECT_GCC and COLLECT_GCC_OPTIONS
122 environment according to LANG_MASK. */
124 static void
125 get_options_from_collect_gcc_options (const char *collect_gcc,
126 const char *collect_gcc_options,
127 unsigned int lang_mask,
128 struct cl_decoded_option **decoded_options,
129 unsigned int *decoded_options_count)
131 struct obstack argv_obstack;
132 char *argv_storage;
133 const char **argv;
134 int j, k, argc;
136 argv_storage = xstrdup (collect_gcc_options);
137 obstack_init (&argv_obstack);
138 obstack_ptr_grow (&argv_obstack, collect_gcc);
140 for (j = 0, k = 0; argv_storage[j] != '\0'; ++j)
142 if (argv_storage[j] == '\'')
144 obstack_ptr_grow (&argv_obstack, &argv_storage[k]);
145 ++j;
148 if (argv_storage[j] == '\0')
149 fatal_error (input_location, "malformed COLLECT_GCC_OPTIONS");
150 else if (strncmp (&argv_storage[j], "'\\''", 4) == 0)
152 argv_storage[k++] = '\'';
153 j += 4;
155 else if (argv_storage[j] == '\'')
156 break;
157 else
158 argv_storage[k++] = argv_storage[j++];
160 while (1);
161 argv_storage[k++] = '\0';
165 obstack_ptr_grow (&argv_obstack, NULL);
166 argc = obstack_object_size (&argv_obstack) / sizeof (void *) - 1;
167 argv = XOBFINISH (&argv_obstack, const char **);
169 decode_cmdline_options_to_array (argc, (const char **)argv,
170 lang_mask,
171 decoded_options, decoded_options_count);
172 obstack_free (&argv_obstack, NULL);
175 /* Append OPTION to the options array DECODED_OPTIONS with size
176 DECODED_OPTIONS_COUNT. */
178 static void
179 append_option (struct cl_decoded_option **decoded_options,
180 unsigned int *decoded_options_count,
181 struct cl_decoded_option *option)
183 ++*decoded_options_count;
184 *decoded_options
185 = (struct cl_decoded_option *)
186 xrealloc (*decoded_options,
187 (*decoded_options_count
188 * sizeof (struct cl_decoded_option)));
189 memcpy (&(*decoded_options)[*decoded_options_count - 1], option,
190 sizeof (struct cl_decoded_option));
193 /* Try to merge and complain about options FDECODED_OPTIONS when applied
194 ontop of DECODED_OPTIONS. */
196 static void
197 merge_and_complain (struct cl_decoded_option **decoded_options,
198 unsigned int *decoded_options_count,
199 struct cl_decoded_option *fdecoded_options,
200 unsigned int fdecoded_options_count)
202 unsigned int i, j;
204 /* ??? Merge options from files. Most cases can be
205 handled by either unioning or intersecting
206 (for example -fwrapv is a case for unioning,
207 -ffast-math is for intersection). Most complaints
208 about real conflicts between different options can
209 be deferred to the compiler proper. Options that
210 we can neither safely handle by intersection nor
211 unioning would need to be complained about here.
212 Ideally we'd have a flag in the opt files that
213 tells whether to union or intersect or reject.
214 In absence of that it's unclear what a good default is.
215 It's also difficult to get positional handling correct. */
217 /* The following does what the old LTO option code did,
218 union all target and a selected set of common options. */
219 for (i = 0; i < fdecoded_options_count; ++i)
221 struct cl_decoded_option *foption = &fdecoded_options[i];
222 switch (foption->opt_index)
224 case OPT_SPECIAL_unknown:
225 case OPT_SPECIAL_ignore:
226 case OPT_SPECIAL_program_name:
227 case OPT_SPECIAL_input_file:
228 break;
230 default:
231 if (!(cl_options[foption->opt_index].flags & CL_TARGET))
232 break;
234 /* Fallthru. */
235 case OPT_fdiagnostics_show_caret:
236 case OPT_fdiagnostics_show_option:
237 case OPT_fdiagnostics_show_location_:
238 case OPT_fshow_column:
239 case OPT_fPIC:
240 case OPT_fpic:
241 case OPT_fPIE:
242 case OPT_fpie:
243 case OPT_fcommon:
244 case OPT_fexceptions:
245 case OPT_fnon_call_exceptions:
246 case OPT_fgnu_tm:
247 /* Do what the old LTO code did - collect exactly one option
248 setting per OPT code, we pick the first we encounter.
249 ??? This doesn't make too much sense, but when it doesn't
250 then we should complain. */
251 for (j = 0; j < *decoded_options_count; ++j)
252 if ((*decoded_options)[j].opt_index == foption->opt_index)
253 break;
254 if (j == *decoded_options_count)
255 append_option (decoded_options, decoded_options_count, foption);
256 break;
258 case OPT_ftrapv:
259 case OPT_fstrict_overflow:
260 case OPT_ffp_contract_:
261 /* For selected options we can merge conservatively. */
262 for (j = 0; j < *decoded_options_count; ++j)
263 if ((*decoded_options)[j].opt_index == foption->opt_index)
264 break;
265 if (j == *decoded_options_count)
266 append_option (decoded_options, decoded_options_count, foption);
267 /* FP_CONTRACT_OFF < FP_CONTRACT_ON < FP_CONTRACT_FAST,
268 -fno-trapv < -ftrapv,
269 -fno-strict-overflow < -fstrict-overflow */
270 else if (foption->value < (*decoded_options)[j].value)
271 (*decoded_options)[j] = *foption;
272 break;
274 case OPT_fmath_errno:
275 case OPT_fsigned_zeros:
276 case OPT_ftrapping_math:
277 case OPT_fwrapv:
278 case OPT_fopenmp:
279 case OPT_fopenacc:
280 case OPT_fcheck_pointer_bounds:
281 /* For selected options we can merge conservatively. */
282 for (j = 0; j < *decoded_options_count; ++j)
283 if ((*decoded_options)[j].opt_index == foption->opt_index)
284 break;
285 if (j == *decoded_options_count)
286 append_option (decoded_options, decoded_options_count, foption);
287 /* -fmath-errno > -fno-math-errno,
288 -fsigned-zeros > -fno-signed-zeros,
289 -ftrapping-math -> -fno-trapping-math,
290 -fwrapv > -fno-wrapv. */
291 else if (foption->value > (*decoded_options)[j].value)
292 (*decoded_options)[j] = *foption;
293 break;
295 case OPT_freg_struct_return:
296 case OPT_fpcc_struct_return:
297 case OPT_fshort_double:
298 for (j = 0; j < *decoded_options_count; ++j)
299 if ((*decoded_options)[j].opt_index == foption->opt_index)
300 break;
301 if (j == *decoded_options_count)
302 fatal_error (input_location,
303 "Option %s not used consistently in all LTO input"
304 " files", foption->orig_option_with_args_text);
305 break;
307 case OPT_foffload_abi_:
308 for (j = 0; j < *decoded_options_count; ++j)
309 if ((*decoded_options)[j].opt_index == foption->opt_index)
310 break;
311 if (j == *decoded_options_count)
312 append_option (decoded_options, decoded_options_count, foption);
313 else if (foption->value != (*decoded_options)[j].value)
314 fatal_error (input_location,
315 "Option %s not used consistently in all LTO input"
316 " files", foption->orig_option_with_args_text);
317 break;
319 case OPT_O:
320 case OPT_Ofast:
321 case OPT_Og:
322 case OPT_Os:
323 for (j = 0; j < *decoded_options_count; ++j)
324 if ((*decoded_options)[j].opt_index == OPT_O
325 || (*decoded_options)[j].opt_index == OPT_Ofast
326 || (*decoded_options)[j].opt_index == OPT_Og
327 || (*decoded_options)[j].opt_index == OPT_Os)
328 break;
329 if (j == *decoded_options_count)
330 append_option (decoded_options, decoded_options_count, foption);
331 else if ((*decoded_options)[j].opt_index == foption->opt_index
332 && foption->opt_index != OPT_O)
333 /* Exact same options get merged. */
335 else
337 /* For mismatched option kinds preserve the optimization
338 level only, thus merge it as -On. This also handles
339 merging of same optimization level -On. */
340 int level = 0;
341 switch (foption->opt_index)
343 case OPT_O:
344 if (foption->arg[0] == '\0')
345 level = MAX (level, 1);
346 else
347 level = MAX (level, atoi (foption->arg));
348 break;
349 case OPT_Ofast:
350 level = MAX (level, 3);
351 break;
352 case OPT_Og:
353 level = MAX (level, 1);
354 break;
355 case OPT_Os:
356 level = MAX (level, 2);
357 break;
358 default:
359 gcc_unreachable ();
361 switch ((*decoded_options)[j].opt_index)
363 case OPT_O:
364 if ((*decoded_options)[j].arg[0] == '\0')
365 level = MAX (level, 1);
366 else
367 level = MAX (level, atoi ((*decoded_options)[j].arg));
368 break;
369 case OPT_Ofast:
370 level = MAX (level, 3);
371 break;
372 case OPT_Og:
373 level = MAX (level, 1);
374 break;
375 case OPT_Os:
376 level = MAX (level, 2);
377 break;
378 default:
379 gcc_unreachable ();
381 (*decoded_options)[j].opt_index = OPT_O;
382 char *tem;
383 tem = xasprintf ("-O%d", level);
384 (*decoded_options)[j].arg = &tem[2];
385 (*decoded_options)[j].canonical_option[0] = tem;
386 (*decoded_options)[j].value = 1;
388 break;
390 case OPT_foffload_:
391 append_option (decoded_options, decoded_options_count, foption);
392 break;
397 /* Auxiliary function that frees elements of PTR and PTR itself.
398 N is number of elements to be freed. If PTR is NULL, nothing is freed.
399 If an element is NULL, subsequent elements are not freed. */
401 static void **
402 free_array_of_ptrs (void **ptr, unsigned n)
404 if (!ptr)
405 return NULL;
406 for (unsigned i = 0; i < n; i++)
408 if (!ptr[i])
409 break;
410 free (ptr[i]);
412 free (ptr);
413 return NULL;
416 /* Parse STR, saving found tokens into PVALUES and return their number.
417 Tokens are assumed to be delimited by ':'. If APPEND is non-null,
418 append it to every token we find. */
420 static unsigned
421 parse_env_var (const char *str, char ***pvalues, const char *append)
423 const char *curval, *nextval;
424 char **values;
425 unsigned num = 1, i;
427 curval = strchr (str, ':');
428 while (curval)
430 num++;
431 curval = strchr (curval + 1, ':');
434 values = (char**) xmalloc (num * sizeof (char*));
435 curval = str;
436 nextval = strchr (curval, ':');
437 if (nextval == NULL)
438 nextval = strchr (curval, '\0');
440 int append_len = append ? strlen (append) : 0;
441 for (i = 0; i < num; i++)
443 int l = nextval - curval;
444 values[i] = (char*) xmalloc (l + 1 + append_len);
445 memcpy (values[i], curval, l);
446 values[i][l] = 0;
447 if (append)
448 strcat (values[i], append);
449 curval = nextval + 1;
450 nextval = strchr (curval, ':');
451 if (nextval == NULL)
452 nextval = strchr (curval, '\0');
454 *pvalues = values;
455 return num;
458 /* Append options OPTS from lto or offload_lto sections to ARGV_OBSTACK. */
460 static void
461 append_compiler_options (obstack *argv_obstack, struct cl_decoded_option *opts,
462 unsigned int count)
464 /* Append compiler driver arguments as far as they were merged. */
465 for (unsigned int j = 1; j < count; ++j)
467 struct cl_decoded_option *option = &opts[j];
469 /* File options have been properly filtered by lto-opts.c. */
470 switch (option->opt_index)
472 /* Drop arguments that we want to take from the link line. */
473 case OPT_flto_:
474 case OPT_flto:
475 case OPT_flto_partition_:
476 continue;
478 default:
479 break;
482 /* For now do what the original LTO option code was doing - pass
483 on any CL_TARGET flag and a few selected others. */
484 switch (option->opt_index)
486 case OPT_fdiagnostics_show_caret:
487 case OPT_fdiagnostics_show_option:
488 case OPT_fdiagnostics_show_location_:
489 case OPT_fshow_column:
490 case OPT_fPIC:
491 case OPT_fpic:
492 case OPT_fPIE:
493 case OPT_fpie:
494 case OPT_fcommon:
495 case OPT_fexceptions:
496 case OPT_fnon_call_exceptions:
497 case OPT_fgnu_tm:
498 case OPT_freg_struct_return:
499 case OPT_fpcc_struct_return:
500 case OPT_fshort_double:
501 case OPT_ffp_contract_:
502 case OPT_fmath_errno:
503 case OPT_fsigned_zeros:
504 case OPT_ftrapping_math:
505 case OPT_fwrapv:
506 case OPT_fopenmp:
507 case OPT_fopenacc:
508 case OPT_ftrapv:
509 case OPT_fstrict_overflow:
510 case OPT_foffload_abi_:
511 case OPT_O:
512 case OPT_Ofast:
513 case OPT_Og:
514 case OPT_Os:
515 case OPT_fcheck_pointer_bounds:
516 break;
518 default:
519 if (!(cl_options[option->opt_index].flags & CL_TARGET))
520 continue;
523 /* Pass the option on. */
524 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
525 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
529 /* Append linker options OPTS to ARGV_OBSTACK. */
531 static void
532 append_linker_options (obstack *argv_obstack, struct cl_decoded_option *opts,
533 unsigned int count)
535 /* Append linker driver arguments. Compiler options from the linker
536 driver arguments will override / merge with those from the compiler. */
537 for (unsigned int j = 1; j < count; ++j)
539 struct cl_decoded_option *option = &opts[j];
541 /* Do not pass on frontend specific flags not suitable for lto. */
542 if (!(cl_options[option->opt_index].flags
543 & (CL_COMMON|CL_TARGET|CL_DRIVER|CL_LTO)))
544 continue;
546 switch (option->opt_index)
548 case OPT_o:
549 case OPT_flto_:
550 case OPT_flto:
551 /* We've handled these LTO options, do not pass them on. */
552 continue;
554 case OPT_freg_struct_return:
555 case OPT_fpcc_struct_return:
556 case OPT_fshort_double:
557 /* Ignore these, they are determined by the input files.
558 ??? We fail to diagnose a possible mismatch here. */
559 continue;
561 default:
562 break;
565 /* Pass the option on. */
566 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
567 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
571 /* Extract options for TARGET offload compiler from OPTIONS and append
572 them to ARGV_OBSTACK. */
574 static void
575 append_offload_options (obstack *argv_obstack, const char *target,
576 struct cl_decoded_option *options,
577 unsigned int options_count)
579 for (unsigned i = 0; i < options_count; i++)
581 const char *cur, *next, *opts;
582 char **argv;
583 unsigned argc;
584 struct cl_decoded_option *option = &options[i];
586 if (option->opt_index != OPT_foffload_)
587 continue;
589 /* If option argument starts with '-' then no target is specified. That
590 means offload options are specified for all targets, so we need to
591 append them. */
592 if (option->arg[0] == '-')
593 opts = option->arg;
594 else
596 opts = strchr (option->arg, '=');
597 /* If there are offload targets specified, but no actual options,
598 there is nothing to do here. */
599 if (!opts)
600 continue;
602 cur = option->arg;
604 while (cur < opts)
606 next = strchr (cur, ',');
607 if (next == NULL)
608 next = opts;
609 next = (next > opts) ? opts : next;
611 /* Are we looking for this offload target? */
612 if (strlen (target) == (size_t) (next - cur)
613 && strncmp (target, cur, next - cur) == 0)
614 break;
616 /* Skip the comma or equal sign. */
617 cur = next + 1;
620 if (cur >= opts)
621 continue;
623 opts++;
626 argv = buildargv (opts);
627 for (argc = 0; argv[argc]; argc++)
628 obstack_ptr_grow (argv_obstack, argv[argc]);
632 /* Check whether NAME can be accessed in MODE. This is like access,
633 except that it never considers directories to be executable. */
635 static int
636 access_check (const char *name, int mode)
638 if (mode == X_OK)
640 struct stat st;
642 if (stat (name, &st) < 0
643 || S_ISDIR (st.st_mode))
644 return -1;
647 return access (name, mode);
650 /* Prepare a target image for offload TARGET, using mkoffload tool from
651 COMPILER_PATH. Return the name of the resultant object file. */
653 static char *
654 compile_offload_image (const char *target, const char *compiler_path,
655 unsigned in_argc, char *in_argv[],
656 struct cl_decoded_option *compiler_opts,
657 unsigned int compiler_opt_count,
658 struct cl_decoded_option *linker_opts,
659 unsigned int linker_opt_count)
661 char *filename = NULL;
662 char **argv;
663 char *suffix
664 = XALLOCAVEC (char, sizeof ("/accel//mkoffload") + strlen (target));
665 strcpy (suffix, "/accel/");
666 strcat (suffix, target);
667 strcat (suffix, "/mkoffload");
669 char **paths = NULL;
670 unsigned n_paths = parse_env_var (compiler_path, &paths, suffix);
672 const char *compiler = NULL;
673 for (unsigned i = 0; i < n_paths; i++)
674 if (access_check (paths[i], X_OK) == 0)
676 compiler = paths[i];
677 break;
680 if (compiler)
682 /* Generate temporary output file name. */
683 filename = make_temp_file (".target.o");
685 struct obstack argv_obstack;
686 obstack_init (&argv_obstack);
687 obstack_ptr_grow (&argv_obstack, compiler);
688 obstack_ptr_grow (&argv_obstack, "-o");
689 obstack_ptr_grow (&argv_obstack, filename);
691 /* Append names of input object files. */
692 for (unsigned i = 0; i < in_argc; i++)
693 obstack_ptr_grow (&argv_obstack, in_argv[i]);
695 /* Append options from offload_lto sections. */
696 append_compiler_options (&argv_obstack, compiler_opts,
697 compiler_opt_count);
699 /* Append options specified by -foffload last. In case of conflicting
700 options we expect offload compiler to choose the latest. */
701 append_offload_options (&argv_obstack, target, compiler_opts,
702 compiler_opt_count);
703 append_offload_options (&argv_obstack, target, linker_opts,
704 linker_opt_count);
706 obstack_ptr_grow (&argv_obstack, NULL);
707 argv = XOBFINISH (&argv_obstack, char **);
708 fork_execute (argv[0], argv, true);
709 obstack_free (&argv_obstack, NULL);
712 free_array_of_ptrs ((void **) paths, n_paths);
713 return filename;
717 /* The main routine dealing with offloading.
718 The routine builds a target image for each offload target. IN_ARGC and
719 IN_ARGV specify options and input object files. As all of them could contain
720 target sections, we pass them all to target compilers. */
722 static void
723 compile_images_for_offload_targets (unsigned in_argc, char *in_argv[],
724 struct cl_decoded_option *compiler_opts,
725 unsigned int compiler_opt_count,
726 struct cl_decoded_option *linker_opts,
727 unsigned int linker_opt_count)
729 char **names = NULL;
730 const char *target_names = getenv (OFFLOAD_TARGET_NAMES_ENV);
731 if (!target_names)
732 return;
733 unsigned num_targets = parse_env_var (target_names, &names, NULL);
735 const char *compiler_path = getenv ("COMPILER_PATH");
736 if (!compiler_path)
737 goto out;
739 /* Prepare an image for each target and save the name of the resultant object
740 file to the OFFLOAD_NAMES array. It is terminated by a NULL entry. */
741 offload_names = XCNEWVEC (char *, num_targets + 1);
742 for (unsigned i = 0; i < num_targets; i++)
744 offload_names[i]
745 = compile_offload_image (names[i], compiler_path, in_argc, in_argv,
746 compiler_opts, compiler_opt_count,
747 linker_opts, linker_opt_count);
748 if (!offload_names[i])
749 fatal_error (input_location,
750 "problem with building target image for %s\n", names[i]);
753 out:
754 free_array_of_ptrs ((void **) names, num_targets);
757 /* Copy a file from SRC to DEST. */
759 static void
760 copy_file (const char *dest, const char *src)
762 FILE *d = fopen (dest, "wb");
763 FILE *s = fopen (src, "rb");
764 char buffer[512];
765 while (!feof (s))
767 size_t len = fread (buffer, 1, 512, s);
768 if (ferror (s) != 0)
769 fatal_error (input_location, "reading input file");
770 if (len > 0)
772 fwrite (buffer, 1, len, d);
773 if (ferror (d) != 0)
774 fatal_error (input_location, "writing output file");
779 /* Find the crtoffloadbegin.o and crtoffloadend.o files in LIBRARY_PATH, make
780 copies and store the names of the copies in offloadbegin and offloadend. */
782 static void
783 find_offloadbeginend (void)
785 char **paths = NULL;
786 const char *library_path = getenv ("LIBRARY_PATH");
787 if (!library_path)
788 return;
789 unsigned n_paths = parse_env_var (library_path, &paths, "/crtoffloadbegin.o");
791 unsigned i;
792 for (i = 0; i < n_paths; i++)
793 if (access_check (paths[i], R_OK) == 0)
795 size_t len = strlen (paths[i]);
796 char *tmp = xstrdup (paths[i]);
797 strcpy (paths[i] + len - strlen ("begin.o"), "end.o");
798 if (access_check (paths[i], R_OK) != 0)
799 fatal_error (input_location,
800 "installation error, can't find crtoffloadend.o");
801 /* The linker will delete the filenames we give it, so make
802 copies. */
803 offloadbegin = make_temp_file (".o");
804 offloadend = make_temp_file (".o");
805 copy_file (offloadbegin, tmp);
806 copy_file (offloadend, paths[i]);
807 free (tmp);
808 break;
810 if (i == n_paths)
811 fatal_error (input_location,
812 "installation error, can't find crtoffloadbegin.o");
814 free_array_of_ptrs ((void **) paths, n_paths);
817 /* A subroutine of run_gcc. Examine the open file FD for lto sections with
818 name prefix PREFIX, at FILE_OFFSET, and store any options we find in OPTS
819 and OPT_COUNT. Return true if we found a matchingn section, false
820 otherwise. COLLECT_GCC holds the value of the environment variable with
821 the same name. */
823 static bool
824 find_and_merge_options (int fd, off_t file_offset, const char *prefix,
825 struct cl_decoded_option **opts,
826 unsigned int *opt_count, const char *collect_gcc)
828 off_t offset, length;
829 char *data;
830 char *fopts;
831 const char *errmsg;
832 int err;
833 struct cl_decoded_option *fdecoded_options = *opts;
834 unsigned int fdecoded_options_count = *opt_count;
836 simple_object_read *sobj;
837 sobj = simple_object_start_read (fd, file_offset, "__GNU_LTO",
838 &errmsg, &err);
839 if (!sobj)
840 return false;
842 char *secname = XALLOCAVEC (char, strlen (prefix) + sizeof (".opts"));
843 strcpy (secname, prefix);
844 strcat (secname, ".opts");
845 if (!simple_object_find_section (sobj, secname, &offset, &length,
846 &errmsg, &err))
848 simple_object_release_read (sobj);
849 return false;
852 lseek (fd, file_offset + offset, SEEK_SET);
853 data = (char *)xmalloc (length);
854 read (fd, data, length);
855 fopts = data;
858 struct cl_decoded_option *f2decoded_options;
859 unsigned int f2decoded_options_count;
860 get_options_from_collect_gcc_options (collect_gcc,
861 fopts, CL_LANG_ALL,
862 &f2decoded_options,
863 &f2decoded_options_count);
864 if (!fdecoded_options)
866 fdecoded_options = f2decoded_options;
867 fdecoded_options_count = f2decoded_options_count;
869 else
870 merge_and_complain (&fdecoded_options,
871 &fdecoded_options_count,
872 f2decoded_options, f2decoded_options_count);
874 fopts += strlen (fopts) + 1;
876 while (fopts - data < length);
878 free (data);
879 simple_object_release_read (sobj);
880 *opts = fdecoded_options;
881 *opt_count = fdecoded_options_count;
882 return true;
885 /* Execute gcc. ARGC is the number of arguments. ARGV contains the arguments. */
887 static void
888 run_gcc (unsigned argc, char *argv[])
890 unsigned i, j;
891 const char **new_argv;
892 const char **argv_ptr;
893 char *list_option_full = NULL;
894 const char *linker_output = NULL;
895 const char *collect_gcc, *collect_gcc_options;
896 int parallel = 0;
897 int jobserver = 0;
898 bool no_partition = false;
899 struct cl_decoded_option *fdecoded_options = NULL;
900 struct cl_decoded_option *offload_fdecoded_options = NULL;
901 unsigned int fdecoded_options_count = 0;
902 unsigned int offload_fdecoded_options_count = 0;
903 struct cl_decoded_option *decoded_options;
904 unsigned int decoded_options_count;
905 struct obstack argv_obstack;
906 int new_head_argc;
907 bool have_lto = false;
908 bool have_offload = false;
909 unsigned lto_argc = 0, offload_argc = 0;
910 char **lto_argv, **offload_argv;
912 /* Get the driver and options. */
913 collect_gcc = getenv ("COLLECT_GCC");
914 if (!collect_gcc)
915 fatal_error (input_location,
916 "environment variable COLLECT_GCC must be set");
917 collect_gcc_options = getenv ("COLLECT_GCC_OPTIONS");
918 if (!collect_gcc_options)
919 fatal_error (input_location,
920 "environment variable COLLECT_GCC_OPTIONS must be set");
921 get_options_from_collect_gcc_options (collect_gcc, collect_gcc_options,
922 CL_LANG_ALL,
923 &decoded_options,
924 &decoded_options_count);
926 /* Allocate arrays for input object files with LTO or offload IL,
927 and for possible preceding arguments. */
928 lto_argv = XNEWVEC (char *, argc);
929 offload_argv = XNEWVEC (char *, argc);
931 /* Look at saved options in the IL files. */
932 for (i = 1; i < argc; ++i)
934 char *p;
935 int fd;
936 off_t file_offset = 0;
937 long loffset;
938 int consumed;
939 char *filename = argv[i];
941 if ((p = strrchr (argv[i], '@'))
942 && p != argv[i]
943 && sscanf (p, "@%li%n", &loffset, &consumed) >= 1
944 && strlen (p) == (unsigned int) consumed)
946 filename = XNEWVEC (char, p - argv[i] + 1);
947 memcpy (filename, argv[i], p - argv[i]);
948 filename[p - argv[i]] = '\0';
949 file_offset = (off_t) loffset;
951 fd = open (filename, O_RDONLY | O_BINARY);
952 if (fd == -1)
954 lto_argv[lto_argc++] = argv[i];
955 continue;
958 if (find_and_merge_options (fd, file_offset, LTO_SECTION_NAME_PREFIX,
959 &fdecoded_options, &fdecoded_options_count,
960 collect_gcc))
962 have_lto = true;
963 lto_argv[lto_argc++] = argv[i];
966 if (find_and_merge_options (fd, file_offset, OFFLOAD_SECTION_NAME_PREFIX,
967 &offload_fdecoded_options,
968 &offload_fdecoded_options_count, collect_gcc))
970 have_offload = true;
971 offload_argv[offload_argc++] = argv[i];
974 close (fd);
977 /* Initalize the common arguments for the driver. */
978 obstack_init (&argv_obstack);
979 obstack_ptr_grow (&argv_obstack, collect_gcc);
980 obstack_ptr_grow (&argv_obstack, "-xlto");
981 obstack_ptr_grow (&argv_obstack, "-c");
983 append_compiler_options (&argv_obstack, fdecoded_options,
984 fdecoded_options_count);
985 append_linker_options (&argv_obstack, decoded_options, decoded_options_count);
987 /* Scan linker driver arguments for things that are of relevance to us. */
988 for (j = 1; j < decoded_options_count; ++j)
990 struct cl_decoded_option *option = &decoded_options[j];
991 switch (option->opt_index)
993 case OPT_o:
994 linker_output = option->arg;
995 break;
997 case OPT_save_temps:
998 save_temps = 1;
999 break;
1001 case OPT_v:
1002 verbose = 1;
1003 break;
1005 case OPT_flto_partition_:
1006 if (strcmp (option->arg, "none") == 0)
1007 no_partition = true;
1008 break;
1010 case OPT_flto_:
1011 if (strcmp (option->arg, "jobserver") == 0)
1013 jobserver = 1;
1014 parallel = 1;
1016 else
1018 parallel = atoi (option->arg);
1019 if (parallel <= 1)
1020 parallel = 0;
1022 /* Fallthru. */
1024 case OPT_flto:
1025 lto_mode = LTO_MODE_WHOPR;
1026 break;
1028 default:
1029 break;
1033 if (no_partition)
1035 lto_mode = LTO_MODE_LTO;
1036 jobserver = 0;
1037 parallel = 0;
1040 if (linker_output)
1042 char *output_dir, *base, *name;
1043 bool bit_bucket = strcmp (linker_output, HOST_BIT_BUCKET) == 0;
1045 output_dir = xstrdup (linker_output);
1046 base = output_dir;
1047 for (name = base; *name; name++)
1048 if (IS_DIR_SEPARATOR (*name))
1049 base = name + 1;
1050 *base = '\0';
1052 linker_output = &linker_output[base - output_dir];
1053 if (*output_dir == '\0')
1055 static char current_dir[] = { '.', DIR_SEPARATOR, '\0' };
1056 output_dir = current_dir;
1058 if (!bit_bucket)
1060 obstack_ptr_grow (&argv_obstack, "-dumpdir");
1061 obstack_ptr_grow (&argv_obstack, output_dir);
1064 obstack_ptr_grow (&argv_obstack, "-dumpbase");
1067 /* Remember at which point we can scrub args to re-use the commons. */
1068 new_head_argc = obstack_object_size (&argv_obstack) / sizeof (void *);
1070 if (have_offload)
1072 compile_images_for_offload_targets (offload_argc, offload_argv,
1073 offload_fdecoded_options,
1074 offload_fdecoded_options_count,
1075 decoded_options,
1076 decoded_options_count);
1077 if (offload_names)
1079 find_offloadbeginend ();
1080 for (i = 0; offload_names[i]; i++)
1081 printf ("%s\n", offload_names[i]);
1082 free_array_of_ptrs ((void **) offload_names, i);
1086 if (offloadbegin)
1087 printf ("%s\n", offloadbegin);
1089 /* If object files contain offload sections, but do not contain LTO sections,
1090 then there is no need to perform a link-time recompilation, i.e.
1091 lto-wrapper is used only for a compilation of offload images. */
1092 if (have_offload && !have_lto)
1094 for (i = 1; i < argc; ++i)
1095 if (strncmp (argv[i], "-fresolution=", sizeof ("-fresolution=") - 1))
1097 char *out_file;
1098 /* Can be ".o" or ".so". */
1099 char *ext = strrchr (argv[i], '.');
1100 if (ext == NULL)
1101 out_file = make_temp_file ("");
1102 else
1103 out_file = make_temp_file (ext);
1104 /* The linker will delete the files we give it, so make copies. */
1105 copy_file (out_file, argv[i]);
1106 printf ("%s\n", out_file);
1108 goto finish;
1111 if (lto_mode == LTO_MODE_LTO)
1113 flto_out = make_temp_file (".lto.o");
1114 if (linker_output)
1115 obstack_ptr_grow (&argv_obstack, linker_output);
1116 obstack_ptr_grow (&argv_obstack, "-o");
1117 obstack_ptr_grow (&argv_obstack, flto_out);
1119 else
1121 const char *list_option = "-fltrans-output-list=";
1122 size_t list_option_len = strlen (list_option);
1123 char *tmp;
1125 if (linker_output)
1127 char *dumpbase = (char *) xmalloc (strlen (linker_output)
1128 + sizeof (".wpa") + 1);
1129 strcpy (dumpbase, linker_output);
1130 strcat (dumpbase, ".wpa");
1131 obstack_ptr_grow (&argv_obstack, dumpbase);
1134 if (linker_output && save_temps)
1136 ltrans_output_file = (char *) xmalloc (strlen (linker_output)
1137 + sizeof (".ltrans.out") + 1);
1138 strcpy (ltrans_output_file, linker_output);
1139 strcat (ltrans_output_file, ".ltrans.out");
1141 else
1142 ltrans_output_file = make_temp_file (".ltrans.out");
1143 list_option_full = (char *) xmalloc (sizeof (char) *
1144 (strlen (ltrans_output_file) + list_option_len + 1));
1145 tmp = list_option_full;
1147 obstack_ptr_grow (&argv_obstack, tmp);
1148 strcpy (tmp, list_option);
1149 tmp += list_option_len;
1150 strcpy (tmp, ltrans_output_file);
1152 if (jobserver)
1153 obstack_ptr_grow (&argv_obstack, xstrdup ("-fwpa=jobserver"));
1154 else if (parallel > 1)
1156 char buf[256];
1157 sprintf (buf, "-fwpa=%i", parallel);
1158 obstack_ptr_grow (&argv_obstack, xstrdup (buf));
1160 else
1161 obstack_ptr_grow (&argv_obstack, "-fwpa");
1164 /* Append the input objects and possible preceding arguments. */
1165 for (i = 0; i < lto_argc; ++i)
1166 obstack_ptr_grow (&argv_obstack, lto_argv[i]);
1167 obstack_ptr_grow (&argv_obstack, NULL);
1169 new_argv = XOBFINISH (&argv_obstack, const char **);
1170 argv_ptr = &new_argv[new_head_argc];
1171 fork_execute (new_argv[0], CONST_CAST (char **, new_argv), true);
1173 if (lto_mode == LTO_MODE_LTO)
1175 printf ("%s\n", flto_out);
1176 free (flto_out);
1177 flto_out = NULL;
1179 else
1181 FILE *stream = fopen (ltrans_output_file, "r");
1182 FILE *mstream = NULL;
1183 struct obstack env_obstack;
1185 if (!stream)
1186 fatal_error (input_location, "fopen: %s: %m", ltrans_output_file);
1188 /* Parse the list of LTRANS inputs from the WPA stage. */
1189 obstack_init (&env_obstack);
1190 nr = 0;
1191 for (;;)
1193 const unsigned piece = 32;
1194 char *output_name = NULL;
1195 char *buf, *input_name = (char *)xmalloc (piece);
1196 size_t len;
1198 buf = input_name;
1199 cont:
1200 if (!fgets (buf, piece, stream))
1201 break;
1202 len = strlen (input_name);
1203 if (input_name[len - 1] != '\n')
1205 input_name = (char *)xrealloc (input_name, len + piece);
1206 buf = input_name + len;
1207 goto cont;
1209 input_name[len - 1] = '\0';
1211 if (input_name[0] == '*')
1212 output_name = &input_name[1];
1214 nr++;
1215 input_names = (char **)xrealloc (input_names, nr * sizeof (char *));
1216 output_names = (char **)xrealloc (output_names, nr * sizeof (char *));
1217 input_names[nr-1] = input_name;
1218 output_names[nr-1] = output_name;
1220 fclose (stream);
1221 maybe_unlink (ltrans_output_file);
1222 ltrans_output_file = NULL;
1224 if (parallel)
1226 makefile = make_temp_file (".mk");
1227 mstream = fopen (makefile, "w");
1230 /* Execute the LTRANS stage for each input file (or prepare a
1231 makefile to invoke this in parallel). */
1232 for (i = 0; i < nr; ++i)
1234 char *output_name;
1235 char *input_name = input_names[i];
1236 /* If it's a pass-through file do nothing. */
1237 if (output_names[i])
1238 continue;
1240 /* Replace the .o suffix with a .ltrans.o suffix and write
1241 the resulting name to the LTRANS output list. */
1242 obstack_grow (&env_obstack, input_name, strlen (input_name) - 2);
1243 obstack_grow (&env_obstack, ".ltrans.o", sizeof (".ltrans.o"));
1244 output_name = XOBFINISH (&env_obstack, char *);
1246 /* Adjust the dumpbase if the linker output file was seen. */
1247 if (linker_output)
1249 char *dumpbase
1250 = (char *) xmalloc (strlen (linker_output)
1251 + sizeof (DUMPBASE_SUFFIX) + 1);
1252 snprintf (dumpbase,
1253 strlen (linker_output) + sizeof (DUMPBASE_SUFFIX),
1254 "%s.ltrans%u", linker_output, i);
1255 argv_ptr[0] = dumpbase;
1258 argv_ptr[1] = "-fltrans";
1259 argv_ptr[2] = "-o";
1260 argv_ptr[3] = output_name;
1261 argv_ptr[4] = input_name;
1262 argv_ptr[5] = NULL;
1263 if (parallel)
1265 fprintf (mstream, "%s:\n\t@%s ", output_name, new_argv[0]);
1266 for (j = 1; new_argv[j] != NULL; ++j)
1267 fprintf (mstream, " '%s'", new_argv[j]);
1268 fprintf (mstream, "\n");
1269 /* If we are not preserving the ltrans input files then
1270 truncate them as soon as we have processed it. This
1271 reduces temporary disk-space usage. */
1272 if (! save_temps)
1273 fprintf (mstream, "\t@-touch -r %s %s.tem > /dev/null 2>&1 "
1274 "&& mv %s.tem %s\n",
1275 input_name, input_name, input_name, input_name);
1277 else
1279 fork_execute (new_argv[0], CONST_CAST (char **, new_argv),
1280 true);
1281 maybe_unlink (input_name);
1284 output_names[i] = output_name;
1286 if (parallel)
1288 struct pex_obj *pex;
1289 char jobs[32];
1291 fprintf (mstream, "all:");
1292 for (i = 0; i < nr; ++i)
1293 fprintf (mstream, " \\\n\t%s", output_names[i]);
1294 fprintf (mstream, "\n");
1295 fclose (mstream);
1296 if (!jobserver)
1298 /* Avoid passing --jobserver-fd= and similar flags
1299 unless jobserver mode is explicitly enabled. */
1300 putenv (xstrdup ("MAKEFLAGS="));
1301 putenv (xstrdup ("MFLAGS="));
1303 new_argv[0] = getenv ("MAKE");
1304 if (!new_argv[0])
1305 new_argv[0] = "make";
1306 new_argv[1] = "-f";
1307 new_argv[2] = makefile;
1308 i = 3;
1309 if (!jobserver)
1311 snprintf (jobs, 31, "-j%d", parallel);
1312 new_argv[i++] = jobs;
1314 new_argv[i++] = "all";
1315 new_argv[i++] = NULL;
1316 pex = collect_execute (new_argv[0], CONST_CAST (char **, new_argv),
1317 NULL, NULL, PEX_SEARCH, false);
1318 do_wait (new_argv[0], pex);
1319 maybe_unlink (makefile);
1320 makefile = NULL;
1321 for (i = 0; i < nr; ++i)
1322 maybe_unlink (input_names[i]);
1324 for (i = 0; i < nr; ++i)
1326 fputs (output_names[i], stdout);
1327 putc ('\n', stdout);
1328 free (input_names[i]);
1330 nr = 0;
1331 free (output_names);
1332 free (input_names);
1333 free (list_option_full);
1334 obstack_free (&env_obstack, NULL);
1337 finish:
1338 if (offloadend)
1339 printf ("%s\n", offloadend);
1341 XDELETE (lto_argv);
1342 XDELETE (offload_argv);
1343 obstack_free (&argv_obstack, NULL);
1347 /* Entry point. */
1350 main (int argc, char *argv[])
1352 const char *p;
1354 gcc_obstack_init (&opts_obstack);
1356 p = argv[0] + strlen (argv[0]);
1357 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
1358 --p;
1359 progname = p;
1361 xmalloc_set_program_name (progname);
1363 gcc_init_libintl ();
1365 diagnostic_initialize (global_dc, 0);
1367 if (atexit (lto_wrapper_cleanup) != 0)
1368 fatal_error (input_location, "atexit failed");
1370 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1371 signal (SIGINT, fatal_signal);
1372 #ifdef SIGHUP
1373 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1374 signal (SIGHUP, fatal_signal);
1375 #endif
1376 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
1377 signal (SIGTERM, fatal_signal);
1378 #ifdef SIGPIPE
1379 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
1380 signal (SIGPIPE, fatal_signal);
1381 #endif
1382 #ifdef SIGCHLD
1383 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
1384 receive the signal. A different setting is inheritable */
1385 signal (SIGCHLD, SIG_DFL);
1386 #endif
1388 /* We may be called with all the arguments stored in some file and
1389 passed with @file. Expand them into argv before processing. */
1390 expandargv (&argc, &argv);
1392 run_gcc (argc, argv);
1394 return 0;