Hello,<div><br></div><div>Richard and I hacked up a simple patch to form minimal multiply DAGs when intermediate results are unused. The code should handle fully generic formation of a minimal DAG of multiplies, sharing intermediate values where-ever possible. Check out the test cases for some of the fun simplifications it performs.</div>
<div><br></div><div>The only real problem is where to put it. Currently I've put it in InstCombine, but not because that's really a good home for it (in fact, it can't be the home, read on). The most "natural" home for this type of transform is the Reassociate pass, but that has its own problems....</div>
<div><br></div><div>The reassociate pass does a really nice job of canonicalizing chains of operations into left-linear trees that fully expose each intermediate operation for CSE and combining with other operations. This is a really nice property that seems a shame to loose. If we form the minimal multiply DAG in reassociate  eagerly, we may miss chances to combine non-minimal intermediate steps with other operations.</div>
<div><br></div><div>However, if we use a cleanup pass like instcombine to mop up one-use left-linear trees like this patch does, we can easily get Reassociate and InstCombine dueling over the canonical form, and into an inf-loop we go.</div>
<div><br></div><div>One possible fix is to have InstCombine form a left-linear tree after it forms the minimal folding to try to keep Reassociate from undoing its work... but this all feels a bit hackish. Especially the deferred-processing hack required to ensure InstCombine performs this optimization on the entire tree at once. Suggestions?</div>