ToolSphere

Code Optimizer

Computer science

Optimize integer TAC with folding, propagation, CSE and live-out-aware dead code; inspect conservative loop motion and simple assembly peephole steps.

Edit the code to see safe simplifications for the selected mode.

13 transformations; t4 = x + y; out = t4 + t4

TAC means three-address code: one simple assignment or jump per line. Integer model with initialized inputs and truncating division. Floating-point code, machine status flags, volatile memory and device I/O are outside this model.

Optimized code

13 recorded transformations

Copy optimized code
t4 = x + y
out = t4 + t4

Step-by-step changes

RuleBeforeAfter
Line 3: constant propagation; constant foldingt1 = a + bt1 = 6
Line 4: algebraic simplificationt2 = x + 0t2 = x
Line 5: algebraic simplificationt3 = y * 1t3 = y
Line 6: copy propagationt4 = t2 + t3t4 = x + y
Line 7: copy propagation; common-subexpression eliminationt5 = t2 + t3t5 = t4
Line 9: copy propagationout = t4 + t5out = t4 + t4
Line 8: dead-code elimination (dead scalar, nontrapping operation)unused = 7removed
Line 7: dead-code elimination (dead scalar, nontrapping operation)t5 = t4removed
Line 5: dead-code elimination (dead scalar, nontrapping operation)t3 = yremoved
Line 4: dead-code elimination (dead scalar, nontrapping operation)t2 = xremoved
Line 3: dead-code elimination (dead scalar, nontrapping operation)t1 = 6removed
Line 2: dead-code elimination (dead scalar, nontrapping operation)b = 2removed
Line 1: dead-code elimination (dead scalar, nontrapping operation)a = 4removed

Assumptions and limits

  • Integer arithmetic with truncating division; all external scalar inputs are assumed initialized.
  • Only declared live-out scalars and array stores are observable; an empty live-out list keeps every assigned scalar.
  • Potentially trapping division, remainder, exponentiation and array loads are retained when their values are dead.

On this browser only

Give feedback

Did this tool help?

Tell us what worked, what didn’t, or what you’d like next.

Opens Google Forms in a new tab with this tool’s name filled in. No sign-in or email required. Feedback is optional.

How to use Code Optimizer

  1. 1Start with the loaded basic-block example and edit one TAC instruction per line.
  2. 2Declare the scalar variables needed after the block, or leave the field blank to preserve every assigned scalar.
  3. 3Read the optimized code and each recorded transformation; assumptions are shown below the result.
  4. 4Choose Loop motion to analyse a whole TAC flow graph, then select a natural-loop header if needed.
  5. 5Choose Peephole assembly for the separate register-machine syntax, and copy the current optimized output.

About Code Optimizer

Inspect why a compiler transformation is valid

This code optimizer shows local TAC transformations, conservative loop-invariant motion and a small assembly peephole pass. Each mode loads an example and updates the result while you edit. The output is accompanied by recorded changes with their original instruction line, rule, previous instruction and replacement. It is an educational optimiser for a declared integer model, not a service that accepts arbitrary C, C++, JavaScript or processor assembly and promises equivalent output.

Basic-block mode combines constant folding, constant propagation, copy propagation, common-subexpression elimination, selected algebraic identities and dead-code elimination. Loop mode uses the same basic-block, reachability, dominator and natural-loop analysis as the flow-graph tool. Peephole mode has a separate abstract register-machine language. Keep the selected language in mind when moving between examples.

State the arithmetic and observable outputs

The TAC model uses integers with truncating division and ordinary nonvolatile arrays. External scalar inputs must already be initialized. Decimal integer literals are supported; floating-point literals are rejected instead of applying integer identities to a different numerical model. Division by zero and invalid integer exponentiation remain errors. The reference interpreter used in regression tests has execution limits to stop runaway examples; it is not a production runtime or a language-standard implementation.

For dead-code elimination, declare which scalar values are needed after the block. Other final scalar values may be removed because you have declared them unobservable. Leaving the field blank is conservative: every assigned scalar is treated as live on exit. Array stores are always retained. Do not list only the displayed answer if another variable is consumed later in your real program; that would give the optimiser an incorrect contract.

A worked basic-block example

The loaded example assigns constants, adds them, copies simplified expressions, computes the same sum twice and contains unused assignments. With out as the live-out variable, the library produces:

t4 = x + y
out = t4 + t4

Running both versions through the integer interpreter with x = 3 and y = 5 gives out = 16 before and out = 16 after. The calculation and transformations come from the same libraries used here. The unused constant addition is still shown in the trace before dead-code elimination removes its result, so you can distinguish folding a value from deciding that the value is not needed.

Propagation follows the current value facts, not the spelling of a name forever. If a copied source is subsequently reassigned, facts depending on that source are invalidated. Common-subexpression elimination tracks operand versions and the variable holding an available expression. Reassigning a carrier or changing an operand prevents reuse of an obsolete value. Commutativity is used only for integer addition and multiplication, not subtraction, division or remainder.

