OSDN Git Service

* tree-inline.c (estimate_num_insns_1): Make OpenMP directives
[pf3gnuchains/gcc-fork.git] / gcc / tree-inline.c
1 /* Tree inlining.
2    Copyright 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
3    Contributed by Alexandre Oliva <aoliva@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "toplev.h"
27 #include "tree.h"
28 #include "tree-inline.h"
29 #include "rtl.h"
30 #include "expr.h"
31 #include "flags.h"
32 #include "params.h"
33 #include "input.h"
34 #include "insn-config.h"
35 #include "varray.h"
36 #include "hashtab.h"
37 #include "langhooks.h"
38 #include "basic-block.h"
39 #include "tree-iterator.h"
40 #include "cgraph.h"
41 #include "intl.h"
42 #include "tree-mudflap.h"
43 #include "tree-flow.h"
44 #include "function.h"
45 #include "ggc.h"
46 #include "tree-flow.h"
47 #include "diagnostic.h"
48 #include "except.h"
49 #include "debug.h"
50 #include "pointer-set.h"
51 #include "ipa-prop.h"
52
53 /* I'm not real happy about this, but we need to handle gimple and
54    non-gimple trees.  */
55 #include "tree-gimple.h"
56
57 /* Inlining, Cloning, Versioning, Parallelization
58
59    Inlining: a function body is duplicated, but the PARM_DECLs are
60    remapped into VAR_DECLs, and non-void RETURN_EXPRs become
61    MODIFY_EXPRs that store to a dedicated returned-value variable.
62    The duplicated eh_region info of the copy will later be appended
63    to the info for the caller; the eh_region info in copied throwing
64    statements and RESX_EXPRs is adjusted accordingly.
65
66    Cloning: (only in C++) We have one body for a con/de/structor, and
67    multiple function decls, each with a unique parameter list.
68    Duplicate the body, using the given splay tree; some parameters
69    will become constants (like 0 or 1).
70
71    Versioning: a function body is duplicated and the result is a new
72    function rather than into blocks of an existing function as with
73    inlining.  Some parameters will become constants.
74
75    Parallelization: a region of a function is duplicated resulting in
76    a new function.  Variables may be replaced with complex expressions
77    to enable shared variable semantics.
78
79    All of these will simultaneously lookup any callgraph edges.  If
80    we're going to inline the duplicated function body, and the given
81    function has some cloned callgraph nodes (one for each place this
82    function will be inlined) those callgraph edges will be duplicated.
83    If we're cloning the body, those callgraph edges will be
84    updated to point into the new body.  (Note that the original
85    callgraph node and edge list will not be altered.)
86
87    See the CALL_EXPR handling case in copy_body_r ().  */
88
89 /* 0 if we should not perform inlining.
90    1 if we should expand functions calls inline at the tree level.
91    2 if we should consider *all* functions to be inline
92    candidates.  */
93
94 int flag_inline_trees = 0;
95
96 /* To Do:
97
98    o In order to make inlining-on-trees work, we pessimized
99      function-local static constants.  In particular, they are now
100      always output, even when not addressed.  Fix this by treating
101      function-local static constants just like global static
102      constants; the back-end already knows not to output them if they
103      are not needed.
104
105    o Provide heuristics to clamp inlining of recursive template
106      calls?  */
107
108 /* Prototypes.  */
109
110 static tree declare_return_variable (copy_body_data *, tree, tree, tree *);
111 static tree copy_generic_body (copy_body_data *);
112 static bool inlinable_function_p (tree);
113 static void remap_block (tree *, copy_body_data *);
114 static tree remap_decls (tree, copy_body_data *);
115 static void copy_bind_expr (tree *, int *, copy_body_data *);
116 static tree mark_local_for_remap_r (tree *, int *, void *);
117 static void unsave_expr_1 (tree);
118 static tree unsave_r (tree *, int *, void *);
119 static void declare_inline_vars (tree, tree);
120 static void remap_save_expr (tree *, void *, int *);
121 static void add_lexical_block (tree current_block, tree new_block);
122 static tree copy_decl_to_var (tree, copy_body_data *);
123 static tree copy_decl_no_change (tree, copy_body_data *);
124 static tree copy_decl_maybe_to_var (tree, copy_body_data *);
125
126 /* Insert a tree->tree mapping for ID.  Despite the name suggests
127    that the trees should be variables, it is used for more than that.  */
128
129 void
130 insert_decl_map (copy_body_data *id, tree key, tree value)
131 {
132   splay_tree_insert (id->decl_map, (splay_tree_key) key,
133                      (splay_tree_value) value);
134
135   /* Always insert an identity map as well.  If we see this same new
136      node again, we won't want to duplicate it a second time.  */
137   if (key != value)
138     splay_tree_insert (id->decl_map, (splay_tree_key) value,
139                        (splay_tree_value) value);
140 }
141
142 /* Remap DECL during the copying of the BLOCK tree for the function.  */
143
144 tree
145 remap_decl (tree decl, copy_body_data *id)
146 {
147   splay_tree_node n;
148   tree fn;
149
150   /* We only remap local variables in the current function.  */
151   fn = id->src_fn;
152
153   /* See if we have remapped this declaration.  */
154
155   n = splay_tree_lookup (id->decl_map, (splay_tree_key) decl);
156
157   /* If we didn't already have an equivalent for this declaration,
158      create one now.  */
159   if (!n)
160     {
161       /* Make a copy of the variable or label.  */
162       tree t = id->copy_decl (decl, id);
163      
164       /* Remember it, so that if we encounter this local entity again
165          we can reuse this copy.  Do this early because remap_type may
166          need this decl for TYPE_STUB_DECL.  */
167       insert_decl_map (id, decl, t);
168
169       if (!DECL_P (t))
170         return t;
171
172       /* Remap types, if necessary.  */
173       TREE_TYPE (t) = remap_type (TREE_TYPE (t), id);
174       if (TREE_CODE (t) == TYPE_DECL)
175         DECL_ORIGINAL_TYPE (t) = remap_type (DECL_ORIGINAL_TYPE (t), id);
176
177       /* Remap sizes as necessary.  */
178       walk_tree (&DECL_SIZE (t), copy_body_r, id, NULL);
179       walk_tree (&DECL_SIZE_UNIT (t), copy_body_r, id, NULL);
180
181       /* If fields, do likewise for offset and qualifier.  */
182       if (TREE_CODE (t) == FIELD_DECL)
183         {
184           walk_tree (&DECL_FIELD_OFFSET (t), copy_body_r, id, NULL);
185           if (TREE_CODE (DECL_CONTEXT (t)) == QUAL_UNION_TYPE)
186             walk_tree (&DECL_QUALIFIER (t), copy_body_r, id, NULL);
187         }
188
189       return t;
190     }
191
192   return unshare_expr ((tree) n->value);
193 }
194
195 static tree
196 remap_type_1 (tree type, copy_body_data *id)
197 {
198   splay_tree_node node;
199   tree new, t;
200
201   if (type == NULL)
202     return type;
203
204   /* See if we have remapped this type.  */
205   node = splay_tree_lookup (id->decl_map, (splay_tree_key) type);
206   if (node)
207     return (tree) node->value;
208
209   /* The type only needs remapping if it's variably modified.  */
210   if (! variably_modified_type_p (type, id->src_fn))
211     {
212       insert_decl_map (id, type, type);
213       return type;
214     }
215
216   /* We do need a copy.  build and register it now.  If this is a pointer or
217      reference type, remap the designated type and make a new pointer or
218      reference type.  */
219   if (TREE_CODE (type) == POINTER_TYPE)
220     {
221       new = build_pointer_type_for_mode (remap_type (TREE_TYPE (type), id),
222                                          TYPE_MODE (type),
223                                          TYPE_REF_CAN_ALIAS_ALL (type));
224       insert_decl_map (id, type, new);
225       return new;
226     }
227   else if (TREE_CODE (type) == REFERENCE_TYPE)
228     {
229       new = build_reference_type_for_mode (remap_type (TREE_TYPE (type), id),
230                                             TYPE_MODE (type),
231                                             TYPE_REF_CAN_ALIAS_ALL (type));
232       insert_decl_map (id, type, new);
233       return new;
234     }
235   else
236     new = copy_node (type);
237
238   insert_decl_map (id, type, new);
239
240   /* This is a new type, not a copy of an old type.  Need to reassociate
241      variants.  We can handle everything except the main variant lazily.  */
242   t = TYPE_MAIN_VARIANT (type);
243   if (type != t)
244     {
245       t = remap_type (t, id);
246       TYPE_MAIN_VARIANT (new) = t;
247       TYPE_NEXT_VARIANT (new) = TYPE_MAIN_VARIANT (t);
248       TYPE_NEXT_VARIANT (t) = new;
249     }
250   else
251     {
252       TYPE_MAIN_VARIANT (new) = new;
253       TYPE_NEXT_VARIANT (new) = NULL;
254     }
255
256   if (TYPE_STUB_DECL (type))
257     TYPE_STUB_DECL (new) = remap_decl (TYPE_STUB_DECL (type), id);
258
259   /* Lazily create pointer and reference types.  */
260   TYPE_POINTER_TO (new) = NULL;
261   TYPE_REFERENCE_TO (new) = NULL;
262
263   switch (TREE_CODE (new))
264     {
265     case INTEGER_TYPE:
266     case REAL_TYPE:
267     case ENUMERAL_TYPE:
268     case BOOLEAN_TYPE:
269       t = TYPE_MIN_VALUE (new);
270       if (t && TREE_CODE (t) != INTEGER_CST)
271         walk_tree (&TYPE_MIN_VALUE (new), copy_body_r, id, NULL);
272
273       t = TYPE_MAX_VALUE (new);
274       if (t && TREE_CODE (t) != INTEGER_CST)
275         walk_tree (&TYPE_MAX_VALUE (new), copy_body_r, id, NULL);
276       return new;
277
278     case FUNCTION_TYPE:
279       TREE_TYPE (new) = remap_type (TREE_TYPE (new), id);
280       walk_tree (&TYPE_ARG_TYPES (new), copy_body_r, id, NULL);
281       return new;
282
283     case ARRAY_TYPE:
284       TREE_TYPE (new) = remap_type (TREE_TYPE (new), id);
285       TYPE_DOMAIN (new) = remap_type (TYPE_DOMAIN (new), id);
286       break;
287
288     case RECORD_TYPE:
289     case UNION_TYPE:
290     case QUAL_UNION_TYPE:
291       {
292         tree f, nf = NULL;
293
294         for (f = TYPE_FIELDS (new); f ; f = TREE_CHAIN (f))
295           {
296             t = remap_decl (f, id);
297             DECL_CONTEXT (t) = new;
298             TREE_CHAIN (t) = nf;
299             nf = t;
300           }
301         TYPE_FIELDS (new) = nreverse (nf);
302       }
303       break;
304
305     case OFFSET_TYPE:
306     default:
307       /* Shouldn't have been thought variable sized.  */
308       gcc_unreachable ();
309     }
310
311   walk_tree (&TYPE_SIZE (new), copy_body_r, id, NULL);
312   walk_tree (&TYPE_SIZE_UNIT (new), copy_body_r, id, NULL);
313
314   return new;
315 }
316
317 tree
318 remap_type (tree type, copy_body_data *id)
319 {
320   splay_tree_node node;
321
322   if (type == NULL)
323     return type;
324
325   /* See if we have remapped this type.  */
326   node = splay_tree_lookup (id->decl_map, (splay_tree_key) type);
327   if (node)
328     return (tree) node->value;
329
330   /* The type only needs remapping if it's variably modified.  */
331   if (! variably_modified_type_p (type, id->src_fn))
332     {
333       insert_decl_map (id, type, type);
334       return type;
335     }
336
337   return remap_type_1 (type, id);
338 }
339
340 static tree
341 remap_decls (tree decls, copy_body_data *id)
342 {
343   tree old_var;
344   tree new_decls = NULL_TREE;
345
346   /* Remap its variables.  */
347   for (old_var = decls; old_var; old_var = TREE_CHAIN (old_var))
348     {
349       tree new_var;
350
351       /* We can not chain the local static declarations into the unexpanded_var_list
352          as we can't duplicate them or break one decl rule.  Go ahead and link
353          them into unexpanded_var_list.  */
354       if (!lang_hooks.tree_inlining.auto_var_in_fn_p (old_var, id->src_fn)
355           && !DECL_EXTERNAL (old_var))
356         {
357           cfun->unexpanded_var_list = tree_cons (NULL_TREE, old_var,
358                                                  cfun->unexpanded_var_list);
359           continue;
360         }
361
362       /* Remap the variable.  */
363       new_var = remap_decl (old_var, id);
364
365       /* If we didn't remap this variable, so we can't mess with its
366          TREE_CHAIN.  If we remapped this variable to the return slot, it's
367          already declared somewhere else, so don't declare it here.  */
368       if (!new_var || new_var == id->retvar)
369         ;
370       else
371         {
372           gcc_assert (DECL_P (new_var));
373           TREE_CHAIN (new_var) = new_decls;
374           new_decls = new_var;
375         }
376     }
377
378   return nreverse (new_decls);
379 }
380
381 /* Copy the BLOCK to contain remapped versions of the variables
382    therein.  And hook the new block into the block-tree.  */
383
384 static void
385 remap_block (tree *block, copy_body_data *id)
386 {
387   tree old_block;
388   tree new_block;
389   tree fn;
390
391   /* Make the new block.  */
392   old_block = *block;
393   new_block = make_node (BLOCK);
394   TREE_USED (new_block) = TREE_USED (old_block);
395   BLOCK_ABSTRACT_ORIGIN (new_block) = old_block;
396   BLOCK_SOURCE_LOCATION (new_block) = BLOCK_SOURCE_LOCATION (old_block);
397   *block = new_block;
398
399   /* Remap its variables.  */
400   BLOCK_VARS (new_block) = remap_decls (BLOCK_VARS (old_block), id);
401
402   fn = id->dst_fn;
403
404   if (id->transform_lang_insert_block)
405     lang_hooks.decls.insert_block (new_block);
406
407   /* Remember the remapped block.  */
408   insert_decl_map (id, old_block, new_block);
409 }
410
411 /* Copy the whole block tree and root it in id->block.  */
412 static tree
413 remap_blocks (tree block, copy_body_data *id)
414 {
415   tree t;
416   tree new = block;
417
418   if (!block)
419     return NULL;
420
421   remap_block (&new, id);
422   gcc_assert (new != block);
423   for (t = BLOCK_SUBBLOCKS (block); t ; t = BLOCK_CHAIN (t))
424     add_lexical_block (new, remap_blocks (t, id));
425   return new;
426 }
427
428 static void
429 copy_statement_list (tree *tp)
430 {
431   tree_stmt_iterator oi, ni;
432   tree new;
433
434   new = alloc_stmt_list ();
435   ni = tsi_start (new);
436   oi = tsi_start (*tp);
437   *tp = new;
438
439   for (; !tsi_end_p (oi); tsi_next (&oi))
440     tsi_link_after (&ni, tsi_stmt (oi), TSI_NEW_STMT);
441 }
442
443 static void
444 copy_bind_expr (tree *tp, int *walk_subtrees, copy_body_data *id)
445 {
446   tree block = BIND_EXPR_BLOCK (*tp);
447   /* Copy (and replace) the statement.  */
448   copy_tree_r (tp, walk_subtrees, NULL);
449   if (block)
450     {
451       remap_block (&block, id);
452       BIND_EXPR_BLOCK (*tp) = block;
453     }
454
455   if (BIND_EXPR_VARS (*tp))
456     /* This will remap a lot of the same decls again, but this should be
457        harmless.  */
458     BIND_EXPR_VARS (*tp) = remap_decls (BIND_EXPR_VARS (*tp), id);
459 }
460
461 /* Called from copy_body_id via walk_tree.  DATA is really an
462    `copy_body_data *'.  */
463
464 tree
465 copy_body_r (tree *tp, int *walk_subtrees, void *data)
466 {
467   copy_body_data *id = (copy_body_data *) data;
468   tree fn = id->src_fn;
469   tree new_block;
470
471   /* Begin by recognizing trees that we'll completely rewrite for the
472      inlining context.  Our output for these trees is completely
473      different from out input (e.g. RETURN_EXPR is deleted, and morphs
474      into an edge).  Further down, we'll handle trees that get
475      duplicated and/or tweaked.  */
476
477   /* When requested, RETURN_EXPRs should be transformed to just the
478      contained MODIFY_EXPR.  The branch semantics of the return will
479      be handled elsewhere by manipulating the CFG rather than a statement.  */
480   if (TREE_CODE (*tp) == RETURN_EXPR && id->transform_return_to_modify)
481     {
482       tree assignment = TREE_OPERAND (*tp, 0);
483
484       /* If we're returning something, just turn that into an
485          assignment into the equivalent of the original RESULT_DECL.
486          If the "assignment" is just the result decl, the result
487          decl has already been set (e.g. a recent "foo (&result_decl,
488          ...)"); just toss the entire RETURN_EXPR.  */
489       if (assignment && TREE_CODE (assignment) == MODIFY_EXPR)
490         {
491           /* Replace the RETURN_EXPR with (a copy of) the
492              MODIFY_EXPR hanging underneath.  */
493           *tp = copy_node (assignment);
494         }
495       else /* Else the RETURN_EXPR returns no value.  */
496         {
497           *tp = NULL;
498           return (tree) (void *)1;
499         }
500     }
501
502   /* Local variables and labels need to be replaced by equivalent
503      variables.  We don't want to copy static variables; there's only
504      one of those, no matter how many times we inline the containing
505      function.  Similarly for globals from an outer function.  */
506   else if (lang_hooks.tree_inlining.auto_var_in_fn_p (*tp, fn))
507     {
508       tree new_decl;
509
510       /* Remap the declaration.  */
511       new_decl = remap_decl (*tp, id);
512       gcc_assert (new_decl);
513       /* Replace this variable with the copy.  */
514       STRIP_TYPE_NOPS (new_decl);
515       *tp = new_decl;
516       *walk_subtrees = 0;
517     }
518   else if (TREE_CODE (*tp) == STATEMENT_LIST)
519     copy_statement_list (tp);
520   else if (TREE_CODE (*tp) == SAVE_EXPR)
521     remap_save_expr (tp, id->decl_map, walk_subtrees);
522   else if (TREE_CODE (*tp) == LABEL_DECL
523            && (! DECL_CONTEXT (*tp)
524                || decl_function_context (*tp) == id->src_fn))
525     /* These may need to be remapped for EH handling.  */
526     *tp = remap_decl (*tp, id);
527   else if (TREE_CODE (*tp) == BIND_EXPR)
528     copy_bind_expr (tp, walk_subtrees, id);
529   /* Types may need remapping as well.  */
530   else if (TYPE_P (*tp))
531     *tp = remap_type (*tp, id);
532
533   /* If this is a constant, we have to copy the node iff the type will be
534      remapped.  copy_tree_r will not copy a constant.  */
535   else if (CONSTANT_CLASS_P (*tp))
536     {
537       tree new_type = remap_type (TREE_TYPE (*tp), id);
538
539       if (new_type == TREE_TYPE (*tp))
540         *walk_subtrees = 0;
541
542       else if (TREE_CODE (*tp) == INTEGER_CST)
543         *tp = build_int_cst_wide (new_type, TREE_INT_CST_LOW (*tp),
544                                   TREE_INT_CST_HIGH (*tp));
545       else
546         {
547           *tp = copy_node (*tp);
548           TREE_TYPE (*tp) = new_type;
549         }
550     }
551
552   /* Otherwise, just copy the node.  Note that copy_tree_r already
553      knows not to copy VAR_DECLs, etc., so this is safe.  */
554   else
555     {
556       /* Here we handle trees that are not completely rewritten.
557          First we detect some inlining-induced bogosities for
558          discarding.  */
559       if (TREE_CODE (*tp) == MODIFY_EXPR
560           && TREE_OPERAND (*tp, 0) == TREE_OPERAND (*tp, 1)
561           && (lang_hooks.tree_inlining.auto_var_in_fn_p
562               (TREE_OPERAND (*tp, 0), fn)))
563         {
564           /* Some assignments VAR = VAR; don't generate any rtl code
565              and thus don't count as variable modification.  Avoid
566              keeping bogosities like 0 = 0.  */
567           tree decl = TREE_OPERAND (*tp, 0), value;
568           splay_tree_node n;
569
570           n = splay_tree_lookup (id->decl_map, (splay_tree_key) decl);
571           if (n)
572             {
573               value = (tree) n->value;
574               STRIP_TYPE_NOPS (value);
575               if (TREE_CONSTANT (value) || TREE_READONLY_DECL_P (value))
576                 {
577                   *tp = build_empty_stmt ();
578                   return copy_body_r (tp, walk_subtrees, data);
579                 }
580             }
581         }
582       else if (TREE_CODE (*tp) == INDIRECT_REF)
583         {
584           /* Get rid of *& from inline substitutions that can happen when a
585              pointer argument is an ADDR_EXPR.  */
586           tree decl = TREE_OPERAND (*tp, 0);
587           splay_tree_node n;
588
589           n = splay_tree_lookup (id->decl_map, (splay_tree_key) decl);
590           if (n)
591             {
592               tree new;
593               /* If we happen to get an ADDR_EXPR in n->value, strip
594                  it manually here as we'll eventually get ADDR_EXPRs
595                  which lie about their types pointed to.  In this case
596                  build_fold_indirect_ref wouldn't strip the INDIRECT_REF,
597                  but we absolutely rely on that.  As fold_indirect_ref
598                  does other useful transformations, try that first, though.  */
599               tree type = TREE_TYPE (TREE_TYPE ((tree)n->value));
600               new = unshare_expr ((tree)n->value);
601               *tp = fold_indirect_ref_1 (type, new);
602               if (! *tp)
603                 {
604                   if (TREE_CODE (new) == ADDR_EXPR)
605                     *tp = TREE_OPERAND (new, 0);
606                   else
607                     *tp = build1 (INDIRECT_REF, type, new);
608                 }
609               *walk_subtrees = 0;
610               return NULL;
611             }
612         }
613
614       /* Here is the "usual case".  Copy this tree node, and then
615          tweak some special cases.  */
616       copy_tree_r (tp, walk_subtrees, NULL);
617        
618       /* If EXPR has block defined, map it to newly constructed block.
619          When inlining we want EXPRs without block appear in the block
620          of function call.  */
621       if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (TREE_CODE (*tp))))
622         {
623           new_block = id->block;
624           if (TREE_BLOCK (*tp))
625             {
626               splay_tree_node n;
627               n = splay_tree_lookup (id->decl_map,
628                                      (splay_tree_key) TREE_BLOCK (*tp));
629               gcc_assert (n);
630               new_block = (tree) n->value;
631             }
632           TREE_BLOCK (*tp) = new_block;
633         }
634
635       if (TREE_CODE (*tp) == RESX_EXPR && id->eh_region_offset)
636         TREE_OPERAND (*tp, 0) =
637           build_int_cst
638             (NULL_TREE,
639              id->eh_region_offset + TREE_INT_CST_LOW (TREE_OPERAND (*tp, 0)));
640
641       TREE_TYPE (*tp) = remap_type (TREE_TYPE (*tp), id);
642
643       /* The copied TARGET_EXPR has never been expanded, even if the
644          original node was expanded already.  */
645       if (TREE_CODE (*tp) == TARGET_EXPR && TREE_OPERAND (*tp, 3))
646         {
647           TREE_OPERAND (*tp, 1) = TREE_OPERAND (*tp, 3);
648           TREE_OPERAND (*tp, 3) = NULL_TREE;
649         }
650
651       /* Variable substitution need not be simple.  In particular, the
652          INDIRECT_REF substitution above.  Make sure that TREE_CONSTANT
653          and friends are up-to-date.  */
654       else if (TREE_CODE (*tp) == ADDR_EXPR)
655         {
656           walk_tree (&TREE_OPERAND (*tp, 0), copy_body_r, id, NULL);
657           recompute_tree_invariant_for_addr_expr (*tp);
658           *walk_subtrees = 0;
659         }
660     }
661
662   /* Keep iterating.  */
663   return NULL_TREE;
664 }
665
666 /* Copy basic block, scale profile accordingly.  Edges will be taken care of
667    later  */
668
669 static basic_block
670 copy_bb (copy_body_data *id, basic_block bb, int frequency_scale, int count_scale)
671 {
672   block_stmt_iterator bsi, copy_bsi;
673   basic_block copy_basic_block;
674
675   /* create_basic_block() will append every new block to
676      basic_block_info automatically.  */
677   copy_basic_block = create_basic_block (NULL, (void *) 0,
678                                          (basic_block) bb->prev_bb->aux);
679   copy_basic_block->count = bb->count * count_scale / REG_BR_PROB_BASE;
680   copy_basic_block->frequency = (bb->frequency
681                                      * frequency_scale / REG_BR_PROB_BASE);
682   copy_bsi = bsi_start (copy_basic_block);
683
684   for (bsi = bsi_start (bb);
685        !bsi_end_p (bsi); bsi_next (&bsi))
686     {
687       tree stmt = bsi_stmt (bsi);
688       tree orig_stmt = stmt;
689
690       walk_tree (&stmt, copy_body_r, id, NULL);
691
692       /* RETURN_EXPR might be removed,
693          this is signalled by making stmt pointer NULL.  */
694       if (stmt)
695         {
696           tree call, decl;
697           bsi_insert_after (&copy_bsi, stmt, BSI_NEW_STMT);
698           call = get_call_expr_in (stmt);
699           /* We're duplicating a CALL_EXPR.  Find any corresponding
700              callgraph edges and update or duplicate them.  */
701           if (call && (decl = get_callee_fndecl (call)))
702             {
703               struct cgraph_node *node;
704               struct cgraph_edge *edge;
705              
706               switch (id->transform_call_graph_edges)
707                 {
708                 case CB_CGE_DUPLICATE:
709                   edge = cgraph_edge (id->src_node, orig_stmt);
710                   if (edge)
711                     cgraph_clone_edge (edge, id->dst_node, stmt,
712                                        REG_BR_PROB_BASE, 1, true);
713                   break;
714
715                 case CB_CGE_MOVE_CLONES:
716                   for (node = id->dst_node->next_clone;
717                        node;
718                        node = node->next_clone)
719                     {
720                       edge = cgraph_edge (node, orig_stmt);
721                       gcc_assert (edge);
722                       edge->call_stmt = stmt;
723                     }
724                   /* FALLTHRU */
725
726                 case CB_CGE_MOVE:
727                   edge = cgraph_edge (id->dst_node, orig_stmt);
728                   if (edge)
729                     edge->call_stmt = stmt;
730                   break;
731
732                 default:
733                   gcc_unreachable ();
734                 }
735             }
736           /* If you think we can abort here, you are wrong.
737              There is no region 0 in tree land.  */
738           gcc_assert (lookup_stmt_eh_region_fn (id->src_cfun, orig_stmt)
739                       != 0);
740
741           if (tree_could_throw_p (stmt))
742             {
743               int region = lookup_stmt_eh_region_fn (id->src_cfun, orig_stmt);
744               /* Add an entry for the copied tree in the EH hashtable.
745                  When cloning or versioning, use the hashtable in
746                  cfun, and just copy the EH number.  When inlining, use the
747                  hashtable in the caller, and adjust the region number.  */
748               if (region > 0)
749                 add_stmt_to_eh_region (stmt, region + id->eh_region_offset);
750
751               /* If this tree doesn't have a region associated with it,
752                  and there is a "current region,"
753                  then associate this tree with the current region
754                  and add edges associated with this region.  */
755               if ((lookup_stmt_eh_region_fn (id->src_cfun,
756                                              orig_stmt) <= 0
757                    && id->eh_region > 0)
758                   && tree_could_throw_p (stmt))
759                 add_stmt_to_eh_region (stmt, id->eh_region);
760             }
761         }
762     }
763   return copy_basic_block;
764 }
765
766 /* Copy edges from BB into its copy constructed earlier, scale profile
767    accordingly.  Edges will be taken care of later.  Assume aux
768    pointers to point to the copies of each BB.  */
769 static void
770 copy_edges_for_bb (basic_block bb, int count_scale)
771 {
772   basic_block new_bb = (basic_block) bb->aux;
773   edge_iterator ei;
774   edge old_edge;
775   block_stmt_iterator bsi;
776   int flags;
777
778   /* Use the indices from the original blocks to create edges for the
779      new ones.  */
780   FOR_EACH_EDGE (old_edge, ei, bb->succs)
781     if (!(old_edge->flags & EDGE_EH))
782       {
783         edge new;
784
785         flags = old_edge->flags;
786
787         /* Return edges do get a FALLTHRU flag when the get inlined.  */
788         if (old_edge->dest->index == EXIT_BLOCK && !old_edge->flags
789             && old_edge->dest->aux != EXIT_BLOCK_PTR)
790           flags |= EDGE_FALLTHRU;
791         new = make_edge (new_bb, (basic_block) old_edge->dest->aux, flags);
792         new->count = old_edge->count * count_scale / REG_BR_PROB_BASE;
793         new->probability = old_edge->probability;
794       }
795
796   if (bb->index == ENTRY_BLOCK || bb->index == EXIT_BLOCK)
797     return;
798
799   for (bsi = bsi_start (new_bb); !bsi_end_p (bsi);)
800     {
801       tree copy_stmt;
802
803       copy_stmt = bsi_stmt (bsi);
804       update_stmt (copy_stmt);
805       /* Do this before the possible split_block.  */
806       bsi_next (&bsi);
807
808       /* If this tree could throw an exception, there are two
809          cases where we need to add abnormal edge(s): the
810          tree wasn't in a region and there is a "current
811          region" in the caller; or the original tree had
812          EH edges.  In both cases split the block after the tree,
813          and add abnormal edge(s) as needed; we need both
814          those from the callee and the caller.
815          We check whether the copy can throw, because the const
816          propagation can change an INDIRECT_REF which throws
817          into a COMPONENT_REF which doesn't.  If the copy
818          can throw, the original could also throw.  */
819
820       if (tree_can_throw_internal (copy_stmt))
821         {
822           if (!bsi_end_p (bsi))
823             /* Note that bb's predecessor edges aren't necessarily
824                right at this point; split_block doesn't care.  */
825             {
826               edge e = split_block (new_bb, copy_stmt);
827               new_bb = e->dest;
828               bsi = bsi_start (new_bb);
829             }
830
831            make_eh_edges (copy_stmt);
832         }
833     }
834 }
835
836 /* Wrapper for remap_decl so it can be used as a callback.  */
837 static tree
838 remap_decl_1 (tree decl, void *data)
839 {
840   return remap_decl (decl, (copy_body_data *) data);
841 }
842
843 /* Make a copy of the body of FN so that it can be inserted inline in
844    another function.  Walks FN via CFG, returns new fndecl.  */
845
846 static tree
847 copy_cfg_body (copy_body_data * id, gcov_type count, int frequency,
848                basic_block entry_block_map, basic_block exit_block_map)
849 {
850   tree callee_fndecl = id->src_fn;
851   /* Original cfun for the callee, doesn't change.  */
852   struct function *src_cfun = DECL_STRUCT_FUNCTION (callee_fndecl);
853   /* Copy, built by this function.  */
854   struct function *new_cfun;
855   /* Place to copy from; when a copy of the function was saved off earlier,
856      use that instead of the main copy.  */
857   struct function *cfun_to_copy =
858     (struct function *) ggc_alloc_cleared (sizeof (struct function));
859   basic_block bb;
860   tree new_fndecl = NULL;
861   int count_scale, frequency_scale;
862
863   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count)
864     count_scale = (REG_BR_PROB_BASE * count
865                    / ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count);
866   else
867     count_scale = 1;
868
869   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency)
870     frequency_scale = (REG_BR_PROB_BASE * frequency
871                        /
872                        ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency);
873   else
874     frequency_scale = count_scale;
875
876   /* Register specific tree functions.  */
877   tree_register_cfg_hooks ();
878
879   /* Must have a CFG here at this point.  */
880   gcc_assert (ENTRY_BLOCK_PTR_FOR_FUNCTION
881               (DECL_STRUCT_FUNCTION (callee_fndecl)));
882
883   *cfun_to_copy = *DECL_STRUCT_FUNCTION (callee_fndecl);
884
885   id->src_cfun = cfun_to_copy;
886
887   /* If requested, create new basic_block_info and label_to_block_maps.
888      Otherwise, insert our new blocks and labels into the existing cfg.  */
889   if (id->transform_new_cfg)
890     {
891       new_cfun =
892         (struct function *) ggc_alloc_cleared (sizeof (struct function));
893       *new_cfun = *DECL_STRUCT_FUNCTION (callee_fndecl);
894       new_cfun->cfg = NULL;
895       new_cfun->decl = new_fndecl = copy_node (callee_fndecl);
896       new_cfun->ib_boundaries_block = (varray_type) 0;
897       DECL_STRUCT_FUNCTION (new_fndecl) = new_cfun;
898       push_cfun (new_cfun);
899       init_empty_tree_cfg ();
900
901       ENTRY_BLOCK_PTR->count =
902         (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count * count_scale /
903          REG_BR_PROB_BASE);
904       ENTRY_BLOCK_PTR->frequency =
905         (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency *
906          frequency_scale / REG_BR_PROB_BASE);
907       EXIT_BLOCK_PTR->count =
908         (EXIT_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count * count_scale /
909          REG_BR_PROB_BASE);
910       EXIT_BLOCK_PTR->frequency =
911         (EXIT_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency *
912          frequency_scale / REG_BR_PROB_BASE);
913
914       entry_block_map = ENTRY_BLOCK_PTR;
915       exit_block_map = EXIT_BLOCK_PTR;
916     }
917
918   ENTRY_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy)->aux = entry_block_map;
919   EXIT_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy)->aux = exit_block_map;
920
921   /* Duplicate any exception-handling regions.  */
922   if (cfun->eh)
923     {
924       if (id->transform_new_cfg)
925         init_eh_for_function ();
926       id->eh_region_offset
927         = duplicate_eh_regions (cfun_to_copy, remap_decl_1, id, id->eh_region);
928     }
929   /* Use aux pointers to map the original blocks to copy.  */
930   FOR_EACH_BB_FN (bb, cfun_to_copy)
931     bb->aux = copy_bb (id, bb, frequency_scale, count_scale);
932   /* Now that we've duplicated the blocks, duplicate their edges.  */
933   FOR_ALL_BB_FN (bb, cfun_to_copy)
934     copy_edges_for_bb (bb, count_scale);
935   FOR_ALL_BB_FN (bb, cfun_to_copy)
936     bb->aux = NULL;
937
938   if (id->transform_new_cfg)
939     pop_cfun ();
940
941   return new_fndecl;
942 }
943
944 /* Make a copy of the body of FN so that it can be inserted inline in
945    another function.  */
946
947 static tree
948 copy_generic_body (copy_body_data *id)
949 {
950   tree body;
951   tree fndecl = id->src_fn;
952
953   body = DECL_SAVED_TREE (fndecl);
954   walk_tree (&body, copy_body_r, id, NULL);
955
956   return body;
957 }
958
959 static tree
960 copy_body (copy_body_data *id, gcov_type count, int frequency,
961            basic_block entry_block_map, basic_block exit_block_map)
962 {
963   tree fndecl = id->src_fn;
964   tree body;
965
966   /* If this body has a CFG, walk CFG and copy.  */
967   gcc_assert (ENTRY_BLOCK_PTR_FOR_FUNCTION (DECL_STRUCT_FUNCTION (fndecl)));
968   body = copy_cfg_body (id, count, frequency, entry_block_map, exit_block_map);
969
970   return body;
971 }
972
973 /* Return true if VALUE is an ADDR_EXPR of an automatic variable
974    defined in function FN, or of a data member thereof.  */
975
976 static bool
977 self_inlining_addr_expr (tree value, tree fn)
978 {
979   tree var;
980
981   if (TREE_CODE (value) != ADDR_EXPR)
982     return false;
983
984   var = get_base_address (TREE_OPERAND (value, 0));
985
986   return var && lang_hooks.tree_inlining.auto_var_in_fn_p (var, fn);
987 }
988
989 static void
990 setup_one_parameter (copy_body_data *id, tree p, tree value, tree fn,
991                      basic_block bb, tree *vars)
992 {
993   tree init_stmt;
994   tree var;
995   tree var_sub;
996
997   /* If the parameter is never assigned to, we may not need to
998      create a new variable here at all.  Instead, we may be able
999      to just use the argument value.  */
1000   if (TREE_READONLY (p)
1001       && !TREE_ADDRESSABLE (p)
1002       && value && !TREE_SIDE_EFFECTS (value))
1003     {
1004       /* We may produce non-gimple trees by adding NOPs or introduce
1005          invalid sharing when operand is not really constant.
1006          It is not big deal to prohibit constant propagation here as
1007          we will constant propagate in DOM1 pass anyway.  */
1008       if (is_gimple_min_invariant (value)
1009           && lang_hooks.types_compatible_p (TREE_TYPE (value), TREE_TYPE (p))
1010           /* We have to be very careful about ADDR_EXPR.  Make sure
1011              the base variable isn't a local variable of the inlined
1012              function, e.g., when doing recursive inlining, direct or
1013              mutually-recursive or whatever, which is why we don't
1014              just test whether fn == current_function_decl.  */
1015           && ! self_inlining_addr_expr (value, fn))
1016         {
1017           insert_decl_map (id, p, value);
1018           return;
1019         }
1020     }
1021
1022   /* Make an equivalent VAR_DECL.  Note that we must NOT remap the type
1023      here since the type of this decl must be visible to the calling
1024      function.  */
1025   var = copy_decl_to_var (p, id);
1026
1027   /* See if the frontend wants to pass this by invisible reference.  If
1028      so, our new VAR_DECL will have REFERENCE_TYPE, and we need to
1029      replace uses of the PARM_DECL with dereferences.  */
1030   if (TREE_TYPE (var) != TREE_TYPE (p)
1031       && POINTER_TYPE_P (TREE_TYPE (var))
1032       && TREE_TYPE (TREE_TYPE (var)) == TREE_TYPE (p))
1033     {
1034       insert_decl_map (id, var, var);
1035       var_sub = build_fold_indirect_ref (var);
1036     }
1037   else
1038     var_sub = var;
1039
1040   /* Register the VAR_DECL as the equivalent for the PARM_DECL;
1041      that way, when the PARM_DECL is encountered, it will be
1042      automatically replaced by the VAR_DECL.  */
1043   insert_decl_map (id, p, var_sub);
1044
1045   /* Declare this new variable.  */
1046   TREE_CHAIN (var) = *vars;
1047   *vars = var;
1048
1049   /* Make gimplifier happy about this variable.  */
1050   DECL_SEEN_IN_BIND_EXPR_P (var) = 1;
1051
1052   /* Even if P was TREE_READONLY, the new VAR should not be.
1053      In the original code, we would have constructed a
1054      temporary, and then the function body would have never
1055      changed the value of P.  However, now, we will be
1056      constructing VAR directly.  The constructor body may
1057      change its value multiple times as it is being
1058      constructed.  Therefore, it must not be TREE_READONLY;
1059      the back-end assumes that TREE_READONLY variable is
1060      assigned to only once.  */
1061   if (TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (p)))
1062     TREE_READONLY (var) = 0;
1063
1064   /* Initialize this VAR_DECL from the equivalent argument.  Convert
1065      the argument to the proper type in case it was promoted.  */
1066   if (value)
1067     {
1068       tree rhs = fold_convert (TREE_TYPE (var), value);
1069       block_stmt_iterator bsi = bsi_last (bb);
1070
1071       if (rhs == error_mark_node)
1072         return;
1073
1074       /* We want to use MODIFY_EXPR, not INIT_EXPR here so that we
1075          keep our trees in gimple form.  */
1076       init_stmt = build2 (MODIFY_EXPR, TREE_TYPE (var), var, rhs);
1077
1078       /* If we did not create a gimple value and we did not create a gimple
1079          cast of a gimple value, then we will need to gimplify INIT_STMTS
1080          at the end.  Note that is_gimple_cast only checks the outer
1081          tree code, not its operand.  Thus the explicit check that its
1082          operand is a gimple value.  */
1083       if (!is_gimple_val (rhs)
1084           && (!is_gimple_cast (rhs)
1085               || !is_gimple_val (TREE_OPERAND (rhs, 0))))
1086         gimplify_stmt (&init_stmt);
1087
1088       /* If VAR represents a zero-sized variable, it's possible that the
1089          assignment statment may result in no gimple statements.  */
1090       if (init_stmt)
1091         bsi_insert_after (&bsi, init_stmt, BSI_NEW_STMT);
1092     }
1093 }
1094
1095 /* Generate code to initialize the parameters of the function at the
1096    top of the stack in ID from the ARGS (presented as a TREE_LIST).  */
1097
1098 static void
1099 initialize_inlined_parameters (copy_body_data *id, tree args, tree static_chain,
1100                                tree fn, basic_block bb)
1101 {
1102   tree parms;
1103   tree a;
1104   tree p;
1105   tree vars = NULL_TREE;
1106   int argnum = 0;
1107
1108   /* Figure out what the parameters are.  */
1109   parms = DECL_ARGUMENTS (fn);
1110
1111   /* Loop through the parameter declarations, replacing each with an
1112      equivalent VAR_DECL, appropriately initialized.  */
1113   for (p = parms, a = args; p;
1114        a = a ? TREE_CHAIN (a) : a, p = TREE_CHAIN (p))
1115     {
1116       tree value;
1117
1118       ++argnum;
1119
1120       /* Find the initializer.  */
1121       value = lang_hooks.tree_inlining.convert_parm_for_inlining
1122               (p, a ? TREE_VALUE (a) : NULL_TREE, fn, argnum);
1123
1124       setup_one_parameter (id, p, value, fn, bb, &vars);
1125     }
1126
1127   /* Initialize the static chain.  */
1128   p = DECL_STRUCT_FUNCTION (fn)->static_chain_decl;
1129   gcc_assert (fn != current_function_decl);
1130   if (p)
1131     {
1132       /* No static chain?  Seems like a bug in tree-nested.c.  */
1133       gcc_assert (static_chain);
1134
1135       setup_one_parameter (id, p, static_chain, fn, bb, &vars);
1136     }
1137
1138   declare_inline_vars (id->block, vars);
1139 }
1140
1141 /* Declare a return variable to replace the RESULT_DECL for the
1142    function we are calling.  An appropriate DECL_STMT is returned.
1143    The USE_STMT is filled to contain a use of the declaration to
1144    indicate the return value of the function.
1145
1146    RETURN_SLOT_ADDR, if non-null, was a fake parameter that
1147    took the address of the result.  MODIFY_DEST, if non-null, was the LHS of
1148    the MODIFY_EXPR to which this call is the RHS.
1149
1150    The return value is a (possibly null) value that is the result of the
1151    function as seen by the callee.  *USE_P is a (possibly null) value that
1152    holds the result as seen by the caller.  */
1153
1154 static tree
1155 declare_return_variable (copy_body_data *id, tree return_slot_addr,
1156                          tree modify_dest, tree *use_p)
1157 {
1158   tree callee = id->src_fn;
1159   tree caller = id->dst_fn;
1160   tree result = DECL_RESULT (callee);
1161   tree callee_type = TREE_TYPE (result);
1162   tree caller_type = TREE_TYPE (TREE_TYPE (callee));
1163   tree var, use;
1164
1165   /* We don't need to do anything for functions that don't return
1166      anything.  */
1167   if (!result || VOID_TYPE_P (callee_type))
1168     {
1169       *use_p = NULL_TREE;
1170       return NULL_TREE;
1171     }
1172
1173   /* If there was a return slot, then the return value is the
1174      dereferenced address of that object.  */
1175   if (return_slot_addr)
1176     {
1177       /* The front end shouldn't have used both return_slot_addr and
1178          a modify expression.  */
1179       gcc_assert (!modify_dest);
1180       if (DECL_BY_REFERENCE (result))
1181         var = return_slot_addr;
1182       else
1183         var = build_fold_indirect_ref (return_slot_addr);
1184       if (TREE_CODE (TREE_TYPE (result)) == COMPLEX_TYPE
1185           && !DECL_COMPLEX_GIMPLE_REG_P (result)
1186           && DECL_P (var))
1187         DECL_COMPLEX_GIMPLE_REG_P (var) = 0;
1188       use = NULL;
1189       goto done;
1190     }
1191
1192   /* All types requiring non-trivial constructors should have been handled.  */
1193   gcc_assert (!TREE_ADDRESSABLE (callee_type));
1194
1195   /* Attempt to avoid creating a new temporary variable.  */
1196   if (modify_dest)
1197     {
1198       bool use_it = false;
1199
1200       /* We can't use MODIFY_DEST if there's type promotion involved.  */
1201       if (!lang_hooks.types_compatible_p (caller_type, callee_type))
1202         use_it = false;
1203
1204       /* ??? If we're assigning to a variable sized type, then we must
1205          reuse the destination variable, because we've no good way to
1206          create variable sized temporaries at this point.  */
1207       else if (TREE_CODE (TYPE_SIZE_UNIT (caller_type)) != INTEGER_CST)
1208         use_it = true;
1209
1210       /* If the callee cannot possibly modify MODIFY_DEST, then we can
1211          reuse it as the result of the call directly.  Don't do this if
1212          it would promote MODIFY_DEST to addressable.  */
1213       else if (TREE_ADDRESSABLE (result))
1214         use_it = false;
1215       else
1216         {
1217           tree base_m = get_base_address (modify_dest);
1218
1219           /* If the base isn't a decl, then it's a pointer, and we don't
1220              know where that's going to go.  */
1221           if (!DECL_P (base_m))
1222             use_it = false;
1223           else if (is_global_var (base_m))
1224             use_it = false;
1225           else if (TREE_CODE (TREE_TYPE (base_m)) == COMPLEX_TYPE
1226                    && !DECL_COMPLEX_GIMPLE_REG_P (result))
1227             DECL_COMPLEX_GIMPLE_REG_P (base_m) = 0;
1228           else if (!TREE_ADDRESSABLE (base_m))
1229             use_it = true;
1230         }
1231
1232       if (use_it)
1233         {
1234           var = modify_dest;
1235           use = NULL;
1236           goto done;
1237         }
1238     }
1239
1240   gcc_assert (TREE_CODE (TYPE_SIZE_UNIT (callee_type)) == INTEGER_CST);
1241
1242   var = copy_decl_to_var (result, id);
1243
1244   DECL_SEEN_IN_BIND_EXPR_P (var) = 1;
1245   DECL_STRUCT_FUNCTION (caller)->unexpanded_var_list
1246     = tree_cons (NULL_TREE, var,
1247                  DECL_STRUCT_FUNCTION (caller)->unexpanded_var_list);
1248
1249   /* Do not have the rest of GCC warn about this variable as it should
1250      not be visible to the user.  */
1251   TREE_NO_WARNING (var) = 1;
1252
1253   /* Build the use expr.  If the return type of the function was
1254      promoted, convert it back to the expected type.  */
1255   use = var;
1256   if (!lang_hooks.types_compatible_p (TREE_TYPE (var), caller_type))
1257     use = fold_convert (caller_type, var);
1258
1259  done:
1260   /* Register the VAR_DECL as the equivalent for the RESULT_DECL; that
1261      way, when the RESULT_DECL is encountered, it will be
1262      automatically replaced by the VAR_DECL.  */
1263   insert_decl_map (id, result, var);
1264
1265   /* Remember this so we can ignore it in remap_decls.  */
1266   id->retvar = var;
1267
1268   *use_p = use;
1269   return var;
1270 }
1271
1272 /* Returns nonzero if a function can be inlined as a tree.  */
1273
1274 bool
1275 tree_inlinable_function_p (tree fn)
1276 {
1277   return inlinable_function_p (fn);
1278 }
1279
1280 static const char *inline_forbidden_reason;
1281
1282 static tree
1283 inline_forbidden_p_1 (tree *nodep, int *walk_subtrees ATTRIBUTE_UNUSED,
1284                       void *fnp)
1285 {
1286   tree node = *nodep;
1287   tree fn = (tree) fnp;
1288   tree t;
1289
1290   switch (TREE_CODE (node))
1291     {
1292     case CALL_EXPR:
1293       /* Refuse to inline alloca call unless user explicitly forced so as
1294          this may change program's memory overhead drastically when the
1295          function using alloca is called in loop.  In GCC present in
1296          SPEC2000 inlining into schedule_block cause it to require 2GB of
1297          RAM instead of 256MB.  */
1298       if (alloca_call_p (node)
1299           && !lookup_attribute ("always_inline", DECL_ATTRIBUTES (fn)))
1300         {
1301           inline_forbidden_reason
1302             = G_("function %q+F can never be inlined because it uses "
1303                  "alloca (override using the always_inline attribute)");
1304           return node;
1305         }
1306       t = get_callee_fndecl (node);
1307       if (! t)
1308         break;
1309
1310       /* We cannot inline functions that call setjmp.  */
1311       if (setjmp_call_p (t))
1312         {
1313           inline_forbidden_reason
1314             = G_("function %q+F can never be inlined because it uses setjmp");
1315           return node;
1316         }
1317
1318       if (DECL_BUILT_IN_CLASS (t) == BUILT_IN_NORMAL)
1319         switch (DECL_FUNCTION_CODE (t))
1320           {
1321             /* We cannot inline functions that take a variable number of
1322                arguments.  */
1323           case BUILT_IN_VA_START:
1324           case BUILT_IN_STDARG_START:
1325           case BUILT_IN_NEXT_ARG:
1326           case BUILT_IN_VA_END:
1327             inline_forbidden_reason
1328               = G_("function %q+F can never be inlined because it "
1329                    "uses variable argument lists");
1330             return node;
1331
1332           case BUILT_IN_LONGJMP:
1333             /* We can't inline functions that call __builtin_longjmp at
1334                all.  The non-local goto machinery really requires the
1335                destination be in a different function.  If we allow the
1336                function calling __builtin_longjmp to be inlined into the
1337                function calling __builtin_setjmp, Things will Go Awry.  */
1338             inline_forbidden_reason
1339               = G_("function %q+F can never be inlined because "
1340                    "it uses setjmp-longjmp exception handling");
1341             return node;
1342
1343           case BUILT_IN_NONLOCAL_GOTO:
1344             /* Similarly.  */
1345             inline_forbidden_reason
1346               = G_("function %q+F can never be inlined because "
1347                    "it uses non-local goto");
1348             return node;
1349
1350           case BUILT_IN_RETURN:
1351           case BUILT_IN_APPLY_ARGS:
1352             /* If a __builtin_apply_args caller would be inlined,
1353                it would be saving arguments of the function it has
1354                been inlined into.  Similarly __builtin_return would
1355                return from the function the inline has been inlined into.  */
1356             inline_forbidden_reason
1357               = G_("function %q+F can never be inlined because "
1358                    "it uses __builtin_return or __builtin_apply_args");
1359             return node;
1360
1361           default:
1362             break;
1363           }
1364       break;
1365
1366     case GOTO_EXPR:
1367       t = TREE_OPERAND (node, 0);
1368
1369       /* We will not inline a function which uses computed goto.  The
1370          addresses of its local labels, which may be tucked into
1371          global storage, are of course not constant across
1372          instantiations, which causes unexpected behavior.  */
1373       if (TREE_CODE (t) != LABEL_DECL)
1374         {
1375           inline_forbidden_reason
1376             = G_("function %q+F can never be inlined "
1377                  "because it contains a computed goto");
1378           return node;
1379         }
1380       break;
1381
1382     case LABEL_EXPR:
1383       t = TREE_OPERAND (node, 0);
1384       if (DECL_NONLOCAL (t))
1385         {
1386           /* We cannot inline a function that receives a non-local goto
1387              because we cannot remap the destination label used in the
1388              function that is performing the non-local goto.  */
1389           inline_forbidden_reason
1390             = G_("function %q+F can never be inlined "
1391                  "because it receives a non-local goto");
1392           return node;
1393         }
1394       break;
1395
1396     case RECORD_TYPE:
1397     case UNION_TYPE:
1398       /* We cannot inline a function of the form
1399
1400            void F (int i) { struct S { int ar[i]; } s; }
1401
1402          Attempting to do so produces a catch-22.
1403          If walk_tree examines the TYPE_FIELDS chain of RECORD_TYPE/
1404          UNION_TYPE nodes, then it goes into infinite recursion on a
1405          structure containing a pointer to its own type.  If it doesn't,
1406          then the type node for S doesn't get adjusted properly when
1407          F is inlined. 
1408
1409          ??? This is likely no longer true, but it's too late in the 4.0
1410          cycle to try to find out.  This should be checked for 4.1.  */
1411       for (t = TYPE_FIELDS (node); t; t = TREE_CHAIN (t))
1412         if (variably_modified_type_p (TREE_TYPE (t), NULL))
1413           {
1414             inline_forbidden_reason
1415               = G_("function %q+F can never be inlined "
1416                    "because it uses variable sized variables");
1417             return node;
1418           }
1419
1420     default:
1421       break;
1422     }
1423
1424   return NULL_TREE;
1425 }
1426
1427 /* Return subexpression representing possible alloca call, if any.  */
1428 static tree
1429 inline_forbidden_p (tree fndecl)
1430 {
1431   location_t saved_loc = input_location;
1432   block_stmt_iterator bsi;
1433   basic_block bb;
1434   tree ret = NULL_TREE;
1435
1436   FOR_EACH_BB_FN (bb, DECL_STRUCT_FUNCTION (fndecl))
1437     for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1438       {
1439         ret = walk_tree_without_duplicates (bsi_stmt_ptr (bsi),
1440                                     inline_forbidden_p_1, fndecl);
1441         if (ret)
1442           goto egress;
1443       }
1444
1445 egress:
1446   input_location = saved_loc;
1447   return ret;
1448 }
1449
1450 /* Returns nonzero if FN is a function that does not have any
1451    fundamental inline blocking properties.  */
1452
1453 static bool
1454 inlinable_function_p (tree fn)
1455 {
1456   bool inlinable = true;
1457
1458   /* If we've already decided this function shouldn't be inlined,
1459      there's no need to check again.  */
1460   if (DECL_UNINLINABLE (fn))
1461     return false;
1462
1463   /* See if there is any language-specific reason it cannot be
1464      inlined.  (It is important that this hook be called early because
1465      in C++ it may result in template instantiation.)
1466      If the function is not inlinable for language-specific reasons,
1467      it is left up to the langhook to explain why.  */
1468   inlinable = !lang_hooks.tree_inlining.cannot_inline_tree_fn (&fn);
1469
1470   /* If we don't have the function body available, we can't inline it.
1471      However, this should not be recorded since we also get here for
1472      forward declared inline functions.  Therefore, return at once.  */
1473   if (!DECL_SAVED_TREE (fn))
1474     return false;
1475
1476   /* If we're not inlining at all, then we cannot inline this function.  */
1477   else if (!flag_inline_trees)
1478     inlinable = false;
1479
1480   /* Only try to inline functions if DECL_INLINE is set.  This should be
1481      true for all functions declared `inline', and for all other functions
1482      as well with -finline-functions.
1483
1484      Don't think of disregarding DECL_INLINE when flag_inline_trees == 2;
1485      it's the front-end that must set DECL_INLINE in this case, because
1486      dwarf2out loses if a function that does not have DECL_INLINE set is
1487      inlined anyway.  That is why we have both DECL_INLINE and
1488      DECL_DECLARED_INLINE_P.  */
1489   /* FIXME: When flag_inline_trees dies, the check for flag_unit_at_a_time
1490             here should be redundant.  */
1491   else if (!DECL_INLINE (fn) && !flag_unit_at_a_time)
1492     inlinable = false;
1493
1494   else if (inline_forbidden_p (fn))
1495     {
1496       /* See if we should warn about uninlinable functions.  Previously,
1497          some of these warnings would be issued while trying to expand
1498          the function inline, but that would cause multiple warnings
1499          about functions that would for example call alloca.  But since
1500          this a property of the function, just one warning is enough.
1501          As a bonus we can now give more details about the reason why a
1502          function is not inlinable.
1503          We only warn for functions declared `inline' by the user.  */
1504       bool do_warning = (warn_inline
1505                          && DECL_INLINE (fn)
1506                          && DECL_DECLARED_INLINE_P (fn)
1507                          && !DECL_IN_SYSTEM_HEADER (fn));
1508
1509       if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (fn)))
1510         sorry (inline_forbidden_reason, fn);
1511       else if (do_warning)
1512         warning (OPT_Winline, inline_forbidden_reason, fn);
1513
1514       inlinable = false;
1515     }
1516
1517   /* Squirrel away the result so that we don't have to check again.  */
1518   DECL_UNINLINABLE (fn) = !inlinable;
1519
1520   return inlinable;
1521 }
1522
1523 /* Estimate the cost of a memory move.  Use machine dependent
1524    word size and take possible memcpy call into account.  */
1525
1526 int
1527 estimate_move_cost (tree type)
1528 {
1529   HOST_WIDE_INT size;
1530
1531   size = int_size_in_bytes (type);
1532
1533   if (size < 0 || size > MOVE_MAX_PIECES * MOVE_RATIO)
1534     /* Cost of a memcpy call, 3 arguments and the call.  */
1535     return 4;
1536   else
1537     return ((size + MOVE_MAX_PIECES - 1) / MOVE_MAX_PIECES);
1538 }
1539
1540 /* Used by estimate_num_insns.  Estimate number of instructions seen
1541    by given statement.  */
1542
1543 static tree
1544 estimate_num_insns_1 (tree *tp, int *walk_subtrees, void *data)
1545 {
1546   int *count = (int *) data;
1547   tree x = *tp;
1548
1549   if (IS_TYPE_OR_DECL_P (x))
1550     {
1551       *walk_subtrees = 0;
1552       return NULL;
1553     }
1554   /* Assume that constants and references counts nothing.  These should
1555      be majorized by amount of operations among them we count later
1556      and are common target of CSE and similar optimizations.  */
1557   else if (CONSTANT_CLASS_P (x) || REFERENCE_CLASS_P (x))
1558     return NULL;
1559
1560   switch (TREE_CODE (x))
1561     {
1562     /* Containers have no cost.  */
1563     case TREE_LIST:
1564     case TREE_VEC:
1565     case BLOCK:
1566     case COMPONENT_REF:
1567     case BIT_FIELD_REF:
1568     case INDIRECT_REF:
1569     case ALIGN_INDIRECT_REF:
1570     case MISALIGNED_INDIRECT_REF:
1571     case ARRAY_REF:
1572     case ARRAY_RANGE_REF:
1573     case OBJ_TYPE_REF:
1574     case EXC_PTR_EXPR: /* ??? */
1575     case FILTER_EXPR: /* ??? */
1576     case COMPOUND_EXPR:
1577     case BIND_EXPR:
1578     case WITH_CLEANUP_EXPR:
1579     case NOP_EXPR:
1580     case VIEW_CONVERT_EXPR:
1581     case SAVE_EXPR:
1582     case ADDR_EXPR:
1583     case COMPLEX_EXPR:
1584     case RANGE_EXPR:
1585     case CASE_LABEL_EXPR:
1586     case SSA_NAME:
1587     case CATCH_EXPR:
1588     case EH_FILTER_EXPR:
1589     case STATEMENT_LIST:
1590     case ERROR_MARK:
1591     case NON_LVALUE_EXPR:
1592     case FDESC_EXPR:
1593     case VA_ARG_EXPR:
1594     case TRY_CATCH_EXPR:
1595     case TRY_FINALLY_EXPR:
1596     case LABEL_EXPR:
1597     case GOTO_EXPR:
1598     case RETURN_EXPR:
1599     case EXIT_EXPR:
1600     case LOOP_EXPR:
1601     case PHI_NODE:
1602     case WITH_SIZE_EXPR:
1603     case OMP_CLAUSE:
1604     case OMP_RETURN_EXPR:
1605       break;
1606
1607     /* We don't account constants for now.  Assume that the cost is amortized
1608        by operations that do use them.  We may re-consider this decision once
1609        we are able to optimize the tree before estimating its size and break
1610        out static initializers.  */
1611     case IDENTIFIER_NODE:
1612     case INTEGER_CST:
1613     case REAL_CST:
1614     case COMPLEX_CST:
1615     case VECTOR_CST:
1616     case STRING_CST:
1617       *walk_subtrees = 0;
1618       return NULL;
1619
1620     /* Try to estimate the cost of assignments.  We have three cases to
1621        deal with:
1622         1) Simple assignments to registers;
1623         2) Stores to things that must live in memory.  This includes
1624            "normal" stores to scalars, but also assignments of large
1625            structures, or constructors of big arrays;
1626         3) TARGET_EXPRs.
1627
1628        Let us look at the first two cases, assuming we have "a = b + C":
1629        <modify_expr <var_decl "a"> <plus_expr <var_decl "b"> <constant C>>
1630        If "a" is a GIMPLE register, the assignment to it is free on almost
1631        any target, because "a" usually ends up in a real register.  Hence
1632        the only cost of this expression comes from the PLUS_EXPR, and we
1633        can ignore the MODIFY_EXPR.
1634        If "a" is not a GIMPLE register, the assignment to "a" will most
1635        likely be a real store, so the cost of the MODIFY_EXPR is the cost
1636        of moving something into "a", which we compute using the function
1637        estimate_move_cost.
1638
1639        The third case deals with TARGET_EXPRs, for which the semantics are
1640        that a temporary is assigned, unless the TARGET_EXPR itself is being
1641        assigned to something else.  In the latter case we do not need the
1642        temporary.  E.g. in <modify_expr <var_decl "a"> <target_expr>>, the
1643        MODIFY_EXPR is free.  */
1644     case INIT_EXPR:
1645     case MODIFY_EXPR:
1646       /* Is the right and side a TARGET_EXPR?  */
1647       if (TREE_CODE (TREE_OPERAND (x, 1)) == TARGET_EXPR)
1648         break;
1649       /* ... fall through ...  */
1650
1651     case TARGET_EXPR:
1652       x = TREE_OPERAND (x, 0);
1653       /* Is this an assignments to a register?  */
1654       if (is_gimple_reg (x))
1655         break;
1656       /* Otherwise it's a store, so fall through to compute the move cost.  */
1657
1658     case CONSTRUCTOR:
1659       *count += estimate_move_cost (TREE_TYPE (x));
1660       break;
1661
1662     /* Assign cost of 1 to usual operations.
1663        ??? We may consider mapping RTL costs to this.  */
1664     case COND_EXPR:
1665     case VEC_COND_EXPR:
1666
1667     case PLUS_EXPR:
1668     case MINUS_EXPR:
1669     case MULT_EXPR:
1670
1671     case FIX_TRUNC_EXPR:
1672     case FIX_CEIL_EXPR:
1673     case FIX_FLOOR_EXPR:
1674     case FIX_ROUND_EXPR:
1675
1676     case NEGATE_EXPR:
1677     case FLOAT_EXPR:
1678     case MIN_EXPR:
1679     case MAX_EXPR:
1680     case ABS_EXPR:
1681
1682     case LSHIFT_EXPR:
1683     case RSHIFT_EXPR:
1684     case LROTATE_EXPR:
1685     case RROTATE_EXPR:
1686     case VEC_LSHIFT_EXPR:
1687     case VEC_RSHIFT_EXPR:
1688
1689     case BIT_IOR_EXPR:
1690     case BIT_XOR_EXPR:
1691     case BIT_AND_EXPR:
1692     case BIT_NOT_EXPR:
1693
1694     case TRUTH_ANDIF_EXPR:
1695     case TRUTH_ORIF_EXPR:
1696     case TRUTH_AND_EXPR:
1697     case TRUTH_OR_EXPR:
1698     case TRUTH_XOR_EXPR:
1699     case TRUTH_NOT_EXPR:
1700
1701     case LT_EXPR:
1702     case LE_EXPR:
1703     case GT_EXPR:
1704     case GE_EXPR:
1705     case EQ_EXPR:
1706     case NE_EXPR:
1707     case ORDERED_EXPR:
1708     case UNORDERED_EXPR:
1709
1710     case UNLT_EXPR:
1711     case UNLE_EXPR:
1712     case UNGT_EXPR:
1713     case UNGE_EXPR:
1714     case UNEQ_EXPR:
1715     case LTGT_EXPR:
1716
1717     case CONVERT_EXPR:
1718
1719     case CONJ_EXPR:
1720
1721     case PREDECREMENT_EXPR:
1722     case PREINCREMENT_EXPR:
1723     case POSTDECREMENT_EXPR:
1724     case POSTINCREMENT_EXPR:
1725
1726     case SWITCH_EXPR:
1727
1728     case ASM_EXPR:
1729
1730     case REALIGN_LOAD_EXPR:
1731
1732     case REDUC_MAX_EXPR:
1733     case REDUC_MIN_EXPR:
1734     case REDUC_PLUS_EXPR:
1735     case WIDEN_SUM_EXPR:
1736     case DOT_PROD_EXPR: 
1737
1738     case WIDEN_MULT_EXPR:
1739
1740     case RESX_EXPR:
1741       *count += 1;
1742       break;
1743
1744     /* Few special cases of expensive operations.  This is useful
1745        to avoid inlining on functions having too many of these.  */
1746     case TRUNC_DIV_EXPR:
1747     case CEIL_DIV_EXPR:
1748     case FLOOR_DIV_EXPR:
1749     case ROUND_DIV_EXPR:
1750     case EXACT_DIV_EXPR:
1751     case TRUNC_MOD_EXPR:
1752     case CEIL_MOD_EXPR:
1753     case FLOOR_MOD_EXPR:
1754     case ROUND_MOD_EXPR:
1755     case RDIV_EXPR:
1756       *count += 10;
1757       break;
1758     case CALL_EXPR:
1759       {
1760         tree decl = get_callee_fndecl (x);
1761         tree arg;
1762
1763         if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
1764           switch (DECL_FUNCTION_CODE (decl))
1765             {
1766             case BUILT_IN_CONSTANT_P:
1767               *walk_subtrees = 0;
1768               return NULL_TREE;
1769             case BUILT_IN_EXPECT:
1770               return NULL_TREE;
1771             default:
1772               break;
1773             }
1774
1775         /* Our cost must be kept in sync with cgraph_estimate_size_after_inlining
1776            that does use function declaration to figure out the arguments.  */
1777         if (!decl)
1778           {
1779             for (arg = TREE_OPERAND (x, 1); arg; arg = TREE_CHAIN (arg))
1780               *count += estimate_move_cost (TREE_TYPE (TREE_VALUE (arg)));
1781           }
1782         else
1783           {
1784             for (arg = DECL_ARGUMENTS (decl); arg; arg = TREE_CHAIN (arg))
1785               *count += estimate_move_cost (TREE_TYPE (arg));
1786           }
1787
1788         *count += PARAM_VALUE (PARAM_INLINE_CALL_COST);
1789         break;
1790       }
1791
1792     case OMP_PARALLEL:
1793     case OMP_FOR:
1794     case OMP_SECTIONS:
1795     case OMP_SINGLE:
1796     case OMP_SECTION:
1797     case OMP_MASTER:
1798     case OMP_ORDERED:
1799     case OMP_CRITICAL:
1800     case OMP_ATOMIC:
1801       /* OpenMP directives are generally very expensive.  */
1802       *count += 40;
1803       break;
1804
1805     default:
1806       gcc_unreachable ();
1807     }
1808   return NULL;
1809 }
1810
1811 /* Estimate number of instructions that will be created by expanding EXPR.  */
1812
1813 int
1814 estimate_num_insns (tree expr)
1815 {
1816   int num = 0;
1817   struct pointer_set_t *visited_nodes;
1818   basic_block bb;
1819   block_stmt_iterator bsi;
1820   struct function *my_function;
1821
1822   /* If we're given an entire function, walk the CFG.  */
1823   if (TREE_CODE (expr) == FUNCTION_DECL)
1824     {
1825       my_function = DECL_STRUCT_FUNCTION (expr);
1826       gcc_assert (my_function && my_function->cfg);
1827       visited_nodes = pointer_set_create ();
1828       FOR_EACH_BB_FN (bb, my_function)
1829         {
1830           for (bsi = bsi_start (bb);
1831                !bsi_end_p (bsi);
1832                bsi_next (&bsi))
1833             {
1834               walk_tree (bsi_stmt_ptr (bsi), estimate_num_insns_1,
1835                          &num, visited_nodes);
1836             }
1837         }
1838       pointer_set_destroy (visited_nodes);
1839     }
1840   else
1841     walk_tree_without_duplicates (&expr, estimate_num_insns_1, &num);
1842
1843   return num;
1844 }
1845
1846 typedef struct function *function_p;
1847
1848 DEF_VEC_P(function_p);
1849 DEF_VEC_ALLOC_P(function_p,heap);
1850
1851 /* Initialized with NOGC, making this poisonous to the garbage collector.  */
1852 static VEC(function_p,heap) *cfun_stack;
1853
1854 void
1855 push_cfun (struct function *new_cfun)
1856 {
1857   VEC_safe_push (function_p, heap, cfun_stack, cfun);
1858   cfun = new_cfun;
1859 }
1860
1861 void
1862 pop_cfun (void)
1863 {
1864   cfun = VEC_pop (function_p, cfun_stack);
1865 }
1866
1867 /* Install new lexical TREE_BLOCK underneath 'current_block'.  */
1868 static void
1869 add_lexical_block (tree current_block, tree new_block)
1870 {
1871   tree *blk_p;
1872
1873   /* Walk to the last sub-block.  */
1874   for (blk_p = &BLOCK_SUBBLOCKS (current_block);
1875        *blk_p;
1876        blk_p = &TREE_CHAIN (*blk_p))
1877     ;
1878   *blk_p = new_block;
1879   BLOCK_SUPERCONTEXT (new_block) = current_block;
1880 }
1881
1882 /* If *TP is a CALL_EXPR, replace it with its inline expansion.  */
1883
1884 static bool
1885 expand_call_inline (basic_block bb, tree stmt, tree *tp, void *data)
1886 {
1887   copy_body_data *id;
1888   tree t;
1889   tree use_retvar;
1890   tree fn;
1891   splay_tree st;
1892   tree args;
1893   tree return_slot_addr;
1894   tree modify_dest;
1895   location_t saved_location;
1896   struct cgraph_edge *cg_edge;
1897   const char *reason;
1898   basic_block return_block;
1899   edge e;
1900   block_stmt_iterator bsi, stmt_bsi;
1901   bool successfully_inlined = FALSE;
1902   tree t_step;
1903   tree var;
1904   tree decl;
1905
1906   /* See what we've got.  */
1907   id = (copy_body_data *) data;
1908   t = *tp;
1909
1910   /* Set input_location here so we get the right instantiation context
1911      if we call instantiate_decl from inlinable_function_p.  */
1912   saved_location = input_location;
1913   if (EXPR_HAS_LOCATION (t))
1914     input_location = EXPR_LOCATION (t);
1915
1916   /* From here on, we're only interested in CALL_EXPRs.  */
1917   if (TREE_CODE (t) != CALL_EXPR)
1918     goto egress;
1919
1920   /* First, see if we can figure out what function is being called.
1921      If we cannot, then there is no hope of inlining the function.  */
1922   fn = get_callee_fndecl (t);
1923   if (!fn)
1924     goto egress;
1925
1926   /* Turn forward declarations into real ones.  */
1927   fn = cgraph_node (fn)->decl;
1928
1929   /* If fn is a declaration of a function in a nested scope that was
1930      globally declared inline, we don't set its DECL_INITIAL.
1931      However, we can't blindly follow DECL_ABSTRACT_ORIGIN because the
1932      C++ front-end uses it for cdtors to refer to their internal
1933      declarations, that are not real functions.  Fortunately those
1934      don't have trees to be saved, so we can tell by checking their
1935      DECL_SAVED_TREE.  */
1936   if (! DECL_INITIAL (fn)
1937       && DECL_ABSTRACT_ORIGIN (fn)
1938       && DECL_SAVED_TREE (DECL_ABSTRACT_ORIGIN (fn)))
1939     fn = DECL_ABSTRACT_ORIGIN (fn);
1940
1941   /* Objective C and fortran still calls tree_rest_of_compilation directly.
1942      Kill this check once this is fixed.  */
1943   if (!id->dst_node->analyzed)
1944     goto egress;
1945
1946   cg_edge = cgraph_edge (id->dst_node, stmt);
1947
1948   /* Constant propagation on argument done during previous inlining
1949      may create new direct call.  Produce an edge for it.  */
1950   if (!cg_edge)
1951     {
1952       struct cgraph_node *dest = cgraph_node (fn);
1953
1954       /* We have missing edge in the callgraph.  This can happen in one case
1955          where previous inlining turned indirect call into direct call by
1956          constant propagating arguments.  In all other cases we hit a bug
1957          (incorrect node sharing is most common reason for missing edges.  */
1958       gcc_assert (dest->needed || !flag_unit_at_a_time);
1959       cgraph_create_edge (id->dst_node, dest, stmt,
1960                           bb->count, bb->loop_depth)->inline_failed
1961         = N_("originally indirect function call not considered for inlining");
1962       goto egress;
1963     }
1964
1965   /* Don't try to inline functions that are not well-suited to
1966      inlining.  */
1967   if (!cgraph_inline_p (cg_edge, &reason))
1968     {
1969       if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (fn))
1970           /* Avoid warnings during early inline pass. */
1971           && (!flag_unit_at_a_time || cgraph_global_info_ready))
1972         {
1973           sorry ("inlining failed in call to %q+F: %s", fn, reason);
1974           sorry ("called from here");
1975         }
1976       else if (warn_inline && DECL_DECLARED_INLINE_P (fn)
1977                && !DECL_IN_SYSTEM_HEADER (fn)
1978                && strlen (reason)
1979                && !lookup_attribute ("noinline", DECL_ATTRIBUTES (fn))
1980                /* Avoid warnings during early inline pass. */
1981                && (!flag_unit_at_a_time || cgraph_global_info_ready))
1982         {
1983           warning (OPT_Winline, "inlining failed in call to %q+F: %s",
1984                    fn, reason);
1985           warning (OPT_Winline, "called from here");
1986         }
1987       goto egress;
1988     }
1989   fn = cg_edge->callee->decl;
1990
1991 #ifdef ENABLE_CHECKING
1992   if (cg_edge->callee->decl != id->dst_node->decl)
1993     verify_cgraph_node (cg_edge->callee);
1994 #endif
1995
1996   /* We will be inlining this callee.  */
1997
1998   id->eh_region = lookup_stmt_eh_region (stmt);
1999
2000   /* Split the block holding the CALL_EXPR.  */
2001
2002   e = split_block (bb, stmt);
2003   bb = e->src;
2004   return_block = e->dest;
2005   remove_edge (e);
2006
2007   /* split_block splits before the statement, work around this by moving
2008      the call into the first half_bb.  Not pretty, but seems easier than
2009      doing the CFG manipulation by hand when the CALL_EXPR is in the last
2010      statement in BB.  */
2011   stmt_bsi = bsi_last (bb);
2012   bsi = bsi_start (return_block);
2013   if (!bsi_end_p (bsi))
2014     bsi_move_before (&stmt_bsi, &bsi);
2015   else
2016     {
2017       tree stmt = bsi_stmt (stmt_bsi);
2018       bsi_remove (&stmt_bsi, false);
2019       bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
2020     }
2021   stmt_bsi = bsi_start (return_block);
2022
2023   /* Build a block containing code to initialize the arguments, the
2024      actual inline expansion of the body, and a label for the return
2025      statements within the function to jump to.  The type of the
2026      statement expression is the return type of the function call.  */
2027   id->block = make_node (BLOCK);
2028   BLOCK_ABSTRACT_ORIGIN (id->block) = fn;
2029   BLOCK_SOURCE_LOCATION (id->block) = input_location;
2030   add_lexical_block (TREE_BLOCK (stmt), id->block);
2031
2032   /* Local declarations will be replaced by their equivalents in this
2033      map.  */
2034   st = id->decl_map;
2035   id->decl_map = splay_tree_new (splay_tree_compare_pointers,
2036                                  NULL, NULL);
2037
2038   /* Initialize the parameters.  */
2039   args = TREE_OPERAND (t, 1);
2040
2041   /* Record the function we are about to inline.  */
2042   id->src_fn = fn;
2043   id->src_node = cg_edge->callee;
2044
2045   initialize_inlined_parameters (id, args, TREE_OPERAND (t, 2), fn, bb);
2046
2047   if (DECL_INITIAL (fn))
2048     add_lexical_block (id->block, remap_blocks (DECL_INITIAL (fn), id));
2049
2050   /* Return statements in the function body will be replaced by jumps
2051      to the RET_LABEL.  */
2052
2053   gcc_assert (DECL_INITIAL (fn));
2054   gcc_assert (TREE_CODE (DECL_INITIAL (fn)) == BLOCK);
2055
2056   /* Find the lhs to which the result of this call is assigned.  */
2057   return_slot_addr = NULL;
2058   if (TREE_CODE (stmt) == MODIFY_EXPR)
2059     {
2060       modify_dest = TREE_OPERAND (stmt, 0);
2061
2062       /* The function which we are inlining might not return a value,
2063          in which case we should issue a warning that the function
2064          does not return a value.  In that case the optimizers will
2065          see that the variable to which the value is assigned was not
2066          initialized.  We do not want to issue a warning about that
2067          uninitialized variable.  */
2068       if (DECL_P (modify_dest))
2069         TREE_NO_WARNING (modify_dest) = 1;
2070       if (CALL_EXPR_RETURN_SLOT_OPT (t))
2071         {
2072           return_slot_addr = build_fold_addr_expr (modify_dest);
2073           modify_dest = NULL;
2074         }
2075     }
2076   else
2077     modify_dest = NULL;
2078
2079   /* Declare the return variable for the function.  */
2080   decl = declare_return_variable (id, return_slot_addr,
2081                                   modify_dest, &use_retvar);
2082   /* Do this only if declare_return_variable created a new one.  */
2083   if (decl && !return_slot_addr && decl != modify_dest)
2084     declare_inline_vars (id->block, decl);
2085
2086   /* This is it.  Duplicate the callee body.  Assume callee is
2087      pre-gimplified.  Note that we must not alter the caller
2088      function in any way before this point, as this CALL_EXPR may be
2089      a self-referential call; if we're calling ourselves, we need to
2090      duplicate our body before altering anything.  */
2091   copy_body (id, bb->count, bb->frequency, bb, return_block);
2092
2093   /* Add local vars in this inlined callee to caller.  */
2094   t_step = id->src_cfun->unexpanded_var_list;
2095   for (; t_step; t_step = TREE_CHAIN (t_step))
2096     {
2097       var = TREE_VALUE (t_step);
2098       if (TREE_STATIC (var) && !TREE_ASM_WRITTEN (var))
2099         cfun->unexpanded_var_list = tree_cons (NULL_TREE, var,
2100                                                cfun->unexpanded_var_list);
2101       else
2102         cfun->unexpanded_var_list = tree_cons (NULL_TREE, remap_decl (var, id),
2103                                                cfun->unexpanded_var_list);
2104     }
2105
2106   /* Clean up.  */
2107   splay_tree_delete (id->decl_map);
2108   id->decl_map = st;
2109
2110   /* If the inlined function returns a result that we care about,
2111      clobber the CALL_EXPR with a reference to the return variable.  */
2112   if (use_retvar && (TREE_CODE (bsi_stmt (stmt_bsi)) != CALL_EXPR))
2113     {
2114       *tp = use_retvar;
2115       maybe_clean_or_replace_eh_stmt (stmt, stmt);
2116     }
2117   else
2118     /* We're modifying a TSI owned by gimple_expand_calls_inline();
2119        tsi_delink() will leave the iterator in a sane state.  */
2120     bsi_remove (&stmt_bsi, true);
2121
2122   bsi_next (&bsi);
2123   if (bsi_end_p (bsi))
2124     tree_purge_dead_eh_edges (return_block);
2125
2126   /* If the value of the new expression is ignored, that's OK.  We
2127      don't warn about this for CALL_EXPRs, so we shouldn't warn about
2128      the equivalent inlined version either.  */
2129   TREE_USED (*tp) = 1;
2130
2131   /* Output the inlining info for this abstract function, since it has been
2132      inlined.  If we don't do this now, we can lose the information about the
2133      variables in the function when the blocks get blown away as soon as we
2134      remove the cgraph node.  */
2135   (*debug_hooks->outlining_inline_function) (cg_edge->callee->decl);
2136
2137   /* Update callgraph if needed.  */
2138   cgraph_remove_node (cg_edge->callee);
2139
2140   /* Declare the 'auto' variables added with this inlined body.  */
2141   record_vars (BLOCK_VARS (id->block));
2142   id->block = NULL_TREE;
2143   successfully_inlined = TRUE;
2144
2145  egress:
2146   input_location = saved_location;
2147   return successfully_inlined;
2148 }
2149
2150 /* Expand call statements reachable from STMT_P.
2151    We can only have CALL_EXPRs as the "toplevel" tree code or nested
2152    in a MODIFY_EXPR.  See tree-gimple.c:get_call_expr_in().  We can
2153    unfortunately not use that function here because we need a pointer
2154    to the CALL_EXPR, not the tree itself.  */
2155
2156 static bool
2157 gimple_expand_calls_inline (basic_block bb, copy_body_data *id)
2158 {
2159   block_stmt_iterator bsi;
2160
2161   /* Register specific tree functions.  */
2162   tree_register_cfg_hooks ();
2163   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
2164     {
2165       tree *expr_p = bsi_stmt_ptr (bsi);
2166       tree stmt = *expr_p;
2167
2168       if (TREE_CODE (*expr_p) == MODIFY_EXPR)
2169         expr_p = &TREE_OPERAND (*expr_p, 1);
2170       if (TREE_CODE (*expr_p) == WITH_SIZE_EXPR)
2171         expr_p = &TREE_OPERAND (*expr_p, 0);
2172       if (TREE_CODE (*expr_p) == CALL_EXPR)
2173         if (expand_call_inline (bb, stmt, expr_p, id))
2174           return true;
2175     }
2176   return false;
2177 }
2178
2179 /* Expand calls to inline functions in the body of FN.  */
2180
2181 void
2182 optimize_inline_calls (tree fn)
2183 {
2184   copy_body_data id;
2185   tree prev_fn;
2186   basic_block bb;
2187   /* There is no point in performing inlining if errors have already
2188      occurred -- and we might crash if we try to inline invalid
2189      code.  */
2190   if (errorcount || sorrycount)
2191     return;
2192
2193   /* Clear out ID.  */
2194   memset (&id, 0, sizeof (id));
2195
2196   id.src_node = id.dst_node = cgraph_node (fn);
2197   id.dst_fn = fn;
2198   /* Or any functions that aren't finished yet.  */
2199   prev_fn = NULL_TREE;
2200   if (current_function_decl)
2201     {
2202       id.dst_fn = current_function_decl;
2203       prev_fn = current_function_decl;
2204     }
2205
2206   id.copy_decl = copy_decl_maybe_to_var;
2207   id.transform_call_graph_edges = CB_CGE_DUPLICATE;
2208   id.transform_new_cfg = false;
2209   id.transform_return_to_modify = true;
2210   id.transform_lang_insert_block = false;
2211
2212   push_gimplify_context ();
2213
2214   /* Reach the trees by walking over the CFG, and note the
2215      enclosing basic-blocks in the call edges.  */
2216   /* We walk the blocks going forward, because inlined function bodies
2217      will split id->current_basic_block, and the new blocks will
2218      follow it; we'll trudge through them, processing their CALL_EXPRs
2219      along the way.  */
2220   FOR_EACH_BB (bb)
2221     gimple_expand_calls_inline (bb, &id);
2222
2223   pop_gimplify_context (NULL);
2224   /* Renumber the (code) basic_blocks consecutively.  */
2225   compact_blocks ();
2226   /* Renumber the lexical scoping (non-code) blocks consecutively.  */
2227   number_blocks (fn);
2228
2229 #ifdef ENABLE_CHECKING
2230     {
2231       struct cgraph_edge *e;
2232
2233       verify_cgraph_node (id.dst_node);
2234
2235       /* Double check that we inlined everything we are supposed to inline.  */
2236       for (e = id.dst_node->callees; e; e = e->next_callee)
2237         gcc_assert (e->inline_failed);
2238     }
2239 #endif
2240   /* We need to rescale frequencies again to peak at REG_BR_PROB_BASE
2241      as inlining loops might increase the maximum.  */
2242   if (ENTRY_BLOCK_PTR->count)
2243     counts_to_freqs ();
2244   fold_cond_expr_cond ();
2245 }
2246
2247 /* FN is a function that has a complete body, and CLONE is a function whose
2248    body is to be set to a copy of FN, mapping argument declarations according
2249    to the ARG_MAP splay_tree.  */
2250
2251 void
2252 clone_body (tree clone, tree fn, void *arg_map)
2253 {
2254   copy_body_data id;
2255
2256   /* Clone the body, as if we were making an inline call.  But, remap the
2257      parameters in the callee to the parameters of caller.  */
2258   memset (&id, 0, sizeof (id));
2259   id.src_fn = fn;
2260   id.dst_fn = clone;
2261   id.src_cfun = DECL_STRUCT_FUNCTION (fn);
2262   id.decl_map = (splay_tree)arg_map;
2263
2264   id.copy_decl = copy_decl_no_change;
2265   id.transform_call_graph_edges = CB_CGE_DUPLICATE;
2266   id.transform_new_cfg = true;
2267   id.transform_return_to_modify = false;
2268   id.transform_lang_insert_block = true;
2269
2270   /* We're not inside any EH region.  */
2271   id.eh_region = -1;
2272
2273   /* Actually copy the body.  */
2274   append_to_statement_list_force (copy_generic_body (&id), &DECL_SAVED_TREE (clone));
2275 }
2276
2277 /* Passed to walk_tree.  Copies the node pointed to, if appropriate.  */
2278
2279 tree
2280 copy_tree_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
2281 {
2282   enum tree_code code = TREE_CODE (*tp);
2283
2284   /* We make copies of most nodes.  */
2285   if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code))
2286       || code == TREE_LIST
2287       || code == TREE_VEC
2288       || code == TYPE_DECL
2289       || code == OMP_CLAUSE)
2290     {
2291       /* Because the chain gets clobbered when we make a copy, we save it
2292          here.  */
2293       tree chain = TREE_CHAIN (*tp);
2294       tree new;
2295
2296       /* Copy the node.  */
2297       new = copy_node (*tp);
2298
2299       /* Propagate mudflap marked-ness.  */
2300       if (flag_mudflap && mf_marked_p (*tp))
2301         mf_mark (new);
2302
2303       *tp = new;
2304
2305       /* Now, restore the chain, if appropriate.  That will cause
2306          walk_tree to walk into the chain as well.  */
2307       if (code == PARM_DECL
2308           || code == TREE_LIST
2309           || code == OMP_CLAUSE)
2310         TREE_CHAIN (*tp) = chain;
2311
2312       /* For now, we don't update BLOCKs when we make copies.  So, we
2313          have to nullify all BIND_EXPRs.  */
2314       if (TREE_CODE (*tp) == BIND_EXPR)
2315         BIND_EXPR_BLOCK (*tp) = NULL_TREE;
2316     }
2317   else if (code == CONSTRUCTOR)
2318     {
2319       /* CONSTRUCTOR nodes need special handling because
2320          we need to duplicate the vector of elements.  */
2321       tree new;
2322
2323       new = copy_node (*tp);
2324
2325       /* Propagate mudflap marked-ness.  */
2326       if (flag_mudflap && mf_marked_p (*tp))
2327         mf_mark (new);
2328
2329       CONSTRUCTOR_ELTS (new) = VEC_copy (constructor_elt, gc,
2330                                          CONSTRUCTOR_ELTS (*tp));
2331       *tp = new;
2332     }
2333   else if (TREE_CODE_CLASS (code) == tcc_type)
2334     *walk_subtrees = 0;
2335   else if (TREE_CODE_CLASS (code) == tcc_declaration)
2336     *walk_subtrees = 0;
2337   else if (TREE_CODE_CLASS (code) == tcc_constant)
2338     *walk_subtrees = 0;
2339   else
2340     gcc_assert (code != STATEMENT_LIST);
2341   return NULL_TREE;
2342 }
2343
2344 /* The SAVE_EXPR pointed to by TP is being copied.  If ST contains
2345    information indicating to what new SAVE_EXPR this one should be mapped,
2346    use that one.  Otherwise, create a new node and enter it in ST.  FN is
2347    the function into which the copy will be placed.  */
2348
2349 static void
2350 remap_save_expr (tree *tp, void *st_, int *walk_subtrees)
2351 {
2352   splay_tree st = (splay_tree) st_;
2353   splay_tree_node n;
2354   tree t;
2355
2356   /* See if we already encountered this SAVE_EXPR.  */
2357   n = splay_tree_lookup (st, (splay_tree_key) *tp);
2358
2359   /* If we didn't already remap this SAVE_EXPR, do so now.  */
2360   if (!n)
2361     {
2362       t = copy_node (*tp);
2363
2364       /* Remember this SAVE_EXPR.  */
2365       splay_tree_insert (st, (splay_tree_key) *tp, (splay_tree_value) t);
2366       /* Make sure we don't remap an already-remapped SAVE_EXPR.  */
2367       splay_tree_insert (st, (splay_tree_key) t, (splay_tree_value) t);
2368     }
2369   else
2370     {
2371       /* We've already walked into this SAVE_EXPR; don't do it again.  */
2372       *walk_subtrees = 0;
2373       t = (tree) n->value;
2374     }
2375
2376   /* Replace this SAVE_EXPR with the copy.  */
2377   *tp = t;
2378 }
2379
2380 /* Called via walk_tree.  If *TP points to a DECL_STMT for a local label,
2381    copies the declaration and enters it in the splay_tree in DATA (which is
2382    really an `copy_body_data *').  */
2383
2384 static tree
2385 mark_local_for_remap_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
2386                         void *data)
2387 {
2388   copy_body_data *id = (copy_body_data *) data;
2389
2390   /* Don't walk into types.  */
2391   if (TYPE_P (*tp))
2392     *walk_subtrees = 0;
2393
2394   else if (TREE_CODE (*tp) == LABEL_EXPR)
2395     {
2396       tree decl = TREE_OPERAND (*tp, 0);
2397
2398       /* Copy the decl and remember the copy.  */
2399       insert_decl_map (id, decl, id->copy_decl (decl, id));
2400     }
2401
2402   return NULL_TREE;
2403 }
2404
2405 /* Perform any modifications to EXPR required when it is unsaved.  Does
2406    not recurse into EXPR's subtrees.  */
2407
2408 static void
2409 unsave_expr_1 (tree expr)
2410 {
2411   switch (TREE_CODE (expr))
2412     {
2413     case TARGET_EXPR:
2414       /* Don't mess with a TARGET_EXPR that hasn't been expanded.
2415          It's OK for this to happen if it was part of a subtree that
2416          isn't immediately expanded, such as operand 2 of another
2417          TARGET_EXPR.  */
2418       if (TREE_OPERAND (expr, 1))
2419         break;
2420
2421       TREE_OPERAND (expr, 1) = TREE_OPERAND (expr, 3);
2422       TREE_OPERAND (expr, 3) = NULL_TREE;
2423       break;
2424
2425     default:
2426       break;
2427     }
2428 }
2429
2430 /* Called via walk_tree when an expression is unsaved.  Using the
2431    splay_tree pointed to by ST (which is really a `splay_tree'),
2432    remaps all local declarations to appropriate replacements.  */
2433
2434 static tree
2435 unsave_r (tree *tp, int *walk_subtrees, void *data)
2436 {
2437   copy_body_data *id = (copy_body_data *) data;
2438   splay_tree st = id->decl_map;
2439   splay_tree_node n;
2440
2441   /* Only a local declaration (variable or label).  */
2442   if ((TREE_CODE (*tp) == VAR_DECL && !TREE_STATIC (*tp))
2443       || TREE_CODE (*tp) == LABEL_DECL)
2444     {
2445       /* Lookup the declaration.  */
2446       n = splay_tree_lookup (st, (splay_tree_key) *tp);
2447
2448       /* If it's there, remap it.  */
2449       if (n)
2450         *tp = (tree) n->value;
2451     }
2452
2453   else if (TREE_CODE (*tp) == STATEMENT_LIST)
2454     copy_statement_list (tp);
2455   else if (TREE_CODE (*tp) == BIND_EXPR)
2456     copy_bind_expr (tp, walk_subtrees, id);
2457   else if (TREE_CODE (*tp) == SAVE_EXPR)
2458     remap_save_expr (tp, st, walk_subtrees);
2459   else
2460     {
2461       copy_tree_r (tp, walk_subtrees, NULL);
2462
2463       /* Do whatever unsaving is required.  */
2464       unsave_expr_1 (*tp);
2465     }
2466
2467   /* Keep iterating.  */
2468   return NULL_TREE;
2469 }
2470
2471 /* Copies everything in EXPR and replaces variables, labels
2472    and SAVE_EXPRs local to EXPR.  */
2473
2474 tree
2475 unsave_expr_now (tree expr)
2476 {
2477   copy_body_data id;
2478
2479   /* There's nothing to do for NULL_TREE.  */
2480   if (expr == 0)
2481     return expr;
2482
2483   /* Set up ID.  */
2484   memset (&id, 0, sizeof (id));
2485   id.src_fn = current_function_decl;
2486   id.dst_fn = current_function_decl;
2487   id.decl_map = splay_tree_new (splay_tree_compare_pointers, NULL, NULL);
2488
2489   id.copy_decl = copy_decl_no_change;
2490   id.transform_call_graph_edges = CB_CGE_DUPLICATE;
2491   id.transform_new_cfg = false;
2492   id.transform_return_to_modify = false;
2493   id.transform_lang_insert_block = false;
2494
2495   /* Walk the tree once to find local labels.  */
2496   walk_tree_without_duplicates (&expr, mark_local_for_remap_r, &id);
2497
2498   /* Walk the tree again, copying, remapping, and unsaving.  */
2499   walk_tree (&expr, unsave_r, &id, NULL);
2500
2501   /* Clean up.  */
2502   splay_tree_delete (id.decl_map);
2503
2504   return expr;
2505 }
2506
2507 /* Allow someone to determine if SEARCH is a child of TOP from gdb.  */
2508
2509 static tree
2510 debug_find_tree_1 (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data)
2511 {
2512   if (*tp == data)
2513     return (tree) data;
2514   else
2515     return NULL;
2516 }
2517
2518 bool
2519 debug_find_tree (tree top, tree search)
2520 {
2521   return walk_tree_without_duplicates (&top, debug_find_tree_1, search) != 0;
2522 }
2523
2524
2525 /* Declare the variables created by the inliner.  Add all the variables in
2526    VARS to BIND_EXPR.  */
2527
2528 static void
2529 declare_inline_vars (tree block, tree vars)
2530 {
2531   tree t;
2532   for (t = vars; t; t = TREE_CHAIN (t))
2533     DECL_SEEN_IN_BIND_EXPR_P (t) = 1;
2534
2535   if (block)
2536     BLOCK_VARS (block) = chainon (BLOCK_VARS (block), vars);
2537 }
2538
2539
2540 /* Copy NODE (which must be a DECL).  The DECL originally was in the FROM_FN,
2541    but now it will be in the TO_FN.  PARM_TO_VAR means enable PARM_DECL to
2542    VAR_DECL translation.  */
2543
2544 static tree
2545 copy_decl_for_dup_finish (copy_body_data *id, tree decl, tree copy)
2546 {
2547   /* Don't generate debug information for the copy if we wouldn't have
2548      generated it for the copy either.  */
2549   DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (decl);
2550   DECL_IGNORED_P (copy) = DECL_IGNORED_P (decl);
2551
2552   /* Set the DECL_ABSTRACT_ORIGIN so the debugging routines know what
2553      declaration inspired this copy.  */ 
2554   DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (decl);
2555
2556   /* The new variable/label has no RTL, yet.  */
2557   if (CODE_CONTAINS_STRUCT (TREE_CODE (copy), TS_DECL_WRTL)
2558       && !TREE_STATIC (copy) && !DECL_EXTERNAL (copy))
2559     SET_DECL_RTL (copy, NULL_RTX);
2560   
2561   /* These args would always appear unused, if not for this.  */
2562   TREE_USED (copy) = 1;
2563
2564   /* Set the context for the new declaration.  */
2565   if (!DECL_CONTEXT (decl))
2566     /* Globals stay global.  */
2567     ;
2568   else if (DECL_CONTEXT (decl) != id->src_fn)
2569     /* Things that weren't in the scope of the function we're inlining
2570        from aren't in the scope we're inlining to, either.  */
2571     ;
2572   else if (TREE_STATIC (decl))
2573     /* Function-scoped static variables should stay in the original
2574        function.  */
2575     ;
2576   else
2577     /* Ordinary automatic local variables are now in the scope of the
2578        new function.  */
2579     DECL_CONTEXT (copy) = id->dst_fn;
2580
2581   return copy;
2582 }
2583
2584 static tree
2585 copy_decl_to_var (tree decl, copy_body_data *id)
2586 {
2587   tree copy, type;
2588
2589   gcc_assert (TREE_CODE (decl) == PARM_DECL
2590               || TREE_CODE (decl) == RESULT_DECL);
2591
2592   type = TREE_TYPE (decl);
2593
2594   copy = build_decl (VAR_DECL, DECL_NAME (decl), type);
2595   TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (decl);
2596   TREE_READONLY (copy) = TREE_READONLY (decl);
2597   TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (decl);
2598   DECL_COMPLEX_GIMPLE_REG_P (copy) = DECL_COMPLEX_GIMPLE_REG_P (decl);
2599
2600   return copy_decl_for_dup_finish (id, decl, copy);
2601 }
2602
2603 static tree
2604 copy_decl_no_change (tree decl, copy_body_data *id)
2605 {
2606   tree copy;
2607
2608   copy = copy_node (decl);
2609
2610   /* The COPY is not abstract; it will be generated in DST_FN.  */
2611   DECL_ABSTRACT (copy) = 0;
2612   lang_hooks.dup_lang_specific_decl (copy);
2613
2614   /* TREE_ADDRESSABLE isn't used to indicate that a label's address has
2615      been taken; it's for internal bookkeeping in expand_goto_internal.  */
2616   if (TREE_CODE (copy) == LABEL_DECL)
2617     {
2618       TREE_ADDRESSABLE (copy) = 0;
2619       LABEL_DECL_UID (copy) = -1;
2620     }
2621
2622   return copy_decl_for_dup_finish (id, decl, copy);
2623 }
2624
2625 static tree
2626 copy_decl_maybe_to_var (tree decl, copy_body_data *id)
2627 {
2628   if (TREE_CODE (decl) == PARM_DECL || TREE_CODE (decl) == RESULT_DECL)
2629     return copy_decl_to_var (decl, id);
2630   else
2631     return copy_decl_no_change (decl, id);
2632 }
2633
2634 /* Return a copy of the function's argument tree.  */
2635 static tree
2636 copy_arguments_for_versioning (tree orig_parm, copy_body_data * id)
2637 {
2638   tree *arg_copy, *parg;
2639
2640   arg_copy = &orig_parm;
2641   for (parg = arg_copy; *parg; parg = &TREE_CHAIN (*parg))
2642     {
2643       tree new = remap_decl (*parg, id);
2644       lang_hooks.dup_lang_specific_decl (new);
2645       TREE_CHAIN (new) = TREE_CHAIN (*parg);
2646       *parg = new;
2647     }
2648   return orig_parm;
2649 }
2650
2651 /* Return a copy of the function's static chain.  */
2652 static tree
2653 copy_static_chain (tree static_chain, copy_body_data * id)
2654 {
2655   tree *chain_copy, *pvar;
2656
2657   chain_copy = &static_chain;
2658   for (pvar = chain_copy; *pvar; pvar = &TREE_CHAIN (*pvar))
2659     {
2660       tree new = remap_decl (*pvar, id);
2661       lang_hooks.dup_lang_specific_decl (new);
2662       TREE_CHAIN (new) = TREE_CHAIN (*pvar);
2663       *pvar = new;
2664     }
2665   return static_chain;
2666 }
2667
2668 /* Return true if the function is allowed to be versioned.
2669    This is a guard for the versioning functionality.  */
2670 bool
2671 tree_versionable_function_p (tree fndecl)
2672 {
2673   if (fndecl == NULL_TREE)
2674     return false;
2675   /* ??? There are cases where a function is
2676      uninlinable but can be versioned.  */
2677   if (!tree_inlinable_function_p (fndecl))
2678     return false;
2679   
2680   return true;
2681 }
2682
2683 /* Create a copy of a function's tree.
2684    OLD_DECL and NEW_DECL are FUNCTION_DECL tree nodes
2685    of the original function and the new copied function
2686    respectively.  In case we want to replace a DECL 
2687    tree with another tree while duplicating the function's 
2688    body, TREE_MAP represents the mapping between these 
2689    trees. If UPDATE_CLONES is set, the call_stmt fields
2690    of edges of clones of the function will be updated.  */
2691 void
2692 tree_function_versioning (tree old_decl, tree new_decl, varray_type tree_map,
2693                           bool update_clones)
2694 {
2695   struct cgraph_node *old_version_node;
2696   struct cgraph_node *new_version_node;
2697   copy_body_data id;
2698   tree p, new_fndecl;
2699   unsigned i;
2700   struct ipa_replace_map *replace_info;
2701   basic_block old_entry_block;
2702   tree t_step;
2703
2704   gcc_assert (TREE_CODE (old_decl) == FUNCTION_DECL
2705               && TREE_CODE (new_decl) == FUNCTION_DECL);
2706   DECL_POSSIBLY_INLINED (old_decl) = 1;
2707
2708   old_version_node = cgraph_node (old_decl);
2709   new_version_node = cgraph_node (new_decl);
2710
2711   allocate_struct_function (new_decl);
2712   /* Cfun points to the new allocated function struct at this point.  */
2713   cfun->function_end_locus = DECL_SOURCE_LOCATION (new_decl);
2714
2715   DECL_ARTIFICIAL (new_decl) = 1;
2716   DECL_ABSTRACT_ORIGIN (new_decl) = DECL_ORIGIN (old_decl);
2717
2718   /* Generate a new name for the new version. */
2719   if (!update_clones)
2720     DECL_NAME (new_decl) = create_tmp_var_name (NULL);
2721   /* Create a new SYMBOL_REF rtx for the new name. */
2722   if (DECL_RTL (old_decl) != NULL)
2723     {
2724       SET_DECL_RTL (new_decl, copy_rtx (DECL_RTL (old_decl)));
2725       XEXP (DECL_RTL (new_decl), 0) =
2726         gen_rtx_SYMBOL_REF (GET_MODE (XEXP (DECL_RTL (old_decl), 0)),
2727                             IDENTIFIER_POINTER (DECL_NAME (new_decl)));
2728     }
2729
2730   /* Prepare the data structures for the tree copy.  */
2731   memset (&id, 0, sizeof (id));
2732   
2733   id.decl_map = splay_tree_new (splay_tree_compare_pointers, NULL, NULL);
2734   id.src_fn = old_decl;
2735   id.dst_fn = new_decl;
2736   id.src_node = old_version_node;
2737   id.dst_node = new_version_node;
2738   id.src_cfun = DECL_STRUCT_FUNCTION (old_decl);
2739   
2740   id.copy_decl = copy_decl_no_change;
2741   id.transform_call_graph_edges
2742     = update_clones ? CB_CGE_MOVE_CLONES : CB_CGE_MOVE;
2743   id.transform_new_cfg = true;
2744   id.transform_return_to_modify = false;
2745   id.transform_lang_insert_block = false;
2746
2747   current_function_decl = new_decl;
2748   
2749   /* Copy the function's static chain.  */
2750   p = DECL_STRUCT_FUNCTION (old_decl)->static_chain_decl;
2751   if (p)
2752     DECL_STRUCT_FUNCTION (new_decl)->static_chain_decl =
2753       copy_static_chain (DECL_STRUCT_FUNCTION (old_decl)->static_chain_decl,
2754                          &id);
2755   /* Copy the function's arguments.  */
2756   if (DECL_ARGUMENTS (old_decl) != NULL_TREE)
2757     DECL_ARGUMENTS (new_decl) =
2758       copy_arguments_for_versioning (DECL_ARGUMENTS (old_decl), &id);
2759   
2760   /* If there's a tree_map, prepare for substitution.  */
2761   if (tree_map)
2762     for (i = 0; i < VARRAY_ACTIVE_SIZE (tree_map); i++)
2763       {
2764         replace_info = VARRAY_GENERIC_PTR (tree_map, i);
2765         if (replace_info->replace_p)
2766           insert_decl_map (&id, replace_info->old_tree,
2767                            replace_info->new_tree);
2768       }
2769   
2770   DECL_INITIAL (new_decl) = remap_blocks (DECL_INITIAL (id.src_fn), &id);
2771   
2772   /* Renumber the lexical scoping (non-code) blocks consecutively.  */
2773   number_blocks (id.dst_fn);
2774   
2775   if (DECL_STRUCT_FUNCTION (old_decl)->unexpanded_var_list != NULL_TREE)
2776     /* Add local vars.  */
2777     for (t_step = DECL_STRUCT_FUNCTION (old_decl)->unexpanded_var_list;
2778          t_step; t_step = TREE_CHAIN (t_step))
2779       {
2780         tree var = TREE_VALUE (t_step);
2781         if (TREE_STATIC (var) && !TREE_ASM_WRITTEN (var))
2782           cfun->unexpanded_var_list = tree_cons (NULL_TREE, var,
2783                                                  cfun->unexpanded_var_list);
2784         else
2785           cfun->unexpanded_var_list =
2786             tree_cons (NULL_TREE, remap_decl (var, &id),
2787                        cfun->unexpanded_var_list);
2788       }
2789   
2790   /* Copy the Function's body.  */
2791   old_entry_block = ENTRY_BLOCK_PTR_FOR_FUNCTION
2792     (DECL_STRUCT_FUNCTION (old_decl));
2793   new_fndecl = copy_body (&id,
2794                           old_entry_block->count,
2795                           old_entry_block->frequency, NULL, NULL);
2796   
2797   DECL_SAVED_TREE (new_decl) = DECL_SAVED_TREE (new_fndecl);
2798
2799   DECL_STRUCT_FUNCTION (new_decl)->cfg =
2800     DECL_STRUCT_FUNCTION (new_fndecl)->cfg;
2801   DECL_STRUCT_FUNCTION (new_decl)->eh = DECL_STRUCT_FUNCTION (new_fndecl)->eh;
2802   DECL_STRUCT_FUNCTION (new_decl)->ib_boundaries_block =
2803     DECL_STRUCT_FUNCTION (new_fndecl)->ib_boundaries_block;
2804   DECL_STRUCT_FUNCTION (new_decl)->last_label_uid =
2805     DECL_STRUCT_FUNCTION (new_fndecl)->last_label_uid;
2806
2807   if (DECL_RESULT (old_decl) != NULL_TREE)
2808     {
2809       tree *res_decl = &DECL_RESULT (old_decl);
2810       DECL_RESULT (new_decl) = remap_decl (*res_decl, &id);
2811       lang_hooks.dup_lang_specific_decl (DECL_RESULT (new_decl));
2812     }
2813   
2814   current_function_decl = NULL;
2815   /* Renumber the lexical scoping (non-code) blocks consecutively.  */
2816   number_blocks (new_decl);
2817
2818   /* Clean up.  */
2819   splay_tree_delete (id.decl_map);
2820   fold_cond_expr_cond ();
2821   return;
2822 }
2823
2824 /* Duplicate a type, fields and all.  */
2825
2826 tree
2827 build_duplicate_type (tree type)
2828 {
2829   struct copy_body_data id;
2830
2831   memset (&id, 0, sizeof (id));
2832   id.src_fn = current_function_decl;
2833   id.dst_fn = current_function_decl;
2834   id.src_cfun = cfun;
2835   id.decl_map = splay_tree_new (splay_tree_compare_pointers, NULL, NULL);
2836
2837   type = remap_type_1 (type, &id);
2838
2839   splay_tree_delete (id.decl_map);
2840
2841   return type;
2842 }