GCC Middle and Back End API Reference
tree-ssa-reassoc.c File Reference
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "hash-table.h"
#include "tm.h"
#include "rtl.h"
#include "tm_p.h"
#include "tree.h"
#include "basic-block.h"
#include "gimple-pretty-print.h"
#include "tree-inline.h"
#include "gimple.h"
#include "gimple-ssa.h"
#include "tree-cfg.h"
#include "tree-phinodes.h"
#include "ssa-iterators.h"
#include "tree-ssanames.h"
#include "tree-ssa-loop-niter.h"
#include "tree-ssa-loop.h"
#include "tree-dfa.h"
#include "tree-ssa.h"
#include "tree-iterator.h"
#include "tree-pass.h"
#include "alloc-pool.h"
#include "vec.h"
#include "langhooks.h"
#include "pointer-set.h"
#include "cfgloop.h"
#include "flags.h"
#include "target.h"
#include "params.h"
#include "diagnostic-core.h"
Include dependency graph for tree-ssa-reassoc.c:

Data Structures

struct  operand_entry
struct  oecount_s
struct  oecount_hasher
struct  range_entry
struct  inter_bb_range_test_entry
struct  repeat_factor_d

Macros

#define PHI_LOOP_BIAS   (1 << 15)
#define INTEGER_CONST_TYPE   1 << 3
#define FLOAT_CONST_TYPE   1 << 2
#define OTHER_CONST_TYPE   1 << 1

Typedefs

typedef struct operand_entryoperand_entry_t
typedef struct oecount_s oecount
typedef struct repeat_factor_d repeat_factor
typedef struct repeat_factor_drepeat_factor_t
typedef struct repeat_factor_dconst_repeat_factor_t

Functions

static long get_rank (tree)
static long phi_rank ()
static bool loop_carried_phi ()
static long propagate_rank ()
static long find_operand_rank ()
static void insert_operand_rank ()
static long get_rank ()
static int constant_type ()
static int sort_by_operand_rank ()
static void add_to_ops_vec ()
static void add_repeat_to_ops_vec (vec< operand_entry_t > *ops, tree op, HOST_WIDE_INT repeat)
static bool is_reassociable_op ()
static tree get_unary_op ()
static bool eliminate_duplicate_pair (enum tree_code opcode, vec< operand_entry_t > *ops, bool *all_done, unsigned int i, operand_entry_t curr, operand_entry_t last)
static bool eliminate_plus_minus_pair (enum tree_code opcode, vec< operand_entry_t > *ops, unsigned int currindex, operand_entry_t curr)
static bool eliminate_not_pairs (enum tree_code opcode, vec< operand_entry_t > *ops, unsigned int currindex, operand_entry_t curr)
static void eliminate_using_constants (enum tree_code opcode, vec< operand_entry_t > *ops)
static void linearize_expr_tree (vec< operand_entry_t > *, gimple, bool, bool)
static int oecount_cmp ()
static bool stmt_is_power_of_op ()
static HOST_WIDE_INT decrement_power ()
static void propagate_op_to_single_use ()
static void zero_one_operation ()
static bool reassoc_stmt_dominates_stmt_p ()
static void insert_stmt_after ()
static gimple build_and_add_sum ()
static bool undistribute_ops_list (enum tree_code opcode, vec< operand_entry_t > *ops, struct loop *loop)
static bool eliminate_redundant_comparison (enum tree_code opcode, vec< operand_entry_t > *ops, unsigned int currindex, operand_entry_t curr)
static void optimize_ops_list (enum tree_code opcode, vec< operand_entry_t > *ops)
static void init_range_entry ()
static int range_entry_cmp ()
static bool update_range_test (struct range_entry *range, struct range_entry *otherrange, unsigned int count, enum tree_code opcode, vec< operand_entry_t > *ops, tree exp, bool in_p, tree low, tree high, bool strict_overflow_p)
static bool optimize_range_tests_xor (enum tree_code opcode, tree type, tree lowi, tree lowj, tree highi, tree highj, vec< operand_entry_t > *ops, struct range_entry *rangei, struct range_entry *rangej)
static bool optimize_range_tests_diff (enum tree_code opcode, tree type, tree lowi, tree lowj, tree highi, tree highj, vec< operand_entry_t > *ops, struct range_entry *rangei, struct range_entry *rangej)
static bool optimize_range_tests_1 (enum tree_code opcode, int first, int length, bool optimize_xor, vec< operand_entry_t > *ops, struct range_entry *ranges)
static bool optimize_range_tests (enum tree_code opcode, vec< operand_entry_t > *ops)
static bool final_range_test_p ()
static bool suitable_cond_bb (basic_block bb, basic_block test_bb, basic_block *other_bb, bool backward)
static bool no_side_effect_bb ()
static bool get_ops (tree var, enum tree_code code, vec< operand_entry_t > *ops, struct loop *loop)
static tree update_ops (tree var, enum tree_code code, vec< operand_entry_t > ops, unsigned int *pidx, struct loop *loop)
static void maybe_optimize_range_tests ()
static bool is_phi_for_stmt ()
static void remove_visited_stmt_chain ()
static void swap_ops_for_binary_stmt (vec< operand_entry_t > ops, unsigned int opindex, gimple stmt)
static gimple find_insert_point ()
static tree rewrite_expr_tree (gimple stmt, unsigned int opindex, vec< operand_entry_t > ops, bool changed)
static int get_required_cycles ()
static int get_reassociation_width (int ops_num, enum tree_code opc, enum machine_mode mode)
static void rewrite_expr_tree_parallel (gimple stmt, int width, vec< operand_entry_t > ops)
static void linearize_expr ()
static gimple get_single_immediate_use ()
static tree negate_value ()
static bool should_break_up_subtract ()
static void break_up_subtract ()
static bool acceptable_pow_call ()
static void repropagate_negates ()
static bool can_reassociate_p ()
static void break_up_subtract_bb ()
static int compare_repeat_factors ()
static tree attempt_builtin_powi ()
static void transform_stmt_to_copy ()
static void transform_stmt_to_multiply (gimple_stmt_iterator *gsi, gimple stmt, tree rhs1, tree rhs2)
static void reassociate_bb ()
void dump_ops_vector (FILE *file, vec< operand_entry_t > ops)
void debug_ops_vector (vec< operand_entry_t > ops)
void dump_ops_vector ()
DEBUG_FUNCTION void debug_ops_vector ()
static void do_reassoc ()
static void init_reassoc ()
static void fini_reassoc ()
static unsigned int execute_reassoc ()
static bool gate_tree_ssa_reassoc ()
gimple_opt_passmake_pass_reassoc ()

Variables

