CComputer Science, Built

Act II · Making It Fast

Part 8 of 61

Out of Order

Degreestarts at this level49 min of film17 chaptersprerequisites: Part 6, Part 7

Why should an instruction wait in line behind one that is stuck, and what does it cost to let it pass?

A load misses the cache, and on a machine that starts instructions in program order everything behind it waits: 81 cycles for sixteen instructions, against 70 when ready work may pass. The part first asks how fast a known path could run at all. Four trips of the Job's scan loop form a dataflow graph of 24 instructions with a longest chain of 6 cycles, and schedules with 1, 2, 4 and 8 starts a cycle take 24, 12, 7 and 6. Reused register names add waits that carry no value, and renaming removes them. The mechanisms follow in historical order: the CDC 6600's scoreboard, Tomasulo's reservation stations and tags (62 against 56 cycles on the textbook example), and the reorder buffer, which retires in program order so that exceptions stay precise. A functional out-of-order core is built and checked against the emulator; on the Job's first chapter it retires 1.89 instructions a cycle. The part turns on speculation: work on a mispredicted path is squashed, but a load it ran has already warmed the cache, and a bounds-check-bypass gadget in the model reads the bytes PEBBLE through that channel. It ends with the compiler-scheduled alternative (VLIW), RISC against CISC, multithreading, the Job's ledger row, and value prediction and secure speculation at the frontier.

What you need. Programming and school algebra. The scheduling bounds use only counting.

Mathematics, ideas and history
dependencies and renaming, scoreboard, Tomasulo, ROB, superscalar limits, speculation, Spectre, RISC vs CISC
What we build or compute
an out-of-order model; the ILP limit study

What you will be able to do

Degree

  • Draw the dataflow graph of a short instruction sequence, find its span, and schedule it with W starts a cycle.
  • Tell a true dependence (read after write) from the name hazards (write after read, write after write), and rename a sequence to remove the name hazards.
  • Explain in plain steps how a squashed load can still reveal a byte through the cache.

Graduate

  • Run the textbook example through a scoreboard and through Tomasulo's algorithm, cycle by cycle, and say where each one waits.
  • Explain how a reorder buffer gives precise exceptions when execution is out of order, and what a load must check about older stores whose addresses are unknown.
  • State the start-slot bound and Graham's bound, and say which resource model each one assumes.

Research

  • Say what an oracle limit study assumes (future paths, memory addresses, unlimited resources) and why its instructions per cycle is not a hardware target.
  • State what a secure-speculation claim needs before it is a theorem: the attacker, the permitted observations, the protected data and a baseline.
  • Evaluate a value predictor by coverage, timing and recovery cost and not by accuracy alone.

Industry

  • Read a core's published numbers with care: which stage a width refers to, and whether a reorder buffer counts instructions, micro-operations or fused groups.
  • Choose between a speculation barrier and index masking for a bounds check, and state what the compiler and the instruction set must preserve for each to work.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 20 min · Graduate 46 min · Research 49 min · Industry 25 min.

  1. 0Waiting in lineDegree2 min
  2. 1The dataflow limitDegree3 min
  3. 2False dependences, and renamingDegree2 min
  4. 3The scoreboardGraduate4 min
  5. 4Tomasulo's algorithmGraduate4 min
  6. 5The reorder bufferGraduate2 min
  7. 6Wider, and the ILP wallGraduate2 min
  8. 7SpeculationDegree3 min
  9. 8Loads, stores, and their orderGraduate3 min
  10. 9SpectreDegree5 min
  11. 10The compiler's alternative: VLIWGraduate2 min
  12. 11RISC and CISCDegree2 min
  13. 12Simultaneous multithreadingIndustry3 min
  14. 13Modern cores in numbersIndustry2 min
  15. 14The Job out of orderGraduate3 min
  16. 15Frontier: past the dataflow limit, safelyResearch4 min
  17. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Waiting in lineDegree2 min

Start with a short program on this part's functional core, constrained to a one-entry issue queue. That forces instructions to start in program order. Rows are instructions; time runs to the right. The fifth instruction loads from a cold cache line. We assign a sixty-cycle miss latency. The next add needs that value and must wait. Several later instructions do not depend on the missing value. They still have their own dependencies and resource requirements, but this in-order configuration cannot pass the waiting add. Their useful work is delayed behind it. This recorded run takes eighty-one cycles for sixteen instructions, including setup and halt. It illustrates head-of-line blocking under the model's chosen resources and timing.

Now use the normal issue queue and ready-instruction selection on the same functional core. An instruction can start when its operands, execution resources and ordering rules allow. The load still misses, and its dependent add still waits. Later independent work can overlap the miss, while dependencies among those later instructions remain. Completed results wait for in-order architectural retirement, shown in blue. When the load finishes, the waiting add executes and the core retires the completed work in order. This run takes seventy cycles instead of eighty-one. The comparison changes queue capacity and scheduling freedom; it does not make every later instruction immediately ready or reproduce every feature of a physical processor.

1The dataflow limitDegree3 min

This is the Job's table-scan fast path when an entry's length differs from the word being searched. Matching lengths need additional letter comparisons, and reaching the insertion point follows another path. The displayed path has six instructions: table-end test, length load, comparison, two increments and a jump. With warm correct direction and target prediction, Part 7's pipeline takes seven steady-state cycles per such trip, including a load-use bubble. Now hold this known path fixed. Give its instructions explicit latencies and ask how overlapping their true dependencies changes the schedule. This idealization assumes the future path and relevant memory information are already known.

Each node is an instruction. An arrow connects a value's producer to an instruction that uses it. These arrows describe register data dependencies for this fixed path; real execution also has memory, control, resource and exception constraints. Place four trips at their earliest starts with unlimited resources. Loads take two cycles and the other displayed operations take one. The jumps have no register predecessors in this oracle graph. A length load needs its entry address, and the comparison waits for that load. The next entry address comes from a one-cycle increment of the previous address. The highlighted longest weighted chain, ending at the last comparison, spans six cycles. Under these dependencies and latencies, no valid schedule finishes the four trips sooner. The corresponding single-start, in-order schedule takes twenty-eight cycles; this is a scoped schedule comparison.

In this ideal scheduler, width W limits how many operations may start each cycle. It does not limit how many earlier operations remain in flight, and execution units are otherwise unlimited. One start slot gives twenty-four cycles for twenty-four instructions, including jumps. Two slots give twelve cycles. Four give seven. Eight give six, reaching this graph's weighted critical path. These are the computed schedules for four fixed fast-path trips. Two immediate lower bounds apply: at least the instruction count divided by start width, rounded up, and at least the longest dependency chain. Real cores need additional front-end, unit, ordering and retirement constraints.

Keep the resource model explicit. N counts instructions, L is the longest latency-weighted path, and W is the number of starts permitted each cycle. Every schedule in this start-slot model needs at least the larger of ceiling N over W and L. Graham's classic list-scheduling result concerns nonpreemptive jobs occupying W processors. Its work is A, the sum of processing times, and a greedy schedule takes at most A over W plus one minus one over W times L. With two-cycle loads, A and the instruction count N differ. Do not substitute one for the other when changing resource models. Our four-trip schedules satisfy the displayed start-slot lower bounds; they have twenty-four instructions and a six-cycle span. Across many fixed fast-path trips, the address recurrence permits one trip per cycle in the unlimited-resource, perfect-path idealization: six instructions per cycle after startup.

2False dependences, and renamingDegree2 min

These five instructions illustrate register dependencies and name hazards. The first load produces the value used by the following add. Without value prediction, that add must wait for its actual input: a read-after-write dependence. The second load reuses a0. If all versions shared one storage location, it must not overwrite the old value before the earlier add reads it: a write-after-read hazard. The two loads also reuse the destination name, creating a write-after-write hazard in such an organization. Those last hazards arise from storage-name reuse, not a value passing between the operations. Separate live versions remove them. The genuine producer-consumer chains, and any memory, control or resource constraints, still have to be respected.

Give each live destination version a separate physical name. A register alias table maps architectural names to their current physical versions. Source operands capture either an existing value or its producing version. Process instructions in order: look up sources first, allocate a fresh destination version, then update the mapping. Here the first load writes p twenty, and its add reads that version while writing p twenty-one. The later load writes p twenty-two. It cannot overwrite the earlier load's value, though its own address, memory and execution-resource constraints still apply. The displayed live versions have distinct names, removing register anti and output hazards. Physical registers are safely reclaimed and reused later; they are not unique forever. The two value chains can overlap when their remaining constraints permit.

