OSDN Git Service

2008-01-16 Richard Guenther <rguenther@suse.de>
[pf3gnuchains/gcc-fork.git] / gcc / tree-inline.c
1 /* Tree inlining.
2    Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
3    Free Software Foundation, Inc.
4    Contributed by Alexandre Oliva <aoliva@redhat.com>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
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 #include "value-prof.h"
53 #include "tree-pass.h"
54 #include "target.h"
55 #include "integrate.h"
56
57 /* I'm not real happy about this, but we need to handle gimple and
58    non-gimple trees.  */
59 #include "tree-gimple.h"
60
61 /* Inlining, Cloning, Versioning, Parallelization
62
63    Inlining: a function body is duplicated, but the PARM_DECLs are
64    remapped into VAR_DECLs, and non-void RETURN_EXPRs become
65    GIMPLE_MODIFY_STMTs that store to a dedicated returned-value variable.
66    The duplicated eh_region info of the copy will later be appended
67    to the info for the caller; the eh_region info in copied throwing
68    statements and RESX_EXPRs is adjusted accordingly.
69
70    Cloning: (only in C++) We have one body for a con/de/structor, and
71    multiple function decls, each with a unique parameter list.
72    Duplicate the body, using the given splay tree; some parameters
73    will become constants (like 0 or 1).
74
75    Versioning: a function body is duplicated and the result is a new
76    function rather than into blocks of an existing function as with
77    inlining.  Some parameters will become constants.
78
79    Parallelization: a region of a function is duplicated resulting in
80    a new function.  Variables may be replaced with complex expressions
81    to enable shared variable semantics.
82
83    All of these will simultaneously lookup any callgraph edges.  If
84    we're going to inline the duplicated function body, and the given
85    function has some cloned callgraph nodes (one for each place this
86    function will be inlined) those callgraph edges will be duplicated.
87    If we're cloning the body, those callgraph edges will be
88    updated to point into the new body.  (Note that the original
89    callgraph node and edge list will not be altered.)
90
91    See the CALL_EXPR handling case in copy_body_r ().  */
92
93 /* 0 if we should not perform inlining.
94    1 if we should expand functions calls inline at the tree level.
95    2 if we should consider *all* functions to be inline
96    candidates.  */
97
98 int flag_inline_trees = 0;
99
100 /* To Do:
101
102    o In order to make inlining-on-trees work, we pessimized
103      function-local static constants.  In particular, they are now
104      always output, even when not addressed.  Fix this by treating
105      function-local static constants just like global static
106      constants; the back-end already knows not to output them if they
107      are not needed.
108
109    o Provide heuristics to clamp inlining of recursive template
110      calls?  */
111
112
113 /* Weights that estimate_num_insns uses for heuristics in inlining.  */
114
115 eni_weights eni_inlining_weights;
116
117 /* Weights that estimate_num_insns uses to estimate the size of the
118    produced code.  */
119
120 eni_weights eni_size_weights;
121
122 /* Weights that estimate_num_insns uses to estimate the time necessary
123    to execute the produced code.  */
124
125 eni_weights eni_time_weights;
126
127 /* Prototypes.  */
128
129 static tree declare_return_variable (copy_body_data *, tree, tree, tree *);
130 static tree copy_generic_body (copy_body_data *);
131 static bool inlinable_function_p (tree);
132 static void remap_block (tree *, copy_body_data *);
133 static tree remap_decls (tree, copy_body_data *);
134 static void copy_bind_expr (tree *, int *, copy_body_data *);
135 static tree mark_local_for_remap_r (tree *, int *, void *);
136 static void unsave_expr_1 (tree);
137 static tree unsave_r (tree *, int *, void *);
138 static void declare_inline_vars (tree, tree);
139 static void remap_save_expr (tree *, void *, int *);
140 static void add_lexical_block (tree current_block, tree new_block);
141 static tree copy_decl_to_var (tree, copy_body_data *);
142 static tree copy_result_decl_to_var (tree, copy_body_data *);
143 static tree copy_decl_no_change (tree, copy_body_data *);
144 static tree copy_decl_maybe_to_var (tree, copy_body_data *);
145
146 /* Insert a tree->tree mapping for ID.  Despite the name suggests
147    that the trees should be variables, it is used for more than that.  */
148
149 void
150 insert_decl_map (copy_body_data *id, tree key, tree value)
151 {
152   *pointer_map_insert (id->decl_map, key) = value;
153
154   /* Always insert an identity map as well.  If we see this same new
155      node again, we won't want to duplicate it a second time.  */
156   if (key != value)
157     *pointer_map_insert (id->decl_map, value) = value;
158 }
159
160 /* Construct new SSA name for old NAME. ID is the inline context.  */
161
162 static tree
163 remap_ssa_name (tree name, copy_body_data *id)
164 {
165   tree new;
166   tree *n;
167
168   gcc_assert (TREE_CODE (name) == SSA_NAME);
169
170   n = (tree *) pointer_map_contains (id->decl_map, name);
171   if (n)
172     return *n;
173
174   /* Do not set DEF_STMT yet as statement is not copied yet. We do that
175      in copy_bb.  */
176   new = remap_decl (SSA_NAME_VAR (name), id);
177   /* We might've substituted constant or another SSA_NAME for
178      the variable. 
179
180      Replace the SSA name representing RESULT_DECL by variable during
181      inlining:  this saves us from need to introduce PHI node in a case
182      return value is just partly initialized.  */
183   if ((TREE_CODE (new) == VAR_DECL || TREE_CODE (new) == PARM_DECL)
184       && (TREE_CODE (SSA_NAME_VAR (name)) != RESULT_DECL
185           || !id->transform_return_to_modify))
186     {
187       new = make_ssa_name (new, NULL);
188       insert_decl_map (id, name, new);
189       SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new)
190         = SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name);
191       TREE_TYPE (new) = TREE_TYPE (SSA_NAME_VAR (new));
192       if (IS_EMPTY_STMT (SSA_NAME_DEF_STMT (name)))
193         {
194           /* By inlining function having uninitialized variable, we might
195              extend the lifetime (variable might get reused).  This cause
196              ICE in the case we end up extending lifetime of SSA name across
197              abnormal edge, but also increase register presure.
198
199              We simply initialize all uninitialized vars by 0 except for case
200              we are inlining to very first BB.  We can avoid this for all
201              BBs that are not withing strongly connected regions of the CFG,
202              but this is bit expensive to test.
203            */
204           if (id->entry_bb && is_gimple_reg (SSA_NAME_VAR (name))
205               && TREE_CODE (SSA_NAME_VAR (name)) != PARM_DECL
206               && (id->entry_bb != EDGE_SUCC (ENTRY_BLOCK_PTR, 0)->dest
207                   || EDGE_COUNT (id->entry_bb->preds) != 1))
208             {
209               block_stmt_iterator bsi = bsi_last (id->entry_bb);
210               tree init_stmt
211                   = build_gimple_modify_stmt (new,
212                                               fold_convert (TREE_TYPE (new),
213                                                             integer_zero_node));
214               bsi_insert_after (&bsi, init_stmt, BSI_NEW_STMT);
215               SSA_NAME_DEF_STMT (new) = init_stmt;
216               SSA_NAME_IS_DEFAULT_DEF (new) = 0;
217             }
218           else
219             {
220               SSA_NAME_DEF_STMT (new) = build_empty_stmt ();
221               if (gimple_default_def (id->src_cfun, SSA_NAME_VAR (name)) == name)
222                 set_default_def (SSA_NAME_VAR (new), new);
223             }
224         }
225     }
226   else
227     insert_decl_map (id, name, new);
228   return new;
229 }
230
231 /* Remap DECL during the copying of the BLOCK tree for the function.  */
232
233 tree
234 remap_decl (tree decl, copy_body_data *id)
235 {
236   tree *n;
237   tree fn;
238
239   /* We only remap local variables in the current function.  */
240   fn = id->src_fn;
241
242   /* See if we have remapped this declaration.  */
243
244   n = (tree *) pointer_map_contains (id->decl_map, decl);
245
246   /* If we didn't already have an equivalent for this declaration,
247      create one now.  */
248   if (!n)
249     {
250       /* Make a copy of the variable or label.  */
251       tree t = id->copy_decl (decl, id);
252      
253       /* Remember it, so that if we encounter this local entity again
254          we can reuse this copy.  Do this early because remap_type may
255          need this decl for TYPE_STUB_DECL.  */
256       insert_decl_map (id, decl, t);
257
258       if (!DECL_P (t))
259         return t;
260
261       /* Remap types, if necessary.  */
262       TREE_TYPE (t) = remap_type (TREE_TYPE (t), id);
263       if (TREE_CODE (t) == TYPE_DECL)
264         DECL_ORIGINAL_TYPE (t) = remap_type (DECL_ORIGINAL_TYPE (t), id);
265
266       /* Remap sizes as necessary.  */
267       walk_tree (&DECL_SIZE (t), copy_body_r, id, NULL);
268       walk_tree (&DECL_SIZE_UNIT (t), copy_body_r, id, NULL);
269
270       /* If fields, do likewise for offset and qualifier.  */
271       if (TREE_CODE (t) == FIELD_DECL)
272         {
273           walk_tree (&DECL_FIELD_OFFSET (t), copy_body_r, id, NULL);
274           if (TREE_CODE (DECL_CONTEXT (t)) == QUAL_UNION_TYPE)
275             walk_tree (&DECL_QUALIFIER (t), copy_body_r, id, NULL);
276         }
277
278       if (cfun && gimple_in_ssa_p (cfun)
279           && (TREE_CODE (t) == VAR_DECL
280               || TREE_CODE (t) == RESULT_DECL || TREE_CODE (t) == PARM_DECL))
281         {
282           tree def = gimple_default_def (id->src_cfun, decl);
283           get_var_ann (t);
284           if (TREE_CODE (decl) != PARM_DECL && def)
285             {
286               tree map = remap_ssa_name (def, id);
287               /* Watch out RESULT_DECLs whose SSA names map directly
288                  to them.  */
289               if (TREE_CODE (map) == SSA_NAME
290                   && IS_EMPTY_STMT (SSA_NAME_DEF_STMT (map)))
291                 set_default_def (t, map);
292             }
293           add_referenced_var (t);
294         }
295       return t;
296     }
297
298   return unshare_expr (*n);
299 }
300
301 static tree
302 remap_type_1 (tree type, copy_body_data *id)
303 {
304   tree new, t;
305
306   /* We do need a copy.  build and register it now.  If this is a pointer or
307      reference type, remap the designated type and make a new pointer or
308      reference type.  */
309   if (TREE_CODE (type) == POINTER_TYPE)
310     {
311       new = build_pointer_type_for_mode (remap_type (TREE_TYPE (type), id),
312                                          TYPE_MODE (type),
313                                          TYPE_REF_CAN_ALIAS_ALL (type));
314       insert_decl_map (id, type, new);
315       return new;
316     }
317   else if (TREE_CODE (type) == REFERENCE_TYPE)
318     {
319       new = build_reference_type_for_mode (remap_type (TREE_TYPE (type), id),
320                                             TYPE_MODE (type),
321                                             TYPE_REF_CAN_ALIAS_ALL (type));
322       insert_decl_map (id, type, new);
323       return new;
324     }
325   else
326     new = copy_node (type);
327
328   insert_decl_map (id, type, new);
329
330   /* This is a new type, not a copy of an old type.  Need to reassociate
331      variants.  We can handle everything except the main variant lazily.  */
332   t = TYPE_MAIN_VARIANT (type);
333   if (type != t)
334     {
335       t = remap_type (t, id);
336       TYPE_MAIN_VARIANT (new) = t;
337       TYPE_NEXT_VARIANT (new) = TYPE_NEXT_VARIANT (t);
338       TYPE_NEXT_VARIANT (t) = new;
339     }
340   else
341     {
342       TYPE_MAIN_VARIANT (new) = new;
343       TYPE_NEXT_VARIANT (new) = NULL;
344     }
345
346   if (TYPE_STUB_DECL (type))
347     TYPE_STUB_DECL (new) = remap_decl (TYPE_STUB_DECL (type), id);
348
349   /* Lazily create pointer and reference types.  */
350   TYPE_POINTER_TO (new) = NULL;
351   TYPE_REFERENCE_TO (new) = NULL;
352
353   switch (TREE_CODE (new))
354     {
355     case INTEGER_TYPE:
356     case REAL_TYPE:
357     case FIXED_POINT_TYPE:
358     case ENUMERAL_TYPE:
359     case BOOLEAN_TYPE:
360       t = TYPE_MIN_VALUE (new);
361       if (t && TREE_CODE (t) != INTEGER_CST)
362         walk_tree (&TYPE_MIN_VALUE (new), copy_body_r, id, NULL);
363
364       t = TYPE_MAX_VALUE (new);
365       if (t && TREE_CODE (t) != INTEGER_CST)
366         walk_tree (&TYPE_MAX_VALUE (new), copy_body_r, id, NULL);
367       return new;
368
369     case FUNCTION_TYPE:
370       TREE_TYPE (new) = remap_type (TREE_TYPE (new), id);
371       walk_tree (&TYPE_ARG_TYPES (new), copy_body_r, id, NULL);
372       return new;
373
374     case ARRAY_TYPE:
375       TREE_TYPE (new) = remap_type (TREE_TYPE (new), id);
376       TYPE_DOMAIN (new) = remap_type (TYPE_DOMAIN (new), id);
377       break;
378
379     case RECORD_TYPE:
380     case UNION_TYPE:
381     case QUAL_UNION_TYPE:
382       {
383         tree f, nf = NULL;
384
385         for (f = TYPE_FIELDS (new); f ; f = TREE_CHAIN (f))
386           {
387             t = remap_decl (f, id);
388             DECL_CONTEXT (t) = new;
389             TREE_CHAIN (t) = nf;
390             nf = t;
391           }
392         TYPE_FIELDS (new) = nreverse (nf);
393       }
394       break;
395
396     case OFFSET_TYPE:
397     default:
398       /* Shouldn't have been thought variable sized.  */
399       gcc_unreachable ();
400     }
401
402   walk_tree (&TYPE_SIZE (new), copy_body_r, id, NULL);
403   walk_tree (&TYPE_SIZE_UNIT (new), copy_body_r, id, NULL);
404
405   return new;
406 }
407
408 tree
409 remap_type (tree type, copy_body_data *id)
410 {
411   tree *node;
412
413   if (type == NULL)
414     return type;
415
416   /* See if we have remapped this type.  */
417   node = (tree *) pointer_map_contains (id->decl_map, type);
418   if (node)
419     return *node;
420
421   /* The type only needs remapping if it's variably modified.  */
422   if (! variably_modified_type_p (type, id->src_fn))
423     {
424       insert_decl_map (id, type, type);
425       return type;
426     }
427
428   return remap_type_1 (type, id);
429 }
430
431 static tree
432 remap_decls (tree decls, copy_body_data *id)
433 {
434   tree old_var;
435   tree new_decls = NULL_TREE;
436
437   /* Remap its variables.  */
438   for (old_var = decls; old_var; old_var = TREE_CHAIN (old_var))
439     {
440       tree new_var;
441
442       /* We can not chain the local static declarations into the unexpanded_var_list
443          as we can't duplicate them or break one decl rule.  Go ahead and link
444          them into unexpanded_var_list.  */
445       if (!auto_var_in_fn_p (old_var, id->src_fn)
446           && !DECL_EXTERNAL (old_var))
447         {
448           cfun->unexpanded_var_list = tree_cons (NULL_TREE, old_var,
449                                                  cfun->unexpanded_var_list);
450           continue;
451         }
452
453       /* Remap the variable.  */
454       new_var = remap_decl (old_var, id);
455
456       /* If we didn't remap this variable, so we can't mess with its
457          TREE_CHAIN.  If we remapped this variable to the return slot, it's
458          already declared somewhere else, so don't declare it here.  */
459       if (!new_var || new_var == id->retvar)
460         ;
461       else
462         {
463           gcc_assert (DECL_P (new_var));
464           TREE_CHAIN (new_var) = new_decls;
465           new_decls = new_var;
466         }
467     }
468
469   return nreverse (new_decls);
470 }
471
472 /* Copy the BLOCK to contain remapped versions of the variables
473    therein.  And hook the new block into the block-tree.  */
474
475 static void
476 remap_block (tree *block, copy_body_data *id)
477 {
478   tree old_block;
479   tree new_block;
480   tree fn;
481
482   /* Make the new block.  */
483   old_block = *block;
484   new_block = make_node (BLOCK);
485   TREE_USED (new_block) = TREE_USED (old_block);
486   BLOCK_ABSTRACT_ORIGIN (new_block) = old_block;
487   BLOCK_SOURCE_LOCATION (new_block) = BLOCK_SOURCE_LOCATION (old_block);
488   *block = new_block;
489
490   /* Remap its variables.  */
491   BLOCK_VARS (new_block) = remap_decls (BLOCK_VARS (old_block), id);
492
493   fn = id->dst_fn;
494
495   if (id->transform_lang_insert_block)
496     lang_hooks.decls.insert_block (new_block);
497
498   /* Remember the remapped block.  */
499   insert_decl_map (id, old_block, new_block);
500 }
501
502 /* Copy the whole block tree and root it in id->block.  */
503 static tree
504 remap_blocks (tree block, copy_body_data *id)
505 {
506   tree t;
507   tree new = block;
508
509   if (!block)
510     return NULL;
511
512   remap_block (&new, id);
513   gcc_assert (new != block);
514   for (t = BLOCK_SUBBLOCKS (block); t ; t = BLOCK_CHAIN (t))
515     add_lexical_block (new, remap_blocks (t, id));
516   return new;
517 }
518
519 static void
520 copy_statement_list (tree *tp)
521 {
522   tree_stmt_iterator oi, ni;
523   tree new;
524
525   new = alloc_stmt_list ();
526   ni = tsi_start (new);
527   oi = tsi_start (*tp);
528   *tp = new;
529
530   for (; !tsi_end_p (oi); tsi_next (&oi))
531     tsi_link_after (&ni, tsi_stmt (oi), TSI_NEW_STMT);
532 }
533
534 static void
535 copy_bind_expr (tree *tp, int *walk_subtrees, copy_body_data *id)
536 {
537   tree block = BIND_EXPR_BLOCK (*tp);
538   /* Copy (and replace) the statement.  */
539   copy_tree_r (tp, walk_subtrees, NULL);
540   if (block)
541     {
542       remap_block (&block, id);
543       BIND_EXPR_BLOCK (*tp) = block;
544     }
545
546   if (BIND_EXPR_VARS (*tp))
547     /* This will remap a lot of the same decls again, but this should be
548        harmless.  */
549     BIND_EXPR_VARS (*tp) = remap_decls (BIND_EXPR_VARS (*tp), id);
550 }
551
552 /* Called from copy_body_id via walk_tree.  DATA is really an
553    `copy_body_data *'.  */
554
555 tree
556 copy_body_r (tree *tp, int *walk_subtrees, void *data)
557 {
558   copy_body_data *id = (copy_body_data *) data;
559   tree fn = id->src_fn;
560   tree new_block;
561
562   /* Begin by recognizing trees that we'll completely rewrite for the
563      inlining context.  Our output for these trees is completely
564      different from out input (e.g. RETURN_EXPR is deleted, and morphs
565      into an edge).  Further down, we'll handle trees that get
566      duplicated and/or tweaked.  */
567
568   /* When requested, RETURN_EXPRs should be transformed to just the
569      contained GIMPLE_MODIFY_STMT.  The branch semantics of the return will
570      be handled elsewhere by manipulating the CFG rather than a statement.  */
571   if (TREE_CODE (*tp) == RETURN_EXPR && id->transform_return_to_modify)
572     {
573       tree assignment = TREE_OPERAND (*tp, 0);
574
575       /* If we're returning something, just turn that into an
576          assignment into the equivalent of the original RESULT_DECL.
577          If the "assignment" is just the result decl, the result
578          decl has already been set (e.g. a recent "foo (&result_decl,
579          ...)"); just toss the entire RETURN_EXPR.  */
580       if (assignment && TREE_CODE (assignment) == GIMPLE_MODIFY_STMT)
581         {
582           /* Replace the RETURN_EXPR with (a copy of) the
583              GIMPLE_MODIFY_STMT hanging underneath.  */
584           *tp = copy_node (assignment);
585         }
586       else /* Else the RETURN_EXPR returns no value.  */
587         {
588           *tp = NULL;
589           return (tree) (void *)1;
590         }
591     }
592   else if (TREE_CODE (*tp) == SSA_NAME)
593     {
594       *tp = remap_ssa_name (*tp, id);
595       *walk_subtrees = 0;
596       return NULL;
597     }
598
599   /* Local variables and labels need to be replaced by equivalent
600      variables.  We don't want to copy static variables; there's only
601      one of those, no matter how many times we inline the containing
602      function.  Similarly for globals from an outer function.  */
603   else if (auto_var_in_fn_p (*tp, fn))
604     {
605       tree new_decl;
606
607       /* Remap the declaration.  */
608       new_decl = remap_decl (*tp, id);
609       gcc_assert (new_decl);
610       /* Replace this variable with the copy.  */
611       STRIP_TYPE_NOPS (new_decl);
612       *tp = new_decl;
613       *walk_subtrees = 0;
614     }
615   else if (TREE_CODE (*tp) == STATEMENT_LIST)
616     copy_statement_list (tp);
617   else if (TREE_CODE (*tp) == SAVE_EXPR)
618     remap_save_expr (tp, id->decl_map, walk_subtrees);
619   else if (TREE_CODE (*tp) == LABEL_DECL
620            && (! DECL_CONTEXT (*tp)
621                || decl_function_context (*tp) == id->src_fn))
622     /* These may need to be remapped for EH handling.  */
623     *tp = remap_decl (*tp, id);
624   else if (TREE_CODE (*tp) == BIND_EXPR)
625     copy_bind_expr (tp, walk_subtrees, id);
626   /* Types may need remapping as well.  */
627   else if (TYPE_P (*tp))
628     *tp = remap_type (*tp, id);
629
630   /* If this is a constant, we have to copy the node iff the type will be
631      remapped.  copy_tree_r will not copy a constant.  */
632   else if (CONSTANT_CLASS_P (*tp))
633     {
634       tree new_type = remap_type (TREE_TYPE (*tp), id);
635
636       if (new_type == TREE_TYPE (*tp))
637         *walk_subtrees = 0;
638
639       else if (TREE_CODE (*tp) == INTEGER_CST)
640         *tp = build_int_cst_wide (new_type, TREE_INT_CST_LOW (*tp),
641                                   TREE_INT_CST_HIGH (*tp));
642       else
643         {
644           *tp = copy_node (*tp);
645           TREE_TYPE (*tp) = new_type;
646         }
647     }
648
649   /* Otherwise, just copy the node.  Note that copy_tree_r already
650      knows not to copy VAR_DECLs, etc., so this is safe.  */
651   else
652     {
653       /* Here we handle trees that are not completely rewritten.
654          First we detect some inlining-induced bogosities for
655          discarding.  */
656       if (TREE_CODE (*tp) == GIMPLE_MODIFY_STMT
657           && GIMPLE_STMT_OPERAND (*tp, 0) == GIMPLE_STMT_OPERAND (*tp, 1)
658           && (auto_var_in_fn_p (GIMPLE_STMT_OPERAND (*tp, 0), fn)))
659         {
660           /* Some assignments VAR = VAR; don't generate any rtl code
661              and thus don't count as variable modification.  Avoid
662              keeping bogosities like 0 = 0.  */
663           tree decl = GIMPLE_STMT_OPERAND (*tp, 0), value;
664           tree *n;
665
666           n = (tree *) pointer_map_contains (id->decl_map, decl);
667           if (n)
668             {
669               value = *n;
670               STRIP_TYPE_NOPS (value);
671               if (TREE_CONSTANT (value) || TREE_READONLY_DECL_P (value))
672                 {
673                   *tp = build_empty_stmt ();
674                   return copy_body_r (tp, walk_subtrees, data);
675                 }
676             }
677         }
678       else if (TREE_CODE (*tp) == INDIRECT_REF)
679         {
680           /* Get rid of *& from inline substitutions that can happen when a
681              pointer argument is an ADDR_EXPR.  */
682           tree decl = TREE_OPERAND (*tp, 0);
683           tree *n;
684
685           n = (tree *) pointer_map_contains (id->decl_map, decl);
686           if (n)
687             {
688               tree new;
689               tree old;
690               /* If we happen to get an ADDR_EXPR in n->value, strip
691                  it manually here as we'll eventually get ADDR_EXPRs
692                  which lie about their types pointed to.  In this case
693                  build_fold_indirect_ref wouldn't strip the INDIRECT_REF,
694                  but we absolutely rely on that.  As fold_indirect_ref
695                  does other useful transformations, try that first, though.  */
696               tree type = TREE_TYPE (TREE_TYPE (*n));
697               new = unshare_expr (*n);
698               old = *tp;
699               *tp = gimple_fold_indirect_ref (new);
700               if (! *tp)
701                 {
702                   if (TREE_CODE (new) == ADDR_EXPR)
703                     {
704                       *tp = fold_indirect_ref_1 (type, new);
705                       /* ???  We should either assert here or build
706                          a VIEW_CONVERT_EXPR instead of blindly leaking
707                          incompatible types to our IL.  */
708                       if (! *tp)
709                         *tp = TREE_OPERAND (new, 0);
710                     }
711                   else
712                     {
713                       *tp = build1 (INDIRECT_REF, type, new);
714                       TREE_THIS_VOLATILE (*tp) = TREE_THIS_VOLATILE (old);
715                     }
716                 }
717               *walk_subtrees = 0;
718               return NULL;
719             }
720         }
721
722       /* Here is the "usual case".  Copy this tree node, and then
723          tweak some special cases.  */
724       copy_tree_r (tp, walk_subtrees, NULL);
725
726       /* Global variables we didn't seen yet needs to go into referenced
727          vars.  */
728       if (gimple_in_ssa_p (cfun) && TREE_CODE (*tp) == VAR_DECL)
729         add_referenced_var (*tp);
730        
731       /* If EXPR has block defined, map it to newly constructed block.
732          When inlining we want EXPRs without block appear in the block
733          of function call.  */
734       if (EXPR_P (*tp) || GIMPLE_STMT_P (*tp))
735         {
736           new_block = id->block;
737           if (TREE_BLOCK (*tp))
738             {
739               tree *n;
740               n = (tree *) pointer_map_contains (id->decl_map,
741                                                  TREE_BLOCK (*tp));
742               gcc_assert (n);
743               new_block = *n;
744             }
745           TREE_BLOCK (*tp) = new_block;
746         }
747
748       if (TREE_CODE (*tp) == RESX_EXPR && id->eh_region_offset)
749         TREE_OPERAND (*tp, 0) =
750           build_int_cst
751             (NULL_TREE,
752              id->eh_region_offset + TREE_INT_CST_LOW (TREE_OPERAND (*tp, 0)));
753
754       if (!GIMPLE_TUPLE_P (*tp) && TREE_CODE (*tp) != OMP_CLAUSE)
755         TREE_TYPE (*tp) = remap_type (TREE_TYPE (*tp), id);
756
757       /* The copied TARGET_EXPR has never been expanded, even if the
758          original node was expanded already.  */
759       if (TREE_CODE (*tp) == TARGET_EXPR && TREE_OPERAND (*tp, 3))
760         {
761           TREE_OPERAND (*tp, 1) = TREE_OPERAND (*tp, 3);
762           TREE_OPERAND (*tp, 3) = NULL_TREE;
763         }
764
765       /* Variable substitution need not be simple.  In particular, the
766          INDIRECT_REF substitution above.  Make sure that TREE_CONSTANT
767          and friends are up-to-date.  */
768       else if (TREE_CODE (*tp) == ADDR_EXPR)
769         {
770           int invariant = TREE_INVARIANT (*tp);
771           walk_tree (&TREE_OPERAND (*tp, 0), copy_body_r, id, NULL);
772           /* Handle the case where we substituted an INDIRECT_REF
773              into the operand of the ADDR_EXPR.  */
774           if (TREE_CODE (TREE_OPERAND (*tp, 0)) == INDIRECT_REF)
775             *tp = TREE_OPERAND (TREE_OPERAND (*tp, 0), 0);
776           else
777             recompute_tree_invariant_for_addr_expr (*tp);
778           /* If this used to be invariant, but is not any longer,
779              then regimplification is probably needed.  */
780           if (invariant && !TREE_INVARIANT (*tp))
781             id->regimplify = true;
782           *walk_subtrees = 0;
783         }
784     }
785
786   /* Keep iterating.  */
787   return NULL_TREE;
788 }
789
790 /* Copy basic block, scale profile accordingly.  Edges will be taken care of
791    later  */
792
793 static basic_block
794 copy_bb (copy_body_data *id, basic_block bb, int frequency_scale, int count_scale)
795 {
796   block_stmt_iterator bsi, copy_bsi;
797   basic_block copy_basic_block;
798
799   /* create_basic_block() will append every new block to
800      basic_block_info automatically.  */
801   copy_basic_block = create_basic_block (NULL, (void *) 0,
802                                          (basic_block) bb->prev_bb->aux);
803   copy_basic_block->count = bb->count * count_scale / REG_BR_PROB_BASE;
804
805   /* We are going to rebuild frequencies from scratch.  These values have just
806      small importance to drive canonicalize_loop_headers.  */
807   copy_basic_block->frequency = ((gcov_type)bb->frequency
808                                      * frequency_scale / REG_BR_PROB_BASE);
809   if (copy_basic_block->frequency > BB_FREQ_MAX)
810     copy_basic_block->frequency = BB_FREQ_MAX;
811   copy_bsi = bsi_start (copy_basic_block);
812
813   for (bsi = bsi_start (bb);
814        !bsi_end_p (bsi); bsi_next (&bsi))
815     {
816       tree stmt = bsi_stmt (bsi);
817       tree orig_stmt = stmt;
818
819       id->regimplify = false;
820       walk_tree (&stmt, copy_body_r, id, NULL);
821
822       /* RETURN_EXPR might be removed,
823          this is signalled by making stmt pointer NULL.  */
824       if (stmt)
825         {
826           tree call, decl;
827
828           gimple_duplicate_stmt_histograms (cfun, stmt, id->src_cfun, orig_stmt);
829
830           /* With return slot optimization we can end up with
831              non-gimple (foo *)&this->m, fix that here.  */
832           if ((TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
833                && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == NOP_EXPR
834                && !is_gimple_val (TREE_OPERAND (GIMPLE_STMT_OPERAND (stmt, 1), 0)))
835               || id->regimplify)
836             gimplify_stmt (&stmt);
837
838           bsi_insert_after (&copy_bsi, stmt, BSI_NEW_STMT);
839
840           /* Process new statement.  gimplify_stmt possibly turned statement
841              into multiple statements, we need to process all of them.  */
842           while (!bsi_end_p (copy_bsi))
843             {
844               tree *stmtp = bsi_stmt_ptr (copy_bsi);
845               tree stmt = *stmtp;
846               call = get_call_expr_in (stmt);
847
848               if (call && CALL_EXPR_VA_ARG_PACK (call) && id->call_expr)
849                 {
850                   /* __builtin_va_arg_pack () should be replaced by
851                      all arguments corresponding to ... in the caller.  */
852                   tree p, *argarray, new_call, *call_ptr;
853                   int nargs = call_expr_nargs (id->call_expr);
854
855                   for (p = DECL_ARGUMENTS (id->src_fn); p; p = TREE_CHAIN (p))
856                     nargs--;
857
858                   argarray = (tree *) alloca ((nargs + call_expr_nargs (call))
859                                               * sizeof (tree));
860
861                   memcpy (argarray, CALL_EXPR_ARGP (call),
862                           call_expr_nargs (call) * sizeof (*argarray));
863                   memcpy (argarray + call_expr_nargs (call),
864                           CALL_EXPR_ARGP (id->call_expr)
865                           + (call_expr_nargs (id->call_expr) - nargs),
866                           nargs * sizeof (*argarray));
867
868                   new_call = build_call_array (TREE_TYPE (call),
869                                                CALL_EXPR_FN (call),
870                                                nargs + call_expr_nargs (call),
871                                                argarray);
872                   /* Copy all CALL_EXPR flags, locus and block, except
873                      CALL_EXPR_VA_ARG_PACK flag.  */
874                   CALL_EXPR_STATIC_CHAIN (new_call)
875                     = CALL_EXPR_STATIC_CHAIN (call);
876                   CALL_EXPR_TAILCALL (new_call) = CALL_EXPR_TAILCALL (call);
877                   CALL_EXPR_RETURN_SLOT_OPT (new_call)
878                     = CALL_EXPR_RETURN_SLOT_OPT (call);
879                   CALL_FROM_THUNK_P (new_call) = CALL_FROM_THUNK_P (call);
880                   CALL_CANNOT_INLINE_P (new_call)
881                     = CALL_CANNOT_INLINE_P (call);
882                   TREE_NOTHROW (new_call) = TREE_NOTHROW (call);
883                   SET_EXPR_LOCUS (new_call, EXPR_LOCUS (call));
884                   TREE_BLOCK (new_call) = TREE_BLOCK (call);
885
886                   call_ptr = stmtp;
887                   if (TREE_CODE (*call_ptr) == GIMPLE_MODIFY_STMT)
888                     call_ptr = &GIMPLE_STMT_OPERAND (*call_ptr, 1);
889                   if (TREE_CODE (*call_ptr) == WITH_SIZE_EXPR)
890                     call_ptr = &TREE_OPERAND (*call_ptr, 0);
891                   gcc_assert (*call_ptr == call);
892                   if (call_ptr == stmtp)
893                     {
894                       bsi_replace (&copy_bsi, new_call, true);
895                       stmtp = bsi_stmt_ptr (copy_bsi);
896                       stmt = *stmtp;
897                     }
898                   else
899                     {
900                       *call_ptr = new_call;
901                       stmt = *stmtp;
902                       update_stmt (stmt);
903                     }
904                 }
905               else if (call
906                        && id->call_expr
907                        && (decl = get_callee_fndecl (call))
908                        && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
909                        && DECL_FUNCTION_CODE (decl)
910                           == BUILT_IN_VA_ARG_PACK_LEN)
911                 {
912                   /* __builtin_va_arg_pack_len () should be replaced by
913                      the number of anonymous arguments.  */
914                   int nargs = call_expr_nargs (id->call_expr);
915                   tree count, *call_ptr, p;
916
917                   for (p = DECL_ARGUMENTS (id->src_fn); p; p = TREE_CHAIN (p))
918                     nargs--;
919
920                   count = build_int_cst (integer_type_node, nargs);
921                   call_ptr = stmtp;
922                   if (TREE_CODE (*call_ptr) == GIMPLE_MODIFY_STMT)
923                     call_ptr = &GIMPLE_STMT_OPERAND (*call_ptr, 1);
924                   if (TREE_CODE (*call_ptr) == WITH_SIZE_EXPR)
925                     call_ptr = &TREE_OPERAND (*call_ptr, 0);
926                   gcc_assert (*call_ptr == call && call_ptr != stmtp);
927                   *call_ptr = count;
928                   stmt = *stmtp;
929                   update_stmt (stmt);
930                   call = NULL_TREE;
931                 }
932
933               /* Statements produced by inlining can be unfolded, especially
934                  when we constant propagated some operands.  We can't fold
935                  them right now for two reasons:
936                  1) folding require SSA_NAME_DEF_STMTs to be correct
937                  2) we can't change function calls to builtins.
938                  So we just mark statement for later folding.  We mark
939                  all new statements, instead just statements that has changed
940                  by some nontrivial substitution so even statements made
941                  foldable indirectly are updated.  If this turns out to be
942                  expensive, copy_body can be told to watch for nontrivial
943                  changes.  */
944               if (id->statements_to_fold)
945                 pointer_set_insert (id->statements_to_fold, stmt);
946               /* We're duplicating a CALL_EXPR.  Find any corresponding
947                  callgraph edges and update or duplicate them.  */
948               if (call && (decl = get_callee_fndecl (call)))
949                 {
950                   struct cgraph_node *node;
951                   struct cgraph_edge *edge;
952                  
953                   switch (id->transform_call_graph_edges)
954                     {
955                     case CB_CGE_DUPLICATE:
956                       edge = cgraph_edge (id->src_node, orig_stmt);
957                       if (edge)
958                         cgraph_clone_edge (edge, id->dst_node, stmt,
959                                            REG_BR_PROB_BASE, 1, edge->frequency, true);
960                       break;
961
962                     case CB_CGE_MOVE_CLONES:
963                       for (node = id->dst_node->next_clone;
964                            node;
965                            node = node->next_clone)
966                         {
967                           edge = cgraph_edge (node, orig_stmt);
968                           gcc_assert (edge);
969                           cgraph_set_call_stmt (edge, stmt);
970                         }
971                       /* FALLTHRU */
972
973                     case CB_CGE_MOVE:
974                       edge = cgraph_edge (id->dst_node, orig_stmt);
975                       if (edge)
976                         cgraph_set_call_stmt (edge, stmt);
977                       break;
978
979                     default:
980                       gcc_unreachable ();
981                     }
982                 }
983               /* If you think we can abort here, you are wrong.
984                  There is no region 0 in tree land.  */
985               gcc_assert (lookup_stmt_eh_region_fn (id->src_cfun, orig_stmt)
986                           != 0);
987
988               if (tree_could_throw_p (stmt)
989                   /* When we are cloning for inlining, we are supposed to
990                      construct a clone that calls precisely the same functions
991                      as original.  However IPA optimizers might've proved
992                      earlier some function calls as non-trapping that might
993                      render some basic blocks dead that might become
994                      unreachable.
995
996                      We can't update SSA with unreachable blocks in CFG and thus
997                      we prevent the scenario by preserving even the "dead" eh
998                      edges until the point they are later removed by
999                      fixup_cfg pass.  */
1000                   || (id->transform_call_graph_edges == CB_CGE_MOVE_CLONES
1001                       && lookup_stmt_eh_region_fn (id->src_cfun, orig_stmt) > 0))
1002                 {
1003                   int region = lookup_stmt_eh_region_fn (id->src_cfun, orig_stmt);
1004                   /* Add an entry for the copied tree in the EH hashtable.
1005                      When cloning or versioning, use the hashtable in
1006                      cfun, and just copy the EH number.  When inlining, use the
1007                      hashtable in the caller, and adjust the region number.  */
1008                   if (region > 0)
1009                     add_stmt_to_eh_region (stmt, region + id->eh_region_offset);
1010
1011                   /* If this tree doesn't have a region associated with it,
1012                      and there is a "current region,"
1013                      then associate this tree with the current region
1014                      and add edges associated with this region.  */
1015                   if ((lookup_stmt_eh_region_fn (id->src_cfun,
1016                                                  orig_stmt) <= 0
1017                        && id->eh_region > 0)
1018                       && tree_could_throw_p (stmt))
1019                     add_stmt_to_eh_region (stmt, id->eh_region);
1020                 }
1021               if (gimple_in_ssa_p (cfun))
1022                 {
1023                    ssa_op_iter i;
1024                    tree def;
1025
1026                    find_new_referenced_vars (bsi_stmt_ptr (copy_bsi));
1027                    FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
1028                     if (TREE_CODE (def) == SSA_NAME)
1029                       SSA_NAME_DEF_STMT (def) = stmt;
1030                 }
1031               bsi_next (&copy_bsi);
1032             }
1033           copy_bsi = bsi_last (copy_basic_block);
1034         }
1035     }
1036   return copy_basic_block;
1037 }
1038
1039 /* Inserting Single Entry Multiple Exit region in SSA form into code in SSA
1040    form is quite easy, since dominator relationship for old basic blocks does
1041    not change.
1042
1043    There is however exception where inlining might change dominator relation
1044    across EH edges from basic block within inlined functions destinating
1045    to landing pads in function we inline into.
1046
1047    The function fills in PHI_RESULTs of such PHI nodes if they refer
1048    to gimple regs.  Otherwise, the function mark PHI_RESULT of such
1049    PHI nodes for renaming.  For non-gimple regs, renaming is safe: the
1050    EH edges are abnormal and SSA_NAME_OCCURS_IN_ABNORMAL_PHI must be
1051    set, and this means that there will be no overlapping live ranges
1052    for the underlying symbol.
1053
1054    This might change in future if we allow redirecting of EH edges and
1055    we might want to change way build CFG pre-inlining to include
1056    all the possible edges then.  */
1057 static void
1058 update_ssa_across_abnormal_edges (basic_block bb, basic_block ret_bb,
1059                                   bool can_throw, bool nonlocal_goto)
1060 {
1061   edge e;
1062   edge_iterator ei;
1063
1064   FOR_EACH_EDGE (e, ei, bb->succs)
1065     if (!e->dest->aux
1066         || ((basic_block)e->dest->aux)->index == ENTRY_BLOCK)
1067       {
1068         tree phi;
1069
1070         gcc_assert (e->flags & EDGE_ABNORMAL);
1071         if (!nonlocal_goto)
1072           gcc_assert (e->flags & EDGE_EH);
1073         if (!can_throw)
1074           gcc_assert (!(e->flags & EDGE_EH));
1075         for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
1076           {
1077             edge re;
1078
1079             /* There shouldn't be any PHI nodes in the ENTRY_BLOCK.  */
1080             gcc_assert (!e->dest->aux);
1081
1082             gcc_assert (SSA_NAME_OCCURS_IN_ABNORMAL_PHI
1083                         (PHI_RESULT (phi)));
1084
1085             if (!is_gimple_reg (PHI_RESULT (phi)))
1086               {
1087                 mark_sym_for_renaming
1088                   (SSA_NAME_VAR (PHI_RESULT (phi)));
1089                 continue;
1090               }
1091
1092             re = find_edge (ret_bb, e->dest);
1093             gcc_assert (re);
1094             gcc_assert ((re->flags & (EDGE_EH | EDGE_ABNORMAL))
1095                         == (e->flags & (EDGE_EH | EDGE_ABNORMAL)));
1096
1097             SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (phi, e),
1098                      USE_FROM_PTR (PHI_ARG_DEF_PTR_FROM_EDGE (phi, re)));
1099           }
1100       }
1101 }
1102
1103 /* Copy edges from BB into its copy constructed earlier, scale profile
1104    accordingly.  Edges will be taken care of later.  Assume aux
1105    pointers to point to the copies of each BB.  */
1106 static void
1107 copy_edges_for_bb (basic_block bb, int count_scale, basic_block ret_bb)
1108 {
1109   basic_block new_bb = (basic_block) bb->aux;
1110   edge_iterator ei;
1111   edge old_edge;
1112   block_stmt_iterator bsi;
1113   int flags;
1114
1115   /* Use the indices from the original blocks to create edges for the
1116      new ones.  */
1117   FOR_EACH_EDGE (old_edge, ei, bb->succs)
1118     if (!(old_edge->flags & EDGE_EH))
1119       {
1120         edge new;
1121
1122         flags = old_edge->flags;
1123
1124         /* Return edges do get a FALLTHRU flag when the get inlined.  */
1125         if (old_edge->dest->index == EXIT_BLOCK && !old_edge->flags
1126             && old_edge->dest->aux != EXIT_BLOCK_PTR)
1127           flags |= EDGE_FALLTHRU;
1128         new = make_edge (new_bb, (basic_block) old_edge->dest->aux, flags);
1129         new->count = old_edge->count * count_scale / REG_BR_PROB_BASE;
1130         new->probability = old_edge->probability;
1131       }
1132
1133   if (bb->index == ENTRY_BLOCK || bb->index == EXIT_BLOCK)
1134     return;
1135
1136   for (bsi = bsi_start (new_bb); !bsi_end_p (bsi);)
1137     {
1138       tree copy_stmt;
1139       bool can_throw, nonlocal_goto;
1140
1141       copy_stmt = bsi_stmt (bsi);
1142       update_stmt (copy_stmt);
1143       if (gimple_in_ssa_p (cfun))
1144         mark_symbols_for_renaming (copy_stmt);
1145       /* Do this before the possible split_block.  */
1146       bsi_next (&bsi);
1147
1148       /* If this tree could throw an exception, there are two
1149          cases where we need to add abnormal edge(s): the
1150          tree wasn't in a region and there is a "current
1151          region" in the caller; or the original tree had
1152          EH edges.  In both cases split the block after the tree,
1153          and add abnormal edge(s) as needed; we need both
1154          those from the callee and the caller.
1155          We check whether the copy can throw, because the const
1156          propagation can change an INDIRECT_REF which throws
1157          into a COMPONENT_REF which doesn't.  If the copy
1158          can throw, the original could also throw.  */
1159
1160       can_throw = tree_can_throw_internal (copy_stmt);
1161       nonlocal_goto = tree_can_make_abnormal_goto (copy_stmt);
1162
1163       if (can_throw || nonlocal_goto)
1164         {
1165           if (!bsi_end_p (bsi))
1166             /* Note that bb's predecessor edges aren't necessarily
1167                right at this point; split_block doesn't care.  */
1168             {
1169               edge e = split_block (new_bb, copy_stmt);
1170
1171               new_bb = e->dest;
1172               new_bb->aux = e->src->aux;
1173               bsi = bsi_start (new_bb);
1174             }
1175         }
1176
1177       if (can_throw)
1178         make_eh_edges (copy_stmt);
1179
1180       if (nonlocal_goto)
1181         make_abnormal_goto_edges (bb_for_stmt (copy_stmt), true);
1182
1183       if ((can_throw || nonlocal_goto)
1184           && gimple_in_ssa_p (cfun))
1185         update_ssa_across_abnormal_edges (bb_for_stmt (copy_stmt), ret_bb,
1186                                           can_throw, nonlocal_goto);
1187     }
1188 }
1189
1190 /* Copy the PHIs.  All blocks and edges are copied, some blocks
1191    was possibly split and new outgoing EH edges inserted.
1192    BB points to the block of original function and AUX pointers links
1193    the original and newly copied blocks.  */
1194
1195 static void
1196 copy_phis_for_bb (basic_block bb, copy_body_data *id)
1197 {
1198   basic_block new_bb = bb->aux;
1199   edge_iterator ei;
1200   tree phi;
1201
1202   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1203     {
1204       tree res = PHI_RESULT (phi);
1205       tree new_res = res;
1206       tree new_phi;
1207       edge new_edge;
1208
1209       if (is_gimple_reg (res))
1210         {
1211           walk_tree (&new_res, copy_body_r, id, NULL);
1212           SSA_NAME_DEF_STMT (new_res)
1213             = new_phi = create_phi_node (new_res, new_bb);
1214           FOR_EACH_EDGE (new_edge, ei, new_bb->preds)
1215             {
1216               edge old_edge = find_edge (new_edge->src->aux, bb);
1217               tree arg = PHI_ARG_DEF_FROM_EDGE (phi, old_edge);
1218               tree new_arg = arg;
1219
1220               walk_tree (&new_arg, copy_body_r, id, NULL);
1221               gcc_assert (new_arg);
1222               /* With return slot optimization we can end up with
1223                  non-gimple (foo *)&this->m, fix that here.  */
1224               if (TREE_CODE (new_arg) != SSA_NAME
1225                   && TREE_CODE (new_arg) != FUNCTION_DECL
1226                   && !is_gimple_val (new_arg))
1227                 {
1228                   tree stmts = NULL_TREE;
1229                   new_arg = force_gimple_operand (new_arg, &stmts,
1230                                                   true, NULL);
1231                   bsi_insert_on_edge_immediate (new_edge, stmts);
1232                 }
1233               add_phi_arg (new_phi, new_arg, new_edge);
1234             }
1235         }
1236     }
1237 }
1238
1239 /* Wrapper for remap_decl so it can be used as a callback.  */
1240 static tree
1241 remap_decl_1 (tree decl, void *data)
1242 {
1243   return remap_decl (decl, (copy_body_data *) data);
1244 }
1245
1246 /* Build struct function and associated datastructures for the new clone
1247    NEW_FNDECL to be build.  CALLEE_FNDECL is the original */
1248
1249 static void
1250 initialize_cfun (tree new_fndecl, tree callee_fndecl, gcov_type count,
1251                  int frequency)
1252 {
1253   struct function *new_cfun
1254      = (struct function *) ggc_alloc_cleared (sizeof (struct function));
1255   struct function *src_cfun = DECL_STRUCT_FUNCTION (callee_fndecl);
1256   int count_scale, frequency_scale;
1257
1258   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count)
1259     count_scale = (REG_BR_PROB_BASE * count
1260                    / ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count);
1261   else
1262     count_scale = 1;
1263
1264   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency)
1265     frequency_scale = (REG_BR_PROB_BASE * frequency
1266                        /
1267                        ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency);
1268   else
1269     frequency_scale = count_scale;
1270
1271   /* Register specific tree functions.  */
1272   tree_register_cfg_hooks ();
1273   *new_cfun = *DECL_STRUCT_FUNCTION (callee_fndecl);
1274   new_cfun->funcdef_no = get_next_funcdef_no ();
1275   VALUE_HISTOGRAMS (new_cfun) = NULL;
1276   new_cfun->unexpanded_var_list = NULL;
1277   new_cfun->cfg = NULL;
1278   new_cfun->decl = new_fndecl /*= copy_node (callee_fndecl)*/;
1279   DECL_STRUCT_FUNCTION (new_fndecl) = new_cfun;
1280   push_cfun (new_cfun);
1281   init_empty_tree_cfg ();
1282
1283   ENTRY_BLOCK_PTR->count =
1284     (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count * count_scale /
1285      REG_BR_PROB_BASE);
1286   ENTRY_BLOCK_PTR->frequency =
1287     (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency *
1288      frequency_scale / REG_BR_PROB_BASE);
1289   EXIT_BLOCK_PTR->count =
1290     (EXIT_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count * count_scale /
1291      REG_BR_PROB_BASE);
1292   EXIT_BLOCK_PTR->frequency =
1293     (EXIT_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency *
1294      frequency_scale / REG_BR_PROB_BASE);
1295   if (src_cfun->eh)
1296     init_eh_for_function ();
1297
1298   if (src_cfun->gimple_df)
1299     {
1300       init_tree_ssa ();
1301       cfun->gimple_df->in_ssa_p = true;
1302       init_ssa_operands ();
1303     }
1304   pop_cfun ();
1305 }
1306
1307 /* Make a copy of the body of FN so that it can be inserted inline in
1308    another function.  Walks FN via CFG, returns new fndecl.  */
1309
1310 static tree
1311 copy_cfg_body (copy_body_data * id, gcov_type count, int frequency,
1312                basic_block entry_block_map, basic_block exit_block_map)
1313 {
1314   tree callee_fndecl = id->src_fn;
1315   /* Original cfun for the callee, doesn't change.  */
1316   struct function *src_cfun = DECL_STRUCT_FUNCTION (callee_fndecl);
1317   struct function *cfun_to_copy;
1318   basic_block bb;
1319   tree new_fndecl = NULL;
1320   int count_scale, frequency_scale;
1321   int last;
1322
1323   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count)
1324     count_scale = (REG_BR_PROB_BASE * count
1325                    / ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count);
1326   else
1327     count_scale = 1;
1328
1329   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency)
1330     frequency_scale = (REG_BR_PROB_BASE * frequency
1331                        /
1332                        ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency);
1333   else
1334     frequency_scale = count_scale;
1335
1336   /* Register specific tree functions.  */
1337   tree_register_cfg_hooks ();
1338
1339   /* Must have a CFG here at this point.  */
1340   gcc_assert (ENTRY_BLOCK_PTR_FOR_FUNCTION
1341               (DECL_STRUCT_FUNCTION (callee_fndecl)));
1342
1343   cfun_to_copy = id->src_cfun = DECL_STRUCT_FUNCTION (callee_fndecl);
1344
1345
1346   ENTRY_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy)->aux = entry_block_map;
1347   EXIT_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy)->aux = exit_block_map;
1348   entry_block_map->aux = ENTRY_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy);
1349   exit_block_map->aux = EXIT_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy);
1350
1351   /* Duplicate any exception-handling regions.  */
1352   if (cfun->eh)
1353     {
1354       id->eh_region_offset
1355         = duplicate_eh_regions (cfun_to_copy, remap_decl_1, id,
1356                                 0, id->eh_region);
1357     }
1358   /* Use aux pointers to map the original blocks to copy.  */
1359   FOR_EACH_BB_FN (bb, cfun_to_copy)
1360     {
1361       basic_block new = copy_bb (id, bb, frequency_scale, count_scale);
1362       bb->aux = new;
1363       new->aux = bb;
1364     }
1365
1366   last = last_basic_block;
1367   /* Now that we've duplicated the blocks, duplicate their edges.  */
1368   FOR_ALL_BB_FN (bb, cfun_to_copy)
1369     copy_edges_for_bb (bb, count_scale, exit_block_map);
1370   if (gimple_in_ssa_p (cfun))
1371     FOR_ALL_BB_FN (bb, cfun_to_copy)
1372       copy_phis_for_bb (bb, id);
1373   FOR_ALL_BB_FN (bb, cfun_to_copy)
1374     {
1375       ((basic_block)bb->aux)->aux = NULL;
1376       bb->aux = NULL;
1377     }
1378   /* Zero out AUX fields of newly created block during EH edge
1379      insertion. */
1380   for (; last < last_basic_block; last++)
1381     BASIC_BLOCK (last)->aux = NULL;
1382   entry_block_map->aux = NULL;
1383   exit_block_map->aux = NULL;
1384
1385   return new_fndecl;
1386 }
1387
1388 /* Make a copy of the body of FN so that it can be inserted inline in
1389    another function.  */
1390
1391 static tree
1392 copy_generic_body (copy_body_data *id)
1393 {
1394   tree body;
1395   tree fndecl = id->src_fn;
1396
1397   body = DECL_SAVED_TREE (fndecl);
1398   walk_tree (&body, copy_body_r, id, NULL);
1399
1400   return body;
1401 }
1402
1403 static tree
1404 copy_body (copy_body_data *id, gcov_type count, int frequency,
1405            basic_block entry_block_map, basic_block exit_block_map)
1406 {
1407   tree fndecl = id->src_fn;
1408   tree body;
1409
1410   /* If this body has a CFG, walk CFG and copy.  */
1411   gcc_assert (ENTRY_BLOCK_PTR_FOR_FUNCTION (DECL_STRUCT_FUNCTION (fndecl)));
1412   body = copy_cfg_body (id, count, frequency, entry_block_map, exit_block_map);
1413
1414   return body;
1415 }
1416
1417 /* Return true if VALUE is an ADDR_EXPR of an automatic variable
1418    defined in function FN, or of a data member thereof.  */
1419
1420 static bool
1421 self_inlining_addr_expr (tree value, tree fn)
1422 {
1423   tree var;
1424
1425   if (TREE_CODE (value) != ADDR_EXPR)
1426     return false;
1427
1428   var = get_base_address (TREE_OPERAND (value, 0));
1429
1430   return var && auto_var_in_fn_p (var, fn);
1431 }
1432
1433 static void
1434 setup_one_parameter (copy_body_data *id, tree p, tree value, tree fn,
1435                      basic_block bb, tree *vars)
1436 {
1437   tree init_stmt;
1438   tree var;
1439   tree var_sub;
1440   tree rhs = value;
1441   tree def = (gimple_in_ssa_p (cfun)
1442               ? gimple_default_def (id->src_cfun, p) : NULL);
1443
1444   if (value
1445       && value != error_mark_node
1446       && !useless_type_conversion_p (TREE_TYPE (p), TREE_TYPE (value)))
1447     rhs = fold_build1 (NOP_EXPR, TREE_TYPE (p), value);
1448
1449   /* If the parameter is never assigned to, has no SSA_NAMEs created,
1450      we may not need to create a new variable here at all.  Instead, we may
1451      be able to just use the argument value.  */
1452   if (TREE_READONLY (p)
1453       && !TREE_ADDRESSABLE (p)
1454       && value && !TREE_SIDE_EFFECTS (value)
1455       && !def)
1456     {
1457       /* We may produce non-gimple trees by adding NOPs or introduce
1458          invalid sharing when operand is not really constant.
1459          It is not big deal to prohibit constant propagation here as
1460          we will constant propagate in DOM1 pass anyway.  */
1461       if (is_gimple_min_invariant (value)
1462           && useless_type_conversion_p (TREE_TYPE (p),
1463                                                  TREE_TYPE (value))
1464           /* We have to be very careful about ADDR_EXPR.  Make sure
1465              the base variable isn't a local variable of the inlined
1466              function, e.g., when doing recursive inlining, direct or
1467              mutually-recursive or whatever, which is why we don't
1468              just test whether fn == current_function_decl.  */
1469           && ! self_inlining_addr_expr (value, fn))
1470         {
1471           insert_decl_map (id, p, value);
1472           return;
1473         }
1474     }
1475
1476   /* Make an equivalent VAR_DECL.  Note that we must NOT remap the type
1477      here since the type of this decl must be visible to the calling
1478      function.  */
1479   var = copy_decl_to_var (p, id);
1480   if (gimple_in_ssa_p (cfun) && TREE_CODE (var) == VAR_DECL)
1481     {
1482       get_var_ann (var);
1483       add_referenced_var (var);
1484     }
1485
1486   /* See if the frontend wants to pass this by invisible reference.  If
1487      so, our new VAR_DECL will have REFERENCE_TYPE, and we need to
1488      replace uses of the PARM_DECL with dereferences.  */
1489   if (TREE_TYPE (var) != TREE_TYPE (p)
1490       && POINTER_TYPE_P (TREE_TYPE (var))
1491       && TREE_TYPE (TREE_TYPE (var)) == TREE_TYPE (p))
1492     {
1493       insert_decl_map (id, var, var);
1494       var_sub = build_fold_indirect_ref (var);
1495     }
1496   else
1497     var_sub = var;
1498
1499   /* Register the VAR_DECL as the equivalent for the PARM_DECL;
1500      that way, when the PARM_DECL is encountered, it will be
1501      automatically replaced by the VAR_DECL.  */
1502   insert_decl_map (id, p, var_sub);
1503
1504   /* Declare this new variable.  */
1505   TREE_CHAIN (var) = *vars;
1506   *vars = var;
1507
1508   /* Make gimplifier happy about this variable.  */
1509   DECL_SEEN_IN_BIND_EXPR_P (var) = 1;
1510
1511   /* Even if P was TREE_READONLY, the new VAR should not be.
1512      In the original code, we would have constructed a
1513      temporary, and then the function body would have never
1514      changed the value of P.  However, now, we will be
1515      constructing VAR directly.  The constructor body may
1516      change its value multiple times as it is being
1517      constructed.  Therefore, it must not be TREE_READONLY;
1518      the back-end assumes that TREE_READONLY variable is
1519      assigned to only once.  */
1520   if (TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (p)))
1521     TREE_READONLY (var) = 0;
1522
1523   /* If there is no setup required and we are in SSA, take the easy route
1524      replacing all SSA names representing the function parameter by the
1525      SSA name passed to function.
1526
1527      We need to construct map for the variable anyway as it might be used
1528      in different SSA names when parameter is set in function.
1529
1530      FIXME: This usually kills the last connection in between inlined
1531      function parameter and the actual value in debug info.  Can we do
1532      better here?  If we just inserted the statement, copy propagation
1533      would kill it anyway as it always did in older versions of GCC.
1534
1535      We might want to introduce a notion that single SSA_NAME might
1536      represent multiple variables for purposes of debugging. */
1537   if (gimple_in_ssa_p (cfun) && rhs && def && is_gimple_reg (p)
1538       && (TREE_CODE (rhs) == SSA_NAME
1539           || is_gimple_min_invariant (rhs))
1540       && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def))
1541     {
1542       insert_decl_map (id, def, rhs);
1543       return;
1544     }
1545
1546   /* If the value of argument is never used, don't care about initializing
1547      it.  */
1548   if (gimple_in_ssa_p (cfun) && !def && is_gimple_reg (p))
1549     {
1550       gcc_assert (!value || !TREE_SIDE_EFFECTS (value));
1551       return;
1552     }
1553
1554   /* Initialize this VAR_DECL from the equivalent argument.  Convert
1555      the argument to the proper type in case it was promoted.  */
1556   if (value)
1557     {
1558       block_stmt_iterator bsi = bsi_last (bb);
1559
1560       if (rhs == error_mark_node)
1561         {
1562           insert_decl_map (id, p, var_sub);
1563           return;
1564         }
1565
1566       STRIP_USELESS_TYPE_CONVERSION (rhs);
1567
1568       /* We want to use GIMPLE_MODIFY_STMT, not INIT_EXPR here so that we
1569          keep our trees in gimple form.  */
1570       if (def && gimple_in_ssa_p (cfun) && is_gimple_reg (p))
1571         {
1572           def = remap_ssa_name (def, id);
1573           init_stmt = build_gimple_modify_stmt (def, rhs);
1574           SSA_NAME_DEF_STMT (def) = init_stmt;
1575           SSA_NAME_IS_DEFAULT_DEF (def) = 0;
1576           set_default_def (var, NULL);
1577         }
1578       else
1579         init_stmt = build_gimple_modify_stmt (var, rhs);
1580
1581       /* If we did not create a gimple value and we did not create a gimple
1582          cast of a gimple value, then we will need to gimplify INIT_STMTS
1583          at the end.  Note that is_gimple_cast only checks the outer
1584          tree code, not its operand.  Thus the explicit check that its
1585          operand is a gimple value.  */
1586       if ((!is_gimple_val (rhs)
1587           && (!is_gimple_cast (rhs)
1588               || !is_gimple_val (TREE_OPERAND (rhs, 0))))
1589           || !is_gimple_reg (var))
1590         {
1591           tree_stmt_iterator i;
1592
1593           push_gimplify_context ();
1594           gimplify_stmt (&init_stmt);
1595           if (gimple_in_ssa_p (cfun)
1596               && init_stmt && TREE_CODE (init_stmt) == STATEMENT_LIST)
1597             {
1598               /* The replacement can expose previously unreferenced
1599                  variables.  */
1600               for (i = tsi_start (init_stmt); !tsi_end_p (i); tsi_next (&i))
1601                 find_new_referenced_vars (tsi_stmt_ptr (i));
1602              }
1603           pop_gimplify_context (NULL);
1604         }
1605
1606       /* If VAR represents a zero-sized variable, it's possible that the
1607          assignment statment may result in no gimple statements.  */
1608       if (init_stmt)
1609         bsi_insert_after (&bsi, init_stmt, BSI_NEW_STMT);
1610       if (gimple_in_ssa_p (cfun))
1611         for (;!bsi_end_p (bsi); bsi_next (&bsi))
1612           mark_symbols_for_renaming (bsi_stmt (bsi));
1613     }
1614 }
1615
1616 /* Generate code to initialize the parameters of the function at the
1617    top of the stack in ID from the CALL_EXPR EXP.  */
1618
1619 static void
1620 initialize_inlined_parameters (copy_body_data *id, tree exp,
1621                                tree fn, basic_block bb)
1622 {
1623   tree parms;
1624   tree a;
1625   tree p;
1626   tree vars = NULL_TREE;
1627   call_expr_arg_iterator iter;
1628   tree static_chain = CALL_EXPR_STATIC_CHAIN (exp);
1629
1630   /* Figure out what the parameters are.  */
1631   parms = DECL_ARGUMENTS (fn);
1632
1633   /* Loop through the parameter declarations, replacing each with an
1634      equivalent VAR_DECL, appropriately initialized.  */
1635   for (p = parms, a = first_call_expr_arg (exp, &iter); p;
1636        a = next_call_expr_arg (&iter), p = TREE_CHAIN (p))
1637     setup_one_parameter (id, p, a, fn, bb, &vars);
1638
1639   /* Initialize the static chain.  */
1640   p = DECL_STRUCT_FUNCTION (fn)->static_chain_decl;
1641   gcc_assert (fn != current_function_decl);
1642   if (p)
1643     {
1644       /* No static chain?  Seems like a bug in tree-nested.c.  */
1645       gcc_assert (static_chain);
1646
1647       setup_one_parameter (id, p, static_chain, fn, bb, &vars);
1648     }
1649
1650   declare_inline_vars (id->block, vars);
1651 }
1652
1653 /* Declare a return variable to replace the RESULT_DECL for the
1654    function we are calling.  An appropriate DECL_STMT is returned.
1655    The USE_STMT is filled to contain a use of the declaration to
1656    indicate the return value of the function.
1657
1658    RETURN_SLOT, if non-null is place where to store the result.  It
1659    is set only for CALL_EXPR_RETURN_SLOT_OPT.  MODIFY_DEST, if non-null,
1660    was the LHS of the GIMPLE_MODIFY_STMT to which this call is the RHS.
1661
1662    The return value is a (possibly null) value that is the result of the
1663    function as seen by the callee.  *USE_P is a (possibly null) value that
1664    holds the result as seen by the caller.  */
1665
1666 static tree
1667 declare_return_variable (copy_body_data *id, tree return_slot, tree modify_dest,
1668                          tree *use_p)
1669 {
1670   tree callee = id->src_fn;
1671   tree caller = id->dst_fn;
1672   tree result = DECL_RESULT (callee);
1673   tree callee_type = TREE_TYPE (result);
1674   tree caller_type = TREE_TYPE (TREE_TYPE (callee));
1675   tree var, use;
1676
1677   /* We don't need to do anything for functions that don't return
1678      anything.  */
1679   if (!result || VOID_TYPE_P (callee_type))
1680     {
1681       *use_p = NULL_TREE;
1682       return NULL_TREE;
1683     }
1684
1685   /* If there was a return slot, then the return value is the
1686      dereferenced address of that object.  */
1687   if (return_slot)
1688     {
1689       /* The front end shouldn't have used both return_slot and
1690          a modify expression.  */
1691       gcc_assert (!modify_dest);
1692       if (DECL_BY_REFERENCE (result))
1693         {
1694           tree return_slot_addr = build_fold_addr_expr (return_slot);
1695           STRIP_USELESS_TYPE_CONVERSION (return_slot_addr);
1696
1697           /* We are going to construct *&return_slot and we can't do that
1698              for variables believed to be not addressable. 
1699
1700              FIXME: This check possibly can match, because values returned
1701              via return slot optimization are not believed to have address
1702              taken by alias analysis.  */
1703           gcc_assert (TREE_CODE (return_slot) != SSA_NAME);
1704           if (gimple_in_ssa_p (cfun))
1705             {
1706               HOST_WIDE_INT bitsize;
1707               HOST_WIDE_INT bitpos;
1708               tree offset;
1709               enum machine_mode mode;
1710               int unsignedp;
1711               int volatilep;
1712               tree base;
1713               base = get_inner_reference (return_slot, &bitsize, &bitpos,
1714                                           &offset,
1715                                           &mode, &unsignedp, &volatilep,
1716                                           false);
1717               if (TREE_CODE (base) == INDIRECT_REF)
1718                 base = TREE_OPERAND (base, 0);
1719               if (TREE_CODE (base) == SSA_NAME)
1720                 base = SSA_NAME_VAR (base);
1721               mark_sym_for_renaming (base);
1722             }
1723           var = return_slot_addr;
1724         }
1725       else
1726         {
1727           var = return_slot;
1728           gcc_assert (TREE_CODE (var) != SSA_NAME);
1729           TREE_ADDRESSABLE (var) |= TREE_ADDRESSABLE (result);
1730         }
1731       if ((TREE_CODE (TREE_TYPE (result)) == COMPLEX_TYPE
1732            || TREE_CODE (TREE_TYPE (result)) == VECTOR_TYPE)
1733           && !DECL_GIMPLE_REG_P (result)
1734           && DECL_P (var))
1735         DECL_GIMPLE_REG_P (var) = 0;
1736       use = NULL;
1737       goto done;
1738     }
1739
1740   /* All types requiring non-trivial constructors should have been handled.  */
1741   gcc_assert (!TREE_ADDRESSABLE (callee_type));
1742
1743   /* Attempt to avoid creating a new temporary variable.  */
1744   if (modify_dest
1745       && TREE_CODE (modify_dest) != SSA_NAME)
1746     {
1747       bool use_it = false;
1748
1749       /* We can't use MODIFY_DEST if there's type promotion involved.  */
1750       if (!useless_type_conversion_p (callee_type, caller_type))
1751         use_it = false;
1752
1753       /* ??? If we're assigning to a variable sized type, then we must
1754          reuse the destination variable, because we've no good way to
1755          create variable sized temporaries at this point.  */
1756       else if (TREE_CODE (TYPE_SIZE_UNIT (caller_type)) != INTEGER_CST)
1757         use_it = true;
1758
1759       /* If the callee cannot possibly modify MODIFY_DEST, then we can
1760          reuse it as the result of the call directly.  Don't do this if
1761          it would promote MODIFY_DEST to addressable.  */
1762       else if (TREE_ADDRESSABLE (result))
1763         use_it = false;
1764       else
1765         {
1766           tree base_m = get_base_address (modify_dest);
1767
1768           /* If the base isn't a decl, then it's a pointer, and we don't
1769              know where that's going to go.  */
1770           if (!DECL_P (base_m))
1771             use_it = false;
1772           else if (is_global_var (base_m))
1773             use_it = false;
1774           else if ((TREE_CODE (TREE_TYPE (result)) == COMPLEX_TYPE
1775                     || TREE_CODE (TREE_TYPE (result)) == VECTOR_TYPE)
1776                    && !DECL_GIMPLE_REG_P (result)
1777                    && DECL_GIMPLE_REG_P (base_m))
1778             use_it = false;
1779           else if (!TREE_ADDRESSABLE (base_m))
1780             use_it = true;
1781         }
1782
1783       if (use_it)
1784         {
1785           var = modify_dest;
1786           use = NULL;
1787           goto done;
1788         }
1789     }
1790
1791   gcc_assert (TREE_CODE (TYPE_SIZE_UNIT (callee_type)) == INTEGER_CST);
1792
1793   var = copy_result_decl_to_var (result, id);
1794   if (gimple_in_ssa_p (cfun))
1795     {
1796       get_var_ann (var);
1797       add_referenced_var (var);
1798     }
1799
1800   DECL_SEEN_IN_BIND_EXPR_P (var) = 1;
1801   DECL_STRUCT_FUNCTION (caller)->unexpanded_var_list
1802     = tree_cons (NULL_TREE, var,
1803                  DECL_STRUCT_FUNCTION (caller)->unexpanded_var_list);
1804
1805   /* Do not have the rest of GCC warn about this variable as it should
1806      not be visible to the user.  */
1807   TREE_NO_WARNING (var) = 1;
1808
1809   declare_inline_vars (id->block, var);
1810
1811   /* Build the use expr.  If the return type of the function was
1812      promoted, convert it back to the expected type.  */
1813   use = var;
1814   if (!useless_type_conversion_p (caller_type, TREE_TYPE (var)))
1815     use = fold_convert (caller_type, var);
1816     
1817   STRIP_USELESS_TYPE_CONVERSION (use);
1818
1819   if (DECL_BY_REFERENCE (result))
1820     var = build_fold_addr_expr (var);
1821
1822  done:
1823   /* Register the VAR_DECL as the equivalent for the RESULT_DECL; that
1824      way, when the RESULT_DECL is encountered, it will be
1825      automatically replaced by the VAR_DECL.  */
1826   insert_decl_map (id, result, var);
1827
1828   /* Remember this so we can ignore it in remap_decls.  */
1829   id->retvar = var;
1830
1831   *use_p = use;
1832   return var;
1833 }
1834
1835 /* Returns nonzero if a function can be inlined as a tree.  */
1836
1837 bool
1838 tree_inlinable_function_p (tree fn)
1839 {
1840   return inlinable_function_p (fn);
1841 }
1842
1843 static const char *inline_forbidden_reason;
1844
1845 static tree
1846 inline_forbidden_p_1 (tree *nodep, int *walk_subtrees ATTRIBUTE_UNUSED,
1847                       void *fnp)
1848 {
1849   tree node = *nodep;
1850   tree fn = (tree) fnp;
1851   tree t;
1852
1853   switch (TREE_CODE (node))
1854     {
1855     case CALL_EXPR:
1856       /* Refuse to inline alloca call unless user explicitly forced so as
1857          this may change program's memory overhead drastically when the
1858          function using alloca is called in loop.  In GCC present in
1859          SPEC2000 inlining into schedule_block cause it to require 2GB of
1860          RAM instead of 256MB.  */
1861       if (alloca_call_p (node)
1862           && !lookup_attribute ("always_inline", DECL_ATTRIBUTES (fn)))
1863         {
1864           inline_forbidden_reason
1865             = G_("function %q+F can never be inlined because it uses "
1866                  "alloca (override using the always_inline attribute)");
1867           return node;
1868         }
1869       t = get_callee_fndecl (node);
1870       if (! t)
1871         break;
1872
1873       /* We cannot inline functions that call setjmp.  */
1874       if (setjmp_call_p (t))
1875         {
1876           inline_forbidden_reason
1877             = G_("function %q+F can never be inlined because it uses setjmp");
1878           return node;
1879         }
1880
1881       if (DECL_BUILT_IN_CLASS (t) == BUILT_IN_NORMAL)
1882         switch (DECL_FUNCTION_CODE (t))
1883           {
1884             /* We cannot inline functions that take a variable number of
1885                arguments.  */
1886           case BUILT_IN_VA_START:
1887           case BUILT_IN_STDARG_START:
1888           case BUILT_IN_NEXT_ARG:
1889           case BUILT_IN_VA_END:
1890             inline_forbidden_reason
1891               = G_("function %q+F can never be inlined because it "
1892                    "uses variable argument lists");
1893             return node;
1894
1895           case BUILT_IN_LONGJMP:
1896             /* We can't inline functions that call __builtin_longjmp at
1897                all.  The non-local goto machinery really requires the
1898                destination be in a different function.  If we allow the
1899                function calling __builtin_longjmp to be inlined into the
1900                function calling __builtin_setjmp, Things will Go Awry.  */
1901             inline_forbidden_reason
1902               = G_("function %q+F can never be inlined because "
1903                    "it uses setjmp-longjmp exception handling");
1904             return node;
1905
1906           case BUILT_IN_NONLOCAL_GOTO:
1907             /* Similarly.  */
1908             inline_forbidden_reason
1909               = G_("function %q+F can never be inlined because "
1910                    "it uses non-local goto");
1911             return node;
1912
1913           case BUILT_IN_RETURN:
1914           case BUILT_IN_APPLY_ARGS:
1915             /* If a __builtin_apply_args caller would be inlined,
1916                it would be saving arguments of the function it has
1917                been inlined into.  Similarly __builtin_return would
1918                return from the function the inline has been inlined into.  */
1919             inline_forbidden_reason
1920               = G_("function %q+F can never be inlined because "
1921                    "it uses __builtin_return or __builtin_apply_args");
1922             return node;
1923
1924           default:
1925             break;
1926           }
1927       break;
1928
1929     case GOTO_EXPR:
1930       t = TREE_OPERAND (node, 0);
1931
1932       /* We will not inline a function which uses computed goto.  The
1933          addresses of its local labels, which may be tucked into
1934          global storage, are of course not constant across
1935          instantiations, which causes unexpected behavior.  */
1936       if (TREE_CODE (t) != LABEL_DECL)
1937         {
1938           inline_forbidden_reason
1939             = G_("function %q+F can never be inlined "
1940                  "because it contains a computed goto");
1941           return node;
1942         }
1943       break;
1944
1945     case LABEL_EXPR:
1946       t = TREE_OPERAND (node, 0);
1947       if (DECL_NONLOCAL (t))
1948         {
1949           /* We cannot inline a function that receives a non-local goto
1950              because we cannot remap the destination label used in the
1951              function that is performing the non-local goto.  */
1952           inline_forbidden_reason
1953             = G_("function %q+F can never be inlined "
1954                  "because it receives a non-local goto");
1955           return node;
1956         }
1957       break;
1958
1959     case RECORD_TYPE:
1960     case UNION_TYPE:
1961       /* We cannot inline a function of the form
1962
1963            void F (int i) { struct S { int ar[i]; } s; }
1964
1965          Attempting to do so produces a catch-22.
1966          If walk_tree examines the TYPE_FIELDS chain of RECORD_TYPE/
1967          UNION_TYPE nodes, then it goes into infinite recursion on a
1968          structure containing a pointer to its own type.  If it doesn't,
1969          then the type node for S doesn't get adjusted properly when
1970          F is inlined. 
1971
1972          ??? This is likely no longer true, but it's too late in the 4.0
1973          cycle to try to find out.  This should be checked for 4.1.  */
1974       for (t = TYPE_FIELDS (node); t; t = TREE_CHAIN (t))
1975         if (variably_modified_type_p (TREE_TYPE (t), NULL))
1976           {
1977             inline_forbidden_reason
1978               = G_("function %q+F can never be inlined "
1979                    "because it uses variable sized variables");
1980             return node;
1981           }
1982
1983     default:
1984       break;
1985     }
1986
1987   return NULL_TREE;
1988 }
1989
1990 static tree
1991 inline_forbidden_p_2 (tree *nodep, int *walk_subtrees,
1992                       void *fnp)
1993 {
1994   tree node = *nodep;
1995   tree fn = (tree) fnp;
1996
1997   if (TREE_CODE (node) == LABEL_DECL && DECL_CONTEXT (node) == fn)
1998     {
1999       inline_forbidden_reason
2000         = G_("function %q+F can never be inlined "
2001              "because it saves address of local label in a static variable");
2002       return node;
2003     }
2004
2005   if (TYPE_P (node))
2006     *walk_subtrees = 0;
2007
2008   return NULL_TREE;
2009 }
2010
2011 /* Return subexpression representing possible alloca call, if any.  */
2012 static tree
2013 inline_forbidden_p (tree fndecl)
2014 {
2015   location_t saved_loc = input_location;
2016   block_stmt_iterator bsi;
2017   basic_block bb;
2018   tree ret = NULL_TREE;
2019   struct function *fun = DECL_STRUCT_FUNCTION (fndecl);
2020   tree step;
2021
2022   FOR_EACH_BB_FN (bb, fun)
2023     for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
2024       {
2025         ret = walk_tree_without_duplicates (bsi_stmt_ptr (bsi),
2026                                             inline_forbidden_p_1, fndecl);
2027         if (ret)
2028           goto egress;
2029       }
2030
2031   for (step = fun->unexpanded_var_list; step; step = TREE_CHAIN (step))
2032     {
2033       tree decl = TREE_VALUE (step);
2034       if (TREE_CODE (decl) == VAR_DECL
2035           && TREE_STATIC (decl)
2036           && !DECL_EXTERNAL (decl)
2037           && DECL_INITIAL (decl))
2038         ret = walk_tree_without_duplicates (&DECL_INITIAL (decl),
2039                                             inline_forbidden_p_2, fndecl);
2040         if (ret)
2041           goto egress;
2042     }
2043
2044 egress:
2045   input_location = saved_loc;
2046   return ret;
2047 }
2048
2049 /* Returns nonzero if FN is a function that does not have any
2050    fundamental inline blocking properties.  */
2051
2052 static bool
2053 inlinable_function_p (tree fn)
2054 {
2055   bool inlinable = true;
2056   bool do_warning;
2057   tree always_inline;
2058
2059   /* If we've already decided this function shouldn't be inlined,
2060      there's no need to check again.  */
2061   if (DECL_UNINLINABLE (fn))
2062     return false;
2063
2064   /* We only warn for functions declared `inline' by the user.  */
2065   do_warning = (warn_inline
2066                 && DECL_INLINE (fn)
2067                 && DECL_DECLARED_INLINE_P (fn)
2068                 && !DECL_IN_SYSTEM_HEADER (fn));
2069
2070   always_inline = lookup_attribute ("always_inline", DECL_ATTRIBUTES (fn));
2071
2072   if (flag_really_no_inline
2073       && always_inline == NULL)
2074     {
2075       if (do_warning)
2076         warning (OPT_Winline, "function %q+F can never be inlined because it "
2077                  "is suppressed using -fno-inline", fn);
2078       inlinable = false;
2079     }
2080
2081   /* Don't auto-inline anything that might not be bound within
2082      this unit of translation.  */
2083   else if (!DECL_DECLARED_INLINE_P (fn)
2084            && DECL_REPLACEABLE_P (fn))
2085     inlinable = false;
2086
2087   else if (!function_attribute_inlinable_p (fn))
2088     {
2089       if (do_warning)
2090         warning (OPT_Winline, "function %q+F can never be inlined because it "
2091                  "uses attributes conflicting with inlining", fn);
2092       inlinable = false;
2093     }
2094
2095   /* If we don't have the function body available, we can't inline it.
2096      However, this should not be recorded since we also get here for
2097      forward declared inline functions.  Therefore, return at once.  */
2098   if (!DECL_SAVED_TREE (fn))
2099     return false;
2100
2101   /* If we're not inlining at all, then we cannot inline this function.  */
2102   else if (!flag_inline_trees)
2103     inlinable = false;
2104
2105   /* Only try to inline functions if DECL_INLINE is set.  This should be
2106      true for all functions declared `inline', and for all other functions
2107      as well with -finline-functions.
2108
2109      Don't think of disregarding DECL_INLINE when flag_inline_trees == 2;
2110      it's the front-end that must set DECL_INLINE in this case, because
2111      dwarf2out loses if a function that does not have DECL_INLINE set is
2112      inlined anyway.  That is why we have both DECL_INLINE and
2113      DECL_DECLARED_INLINE_P.  */
2114   /* FIXME: When flag_inline_trees dies, the check for flag_unit_at_a_time
2115             here should be redundant.  */
2116   else if (!DECL_INLINE (fn) && !flag_unit_at_a_time)
2117     inlinable = false;
2118
2119   else if (inline_forbidden_p (fn))
2120     {
2121       /* See if we should warn about uninlinable functions.  Previously,
2122          some of these warnings would be issued while trying to expand
2123          the function inline, but that would cause multiple warnings
2124          about functions that would for example call alloca.  But since
2125          this a property of the function, just one warning is enough.
2126          As a bonus we can now give more details about the reason why a
2127          function is not inlinable.  */
2128       if (always_inline)
2129         sorry (inline_forbidden_reason, fn);
2130       else if (do_warning)
2131         warning (OPT_Winline, inline_forbidden_reason, fn);
2132
2133       inlinable = false;
2134     }
2135
2136   /* Squirrel away the result so that we don't have to check again.  */
2137   DECL_UNINLINABLE (fn) = !inlinable;
2138
2139   return inlinable;
2140 }
2141
2142 /* Estimate the cost of a memory move.  Use machine dependent
2143    word size and take possible memcpy call into account.  */
2144
2145 int
2146 estimate_move_cost (tree type)
2147 {
2148   HOST_WIDE_INT size;
2149
2150   size = int_size_in_bytes (type);
2151
2152   if (size < 0 || size > MOVE_MAX_PIECES * MOVE_RATIO)
2153     /* Cost of a memcpy call, 3 arguments and the call.  */
2154     return 4;
2155   else
2156     return ((size + MOVE_MAX_PIECES - 1) / MOVE_MAX_PIECES);
2157 }
2158
2159 /* Arguments for estimate_num_insns_1.  */
2160
2161 struct eni_data
2162 {
2163   /* Used to return the number of insns.  */
2164   int count;
2165
2166   /* Weights of various constructs.  */
2167   eni_weights *weights;
2168 };
2169
2170 /* Used by estimate_num_insns.  Estimate number of instructions seen
2171    by given statement.  */
2172
2173 static tree
2174 estimate_num_insns_1 (tree *tp, int *walk_subtrees, void *data)
2175 {
2176   struct eni_data *d = data;
2177   tree x = *tp;
2178   unsigned cost;
2179
2180   if (IS_TYPE_OR_DECL_P (x))
2181     {
2182       *walk_subtrees = 0;
2183       return NULL;
2184     }
2185   /* Assume that constants and references counts nothing.  These should
2186      be majorized by amount of operations among them we count later
2187      and are common target of CSE and similar optimizations.  */
2188   else if (CONSTANT_CLASS_P (x) || REFERENCE_CLASS_P (x))
2189     return NULL;
2190
2191   switch (TREE_CODE (x))
2192     {
2193     /* Containers have no cost.  */
2194     case TREE_LIST:
2195     case TREE_VEC:
2196     case BLOCK:
2197     case COMPONENT_REF:
2198     case BIT_FIELD_REF:
2199     case INDIRECT_REF:
2200     case ALIGN_INDIRECT_REF:
2201     case MISALIGNED_INDIRECT_REF:
2202     case ARRAY_REF:
2203     case ARRAY_RANGE_REF:
2204     case OBJ_TYPE_REF:
2205     case EXC_PTR_EXPR: /* ??? */
2206     case FILTER_EXPR: /* ??? */
2207     case COMPOUND_EXPR:
2208     case BIND_EXPR:
2209     case WITH_CLEANUP_EXPR:
2210     case NOP_EXPR:
2211     case CONVERT_EXPR:
2212     case VIEW_CONVERT_EXPR:
2213     case SAVE_EXPR:
2214     case ADDR_EXPR:
2215     case COMPLEX_EXPR:
2216     case RANGE_EXPR:
2217     case CASE_LABEL_EXPR:
2218     case SSA_NAME:
2219     case CATCH_EXPR:
2220     case EH_FILTER_EXPR:
2221     case STATEMENT_LIST:
2222     case ERROR_MARK:
2223     case NON_LVALUE_EXPR:
2224     case FDESC_EXPR:
2225     case VA_ARG_EXPR:
2226     case TRY_CATCH_EXPR:
2227     case TRY_FINALLY_EXPR:
2228     case LABEL_EXPR:
2229     case GOTO_EXPR:
2230     case RETURN_EXPR:
2231     case EXIT_EXPR:
2232     case LOOP_EXPR:
2233     case PHI_NODE:
2234     case WITH_SIZE_EXPR:
2235     case OMP_CLAUSE:
2236     case OMP_RETURN:
2237     case OMP_CONTINUE:
2238     case OMP_SECTIONS_SWITCH:
2239     case OMP_ATOMIC_STORE:
2240       break;
2241
2242     /* We don't account constants for now.  Assume that the cost is amortized
2243        by operations that do use them.  We may re-consider this decision once
2244        we are able to optimize the tree before estimating its size and break
2245        out static initializers.  */
2246     case IDENTIFIER_NODE:
2247     case INTEGER_CST:
2248     case REAL_CST:
2249     case FIXED_CST:
2250     case COMPLEX_CST:
2251     case VECTOR_CST:
2252     case STRING_CST:
2253       *walk_subtrees = 0;
2254       return NULL;
2255
2256       /* CHANGE_DYNAMIC_TYPE_EXPR explicitly expands to nothing.  */
2257     case CHANGE_DYNAMIC_TYPE_EXPR:
2258       *walk_subtrees = 0;
2259       return NULL;
2260
2261     /* Try to estimate the cost of assignments.  We have three cases to
2262        deal with:
2263         1) Simple assignments to registers;
2264         2) Stores to things that must live in memory.  This includes
2265            "normal" stores to scalars, but also assignments of large
2266            structures, or constructors of big arrays;
2267         3) TARGET_EXPRs.
2268
2269        Let us look at the first two cases, assuming we have "a = b + C":
2270        <GIMPLE_MODIFY_STMT <var_decl "a">
2271                            <plus_expr <var_decl "b"> <constant C>>
2272        If "a" is a GIMPLE register, the assignment to it is free on almost
2273        any target, because "a" usually ends up in a real register.  Hence
2274        the only cost of this expression comes from the PLUS_EXPR, and we
2275        can ignore the GIMPLE_MODIFY_STMT.
2276        If "a" is not a GIMPLE register, the assignment to "a" will most
2277        likely be a real store, so the cost of the GIMPLE_MODIFY_STMT is the cost
2278        of moving something into "a", which we compute using the function
2279        estimate_move_cost.
2280
2281        The third case deals with TARGET_EXPRs, for which the semantics are
2282        that a temporary is assigned, unless the TARGET_EXPR itself is being
2283        assigned to something else.  In the latter case we do not need the
2284        temporary.  E.g. in:
2285                 <GIMPLE_MODIFY_STMT <var_decl "a"> <target_expr>>, the
2286        GIMPLE_MODIFY_STMT is free.  */
2287     case INIT_EXPR:
2288     case GIMPLE_MODIFY_STMT:
2289       /* Is the right and side a TARGET_EXPR?  */
2290       if (TREE_CODE (GENERIC_TREE_OPERAND (x, 1)) == TARGET_EXPR)
2291         break;
2292       /* ... fall through ...  */
2293
2294     case TARGET_EXPR:
2295       x = GENERIC_TREE_OPERAND (x, 0);
2296       /* Is this an assignments to a register?  */
2297       if (is_gimple_reg (x))
2298         break;
2299       /* Otherwise it's a store, so fall through to compute the move cost.  */
2300
2301     case CONSTRUCTOR:
2302       d->count += estimate_move_cost (TREE_TYPE (x));
2303       break;
2304
2305     /* Assign cost of 1 to usual operations.
2306        ??? We may consider mapping RTL costs to this.  */
2307     case COND_EXPR:
2308     case VEC_COND_EXPR:
2309
2310     case PLUS_EXPR:
2311     case POINTER_PLUS_EXPR:
2312     case MINUS_EXPR:
2313     case MULT_EXPR:
2314
2315     case FIXED_CONVERT_EXPR:
2316     case FIX_TRUNC_EXPR:
2317
2318     case NEGATE_EXPR:
2319     case FLOAT_EXPR:
2320     case MIN_EXPR:
2321     case MAX_EXPR:
2322     case ABS_EXPR:
2323
2324     case LSHIFT_EXPR:
2325     case RSHIFT_EXPR:
2326     case LROTATE_EXPR:
2327     case RROTATE_EXPR:
2328     case VEC_LSHIFT_EXPR:
2329     case VEC_RSHIFT_EXPR:
2330
2331     case BIT_IOR_EXPR:
2332     case BIT_XOR_EXPR:
2333     case BIT_AND_EXPR:
2334     case BIT_NOT_EXPR:
2335
2336     case TRUTH_ANDIF_EXPR:
2337     case TRUTH_ORIF_EXPR:
2338     case TRUTH_AND_EXPR:
2339     case TRUTH_OR_EXPR:
2340     case TRUTH_XOR_EXPR:
2341     case TRUTH_NOT_EXPR:
2342
2343     case LT_EXPR:
2344     case LE_EXPR:
2345     case GT_EXPR:
2346     case GE_EXPR:
2347     case EQ_EXPR:
2348     case NE_EXPR:
2349     case ORDERED_EXPR:
2350     case UNORDERED_EXPR:
2351
2352     case UNLT_EXPR:
2353     case UNLE_EXPR:
2354     case UNGT_EXPR:
2355     case UNGE_EXPR:
2356     case UNEQ_EXPR:
2357     case LTGT_EXPR:
2358
2359     case CONJ_EXPR:
2360
2361     case PREDECREMENT_EXPR:
2362     case PREINCREMENT_EXPR:
2363     case POSTDECREMENT_EXPR:
2364     case POSTINCREMENT_EXPR:
2365
2366     case ASM_EXPR:
2367
2368     case REALIGN_LOAD_EXPR:
2369
2370     case REDUC_MAX_EXPR:
2371     case REDUC_MIN_EXPR:
2372     case REDUC_PLUS_EXPR:
2373     case WIDEN_SUM_EXPR:
2374     case DOT_PROD_EXPR: 
2375     case VEC_WIDEN_MULT_HI_EXPR:
2376     case VEC_WIDEN_MULT_LO_EXPR:
2377     case VEC_UNPACK_HI_EXPR:
2378     case VEC_UNPACK_LO_EXPR:
2379     case VEC_UNPACK_FLOAT_HI_EXPR:
2380     case VEC_UNPACK_FLOAT_LO_EXPR:
2381     case VEC_PACK_TRUNC_EXPR:
2382     case VEC_PACK_SAT_EXPR:
2383     case VEC_PACK_FIX_TRUNC_EXPR:
2384
2385     case WIDEN_MULT_EXPR:
2386
2387     case VEC_EXTRACT_EVEN_EXPR:
2388     case VEC_EXTRACT_ODD_EXPR:
2389     case VEC_INTERLEAVE_HIGH_EXPR:
2390     case VEC_INTERLEAVE_LOW_EXPR:
2391
2392     case RESX_EXPR:
2393       d->count += 1;
2394       break;
2395
2396     case SWITCH_EXPR:
2397       /* Take into account cost of the switch + guess 2 conditional jumps for
2398          each case label.  
2399
2400          TODO: once the switch expansion logic is sufficiently separated, we can
2401          do better job on estimating cost of the switch.  */
2402       d->count += TREE_VEC_LENGTH (SWITCH_LABELS (x)) * 2;
2403       break;
2404
2405     /* Few special cases of expensive operations.  This is useful
2406        to avoid inlining on functions having too many of these.  */
2407     case TRUNC_DIV_EXPR:
2408     case CEIL_DIV_EXPR:
2409     case FLOOR_DIV_EXPR:
2410     case ROUND_DIV_EXPR:
2411     case EXACT_DIV_EXPR:
2412     case TRUNC_MOD_EXPR:
2413     case CEIL_MOD_EXPR:
2414     case FLOOR_MOD_EXPR:
2415     case ROUND_MOD_EXPR:
2416     case RDIV_EXPR:
2417       d->count += d->weights->div_mod_cost;
2418       break;
2419     case CALL_EXPR:
2420       {
2421         tree decl = get_callee_fndecl (x);
2422
2423         if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
2424           cost = d->weights->target_builtin_call_cost;
2425         else
2426           cost = d->weights->call_cost;
2427         
2428         if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
2429           switch (DECL_FUNCTION_CODE (decl))
2430             {
2431             case BUILT_IN_CONSTANT_P:
2432               *walk_subtrees = 0;
2433               return NULL_TREE;
2434             case BUILT_IN_EXPECT:
2435               return NULL_TREE;
2436             /* Prefetch instruction is not expensive.  */
2437             case BUILT_IN_PREFETCH:
2438               cost = 1;
2439               break;
2440             default:
2441               break;
2442             }
2443
2444         /* Our cost must be kept in sync with cgraph_estimate_size_after_inlining
2445            that does use function declaration to figure out the arguments.  */
2446         if (!decl)
2447           {
2448             tree a;
2449             call_expr_arg_iterator iter;
2450             FOR_EACH_CALL_EXPR_ARG (a, iter, x)
2451               d->count += estimate_move_cost (TREE_TYPE (a));
2452           }
2453         else
2454           {
2455             tree arg;
2456             for (arg = DECL_ARGUMENTS (decl); arg; arg = TREE_CHAIN (arg))
2457               d->count += estimate_move_cost (TREE_TYPE (arg));
2458           }
2459
2460         d->count += cost;
2461         break;
2462       }
2463
2464     case OMP_PARALLEL:
2465     case OMP_FOR:
2466     case OMP_SECTIONS:
2467     case OMP_SINGLE:
2468     case OMP_SECTION:
2469     case OMP_MASTER:
2470     case OMP_ORDERED:
2471     case OMP_CRITICAL:
2472     case OMP_ATOMIC:
2473     case OMP_ATOMIC_LOAD:
2474       /* OpenMP directives are generally very expensive.  */
2475       d->count += d->weights->omp_cost;
2476       break;
2477
2478     default:
2479       gcc_unreachable ();
2480     }
2481   return NULL;
2482 }
2483
2484 /* Estimate number of instructions that will be created by expanding EXPR.
2485    WEIGHTS contains weights attributed to various constructs.  */
2486
2487 int
2488 estimate_num_insns (tree expr, eni_weights *weights)
2489 {
2490   struct pointer_set_t *visited_nodes;
2491   basic_block bb;
2492   block_stmt_iterator bsi;
2493   struct function *my_function;
2494   struct eni_data data;
2495
2496   data.count = 0;
2497   data.weights = weights;
2498
2499   /* If we're given an entire function, walk the CFG.  */
2500   if (TREE_CODE (expr) == FUNCTION_DECL)
2501     {
2502       my_function = DECL_STRUCT_FUNCTION (expr);
2503       gcc_assert (my_function && my_function->cfg);
2504       visited_nodes = pointer_set_create ();
2505       FOR_EACH_BB_FN (bb, my_function)
2506         {
2507           for (bsi = bsi_start (bb);
2508                !bsi_end_p (bsi);
2509                bsi_next (&bsi))
2510             {
2511               walk_tree (bsi_stmt_ptr (bsi), estimate_num_insns_1,
2512                          &data, visited_nodes);
2513             }
2514         }
2515       pointer_set_destroy (visited_nodes);
2516     }
2517   else
2518     walk_tree_without_duplicates (&expr, estimate_num_insns_1, &data);
2519
2520   return data.count;
2521 }
2522
2523 /* Initializes weights used by estimate_num_insns.  */
2524
2525 void
2526 init_inline_once (void)
2527 {
2528   eni_inlining_weights.call_cost = PARAM_VALUE (PARAM_INLINE_CALL_COST);
2529   eni_inlining_weights.target_builtin_call_cost = 1;
2530   eni_inlining_weights.div_mod_cost = 10;
2531   eni_inlining_weights.omp_cost = 40;
2532
2533   eni_size_weights.call_cost = 1;
2534   eni_size_weights.target_builtin_call_cost = 1;
2535   eni_size_weights.div_mod_cost = 1;
2536   eni_size_weights.omp_cost = 40;
2537
2538   /* Estimating time for call is difficult, since we have no idea what the
2539      called function does.  In the current uses of eni_time_weights,
2540      underestimating the cost does less harm than overestimating it, so
2541      we choose a rather small value here.  */
2542   eni_time_weights.call_cost = 10;
2543   eni_time_weights.target_builtin_call_cost = 10;
2544   eni_time_weights.div_mod_cost = 10;
2545   eni_time_weights.omp_cost = 40;
2546 }
2547
2548 /* Install new lexical TREE_BLOCK underneath 'current_block'.  */
2549 static void
2550 add_lexical_block (tree current_block, tree new_block)
2551 {
2552   tree *blk_p;
2553
2554   /* Walk to the last sub-block.  */
2555   for (blk_p = &BLOCK_SUBBLOCKS (current_block);
2556        *blk_p;
2557        blk_p = &BLOCK_CHAIN (*blk_p))
2558     ;
2559   *blk_p = new_block;
2560   BLOCK_SUPERCONTEXT (new_block) = current_block;
2561 }
2562
2563 /* If *TP is a CALL_EXPR, replace it with its inline expansion.  */
2564
2565 static bool
2566 expand_call_inline (basic_block bb, tree stmt, tree *tp, void *data)
2567 {
2568   copy_body_data *id;
2569   tree t;
2570   tree use_retvar;
2571   tree fn;
2572   struct pointer_map_t *st;
2573   tree return_slot;
2574   tree modify_dest;
2575   location_t saved_location;
2576   struct cgraph_edge *cg_edge;
2577   const char *reason;
2578   basic_block return_block;
2579   edge e;
2580   block_stmt_iterator bsi, stmt_bsi;
2581   bool successfully_inlined = FALSE;
2582   bool purge_dead_abnormal_edges;
2583   tree t_step;
2584   tree var;
2585
2586   /* See what we've got.  */
2587   id = (copy_body_data *) data;
2588   t = *tp;
2589
2590   /* Set input_location here so we get the right instantiation context
2591      if we call instantiate_decl from inlinable_function_p.  */
2592   saved_location = input_location;
2593   if (EXPR_HAS_LOCATION (t))
2594     input_location = EXPR_LOCATION (t);
2595
2596   /* From here on, we're only interested in CALL_EXPRs.  */
2597   if (TREE_CODE (t) != CALL_EXPR)
2598     goto egress;
2599
2600   /* First, see if we can figure out what function is being called.
2601      If we cannot, then there is no hope of inlining the function.  */
2602   fn = get_callee_fndecl (t);
2603   if (!fn)
2604     goto egress;
2605
2606   /* Turn forward declarations into real ones.  */
2607   fn = cgraph_node (fn)->decl;
2608
2609   /* If fn is a declaration of a function in a nested scope that was
2610      globally declared inline, we don't set its DECL_INITIAL.
2611      However, we can't blindly follow DECL_ABSTRACT_ORIGIN because the
2612      C++ front-end uses it for cdtors to refer to their internal
2613      declarations, that are not real functions.  Fortunately those
2614      don't have trees to be saved, so we can tell by checking their
2615      DECL_SAVED_TREE.  */
2616   if (! DECL_INITIAL (fn)
2617       && DECL_ABSTRACT_ORIGIN (fn)
2618       && DECL_SAVED_TREE (DECL_ABSTRACT_ORIGIN (fn)))
2619     fn = DECL_ABSTRACT_ORIGIN (fn);
2620
2621   /* Objective C and fortran still calls tree_rest_of_compilation directly.
2622      Kill this check once this is fixed.  */
2623   if (!id->dst_node->analyzed)
2624     goto egress;
2625
2626   cg_edge = cgraph_edge (id->dst_node, stmt);
2627
2628   /* Constant propagation on argument done during previous inlining
2629      may create new direct call.  Produce an edge for it.  */
2630   if (!cg_edge)
2631     {
2632       struct cgraph_node *dest = cgraph_node (fn);
2633
2634       /* We have missing edge in the callgraph.  This can happen in one case
2635          where previous inlining turned indirect call into direct call by
2636          constant propagating arguments.  In all other cases we hit a bug
2637          (incorrect node sharing is most common reason for missing edges.  */
2638       gcc_assert (dest->needed || !flag_unit_at_a_time);
2639       cgraph_create_edge (id->dst_node, dest, stmt,
2640                           bb->count, CGRAPH_FREQ_BASE,
2641                           bb->loop_depth)->inline_failed
2642         = N_("originally indirect function call not considered for inlining");
2643       if (dump_file)
2644         {
2645            fprintf (dump_file, "Created new direct edge to %s",
2646                     cgraph_node_name (dest));
2647         }
2648       goto egress;
2649     }
2650
2651   /* Don't try to inline functions that are not well-suited to
2652      inlining.  */
2653   if (!cgraph_inline_p (cg_edge, &reason))
2654     {
2655       if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (fn))
2656           /* Avoid warnings during early inline pass. */
2657           && (!flag_unit_at_a_time || cgraph_global_info_ready))
2658         {
2659           sorry ("inlining failed in call to %q+F: %s", fn, reason);
2660           sorry ("called from here");
2661         }
2662       else if (warn_inline && DECL_DECLARED_INLINE_P (fn)
2663                && !DECL_IN_SYSTEM_HEADER (fn)
2664                && strlen (reason)
2665                && !lookup_attribute ("noinline", DECL_ATTRIBUTES (fn))
2666                /* Avoid warnings during early inline pass. */
2667                && (!flag_unit_at_a_time || cgraph_global_info_ready))
2668         {
2669           warning (OPT_Winline, "inlining failed in call to %q+F: %s",
2670                    fn, reason);
2671           warning (OPT_Winline, "called from here");
2672         }
2673       goto egress;
2674     }
2675   fn = cg_edge->callee->decl;
2676
2677 #ifdef ENABLE_CHECKING
2678   if (cg_edge->callee->decl != id->dst_node->decl)
2679     verify_cgraph_node (cg_edge->callee);
2680 #endif
2681
2682   /* We will be inlining this callee.  */
2683   id->eh_region = lookup_stmt_eh_region (stmt);
2684
2685   /* Split the block holding the CALL_EXPR.  */
2686   e = split_block (bb, stmt);
2687   bb = e->src;
2688   return_block = e->dest;
2689   remove_edge (e);
2690
2691   /* split_block splits after the statement; work around this by
2692      moving the call into the second block manually.  Not pretty,
2693      but seems easier than doing the CFG manipulation by hand
2694      when the CALL_EXPR is in the last statement of BB.  */
2695   stmt_bsi = bsi_last (bb);
2696   bsi_remove (&stmt_bsi, false);
2697
2698   /* If the CALL_EXPR was in the last statement of BB, it may have
2699      been the source of abnormal edges.  In this case, schedule
2700      the removal of dead abnormal edges.  */
2701   bsi = bsi_start (return_block);
2702   if (bsi_end_p (bsi))
2703     {
2704       bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
2705       purge_dead_abnormal_edges = true;
2706     }
2707   else
2708     {
2709       bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
2710       purge_dead_abnormal_edges = false;
2711     }
2712
2713   stmt_bsi = bsi_start (return_block);
2714
2715   /* Build a block containing code to initialize the arguments, the
2716      actual inline expansion of the body, and a label for the return
2717      statements within the function to jump to.  The type of the
2718      statement expression is the return type of the function call.  */
2719   id->block = make_node (BLOCK);
2720   BLOCK_ABSTRACT_ORIGIN (id->block) = fn;
2721   BLOCK_SOURCE_LOCATION (id->block) = input_location;
2722   add_lexical_block (TREE_BLOCK (stmt), id->block);
2723
2724   /* Local declarations will be replaced by their equivalents in this
2725      map.  */
2726   st = id->decl_map;
2727   id->decl_map = pointer_map_create ();
2728
2729   /* Record the function we are about to inline.  */
2730   id->src_fn = fn;
2731   id->src_node = cg_edge->callee;
2732   id->src_cfun = DECL_STRUCT_FUNCTION (fn);
2733   id->call_expr = t;
2734
2735   gcc_assert (!id->src_cfun->after_inlining);
2736
2737   id->entry_bb = bb;
2738   initialize_inlined_parameters (id, t, fn, bb);
2739
2740   if (DECL_INITIAL (fn))
2741     add_lexical_block (id->block, remap_blocks (DECL_INITIAL (fn), id));
2742
2743   /* Return statements in the function body will be replaced by jumps
2744      to the RET_LABEL.  */
2745
2746   gcc_assert (DECL_INITIAL (fn));
2747   gcc_assert (TREE_CODE (DECL_INITIAL (fn)) == BLOCK);
2748
2749   /* Find the lhs to which the result of this call is assigned.  */
2750   return_slot = NULL;
2751   if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
2752     {
2753       modify_dest = GIMPLE_STMT_OPERAND (stmt, 0);
2754
2755       /* The function which we are inlining might not return a value,
2756          in which case we should issue a warning that the function
2757          does not return a value.  In that case the optimizers will
2758          see that the variable to which the value is assigned was not
2759          initialized.  We do not want to issue a warning about that
2760          uninitialized variable.  */
2761       if (DECL_P (modify_dest))
2762         TREE_NO_WARNING (modify_dest) = 1;
2763       if (CALL_EXPR_RETURN_SLOT_OPT (t))
2764         {
2765           return_slot = modify_dest;
2766           modify_dest = NULL;
2767         }
2768     }
2769   else
2770     modify_dest = NULL;
2771
2772   /* Declare the return variable for the function.  */
2773   declare_return_variable (id, return_slot,
2774                            modify_dest, &use_retvar);
2775
2776   /* This is it.  Duplicate the callee body.  Assume callee is
2777      pre-gimplified.  Note that we must not alter the caller
2778      function in any way before this point, as this CALL_EXPR may be
2779      a self-referential call; if we're calling ourselves, we need to
2780      duplicate our body before altering anything.  */
2781   copy_body (id, bb->count, bb->frequency, bb, return_block);
2782
2783   /* Add local vars in this inlined callee to caller.  */
2784   t_step = id->src_cfun->unexpanded_var_list;
2785   for (; t_step; t_step = TREE_CHAIN (t_step))
2786     {
2787       var = TREE_VALUE (t_step);
2788       if (TREE_STATIC (var) && !TREE_ASM_WRITTEN (var))
2789         cfun->unexpanded_var_list = tree_cons (NULL_TREE, var,
2790                                                cfun->unexpanded_var_list);
2791       else
2792         cfun->unexpanded_var_list = tree_cons (NULL_TREE, remap_decl (var, id),
2793                                                cfun->unexpanded_var_list);
2794     }
2795
2796   /* Clean up.  */
2797   pointer_map_destroy (id->decl_map);
2798   id->decl_map = st;
2799
2800   /* If the inlined function returns a result that we care about,
2801      clobber the CALL_EXPR with a reference to the return variable.  */
2802   if (use_retvar && (TREE_CODE (bsi_stmt (stmt_bsi)) != CALL_EXPR))
2803     {
2804       *tp = use_retvar;
2805       if (gimple_in_ssa_p (cfun))
2806         {
2807           update_stmt (stmt);
2808           mark_symbols_for_renaming (stmt);
2809         }
2810       maybe_clean_or_replace_eh_stmt (stmt, stmt);
2811     }
2812   else
2813     /* We're modifying a TSI owned by gimple_expand_calls_inline();
2814        tsi_delink() will leave the iterator in a sane state.  */
2815     {
2816       /* Handle case of inlining function that miss return statement so 
2817          return value becomes undefined.  */
2818       if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
2819           && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 0)) == SSA_NAME)
2820         {
2821           tree name = TREE_OPERAND (stmt, 0);
2822           tree var = SSA_NAME_VAR (TREE_OPERAND (stmt, 0));
2823           tree def = gimple_default_def (cfun, var);
2824
2825           /* If the variable is used undefined, make this name undefined via
2826              move.  */
2827           if (def)
2828             {
2829               TREE_OPERAND (stmt, 1) = def;
2830               update_stmt (stmt);
2831             }
2832           /* Otherwise make this variable undefined.  */
2833           else
2834             {
2835               bsi_remove (&stmt_bsi, true);
2836               set_default_def (var, name);
2837               SSA_NAME_DEF_STMT (name) = build_empty_stmt ();
2838             }
2839         }
2840       else
2841         bsi_remove (&stmt_bsi, true);
2842     }
2843
2844   if (purge_dead_abnormal_edges)
2845     tree_purge_dead_abnormal_call_edges (return_block);
2846
2847   /* If the value of the new expression is ignored, that's OK.  We
2848      don't warn about this for CALL_EXPRs, so we shouldn't warn about
2849      the equivalent inlined version either.  */
2850   TREE_USED (*tp) = 1;
2851
2852   /* Output the inlining info for this abstract function, since it has been
2853      inlined.  If we don't do this now, we can lose the information about the
2854      variables in the function when the blocks get blown away as soon as we
2855      remove the cgraph node.  */
2856   (*debug_hooks->outlining_inline_function) (cg_edge->callee->decl);
2857
2858   /* Update callgraph if needed.  */
2859   cgraph_remove_node (cg_edge->callee);
2860
2861   id->block = NULL_TREE;
2862   successfully_inlined = TRUE;
2863
2864  egress:
2865   input_location = saved_location;
2866   return successfully_inlined;
2867 }
2868
2869 /* Expand call statements reachable from STMT_P.
2870    We can only have CALL_EXPRs as the "toplevel" tree code or nested
2871    in a GIMPLE_MODIFY_STMT.  See tree-gimple.c:get_call_expr_in().  We can
2872    unfortunately not use that function here because we need a pointer
2873    to the CALL_EXPR, not the tree itself.  */
2874
2875 static bool
2876 gimple_expand_calls_inline (basic_block bb, copy_body_data *id)
2877 {
2878   block_stmt_iterator bsi;
2879
2880   /* Register specific tree functions.  */
2881   tree_register_cfg_hooks ();
2882   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
2883     {
2884       tree *expr_p = bsi_stmt_ptr (bsi);
2885       tree stmt = *expr_p;
2886
2887       if (TREE_CODE (*expr_p) == GIMPLE_MODIFY_STMT)
2888         expr_p = &GIMPLE_STMT_OPERAND (*expr_p, 1);
2889       if (TREE_CODE (*expr_p) == WITH_SIZE_EXPR)
2890         expr_p = &TREE_OPERAND (*expr_p, 0);
2891       if (TREE_CODE (*expr_p) == CALL_EXPR)
2892         if (expand_call_inline (bb, stmt, expr_p, id))
2893           return true;
2894     }
2895   return false;
2896 }
2897
2898 /* Walk all basic blocks created after FIRST and try to fold every statement
2899    in the STATEMENTS pointer set.  */
2900 static void
2901 fold_marked_statements (int first, struct pointer_set_t *statements)
2902 {
2903   for (;first < n_basic_blocks;first++)
2904     if (BASIC_BLOCK (first))
2905       {
2906         block_stmt_iterator bsi;
2907         for (bsi = bsi_start (BASIC_BLOCK (first));
2908              !bsi_end_p (bsi); bsi_next (&bsi))
2909           if (pointer_set_contains (statements, bsi_stmt (bsi)))
2910             {
2911               tree old_stmt = bsi_stmt (bsi);
2912               if (fold_stmt (bsi_stmt_ptr (bsi)))
2913                 {
2914                   update_stmt (bsi_stmt (bsi));
2915                   if (maybe_clean_or_replace_eh_stmt (old_stmt, bsi_stmt (bsi)))
2916                      tree_purge_dead_eh_edges (BASIC_BLOCK (first));
2917                 }
2918             }
2919       }
2920 }
2921
2922 /* Return true if BB has at least one abnormal outgoing edge.  */
2923
2924 static inline bool
2925 has_abnormal_outgoing_edge_p (basic_block bb)
2926 {
2927   edge e;
2928   edge_iterator ei;
2929
2930   FOR_EACH_EDGE (e, ei, bb->succs)
2931     if (e->flags & EDGE_ABNORMAL)
2932       return true;
2933
2934   return false;
2935 }
2936
2937 /* Expand calls to inline functions in the body of FN.  */
2938
2939 unsigned int
2940 optimize_inline_calls (tree fn)
2941 {
2942   copy_body_data id;
2943   tree prev_fn;
2944   basic_block bb;
2945   int last = n_basic_blocks;
2946   /* There is no point in performing inlining if errors have already
2947      occurred -- and we might crash if we try to inline invalid
2948      code.  */
2949   if (errorcount || sorrycount)
2950     return 0;
2951
2952   /* Clear out ID.  */
2953   memset (&id, 0, sizeof (id));
2954
2955   id.src_node = id.dst_node = cgraph_node (fn);
2956   id.dst_fn = fn;
2957   /* Or any functions that aren't finished yet.  */
2958   prev_fn = NULL_TREE;
2959   if (current_function_decl)
2960     {
2961       id.dst_fn = current_function_decl;
2962       prev_fn = current_function_decl;
2963     }
2964
2965   id.copy_decl = copy_decl_maybe_to_var;
2966   id.transform_call_graph_edges = CB_CGE_DUPLICATE;
2967   id.transform_new_cfg = false;
2968   id.transform_return_to_modify = true;
2969   id.transform_lang_insert_block = false;
2970   id.statements_to_fold = pointer_set_create ();
2971
2972   push_gimplify_context ();
2973
2974   /* We make no attempts to keep dominance info up-to-date.  */
2975   free_dominance_info (CDI_DOMINATORS);
2976   free_dominance_info (CDI_POST_DOMINATORS);
2977
2978   /* Reach the trees by walking over the CFG, and note the
2979      enclosing basic-blocks in the call edges.  */
2980   /* We walk the blocks going forward, because inlined function bodies
2981      will split id->current_basic_block, and the new blocks will
2982      follow it; we'll trudge through them, processing their CALL_EXPRs
2983      along the way.  */
2984   FOR_EACH_BB (bb)
2985     gimple_expand_calls_inline (bb, &id);
2986
2987   pop_gimplify_context (NULL);
2988
2989 #ifdef ENABLE_CHECKING
2990     {
2991       struct cgraph_edge *e;
2992
2993       verify_cgraph_node (id.dst_node);
2994
2995       /* Double check that we inlined everything we are supposed to inline.  */
2996       for (e = id.dst_node->callees; e; e = e->next_callee)
2997         gcc_assert (e->inline_failed);
2998     }
2999 #endif
3000   
3001   /* Fold the statements before compacting/renumbering the basic blocks.  */
3002   fold_marked_statements (last, id.statements_to_fold);
3003   pointer_set_destroy (id.statements_to_fold);
3004   
3005   /* Renumber the (code) basic_blocks consecutively.  */
3006   compact_blocks ();
3007   /* Renumber the lexical scoping (non-code) blocks consecutively.  */
3008   number_blocks (fn);
3009
3010   /* We are not going to maintain the cgraph edges up to date.
3011      Kill it so it won't confuse us.  */
3012   cgraph_node_remove_callees (id.dst_node);
3013
3014   fold_cond_expr_cond ();
3015   /* It would be nice to check SSA/CFG/statement consistency here, but it is
3016      not possible yet - the IPA passes might make various functions to not
3017      throw and they don't care to proactively update local EH info.  This is
3018      done later in fixup_cfg pass that also execute the verification.  */
3019   return (TODO_update_ssa | TODO_cleanup_cfg
3020           | (gimple_in_ssa_p (cfun) ? TODO_remove_unused_locals : 0)
3021           | (profile_status != PROFILE_ABSENT ? TODO_rebuild_frequencies : 0));
3022 }
3023
3024 /* FN is a function that has a complete body, and CLONE is a function whose
3025    body is to be set to a copy of FN, mapping argument declarations according
3026    to the ARG_MAP splay_tree.  */
3027
3028 void
3029 clone_body (tree clone, tree fn, void *arg_map)
3030 {
3031   copy_body_data id;
3032
3033   /* Clone the body, as if we were making an inline call.  But, remap the
3034      parameters in the callee to the parameters of caller.  */
3035   memset (&id, 0, sizeof (id));
3036   id.src_fn = fn;
3037   id.dst_fn = clone;
3038   id.src_cfun = DECL_STRUCT_FUNCTION (fn);
3039   id.decl_map = (struct pointer_map_t *)arg_map;
3040
3041   id.copy_decl = copy_decl_no_change;
3042   id.transform_call_graph_edges = CB_CGE_DUPLICATE;
3043   id.transform_new_cfg = true;
3044   id.transform_return_to_modify = false;
3045   id.transform_lang_insert_block = true;
3046
3047   /* We're not inside any EH region.  */
3048   id.eh_region = -1;
3049
3050   /* Actually copy the body.  */
3051   append_to_statement_list_force (copy_generic_body (&id), &DECL_SAVED_TREE (clone));
3052 }
3053
3054 /* Passed to walk_tree.  Copies the node pointed to, if appropriate.  */
3055
3056 tree
3057 copy_tree_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
3058 {
3059   enum tree_code code = TREE_CODE (*tp);
3060   enum tree_code_class cl = TREE_CODE_CLASS (code);
3061
3062   /* We make copies of most nodes.  */
3063   if (IS_EXPR_CODE_CLASS (cl)
3064       || IS_GIMPLE_STMT_CODE_CLASS (cl)
3065       || code == TREE_LIST
3066       || code == TREE_VEC
3067       || code == TYPE_DECL
3068       || code == OMP_CLAUSE)
3069     {
3070       /* Because the chain gets clobbered when we make a copy, we save it
3071          here.  */
3072       tree chain = NULL_TREE, new;
3073
3074       if (!GIMPLE_TUPLE_P (*tp))
3075         chain = TREE_CHAIN (*tp);
3076
3077       /* Copy the node.  */
3078       new = copy_node (*tp);
3079
3080       /* Propagate mudflap marked-ness.  */
3081       if (flag_mudflap && mf_marked_p (*tp))
3082         mf_mark (new);
3083
3084       *tp = new;
3085
3086       /* Now, restore the chain, if appropriate.  That will cause
3087          walk_tree to walk into the chain as well.  */
3088       if (code == PARM_DECL
3089           || code == TREE_LIST
3090           || code == OMP_CLAUSE)
3091         TREE_CHAIN (*tp) = chain;
3092
3093       /* For now, we don't update BLOCKs when we make copies.  So, we
3094          have to nullify all BIND_EXPRs.  */
3095       if (TREE_CODE (*tp) == BIND_EXPR)
3096         BIND_EXPR_BLOCK (*tp) = NULL_TREE;
3097     }
3098   else if (code == CONSTRUCTOR)
3099     {
3100       /* CONSTRUCTOR nodes need special handling because
3101          we need to duplicate the vector of elements.  */
3102       tree new;
3103
3104       new = copy_node (*tp);
3105
3106       /* Propagate mudflap marked-ness.  */
3107       if (flag_mudflap && mf_marked_p (*tp))
3108         mf_mark (new);
3109
3110       CONSTRUCTOR_ELTS (new) = VEC_copy (constructor_elt, gc,
3111                                          CONSTRUCTOR_ELTS (*tp));
3112       *tp = new;
3113     }
3114   else if (TREE_CODE_CLASS (code) == tcc_type)
3115     *walk_subtrees = 0;
3116   else if (TREE_CODE_CLASS (code) == tcc_declaration)
3117     *walk_subtrees = 0;
3118   else if (TREE_CODE_CLASS (code) == tcc_constant)
3119     *walk_subtrees = 0;
3120   else
3121     gcc_assert (code != STATEMENT_LIST);
3122   return NULL_TREE;
3123 }
3124
3125 /* The SAVE_EXPR pointed to by TP is being copied.  If ST contains
3126    information indicating to what new SAVE_EXPR this one should be mapped,
3127    use that one.  Otherwise, create a new node and enter it in ST.  FN is
3128    the function into which the copy will be placed.  */
3129
3130 static void
3131 remap_save_expr (tree *tp, void *st_, int *walk_subtrees)
3132 {
3133   struct pointer_map_t *st = (struct pointer_map_t *) st_;
3134   tree *n;
3135   tree t;
3136
3137   /* See if we already encountered this SAVE_EXPR.  */
3138   n = (tree *) pointer_map_contains (st, *tp);
3139
3140   /* If we didn't already remap this SAVE_EXPR, do so now.  */
3141   if (!n)
3142     {
3143       t = copy_node (*tp);
3144
3145       /* Remember this SAVE_EXPR.  */
3146       *pointer_map_insert (st, *tp) = t;
3147       /* Make sure we don't remap an already-remapped SAVE_EXPR.  */
3148       *pointer_map_insert (st, t) = t;
3149     }
3150   else
3151     {
3152       /* We've already walked into this SAVE_EXPR; don't do it again.  */
3153       *walk_subtrees = 0;
3154       t = *n;
3155     }
3156
3157   /* Replace this SAVE_EXPR with the copy.  */
3158   *tp = t;
3159 }
3160
3161 /* Called via walk_tree.  If *TP points to a DECL_STMT for a local label,
3162    copies the declaration and enters it in the splay_tree in DATA (which is
3163    really an `copy_body_data *').  */
3164
3165 static tree
3166 mark_local_for_remap_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
3167                         void *data)
3168 {
3169   copy_body_data *id = (copy_body_data *) data;
3170
3171   /* Don't walk into types.  */
3172   if (TYPE_P (*tp))
3173     *walk_subtrees = 0;
3174
3175   else if (TREE_CODE (*tp) == LABEL_EXPR)
3176     {
3177       tree decl = TREE_OPERAND (*tp, 0);
3178
3179       /* Copy the decl and remember the copy.  */
3180       insert_decl_map (id, decl, id->copy_decl (decl, id));
3181     }
3182
3183   return NULL_TREE;
3184 }
3185
3186 /* Perform any modifications to EXPR required when it is unsaved.  Does
3187    not recurse into EXPR's subtrees.  */
3188
3189 static void
3190 unsave_expr_1 (tree expr)
3191 {
3192   switch (TREE_CODE (expr))
3193     {
3194     case TARGET_EXPR:
3195       /* Don't mess with a TARGET_EXPR that hasn't been expanded.
3196          It's OK for this to happen if it was part of a subtree that
3197          isn't immediately expanded, such as operand 2 of another
3198          TARGET_EXPR.  */
3199       if (TREE_OPERAND (expr, 1))
3200         break;
3201
3202       TREE_OPERAND (expr, 1) = TREE_OPERAND (expr, 3);
3203       TREE_OPERAND (expr, 3) = NULL_TREE;
3204       break;
3205
3206     default:
3207       break;
3208     }
3209 }
3210
3211 /* Called via walk_tree when an expression is unsaved.  Using the
3212    splay_tree pointed to by ST (which is really a `splay_tree'),
3213    remaps all local declarations to appropriate replacements.  */
3214
3215 static tree
3216 unsave_r (tree *tp, int *walk_subtrees, void *data)
3217 {
3218   copy_body_data *id = (copy_body_data *) data;
3219   struct pointer_map_t *st = id->decl_map;
3220   tree *n;
3221
3222   /* Only a local declaration (variable or label).  */
3223   if ((TREE_CODE (*tp) == VAR_DECL && !TREE_STATIC (*tp))
3224       || TREE_CODE (*tp) == LABEL_DECL)
3225     {
3226       /* Lookup the declaration.  */
3227       n = (tree *) pointer_map_contains (st, *tp);
3228
3229       /* If it's there, remap it.  */
3230       if (n)
3231         *tp = *n;
3232     }
3233
3234   else if (TREE_CODE (*tp) == STATEMENT_LIST)
3235     copy_statement_list (tp);
3236   else if (TREE_CODE (*tp) == BIND_EXPR)
3237     copy_bind_expr (tp, walk_subtrees, id);
3238   else if (TREE_CODE (*tp) == SAVE_EXPR)
3239     remap_save_expr (tp, st, walk_subtrees);
3240   else
3241     {
3242       copy_tree_r (tp, walk_subtrees, NULL);
3243
3244       /* Do whatever unsaving is required.  */
3245       unsave_expr_1 (*tp);
3246     }
3247
3248   /* Keep iterating.  */
3249   return NULL_TREE;
3250 }
3251
3252 /* Copies everything in EXPR and replaces variables, labels
3253    and SAVE_EXPRs local to EXPR.  */
3254
3255 tree
3256 unsave_expr_now (tree expr)
3257 {
3258   copy_body_data id;
3259
3260   /* There's nothing to do for NULL_TREE.  */
3261   if (expr == 0)
3262     return expr;
3263
3264   /* Set up ID.  */
3265   memset (&id, 0, sizeof (id));
3266   id.src_fn = current_function_decl;
3267   id.dst_fn = current_function_decl;
3268   id.decl_map = pointer_map_create ();
3269
3270   id.copy_decl = copy_decl_no_change;
3271   id.transform_call_graph_edges = CB_CGE_DUPLICATE;
3272   id.transform_new_cfg = false;
3273   id.transform_return_to_modify = false;
3274   id.transform_lang_insert_block = false;
3275
3276   /* Walk the tree once to find local labels.  */
3277   walk_tree_without_duplicates (&expr, mark_local_for_remap_r, &id);
3278
3279   /* Walk the tree again, copying, remapping, and unsaving.  */
3280   walk_tree (&expr, unsave_r, &id, NULL);
3281
3282   /* Clean up.  */
3283   pointer_map_destroy (id.decl_map);
3284
3285   return expr;
3286 }
3287
3288 /* Allow someone to determine if SEARCH is a child of TOP from gdb.  */
3289
3290 static tree
3291 debug_find_tree_1 (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data)
3292 {
3293   if (*tp == data)
3294     return (tree) data;
3295   else
3296     return NULL;
3297 }
3298
3299 bool
3300 debug_find_tree (tree top, tree search)
3301 {
3302   return walk_tree_without_duplicates (&top, debug_find_tree_1, search) != 0;
3303 }
3304
3305
3306 /* Declare the variables created by the inliner.  Add all the variables in
3307    VARS to BIND_EXPR.  */
3308
3309 static void
3310 declare_inline_vars (tree block, tree vars)
3311 {
3312   tree t;
3313   for (t = vars; t; t = TREE_CHAIN (t))
3314     {
3315       DECL_SEEN_IN_BIND_EXPR_P (t) = 1;
3316       gcc_assert (!TREE_STATIC (t) && !TREE_ASM_WRITTEN (t));
3317       cfun->unexpanded_var_list =
3318         tree_cons (NULL_TREE, t,
3319                    cfun->unexpanded_var_list);
3320     }
3321
3322   if (block)
3323     BLOCK_VARS (block) = chainon (BLOCK_VARS (block), vars);
3324 }
3325
3326
3327 /* Copy NODE (which must be a DECL).  The DECL originally was in the FROM_FN,
3328    but now it will be in the TO_FN.  PARM_TO_VAR means enable PARM_DECL to
3329    VAR_DECL translation.  */
3330
3331 static tree
3332 copy_decl_for_dup_finish (copy_body_data *id, tree decl, tree copy)
3333 {
3334   /* Don't generate debug information for the copy if we wouldn't have
3335      generated it for the copy either.  */
3336   DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (decl);
3337   DECL_IGNORED_P (copy) = DECL_IGNORED_P (decl);
3338
3339   /* Set the DECL_ABSTRACT_ORIGIN so the debugging routines know what
3340      declaration inspired this copy.  */ 
3341   DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (decl);
3342
3343   /* The new variable/label has no RTL, yet.  */
3344   if (CODE_CONTAINS_STRUCT (TREE_CODE (copy), TS_DECL_WRTL)
3345       && !TREE_STATIC (copy) && !DECL_EXTERNAL (copy))
3346     SET_DECL_RTL (copy, NULL_RTX);
3347   
3348   /* These args would always appear unused, if not for this.  */
3349   TREE_USED (copy) = 1;
3350
3351   /* Set the context for the new declaration.  */
3352   if (!DECL_CONTEXT (decl))
3353     /* Globals stay global.  */
3354     ;
3355   else if (DECL_CONTEXT (decl) != id->src_fn)
3356     /* Things that weren't in the scope of the function we're inlining
3357        from aren't in the scope we're inlining to, either.  */
3358     ;
3359   else if (TREE_STATIC (decl))
3360     /* Function-scoped static variables should stay in the original
3361        function.  */
3362     ;
3363   else
3364     /* Ordinary automatic local variables are now in the scope of the
3365        new function.  */
3366     DECL_CONTEXT (copy) = id->dst_fn;
3367
3368   return copy;
3369 }
3370
3371 static tree
3372 copy_decl_to_var (tree decl, copy_body_data *id)
3373 {
3374   tree copy, type;
3375
3376   gcc_assert (TREE_CODE (decl) == PARM_DECL
3377               || TREE_CODE (decl) == RESULT_DECL);
3378
3379   type = TREE_TYPE (decl);
3380
3381   copy = build_decl (VAR_DECL, DECL_NAME (decl), type);
3382   TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (decl);
3383   TREE_READONLY (copy) = TREE_READONLY (decl);
3384   TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (decl);
3385   DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (decl);
3386   DECL_NO_TBAA_P (copy) = DECL_NO_TBAA_P (decl);
3387
3388   return copy_decl_for_dup_finish (id, decl, copy);
3389 }
3390
3391 /* Like copy_decl_to_var, but create a return slot object instead of a
3392    pointer variable for return by invisible reference.  */
3393
3394 static tree
3395 copy_result_decl_to_var (tree decl, copy_body_data *id)
3396 {
3397   tree copy, type;
3398
3399   gcc_assert (TREE_CODE (decl) == PARM_DECL
3400               || TREE_CODE (decl) == RESULT_DECL);
3401
3402   type = TREE_TYPE (decl);
3403   if (DECL_BY_REFERENCE (decl))
3404     type = TREE_TYPE (type);
3405
3406   copy = build_decl (VAR_DECL, DECL_NAME (decl), type);
3407   TREE_READONLY (copy) = TREE_READONLY (decl);
3408   TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (decl);
3409   if (!DECL_BY_REFERENCE (decl))
3410     {
3411       TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (decl);
3412       DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (decl);
3413       DECL_NO_TBAA_P (copy) = DECL_NO_TBAA_P (decl);
3414     }
3415
3416   return copy_decl_for_dup_finish (id, decl, copy);
3417 }
3418
3419
3420 static tree
3421 copy_decl_no_change (tree decl, copy_body_data *id)
3422 {
3423   tree copy;
3424
3425   copy = copy_node (decl);
3426
3427   /* The COPY is not abstract; it will be generated in DST_FN.  */
3428   DECL_ABSTRACT (copy) = 0;
3429   lang_hooks.dup_lang_specific_decl (copy);
3430
3431   /* TREE_ADDRESSABLE isn't used to indicate that a label's address has
3432      been taken; it's for internal bookkeeping in expand_goto_internal.  */
3433   if (TREE_CODE (copy) == LABEL_DECL)
3434     {
3435       TREE_ADDRESSABLE (copy) = 0;
3436       LABEL_DECL_UID (copy) = -1;
3437     }
3438
3439   return copy_decl_for_dup_finish (id, decl, copy);
3440 }
3441
3442 static tree
3443 copy_decl_maybe_to_var (tree decl, copy_body_data *id)
3444 {
3445   if (TREE_CODE (decl) == PARM_DECL || TREE_CODE (decl) == RESULT_DECL)
3446     return copy_decl_to_var (decl, id);
3447   else
3448     return copy_decl_no_change (decl, id);
3449 }
3450
3451 /* Return a copy of the function's argument tree.  */
3452 static tree
3453 copy_arguments_for_versioning (tree orig_parm, copy_body_data * id)
3454 {
3455   tree *arg_copy, *parg;
3456
3457   arg_copy = &orig_parm;
3458   for (parg = arg_copy; *parg; parg = &TREE_CHAIN (*parg))
3459     {
3460       tree new = remap_decl (*parg, id);
3461       lang_hooks.dup_lang_specific_decl (new);
3462       TREE_CHAIN (new) = TREE_CHAIN (*parg);
3463       *parg = new;
3464     }
3465   return orig_parm;
3466 }
3467
3468 /* Return a copy of the function's static chain.  */
3469 static tree
3470 copy_static_chain (tree static_chain, copy_body_data * id)
3471 {
3472   tree *chain_copy, *pvar;
3473
3474   chain_copy = &static_chain;
3475   for (pvar = chain_copy; *pvar; pvar = &TREE_CHAIN (*pvar))
3476     {
3477       tree new = remap_decl (*pvar, id);
3478       lang_hooks.dup_lang_specific_decl (new);
3479       TREE_CHAIN (new) = TREE_CHAIN (*pvar);
3480       *pvar = new;
3481     }
3482   return static_chain;
3483 }
3484
3485 /* Return true if the function is allowed to be versioned.
3486    This is a guard for the versioning functionality.  */
3487 bool
3488 tree_versionable_function_p (tree fndecl)
3489 {
3490   if (fndecl == NULL_TREE)
3491     return false;
3492   /* ??? There are cases where a function is
3493      uninlinable but can be versioned.  */
3494   if (!tree_inlinable_function_p (fndecl))
3495     return false;
3496   
3497   return true;
3498 }
3499
3500 /* Create a copy of a function's tree.
3501    OLD_DECL and NEW_DECL are FUNCTION_DECL tree nodes
3502    of the original function and the new copied function
3503    respectively.  In case we want to replace a DECL 
3504    tree with another tree while duplicating the function's 
3505    body, TREE_MAP represents the mapping between these 
3506    trees. If UPDATE_CLONES is set, the call_stmt fields
3507    of edges of clones of the function will be updated.  */
3508 void
3509 tree_function_versioning (tree old_decl, tree new_decl, varray_type tree_map,
3510                           bool update_clones)
3511 {
3512   struct cgraph_node *old_version_node;
3513   struct cgraph_node *new_version_node;
3514   copy_body_data id;
3515   tree p;
3516   unsigned i;
3517   struct ipa_replace_map *replace_info;
3518   basic_block old_entry_block;
3519   tree t_step;
3520   tree old_current_function_decl = current_function_decl;
3521
3522   gcc_assert (TREE_CODE (old_decl) == FUNCTION_DECL
3523               && TREE_CODE (new_decl) == FUNCTION_DECL);
3524   DECL_POSSIBLY_INLINED (old_decl) = 1;
3525
3526   old_version_node = cgraph_node (old_decl);
3527   new_version_node = cgraph_node (new_decl);
3528
3529   DECL_ARTIFICIAL (new_decl) = 1;
3530   DECL_ABSTRACT_ORIGIN (new_decl) = DECL_ORIGIN (old_decl);
3531
3532   /* Prepare the data structures for the tree copy.  */
3533   memset (&id, 0, sizeof (id));
3534
3535   /* Generate a new name for the new version. */
3536   if (!update_clones)
3537     {
3538       DECL_NAME (new_decl) =  create_tmp_var_name (NULL);
3539       SET_DECL_ASSEMBLER_NAME (new_decl, DECL_NAME (new_decl));
3540       SET_DECL_RTL (new_decl, NULL_RTX);
3541       id.statements_to_fold = pointer_set_create ();
3542     }
3543   
3544   id.decl_map = pointer_map_create ();
3545   id.src_fn = old_decl;
3546   id.dst_fn = new_decl;
3547   id.src_node = old_version_node;
3548   id.dst_node = new_version_node;
3549   id.src_cfun = DECL_STRUCT_FUNCTION (old_decl);
3550   
3551   id.copy_decl = copy_decl_no_change;
3552   id.transform_call_graph_edges
3553     = update_clones ? CB_CGE_MOVE_CLONES : CB_CGE_MOVE;
3554   id.transform_new_cfg = true;
3555   id.transform_return_to_modify = false;
3556   id.transform_lang_insert_block = false;
3557
3558   current_function_decl = new_decl;
3559   old_entry_block = ENTRY_BLOCK_PTR_FOR_FUNCTION
3560     (DECL_STRUCT_FUNCTION (old_decl));
3561   initialize_cfun (new_decl, old_decl,
3562                    old_entry_block->count,
3563                    old_entry_block->frequency);
3564   push_cfun (DECL_STRUCT_FUNCTION (new_decl));
3565   
3566   /* Copy the function's static chain.  */
3567   p = DECL_STRUCT_FUNCTION (old_decl)->static_chain_decl;
3568   if (p)
3569     DECL_STRUCT_FUNCTION (new_decl)->static_chain_decl =
3570       copy_static_chain (DECL_STRUCT_FUNCTION (old_decl)->static_chain_decl,
3571                          &id);
3572   /* Copy the function's arguments.  */
3573   if (DECL_ARGUMENTS (old_decl) != NULL_TREE)
3574     DECL_ARGUMENTS (new_decl) =
3575       copy_arguments_for_versioning (DECL_ARGUMENTS (old_decl), &id);
3576   
3577   /* If there's a tree_map, prepare for substitution.  */
3578   if (tree_map)
3579     for (i = 0; i < VARRAY_ACTIVE_SIZE (tree_map); i++)
3580       {
3581         replace_info = VARRAY_GENERIC_PTR (tree_map, i);
3582         if (replace_info->replace_p)
3583           insert_decl_map (&id, replace_info->old_tree,
3584                            replace_info->new_tree);
3585       }
3586   
3587   DECL_INITIAL (new_decl) = remap_blocks (DECL_INITIAL (id.src_fn), &id);
3588   
3589   /* Renumber the lexical scoping (non-code) blocks consecutively.  */
3590   number_blocks (id.dst_fn);
3591   
3592   if (DECL_STRUCT_FUNCTION (old_decl)->unexpanded_var_list != NULL_TREE)
3593     /* Add local vars.  */
3594     for (t_step = DECL_STRUCT_FUNCTION (old_decl)->unexpanded_var_list;
3595          t_step; t_step = TREE_CHAIN (t_step))
3596       {
3597         tree var = TREE_VALUE (t_step);
3598         if (TREE_STATIC (var) && !TREE_ASM_WRITTEN (var))
3599           cfun->unexpanded_var_list = tree_cons (NULL_TREE, var,
3600                                                  cfun->unexpanded_var_list);
3601         else
3602           cfun->unexpanded_var_list =
3603             tree_cons (NULL_TREE, remap_decl (var, &id),
3604                        cfun->unexpanded_var_list);
3605       }
3606   
3607   /* Copy the Function's body.  */
3608   copy_body (&id, old_entry_block->count, old_entry_block->frequency, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR);
3609   
3610   if (DECL_RESULT (old_decl) != NULL_TREE)
3611     {
3612       tree *res_decl = &DECL_RESULT (old_decl);
3613       DECL_RESULT (new_decl) = remap_decl (*res_decl, &id);
3614       lang_hooks.dup_lang_specific_decl (DECL_RESULT (new_decl));
3615     }
3616   
3617   /* Renumber the lexical scoping (non-code) blocks consecutively.  */
3618   number_blocks (new_decl);
3619
3620   /* Clean up.  */
3621   pointer_map_destroy (id.decl_map);
3622   if (!update_clones)
3623     {
3624       fold_marked_statements (0, id.statements_to_fold);
3625       pointer_set_destroy (id.statements_to_fold);
3626       fold_cond_expr_cond ();
3627     }
3628   if (gimple_in_ssa_p (cfun))
3629     {
3630       free_dominance_info (CDI_DOMINATORS);
3631       free_dominance_info (CDI_POST_DOMINATORS);
3632       if (!update_clones)
3633         delete_unreachable_blocks ();
3634       update_ssa (TODO_update_ssa);
3635       if (!update_clones)
3636         {
3637           fold_cond_expr_cond ();
3638           if (need_ssa_update_p ())
3639             update_ssa (TODO_update_ssa);
3640         }
3641     }
3642   free_dominance_info (CDI_DOMINATORS);
3643   free_dominance_info (CDI_POST_DOMINATORS);
3644   pop_cfun ();
3645   current_function_decl = old_current_function_decl;
3646   gcc_assert (!current_function_decl
3647               || DECL_STRUCT_FUNCTION (current_function_decl) == cfun);
3648   return;
3649 }
3650
3651 /* Duplicate a type, fields and all.  */
3652
3653 tree
3654 build_duplicate_type (tree type)
3655 {
3656   struct copy_body_data id;
3657
3658   memset (&id, 0, sizeof (id));
3659   id.src_fn = current_function_decl;
3660   id.dst_fn = current_function_decl;
3661   id.src_cfun = cfun;
3662   id.decl_map = pointer_map_create ();
3663   id.copy_decl = copy_decl_no_change;
3664
3665   type = remap_type_1 (type, &id);
3666
3667   pointer_map_destroy (id.decl_map);
3668
3669   return type;
3670 }