Read the local optimisation rules

Constant folding evaluates an operation only when its operands are known integer constants and evaluation succeeds within the demonstration limits. A division by zero is left in the program rather than turned into a fabricated number. Constant and copy propagation then substitute known values where the current facts permit it. Algebraic simplification includes identities such as adding zero, multiplying by one and dividing by one under this integer model.

The backward liveness pass starts from the declared live-out set. A dead scalar assignment can be removed when the operation is nontrapping in the model. Potentially trapping division, remainder, exponentiation and array loads stay when their results are dead; deleting their destination alone would not justify deleting an error. Stores and their operand dependencies stay observable. This deliberately conservative behaviour may retain more instructions than a compiler with stronger proofs.

Move loop invariants without creating a zero-trip bug

Loop mode accepts whole TAC and lets you select a natural-loop header. It needs an existing preheader outside the loop that leads only to that header. The tool does not split critical edges or invent a preheader. For headers with multiple latches, it considers their combined loop region before checking motion conditions.

A candidate must have a single scalar definition, invariant operands and a safe operation. Its block must dominate the relevant uses, latches and loop exits; same-block uses must occur after the definition. Loads and potentially trapping operations are not speculated. These conditions prevent a statement inside a possibly zero-trip body from being executed earlier merely because its formula looks unchanged.

The loaded loop example moves 2 instructions into its preheader. Its generated result is:

i = 0
t = a + b
u = t * 2
L1:
sum = sum + u
i = i + 1
if i < n goto L1

Notice that the loop label stays after the moved instructions. Copying the label onto a hoisted instruction would make the back edge execute it repeatedly and would fail to perform the intended motion. If no candidate meets the conditions, the original program remains with an explanation.

Peephole rules use a simple register-machine model

The assembly mode accepts LD, ST, MOV, ADD, SUB, MUL, DIV, MOD, SHL, JMP, JZ, JNZ and HALT. Registers have R-prefixed numeric names; integer immediate operands use a number sign. This abstract machine has no status flags, volatile memory, device I/O, interrupts or aliasing between its named memory cells. The rules are not an assurance that equivalent-looking edits preserve a real CPU's flags or memory-mapped side effects.

Adjacent redundant loads and stores can be removed when no labelled entry point invalidates the assumption. Jump chains can be redirected when they terminate without cycling. Instructions after an unconditional transfer are removed up to the next labelled entry. Multiplication by a positive power of two can become a left shift. Signed division is deliberately not replaced by a right shift, because truncation and negative-value shift behaviour can differ.

Verify the assumptions before using the result

Regression tests run original and optimised TAC on randomized initialized integer inputs and compare live outputs, memory effects and errors. Separate tests cover reassignment, repeated expressions, dead divisions, labelled assembly entry points, negative values and zero-trip loop paths. Tests support the stated model; they do not establish compatibility with every source language or instruction set.

Use the three-address code generator to study translation before optimisation, and the compiler lab to follow the broader workflow. Copy optimized code saves the currently displayed result. Keep your live-out declaration and model assumptions with that result when checking an exam solution.

Frequently asked questions

Can this optimize arbitrary source code?

No. Basic-block and loop modes accept the documented integer TAC syntax. Assembly mode accepts a small abstract register machine, not an arbitrary real processor’s instruction set.

What is constant folding?

It evaluates an operation whose operands are known constants. A potentially invalid operation is retained instead of being replaced by a made-up value.

How are constant and copy propagation different?

Constant propagation substitutes a known integer value. Copy propagation substitutes a currently valid copied value; reassignments invalidate facts that depended on the changed source.

Which variables should I put in the live-out field?

List every scalar whose final value is needed after the block. Other scalars may be removed; leaving the field blank preserves every assigned scalar conservatively.

Why is an unused division still present?

It could raise a division-by-zero error even when its destination is dead. The tool retains potentially trapping instructions unless a safe constant evaluation has already justified their replacement.

Does the optimizer support floating point?

No. It explicitly uses an integer model with truncating division. Floating-point identities, rounding, NaNs and signed zero require different reasoning.

Why was my loop-invariant expression not moved?

It must satisfy the preheader, single-definition, invariant-operand and dominance conditions. Loads, trapping operators, early uses and zero-trip exit paths can prevent motion.

Does every loop need a new preheader?

The tool only uses an existing single-successor preheader. It does not restructure edges to create one, so some otherwise optimizable loops remain unchanged.

Can I apply the peephole output to real assembly?

Check the real architecture first. This model has no status flags or volatile/device memory, and a transformation that is valid here may change those effects on a real machine.

How is correctness checked?

The regression suite interprets original and optimized TAC on randomized inputs and compares the declared outputs and memory effects. Targeted cases also check traps, loop entry and register-machine peephole rules.

Have a suggestion for Code Optimizer?Share your feedback ↗