struct {
   int   linearized
   int   constants_eliminated
   int   ops_eliminated
   int   rewritten
   int   pows_encountered
   int   pows_created
reassociate_stats
static alloc_pool operand_entry_pool
static int next_operand_entry_id
static long * bb_rank
static struct pointer_map_toperand_rank
static vec< treeplus_negates
static vec< oecountcvec
static vec< repeat_factorrepeat_factor_vec

Macro Definition Documentation

#define FLOAT_CONST_TYPE   1 << 2
#define INTEGER_CONST_TYPE   1 << 3

We want integer ones to end up last no matter what, since they are the ones we can do the most with.

#define OTHER_CONST_TYPE   1 << 1
#define PHI_LOOP_BIAS   (1 << 15)

Bias amount for loop-carried phis. We want this to be larger than the depth of any reassociation tree we can see, but not larger than the rank difference between two blocks.


Typedef Documentation

typedef struct oecount_s oecount

Structure for tracking and counting operands.

typedef struct operand_entry * operand_entry_t

Operator, rank pair.

typedef struct repeat_factor_d * repeat_factor_t

Function Documentation

static bool acceptable_pow_call ( )
static

Determine whether STMT is a builtin call that raises an SSA name to an integer power and has only one use. If so, and this is early reassociation and unsafe math optimizations are permitted, place the SSA name in *BASE and the exponent in *EXPONENT, and return TRUE. If any of these conditions does not hold, return FALSE.

Expanding negative exponents is generally unproductive, so we don't complicate matters with those. Exponents of zero and one should have been handled by expression folding.

References add_repeat_to_ops_vec(), and gimple_set_visited().

static void add_repeat_to_ops_vec ( vec< operand_entry_t > *  ops,
tree  op,
HOST_WIDE_INT  repeat 
)
static

Add an operand entry to *OPS for the tree operand OP with repeat count REPEAT.

References gimple_assign_rhs1(), gimple_assign_rhs_code(), is_gimple_assign(), NULL_TREE, and SSA_NAME_DEF_STMT.

Referenced by acceptable_pow_call().

static void add_to_ops_vec ( )
static

Add an operand entry to *OPS for the tree operand OP.

static tree attempt_builtin_powi ( )
static

Look for repeated operands in OPS in the multiply tree rooted at STMT. Replace them with an optimal sequence of multiplies and powi builtin calls, and remove the used operands from OPS. Return an SSA name representing the value of the replacement sequence.

 Nothing to do if BUILT_IN_POWI doesn't exist for this type and
 target.   
 Allocate the repeated factor vector.   
 Scan the OPS vector for all SSA names in the product and build
 up a vector of occurrence counts for each factor.   
 Sort the repeated factor vector by (a) increasing occurrence count,
 and (b) decreasing rank.   
 It is generally best to combine as many base factors as possible
 into a product before applying __builtin_powi to the result.
 However, the sort order chosen for the repeated factor vector
 allows us to cache partial results for the product of the base
 factors for subsequent use.  When we already have a cached partial
 result from a previous iteration, it is best to make use of it
 before looking for another __builtin_pow opportunity.

 As an example, consider x * x * y * y * y * z * z * z * z.
 We want to first compose the product x * y * z, raise it to the
 second power, then multiply this by y * z, and finally multiply
 by z.  This can be done in 5 multiplies provided we cache y * z
 for use in both expressions:

    t1 = y * z
    t2 = t1 * x
    t3 = t2 * t2
    t4 = t1 * t3
    result = t4 * z

 If we instead ignored the cached y * z and first multiplied by
 the __builtin_pow opportunity z * z, we would get the inferior:

    t1 = y * z
    t2 = t1 * x
    t3 = t2 * t2
    t4 = z * z
    t5 = t3 * t4
    result = t5 * y   
 Repeatedly look for opportunities to create a builtin_powi call.   
     First look for the largest cached product of factors from
     preceding iterations.  If found, create a builtin_powi for
     it if the minimum occurrence count for its factors is at
     least 2, or just use this cached product as our next 
     multiplicand if the minimum occurrence count is 1.   
         Otherwise, find the first factor in the repeated factor
         vector whose occurrence count is at least 2.  If no such
         factor exists, there are no builtin_powi opportunities
         remaining.   
         Visit each element of the vector in reverse order (so that
         high-occurrence elements are visited first, and within the
         same occurrence count, lower-ranked elements are visited
         first).  Form a linear product of all elements in this order
         whose occurrencce count is at least that of element J.
         Record the SSA name representing the product of each element
         with all subsequent elements in the vector.   
                 Init the last factor's representative to be itself.   
                 Don't reprocess the multiply we just introduced.   
         Form a call to __builtin_powi for the maximum product
         just formed, raised to the power obtained earlier.   
     If we previously formed at least one other builtin_powi call,
     form the product of this one and those others.   
     Decrement the occurrence count of each element in the product
     by the count found above, and remove this many copies of each
     factor from OPS.   
 At this point all elements in the repeated factor vector have a
 remaining occurrence count of 0 or 1, and those with a count of 1
 don't have cached representatives.  Re-sort the ops vector and
 clean up.   
 Return the final product computed herein.  Note that there may
 still be some elements with single occurrence count left in OPS;
 those will be handled by the normal reassociation logic.   

References repeat_factor_d::factor, gimple_build_assign_with_ops(), gimple_location(), gimple_set_location(), gimple_set_visited(), gsi_insert_before(), GSI_SAME_STMT, make_temp_ssa_name(), NULL, and repeat_factor_d::repr.

static void break_up_subtract ( )
static

Transform STMT from A - B into A + -B.

References dump_file, and print_gimple_stmt().

static void break_up_subtract_bb ( )
static

Break up subtract operations in block BB.

We do this top down because we don't know whether the subtract is part of a possible chain of reassociation except at the top.

IE given d = f + g c = a + e b = c - d q = b - r k = t - q

we want to break up k = t - q, but we won't until we've transformed q = b - r, which won't be broken up until we transform b = c - d.

En passant, clear the GIMPLE visited flag on every statement and set UIDs within each basic block.

Look for simple gimple subtract operations.

         Check for a subtract used only in an addition.  If this
         is the case, transform it into add of a negate for better
         reassociation.  IE transform C = A-B into C = A + -B if C
         is only used in an addition.   

References dump_file, dump_flags, repeat_factor_d::factor, print_generic_expr(), and repeat_factor_d::repr.

static gimple build_and_add_sum ( )
static

Builds one statement performing OP1 OPCODE OP2 using TMPVAR for the result. Places the statement after the definition of either OP1 or OP2. Returns the new statement.

Create the addition statement.