3The scoreboardGraduate4 min

The Control Data 6600, delivered in 1964, is a landmark in dynamic instruction scheduling, associated with Seymour Cray and James Thornton. Its ten functional units could overlap different operations, subject to dependencies and shared resources. The scoreboard tracked functional-unit availability, pending register writers and operand readiness. That bookkeeping let instructions execute out of order while protecting their register dependencies. The machine used a hundred-nanosecond clock. Historical peak floating-point rates and application throughput are different measures, so we will focus on its scheduling mechanism rather than a universal performance ranking. The important question is how several units cooperate without changing the program's results.

Each instruction passes through four steps, and the scoreboard checks one kind of hazard at each. Issue happens in program order. An instruction issues when its kind of unit is free, and when no instruction already in flight is going to write the same register; that is the write after write hazard, and the 6600 simply refuses to have two writers of one name. Next, read operands. The instruction waits at its unit until every register it reads has been written by whoever was producing it: the true dependence. Then it executes, taking as many cycles as its unit needs. Last, write result. Before overwriting its destination, it waits until every earlier instruction that still needs the old value has read it: the write after read hazard. Notice that values travel only through the registers. Every hazard is a wait; nothing is renamed.

Here is the standard example from Hennessy and Patterson's textbook, written in Pebble's registers, with their latencies: a load takes one cycle, an add two, a multiply ten, a divide forty. Watch the scoreboard fill in the cycle at which each instruction completes each step. The first load issues in cycle one, reads in two, executes in three, writes in four. The second load cannot even issue until cycle five: there is only one integer unit, and the first load holds it until its result is written. The multiply and the subtract both wait for the second load, then read their operands together in cycle nine. The divide needs the multiply's result, so it waits at its unit until cycle twenty-one. And the last add. It issues in thirteen, when the adder is free, and its result is ready by sixteen. But it writes a1, and the divide, an earlier instruction, has not yet read the old a1. So the add sits on its finished result until cycle twenty-two. The whole thing takes sixty-two cycles.

This scoreboard handles several hazards by waiting. A pending writer blocks another writer of the same register, and an earlier reader can delay a later writeback. Dispatch is in program order: if the next instruction cannot reserve its required unit, later instructions cannot dispatch past it. Tomasulo's algorithm adds reservation stations, producer tags and direct result broadcast. Those remove register-name hazards and decouple dispatch from immediate unit availability. Traditional Tomasulo still dispatches in order, and still stalls when the needed station is full. It does not remove every limit listed here.

4Tomasulo's algorithmGraduate4 min

In 1967 IBM shipped the System/360 Model 91, a machine built for scientific computing. Its floating-point unit had a problem far worse than Pebble's: only four floating-point registers in the instruction set, so the same few names were reused constantly, and a scoreboard would have stalled on false dependences all the time. Robert Tomasulo's answer was to stop naming values by registers at all. A value in flight is named by the reservation station, a small waiting area in front of a functional unit, of the instruction that will produce it. An instruction waiting in a station holds, for each operand, either the value itself or the tag of the station that will produce it. And when a unit finishes, it broadcasts the result and its tag on a common data bus. Every station and the register file listen, and whoever is waiting for that tag takes the value. This is register renaming, done in 1967 with a handful of tags.

Here is the machine. On the left, the instructions waiting to issue, in order. In the middle, the reservation stations: three for loads, three in front of the adder, two in front of the multiplier and divider. Below them the units, and under everything the common data bus, which runs back to every station and to the registers. Cycle one: the first load issues into Load1, and the register a1 now records that its next value will come from Load1. Cycle two: the second load issues, and a2 points at Load2. Cycle three: the multiply issues. Its operand a2 is not ready, so the station takes the tag Load2 instead. And the first load broadcasts: tag Load1 and its value go out on the bus, and a1 takes it. Cycle four: Load2 broadcasts, and the multiply, which was waiting for that tag, captures the value. The subtract issues with both its values in hand. Cycle five: the divide issues, waiting on tag Mult1, and holding the current value of a1. Cycle six: the last add issues. It will write a1, so a1 now points at Add2, but the divide does not care: it has already copied the old a1. That is the write after read hazard, gone. The subtract broadcasts in cycle seven, the add starts in the next cycle, and it broadcasts in cycle ten, while the multiply is still working. The multiply finishes in fifteen and its broadcast wakes the divide, which takes forty cycles and broadcasts in fifty-six.

Side by side. Most results arrive a little earlier, because the bus hands a value straight to the stations waiting for it, with no write and read through the register file. And the last add finishes twelve cycles sooner: under Tomasulo nobody waits for an earlier reader, because every reader has already copied what it needs. Fifty-six cycles instead of sixty-two. The divide's forty cycles dominate both, as they should: that is this example's critical path.

Out-of-order writeback creates an exception problem if architectural results become visible immediately. In this teaching schedule, the younger add writes in cycle ten, before the older divide broadcasts in cycle fifty-six. Suppose our illustrative divide-zero policy reports a fault when the divide finishes. Pebble uses such a fault policy, unlike RISC-V M's defined integer divide-zero result. The younger add has already changed architectural state, so simply stopping cannot expose the state immediately before the divide. This is an imprecise exception. The historical Model 91 had imprecise floating-point interruptions; that is a separate ISA-specific behavior, not this integer example. Precise recovery has several possible implementations. Next we will separate execution from architectural retirement using a reorder buffer.

5The reorder bufferGraduate2 min

Smith and Pleszkun's 1985 work studied several ways to provide precise interrupts in pipelined processors. The reorder buffer is one important approach. Dispatch instructions in order, execute them when their operands, resources and ordering constraints permit, and retire architectural effects in program order. Execution results may already be in temporary storage or a physical register file, and dependent instructions may use them before retirement. A precise exception exposes a valid architectural prefix of the program, with the faulting instruction handled according to its specified policy. Cache and predictor effects require separate reasoning.

We draw this reorder buffer as a ring of slots. The animation follows a short recorded scan-loop window. Up to four instructions are renamed into tail slots each cycle. Orange means waiting, green executing, and blue complete but waiting to retire. Up to four completed instructions retire from the head in order. A completed younger instruction cannot retire around an unfinished older one. A branch redirect discards its younger entries and restarts fetch. Their architectural destinations were never committed, but their execution was real within the model: loads may already have changed the simulated cache. The ring records retirement order; it does not erase every microarchitectural trace of squashed work.

Here is Pebble's deliberate divide-zero fault policy. Division has a modeled sixteen-cycle latency. The fault is recorded with its instruction instead of being reported immediately. Younger operations can compute results, including a store's address and data. They wait behind the divide and cannot commit architectural effects. When the fault reaches the head, older instructions have retired, the faulting divide does not write a result, and younger instructions are discarded. Pebble stops and reports the fault; it does not implement an operating-system resume path. The older store has written eleven to memory. The younger store has not committed its write. That is precise architectural state under this policy. Remaining cache or predictor effects are a separate question, and RISC-V M defines a different result for integer division by zero.

6Wider, and the ILP wallGraduate2 min

Limit studies inspired by David Wall's 1991 work schedule a recorded execution under progressively changed assumptions. Our bars change one assumption at a time from the same baseline; they are not cumulative stages. Unlimited start width and lookahead, fixed latencies, perfect path and word-address knowledge, register renaming and omitted realistic I/O ordering produce about twenty-four hundred instructions per modeled cycle on this trace. Adding register-name constraints alone gives about three point seven. Making loads wait for earlier store addresses instead gives about sixty-two. Keeping the other oracle powers but adding tournament-predicted control barriers gives about three point four. Barriers at every branch and jump give under one half. These are sensitivities of a particular trace scheduler, not attainable processor specifications or universal program limits.

Now vary start width and the scheduler's window parameter. This parameter constrains an instruction's start relative to the start of an earlier trace position. With the modeled predictor barriers, curves for the tested window parameters almost overlap and flatten near three point four. With perfect control, a parameter of one hundred twenty-eight permits considerably more overlap. Two thousand forty-eight permits still more. Control assumptions interact strongly with start-width and lookahead assumptions here.

This illustrates an instruction-level parallelism trade-off. An offline oracle exposes large overlap by supplying knowledge and resources that a real core lacks. Its twenty-four-hundred figure is not independently available hardware parallelism. Finite lookahead, prediction, memory ordering and front-end bandwidth restrict useful overlap in the functional model. Larger windows can still help other workloads, especially when they expose independent misses or long-latency work. Increasing width also adds bypass, selection, port, wiring and energy costs. Those costs depend on the implementation; not every design uses one fully connected broadcast structure. Designers balance wider cores, caches, multiple cores and other techniques. Fetch, decode, issue and retirement widths are different metrics, and there is no universal four-to-eight-wide stopping point.

