Code motion
In computer science, code motion, which includes code hoisting, code sinking, loop-invariant code motion, and code factoring, is a blanket term for any process that moves code within a program. This is typically done for performance and size benefits, and it is a common optimization performed in most optimizing compilers.
Uses
Code motion has a variety of uses and benefits, many of which overlap each other in their implementation.Removing unused/useless operations
Code sinking, also known as lazy code motion, is a term for a technique that reduces wasted instructions by moving instructions to branches in which they are used: If an operation is executed before a branch, and only one of the branch paths use the result of that operation, then code sinking entails moving that operation into the branch where it will be used.This technique is a form of dead code elimination in the sense that it removes code when its results are discarded or unused, but in contrast to dead code elimination, it can remove pointless instructions even if there is a possible use of that instruction’s results in an execution code path.
Reducing the size of the program
Code factoring is a term for a size-optimization technique that merges common dependencies in branches into the branch above it. Just like factorizing integers decomposes a number into its smallest possible forms, code factorization transforms the code into the smallest possible form, by merging common "factors" until no duplicates remain.Reducing dependency stalls
Global code motion, local code motion, code scheduling, Instruction scheduling and code hoisting/sinking are all terms for a technique where instructions are rearranged to improve the efficiency of execution within the CPU. Modern CPUs are able to schedule five or more instructions per clock cycle. However, a CPU cannot schedule an instruction that relies on data from a currently instruction. Compilers will interleave dependencies in a manner that maximizes the amount of instructions a CPU can process at any point in time.On the defunct Intel Itanium architecture, the branch predict instruction is manually hoisted above branches by the compiler to enable the branch to be immediately taken by the CPU. Itanium relies on additional code scheduling from the CPU to maximize efficiency in the processor.