 Find an insertion place and insert.   

References bitmap_clear(), bitmap_first_set_bit(), bitmap_set_bit, candidates, changed, hash_table< Descriptor, Allocator >::create(), dump_file, dump_flags, EXECUTE_IF_SET_IN_BITMAP, FOR_EACH_VEC_ELT, gimple_assign_rhs_code(), is_gimple_assign(), is_reassociable_op(), linearize_expr_tree(), operand_entry::op, print_generic_expr(), sbitmap_alloc(), sbitmap_free(), SSA_NAME_DEF_STMT, and TREE_CODE.

static bool can_reassociate_p ( )
static

Returns true if OP is of a type for which we can do reassociation. That is for integral or non-saturating fixed-point types, and for floating point type when associative-math is enabled.

References repeat_factor_d::count, FOR_EACH_VEC_ELT, HOST_WIDE_INT, and repeat_factor_d::repr.

static int compare_repeat_factors ( )
static

Used for sorting the repeat factor vector. Sort primarily by ascending occurrence count, secondarily by descending rank.

static int constant_type ( )
inlinestatic

Classify an invariant tree into integer, float, or other, so that we can sort them to be near other constants of the same type.

References operand_entry::id, operand_entry::op, and SSA_NAME_VERSION.

void debug_ops_vector ( vec< operand_entry_t ops)
DEBUG_FUNCTION void debug_ops_vector ( )

Dump the operand entry vector OPS to STDERR.

static HOST_WIDE_INT decrement_power ( )
static

Given STMT which is a __builtin_pow* call, decrement its exponent in place and return the result. Assumes that stmt_is_power_of_op was previously called for STMT and returned TRUE.

References gimple_assign_rhs1(), gimple_assign_rhs2(), gimple_assign_rhs_code(), propagate_op_to_single_use(), SSA_NAME_DEF_STMT, and stmt_is_power_of_op().

static void do_reassoc ( )
static
void dump_ops_vector ( FILE *  file,
vec< operand_entry_t ops 
)
void dump_ops_vector ( )

Dump the operand entry vector OPS to FILE.

static bool eliminate_duplicate_pair ( enum tree_code  opcode,
vec< operand_entry_t > *  ops,
bool all_done,
unsigned int  i,
operand_entry_t  curr,
operand_entry_t  last 
)
static

If CURR and LAST are a pair of ops that OPCODE allows us to eliminate through equivalences, do so, remove them from OPS, and return true. Otherwise, return false.

If we have two of the same op, and the opcode is & |, min, or max, we can eliminate one of them. If we have two of the same op, and the opcode is ^, we can eliminate both of them.

static bool eliminate_not_pairs ( enum tree_code  opcode,
vec< operand_entry_t > *  ops,
unsigned int  currindex,
operand_entry_t  curr 
)
static

If OPCODE is BIT_IOR_EXPR, BIT_AND_EXPR, and, CURR->OP is really a bitwise not expression, look in OPS for a corresponding operand to cancel it out. If we find one, remove the other from OPS, replace OPS[CURRINDEX] with 0, and return true. Otherwise, return false.

Any non-not version will have a rank that is one less than the current rank. So once we hit those ranks, if we don't find one, we can stop.

static bool eliminate_plus_minus_pair ( enum tree_code  opcode,
vec< operand_entry_t > *  ops,
unsigned int  currindex,
operand_entry_t  curr 
)
static

If OPCODE is PLUS_EXPR, CURR->OP is a negate expression or a bitwise not expression, look in OPS for a corresponding positive operation to cancel it out. If we find one, remove the other from OPS, replace OPS[CURRINDEX] with 0 or -1, respectively, and return true. Otherwise, return false.

Any non-negated version will have a rank that is one less than the current rank. So once we hit those ranks, if we don't find one, we can stop.

 CURR->OP is a negate expr in a plus expr: save it for later
 inspection in repropagate_negates().   
static bool eliminate_redundant_comparison ( enum tree_code  opcode,
vec< operand_entry_t > *  ops,
unsigned int  currindex,
operand_entry_t  curr 
)
static

If OPCODE is BIT_IOR_EXPR or BIT_AND_EXPR and CURR is a comparison expression, examine the other OPS to see if any of them are comparisons of the same values, which we may be able to combine or eliminate. For example, we can rewrite (a < b) | (a == b) as (a <= b).

 Check that CURR is a comparison.   
 Now look for a similar comparison in the remaining OPS.   
     If we got here, we have a match.  See if we can combine the
     two comparisons.   
     maybe_fold_and_comparisons and maybe_fold_or_comparisons
     always give us a boolean_type_node value back.  If the original
     BIT_AND_EXPR or BIT_IOR_EXPR was of a wider integer type,
     we need to convert.   
     Now we can delete oe, as it has been subsumed by the new combined
     expression t.   
     If t is the same as curr->op, we're done.  Otherwise we must
     replace curr->op with t.  Special case is if we got a constant
     back, in which case we add it to the end instead of in place of
     the current entry.   
static void eliminate_using_constants ( enum tree_code  opcode,
vec< operand_entry_t > *  ops 
)
static

Use constant value that may be present in OPS to try to eliminate operands. Note that this function is only really used when we've eliminated ops for other reasons, or merged constants. Across single statements, fold already does all of this, plus more. There is little point in duplicating logic, so I've only included the identities that I could ever construct testcases to trigger.

static unsigned int execute_reassoc ( )
static

Gate and execute functions for Reassociation.

static bool final_range_test_p ( )
static

Return true if STMT is a cast like: <bb n>="">: ... _123 = (int) _234;

<bb m>="">:

_345 = PHI <_123(N), 1(...), 1(...)>

where _234 has bool type, _123 has single use and bb N has a single successor M. This is commonly used in the last block of a range test.

Test whether lhs is consumed only by a PHI in the only successor bb.

 And that the rhs is defined in the same loop.   

References edge_def::dest_idx, gimple_assign_lhs(), gimple_phi_arg_def(), gsi_stmt(), integer_onep(), integer_zerop(), last_stmt(), and operand_equal_p().

static gimple find_insert_point ( )
inlinestatic

If definition of RHS1 or RHS2 dominates STMT, return the later of those two definitions, otherwise return STMT.

References exact_log2().

Referenced by is_phi_for_stmt(), remove_visited_stmt_chain(), and swap_ops_for_binary_stmt().

static long find_operand_rank ( )
inlinestatic

Look up the operand rank structure for expression E.

References is_gimple_min_invariant().

Referenced by get_rank().

static void fini_reassoc ( )
static

Cleanup after the reassociation pass, and print stats if requested.

static bool gate_tree_ssa_reassoc ( )
static
static bool get_ops ( tree  var,
enum tree_code  code,
vec< operand_entry_t > *  ops,
struct loop loop 
)
static

If VAR is set by CODE (BIT_{AND,IOR}_EXPR) which is reassociable, return true and fill in *OPS recursively.

static long get_rank ( tree  )
static

Forward decls.

static long get_rank ( )
static

Given an expression E, return the rank of the expression.