7SpeculationDegree3 min

Prediction lets fetch proceed before a branch resolves. Fetch follows a predicted direction and target, within its bandwidth limits. Younger operations may be renamed and execute when their operands, resources and ordering rules allow. Ordered retirement prevents younger architectural effects from committing past an unresolved older branch. It does not keep every physical result or cache effect inside the reorder buffer. A wrong direction or target discards younger work, repairs register mappings and recovery state, and redirects fetch. Our simulator rebuilds its alias table from surviving entries. Physical processors use different mixtures of checkpoints and rollback; checkpoint availability and front-end refill affect recovery time. A single-cycle universal repair rule would be misleading.

This is a recorded branch redirect in the functional core. Grey covers fetch and decode; the other colors distinguish waiting, execution, completion and retirement. The prediction follows a same-length entry into the letter-comparison path. Eleven displayed younger entries are later squashed. They reached different stages; some executed and some only waited. The resolved branch selects the different-length path. No younger entry has retired, but its resource use and any modeled cache effects still matter. The chart measures about eight cycles from the branch's rename to the first refetched instruction's rename. That interval includes branch execution and front-end progress. Recovery penalty depends on the timestamps and configuration; it is not a universal constant for all branches or processors.

These four functional-core runs differ in prediction policy. Always-taken prediction gives about zero point six nine retired instructions per cycle. Two-bit and tournament prediction give about one point eight seven and one point eight nine. The oracle-assisted setting gives about three point one six. It knows correct-path outcomes, yet this implementation still records two redirects and one memory-order violation, so its label must not imply zero recovery events. In the tournament run, the model counts twenty-two thousand two hundred ninety-six branch redirects and two hundred fifty-three thousand seven hundred sixty-four squashed renamed entries. That is about thirty-one percent of the retired count, not thirty-one percent extra executed instructions. Some entries never issued. Separately, twenty-eight thousand nine hundred five loads execute on wrong paths in the modeled memory system.

8Loads, stores, and their orderGraduate3 min

Register names are available at decode, but effective memory addresses may depend on unfinished arithmetic. Here an older store waits for its address in a3, while a younger load already knows s0 plus four. If their byte ranges overlap, the load must observe the correct older store's bytes, perhaps through forwarding or after waiting. Equal starting addresses are only one overlap case. Disjoint byte ranges remove this particular dependency, though resources and other ordering rules still apply. Until the store address is known, the core must either wait conservatively or speculate and later check. That is the memory-disambiguation problem in this single-core model.

The load and store queues retain program-order relationships among memory operations. In this simulator, stores compute address and data early but write the byte array only at retirement. A squashed store does not commit that write. Real processors can have earlier store-related cache or coherence effects, which this rule does not model. A load searches for the youngest relevant older store. If that store covers all requested bytes and its data is ready, it can forward the value. This implementation waits on partial overlaps rather than merging several stores. Conservative disambiguation waits for unknown older store addresses. Speculative disambiguation proceeds and checks later. The load-PC wait table conservatively retrains previously violating loads; it is a simplified policy inspired by historical load-wait predictors, not a complete store-set predictor.

This recorded example makes the ordering mistake visible. A younger load executes before the older store's address is ready and reads zero from memory. The delayed address resolves to the same word, which the older store must write with seventy-seven. The model detects the overlapping younger load, squashes it and its dependents, and refetches. The corrected load obtains seventy-seven after the required older-store ordering is respected. In this recording the store retires before the replayed load starts; forwarding can satisfy other valid cases before a store retires. The speculative run takes thirty-five cycles and the conservative one twenty-nine. Speculation is not always faster: a wrong guess can cost more than the waiting it avoided.

The Job's first chapter behaves differently. All three tested disambiguation policies give the same four hundred thirty-seven thousand five hundred eighty model cycles. Its recorded trace has a hundred fifty-four thousand eight hundred thirty-five loads and five thousand two hundred seventy stores. Stores update counts, table metadata and the letter pool. These runs show no benefit from changing the tested policy; they do not prove that every load is independent or that memory disambiguation never matters. Different workloads expose different bottlenecks.

9SpectreDegree5 min

We will demonstrate a cache timing channel entirely inside the functional simulator. The victim and observer share its byte-array memory and a probe array. The observer can evict and time probe lines using model devices. Allocate two hundred fifty-six probe lines, one for each possible byte value. The diagram shows sixteen of them. A victim access leaves its selected line in the modeled cache. Access assigns a two-cycle hit or sixty-cycle miss and allocates a missed line immediately; it is a simplified cache model. Timing later accesses distinguishes a warm line from cold ones; the measured interval includes the timer and surrounding instructions. Flush-and-reload-style attacks exploit this kind of observable shared state on suitable hardware. Our demonstration supplies those sharing and timing assumptions explicitly and does not extract secrets from the host processor.

The victim interface accepts an unsigned word-sized index and a nonempty sixteen-byte array. On architectural execution, the unsigned bounds check rejects indices at or above the array size. An accepted byte selects one probe line. The assembly uses an unsigned branch, then loads the byte and shifts it by six to select a sixty-four-byte line. The adjacent secret is outside the victim interface's permitted array, but inside the same modeled address space. This is a software bounds policy, not a hardware page-permission boundary. The secret bytes spell PEBBLE and begin at index sixteen. Correct architectural control flow rejects those indices. The experiment asks whether transient execution can nevertheless encode their values in the simulated cache.

Follow the actual program order in the simulated attack. First flush all probe lines, then make six in-bounds training calls. The allowed array contains zeros, so those calls warm probe line zero. Next evict the size variable and execute the model's timer barrier before the attack call. The next bounds check must wait for the modeled miss. Call with index sixteen, then successive secret positions. Prediction follows the in-bounds path while the size is delayed. A transient byte load reads P and a dependent access selects its probe line. The timing diagram illustrates that overlap; it is not a gate-level timing trace. Once the size arrives, the branch rejects the index and squashes younger architectural results. The selected probe line remains warm. That observable cache effect is exactly why saying the access never happened would be wrong.

The actual attack probes indices one through two hundred fifty-five. Line zero is intentionally omitted because the training calls warm it, so this simple decoder cannot recover a zero-valued secret byte. Each plotted measurement is the difference between two model-counter reads around one probe access. In the first round, line eighty, ASCII P, is the uniquely fast tested line. It takes five measured cycles versus sixty-three for the other tested lines, including timing overhead. Repeating the procedure recovers the six supplied nonzero secret bytes, PEBBLE. That is a concrete simulated witness under the stated shared-memory and timing capabilities, not evidence of a leak from arbitrary host memory.

Compare two mitigations for this gadget. The first inserts our custom serializing timer read after the check. In this program its known device address lets the model recognize the barrier and prevent younger issue until it retires. This is not a universal description of x86 RDTSC or LFENCE; real barriers require the specified ISA and vendor protocol. The second makes the array index depend on the unsigned bounds result: all ones for an allowed index, zero otherwise. Here array element zero exists, so the out-of-bounds transient path is redirected to a valid element. Compilers and hardware must preserve the dependency for such hardening to work. Both tested runs fail to recover the supplied secret from the nonzero probe lines. The benign-call costs shown below are specific to this program and model. Real applications need their own correctness, performance and threat-model evaluation.

Spectre and Meltdown were publicly disclosed in January 2018, with variants affecting different processor implementations. Spectre-style attacks manipulate predictions to induce transient computations that reveal information through observable microarchitectural state. Our example is bounds-check bypass, not every Spectre variant. Meltdown's original attack exploited delayed enforcement of access restrictions on affected processors. Its prerequisites and mitigations differ from this shared-address-space victim-interface experiment. Operating systems, browsers, compilers and processors have adopted multiple defenses, including isolation, hardening and prediction controls. Their applicability depends on architecture, version, configuration and threat model. Speculation does not by itself imply that every implementation is vulnerable to every attack, and precise architectural exceptions alone do not establish security.

10The compiler's alternative: VLIWGraduate2 min

Dynamic scheduling spends hardware on dependency checking, wakeup and selection. A straightforward W-wide rename stage compares destinations and sources within the incoming group, giving a quadratic family of comparisons. Implementations can organize that logic differently. Waiting instructions must learn when their operands become available, and ready operations must compete for resources. Very Long Instruction Word designs move more scheduling decisions into the compiler, which places operations into explicit issue groups. The hardware still decodes, executes and handles the ISA's timing, memory and exception rules. Some designs retain interlocks, caches and variable-latency operations. Static scheduling changes where decisions are made; it does not eliminate every hardware scheduling or correctness mechanism.

