ArticleslgStudy

computer science

Code motion

Code motion is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Code motion rather than just read about it. In short: 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.

Code motion — main illustration
Code motion — illustration

Key takeaways

  • Code motion belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Code motion to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Code motion from memory before moving on to harder problems.

Reference excerpt

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 (as factors), 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 (or "scheduled") 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 (or not yet executed) 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 (BRP) 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.

Loop-invariant code motion

Loop-invariant code motion is the process of moving loop-invariant code to a position outside the loop, which may reduce the execution time of the loop by preventing some computations from being done twice for the same result.

Compiler examples

LLVM LLVM has a sinking pass in its single static assignment form. LLVM 15.0 will not sink an operation if any of its code paths include a store instruction, or if it may throw an error. Additionally, LLVM will not sink an instruction into a loop.

GCC The GNU Compiler Collection implements code motion under the name "code factoring", with the purpose of reducing the size of a compiled program. GCC will move any code upwards or downwards if it "[does not] invalidate any existing dependences nor introduce new ones".

LuaJIT LuaJIT uses code sinking under the name "Allocation sinking", to reduce the amount of time compiled code spends allocating and collecting temporary objects within a loop. Allocation sinking moves allocations to execution paths where the allocated object may escape the executing code, and will thus require heap allocation. All removed allocations are filled in with load-to-store forwarding over their fields.

See also Loop-invariant code motion Instruction scheduling Dependency graph

References

Illustrations

Code motion: A diagram that demonstrates optimizing for size using code factoring, assuming all operations are not dependent on other operations executing before it
A diagram that demonstrates optimizing for size using code factoring, assuming all operations are not dependent on other operations executing before it
Code motion: An example of how a compiler might prevent dependency stalls in assembled code with code movement, by observing a dependency graph. Due to out-of-order execution advancements, optimization may not have any benefit on modern CPUs.
An example of how a compiler might prevent dependency stalls in assembled code with code movement, by observing a dependency graph. Due to out-of-order execution advancements, optimization may not have any benefit on modern CPUs.
Code motion: A diagram depicting loop-invariant code motion over an execution graph. This assumes that D is invariant between loop executions.
A diagram depicting loop-invariant code motion over an execution graph. This assumes that D is invariant between loop executions.

Worked examples

Example 1 — a first encounter with Code motion

Start with the simplest possible case. Write down what Code motion claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Code motion before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Code motion ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Code motion

In research
Code motion appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Code motion in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Code motion is common in secondary-school and first-year university syllabi. It links to neighbouring topics Code refactoring, Compiler optimizations, Compiler theory, so understanding it makes those chapters shorter.
In everyday life
Look for Code motion outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Code motion” →

How to study Code motion in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Code motion means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Code motion out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Code motion in simple terms?

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 mo…

Why does Code motion matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Code motion?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Code motion.

Tags

  • Code refactoring
  • Compiler optimizations
  • Compiler theory
  • Computer performance
  • Program transformation
  • Static program analysis

Keep exploring