 Constants have rank 0.   
 SSA_NAME's have the rank of the expression they are the result
 of.
 For globals and uninitialized values, the rank is 0.
 For function arguments, use the pre-setup rank.
 For PHI nodes, stores, asm statements, etc, we use the rank of
 the BB.
 For simple operations, the rank is the maximum rank of any of
 its operands, or the bb_rank, whichever is less.
 I make no claims that this is optimal, however, it gives good
 results.   
 We make an exception to the normal ranking system to break
 dependences of accumulator variables in loops.  Suppose we
 have a simple one-block loop containing:

   x_1 = phi(x_0, x_2)
   b = a + x_1
   c = b + d
   x_2 = c + e

 As shown, each iteration of the calculation into x is fully
 dependent upon the iteration before it.  We would prefer to
 see this in the form:

   x_1 = phi(x_0, x_2)
   b = a + d
   c = b + e
   x_2 = c + x_1

 If the loop is unrolled, the calculations of b and c from
 different iterations can be interleaved.

 To obtain this result during reassociation, we bias the rank
 of the phi definition x_1 upward, when it is recognized as an
 accumulator pattern.  The artificial rank causes it to be 
 added last, providing the desired independence.   
     If we already have a rank for this expression, use that.   
     Otherwise, find the maximum rank for the operands.  As an
     exception, remove the bias from loop-carried phis when propagating
     the rank so that dependent operations are not also biased.   
     Note the rank in the hashtable so we don't recompute it.   
 Globals, etc,  are rank 0  

References bb_rank, dump_file, dump_flags, find_operand_rank(), gcc_assert, gimple_assign_rhs1(), gimple_assign_single_p(), gimple_bb(), gimple_num_ops(), gimple_op(), gimple_vdef(), basic_block_def::index, insert_operand_rank(), is_gimple_assign(), NULL_TREE, phi_rank(), print_generic_expr(), propagate_rank(), SSA_NAME_DEF_STMT, SSA_NAME_IS_DEFAULT_DEF, TDF_DETAILS, TREE_OPERAND, and TREE_OPERAND_LENGTH.

static int get_reassociation_width ( int  ops_num,
enum tree_code  opc,
enum machine_mode  mode 
)
static

Returns an optimal number of registers to use for computation of given statements.

Get the minimal time required for sequence computation.

 Check if we may use less width and still compute sequence for
 the same time.  It will allow us to reduce registers usage.
 get_required_cycles is monotonically increasing with lower width
 so we can perform a binary search for the minimal width that still
 results in the optimal cycle count.   
static int get_required_cycles ( )
static

Find out how many cycles we need to compute statements chain. OPS_NUM holds number os statements in a chain. CPU_WIDTH is a maximum number of independent statements we may execute per cycle.

While we have more than 2 * cpu_width operands we may reduce number of operands by cpu_width per cycle.

 Remained operands count may be reduced twice per cycle
 until we have only one operand.   

References dump_file, and print_gimple_stmt().

static gimple get_single_immediate_use ( )
static

If LHS has a single immediate use that is a GIMPLE_ASSIGN statement, return it. Otherwise, return NULL.

static tree get_unary_op ( )
static

Given NAME, if NAME is defined by a unary operation OPCODE, return the operand of the negate operation. Otherwise, return NULL.

References dump_file, operand_entry::op, print_generic_expr(), and print_generic_stmt().

static void init_range_entry ( )
static

This is similar to make_range in fold-const.c, but on top of GIMPLE instead of trees. If EXP is non-NULL, it should be an SSA_NAME and STMT argument is ignored, otherwise STMT argument should be a GIMPLE_COND.

 Start with simply saying "EXP != 0" and then look at the code of EXP
 and see if we can refine the range.  Some of the cases below may not
 happen, but it doesn't seem worth worrying about this.  We "continue"
 the outer loop when we've changed something; otherwise we "break"
 the switch, which will "break" the while.   
             Ensure the range is either +[-,0], +[0,0],
             -[-,0], -[0,0] or +[1,-], +[1,1], -[1,-] or
             -[1,1].  If it is e.g. +[-,-] or -[-,-]
             or similar expression of unconditional true or
             false, it should not be negated.   
         FALLTHRU  

References TREE_TYPE, and TYPE_UNSIGNED.

Referenced by optimize_range_tests_diff().

static void init_reassoc ( )
static

Initialize the reassociation pass.

 Find the loops, so that we can prevent moving calculations in
 them.   
 Reverse RPO (Reverse Post Order) will give us something where
 deeper loops come later.   
 Give each default definition a distinct rank.  This includes
 parameters and the static chain.  Walk backwards over all
 SSA names so that we get proper rank ordering according
 to tree_swap_operands_p.   
 Set up rank for each BB   
static void insert_operand_rank ( )
inlinestatic

Insert {E,RANK} into the operand rank hashtable.

Referenced by get_rank().

static void insert_stmt_after ( )
static

Insert STMT after INSERT_POINT.

We assume INSERT_POINT is a SSA_NAME_DEF_STMT of some SSA_NAME, thus if it must end a basic block, it should be a call that can throw, or some assignment that can throw. If it throws, the LHS of it will not be initialized though, so only valid places using the SSA_NAME should be dominated by the fallthru edge.

Referenced by is_phi_for_stmt(), and swap_ops_for_binary_stmt().

static bool is_phi_for_stmt ( )
static

Return true if OPERAND is defined by a PHI node which uses the LHS of STMT in it's operands. This is also known as a "destructive update" operation.

References dump_file, dump_flags, find_insert_point(), gimple_assign_rhs_code(), gimple_build_assign_with_ops(), gimple_set_uid(), gimple_set_visited(), gimple_uid(), gsi_for_stmt(), gsi_insert_before(), GSI_SAME_STMT, gsi_stmt(), insert_stmt_after(), make_ssa_name(), NULL, operand_entry::op, and print_gimple_stmt().

static bool is_reassociable_op ( )
static

Return true if STMT is reassociable operation containing a binary operation with tree code CODE, and is inside LOOP.

References dump_file, dump_flags, operand_entry::op, and TDF_DETAILS.

Referenced by build_and_add_sum().

static void linearize_expr ( )
static

Transform STMT, which is really (A +B) + (C + D) into the left linear form, ((A+B)+C)+D. Recurse on D if necessary.

Tail recurse on the new rhs if it still needs reassociation.