Use the six-operation mismatched-length path as a scheduling illustration with four start slots. This is not an executable VLIW translation of the whole search. Under the chart's same-bundle read-before-write convention, the load and table-end test read old register versions while the increments produce later versions. That convention must be part of a real target's semantics. With a two-cycle load and these fixed data dependencies, the comparison cannot start in the next cycle, leaving an empty bundle in this candidate schedule. The displayed operations occupy three cycles and six of twelve slots. Actual exits, multiple control operations in a bundle, safe early loads and side effects need a complete control and guard policy before this could replace the original program.

Static and dynamic scheduling make different trade-offs. Cache misses and variable execution times can invalidate a compiler's preferred timing. Depending on the ISA, interlocks or other mechanisms preserve correctness, sometimes by stalling. Data-dependent branches require control flow, predication, speculation or guarded schedules; a compiler need not know every runtime outcome in advance. A schedule tuned for one implementation can perform poorly on another. Itanium's EPIC approach included features such as predication and advanced loads and faced several commercial and technical challenges. One simple bundle chart cannot explain its whole history. VLIW remains useful in some DSPs and accelerators, where workload knowledge and implementation choices can make static scheduling attractive, even when real systems still contain caches or variable-latency events.

11RISC and CISCDegree2 min

Return to execution time: instruction count times cycles per instruction times clock period. Rich instructions can express more work per architectural instruction, reducing the count for some programs. Their implementation may use direct hardware or microcode; not every complex instruction is slow or microcoded. RISC projects emphasized simpler operations, regular encoding and efficient pipelines. The goal of starting or completing one operation per cycle is a throughput goal, not a claim that every load, divide or other instruction has one-cycle latency. Compiler quality, memory behavior and implementation choices affect all three factors in the equation, so instruction-set labels alone do not determine performance. IBM 801, Berkeley RISC and Stanford MIPS are influential examples. Their lessons concern measured workload and implementation trade-offs, rather than a universal rule that fewer instructions or simpler instructions must always win.

Its arithmetic, branches, loads and jumps dominate the recorded chapter. An x86 compare can read a memory operand directly, but the conditional jump still remains. Our Pebble load followed by a combined compare-and-branch can therefore map to a memory compare plus a jump: two architectural instructions, not one. The trace heuristic finds ninety thousand seven hundred twenty-six loads whose result feeds the next instruction and soon becomes dead. That is about fifty-nine percent of the loads. It is a local use pattern, not a count of legal folded x86 instructions or an eleven-percent instruction reduction. Addressing, flags, branches, register allocation and actual code generation must be included in such a comparison.

Instruction sets preserve software investments while implementations evolve. Arm designs span many implementations and markets, with distinct instruction-set states and encoding choices. RISC-V provides an open ISA that can be implemented without an ISA license royalty. That does not remove every other IP, implementation or compliance cost. MIPS and other architectures also shaped processors and teaching systems. Across these families, evaluate the generated program and the specific implementation using instruction counts, timing and resource measurements, rather than treating RISC or CISC as a complete performance prediction.

12Simultaneous multithreadingIndustry3 min

This grid shows starts in a twenty-four-cycle sample from the offline trace scheduler, with four start slots per cycle. It is not an issue-activity recording from the functional core. Fifty-eight of its ninety-six displayed slots contain scheduled instructions. The empty cells are directly counted in this particular sample. Separately, the functional core retires about one point nine instructions per cycle. Retired IPC cannot tell us how many issue slots were used: wrong-path and replayed operations may execute without retiring. Our implementation also has a different total execution-start limit from its four-wide front end. The useful question is whether another independent thread can share resources and improve aggregate throughput, under an explicitly stated scheduling model. Neither the grid nor retired IPC measures powered idle hardware or energy consumption.

Simultaneous multithreading lets operations from different threads share execution resources. Tullsen, Eggers and Levy's 1995 paper is an influential study of this approach. Here we interleave two known Job traces in an offline oracle scheduler, sharing four start slots and giving each thread its own dependency state, control barriers and half of the start-distance allowance. This is not a functionally verified SMT implementation of Pebble. Real SMT needs per-thread architectural, retirement, exception and recovery state, plus ownership information for shared queues. PCs, register mappings and branch history alone are not enough. Sharing and partitioning policies vary by design. The colored grid illustrates how one thread can use cycles where another lacks ready work. Actual fairness, cache contention, recovery and isolation require a fuller machine and workload analysis.

These bars report combined throughput in the same offline scheduling study. The traces are truncated to equal instruction counts, and both must finish. With four start slots and the stated lookahead allowance, one trace averages about two point seven instructions per cycle; the two together reach about three point seven. At eight slots, the aggregate improvement is larger for these particular traces and assumptions. This is not a universal scaling rule or a measurement of a production SMT processor. Real sharing can improve aggregate throughput while slowing an individual thread, and results depend on workload, partitioning and contention. Fairness, latency, energy and security are separate evaluation axes. Timing interactions between threads can also expose information, so throughput alone is not a complete design objective.

13Modern cores in numbersIndustry2 min

These are reported retirement-tracking capacities in a historical selection of cores from 1995 through 2024. The entries do not all count the same thing: architectural instructions, micro-operations and fused operations must be distinguished. The early examples include Pentium Pro, MIPS R10000 and Alpha 21264. Later examples include Core 2, Sandy Bridge, Haswell, Skylake and Zen. Their capacities increased as implementations changed, but capacity alone does not predict workload performance. Sunny Cove, Golden Cove, Zen 4 and Zen 5 extend this historical sample. Apple Firestorm is shown separately: Dougall Johnson's reverse-engineered notes describe about three hundred thirty coalesced retire groups and six hundred twenty-three rename-retire entries. A single six-hundred-thirty-instruction ROB dot would hide that distinction. Our model tracks a hundred twenty-eight architectural instructions and is never full on this chapter; its entries are not directly interchangeable with every hardware entry on the plot.

Larger windows can expose independent work while a long-latency operation waits. As an illustration, a memory access lasting three hundred core cycles represents twelve hundred potential start opportunities at four per cycle. Whether they exist and can be reached depends on dependencies, prediction and resources; DRAM latency in cycles also depends on the clock and memory system. Branch accuracy varies with workload, predictor and measurement definition. A few misses per thousand instructions is not a universal property of typical code. Fetch, decode, dispatch, issue and retirement widths must be specified separately. Encoding, fusion and instruction mix change the operations counted at each stage. Larger tracking and selection structures cost area and energy. Banking, clustering, gating and other implementation choices change those costs. This discussion does not measure which structure is hottest or establish one universal best window size.

14The Job out of orderGraduate3 min

This stack is an accounting comparison, not a unique causal decomposition. Four-wide architectural retirement gives an ideal lower floor of one quarter cycle per retired instruction. It is not the total execution-start limit. The oracle-assisted run uses about zero point three one seven cycles per instruction; its gap above that floor includes the model's dependency, front-end and resource constraints. The tournament run uses about zero point five two nine. Their difference is a configuration gap, not a separately measured amount of time spent only on branches. Part 7's pipeline is another configuration, with about one point two cycles per instruction. The oracle-assisted core uses about forty percent fewer cycles than the tournament core on this chapter, with interactions among prediction, queues and memory recovery. The length test is important in the measured trace, but these comparisons do not prove its outcomes are unlearnable or assign every saved cycle to it.

A full cycle-by-cycle simulation of the corpus is expensive, so use a fitted projection and expose its limits. The training set contains twenty-four randomly selected text slices, four hundred to four thousand characters long. The actual inputs and byte-count features are UTF-8 encoded; the slice length metadata is not always the encoded byte length. Fit model cycles as a linear function of text features, including word counts, scanned entries and letter comparisons. One separate Moby-Dick slice has sixteen thousand characters and sixteen thousand nineteen encoded bytes. It takes about three point two nine million simulated cycles, and this fit predicts it within about zero point zero nine percent. That is one heldout check, not a full-corpus error bound or evidence that all unseen texts behave equally well. Host simulation speed also depends on machine and configuration.

Apply the fitted cycle model to the corpus's counted text features. It projects about fifty point seven billion cycles for about a hundred six point nine billion architectural instructions, an average IPC near two point one. Those corpus cycles were not obtained by running every instruction through this core. Converting them to time additionally assumes Part 7's teaching clock budget, about eight hundred eighty-five megahertz. This out-of-order design has no gate-level timing result establishing that frequency. The projected runtime is about fifty-seven seconds. the previous fitted pipeline row is about two and a half times slower. Both the cycle extrapolation and frequency assumptions travel with that ratio.

15Frontier: past the dataflow limit, safelyResearch4 min

Value prediction changes the dependency model by guessing a load's result before it is verified. Dependents can tentatively use a predicted value, then correctness requires validation and recovery if it was wrong. This can pass a dependency bound derived for waiting on actual values because the assumptions changed. Here a per-load-PC stride predictor learns from the recorded trace, with a confidence threshold. It is an offline scheduling study, including trace-supplied inputs, not an implemented functional value-predicting core. At eight start slots, the no-value-prediction baseline is about three point three four IPC; an oracle that guesses every load correctly reaches about three point nine eight under the other retained assumptions. The real heuristic predicts only a subset and makes mistakes, so its schedules are slower than the baseline at the shown thresholds. Correctness, coverage, prediction availability, I/O ordering and recovery cost must all be addressed before translating this exercise into hardware.

Accuracy alone does not determine whether value prediction pays. Benefit depends on which loads are covered, when predictions arrive, how much dependent work they unlock, and the cost of validation and mistakes. There is no universal ninety-nine-percent threshold. High-confidence value-prediction work, including Perais and Seznec's 2014 research, studies particular mechanisms and recovery choices. Our simple scheduler is not a reproduction of those designs. In the shown eight-slot configuration, perfect load guesses improve this trace schedule by about nineteen percent, while the simple stride heuristic loses performance. Both statements are conditional on the rest of the scheduler's assumptions, including its prediction barriers and idealized memory information. A useful research question is which workload, coverage and recovery policy produces net benefit under a realistic functional model.

Our optional rule delays broadcasting a completed load's value while an older branch or indirect jump remains unresolved. That prevents dependent operations from using that value during the unresolved control speculation. It is inspired by information-flow defenses, but does not implement complete STT or NDA algorithms. In the supplied Spectre experiment, the tested nonzero probe lines no longer reveal PEBBLE. On the Job chapter, model cycles increase from four hundred thirty-seven thousand five hundred eighty to four hundred fifty-three thousand one hundred twelve, about three point five percent. That cost is specific to this trace and implementation. Fault speculation, memory-alias speculation, preexisting register secrets, stores and other channels require separate analysis. We must state the attacker, permitted observations and protected data before making a security guarantee.

Secure speculation is an active research area with formal results under explicit models. ProSpeCT, published in 2023, gives a formal processor model and a constant-time-policy security proof, plus a RISC-V hardware prototype. Dolma's 2021 transient-non-observability design examines broader data sources and store-related attacks, with overheads measured on its chosen workloads and threat models. Such papers show why a successful gadget test is weaker than a stated security theorem. Compare like observations, attacker powers, protected inputs and baseline behavior before comparing guarantees or costs. There is no single minimum security overhead without those definitions. Likewise, the earlier oracle IPC is a trace-and-assumption result, not an implementation target guaranteed by a universal parallelism theorem. Good research turns an explicit model into a precise claim, then tests where that claim stops applying.

Recap, problems, and where this comes backAll tracks3 min

This part connected dependency graphs to scheduling under stated latencies and resources, then separated register-name hazards from real value dependencies. We followed scoreboards, producer tags and precise architectural retirement, and checked a functional out-of-order model against the emulator on finite tests. Trace-oracle studies exposed the importance of their own knowledge, resource and ordering assumptions. A simulated Spectre gadget showed that squashed architectural work can leave observable cache effects, while two mitigations stopped that supplied witness under the model's rules. Finally, passage simulations supported a fitted full-corpus ledger projection. Each conclusion travels with that evidence and scope.

These ideas return in several later parts. Larger windows interact with cache misses and memory-level parallelism in Part 9. Width, energy and multiple cores interact in Part 10. Static scheduling and software pipelining return with compiler transformations. Reordering loads and stores connects to concurrency and memory models, where single-thread correctness and inter-thread visibility are different questions. The simulated security example leads into threat models and operating-system defenses, and static scheduling reappears in specialized hardware. The common habit is to connect a mechanism to a measured workload and explicit assumptions.

In practice, use implementation manuals and measurements together. Linux perf and top-down analysis expose supported event categories when hardware and permissions allow, but event meanings differ across cores. Production processors combine related scheduling ideas with many details omitted by Pebble. BOOM and other open designs let you inspect an implementation, while gem5 and trace simulators answer different modeling questions. Compiler and kernel hardening can mitigate particular speculative attacks under specified conditions; their names are not blanket security guarantees. When a counter, simulator or diagram supports a claim, state what it measures and what assumptions connect that measurement to the question.

The exercises ask you to build dependency schedules, distinguish instruction-count start limits from weighted processing-work bounds, and rename live register versions. Treat the CPI penalty calculation as a defined accounting model rather than a universal causal law. Before hoisting a load, prove its address and exception safety. For the research exercise, define protected data, public inputs, permitted observations and a non-speculative baseline, then search for a counterexample to our control-shadow rule. A finite successful test and a general security proof are different deliverables.

Next, the memory hierarchy. Part 9 studies caches, locality and the Job's miss-rate curves, and measures a latency staircase on this host. It also develops data-movement bounds for classical matrix multiplication under a specified computation model and limited fast memory.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Large windows meet cache misses in Part 9, and width, energy and several cores in Part 10; static scheduling and software pipelining return with the compiler in Part 13; the reordering of loads and stores returns as memory models in Parts 10 and 33; the Spectre gadget returns with threat models in Part 55.

Key results

The part's results in one place, for revision.

The start-slot bound\(\displaystyle T_W\ \ge\ \max\bigl(\lceil N/W\rceil,\ L\bigr)\)
Graham's bound\(\displaystyle T_G\ \le\ \frac{A}{W}+\Bigl(1-\frac{1}{W}\Bigr)L\)
Renaming\(\displaystyle \text{fresh }\allowbreak \text{name }\allowbreak \text{per }\allowbreak \text{write}\ \Rightarrow\ \text{WAR, }\allowbreak \text{WAW }\allowbreak \text{vanish; }\allowbreak \text{RAW }\allowbreak \text{remains}\)
Precise state\(\displaystyle \text{execute }\allowbreak \text{in }\allowbreak \text{any }\allowbreak \text{valid }\allowbreak \text{order; }\allowbreak \text{commit }\allowbreak \text{in }\allowbreak \text{program }\allowbreak \text{order}\)
Penalty accounting\(\displaystyle \text{CPI}=\text{CPI}_{\text{perfect}}+\frac{P}{\text{instructions per redirect}}\)
Index masking\(\displaystyle m=-(x<_u \text{size}),\qquad\allowbreak \text{load } a[x \mathbin{\&} m]\)

Try it

Lab 8 · The dataflow limit of a table scan