   ??? This should probably be linearize_expr (newbinrhs) but I don't
       want to change the algorithm while converting to tuples.   

References dump_file, dump_flags, gimple_assign_rhs1(), gimple_assign_rhs2(), gimple_assign_set_rhs_with_ops(), negate_value(), print_gimple_stmt(), and update_stmt().

static void linearize_expr_tree ( vec< operand_entry_t > *  ops,
gimple  stmt,
bool  is_associative,
bool  set_visited 
)
static

Recursively linearize a binary expression that is the RHS of STMT. Place the operands of the expression tree in the vector named OPS.

 If the LHS is not reassociable, but the RHS is, we need to swap
 them.  If neither is reassociable, there is nothing we can do, so
 just put them in the ops vector.  If the LHS is reassociable,
 linearize it.  If both are reassociable, then linearize the RHS
 and the LHS.   
     If this is not a associative operation like division, give up.   
     We want to make it so the lhs is always the reassociative op,
     so swap.   

Referenced by build_and_add_sum().

static bool loop_carried_phi ( )
static

If EXP is an SSA_NAME defined by a PHI statement that represents a loop-carried dependence of an innermost loop, return TRUE; else return FALSE.

Non-loop-carried phis have block rank. Loop-carried phis have an additional bias added in. If this phi doesn't have block rank, it's biased and should not be propagated.

gimple_opt_pass* make_pass_reassoc ( )
static void maybe_optimize_range_tests ( )
static

Inter-bb range test optimization.

 Consider only basic blocks that end with GIMPLE_COND or
 a cast statement satisfying final_range_test_p.  All
 but the last bb in the first_bb .. last_bb range
 should end with GIMPLE_COND.   
 As relative ordering of post-dominator sons isn't fixed,
 maybe_optimize_range_tests can be called first on any
 bb in the range we want to optimize.  So, start searching
 backwards, if first_bb can be set to a predecessor.   
 If first_bb is last_bb, other_bb hasn't been computed yet.
 Before starting forward search in last_bb successors, find
 out the other_bb.   
     As non-GIMPLE_COND last stmt always terminates the range,
     if forward search didn't discover anything, just give up.   
     Look at both successors.  Either it ends with a GIMPLE_COND
     and satisfies suitable_cond_bb, or ends with a cast and
     other_bb is that cast's successor.   
 Now do the forward search, moving last_bb to successor bbs
 that aren't other_bb.   
 Here basic blocks first_bb through last_bb's predecessor
 end with GIMPLE_COND, all of them have one of the edges to
 other_bb and another to another block in the range,
 all blocks except first_bb don't have side-effects and
 last_bb ends with either GIMPLE_COND, or cast satisfying
 final_range_test_p.   
         stmt is
         _123 = (int) _234;

         followed by:
         <bb M>:
         # _345 = PHI <_123(N), 1(...), 1(...)>