Record a scan over a table of word lengths (the shape of the Job's search loop), schedule four of its trips with 1 to 8 starts a cycle, and compare each schedule with the bound max(ceil(N/W), L). Then run the whole scan on the functional out-of-order core with a one-entry and a 64-entry issue queue.

Figure produced by Lab 8: The dataflow limit of a table scan
Produced by the lab below, seed 0, in 0.1 s.
python -m videos.cs.labs 8 needs numpy, scipy, matplotlib · download lab08.py · source on GitHub
four trips: instructions N, work A, span L  24, 28, 6   (the film: 24, 28, 6)
1 start a cycle                             24 cycles   (bound 24)
2 starts a cycle                            12 cycles   (bound 12)
4 starts a cycle                            7 cycles   (bound 6)
8 starts a cycle                            6 cycles   (bound 6)
whole scan, unlimited width: IPC            5.82 renamed, 3.01 with register names reused
functional core, 1-entry issue queue        546 cycles, IPC 0.83
functional core, 64-entry issue queue       174 cycles, IPC 2.61

Width helps until the longest dependency chain is reached: 24, 12, 7 and then 6 cycles, the span. The real core, with a finite front end and in-order retirement, sits between the in-order machine and the oracle.
The code (100 lines; it asserts its own result)
"""Lab 8: schedule four trips of a table scan on an oracle machine, then run the scan on Pebble's out-of-order core."""

from videos.coursekit import labs

import math

import numpy as np

from explainer.cs.pebble import assemble
from explainer.cs.pebble import predict as PR
from explainer.cs.pebble.emu import run as emulate
from explainer.cs.pebble.limits import LAT, Trace, schedule, trace
from explainer.cs.pebble.ooo import OutOfOrder

TITLE = "The dataflow limit of a table scan"
GOAL = ("Record a scan over a table of word lengths (the shape of the Job's search loop), schedule four of its trips "
        "with 1 to 8 starts a cycle, and compare each schedule with the bound max(ceil(N/W), L). Then run the "
        "whole scan on the functional out-of-order core with a one-entry and a 64-entry issue queue.")
TASKS = [
    "Give loads a latency of 4 (schedule(sub, width=w, latency={'load': 4})). What is the new span L, and at which width is it reached?",
    "Schedule the whole trace with branches='barrier' (no speculation). How far does the IPC fall, and why?",
    "Run the core with width=8 and with rob_size=16. Which of the two changes the cycle count on this scan?",
]

SCAN = """
        la   t0, table
        li   a2, 0
        li   s1, {n}
        li   a1, 99          # a length no entry has: every trip takes the fast path
scan:   beq  a2, s1, done    # end of the table?
        lw   t1, 4(t0)       # this entry's length
        bne  t1, a1, next    # a different length: next entry
        j    done
next:   addi t0, t0, 12
        addi a2, a2, 1
        j    scan
done:   halt
        .align 4
table:
{rows}
"""


def run(seed=0):
    rng = np.random.default_rng(seed)
    n = int(rng.integers(40, 80))
    rows = "\n".join(f"        .word 0, {int(v)}, 0" for v in rng.integers(1, 12, n))
    prog = assemble(SCAN.format(n=n, rows=rows))
    tr = trace(prog.image, mem_size=8192)
    i0 = int(np.flatnonzero(tr.pc == prog.labels["scan"])[10])  # four trips from the middle of the scan
    sub = Trace(*(x[i0:i0 + 24] for x in (tr.pc, tr.kind, tr.srcs, tr.dst, tr.addr, tr.taken, tr.load_value)))
    N, A, L = len(sub), sum(LAT[k] for k in sub.kind), schedule(sub).cycles
    lab = labs.Lab()
    lab.row("four trips: instructions N, work A, span L", f"{N}, {A}, {L}   (the film: 24, 28, 6)")
    assert (N, A, L) == (24, 28, 6)

    widths = list(range(1, 9))
    cycles = [schedule(sub, width=w).cycles for w in widths]
    bounds = [max(math.ceil(N / w), L) for w in widths]
    for w in (1, 2, 4, 8):
        lab.row(f"{w} start{'s' if w > 1 else ''} a cycle", f"{cycles[w - 1]} cycles   (bound {bounds[w - 1]})")
    assert all(c >= b for c, b in zip(cycles, bounds)), "no schedule beats max(ceil(N/W), L)"
    assert [cycles[w - 1] for w in (1, 2, 4, 8)] == [24, 12, 7, 6], "the film's four schedules"
    assert all(a >= b for a, b in zip(cycles, cycles[1:])), "more start slots never hurt"

    free, named = schedule(tr), schedule(tr, rename=False)
    lab.row("whole scan, unlimited width: IPC", f"{free.ipc:.2f} renamed, {named.ipc:.2f} with register names reused")
    assert 5 < free.ipc <= 6 and named.ipc < 0.7 * free.ipc, "one trip a cycle, unless names are reused"

    ref = emulate(prog.image, mem_size=8192)
    cores = {}
    for iq in (1, 64):
        c = OutOfOrder(prog.image, mem_size=8192, iq_size=iq, predictor=PR.Tournament()).run()
        assert c.regs == ref.regs and c.committed == ref.steps, "the core computes what the emulator does"
        cores[iq] = c
    lab.row("functional core, 1-entry issue queue", f"{cores[1].cycles} cycles, IPC {cores[1].ipc:.2f}")
    lab.row("functional core, 64-entry issue queue", f"{cores[64].cycles} cycles, IPC {cores[64].ipc:.2f}")
    assert cores[64].cycles < 0.6 * cores[1].cycles and cores[64].ipc < free.ipc
    lab.note = ("Width helps until the longest dependency chain is reached: 24, 12, 7 and then 6 cycles, the span. "
                "The real core, with a finite front end and in-order retirement, sits between the in-order machine "
                "and the oracle.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    colors = {"load": labs.BLUE, "branch": labs.RED, "alu": labs.GREEN, "jump": labs.GREY}
    s4 = schedule(sub, width=4).start
    seen = set()
    for i in range(N):
        k = sub.kind[i]
        ax[0].barh(i, LAT[k], left=int(s4[i]), color=colors[k], height=0.8, label=None if k in seen else k)
        seen.add(k)
    ax[0].invert_yaxis()
    ax[0].set(title="Four trips, four starts a cycle: 7 cycles", xlabel="cycle", ylabel="instruction, in program order")
    ax[0].legend(loc="upper right")
    ax[1].plot(widths, cycles, "o-", color=labs.GOLD, label="scheduled cycles")
    ax[1].plot(widths, bounds, "--", color=labs.BLUE, label="bound max(ceil(N/W), L)")
    ax[1].axhline(L, color=labs.RED, ls=":", label=f"span L = {L}")
    ax[1].set(title="Cycles against start width", xlabel="starts per cycle W", ylabel="cycles", ylim=(0, 26))
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Give loads a latency of 4 (schedule(sub, width=w, latency={'load': 4})). What is the new span L, and at which width is it reached?
  2. Schedule the whole trace with branches='barrier' (no speculation). How far does the IPC fall, and why?
  3. Run the core with width=8 and with rob_size=16. Which of the two changes the cycle count on this scan?

Problems, with solutions

Try each problem before opening its solution.

  1. Work and span. Use lw a0, 0(s0); lw a1, 4(s0); add a2, a0, a1; mul a3, a2, a2; add a4, a0, a3, with load/multiply/add latencies 2/3/1. Find N, A and L, then distinguish the two width models.

    Solution

    N = 5, A = 9, L = 7. Both loads feed the first add, then multiply, then final add; the first load also feeds the final add. With W new starts per cycle and otherwise unlimited resources, T₁ = 8 and T₂ = 7; each satisfies max(⌈N/W⌉, L) ≤ T_W. For W nonpreemptive processors occupied for the operation's full latency, greedy T_G is 9 at W = 1 and 7 at W = 2, within Graham's bounds 9 and 8 respectively.

  2. Renaming. Rename the textbook example with p10, p11, ….

    Solution

    lw p10, 0(s0); lw p11, 4(s1); mul p12, p11, a3; sub p13, p10, p11; div p14, p12, p10; add p15, p13, p11. True value dependencies survive. The divide reads the older p10 while the add writes p15, removing the architectural-name WAR hazard. Reclaim names only when safe.

  3. Penalty accounting. A defined model has perfect-prediction CPI 0.3, one miss per 40 retired instructions and an additive 15-cycle effective penalty. Determine CPI. Can these values determine ROB occupancy?

    Solution

    CPI = 0.3 + 15/40 = 0.675. The additive term is 55.6% of this accounting total. It does not determine occupancy: dependency chains, unresolved-operation duration, fetch/issue/retire widths, recovery and memory behavior also matter. An average inter-miss instruction count is not a hard lookahead bound.

  4. Masking. Compare a bound-dependent mask with x & (size - 1) for unsigned x and a nonempty 2ᵏ-byte array.

    Solution

    In this model, sltu, sub, and make the dependent access wait for the bound comparison's value; invalid x maps to the valid fallback index 0. Modulo masking also stays inside that exact power-of-two array, but wraps invalid requests rather than validating them. For a shorter logical array it may expose invalid logical elements. Either mechanism needs the intended policy, valid fallback and compiler/ISA dependency guarantees. This model does not implement value prediction; general side-channel security needs a threat model.

  5. Hoist the scan load. Repeat Part 7's transformation on chapter 1 after checking address/exception safety.

    Solution

    The stored experiment takes 437,580 → 437,072 cycles (about 0.12%), with 331 extra retired instructions and unchanged output. The specified extra read stays in allocated model memory. Out-of-order scheduling already overlaps much of this load's latency; this result is conditional on the program, inputs, memory and prediction policy, and does not authorize arbitrary speculative loads.

  6. Research. Define protected/public inputs, permitted observations and a non-speculative baseline. Search for a leak or a workload costing over 30% under secure=True, then compare a more selective rule.

    Starting point. The rule withholds completed load values while an older branch is unresolved; cache fills still occur. The supplied gadget's decoder fails, and a 3,000-node pointer chase costs 19,378 → 23,919 cycles (23.4%). Neither observation proves security, guarantees a larger slowdown on longer chains, nor predicts the cost of a literature design. Test counterexamples and overhead separately; a general proof needs the defined observation/threat model and full microarchitectural behavior.

Notes and sources

Glossary

乱序执行 out-of-order execution · 数据流图 dataflow graph · 关键路径 critical path · 工作量与跨度 work and span · 指令级并行 instruction-level parallelism (ILP) · 真依赖 true dependence · 反依赖 anti-dependence (WAR) · 输出依赖 output dependence (WAW) · 寄存器重命名 register renaming · 寄存器别名表 register alias table (RAT) · 物理寄存器 physical register · 空闲列表 free list · 记分牌 scoreboard · 保留站 reservation station · 公共数据总线 common data bus · 标签 tag · 托马苏洛算法 Tomasulo's algorithm · 重排序缓冲区 reorder buffer (ROB) · 提交 / 退休 commit / retire · 不精确异常 imprecise exception · 发射队列 issue queue · 唤醒与选择 wakeup and select · 超标量 superscalar · 指令窗口 instruction window · 极限研究 limit study · 推测执行 speculative execution · 错误路径 wrong path · 预测错误代价 misprediction penalty · 取数队列 / 存数队列 load queue / store queue · 存数到取数转发 store-to-load forwarding · 内存消歧 memory disambiguation · 内存顺序违例 memory-order violation · 等待表 wait table · 存储集 store sets · 机器清除 machine clear · 侧信道 side channel · 冲刷+重载 Flush+Reload · 幽灵 Spectre · 熔断 Meltdown · 推测屏障 speculation barrier · 下标掩码 index masking · 超长指令字 VLIW · 显式并行指令计算 EPIC · 软件流水 software pipelining · 启动间隔 initiation interval · 精简指令集 RISC · 复杂指令集 CISC · 微操作 micro-op · 宏融合 macro-fusion · 同时多线程 simultaneous multithreading (SMT) · 超线程 Hyper-Threading · 数值预测 value prediction · 安全推测 secure speculation · 推测污点追踪 speculative taint tracking · 推测非干涉 speculative non-interference · 超前执行 runahead execution

Sources

The reading list is split, as the research tier asks (videos/cs/SYLLABUS.md §1.1), into the qualifying-exam canon and recent work.

Canon. Books: Hennessy & Patterson, Computer Architecture: A Quantitative Approach, 6th ed., ch. 3 (the scoreboard example and its latencies, Tomasulo's algorithm, the reorder buffer, multiple issue, limits of ILP, SMT); Shen & Lipasti, Modern Processor Design, ch. 4–9; Thornton, Design of a Computer: The Control Data 6600 (1970); Fog, The microarchitecture of Intel, AMD and VIA CPUs (updated yearly).

Papers: Graham, "Bounds for certain multiprocessing anomalies", Bell System Technical Journal (1966); Tomasulo, "An efficient algorithm for exploiting multiple arithmetic units", IBM J. R&D (1967); Riseman & Foster, "The inhibition of potential parallelism by conditional jumps", IEEE Trans. Computers (1972); Keller, "Look-ahead processors", Computing Surveys (1975); Patterson & Ditzel, "The case for the reduced instruction set computer", Computer Architecture News (1980); Fisher, "Trace scheduling: a technique for global microcode compaction", IEEE Trans. Computers (1981); Rau & Glaeser, "Some scheduling techniques and an easily schedulable horizontal architecture", MICRO (1981); Smith & Pleszkun, "Implementation of precise interrupts in pipelined processors", ISCA (1985); Lam, "Software pipelining", PLDI (1988); Wall, "Limits of instruction-level parallelism", ASPLOS (1991); Tullsen, Eggers & Levy, "Simultaneous multithreading: maximizing on-chip parallelism", ISCA (1995); Lipasti, Wilkerson & Shen, "Value locality and load value prediction", ASPLOS (1996); Yeager, "The MIPS R10000 superscalar microprocessor", IEEE Micro (1996); Moshovos, Breach, Vijaykumar & Sohi, "Dynamic speculation and synchronization of data dependences", ISCA (1997); Chrysos & Emer, "Memory dependence prediction using store sets", ISCA (1998); Kessler, "The Alpha 21264 microprocessor", IEEE Micro (1999).

Recent. Mutlu, Stark, Wilkerson & Patt, "Runahead execution", HPCA (2003); Yarom & Falkner, "FLUSH+RELOAD", USENIX Security (2014); Perais & Seznec, "Practical data value speculation for future high-end processors", HPCA (2014); Kocher et al., "Spectre attacks: exploiting speculative execution", IEEE S&P (2019); Lipp et al., "Meltdown: reading kernel memory from user space", USENIX Security (2018); Yan et al., "InvisiSpec", MICRO (2018); Yu et al., "Speculative taint tracking (STT)", MICRO (2019); Weisse et al., "NDA: preventing speculative execution attacks at their source", MICRO (2019); Guarnieri et al., "Spectector: principled detection of speculative information flows", IEEE S&P (2020); Choudhary et al., "Speculative privacy tracking (SPT)", MICRO (2021).

Core data (chapter 13) are a historical selection, not a current-core survey. Counted operation units vary. Apple Firestorm is separate: Dougall Johnson's reverse-engineered notes distinguish about 330 coalesced retire groups from about 623 rename-retire entries. See his notes.

Additional research: Loughlin et al., Dolma: Securing speculation with the principle of transient non-observability, USENIX Security (2021); Daniel et al., ProSpeCT: Provably secure speculation for the constant-time policy, USENIX Security (2023). These are distinct mechanisms and threat models; this chapter's control-shadow experiment reproduces neither complete design. The QA packet records exactly which primary excerpts were inspected.

About this partfrom its README

Part 8 of the sixty-one-part course (series plan, syllabus) studies dependency scheduling, register renaming, retirement, speculation and memory ordering using an executable teaching model. The functional core is explainer/cs/pebble/ooo.py; the offline trace scheduler is explainer/cs/pebble/limits.py. These implement different scheduling models. compute.py produces the chapter's numerical data, and tests/test_cs8_ooo.py checks selected configurations against the emulator.

Chapter notes
  • Hook. A one-entry issue queue forces in-order starts; increasing it to 64 exposes overlap and increases queue capacity together. The short cold-load example takes 81 versus 70 modeled cycles. On chapter 1, retired IPC is 0.78 versus 1.89; Part 7's 0.83 comes from a separate pipeline. Whole-run mean ROB occupancy is 10.7 of 128 entries; the plot shows a 600-cycle sample, not a complete execution.
  • 1. Dataflow. Four scan trips have N = 24 instructions, weighted latency work A = 28 and span L = 6. The unlimited-unit scheduler limits new starts per cycle: widths 1, 2, 4, 8 take 24, 12, 7, 6 cycles. Its lower bound is max(⌈N/W⌉, L). Graham's nonpreemptive W-processor bound is separately T_G ≤ A/W + (1 − 1/W)L, using occupied processor time rather than start slots.
  • 2. Renaming. Source-operand uses and name-reuse events have explicit counting conventions. Distinct live versions remove register WAR/WAW hazards; physical registers are later reclaimed safely. The offline oracle's 2,399 versus 3.68 IPC uses future paths, trace-supplied inputs and memory word addresses, unlimited resources, and omitted realistic device/I/O ordering. It is not a feasible hardware speedup or an algorithmic lower bound.
  • 3–4. Scoreboard and Tomasulo. Stage-specific hazards, reservation-station tags and broadcasts are animated through a textbook example (62 versus 56 cycles). In-order dispatch and finite station pressure still matter. Renaming alone does not provide precise architectural exceptions.
  • 5. Reorder buffer. The retirement ring and exception timeline separate architectural commit from physical execution/cache effects. Pebble deliberately faults on divide by zero; this differs from RISC-V M. The model's width W applies to fetch, rename and retirement, with up to W ALUs and two memory ports, W+2 total issue slots.
  • 6. ILP limits. Sensitivity bars and start-distance curves describe the offline scheduler. Its window constrains start times by instruction-index distance, not by the oldest unfinished instruction or a physical ROB. Functional-core width/capacity sweeps are a separate experiment; retired IPC is not slot utilization.
  • 7. Speculation. A recorded wrong path is squashed and fetched again. The chapter-1 tournament run counts 22,296 redirects and 253,764 squashed renamed entries, including some wrong-path redirects; entries are not execution starts. The fitted effective penalty, about 7.9 cycles, is counterfactual configuration accounting. The 37 retired instructions per counted redirect do not determine ROB occupancy or a lookahead ceiling.
  • 8. Memory ordering. Byte-range overlap, youngest older stores, forwarding and late-address replay are distinguished. A fixed 1,500-sample histogram takes 97,740 / 7,652 / 7,408 cycles under conservative, speculative and wait-table policies; the speculative run has 23 dynamic violations. All three take 437,580 cycles on chapter 1, with 154,835 loads and 5,270 stores covering counts, metadata and copied letters.
  • 9. Spectre. The simulated byte array places secret bytes outside a policy bound, without hardware permission isolation. The experiment flushes probes, trains six times (warming line 0), evicts the bound, executes a custom timer barrier, attacks, then times lines 1–255. Hit/miss intervals are 5/63 cycles; six rounds decode PEBBLE in 109,424 cycles. The decoder excludes zero. Barrier, mask and control-shadow variants give all-63 tested probe intervals. This finite gadget result is not a proof against every channel. Barriers are ISA-specific; masking needs unsigned comparisons, a nonempty valid fallback and preserved dependencies.
  • 10. VLIW. Bundles and colored software-pipelined iterations illustrate resource/data schedules on a fixed path. They are not an executable control-flow translation: same-bundle operand versions, guards, exits and branches need ISA rules. Variable latency, interlocks and compatibility costs depend on the implementation.
  • 11. RISC/CISC. Runtime depends on instruction count, CPI and clock. lw plus a combined compare/branch can correspond to cmp [mem] plus jne: two instructions on each side. The 90,726 heuristic load-use/name-liveness candidates do not establish legal translations or instruction savings. Internal micro-ops are implementation operations, and load-operation micro-fusion differs from compare/branch macro-fusion.
  • 12. SMT. An offline two-trace start-slot schedule illustrates aggregate throughput (+40% at four slots, +80% at eight in the selected study). It is not a functional SMT core or a per-thread latency/fairness guarantee.
  • 13. Core measurements. A 1995–2024 historical selection uses differing counted units. Firestorm's estimated coalesced groups and rename-retire entries are shown separately. Widths at different stages, workload-dependent branch accuracy, physical memory delays and measurement definitions must be distinguished.
  • 14. Job projection. CPI components compare configurations rather than partition unique causes. A fit to 24 passages uses encoded-byte features. The heldout 16,000-character passage is 16,019 bytes: 3,290,777 measured cycles versus 3,287,720 predicted (−0.09%). The corpus row projects 50,727,519,299 cycles, 57.32 seconds at an assumed 884.96 MHz, 2.52 times faster than the pipeline projection. No full-corpus run, error bound or physical out-of-order clock validation is supplied.
  • 15. Frontier. Value prediction needs accuracy, coverage, availability and recovery. Perfect load guesses improve the selected eight-slot oracle schedule by 19%; the stride heuristic loses at the shown thresholds. There is no universal 99% threshold. The control-shadow rule blocks this decoder at a 3.55% chapter-1 cost; STT, NDA, Dolma and ProSpeCT have distinct mechanisms, policies and proof scopes.
  • Outro. Animated recap, course connections, practical tools, exercises and the next part's illustrative memory hierarchy. Matrix-multiplication data-movement bounds depend on the computation model and memory assumptions.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. The limits of in-order: one cache miss stalls everything. The dataflow graph of a basic block: its critical path against the machine's width.
  2. Dependencies: true (RAW) against name (WAR, WAW). Renaming removes the false ones.
  3. Scoreboarding (CDC 6600, 1964, Thornton and Cray).
  4. Tomasulo's algorithm (IBM 360/91, 1967), step by step: reservation stations, the common data bus, tag broadcast.
  5. The reorder buffer and in-order commit (Smith & Pleszkun 1985): precise exceptions with out-of-order execution. The physical register file and the RAT. The modern pipeline: fetch, rename, dispatch, issue, execute, write back, commit.
  6. Superscalar issue, and the ILP wall: Wall's 1991 limits study, repeated on our traces with an oracle machine at widths 1–16.
  7. Speculation past predicted branches, and recovery.
  8. Memory disambiguation: load and store queues; store-to-load forwarding.
  9. Spectre and Meltdown (2018): speculation leaves cache footprints. The bounds-check-bypass gadget runs in our out-of-order model, with a simulated cache-timing channel (Part 55 returns to it).
  10. VLIW and EPIC (Itanium): the compiler-scheduled alternative and why it lost; list scheduling and software pipelining (Part 13).
  11. RISC against CISC: the IBM 801 (Cocke), Berkeley RISC, Stanford MIPS, x86 µops, ARM, RISC-V; the 2017 Turing Award.
  12. Simultaneous multithreading.
  13. Modern cores in numbers (cited): ROB sizes, decode widths, port counts.
  14. The Job on our out-of-order model. Ledger row 2.
  15. Frontier: past the dataflow limit, safely. Value prediction in the limit study (perfect +19%, a stride predictor loses); a secure-speculation rule built into the core (blocks the gadget for 3.5%); speculative non-interference and the open cost floor.
  16. Outro.

Computed: the out-of-order simulator (Tomasulo plus ROB) on Pebble traces; IPC against width and ROB size; the dataflow-limit study; the Spectre toy. Visuals: the CDB broadcasting tags as glowing pulses; the Job's inner-loop dataflow graph with its critical path; the ROB as a ring buffer filling and retiring. In practice: CPU design teams, Spectre mitigations in kernels, browsers and clouds, reading microarchitecture guides for tuning. Reading: Hennessy & Patterson ch. 3; Tomasulo 1967; Thornton, Design of a Computer: The Control Data 6600; Smith & Pleszkun 1985; Shen & Lipasti; Wall 1991; Patterson & Ditzel 1980; Kocher et al. 2019; Lipp et al. 2018.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 工作量与跨度。 上述五条指令有 N = 5、A = 9、L = 7。每周期限制新启动数、其余资源无限时,T₁ = 8、T₂ = 7, 满足 max(⌈N/W⌉, L) ≤ T_W。若 W 个处理器在指令整个延迟内被占用,则贪心调度分别为 9 和 7,Graham 上界分别为 9 和 8。
  2. 重命名。 依次使用 p10–p15,得到上面的指令序列。真实值依赖仍在;除法读取旧版本 p10,加法写入 p15,名称反依赖消失。 物理名称只能在安全时回收。
  3. 预测代价。 指定加法记账模型给出 CPI = 0.3 + 15/40 = 0.675,附加项占总量 55.6%。这些平均数不能确定 ROB 占用; 依赖、未完成操作、宽度、恢复和内存行为同样重要。
  4. 掩码。 无符号、非空且大小恰为 2ᵏ 字节时,两种掩码都把下标限制在数组内。依赖比较的掩码把无效请求映射到合法的零下标; 模数掩码会回绕,并不验证原请求。较短逻辑数组仍可能暴露无效元素;还须保持编译器与 ISA 要求的数据依赖。
  5. 提前取数。 先证明指定额外读的地址与异常安全。该实验周期为 437,580 → 437,072,约省 0.12%,多退休 331 条指令,输出相同。 乱序调度已重叠大部分延迟;结论受程序、输入、内存与预测策略约束。
  6. 研究题。 明确秘密、公开输入、可见观察与非推测基线,再寻找泄露反例或超过 30% 的开销。规则扣住取数值,却仍会填充缓存; 指定攻击解码失败与一次指针追逐的 23.4% 开销都不是一般安全证明,也不能预测文献方案的成本。

Build the film

python -m videos.cs.cs8.compute        # the part's numbers, into .cache/cs8
python tools/build.py cs8                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs8 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs8. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs8.compute
python -m videos.cs.cs8.compute --force spectre  # refresh the corrected timer-site parser
python -m unittest discover -s tests -p test_cs8_ooo.py -q
python tools/build.py cs8 -q l
python tools/build.py cs8

The corpus is projected from passages. Ledger rows 0–2 live in .cache/cs8/ledger.json; the clock is an assumed teaching budget inherited from Part 7. Host simulation throughput is not a silicon timing measurement.

The 9 November 2026 QA packet binds the source/preview checkpoint to bilingual captures, numerical witnesses, English speech signals, actual cue requests and selected native/narrated clips. The Spectre parser now identifies the two timed probe instruction PCs: extra timer reads inserted by fenced training previously shifted fixed-size chunks. Only mitigations.fence.fast[0] changes, 2 → 1; simulated execution and all other numerical fields are unchanged. Continuous narrated listening, Chinese speech, whole-video native review and production runtime approval remain open.