         or 0 instead of 1.  If it is 0, the _234
         range test is anded together with all the
         other range tests, if it is 1, it is ored with
         them.   
         If _234 SSA_NAME_DEF_STMT is
         _234 = _567 | _789;
         (or &, corresponding to 1/0 in the phi arguments,
         push into ops the individual range test arguments
         of the bitwise or resp. and, recursively.   
             Otherwise, push the _234 range test itself.   
     Otherwise stmt is GIMPLE_COND.   
                Either push into ops the individual bitwise
                or resp. and operands, depending on which
                edge is other_bb.   
         Or push the GIMPLE_COND stmt itself.   
         oe->op = NULL signs that there is no SSA_NAME
         for the range test, and oe->id instead is the
         basic block number, at which's end the GIMPLE_COND
         is.   
static tree negate_value ( )
static

Recursively negate the value of TONEGATE, and return the SSA_NAME representing the negated value. Insertions of any necessary instructions go before GSI. This function is recursive in that, if you hand it "a_5" as the value to negate, and a_5 is defined by "a_5 = b_3 + b_4", it will transform b_3 + b_4 into a_5 = -b_3 + -b_4.

If we are trying to negate a name, defined by an add, negate the add operands instead.

Referenced by linearize_expr().

static bool no_side_effect_bb ( )
static

Return true if BB doesn't have side-effects that would disallow range test optimization, all SSA_NAMEs set in the bb are consumed in the bb and there are no PHIs.

static int oecount_cmp ( )
static

Comparison function for qsort sorting oecount elements by count.

If counts are identical, use unique IDs to stabilize qsort.

static void optimize_ops_list ( enum tree_code  opcode,
vec< operand_entry_t > *  ops 
)
static

Perform various identities and other optimizations on the list of operand entries, stored in OPS. The tree code for the binary operation between all the operands is OPCODE.

If the last two are constants, pop the constants off, merge them and try the next two.

References range_entry::exp, range_entry::high, range_entry::idx, range_entry::in_p, range_entry::low, range_entry::next, and range_entry::strict_overflow_p.

static bool optimize_range_tests ( enum tree_code  opcode,
vec< operand_entry_t > *  ops 
)
static

Optimize range tests, similarly how fold_range_test optimizes it on trees. The tree code for the binary operation between all the operands is OPCODE. If OPCODE is ERROR_MARK, optimize_range_tests is called from within maybe_optimize_range_tests for inter-bb range optimization. In that case if oe->op is NULL, oe->id is bb->index whose GIMPLE_COND is && or ||ed into the test, and oe->rank says the actual opcode.

For | invert it now, we will invert it again before emitting
the optimized expression.   
 Try to merge ranges.   


     Avoid quadratic complexity if all merge_ranges calls would succeed,
     while update_range_test would fail.   
static bool optimize_range_tests_1 ( enum tree_code  opcode,
int  first,
int  length,
bool  optimize_xor,
vec< operand_entry_t > *  ops,
struct range_entry ranges 
)
static

It does some common checks for function optimize_range_tests_xor and optimize_range_tests_diff. If OPTIMIZE_XOR is TRUE, it calls optimize_range_tests_xor. Else it calls optimize_range_tests_diff.

Check lowj > highi.

static bool optimize_range_tests_diff ( enum tree_code  opcode,
tree  type,
tree  lowi,
tree  lowj,
tree  highi,
tree  highj,
vec< operand_entry_t > *  ops,
struct range_entry rangei,
struct range_entry rangej 
)
static

Optimize X == CST1 || X == CST2 if popcount (CST2 - CST1) == 1 into ((X - CST1) & ~(CST2 - CST1)) == 0. Similarly for ranges. E.g. X == 43 || X == 76 || X == 44 || X == 78 || X == 77 || X == 46 || X == 75 || X == 45 will be transformed by the previous optimization into (X - 43U) <= 3U || (X - 75U) <= 3U and this loop can transform that into ((X - 43U) & ~(75U - 43U)) <= 3U.

Check highi - lowi == highj - lowj.

 Check popcount (lowj - lowi) == 1.   

References BASIC_BLOCK, first, range_entry::high, operand_entry::id, range_entry::idx, range_entry::in_p, init_range_entry(), last_stmt(), range_entry::low, merge_ranges(), NULL, NULL_TREE, operand_entry::op, range_entry_cmp(), operand_entry::rank, range_entry::strict_overflow_p, and TREE_CODE.

static bool optimize_range_tests_xor ( enum tree_code  opcode,
tree  type,
tree  lowi,
tree  lowj,
tree  highi,
tree  highj,
vec< operand_entry_t > *  ops,
struct range_entry rangei,
struct range_entry rangej 
)
static

Optimize X == CST1 || X == CST2 if popcount (CST1 ^ CST2) == 1 into (X & ~(CST1 ^ CST2)) == (CST1 & ~(CST1 ^ CST2)). Similarly for ranges. E.g. X != 2 && X != 3 && X != 10 && X != 11 will be transformed by the previous optimization into !((X - 2U) <= 1U || (X - 10U) <= 1U) and this loop can transform that into !(((X & ~8) - 2U) <= 1U).

Check highi ^ lowi == highj ^ lowj and popcount (highi ^ lowi) == 1.

static long phi_rank ( )
static

Rank assigned to a phi statement. If STMT is a loop-carried phi of an innermost loop, and the phi has only a single use which is inside the loop, then the rank is the block rank of the loop latch plus an extra bias for the loop-carried dependence. This causes expressions calculated into an accumulator variable to be independent for each iteration of the loop. If STMT is some other phi, the rank is the block rank of its containing block.

 We only care about real loops (those with a latch).   
 Interesting phis must be in headers of innermost loops.   
 Ignore virtual SSA_NAMEs.   
 The phi definition must have a single use, and that use must be
 within the loop.  Otherwise this isn't an accumulator pattern.   
 Look for phi arguments from within the loop.  If found, bias this phi.   
 Must be an uninteresting phi.   

Referenced by get_rank().

static void propagate_op_to_single_use ( )
static

Find the single immediate use of STMT's LHS, and replace it with OP. Remove STMT. If STMT's LHS is the same as *DEF, replace *DEF with OP as well.

Referenced by decrement_power().

static long propagate_rank ( )
static

Return the maximum of RANK and the rank that should be propagated from expression OP. For most operands, this is just the rank of OP. For loop-carried phis, the value is zero to avoid undoing the bias in favor of the phi.

Referenced by get_rank().

static int range_entry_cmp ( )
static

Comparison function for qsort. Sort entries without SSA_NAME exp first, then with SSA_NAMEs sorted by increasing SSA_NAME_VERSION, and for the same SSA_NAMEs by increasing ->low and if ->low is the same, by increasing ->high. ->low == NULL_TREE means minimum, ->high == NULL_TREE maximum.

         Group range_entries for the same SSA_NAME together.   
         If ->low is different, NULL low goes first, then by
         ascending low.   
         If ->high is different, NULL high goes last, before that by
         ascending high.   
         If both ranges are the same, sort below by ascending idx.   

Referenced by optimize_range_tests_diff().

static bool reassoc_stmt_dominates_stmt_p ( )
static

Returns true if statement S1 dominates statement S2. Like stmt_dominates_stmt_p, but uses stmt UIDs to optimize.

 If bb1 is NULL, it should be a GIMPLE_NOP def stmt of an (D)
 SSA_NAME.  Assume it lives at the beginning of function and
 thus dominates everything.   
 If bb2 is NULL, it doesn't dominate any stmt with a bb.   
     PHIs in the same basic block are assumed to be
     executed all in parallel, if only one stmt is a PHI,
     it dominates the other stmt in the same basic block.   
static void reassociate_bb ( )
static

Reassociate expressions in basic block BB and its post-dominator as children.

         If this is not a gimple binary expression, there is
         nothing for us to do with it.   
         If this was part of an already processed statement,
         we don't need to touch it again.  
             This statement might have become dead because of previous
             reassociations.   
                 We might end up removing the last stmt above which
                 places the iterator to the end of the sequence.
                 Reset it to the last stmt in this case which might
                 be the end of the sequence as well if we removed
                 the last statement of the sequence.  In which case
                 we need to bail out.   
         For non-bit or min/max operations we can't associate
         all types.  Verify that here.   
             There may be no immediate uses left by the time we
             get here because we may have eliminated them all.   
             If the operand vector is now empty, all operands were 
             consumed by the __builtin_powi optimization.   
                     When there are three operands left, we want
                     to make sure the ones that get the double
                     binary op are chosen wisely.   
                 If we combined some repeated factors into a 
                 __builtin_powi call, multiply that result by the
                 reassociated operands.   
static void remove_visited_stmt_chain ( )
static

Remove def stmt of VAR if VAR has zero uses and recurse on rhs1 operand if so.

References find_insert_point(), gcc_checking_assert, gimple_assign_set_rhs1(), gimple_assign_set_rhs2(), operand_entry::op, and update_stmt().

static void repropagate_negates ( )
static

Repropagate the negates back into subtracts, since no other pass currently does it.

     The negate operand can be either operand of a PLUS_EXPR
     (it can be the LHS if the RHS is a constant for example).

     Force the negate operand to the RHS of the PLUS_EXPR, then
     transform the PLUS_EXPR into a MINUS_EXPR.   
         If the negated operand appears on the LHS of the
         PLUS_EXPR, exchange the operands of the PLUS_EXPR
         to force the negated operand to the RHS of the PLUS_EXPR.   
         Now transform the PLUS_EXPR into a MINUS_EXPR and replace
         the RHS of the PLUS_EXPR with the operand of the NEGATE_EXPR.   
             We have
               x = -a
               y = x - b
             which we transform into
               x = a + b
               y = -x .
             This pushes down the negate which we possibly can merge
             into some other operation, hence insert it into the
             plus_negates vector.   
             Transform "x = -a; y = b - x" into "y = b + a", getting
             rid of one operation.   

References repeat_factor_d::count, and repeat_factor_d::rank.

static tree rewrite_expr_tree ( gimple  stmt,
unsigned int  opindex,
vec< operand_entry_t ops,
bool  changed 
)
static

Recursively rewrite our linearized statements so that the operators match those in OPS[OPINDEX], putting the computation in rank order. Return new lhs.

 The final recursion case for this function is that you have
 exactly two operations left.
 If we had one exactly one op in the entire list to start with, we
 would have never called this function, and the tail recursion
 rewrites them one at a time.   
 If we hit here, we should have 3 or more ops left.   
 Rewrite the next operator.   
 Recurse on the LHS of the binary operator, which is guaranteed to
 be the non-leaf side.   
     If changed is false, this is either opindex == 0
     or all outer rhs2's were equal to corresponding oe->op,
     and powi_result is NULL.
     That means lhs is equivalent before and after reassociation.
     Otherwise ensure the old lhs SSA_NAME is not reused and
     create a new stmt as well, so that any debug stmts will be
     properly adjusted.   
static void rewrite_expr_tree_parallel ( gimple  stmt,
int  width,
vec< operand_entry_t ops 
)
static

Recursively rewrite our linearized statements so that the operators match those in OPS[OPINDEX], putting the computation in rank order and trying to allow operations to be executed in parallel.

 We start expression rewriting from the top statements.
 So, in this loop we create a full list of statements
 we will work with.   
     Determine whether we should use results of
     already handled statements or not.   
     Now we choose operands for the next statement.  Non zero
     value in ready_stmts_end means here that we should use
     the result of already generated statements as new operand.   
     If we emit the last statement then we should put
     operands into the last statement.  It will also
     break the loop.   
     We keep original statement only for the last one.  All
     others are recreated.   
static bool should_break_up_subtract ( )
static

Return true if we should break up the subtract in STMT into an add with negate. This is true when we the subtract operands are really adds, or the subtract itself is used in an add expression. In either case, breaking up the subtract into an add with negate exposes the adds to reassociation.

static int sort_by_operand_rank ( )
static

qsort comparison function to sort operand entries PA and PB by rank so that the sorted array is ordered by rank in decreasing order.

 It's nicer for optimize_expression if constants that are likely
 to fold when added/multiplied//whatever are put next to each
 other.  Since all constants have rank 0, order them by type.   
       To make sorting result stable, we use unique IDs to determine
       order.   
 Lastly, make sure the versions that are the same go next to each
 other.  We use SSA_NAME_VERSION because it's stable.   
static bool stmt_is_power_of_op ( )
static

Return TRUE iff STMT represents a builtin call that raises OP to some exponent.

References gcc_assert, gimple_assign_lhs(), gimple_call_lhs(), gsi_for_stmt(), gsi_remove(), has_single_use(), is_gimple_call(), release_defs(), SET_USE, single_imm_use(), TREE_CODE, unlink_stmt_vdef(), and update_stmt().

Referenced by decrement_power().

static bool suitable_cond_bb ( basic_block  bb,
basic_block  test_bb,
basic_block other_bb,
bool  backward 
)
static

Return true if BB is suitable basic block for inter-bb range test optimization. If BACKWARD is true, BB should be the only predecessor of TEST_BB, and *OTHER_BB is either NULL and filled by the routine, or compared with to find a common basic block to which all conditions branch to if true resp. false. If BACKWARD is false, TEST_BB should be the only predecessor of BB.

 Check last stmt first.   
     If last stmt is GIMPLE_COND, verify that one of the succ edges
     goes to the next bb (if BACKWARD, it is TEST_BB), and the other
     to *OTHER_BB (if not set yet, try to find it out).   
 Now check all PHIs of *OTHER_BB.   
     If both BB and TEST_BB end with GIMPLE_COND, all PHI arguments
     corresponding to BB and TEST_BB predecessor must be the same.   
         Otherwise, if one of the blocks doesn't end with GIMPLE_COND,
         one of the PHIs should have the lhs of the last stmt in
         that block as PHI arg and that PHI should have 0 or 1
         corresponding to it in all other range test basic blocks
         considered.   
static void swap_ops_for_binary_stmt ( vec< operand_entry_t ops,
unsigned int  opindex,
gimple  stmt 
)
static

This function checks three consequtive operands in passed operands vector OPS starting from OPINDEX and swaps two operands if it is profitable for binary operation consuming OPINDEX + 1 abnd OPINDEX + 2 operands.

We pair ops with the same rank if possible.

The alternative we try is to see if STMT is a destructive update style statement, which is like: b = phi (a, ...) a = c + b; In that case, we want to use the destructive update form to expose the possible vectorizer sum reduction opportunity. In that case, the third operand will be the phi node. This check is not performed if STMT is null.

We could, of course, try to be better as noted above, and do a lot of work to try to find these opportunities in >3 operand cases, but it is unlikely to be worth it.

References find_insert_point(), gimple_assign_rhs_code(), gimple_build_assign_with_ops(), gimple_set_uid(), gimple_set_visited(), gimple_uid(), gsi_for_stmt(), gsi_insert_before(), GSI_SAME_STMT, gsi_stmt(), insert_stmt_after(), make_ssa_name(), and NULL.

static void transform_stmt_to_copy ( )
static

Transform STMT at *GSI into a copy by replacing its rhs with NEW_RHS.

static void transform_stmt_to_multiply ( gimple_stmt_iterator gsi,
gimple  stmt,
tree  rhs1,
tree  rhs2 
)
static

Transform STMT at *GSI into a multiply of RHS1 and RHS2.

References dump_ops_vector().

static bool undistribute_ops_list ( enum tree_code  opcode,
vec< operand_entry_t > *  ops,
struct loop loop 
)
static

Perform un-distribution of divisions and multiplications. A * X + B * X is transformed into (A + B) * X and A / X + B / X to (A + B) / X for real X.

The algorithm is organized as follows.

  • First we walk the addition chain *OPS looking for summands that are defined by a multiplication or a real division. This results in the candidates bitmap with relevant indices into *OPS.
  • Second we build the chains of multiplications or divisions for these candidates, counting the number of occurrences of (operand, code) pairs in all of the candidates chains.
  • Third we sort the (operand, code) pairs by number of occurrence and process them starting with the pair with the most uses.

    For each such pair we walk the candidates again to build a second candidate bitmap noting all multiplication/division chains that have at least one occurrence of (operand, code).

    We build an alternate addition chain only covering these candidates with one (operand, code) operation removed from their multiplication/division chain.

    The first candidate gets replaced by the alternate addition chain multiplied/divided by the operand.

    All candidate chains get disabled for further processing and processing of (operand, code) pairs continues.

The alternate addition chains built are re-processed by the main reassociation algorithm which allows optimizing a * x * y + b * y * x to (a + b ) * x * y in one invocation of the reassociation pass.

 Build a list of candidates to process.   
 Build linearized sub-operand lists and the counting table.   
 ??? Macro arguments cannot have multi-argument template types in
 them.  This typedef is needed to workaround that limitation.   
 Sort the counting table.   
 Process the (operand, code) pairs in order of most occurrence.   
     Now collect the operands in the outer chain that contain
     the common operand in their inner chain.   
         If we undistributed in this chain already this may be
         a constant.   
         Build the new addition chain.   
         Apply the multiplication/division.   
         Record it in the addition chain and disable further
         undistribution with this op.   
static tree update_ops ( tree  var,
enum tree_code  code,
vec< operand_entry_t ops,
unsigned int *  pidx,
struct loop loop 
)
static

Find the ops that were added by get_ops starting from VAR, see if they were changed during update_range_test and if yes, create new stmts.

static bool update_range_test ( struct range_entry range,
struct range_entry otherrange,
unsigned int  count,
enum tree_code  opcode,
vec< operand_entry_t > *  ops,
tree  exp,
bool  in_p,
tree  low,
tree  high,
bool  strict_overflow_p 
)
static

Helper routine of optimize_range_test. [EXP, IN_P, LOW, HIGH, STRICT_OVERFLOW_P] is a merged range for RANGE and OTHERRANGE through OTHERRANGE + COUNT - 1 ranges, OPCODE and OPS are arguments of optimize_range_tests. Return true if the range merge has been successful. If OPCODE is ERROR_MARK, this is called from within maybe_optimize_range_tests and is performing inter-bb range optimization. In that case, whether an op is BIT_AND_EXPR or BIT_IOR_EXPR is found in oe->rank.

Now change all the other range test immediate uses, so that those tests will be optimized away.

References exp(), range_entry::exp, fold_binary, fold_build1, fold_build2, range_entry::in_p, NULL_TREE, range_entry::strict_overflow_p, TREE_CODE, tree_int_cst_equal(), and tree_log2().

static void zero_one_operation ( )
static

Walks the linear chain with result *DEF searching for an operation with operand OP and code OPCODE removing that from the chain. *DEF is updated if there is only one operand but no operation left.

     If this is the operation we look for and one of the operands
     is ours simply propagate the other operand into the stmts
     single use.   
     We might have a multiply of two __builtin_pow* calls, and
     the operand might be hiding in the rightmost one.   
     Continue walking the chain.   

References CDI_DOMINATORS, dominated_by_p(), gcc_assert, gimple_bb(), gimple_uid(), gsi_end_p(), gsi_for_stmt(), gsi_next(), and gsi_stmt().


Variable Documentation

long* bb_rank
static

Starting rank number for a given basic block, so that we can rank operations using unmovable instructions in that BB based on the bb depth.

Referenced by get_rank().

int constants_eliminated
vec<oecount> cvec
static

The heap for the oecount hashtable and the sorted list of operands.

int linearized
int next_operand_entry_id
static

This is used to assign a unique ID to each struct operand_entry so that qsort results are identical on different hosts.

alloc_pool operand_entry_pool
static
struct pointer_map_t* operand_rank
static

Operand->rank hashtable.

int ops_eliminated
vec<tree> plus_negates
static
int pows_created
int pows_encountered
struct { ... } reassociate_stats

Reassociation for trees. Copyright (C) 2005-2013 Free Software Foundation, Inc. Contributed by Daniel Berlin dan@d.nosp@m.berl.nosp@m.in.or.nosp@m.g

This file is part of GCC.

GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.

GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see http://www.gnu.org/licenses/. This is a simple global reassociation pass. It is, in part, based on the LLVM pass of the same name (They do some things more/less than we do, in different orders, etc).

It consists of five steps:

  1. Breaking up subtract operations into addition + negate, where it would promote the reassociation of adds.
  1. Left linearization of the expression trees, so that (A+B)+(C+D) becomes (((A+B)+C)+D), which is easier for us to rewrite later. During linearization, we place the operands of the binary expressions into a vector of operand_entry_t
  1. Optimization of the operand lists, eliminating things like a + -a, a & a, etc.

3a. Combine repeated factors with the same occurrence counts into a __builtin_powi call that will later be optimized into an optimal number of multiplies.

  1. Rewrite the expression trees we linearized and optimized so they are in proper rank order.
  1. Repropagate negates, as nothing else will clean it up ATM.

A bit of theory on #4, since nobody seems to write anything down about why it makes sense to do it the way they do it:

We could do this much nicer theoretically, but don't (for reasons explained after how to do it theoretically nice :P).

In order to promote the most redundancy elimination, you want binary expressions whose operands are the same rank (or preferably, the same value) exposed to the redundancy eliminator, for possible elimination.

So the way to do this if we really cared, is to build the new op tree from the leaves to the roots, merging as you go, and putting the new op on the end of the worklist, until you are left with one thing on the worklist.

IE if you have to rewrite the following set of operands (listed with rank in parentheses), with opcode PLUS_EXPR:

a (1), b (1), c (1), d (2), e (2)

We start with our merge worklist empty, and the ops list with all of those on it.

You want to first merge all leaves of the same rank, as much as possible.

So first build a binary op of

mergetmp = a + b, and put "mergetmp" on the merge worklist.

Because there is no three operand form of PLUS_EXPR, c is not going to be exposed to redundancy elimination as a rank 1 operand.

So you might as well throw it on the merge worklist (you could also consider it to now be a rank two operand, and merge it with d and e, but in this case, you then have evicted e from a binary op. So at least in this situation, you can't win.)

Then build a binary op of d + e mergetmp2 = d + e

and put mergetmp2 on the merge worklist.

so merge worklist = {mergetmp, c, mergetmp2}

Continue building binary ops of these operations until you have only one operation left on the worklist.

So we have

build binary op mergetmp3 = mergetmp + c

worklist = {mergetmp2, mergetmp3}

mergetmp4 = mergetmp2 + mergetmp3

worklist = {mergetmp4}

because we have one operation left, we can now just set the original statement equal to the result of that operation.

This will at least expose a + b and d + e to redundancy elimination as binary operations.

For extra points, you can reuse the old statements to build the mergetmps, since you shouldn't run out.

So why don't we do this?

Because it's expensive, and rarely will help. Most trees we are reassociating have 3 or less ops. If they have 2 ops, they already will be written into a nice single binary op. If you have 3 ops, a single simple check suffices to tell you whether the first two are of the same rank. If so, you know to order it

mergetmp = op1 + op2 newstmt = mergetmp + op3

instead of mergetmp = op2 + op3 newstmt = mergetmp + op1

If all three are of the same rank, you can't expose them all in a single binary operator anyway, so the above is still the best you can do.

Thus, this is what we do. When we have three ops left, we check to see what order to put them in, and call it a day. As a nod to vector sum reduction, we check if any of the ops are really a phi node that is a destructive update for the associating op, and keep the destructive update together for vector sum reduction recognition. Statistics

vec<repeat_factor> repeat_factor_vec
static
int rewritten