這份筆記照 UCA2026_Chapter_4.pptx 的頁序走,內容對應課本
(Patterson & Hennessy, Computer Organization and Design, RISC-V Edition)第四章。
課本的專有名詞一律用英文,只在第一次出現時附上中文;ch01–ch03 定義過的詞(register、ALU、PC、CPI、IPC、throughput、sign extension、R/I/S/SB-format、DGEMM、FMA…)直接使用。
標題的節號照投影片;投影片從 §4.6 開始比第一版課本多 1(例如投影片的 §4.6 Pipelining 是第一版的 §4.5)。
ch01 說程式的執行時間是 IC × CPI × clock cycle time;ch02 說明了 IC 由 ISA 與 compiler 決定。 剩下的 CPI 和 clock cycle time 由 processor 的硬體決定,第四章就是要打開 processor,看硬體到底怎麼執行一條 instruction。整章的敘事線是:
flowchart TD
A["最簡單的做法:single-cycle<br/>一條 instruction 一個 clock cycle"] --> B["問題:clock cycle 被最慢的 ld 拖長"]
B --> C["解法:pipelining<br/>把 instruction 切成五段接力做"]
C --> D["新問題:hazard<br/>下一條 instruction 不能馬上開始"]
D --> E["data hazard<br/>forwarding 與 stall"]
D --> F["control hazard<br/>branch prediction 與 flush"]
E --> G["exception<br/>另一種 control hazard"]
F --> G
G --> H["再更快:ILP<br/>multiple issue、dynamic scheduling、speculation"]
H --> I["實例:Cortex-A53、Core i7<br/>以及 DGEMM 的 loop unrolling"]貫穿全章的一句話是:pipelining 提高 instruction 的 throughput,但不縮短單一 instruction 的 latency。後半章所有的麻煩(hazard、exception、speculation)都來自「同時有好幾條 instruction 在跑」。
page-02–03 Introduction(§4.1)
這章做出兩個 RISC-V 的實作。 先做一個簡化版(single-cycle),再做一個比較接近真實的 pipelined 版本。 為了讓圖畫得下,只實作 RISC-V 的一小部分 instruction,但這幾條已經涵蓋了各類 instruction 需要的硬體:
| 類別 | Instruction | 需要的硬體 |
|---|---|---|
| Memory reference | ld、sd | 算 address、讀寫 data memory |
| Arithmetic/logical | add、sub、and、or | 讀兩個 register、ALU 運算、寫回 register |
| Control transfer | beq | 比較兩個 register、算跳躍目標、改 PC |
沒有 shift、乘除、floating point,但它們的做法跟這幾條類似。
每條 instruction 的執行步驟(page-03)。 不管哪一類,前兩步都一樣:
- 用 PC 當 address 到 instruction memory 取出 instruction(fetch);
- 用 instruction 裡的 register 編號欄位,從 register file 讀出一個或兩個 register。
之後才依類別分開,但三類的動作也很像——都會用到 ALU:
- Arithmetic/logical 用 ALU 算結果;
- Load/store 用 ALU 算 memory address,然後讀或寫 data memory;
- Branch 用 ALU 比較兩個 register。
最後,arithmetic/logical 與 load 把結果寫回 register;PC 則更新成 PC + 4,或者(branch 成立時)跳躍目標。 三類 instruction 這麼相似,是因為 RISC-V 的 instruction set 簡單又規律(ch02 的 simplicity favors regularity),硬體才能共用。
page-04–06 CPU Overview, Multiplexers, Control
page-04 的圖是上面步驟的硬體版:PC 接 instruction memory,取出的 instruction 送到 register file,讀出的值送進 ALU,ALU 的結果再送到 data memory 或寫回 register file;上方兩個 Add 分別算 PC + 4 與 branch 目標。
這張圖省略了兩件事,page-05 與 page-06 補上。
1. 線不能直接接在一起(page-05)。 圖上有三個地方是「兩個來源接到同一個輸入」(紅圈處):
- PC 的新值來自 PC + 4 或 branch 目標;
- 寫回 register file 的資料來自 ALU 或 data memory;
- ALU 的第二個輸入來自 register 或 instruction 裡的 immediate。
兩條訊號線直接接在一起會互相干擾,所以要放一個元件負責挑一個:
有好幾個資料輸入和一個選擇訊號(select),依選擇訊號把其中一個輸入送到輸出。課本說它其實更該叫 data selector。
2. 各元件要被控制(page-06)。 同一個元件,不同 instruction 要它做不同的事:data memory 遇到 load 要讀、遇到 store 要寫;register file 只有 load 和 arithmetic/logical 才寫;ALU 要做加、減、AND 或 OR。 這些都靠 control signal 決定,而 control signal 由一個 control unit 根據 instruction 的欄位產生。 page-06 的藍線就是 control signal:RegWrite、ALU operation、MemRead、MemWrite,以及三個 mux 的選擇訊號。 最上面那個 mux 決定 PC 的新值:一個輸入是 PC + 4(下一條),另一個是 branch 的跳躍目標。它的選擇訊號來自圖上 mux 旁邊那個 AND gate,AND gate 有兩個輸入:
- Branch:control unit 看 instruction 後給出,這條是
beq時為 1; - Zero:ALU 的一個輸出,運算結果是 0 時為 1。
beq讓 ALU 把兩個 register 相減,相減得 0 就代表兩者相等。
兩個都是 1(這條是 beq,而且兩個 register 相等),mux 才選跳躍目標;其他情況都選 PC + 4。只看 Zero 不夠,因為別的 instruction(例如 sub 算出 0)也可能讓 Zero 是 1,但它們不該跳。
page-07–11 Logic Design Basics(§4.2)
在組 datapath 之前,要先約定硬體元件怎麼運作、什麼時候讀寫。
資訊怎麼表示(page-07)。 低電壓代表 0、高電壓代表 1;一條線一個 bit,多個 bit 的資料走一組線(bus)。圖上粗線是 bus,64-bit 的資料就是 64 條線。
datapath 裡的元件只有兩種:
輸出只取決於「現在」的輸入:同樣的輸入永遠得到同樣的輸出,內部不存任何東西。例如 AND gate、adder、mux、ALU(page-08)。
內部存有資料的元件,輸出取決於輸入和存著的內容,又叫 sequential element。例如 register、register file、memory。
為什麼叫 state?把電腦的所有 state element 的內容存起來,斷電後再寫回去,電腦就能像沒斷過電一樣繼續跑——這些元件的內容完整描述了電腦的狀態。
Combinational element 的例子(page-08)。
| 元件 | 功能 |
|---|---|
| AND gate | |
| Multiplexer | (S 是 1 選 ,0 選 ) |
| Adder | |
| ALU | ,F 是選擇運算種類的 control 輸入 |
Register(page-09–10)。 Register 用 clock 訊號決定什麼時候更新存的值。
只在 clock 改變的那一瞬間(clock edge)更新存的值;其他時間輸入怎麼變,輸出都不變。Clock edge 有兩種:從 0 變 1 的 rising edge,以及從 1 變 0 的 falling edge。
page-09 的波形:D(輸入)可以隨時變,但 Q(輸出)只在 Clk 的 rising edge 才跟著變成那一刻的 D。
有些 register 不是每個 cycle 都要更新,例如存著之後還要用的值。page-10 的 register 多了一個 Write 控制輸入:只有在 clock edge 而且 Write = 1 時才更新。 沒畫 Write 的 state element(例如 PC)就是每個 clock edge 都會寫入。
Asserted 與 deasserted課本用 asserted 表示訊號是邏輯上的「真」,deasserted 表示「假」。不直接說 1 和 0,是因為實際電路有時用低電壓代表真。這份筆記為了好讀,直接說訊號是 1 或 0。
Clocking methodology(page-11)
規定訊號什麼時候可以讀、什麼時候可以寫的規則。
為什麼需要規則?如果一個訊號在被寫入的同時被讀取,讀到的可能是舊值、新值,甚至新舊混在一起,硬體就不可預測。這章用的規則是 edge-triggered:所有 state element(包括 memory)都只在 clock edge 更新,而且課本統一假設是 rising edge,之後筆記說的「clock edge」都是指它。用 falling edge 也可以,只要全部元件都用同一種。 注意 clock 只管寫入:state element 隨時可以讀,輸出一直是上一個 edge 寫進去的值;combinational element 沒有 clock,輸入一變輸出就跟著變。於是:
- Combinational logic 夾在 state element 之間(page-11 左圖):輸入來自 state element 1,輸出寫進 state element 2;
- 一個 clock cycle 內,訊號要從 state element 1 出發、穿過 combinational logic、在下一個 clock edge 之前穩定地抵達 state element 2;
- 所以 最長的那條路徑的延遲決定 clock period。
page-11 右圖是同一個 state element 的輸出經過 combinational logic 又接回自己的輸入。這樣不會亂掉嗎?不會:state element 只在 edge 更新,這個 cycle 讀到的一定是上一個 edge 寫進去的值,新算出的值要等下一個 edge 才寫入。 所以同一個 cycle 裡可以讀一個 register、算一算、再寫回同一個 register。後面的 register file 與 PC 都靠這個性質。
page-12–17 Building a Datapath(§4.3)
CPU 裡處理資料與 address 的元件,以及它們之間的連線:register、ALU、mux、memory……
做法是一類一類看 instruction 需要哪些元件,最後拼成一張圖。
Instruction fetch(page-13)
每條 instruction 都要做:用 PC 從 instruction memory 讀出 instruction,同時算出下一條的 address。需要三個元件:
- PC:64-bit register,存目前這條 instruction 的 address。每個 cycle 都寫入,所以沒有 write 控制;
- Instruction memory:給 address、輸出那裡的 instruction。這個 datapath 只讀不寫,所以把它當 combinational logic,不需要 read 控制;
- Adder:把 PC 加 4(instruction 都是 4 bytes),結果接回 PC。它是一個控制線固定成「加」的 ALU,圖上標 Add。
R-format(page-14)
add x1, x2, x3 這類 instruction 讀兩個 register、做運算、寫一個 register。需要兩個元件:
存放 32 個 register 的 state element,給 register 編號就能讀寫對應的 register。
page-14 左邊的 register file 有:
| 埠 | 寬度 | 作用 |
|---|---|---|
| Read register 1、Read register 2 | 5 bits | 要讀的 register 編號() |
| Read data 1、Read data 2 | 64 bits | 讀出的值 |
| Write register | 5 bits | 要寫的 register 編號 |
| Write data | 64 bits | 要寫入的值 |
| RegWrite | 1 bit | 寫入控制 |
讀不需要控制訊號:register file 隨時輸出 Read register 指定的那兩個 register 的內容。寫要等 RegWrite = 1 且 clock edge 到來。 因為寫入是 edge-triggered,同一個 cycle 裡讀和寫同一個 register 是合法的:讀到的是之前寫入的舊值,這個 cycle 寫的值下一個 cycle 才讀得到。
右邊的 ALU 吃兩個 64-bit 輸入、輸出 64-bit 結果,另外有一個 Zero 輸出:結果是 0 時為 1。運算種類由 4-bit 的 ALU operation 訊號選擇(page-21)。
Load / store(page-15)
ld x1, offset(x2) 和 sd x1, offset(x2) 都要算 address = x2 + offset,offset 是 instruction 裡的 12-bit signed 常數。
sd 還要讀出 x1 寫進 memory;ld 要把讀出的資料寫進 x1。除了 register file 與 ALU,還需要兩個元件:
- Data memory:輸入有 Address 與 Write data,輸出 Read data;控制訊號 MemWrite(store 時寫入)與 MemRead(load 時讀出)。
為什麼 data memory 要有 read 控制,register file 卻不用?因為 register 編號不可能不合法:5 bits 能表示的 0–31 剛好對應 32 個 register,隨便讀哪一個都沒事。
Memory address 則有 64 bits,實際的 memory 遠小於 bytes,很多 address 根本沒有對應的 memory,讀了會出問題(第 5 章)。
而 ALU 每個 cycle 都會算出一個結果送到 data memory 的 Address,例如
add的和根本不是 address;沒有 MemRead,每條 instruction 都會拿這個值去讀 memory。所以只在 load 時才讀。 - Imm Gen(immediate generation unit):輸入整條 32-bit instruction,取出 immediate 欄位並 sign-extend 成 64 bits(ch02 的 sign extension)。ALU 只吃 64-bit 的輸入,12-bit 的 offset 得先擴展。
Imm Gen 要從哪幾個 bit 取 immediate,依 instruction 而不同(ch02 說過 S-format 把 immediate 拆成兩段):
| Instruction | Immediate 所在的 bits |
|---|---|
ld(I-format) | 31:20 |
sd(S-format) | 31:25 與 11:7 |
beq(SB-format) | 31、7、30:25、11:8 |
Imm Gen 看 opcode 決定取哪組:opcode 的 bit 6 對 load/store 是 0、對 branch 是 1;bit 5 對 load 是 0、對 store 是 1。用這兩個 bit 控制內部一個三選一的 mux 就行了。
Branch(page-16–17)
beq x1, x2, offset 要做兩件事:
- 比較 x1 和 x2 是否相等。 用 ALU 做減法,看 Zero 輸出:Zero = 1 代表相等。
- 算目標 address。 ch02 說過 branch 是 PC-relative,而且 offset 以 2 bytes 為單位:目標 = PC + imm × 2。這裡的 PC 是 branch 自己的 address。 硬體上就是:Imm Gen sign-extend 後左移 1 bit,再用一個獨立的 adder 加上 PC。
相等時 PC 換成目標 address,叫 branch taken;不相等時 PC 照常換成 PC + 4,叫 branch not taken。
page-17 的圖有兩個標註,說的是這兩步其實都不需要真正的電路:
- “Just re-routes wires”(Shift left 1):左移的位數固定是 1,只要把第 條線接到第 個位置、最低位接 0 就好,純粹是接線;
- “Sign-bit wire replicated”(Imm Gen):sign extension 只是把 sign bit 那條線分接到高位的每一個位置。
為什麼 branch 要另外放一個 adder 算目標,不用 ALU?因為 ALU 正忙著比較兩個 register,同一個 cycle 不能做兩件事(下一頁的原則)。
page-18–20 Composing the Elements
現在把前面各類 instruction 的元件拼成一個 datapath。這一版的前提是:每條 instruction 在一個 clock cycle 內做完。拼的時候會遇到兩個問題。
問題一:同一條 instruction 要用同一個元件兩次
ld 在一個 cycle 裡要讀 memory 兩次:用 PC 讀 instruction、用算出的 address 讀資料。只放一個 memory 不行:
- Memory 的 Address 輸入是 64 條線,每條線同一時間只有一個電壓,所以同一時間只能表示一個 address、讀出一個位置。
- 改成前半 cycle 讀 instruction、後半讀資料也不行:讀出的 instruction 整個 cycle 都要用,得先存起來,但 state element 只在 clock edge 更新,cycle 中間沒地方存。
結論:一個 cycle 內每個元件只能用一次,要用兩次就得放兩份。 所以 instruction memory 與 data memory 分開,算 branch 目標也要另一個 adder(ALU 正在比較 register)。
問題二:不同 instruction 要的輸入來源不同
例如 ALU 的第二個輸入,R-format 要 Read data 2,load/store 要 offset。兩個來源不能直接接在一起(page-05),所以加 mux,由 control signal 選。
page-19 先合併 R-format 與 load/store,兩者的差別只有兩處,各加一個 mux:
| Mux | 選擇訊號 | 0 | 1 |
|---|---|---|---|
| ALU 的第二個輸入 | ALUSrc | Read data 2(R-format) | Imm Gen 的輸出(load/store 的 offset) |
| 寫回 register 的資料 | MemtoReg | ALU result(R-format) | Data memory 的 Read data(load) |
page-20 再加上 instruction fetch 與 branch:多一個 mux 選 PC 的新值(選擇訊號 PCSrc:0 是 PC + 4,1 是 branch 目標),以及算 branch 目標的 adder。這就是完整的 single-cycle datapath。
page-21–24 ALU Control and the Main Control Unit(§4.4)
Datapath 有了,接下來決定每條 instruction 要把 control signal 設成什麼。先處理 ALU,再處理其他訊號。
ALU control(page-21–23)
ALU 的 4-bit 控制輸入對應的運算:
| ALU control | 運算 |
|---|---|
| 0000 | AND |
| 0001 | OR |
| 0010 | add |
| 0110 | subtract |
不同 instruction 需要的運算:load/store 算 address 要 add;beq 比較要 subtract;R-format 則依 instruction 而定(add、sub、and、or)。
兩層解碼。 不直接從整條 instruction 算出 4-bit 的 ALU control,而是分兩層:main control unit 看 opcode 產生 2-bit 的 ALUOp,一個小的 ALU control 單元再根據 ALUOp 與 funct 欄位產生 4-bit 的 ALU control:
| ALUOp | 意思 |
|---|---|
| 00 | 做 add(ld、sd) |
| 01 | 做 subtract(beq) |
| 10 | 看 funct7 與 funct3 決定(R-format) |
分兩層的好處是 main control unit 變小,而且幾個小的 control 單元可能比一個大的更快——control 的延遲常常就在決定 clock cycle 的關鍵路徑上。
完整的對應表(課本 Figure 4.12):
| Instruction | ALUOp | 運算 | funct7 | funct3 | ALU 動作 | ALU control |
|---|---|---|---|---|---|---|
ld | 00 | load doubleword | XXXXXXX | XXX | add | 0010 |
sd | 00 | store doubleword | XXXXXXX | XXX | add | 0010 |
beq | 01 | branch if equal | XXXXXXX | XXX | subtract | 0110 |
| R-type | 10 | add | 0000000 | 000 | add | 0010 |
| R-type | 10 | sub | 0100000 | 000 | subtract | 0110 |
| R-type | 10 | and | 0000000 | 111 | AND | 0000 |
| R-type | 10 | or | 0000000 | 110 | OR | 0001 |
X 是 don’t care:ALUOp 是 00 或 01 時,ALU 該做什麼跟 funct 欄位無關,不管它們是什麼值都一樣。
投影片的筆誤page-22 的表把 R-type 的欄位寫成一個 6-bit 的 “Opcode field”(100000、100010、100100、100101),那是 MIPS 版投影片的 funct 欄位。RISC-V 是用 funct7 與 funct3 區分,正確的值如上表;page-23 下方的真值表才是 RISC-V 的版本。
page-23 下方的真值表只列出 ALU control 必須是特定值的那幾列。仔細看會發現四個 R-format instruction 之間,只有 bit 30(funct7 的第二高位,sub 是 1)與 bits 14:12(funct3)不同,所以 ALU control 單元只需要這 4 個 bit,不必看全部 10 個 funct bits。 另外 ALUOp 不會出現 11,所以表上把 00、01、10 寫成 00、X1、1X,讓邏輯更簡單。
Main control unit(page-23–24)
page-23 上方列出四種 instruction format(R、I、S、SB)。設計 control 要靠它們的幾個規律:
- Opcode 永遠在 bits 6:0;funct3(bits 14:12)與 funct7(bits 31:25)是延伸的 opcode;
- 第一個來源 register(rs1)永遠在 bits 19:15:R-format 與 branch 的第一個 operand,load/store 的 base register;
- 第二個來源 register(rs2)永遠在 bits 24:20:R-format 與 branch 的第二個 operand,store 要寫進 memory 的那個 register;
- 目的 register(rd)永遠在 bits 11:7(R-format 與 load)。
因為欄位位置固定,register file 的 Read register 1、2 與 Write register 可以直接接到 instruction 的固定 bits,不需要 mux——ch02 的 simplicity favors regularity 在這裡兌現。
除了 2-bit 的 ALUOp,datapath 上還有 6 個 1-bit 的 control signal:
| 訊號 | 是 0 時 | 是 1 時 |
|---|---|---|
| RegWrite | 不寫 register | Write register 指定的 register 寫入 Write data |
| ALUSrc | ALU 第二個輸入是 Read data 2 | ALU 第二個輸入是 Imm Gen 的 sign-extended immediate |
| PCSrc | PC ← PC + 4 | PC ← branch 目標 |
| MemRead | 不讀 | 讀出 data memory 中 Address 那格的資料,放到 Read data |
| MemWrite | 不寫 | 把 Write data 寫進 data memory 中 Address 那格 |
| MemtoReg | 寫回 register 的值來自 ALU result | 寫回 register 的值來自 data memory |
其中 PCSrc 不能只看 opcode 決定:是 beq 還要兩個 register 相等才跳。所以 control unit 輸出的是 Branch(這是 beq),再跟 ALU 的 Zero 做 AND:
其餘訊號只由 7-bit 的 opcode 決定(課本 Figure 4.18):
| Instruction | opcode | ALUSrc | MemtoReg | RegWrite | MemRead | MemWrite | Branch | ALUOp1 | ALUOp0 |
|---|---|---|---|---|---|---|---|---|---|
| R-format | 0110011 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 |
ld | 0000011 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 |
sd | 0100011 | 1 | X | 0 | 0 | 1 | 0 | 0 | 0 |
beq | 1100011 | 0 | X | 0 | 0 | 0 | 1 | 0 | 1 |
每一格都能從 datapath 推出來,例如 ld:ALU 要加 offset(ALUSrc = 1、ALUOp = 00)、要讀 memory(MemRead = 1)、讀到的值寫回 register(MemtoReg = 1、RegWrite = 1)。
sd 與 beq 的 MemtoReg 是 X:它們的 RegWrite = 0,不寫 register,MemtoReg 選哪個都沒影響。這種 don’t care 要設計者懂 datapath 才加得上去。
反過來,RegWrite、MemWrite 絕對不能是 X——寫錯會破壞 register 或 memory 的內容。
整個 control unit 就是以 opcode 為輸入、上表為輸出的真值表,可以自動轉成 logic gate。page-24 是加上 control unit 的完整 single-cycle datapath:

page-25–27 R-Type, Load, and Branch-on-Equal Instructions
這三頁在 page-24 的圖上,把一條 instruction 用到的部分畫亮、用不到的變淡。雖然整條 instruction 在一個 cycle 內完成,可以照資料流動的順序想成幾個步驟。
R-type:add x1, x2, x3(page-25)。
- Fetch instruction,PC + 4;
- 從 register file 讀 x2、x3;同時 main control unit 算出所有 control signal;
- ALU 對兩個值運算,運算種類由 ALU control 根據 funct 欄位決定;
- ALU result 經過 MemtoReg mux(選 0)寫進 x1。
Imm Gen、data memory、算 branch 目標的 adder 都有在動,但它們的輸出沒被選上,所以圖上是淡的。
Load:ld x1, offset(x2)(page-26)。
- Fetch instruction,PC + 4;
- 從 register file 讀 x2;
- ALU 把 x2 加上 Imm Gen 產生的 sign-extended offset;
- 用這個和當 address 讀 data memory;
- 讀出的資料經過 MemtoReg mux(選 1)寫進 x1。
Load 用到了 datapath 上所有的主要元件,而且是一個接一個串著用,這點在 page-28 很重要。 (Store 幾乎一樣:差別是 data memory 是寫而不是讀,寫入的資料是 Read data 2,最後不寫 register。)
Branch:beq x1, x2, offset(page-27)。
- Fetch instruction,PC + 4;
- 從 register file 讀 x1、x2;
- ALU 把兩個值相減;同時另一個 adder 算出 PC + sign-extended offset × 2;
- ALU 的 Zero 跟 Branch 做 AND,決定 PC 的新值是 PC + 4 還是 branch 目標。
page-28 Performance Issues
Single-cycle 的設計能正確運作,但很慢。
Clock cycle 被最長的路徑決定。 所有 instruction 都在一個 cycle 內完成,所以 cycle 要長到最慢的 instruction 也做得完。最慢的是 load,它的 critical path(關鍵路徑) 依序經過五個元件:
每類 instruction 不能用不同長度的 cycle。 Clock 是固定週期的訊號,不能看這條是 R-format 就把 cycle 縮短。 所以即使 R-format 用不到 data memory、本來可以早點做完,也只能跟 load 一樣花一整個長 cycle。
這違反了 make the common case fast。 Cycle 長度由最壞情況決定,再怎麼加速常見的 instruction 都沒用。 (如果要支援 floating point 或更複雜的 instruction,最慢的那條會更慢,single-cycle 就更不可行。早期 instruction set 很簡單的電腦確實用過這種做法。)
CPI 是 1 沒錯,但 clock cycle 太長,整體 performance 差。解法是下一節的 pipelining:用幾乎一樣的硬體,讓好幾條 instruction 同時在不同階段執行。
page-29–30 Pipelining Analogy / RISC-V Pipeline(§4.6)
把一條 instruction 的執行切成好幾個階段(stage),讓不同 instruction 的不同階段同時進行,像生產線一樣重疊執行。
投影片的洗衣比喻(page-29)。 洗一批衣服有四步:洗、烘、摺、收,各 30 分鐘。
- 不用 pipeline:一批四步做完(2 小時)才開始下一批,四批要 8 小時;
- 用 pipeline:第一批進烘衣機時,第二批就放進洗衣機……四台機器同時在處理不同批。第一批 2 小時後收好,之後每 30 分鐘完成一批,四批共 小時。
四批的 speedup 是 。如果一直有衣服要洗(n 批,n 很大):
極限剛好是 stage 數。四批時只有 2.3 倍,是因為開頭要等 pipeline 填滿、結尾要等它清空,這段時間不是每台機器都在工作;批數越多,這段開銷佔的比例越小。
注意單一批衣服從髒到收好仍然要 2 小時,一點都沒變快。快的是「每小時完成幾批」,也就是 throughput。
RISC-V 的五個 stage(page-30)。 RISC-V 的 instruction 剛好可以切成五步,每個 stage 做一步:
| Stage | 名稱 | 做什麼 |
|---|---|---|
| IF | Instruction fetch | 從 instruction memory 取 instruction |
| ID | Instruction decode & register read | 解碼,同時讀 register |
| EX | Execute | 做運算或算 address |
| MEM | Memory access | 存取 data memory |
| WB | Write back | 把結果寫回 register |
page-31–33 Pipeline Performance / Pipeline Speedup
例子(page-31)。 假設讀或寫 register file 各 100 ps,其他步驟(instruction memory、ALU、data memory)各 200 ps,mux、control 等延遲忽略。每類 instruction 實際用到的步驟加起來:
| Instruction | IF | Reg read | ALU | MEM | Reg write | 總時間 |
|---|---|---|---|---|---|---|
ld | 200 | 100 | 200 | 200 | 100 | 800 ps |
sd | 200 | 100 | 200 | 200 | 700 ps | |
| R-format | 200 | 100 | 200 | 100 | 600 ps | |
beq | 200 | 100 | 200 | 500 ps |
比較兩種設計(page-32)。
- Single-cycle:clock cycle 要容納最慢的
ld, ps。連續三條ld,第一條開始到第四條開始相隔 ps。 - Pipelined:每個 stage 一個 cycle,cycle 要容納最慢的 stage(200 ps), ps。register file 只要 100 ps,也得佔一整個 200 ps 的 stage。三條
ld之間只相隔 ps。

每條 instruction 的間隔從 800 ps 降到 200 ps,快了 4 倍。
圖上有一個細節:pipelined 的 Reg 方塊只畫了半格。課本假設 register file 在 cycle 的前半寫入、後半讀出,這個假設整章都會用到(page-37 的 data hazard 就靠它少等一個 cycle)。
Speedup 公式(page-33)。 如果每個 stage 花的時間都一樣(balanced):
照這個公式,五個 stage 應該快 5 倍,cycle 是 ps。但上面的例子 stage 不平均(register file 只要 100 ps),cycle 只能縮到 200 ps,所以只快 4 倍。Stage 不平均,speedup 就小於 stage 數;而且 pipeline 本身也有額外開銷(例如資料要多經過 pipeline register)。
還有,只看三條 instruction 的總時間,pipelined 是 1400 ps(第一條花 ps,之後每 200 ps 完成一條),single-cycle 是 2400 ps,還不到 4 倍。 但真實的程式有上億條 instruction。多跑 1,000,000 條時,pipelined 是 ps,single-cycle 是 ps,比值就非常接近 。
Pipelining 加快的是 throughput每條 instruction 從頭到尾的時間(latency)沒有變短——上例的 pipelined
ld從 IF 到 WB 是 ps,比 single-cycle 的 800 ps 還長。變快的是每單位時間完成的 instruction 數。程式由大量 instruction 組成,所以 throughput 才是重要的指標。
page-34 Pipelining and ISA Design
RISC-V 的 instruction set 一開始就是為 pipeline 設計的,有三個特點讓五級 pipeline 好做:
- 所有 instruction 都是 32 bits。 IF 每次固定取 4 bytes,ID 也好解碼。對比 x86 的 instruction 長度從 1 到 15 bytes 不等,取指令時連一條 instruction 有多長都要先分析。現代 x86 的做法是先把 x86 instruction 轉成類似 RISC-V 的簡單運算(micro-operation),再 pipeline 這些簡單運算(page-125)。
- Format 少且規律。 來源 register 的欄位在每種 format 都在同樣的位置,所以 ID 可以在知道是哪種 instruction 之前就先讀 register,解碼與讀 register 在同一個 stage 完成。
- 只有 load/store 會存取 memory。 Address 在第 3 個 stage(EX)算好,第 4 個 stage(MEM)存取 memory。如果像 x86 那樣運算可以直接拿 memory 的資料當 operand,EX 與 MEM 就得擴成「算 address、讀 memory、運算」三段,pipeline 變更長。
投影片的數字投影片寫 x86 是 “1- to 17-byte instructions”,課本與 x86 的規格是最長 15 bytes。
page-35–40 Hazards
理想的 pipeline 每個 cycle 都開始一條新的 instruction。但有些情況做不到:
使下一條 instruction 無法在下一個 cycle 開始執行的情況。分三種:
- Structural hazard:需要的硬體資源正被別人佔用;
- Data hazard:要等前面的 instruction 把資料讀寫完成;
- Control hazard:下一步要做什麼,取決於前面 instruction 的結果。
Structural hazard(page-36)
兩條 instruction 在同一個 cycle 要用同一個硬體。例如只有一個 memory 時:load/store 在 MEM stage 讀寫 data,同一個 cycle 另一條 instruction 正在 IF stage 取 instruction,兩者搶同一個 memory。 取指令的那條只好等一個 cycle,pipeline 裡就出現一個空格:
Stall(停頓):為了解決 hazard,讓 instruction 暫停、晚一個 cycle 再前進。被空出來、沒有做事的那個 stage 時段叫 bubble。
所以 pipelined datapath 一定要把 instruction memory 與 data memory 分開(實際上是分開的 instruction cache 與 data cache,第 5 章)。 RISC-V 本來就是為 pipeline 設計的,避開 structural hazard 相對容易。
Data hazard(page-37–39)
一條 instruction 要用前一條 instruction 的結果,而那個結果還沒算好或還沒寫回:
add x19, x0, x1 // x19 在 WB(第 5 個 stage)才寫回sub x2, x19, x3 // 卻在 ID(第 2 個 stage)就要讀 x19如果什麼都不做,sub 只能等到 add 把 x19 寫回 register file 之後才讀。page-37 的圖上 sub 的 ID 要對齊 add 的 WB(WB 前半寫、ID 後半讀,剛好讀到新值),中間多了兩個 cycle 的 bubble。
這種相依太常見了,每次都等兩三個 cycle 不可接受,也不能指望 compiler 全部排開。
解法:forwarding(page-38)。 觀察:add 的結果在 EX stage 結束時就已經算出來了,只是還沒寫進 register。直接把它從 ALU 的輸出拉一條線送到下一條 instruction 的 ALU 輸入,就不必等。
不等結果寫回 register file,直接從 pipeline 內部的暫存處把剛算好的值送給需要它的 instruction。需要在 datapath 上多加連線。
(Forwarding 是把結果「往前」送給後面的 instruction;bypassing 是指繞過 register file。)
page-38 的圖:add x1, x2, x3 在 EX 結束時算出 x1,接著 sub x4, x1, x5 的 EX 就拿這個值來用,不需要 stall。
Forwarding 不能解決所有情況:load-use data hazard(page-39)。
ld x1, 0(x2) // x1 的值在 MEM 結束時才從 memory 讀出來sub x4, x1, x5 // 下一個 cycle 的 EX 就要用 x1ld 的資料到 MEM stage 結束才有,但 sub 的 EX 跟 ld 的 MEM 在同一個 cycle,那時資料還沒讀出來。Forwarding 只能把值送給時間上更晚的 stage,不能送回過去。
所以即使有 forwarding,也得 stall 一個 cycle,讓 sub 的 EX 延到 ld 的 MEM 之後。
Load 讀出的資料,在下一條 instruction 需要時還沒準備好。
Code scheduling(page-40)
Load-use hazard 也能靠調整 instruction 順序避開:只要 load 的下一條不用它的結果就行。C code a = b + e; c = b + f;,變數都在 memory:
| 原本的順序 | 調整後 |
|---|---|
ld x1, 0(x0) | ld x1, 0(x0) |
ld x2, 8(x0) | ld x2, 8(x0) |
add x3, x1, x2 ← 用到上一條 load 的 x2,stall | ld x4, 16(x0) |
sd x3, 24(x0) | add x3, x1, x2 |
ld x4, 16(x0) | sd x3, 24(x0) |
add x5, x1, x4 ← 用到上一條 load 的 x4,stall | add x5, x1, x4 |
sd x5, 32(x0) | sd x5, 32(x0) |
| 13 cycles | 11 cycles |
把第三條 ld 往上移,兩個 add 都不再緊接在它要用的 load 後面,兩個 stall 都消失了。
其他相依(例如第一個 add 用到第一條 ld 的 x1、sd 用到 add 的結果)都隔得夠遠或能靠 forwarding 解決,不會 stall。
Cycle 數怎麼算:五級 pipeline 跑 7 條 instruction,第一條要 5 個 cycle 才做完,之後每 cycle 完成一條,共 個 cycle;原本的順序多兩個 stall,就是 13。
page-41–44 Control Hazards
問題(page-41)。 Branch 決定接下來要執行哪條 instruction。但 pipeline 每個 cycle 都要 fetch 一條新的,branch 才剛在 ID stage 解碼、還不知道要不要跳,下一個 cycle 該 fetch PC + 4 還是 branch 目標?
Fetch 進來的 instruction 不是真正該執行的那條,因為控制流程取決於還沒算完的 branch。
RISC-V pipeline 的對策是:盡早在 pipeline 裡比較 register、算出目標,多加硬體讓這些在 ID stage 完成(細節在 page-79)。
方法一:stall on branch(page-42)。 等 branch 的結果出來再 fetch 下一條。就算 branch 在 ID 就能決定,也要多等一個 cycle:page-42 的圖上 beq 之後的 or 晚了 400 ps 才 fetch(正常是 200 ps)。
要付多少代價?課本說 SPECint2006 裡 conditional branch 佔執行 instruction 的 17%。其他 instruction 的 CPI 是 1、每個 branch 多 1 個 cycle,CPI 就變成 1.17。 如果 branch 沒辦法在第 2 個 stage 就決定(較長的 pipeline 常常如此),代價更大。
方法二:branch prediction(page-43)。
不等 branch 的結果,先假設一個結果繼續 fetch;猜對就沒有損失,猜錯才把錯拿的 instruction 丟掉、從正確的地方重來。
這是 ch01 的 great idea performance via prediction。較長的 pipeline 無法早早決定 branch,stall 的代價太高,所以一定要預測。
RISC-V 五級 pipeline 最簡單的預測是 predict not taken:一律當作不跳,直接 fetch branch 的下一條,沒有延遲。真的不跳就賺到;真的跳了才 stall(丟掉拿錯的那條)。
更實際的預測(page-44)。
- Static branch prediction:根據 branch 的典型行為固定地猜。
- 往回跳的 branch(backward)猜 taken:這通常是 loop 底部跳回開頭的 branch,loop 會跑很多次;
- 往前跳的 branch(forward)猜 not taken:通常是 if 敘述。
- Dynamic branch prediction:硬體記錄每個 branch 最近的實際行為(例如上幾次有沒有跳),假設未來會延續同樣的趨勢。猜錯時 stall 重新 fetch,並更新記錄。現在的 dynamic predictor 準確率可以超過 90%(page-85)。
第三種方法:delayed branch課本在 elaboration 提到 MIPS 用的 delayed branch:branch 之後的那一條 instruction 不管跳不跳都一定執行,跳躍延後一條才生效。 Assembler 會把一條不受 branch 影響的 instruction 搬到這個位置(叫 delay slot),讓等待的那個 cycle 做有用的事。 它只適合 branch delay 很短的 pipeline,page-131 會說明它後來為什麼變成包袱。RISC-V 沒有 delayed branch。
page-45 Pipeline Summary(Big Picture)
- Pipelining 讓多條 instruction 同時執行,提高 instruction throughput;每條 instruction 的 latency 不變。
- 它會遇到三種 hazard:structural、data、control。
- Instruction set 的設計會影響 pipeline 實作的難易(page-34)。
Pipelining 有一個很大的優點:跟寫多處理器程式(第 6 章)不同,它對程式設計師是看不見的,程式不用改就能變快。
接下來四節把這些想法做成真正的硬體:§4.7 pipelined datapath 與 control、§4.8 data hazard、§4.9 control hazard、§4.10 exception。
page-46–47 RISC-V Pipelined Datapath(§4.7)
把 single-cycle datapath 切成五段(page-46)。 page-24 的 datapath 由左到右剛好對應五個 stage:instruction memory(IF)、register file 與 Imm Gen(ID)、ALU(EX)、data memory(MEM)、寫回 register file 的 mux(WB)。 Instruction 大致由左往右流動,只有兩個例外是由右往左:
| 由右往左的資料 | 從哪裡到哪裡 | 造成 |
|---|---|---|
| WB 的結果 | 寫回中間的 register file | Data hazard:後面的 instruction 可能在寫回前就讀了 |
| 下一個 PC 的選擇 | MEM stage 決定 branch 目標,送回最左邊的 PC | Control hazard:決定之前已經 fetch 了別的 instruction |
由右往左的資料不影響目前這條 instruction,只影響後面的 instruction,所以才會變成 hazard。
Pipeline register(page-47)。 只有一套 datapath,卻有五條 instruction 同時在用:每個 stage 由不同的 instruction 佔著。 例如 instruction memory 只在 IF 用一次,下一個 cycle 就換下一條 instruction 用;那上一條 instruction 讀出來的內容後面還要用,就得存起來。所以在每兩個 stage 之間放一組 register:
放在相鄰兩個 stage 之間的 register,保存前一個 stage 在上一個 cycle 產生、後面 stage 還要用的資料。以它隔開的兩個 stage 命名:IF/ID、ID/EX、EX/MEM、MEM/WB。
每個 clock edge,所有 instruction 一起往下一個 pipeline register 前進一格。Pipeline register 要寬到能存所有通過它的線:
| Pipeline register | 寬度 | 存什麼 |
|---|---|---|
| IF/ID | 96 bits | instruction(32)、PC(64) |
| ID/EX | 256 bits | PC(64)、Read data 1(64)、Read data 2(64)、sign-extended immediate(64) |
| EX/MEM | 193 bits | branch 目標(64)、Zero(1)、ALU result(64)、Read data 2(64) |
| MEM/WB | 128 bits | memory 讀出的資料(64)、ALU result(64) |
(後面加入 control、register 編號等欄位時還會再變寬。)
WB 之後沒有 pipeline register:每條 instruction 最後都會更新 register file、memory 或 PC,這些本身就是 state,後面的 instruction 直接去讀它們就好。
PC 也可以看成一個 pipeline register,它餵資料給 IF stage。但 PC 跟其他 pipeline register 不同,它是程式看得見的 architectural state:發生 exception 時 PC 的內容一定要保存,pipeline register 的內容則可以丟掉。
page-48–57 Pipeline Operation: Load and Store
page-48 介紹兩種畫 pipeline 的方式(page-58 再比較),這幾頁用的是 single-clock-cycle 的畫法:一張圖畫一個 cycle 裡整個 datapath 的狀態,把那一條 instruction 這個 stage 用到的元件塗亮。 Register 或 memory 塗右半代表讀,塗左半代表寫。
Load 走過五個 stage(page-49–53)
先看 ld,因為它五個 stage 都有事做。
- IF(page-49):用 PC 讀 instruction memory,instruction 存進 IF/ID;PC + 4 寫回 PC,也存進 IF/ID。 這時還不知道是哪種 instruction,只能把後面任何 instruction 可能用到的東西(例如 beq 要用的 PC)都往下傳。
- ID(page-50):IF/ID 裡的 instruction 提供兩個 register 編號與 immediate;讀出兩個 register、sign-extend immediate,三個值連同 PC 都存進 ID/EX。
ld其實只用到 rs1,但多讀一個 register 沒有壞處,而且讓 control 簡單。 - EX(page-51):從 ID/EX 取出 register 值與 immediate,ALU 相加得到 address,存進 EX/MEM。
- MEM(page-52):用 EX/MEM 裡的 address 讀 data memory,讀出的資料存進 MEM/WB。
- WB(page-53):從 MEM/WB 取出資料,寫進 register file。
WB 有個 bug(page-53 紅圈)。 寫回時,Write register 的編號從哪裡來?從 IF/ID 裡的 instruction——但那是此刻正在 ID stage 的另一條 instruction,比 ld 晚了三條!ld 會把資料寫進別人的目的 register。
修正(page-54)。 讓 ld 自己的 rd 編號跟著它一起走:ID 時存進 ID/EX,再傳到 EX/MEM、MEM/WB,WB 時從 MEM/WB 取出當 Write register。後三個 pipeline register 各多 5 bits(圖上的藍線)。
這揭示了 pipeline 的一個原則:後面 stage 需要的任何資訊,都必須經由 pipeline register 一路傳過去,否則下一條 instruction 進入這個 stage 時就會被蓋掉。換個角度想,每個 pipeline register 存的就是這條 instruction 剩下的 stage 還需要的那部分。
Store(page-55–57)
sd 的 IF、ID 跟 ld 一樣(這時還不知道是哪種 instruction,所有 instruction 都做同樣的事)。之後:
- EX(page-55):ALU 算出 address 存進 EX/MEM。另外,要寫進 memory 的資料(rs2 的值,在 ID 讀出、存在 ID/EX)也要搬進 EX/MEM,因為 MEM stage 才用得到。
- MEM(page-56):用 EX/MEM 裡的 address 與資料寫 data memory。
- WB(page-57):什麼都不做。但
sd還是得走過這個 stage:後面的 instruction 已經以最快速度跟在後面,sd提早離開也無法讓它們更快。
投影片的圖page-56 “MEM for Store” 的圖跟 page-52 一模一樣(標的是
ld、塗亮的是 Read data)。Store 的 MEM 應該是把 data memory 的左半(寫入)塗亮,資料來自 EX/MEM,MEM/WB 不變。
ld 與 sd 也說明了第二個原則:datapath 的每個元件只能在一個 stage 裡使用(instruction memory、register 的讀埠、ALU、data memory、register 的寫埠),否則就會有 structural hazard。
所以每個元件和控制它的訊號,都可以歸屬於某一個 stage。
page-58–60 Multi-Cycle and Single-Cycle Pipeline Diagrams
畫 pipeline 有兩種方式,以下面五條 instruction 為例:
ld x10, 40(x1)sub x11, x2, x3add x12, x3, x4ld x13, 48(x1)add x14, x5, x6Multiple-clock-cycle diagram(page-58–59)。 橫軸是時間(CC 1、CC 2……),縱軸是 instruction,每條 instruction 斜著排下去。一張圖就看得到整段程式的執行過程,適合看全貌。
- page-58 是「資源」的畫法:每格畫出那個 stage 用的硬體(IM、Reg、ALU、DM、Reg);
- page-59 是傳統畫法:每格只寫 stage 名稱。
Single-clock-cycle diagram(page-60)。 畫出某一個 cycle 整個 datapath 的狀態,在每個 stage 上方標出是哪條 instruction。它就是 multiple-clock-cycle diagram 的一個垂直切面。page-60 是 CC 5:
| IF | ID | EX | MEM | WB |
|---|---|---|---|---|
add x14, x5, x6 | ld x13, 48(x1) | add x12, x3, x4 | sub x11, x2, x3 | ld x10, 40(x1) |
Single-clock-cycle diagram 細節多、佔空間,適合看某個 cycle 裡各個訊號怎麼走;後面講 forwarding、stall 的硬體時都用它。
page-61–63 Pipelined Control
Control signal 跟 single-cycle 一樣(page-61)。 把 single-cycle 的 control 搬過來:同樣的 ALU control、同樣的 branch 邏輯、同樣的 control signal(page-23)。 PC 與 pipeline register 每個 cycle 都寫入,不需要 write 控制。
既然每個元件只屬於一個 stage,control signal 也可以依 stage 分組:
| Stage | 要設定的 control signal |
|---|---|
| IF | 無(每個 cycle 都讀 instruction memory、寫 PC) |
| ID | 無(來源 register 欄位位置固定,每次都一樣讀) |
| EX | ALUOp、ALUSrc |
| MEM | Branch、MemRead、MemWrite |
| WB | MemtoReg、RegWrite |
各 instruction 的值跟 single-cycle 的表一樣,只是依 stage 重新分組(課本 Figure 4.47):
| Instruction | EX:ALUOp1 | ALUOp0 | ALUSrc | MEM:Branch | MemRead | MemWrite | WB:RegWrite | MemtoReg |
|---|---|---|---|---|---|---|---|---|
| R-format | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
ld | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 1 |
sd | 0 | 0 | 1 | 0 | 0 | 1 | 0 | X |
beq | 0 | 1 | 0 | 1 | 0 | 0 | 0 | X |
Control signal 也跟著 instruction 走(page-62)。 問題是 control unit 在 ID 解碼時就產生所有訊號,但它們要到 EX、MEM、WB 才用。跟 page-54 的 rd 編號一樣,把它們存進 pipeline register 一路傳下去:
- ID:control unit 產生全部訊號,分成 EX、M、WB 三組存進 ID/EX;
- EX:用掉 EX 組(ALUOp、ALUSrc),把 M、WB 組傳進 EX/MEM;
- MEM:用掉 M 組(Branch、MemRead、MemWrite),把 WB 組傳進 MEM/WB;
- WB:用掉 WB 組(MemtoReg、RegWrite)。
page-63 是接好 control 的完整 pipelined datapath。除了 control 欄位,ID/EX 還要多存 ALU control 要用的 funct 欄位(Instruction[30, 14–12])與 rd(Instruction[11–7]):

到這裡為止的 pipeline 假設 instruction 之間互不相依。接下來處理真實程式裡的 hazard。
page-64–69 Data Hazards in ALU Instructions(§4.8)
哪些相依會出問題(page-64–65)
看一段有很多相依的程式,後四條都要用第一條算出的 x2:
sub x2, x1, x3 // 寫 x2and x12, x2, x5 // 第一個 operand 是 x2or x13, x6, x2 // 第二個 operand 是 x2add x14, x2, x2 // 兩個 operand 都是 x2sd x15, 100(x2) // base register 是 x2假設 sub 之前 x2 = 10、之後 x2 = −20,程式設計師希望後面四條都用 −20。page-65 畫出它們在 pipeline 裡的時間關係:

sub 在 CC 5 的 WB 才把 −20 寫進 register file(前半寫入),所以:
| Instruction | 在哪個 cycle 讀 x2(ID) | 讀到 |
|---|---|---|
and | CC 3 | 10(錯) |
or | CC 4 | 10(錯) |
add | CC 5 | −20(前半寫、後半讀,剛好讀到) |
sd | CC 6 | −20 |
圖上的相依線如果往左上(時間倒退)走,就是 hazard。
可是 −20 其實在 sub 的 EX 結束(CC 3 結束)時就算出來了,而 and 和 or 真正需要它是在它們自己的 EX 開始時(CC 4、CC 5)。只要 forwarding,就能不 stall。
值算出來後依序待在 EX/MEM(CC 4)、MEM/WB(CC 5),從這兩個 pipeline register 拉線回 ALU 的輸入即可:圖中紅線代表 and 從 EX/MEM 取值、or 從 MEM/WB 取值,都是往右下走,時間上可行。
偵測何時要 forward(page-66–67)
以下只考慮 forward 給 EX stage 的 ALU(ALU 運算或 load/store 算 address)。先定義記號:
ID/EX.RegisterRs1 表示 ID/EX 這個 pipeline register 裡存的 rs1 編號;點的左邊是 pipeline register,右邊是欄位名稱。
正在 EX 的 instruction,它的 ALU operand 編號是 ID/EX.RegisterRs1 與 ID/EX.RegisterRs2。前一條 instruction 此刻在 MEM(它的 rd 在 EX/MEM),前兩條在 WB(rd 在 MEM/WB)。所以 hazard 有四種:
| 編號 | 條件 | 從哪裡 forward |
|---|---|---|
| 1a | EX/MEM.RegisterRd = ID/EX.RegisterRs1 | EX/MEM(前一條的結果) |
| 1b | EX/MEM.RegisterRd = ID/EX.RegisterRs2 | EX/MEM |
| 2a | MEM/WB.RegisterRd = ID/EX.RegisterRs1 | MEM/WB(前兩條的結果) |
| 2b | MEM/WB.RegisterRd = ID/EX.RegisterRs2 | MEM/WB |
套到上面的程式:sub–and 是 1a(and 在 EX 時 sub 在 MEM,x2 是 and 的 rs1);sub–or 是 2b(x2 是 or 的 rs2)。
sub–add 不是 hazard,register file 在 add 的 ID 就給出正確值;sub–sd 也不是,sd 在 sub 寫完的下一個 cycle 才讀。
為了做這個比較,rs1、rs2 的編號要從 ID 經由 ID/EX 傳到 EX stage(加 forwarding 之前 ID/EX 不需要存它們)。
還要再加兩個條件(page-67)。 光比較編號會誤判:
- 前面那條 instruction 真的會寫 register。
sd、beq沒有 rd,它們 bits 11:7 那個位置是 immediate 的一部分,剛好跟某個 rs 相同時不該 forward。所以要檢查跟著它走的 RegWrite:EX/MEM.RegWrite、MEM/WB.RegWrite。 - rd 不是 x0。 x0 永遠是 0,但像
addi x0, x1, 2這種 instruction 會算出一個非 0 的結果(只是不會真的寫進 x0)。如果把它 forward 給讀 x0 的 instruction,x0 就不是 0 了。所以要求EX/MEM.RegisterRd ≠ 0、MEM/WB.RegisterRd ≠ 0。這樣 compiler 與程式設計師就不必特別避免拿 x0 當目的 register。
Forwarding 的硬體(page-68–69)
在 ALU 兩個輸入前各加一個三選一的 mux,由 forwarding unit 控制(page-68)。Forwarding unit 在 EX stage,輸入是 ID/EX 的 Rs1、Rs2,以及 EX/MEM、MEM/WB 的 Rd 與 RegWrite:
| Mux control | 來源 | 意思 |
|---|---|---|
| ForwardA = 00 | ID/EX | 第一個 ALU operand 來自 register file(沒有 hazard) |
| ForwardA = 10 | EX/MEM | 第一個 ALU operand 是前一條的 ALU result |
| ForwardA = 01 | MEM/WB | 第一個 ALU operand 來自 data memory 或更早的 ALU result |
| ForwardB = 00、10、01 | 同上 | 第二個 ALU operand,規則相同 |
合起來,EX hazard(從 EX/MEM forward)的條件是:
if (EX/MEM.RegWrite and (EX/MEM.RegisterRd ≠ 0) and (EX/MEM.RegisterRd = ID/EX.RegisterRs1)) ForwardA = 10
if (EX/MEM.RegWrite and (EX/MEM.RegisterRd ≠ 0) and (EX/MEM.RegisterRd = ID/EX.RegisterRs2)) ForwardB = 10MEM hazard(從 MEM/WB forward)把 EX/MEM 換成 MEM/WB、10 換成 01,但還要再修正一次,見下一頁。
為什麼沒有「WB hazard」?前三條 instruction 在 WB 寫 register 的同一個 cycle,目前這條正在 ID 讀 register;register file 前半寫、後半讀,讀到的就是新值。這等於 register file 內部自己做了一次 forwarding。
page-70–72 Double Data Hazard
add x1, x1, x2add x1, x1, x3add x1, x1, x4把一串數字加到同一個 register 裡就會長這樣。第三條 add 在 EX 時,第二條在 MEM(EX/MEM.RegisterRd = x1),第一條在 WB(MEM/WB.RegisterRd = x1),兩種 hazard 同時成立。
第三條要的是 x1 最新的值,也就是第二條的結果(在 EX/MEM),不是第一條的。
所以修改 MEM hazard 的條件:只有在 EX hazard 不成立時,才從 MEM/WB forward(page-71,新增的是 not(...) 那兩行):
if (MEM/WB.RegWrite and (MEM/WB.RegisterRd ≠ 0) and not(EX/MEM.RegWrite and (EX/MEM.RegisterRd ≠ 0) and (EX/MEM.RegisterRd = ID/EX.RegisterRs1)) and (MEM/WB.RegisterRd = ID/EX.RegisterRs1)) ForwardA = 01
if (MEM/WB.RegWrite and (MEM/WB.RegisterRd ≠ 0) and not(EX/MEM.RegWrite and (EX/MEM.RegisterRd ≠ 0) and (EX/MEM.RegisterRd = ID/EX.RegisterRs2)) and (MEM/WB.RegisterRd = ID/EX.RegisterRs2)) ForwardB = 01not(...) 裡面正好是 EX hazard 的條件。
page-72 是加上 forwarding unit 與兩個 forwarding mux 的 datapath(簡化畫法,省略了 sign extension 與 branch 的硬體):

注意 EX/MEM.RegisterRd 可能是 ALU instruction 的目的 register,也可能是 load 的。
ALUSrc 的 mux 放哪裡圖上省略了 load/store 需要的 immediate 輸入。ALU 的第二個輸入要在「register 值」與「immediate」之間選(ALUSrc,由 control 決定),而 register 值本身又要在三個來源之間選(ForwardB,由 forwarding unit 決定)。 最簡單的做法是 ForwardB mux 之後再接一個二選一的 mux,一邊是 ForwardB mux 的輸出,一邊是 immediate。
page-73–76 Load-Use Hazard Detection
page-39 說過 load 後面緊接著用它結果的 instruction,forwarding 救不了,一定要 stall 一個 cycle。現在要讓硬體自己偵測並插入 stall。
在 ID stage 偵測(page-73)。 要在用到結果的 instruction 進入 EX 之前攔住它,所以在它還在 ID 時檢查。這時它的 operand 編號在 IF/ID.RegisterRs1、IF/ID.RegisterRs2,而前一條 instruction 正在 EX。條件是:
if (ID/EX.MemRead and ((ID/EX.RegisterRd = IF/ID.RegisterRs1) or (ID/EX.RegisterRd = IF/ID.RegisterRs2))) stall the pipeline第一行檢查前一條是不是 load——只有 load 會讀 data memory。後兩行檢查 load 的目的 register 是否跟目前這條的任一個來源 register 相同。這個單元叫 hazard detection unit。
投影片的筆誤page-73 的條件把兩邊都寫成
IF/ID.RegisterRs1,第二個應該是IF/ID.RegisterRs2。
怎麼 stall(page-74)。 要讓 ID 的那條和 IF 的那條原地停一個 cycle,同時讓 EX 以後照常往前:
- 把 ID/EX 裡的 control 值全部設成 0。 EX、MEM、WB 看到全 0 的 control,就不寫 register 也不寫 memory,等於執行一條 nop(no operation)——這就是插進去的 bubble。(嚴格說只有 RegWrite 和 MemWrite 必須是 0,其他是 don’t care。)
- 不讓 PC 和 IF/ID 更新。 於是 ID 的那條下個 cycle 用同樣的欄位再解碼一次,IF 的那條用同樣的 PC 再 fetch 一次。
一個 cycle 之後,ld 已經在 MEM 讀出資料、存進 MEM/WB,再靠 forwarding(MEM/WB → EX)交給下一條。(沒有 forwarding 的話還要再多 stall 一個 cycle。)
page-75 的例子:ld x2, 20(x1) 後面接 and x4, x2, x5。CC 3 時 and 在 ID、ld 在 EX,偵測到 hazard。原本 and 在 CC 4 的執行時段變成 bubble,and 和 or 在 CC 4 重做 CC 3 做過的事(and 再解碼、or 再 fetch),之後所有 instruction 都晚一個 cycle:

Bubble 像水管裡的氣泡,每個 cycle 往後移一個 stage,直到從 pipeline 尾端離開。
page-76 是加上 hazard detection unit 的 datapath。它的輸入是 ID/EX.MemRead、ID/EX.RegisterRd 與 IF/ID 的 Rs1、Rs2;輸出三個訊號:PCWrite、IF/IDWrite(stall 時設 0,凍結 PC 與 IF/ID),以及控制 control 欄位前那個 mux 的訊號(stall 時選 0):

page-77 Stalls and Performance(Big Picture)
Stall 會降低 performance,但為了得到正確結果是必要的。
雖然 hazard 由硬體偵測、保證正確,compiler 還是要了解 pipeline 的結構,才能像 page-40 那樣重排 instruction、避開 stall;否則編出來的程式會有意料之外的 stall。
page-78–81 Branch Hazards(§4.9)
目前的設計要到 MEM 才決定 branch(page-78)。 在 page-63 的 datapath 裡,branch 目標在 EX 算出、Zero 在 EX 產生,兩者存進 EX/MEM,到 MEM stage 才用 Branch AND Zero 決定 PCSrc。 這時 branch 後面已經 fetch 了三條 instruction:
| Address | Instruction | branch 在 MEM 時,它在 |
|---|---|---|
| 40 | beq x1, x0, 16 | MEM |
| 44 | and x12, x2, x5 | EX |
| 48 | or x13, x6, x2 | ID |
| 52 | add x14, x2, x2 | IF |
| 72 | ld x4, 100(x7) | 跳躍目標:40 + 16 × 2 = 72 |
Predict not taken + flush。 用 page-43 的 predict not taken:照常 fetch 下去,如果 branch 真的 taken,就把 IF、ID、EX 這三條已經進來的 instruction 丟掉。
把 pipeline 裡已經開始執行、但不該執行的 instruction 丟掉,通常是因為意料之外的事件(branch taken、exception)。
丟掉的方法跟 load-use stall 一樣:把它們的 control 值設成 0。差別是 load-use stall 只要把 ID 的 control 歸零、讓它往後傳;branch 則要同時把 IF、ID、EX 三個 stage 的 instruction 都清掉。 如果 branch 一半時間不跳,而且丟掉 instruction 的成本很低,這樣就把 control hazard 的代價減半。但每次 taken 仍要損失 3 個 cycle。
Reducing branch delay(page-79)
要減少 taken 時丟掉的 instruction,就把 branch 的決定往前移到 ID stage。要提早做兩件事:
- 算目標 address。 簡單:PC 與 immediate 在 IF/ID 裡都有了,把算 branch 目標的 adder 從 EX 搬到 ID 就好。每條 instruction 都會算,只是只有 branch 用得到。
- 比較兩個 register。 在 ID 加一個專門比較相等的電路:兩個值逐 bit 做 XOR,再把所有結果 OR 起來,是 0 就代表相等。這比用 ALU 做完整的減法快得多,所以塞得進 ID stage。
代價是要多加 forwarding 與 hazard detection:branch 要比較的 register 可能還在 pipeline 裡沒寫回(page-82)。
搬到 ID 之後,taken 時只要丟掉一條:此刻正在 IF 的那條。為此加一個控制訊號 IF.Flush,把 IF/ID 裡的 instruction 欄位清成 0,它就變成 nop。
Example: branch taken(page-79–81)
36: sub x10, x4, x840: beq x1, x3, 16 // PC-relative,目標 = 40 + 16 × 2 = 7244: and x12, x2, x548: or x13, x2, x652: add x14, x4, x256: sub x15, x6, x7 ...72: ld x4, 50(x7)(16 是 instruction 裡存的 imm,以 2 bytes 為單位,所以要乘 2。)
- Clock 3(page-80):
beq在 ID,比較發現 x1 = x3,決定 taken。PC 的 mux 選 branch 目標 72,同時 IF.Flush 把正在 fetch 的and(address 44)清掉。 - Clock 4(page-81):IF fetch address 72 的
ld;ID 是被清掉的and變成的 bubble;beq在 EX、sub x10在 MEM。
Taken branch 只多了一個 bubble,而不是三個。
投影片的指令名稱page-79 的
orr x13, x2, x6是 ARM 的寫法,RISC-V 是or。
page-82–84 Data Hazards for Branches
Branch 在 ID 就要比較 register,比一般 instruction 在 EX 才用 operand 早了一個 stage,所以更容易撞上 data hazard。 新的比較電路在 ID,原本 ALU 前的 forwarding 用不上,要另外加 forwarding 送到 ID(來源仍是 EX/MEM 或 MEM/WB)。分三種情況:
1. 要比較的 register 是前兩條或前三條 ALU instruction 的結果:forwarding 就夠(page-82)。
add x1, x2, x3 // 前三條add x4, x5, x6 // 前兩條... // 前一條(無關)beq x1, x4, targetbeq 在 ID 時,add x4 在 MEM,結果已在 EX/MEM,forward 過去;add x1 在 WB,register file 前半寫、後半讀,直接讀到。
2. 前一條是 ALU instruction,或前兩條是 load:stall 1 個 cycle(page-83)。
ld x1, addr // 前兩條add x4, x5, x6 // 前一條beq x1, x4, targetbeq 第一次在 ID 時,add x4 才在 EX(結果這個 cycle 結束才出來),ld x1 在 MEM(資料這個 cycle 結束才讀出來)。都來不及,beq 在 ID 多待一個 cycle;之後兩個值分別在 MEM/WB 與 EX/MEM,forward 過去。
3. 前一條就是 load:stall 2 個 cycle(page-84)。
ld x1, addrbeq x1, x0, targetLoad 的資料要到 MEM 結束才有,beq 卻在 load 的 EX 那個 cycle 就在 ID 要用了,差兩個 cycle。
| 產生 operand 的 instruction | 一般 instruction(在 EX 用)的 stall | Branch(在 ID 用)的 stall |
|---|---|---|
| 前一條 ALU | 0 | 1 |
| 前一條 load | 1 | 2 |
| 前兩條 load | 0 | 1 |
投影片的指令寫法page-83、84 的
lw x1, addr、$x5是沿用 MIPS 版投影片的寫法(MIPS 的 register 前面加$)。意思等同這章的ld。
page-85–88 Dynamic Branch Prediction
為什麼需要(page-85)。 五級 pipeline 用 predict not taken 加上 page-79 的優化大概夠了。 但 pipeline 越深,branch 猜錯要丟掉的 cycle 越多;multiple issue(page-101)每個 cycle 處理好幾條 instruction,猜錯一次丟掉的 instruction 也更多。這時固定的預測太浪費,要在執行時根據每個 branch 的實際行為來猜。
一塊小 memory,用 branch instruction address 的低位當 index,每格存這個 branch 最近一次有沒有跳(taken / not taken)。
執行 branch 時:
- 查表,預期這次跟上次結果相同;
- 從預測的方向開始 fetch(taken 就從目標、not taken 就從下一條,即 fall-through);
- 猜錯就 flush pipeline、改從正確的地方 fetch,並把表裡的預測反過來。
表只用 address 的低位當 index,兩個 branch 可能共用同一格,查到的可能是別人的紀錄。但這不影響正確性:預測只是提示,猜錯了反正會修正。
1-bit predictor 的缺點(page-86)
outer: ...inner: ... beq ..., ..., inner // 內層 loop 的 branch ... beq ..., ..., outer內層 loop 的 branch 幾乎每次都 taken,只有最後一次 not taken。用 1 bit 記錄,每跑完一次內層 loop 會猜錯兩次:
- 內層 loop 最後一次:表裡記著 taken,實際 not taken → 猜錯,表改成 not taken;
- 下一輪外層 loop 再進內層 loop 的第一次:表裡記著 not taken,實際 taken → 又猜錯。
課本的例子:一個 branch 連續 taken 9 次、接著 not taken 1 次,這樣重複。它有 90% 的時間 taken,1-bit predictor 卻只猜對 80%(10 次錯 2 次)。
2-bit predictor(page-87)
改成連續猜錯兩次才改變預測。2 bits 記四個狀態:
stateDiagram-v2
direction LR
state "強 predict taken" as ST
state "弱 predict taken" as WT
state "弱 predict not taken" as WN
state "強 predict not taken" as SN
ST --> ST: Taken
ST --> WT: Not taken
WT --> ST: Taken
WT --> WN: Not taken
WN --> WT: Taken
WN --> SN: Not taken
SN --> WN: Taken
SN --> SN: Not taken(「強」「弱」是為了區分狀態加的,投影片上兩個都只寫 Predict taken / Predict not taken。)
它其實是一個 0 到 3 的計數器:taken 加 1、not taken 減 1(到頂或到底就停住),2、3 預測 taken,0、1 預測 not taken。
再看上面的 loop:平常停在「強 taken」;最後一次 not taken 猜錯,掉到「弱 taken」;下一輪第一次 taken,仍然預測 taken——猜對,回到「強 taken」。每輪只錯一次,準確率 90%,跟 branch taken 的比例一樣。
Branch target buffer(page-88)
Predictor 只告訴你跳不跳,目標 address 還是要算。在五級 pipeline 裡目標要到 ID 才算出來,所以就算預測 taken 而且猜對,也要損失 1 個 cycle。
存放 branch 目標 address 的 cache,在 IF stage 用 PC 查詢。
Fetch 時就拿 PC 查 BTB:查到了、而且這是一個預測 taken 的 branch,下一個 cycle 直接從目標 fetch,連那 1 個 cycle 都省了。
page-89–92 Exceptions and Interrupts(§4.10)
除了 branch,還有一類事件會改變 instruction 的執行流程,而且是「意料之外」的:
- Exception:來自 CPU 內部的意外事件,例如遇到未定義的 opcode、system call;
- Interrupt:來自外部 I/O controller 的事件。
不同 ISA 的用法不同:x86 把兩者都叫 interrupt,課本則用 exception 指所有意外的控制流程改變,只有外部造成的才叫 interrupt。RISC-V 的叫法:
| 事件 | 來源 | RISC-V 的名稱 |
|---|---|---|
| System reset | 外部 | Exception |
| I/O device request | 外部 | Interrupt |
| User program 呼叫 OS(system call) | 內部 | Exception |
| 使用未定義的 instruction | 內部 | Exception |
| Hardware malfunction | 都有可能 | 都有可能 |
處理它們而不犧牲 performance 很難:偵測 exception 常常就在決定 clock cycle 的關鍵路徑上。
怎麼處理(page-90)
這章的實作只會產生兩種 exception:未定義的 instruction,以及 hardware malfunction。發生時硬體要做三件事:
- 存下出事的(或被中斷的)instruction 的 address。 RISC-V 存在 SEPC(Supervisor Exception Program Counter)。OS 處理完後要從這裡繼續,或用它回報錯誤。
- 存下出了什麼事。 RISC-V 存在 SCAUSE(Supervisor Exception Cause Register)。它有 64 bits,但大部分沒用到,其中一個欄位記錄原因:課本假設 2 是未定義的 opcode、12 是 hardware malfunction。
- 跳到 OS 的 handler。 課本假設 handler 在 address
0000 0000 1C09 0000hex,所有 exception 都從這個入口進去。
(這個 address 是課本隨意選的。實際的 RISC-V 電腦把入口 address 放在 STVEC(Supervisor Trap Vector)register 裡,由 OS 設定。)
另一種做法:vectored interrupt(page-91)
跳去的 handler address 由 exception 的原因決定。
例如每種原因對應一個 offset,加上一個 vector table base register:
| Exception 種類 | 加到 vector table base register 的 offset |
|---|---|
| Undefined opcode | 00 0100 0000two |
| Hardware malfunction | 01 1000 0000two |
OS 從跳進來的位置就知道原因。每個入口之間只隔一小段(課本說例如 32 bytes,即 8 條 instruction),放在那裡的 instruction 要嘛直接處理掉,要嘛跳到真正的 handler。 RISC-V 不用 vectored 的方式,而是單一入口,OS 讀 SCAUSE 判斷原因。
Handler 做什麼(page-92)
- 讀 SCAUSE,跳到對應的處理程式;
- 決定要怎麼處理;
- 如果可以重新執行(restartable):修正問題,再用 SEPC 回到原程式;
- 否則:終止程式,用 SEPC、SCAUSE 等資訊回報錯誤。
例如未定義的 instruction 或硬體故障,OS 通常終止程式;I/O 要求或 system call,OS 保存程式的狀態、做完事情後再恢復它繼續執行。
page-93–98 Exceptions in a Pipeline
Exception 是另一種 control hazard(page-93)。 跟 branch taken 一樣,要把後面已進入 pipeline 的 instruction 清掉、改從新的 address fetch。以 EX stage 的 add x1, x2, x1 發生 hardware malfunction 為例:
- 不能讓 x1 被蓋掉。 如果
add繼續走到 WB 寫入 x1,x1 原本的值就沒了;而這條add自己就讀 x1,之後要重新執行它就需要原本的值; - 讓前面的 instruction 做完;
- 清掉
add和它後面的 instruction; - 設定 SEPC 與 SCAUSE;
- 跳到 handler。
這跟處理猜錯的 branch 很像,可以共用大部分硬體。
硬體(page-94)。
- IF:沿用 IF.Flush 清掉正在 fetch 的 instruction;
- ID:新增 ID.Flush,跟 hazard detection unit 的 stall 訊號 OR 起來,共用那個把 control 歸零的 mux;
- EX:新增 EX.Flush,控制新的 mux 把 EX stage 的 control 歸零(這條
add就不會在 WB 寫入 x1); - PC 的 mux 多一個輸入:
1C09 0000hex(handler 入口); - 新增 SEPC 與 SCAUSE register。

Restartable(page-95)。 很多 exception 處理完要讓出事的 instruction 照常完成。最簡單的方法是:flush 掉它,handler 執行完後回到它,重新 fetch、從頭執行一次。SEPC 存的就是它的 address,所以能找回來。
Example(page-96–98)
40hex: sub x11, x2, x444hex: and x12, x2, x548hex: or x13, x2, x64Chex: add x1, x2, x1 // 這條發生 hardware malfunction50hex: sub x15, x6, x754hex: ld x16, 100(x7)...// handler1C090000hex: sd x26, 1000(x10)1C090004hex: sd x27, 1008(x10)- Clock 6(page-97):
add在 EX 偵測到 malfunction。此時ld在 IF、sub x15在 ID、or在 MEM、and在 WB。硬體把add的 address4Chex存進 SEPC,設好 SCAUSE,把1C090000hex送進 PC,並在 cycle 結束前拉起所有 flush 訊號。 - Clock 7(page-98):IF fetch handler 的第一條
sd x26;ID、EX、MEM 都是 bubble(ld、sub x15、add被清掉);or在 WB 完成。
add 前面的 and、or 都正常做完,add 和後面的都被清掉,乾淨地切在 add 這條。
投影片的指令名稱page-96 的
orr一樣是 ARM 的寫法,應為or。
page-99–100 Multiple Exceptions / Imprecise Exceptions
同時發生好幾個 exception(page-99)。 Pipeline 裡同時有五條 instruction,一個 cycle 內可能有好幾條都出事。最簡單的做法是處理最早的那條 instruction 的 exception,把它後面的全部清掉,SCAUSE 記錄優先度最高的那個。 這樣 exception 一定對應到正確的 instruction,叫 precise exception。
I/O 要求與硬體故障不屬於某條特定的 instruction,什麼時候中斷 pipeline 比較有彈性,同樣的機制也適用。
複雜的 pipeline(一個 cycle 發出好幾條 instruction、instruction 不按順序完成)要維持 precise exception 很困難。
Imprecise exception(page-100)。 另一種做法是硬體不負責找出是哪條:
- 硬體直接停下 pipeline、存下狀態(包括 exception 的原因);
- 交給 handler 去判斷是哪條 instruction 出事、哪些要做完、哪些要清掉,有時還得用軟體「手動」把某些 instruction 做完。
例如上面的例子,偵測到 exception 的下一個 cycle 開始時 PC 是 58hex,而出事的是 4Chex。Imprecise 的處理器可能直接把 58hex 存進 SEPC,讓 OS 自己往回推。
- Precise:exception 總是對應到真正造成它的那條 instruction;
- Imprecise:exception 不一定對應到正確的 instruction。
Imprecise 讓硬體變簡單,但 handler 軟體變複雜;而對複雜的 multiple-issue、out-of-order pipeline,根本不可行。RISC-V 和現今絕大多數電腦都支援 precise exception,另一個原因是 virtual memory(第 5 章)需要它。
page-101–105 Instruction-Level Parallelism, Multiple Issue, and Speculation(§4.11)
Pipelining 讓好幾條 instruction 重疊執行,利用的是 instruction 之間的平行性:
一段程式中,instruction 之間可以同時執行的程度。
兩種提高 ILP 的方法(page-101)。
- Deeper pipeline(更深的 pipeline)。 把工作切成更多 stage,每個 stage 做的事更少,clock cycle 就能更短;同時重疊的 instruction 也更多。(要切得平均才有用,page-33。)
- Multiple issue(多發)。 把 pipeline 的硬體複製幾份,每個 cycle 開始好幾條 instruction。
每個 clock cycle 發出(開始執行)多條 instruction 的做法。
Multiple issue 讓 CPI 小於 1,所以改用 IPC(ch01)。例如 4 GHz、每 cycle 發 4 條(4-way)的處理器:峰值是每秒 160 億條 instruction(16 BIPS),CPI 最低 0.25、IPC 最高 4;如果是五級 pipeline,同時最多有 20 條 instruction 在跑。 但實際上 instruction 之間的相依會讓它達不到峰值。
Static 與 dynamic multiple issue(page-102)
Multiple issue 要解決兩件事:每個 cycle 發哪幾條 instruction(把 instruction 放進 issue slot),以及怎麼處理 data hazard 與 control hazard。依這些決定由誰做,分成兩種:
| Static multiple issue | Dynamic multiple issue | |
|---|---|---|
| 誰決定一起發哪些 | Compiler,在編譯時把 instruction 分組放進 issue slot | CPU,執行時檢查 instruction 流、每個 cycle 挑選 |
| 誰處理 hazard | Compiler 偵測並避開 | CPU 在執行時用進階技術解決;compiler 可以幫忙重排 |
(課本說兩者實際上會互相借用技術,沒有哪個是純粹的。)
Speculation(page-103–105)
找出更多 ILP 最重要的方法之一,也是 prediction 的延伸:
先「猜」一條 instruction 的某個性質(例如 branch 跳不跳),讓相依於它的其他 instruction 能盡早開始;之後檢查猜得對不對,對就完成,不對就撤銷(roll back)並改做正確的事。
Static 與 dynamic multiple issue 都會用。例子:
- 猜 branch 的結果:先執行 branch 後面的 instruction;走錯路就撤銷;
- 猜 load:例如猜一個 load 前面的 store 寫的不是同一個 address,讓 load 先做;如果那個 address 其實被 store 改了,就撤銷。
Compiler 與硬體的 speculation(page-104)。
- Compiler:重排 instruction,例如把 load 搬到 branch 前面;並加入檢查猜測、猜錯時修正的「fix-up」instruction。
- 硬體:往前看、先執行之後的 instruction,把結果暫存在 buffer 裡,確定真的需要才寫進 register 或 memory;猜錯就清掉 buffer。
Speculation 與 exception(page-105)。 如果被提前執行的 instruction 發生 exception 怎麼辦?例如:
if (p != NULL) x = *p;Compiler 把 *p 的 load 搬到檢查之前。當 p 是 NULL 時,原程式根本不會執行這個 load,提前執行卻會觸發 exception——一個原本不該發生的 exception。但如果猜測是對的(load 本來就要執行),那個 exception 就必須發生。
- Static speculation:在 ISA 裡加支援,讓這種 exception 先延後,等確定這條 instruction 真的該執行才處理;
- Dynamic speculation:把 exception 也暫存起來,等這條 instruction 確定要完成(commit)時才觸發;如果它最後被撤銷,exception 就跟著消失。
page-106–113 Static Multiple Issue
Issue packet 與 VLIW(page-106)。 Static multiple issue 的處理器,由 compiler 把同一個 cycle 要發出的 instruction 組成一組:
同一個 clock cycle 一起發出的一組 instruction。哪些能放在一起,取決於它們需要的 pipeline 資源。
處理器通常限制一個 packet 裡各類 instruction 的組合,所以可以把整個 packet 想成一條很長、裡面有好幾個運算欄位的 instruction。這就是這種做法原本的名字:
一種 ISA 風格:一條很寬的 instruction 裡包含好幾個獨立的運算,各有自己的 opcode 欄位,一起發出。
排程(page-107)。 Compiler 必須排除部分或全部的 hazard:
- 把 instruction 重排進 issue packet;
- 同一個 packet 內的 instruction 不能互相相依;
- packet 之間可能可以有相依——這依 ISA 而定,compiler 必須知道;
- 湊不滿就補 nop。
RISC-V 的 static dual issue(page-108–110)
一個簡單的雙發 RISC-V:每個 packet 兩條 instruction,一條是 ALU 或 branch,另一條是 load 或 store。
- 兩條共 64 bits,對齊 64-bit 邊界,ALU/branch 在前、load/store 在後;
- 其中一條用不到就補 nop。
| Address | 類型 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| n | ALU/branch | IF | ID | EX | MEM | WB | ||
| n + 4 | Load/store | IF | ID | EX | MEM | WB | ||
| n + 8 | ALU/branch | IF | ID | EX | MEM | WB | ||
| n + 12 | Load/store | IF | ID | EX | MEM | WB | ||
| n + 16 | ALU/branch | IF | ID | EX | MEM | WB | ||
| n + 20 | Load/store | IF | ID | EX | MEM | WB |
要多加的硬體(page-109)。 不加的話就會有 structural hazard:
- Instruction memory 一次多取 32 bits;
- Register file 多兩個讀埠、一個寫埠:一個 cycle 裡 ALU instruction 要讀兩個 register、store 也要讀兩個(base 與要存的值),ALU instruction 與 load 各寫一個;
- 多一個 adder(圖上下面那個 ALU)專門算 load/store 的 address,因為主 ALU 被 ALU instruction 佔著。
Hazard 變得更嚴重(page-110)。 同時執行的 instruction 變兩倍,hazard 的影響也跟著放大:
-
EX data hazard:單發時 ALU 的結果靠 forwarding 可以馬上給下一條用;雙發時,同一個 packet 裡的 load/store 不能用同 packet 那條 ALU instruction 的結果,因為兩者同時進 EX:
add x10, x0, x1ld x2, 0(x10) // 要用 add 的結果,不能跟 add 放在同一個 packet只能拆成兩個 packet,實際上等於 stall。
-
Load-use hazard:load 的 use latency 仍是一個 cycle,但一個 cycle 現在是兩條 instruction,所以 load 後面的兩條都不能用它的結果。
Load 與能夠使用其結果而不 stall 的 instruction 之間,隔了幾個 clock cycle。
所以要更積極的排程,這是 compiler 的責任。
排程的例子(page-111)
Loop: ld x31, 0(x20) // x31 = 陣列元素 add x31, x31, x21 // 加上 x21 裡的純量 sd x31, 0(x20) // 存回去 addi x20, x20, -8 // 指標往前移一個 doubleword blt x22, x20, Loop // x22 < x20 就繼續前三條彼此相依(ld → add → sd),後兩條也相依(addi → blt)。假設 branch 有預測、control hazard 由硬體處理,最好的排法是:
| Cycle | ALU/branch | Load/store |
|---|---|---|
| 1 | nop | ld x31, 0(x20) |
| 2 | addi x20, x20, -8 | nop |
| 3 | add x31, x31, x21 | nop |
| 4 | blt x22, x20, Loop | sd x31, 8(x20) |
add要用ld的結果,use latency 一個 cycle,所以最早在 cycle 3;addi跟誰都不衝突,塞進 cycle 2 的空位;sd要用add的結果,放 cycle 4,跟blt一組;addi被移到sd前面,x20 已經減了 8,所以sd的 offset 從 0 改成 8,才會存回原來的位置。
4 個 cycle 執行 5 條 instruction,IPC = 5 / 4 = 1.25,峰值是 2。(算 IPC 時 nop 不算有用的 instruction。)
Loop unrolling(page-112–113)
把 loop body 複製好幾份,讓不同 iteration 的 instruction 可以排在一起,找出更多 ILP;同時也減少 loop 控制(遞增、比較、跳回)的 instruction。
把上面的 loop 展開成 4 份,每份用不同的 register:
| Cycle | ALU/branch | Load/store |
|---|---|---|
| 1 | addi x20, x20, -32 | ld x28, 0(x20) |
| 2 | nop | ld x29, 24(x20) |
| 3 | add x28, x28, x21 | ld x30, 16(x20) |
| 4 | add x29, x29, x21 | ld x31, 8(x20) |
| 5 | add x30, x30, x21 | sd x28, 32(x20) |
| 6 | add x31, x31, x21 | sd x29, 24(x20) |
| 7 | nop | sd x30, 16(x20) |
| 8 | blt x22, x20, Loop | sd x31, 8(x20) |
Offset 怎麼來的:cycle 1 的 ld x28, 0(x20) 跟 addi 同時讀 register,讀到的是減之前的 x20,存取原本的 x20;之後的 instruction 看到的都是減了 32 的 x20,所以 24(x20)、16(x20)、8(x20) 分別是原本的 x20 − 8、−16、−24,sd x28, 32(x20) 存回原本的 x20。
8 個 cycle 執行 14 條 instruction(4 份 ld、add、sd,加 1 個 addi、1 個 blt),IPC = 14 / 8 = 1.75,更接近 2。代價是多用了 register、code 也變長一倍多。 跟原本比,4 個 iteration 從 20 個 cycle 降到 8 個:一部分來自少了 loop 控制 instruction,一部分來自雙發。
為什麼每份要用不同的 register? 如果 4 份都用 x31,就會一直重複 ld x31 → add x31 → sd x31。前一份的 sd x31 要讀 x31,下一份的 ld x31 要寫 x31,ld 就不能搬到 sd 前面,否則會蓋掉 sd 還沒存的值。
但這兩份之間其實沒有任何資料流動,只是剛好共用 x31 這個名字。
只因為重複使用同一個名字(通常是 register)而產生的先後順序限制,兩條 instruction 之間並沒有傳遞資料。相對地,真的有值從一條傳到另一條的叫 true dependence(data dependence)。
由 compiler 或硬體把 register 換成別的名字,消除 antidependence。
上面的 loop 就是 compiler 在展開時把 4 份分別改用 x28–x31,消除了 name dependence、保留了 true dependence,才能自由地重排。
(page-112 說 antidependence 是 “store followed by a load of the same register”,指的就是這個情況:sd 讀 x31 之後,ld 才寫 x31。)
page-114–120 Dynamic Multiple Issue
Superscalar(page-114)。
在執行時由 CPU 挑選 instruction、每個 cycle 能執行多條 instruction 的處理器,也就是 dynamic multiple issue 的處理器。
CPU 每個 cycle 決定發出 0、1、2……條,避開 structural 與 data hazard。這樣就不需要 compiler 排程(雖然排了還是有幫助),而且程式的正確性由 CPU 保證: 同一份程式碼,不管有沒有排程、在每 cycle 發幾條的處理器上,都能正確執行。有些 VLIW 設計做不到這點,換一個處理器型號就得重新編譯。
Dynamic pipeline scheduling(page-115–116)
由硬體決定 instruction 執行的順序(可以跟程式順序不同),以避開 stall。
ld x31, 20(x21)add x1, x31, x2 // 要等 ldsub x23, x23, x3 // 跟前面兩條無關andi x5, x23, 20 // 要等 subadd 要等 ld,如果 ld 遇上 cache miss(第 5 章),可能要等很多個 cycle。依序執行的 pipeline 裡,sub 也只能跟著等。
Dynamic scheduling 讓 CPU 不按順序執行(out of order):add 在等的時候,sub 先做。但結果寫回 register 時仍然依照程式順序(in order)。
page-116 是這種處理器的架構,分成三大塊:

| 部分 | 做什麼 |
|---|---|
| Instruction fetch and decode unit | 依序 fetch、解碼,把每條 instruction 送到對應 functional unit 的 reservation station(in-order issue,這樣才能追蹤相依) |
| Reservation station | 每個 functional unit 前的 buffer,存放 instruction 的運算與 operand,等還沒到的 operand(hold pending operands) |
| Functional unit | Operand 都到齊、unit 有空,就開始執行(out-of-order execute)。結果除了送給 commit unit,也直接送給正在等這個結果的 reservation station |
| Commit unit | 結果先放在它的 reorder buffer,確定安全了才依程式順序寫進 register 或 memory(in-order commit)。Reorder buffer 也能把結果提供給剛發出的 instruction 當 operand,作用類似 forwarding |
- Reservation station:functional unit 內存放運算與 operand 的 buffer;
- Reorder buffer:暫存結果,直到可以安全地寫進 register 或 memory;
- Commit unit:決定什麼時候可以把結果釋放到程式看得見的 register 與 memory。
- Out-of-order execution:一條 instruction 被擋住時,後面的 instruction 不必跟著等;
- In-order commit:結果依 instruction 被 fetch 的順序寫進程式看得見的 state。
為什麼一定要 in-order commit?這樣發生 exception 時,被更新過的 register 都屬於出事那條之前的 instruction,就能做到 precise exception;speculation 猜錯時,錯誤路徑上的結果也還沒寫進去,直接丟掉就好。現在所有 dynamically scheduled pipeline 都用 in-order commit。
Register renaming(page-117)
Reservation station 與 reorder buffer 合起來,在硬體上做到了 page-113 compiler 做的 register renaming:
- Instruction 發到 reservation station 時,如果 operand 已經在 register file 或 reorder buffer 裡,就複製一份到 reservation station。之後那個 register 就算被別的 instruction 改寫也沒關係——這條 instruction 已經有自己的副本了。
- 如果 operand 還沒算出來,reservation station 記下「是哪個 functional unit 會產生它」,等那個 unit 算出結果就直接送過來,不經過 register。(如果後面又有人寫同一個 register,這個中間值甚至不必真的寫進 register。)
於是 antidependence 消失了:instruction 等的是「某個 functional unit 的某個結果」,而不是「某個 register 名字」。
Speculation(page-118)
Dynamic scheduling 通常會搭配硬體 speculation:
-
Branch:預測 branch 方向,繼續發出預測路徑上的 instruction;在 branch 結果確定之前不 commit 它們。因為 commit 依順序,branch 一定比它後面的 instruction 先 commit,到時就知道猜得對不對。
-
Load:為了避開 load 與 cache miss 的延遲,可以:
- 預測 load 的 effective address,提早開始存取;
- 預測 load 會讀到的值,讓相依的 instruction 先用;
- 在前面還沒完成的 store 之前先做 load(猜它們存取的 address 不同);
- 前面的 store 剛好寫同一個 address 時,直接把 store 要寫的值轉給 load,不必等它寫進 memory。
猜測確認之前,load 都不 commit。
(這幾種 load speculation 投影片只列名稱,課本沒有展開實作細節。)
為什麼不讓 compiler 排就好(page-119)
- 不是所有 stall 都能預先知道。 例如 cache miss 什麼時候發生,編譯時不知道;dynamic scheduling 能在等待時繼續執行別的 instruction。
- Branch 的結果在執行時才決定。 用了 dynamic branch prediction,instruction 的實際執行順序在編譯時就無法確定,compiler 沒辦法跨 branch 排好。
- 同一個 ISA 的不同實作有不同的 latency 與 hazard。 最好的排法依 issue 寬度、pipeline 深度而變。Dynamic scheduling 把這些細節藏起來,同一個執行檔在新處理器上不必重新編譯也能受益。
Multiple issue 有用嗎(page-120,Big Picture)
有用,但沒有期望的那麼多。課本說現在的處理器每 cycle 能發 4 到 6 條,但很少程式能持續超過 2 條。原因:
- 程式裡有真正的相依,限制了 ILP;
- 有些相依很難消除,例如 pointer aliasing:兩個指標可能指向同一個位置,compiler 或硬體無法確定時,只能保守地假設有相依;
- 有些平行性很難找出來:硬體一次只能看一小段 instruction(issue 時的 window 大小有限),隔很遠的平行性看不到;
- Memory 的延遲與頻寬有限,很難讓 pipeline 一直滿載;
- Speculation 做得好可以幫忙,但猜錯會反過來降低 performance。
page-121 Power Efficiency
Dynamic scheduling 與 speculation 的複雜硬體很耗電。每項技術都把更多 transistor 換成 performance,但換得很沒效率。撞上 power wall(ch01)之後,多個較簡單的 core 可能更好:單一 core 沒那麼快,但每焦耳的 performance 更高。
| Microprocessor | Year | Clock rate | Pipeline stages | Issue width | Out-of-order / speculation | Cores/chip | Power |
|---|---|---|---|---|---|---|---|
| Intel 486 | 1989 | 25 MHz | 5 | 1 | No | 1 | 5 W |
| Intel Pentium | 1993 | 66 MHz | 5 | 2 | No | 1 | 10 W |
| Intel Pentium Pro | 1997 | 200 MHz | 10 | 3 | Yes | 1 | 29 W |
| Intel Pentium 4 Willamette | 2001 | 2000 MHz | 22 | 3 | Yes | 1 | 75 W |
| Intel Pentium 4 Prescott | 2004 | 3600 MHz | 31 | 3 | Yes | 1 | 103 W |
| Intel Core | 2006 | 3000 MHz | 14 | 4 | Yes | 2 | 75 W |
| Intel Core i7 Nehalem | 2008 | 3600 MHz | 14 | 4 | Yes | 2–4 | 87 W |
| Intel Core Westmere | 2010 | 3730 MHz | 14 | 4 | Yes | 6 | 130 W |
| Intel Core i7 Ivy Bridge | 2012 | 3400 MHz | 14 | 4 | Yes | 6 | 130 W |
| Intel Core Broadwell | 2014 | 3700 MHz | 14 | 4 | Yes | 10 | 140 W |
| Intel Core i9 Skylake | 2016 | 3100 MHz | 14 | 4 | Yes | 14 | 165 W |
| Intel Ice Lake | 2018 | 4200 MHz | 14 | 4 | Yes | 16 | 185 W |
讀法:到 Pentium 4 Prescott 為止,pipeline 越切越深(31 級)、clock rate 越拉越高;2006 年的 Core 把 pipeline 縮回 14 級、power 降下來,改成一顆晶片放多個 core。 之後 pipeline 深度、issue width、clock rate 都幾乎不變,增加的是 core 數。
page-122–126 Cortex-A53 and Core i7(§4.12)
這節看兩個真實的處理器,分別代表 post-PC 時代的兩端:手機與雲端。(投影片的節標題寫 Core i7 6700,但表與圖的資料是課本的 Core i7 920。)
| ARM Cortex-A53 | Intel Core i7 920 | |
|---|---|---|
| 市場 | Personal mobile device | Server、cloud |
| Thermal design power | 100 mW(1 core @ 1 GHz) | 130 W |
| Clock rate | 1.5 GHz | 2.66 GHz |
| Cores/chip | 4(可設定) | 4 |
| Floating point | 有 | 有 |
| Multiple issue | Dynamic | Dynamic |
| 每 cycle 最多幾條 instruction | 2 | 4 |
| Pipeline stages | 8 | 14 |
| Pipeline schedule | Static in-order | Dynamic out-of-order with speculation |
| Branch prediction | Hybrid | 2-level |
| L1 cache / core | 16–64 KiB I、16–64 KiB D | 32 KiB I、32 KiB D |
| L2 cache / core | 128–2048 KiB | 256 KiB |
| L3 cache(共用) | 依平台而定 | 2–8 MB |
Branch prediction 那一列的 hybrid、2-level 都是比 2-bit predictor 更進階的 predictor,會同時參考這個 branch 自己與最近其他 branch 的歷史;課本只在 elaboration 帶過,沒有教細節。Cache 是第 5 章的內容。
ARM Cortex-A53(page-123–124)
A53 是 dynamic multiple issue(每 cycle 2 條),但是 static in-order pipeline:instruction 依序發出、執行、commit。它被當成 IP core 授權給其他公司,跟其他電路一起做成晶片,所以 L2 cache 等規格可以設定。page-123 的 pipeline 分三段:
- Instruction fetch & predict(F1–F4):每次 fetch 兩條 instruction,盡量讓一個 13-entry 的 instruction queue 保持滿的。用 6k-bit 的 hybrid predictor 預測 conditional branch、256-entry 的 indirect predictor 預測間接跳躍(要多花一個 stage),另有 8-entry 的 return stack 預測 function return。猜錯要清空 pipeline,損失 8 個 cycle;
- Instruction decode(D1–D3):判斷兩條 instruction 之間有沒有相依(有的話只能依序執行),決定各送到哪條執行 pipeline;
- Execute(Iss、Ex1、Ex2、Wr):一條 load pipeline、一條 store pipeline、兩條整數 ALU pipeline、獨立的乘法(MAC)與除法 pipeline,之間有完整的 forwarding。Floating point 與 SIMD(NEON)再多兩個 stage(F1–F5),一條做乘除與平方根,一條做其他運算。
Performance(page-124)。 在 SPEC2006 整數 benchmark 上,理想 CPI 是 0.5(每 cycle 2 條),實際最好是 hmmer 的 0.97、中位數約 1.3、最差是 mcf 的 8.56。 每根長條分成三部分:ideal CPI、pipeline stalls、memory hierarchy stalls。中位數的情況下,60% 的 stall 來自 pipeline hazard(branch 猜錯、structural hazard、兩條 instruction 之間的相依),40% 來自 memory。 mcf 幾乎全是 memory stall。因為 A53 是 static pipeline,避開 structural hazard 與相依要靠 compiler。
Intel Core i7 920(page-125–126)
x86 instruction 很複雜,所以 i7 先把它們翻譯成類似 RISC-V 的簡單運算,叫 micro-operation(micro-op),再用 dynamically scheduled、speculative 的 pipeline 執行,每 cycle 最多執行 6 個 micro-op。 它用 reorder buffer 加上 register renaming:把 x86-64 的 16 個 architectural register 對應到更多的 physical register。猜錯時只要撤銷錯誤猜測之後的 renaming 對應,就回到正確的狀態。
處理器的組織方式,包括主要的 functional unit、它們的連接與控制。像 i7 這種設計,datapath 與 pipeline 已經無法分開談,所以改用這個詞。
一條 x86 instruction 在 i7 裡經過八個步驟(page-125 由上到下):
- Instruction fetch:用多層的 branch target buffer 與 return address stack 預測,猜錯約損失 15 個 cycle;每次從 instruction cache 取 16 bytes;
- Predecode:把 16 bytes 切成一條條 x86 instruction(長度 1–15 bytes,要掃過好幾個 byte 才知道一條多長),放進 18-entry 的 instruction queue;
- Micro-op decode:三個簡單的 decoder 處理能直接翻成一個 micro-op 的 instruction,一個複雜的 decoder(搭配 microcode)處理需要多個 micro-op 的;結果依序放進 28-entry 的 micro-op buffer;
- Loop stream detection:如果 micro-op buffer 裡有一個夠小的 loop(少於 28 條 instruction 或 256 bytes),直接從 buffer 重複發出,不必再 fetch 和 decode;
- Issue:查 register 表、做 renaming、配置 reorder buffer 的位置,從 register 或 reorder buffer 取得已有的結果,送到 reservation station;
- Dispatch:36-entry 的共用 reservation station,每 cycle 最多送 6 個 micro-op 給 6 個 functional unit;
- Execute:結果送回等待中的 reservation station,以及 register retirement unit;確定不是 speculative 之後才更新 register,reorder buffer 裡對應的位置標成完成;
- Retire:Reorder buffer 開頭的 instruction 完成後,執行它們待寫的 register 更新,從 reorder buffer 移除。
整條 pipeline 14 級,課本的圖說寫 branch 猜錯損失 17 個 cycle(跟步驟 1 的 15 個說法略有出入)。
Performance(page-126)。 理想 CPI 是 0.25(每 cycle 4 條),實際最好是 libquantum 的 0.44、中位數 0.79、最差是 mcf 的 2.67。 Out-of-order pipeline 很難區分 pipeline stall 與 memory stall,所以右圖改看 branch 預測與 speculation 的效果:
- Branch misprediction:最小、中位數、最大是 0%、2%、10%;
- Wasted work(被丟掉、沒有 commit 的 micro-op 佔所有發出的比例):1%、18%、39%。
有些 benchmark 的 wasted work 跟猜錯率很接近(gobmk、astar)。mcf 的 wasted work 卻比猜錯率高很多:它的 cache miss 很多,等 memory 的時候處理器沿著猜測的路徑發出大量 instruction,一旦其中某個 branch 猜錯,這些全部都要清掉。
page-127–129 Matrix Multiply(§4.13)
ch03 page-45 用 subword parallelism 讓 DGEMM 一次算 8 個 double。這節再加上 ILP:把 loop 展開,讓 out-of-order 的 i7 有更多 instruction 可以排。
C code(page-127)。
#include <x86intrin.h>#define UNROLL (4)
void dgemm(int n, double* A, double* B, double* C) { for (int i = 0; i < n; i += UNROLL*8) for (int j = 0; j < n; ++j) { __m512d c[UNROLL]; for (int r = 0; r < UNROLL; r++) c[r] = _mm512_load_pd(C + i + r*8 + j*n);
for (int k = 0; k < n; k++) { __m512d bb = _mm512_broadcastsd_pd(_mm_load_sd(B + j*n + k)); for (int r = 0; r < UNROLL; r++) c[r] = _mm512_fmadd_pd(_mm512_load_pd(A + n*k + r*8 + i), bb, c[r]); }
for (int r = 0; r < UNROLL; r++) _mm512_store_pd(C + i + r*8 + j*n, c[r]); }}跟 ch03 的版本比:原本的 c0 換成 4 個元素的陣列 c[],每個 intrinsic 外面包一個跑 4 次的小 for loop,外層 i 每次前進 UNROLL*8 = 32。
所以每次處理 C 同一個 column 裡相鄰的 32 個元素(4 組、每組 8 個)。不用手動複製 4 份 code,gcc 在 -O3 下會自己把這些小 loop 展開;UNROLL 寫成常數,方便試其他展開倍數。
組合語言(page-128)。
| Instruction | 作用 |
|---|---|
vmovapd (%r11), %zmm4 等 4 條 | load 4 組、每組 8 個 C 元素到 %zmm4–%zmm1 |
mov %rbx, %rcx、xor %eax, %eax | 初始化 A 的 address 與 loop counter |
vbroadcastsd (%rax,%r8,8), %zmm0 | 把一個 B 元素複製 8 份到 %zmm0——只要 1 條,4 組共用 |
add $0x8, %rax | 下一個 B 元素 |
vfmadd231pd (%rcx), %zmm0, %zmm4 等 4 條 | 4 組平行的 multiply-add |
add %r9, %rcx、cmp %r10, %rax、jne | 跳到 A 的下一個 column,沒跑完就回到 vbroadcastsd |
add $0x1, %esi | 外層 counter |
vmovapd %zmm4, (%r11) 等 4 條 | 把 4 組結果存回 C |
最內層 loop(vbroadcastsd 到 jne)從 ch03 的 6 條變成 9 條,卻做了 4 倍的工作(32 個 multiply-add,而不是 8 個):broadcast 只要一次,loop 控制的 add、cmp、jne 也只要一份。
另一個好處是 4 組計算互相獨立。ch03 的版本每次 vfmadd 都要等上一次的 c0 算完(true dependence),FMA 要好幾個 cycle,後面那條只能等;現在 4 條 vfmadd 分別累加到 4 個不同的 register,out-of-order 的 i7 可以讓它們重疊執行。
投影片的組合語言這段 assembly 是從課本 256-bit AVX 版本改成
%zmm的,有兩處沒改乾淨:
- 4 組 C 元素的 offset 寫成
0x20、0x40、0x60,那是一個%ymm(4 個 double = 32 bytes)的間距。一個%zmm是 8 個 double = 64 bytes,應該是0x40、0x80、0xc0;- 跟 ch03 一樣,
add %r9, %rcx的註解應為 “%rcx = %rcx + %r9”,jne的註解多了一個 not。
Performance(page-129)。 32 × 32 的矩陣:
| 版本 | GFLOPS |
|---|---|
| 未優化 | 1.7 |
| AVX(subword parallelism) | 6.4 |
| AVX + unroll(再加 ILP) | 14.6 |
光是展開就讓 performance 多了一倍以上(6.4 → 14.6),跟未優化版相比總共快 8.59 倍。 (這組數字是課本用 256-bit AVX 在 2.6 GHz 的 Core i7 上量的,跟 ch03 一樣;投影片的 code 是 AVX-512 版本。)
課本補充:assembly 裡重複使用同一個 register 也不會造成 stall,因為 i7 的 pipeline 會做 register renaming(page-117)。
page-130–131 Fallacies and Pitfalls(§4.15)
Fallacy:pipelining 很簡單(page-130)基本概念很簡單,魔鬼藏在細節裡,例如偵測 data hazard。課本作者說他們的進階教科書第一版就有一個 pipeline 的 bug,經過一百多人審稿、18 所大學試教都沒發現,直到有人真的照書做出那台電腦才找到。 像 Core i7 這樣的 pipeline,用 Verilog 描述會有幾十萬行。
Fallacy:pipelining 的想法跟製程技術無關(page-130)那為什麼不是一直都用 pipeline?因為更多 transistor 才讓更進階的技術變得可行,最好的 pipeline 設計會隨技術改變:
- Transistor 數量與速度讓五級 pipeline 最划算的年代,delayed branch(page-44)是解決 control hazard 的簡單方法;有了更長的 pipeline、superscalar 與 dynamic branch prediction 之後,它就多餘了;
- 1990 年代初,dynamic pipeline scheduling 太耗資源;transistor 預算隨 Moore’s Law 一直加倍、logic 變得比 memory 快很多之後,多個 functional unit 與 dynamic pipeline 才變得合理;
- 現在 power 成了限制,設計又轉向不那麼激進、更有效率的方向(page-121)。
所以跟 pipeline 有關的 ISA 設計要考慮技術趨勢。投影片舉的例子是 predicated instruction:根據一個條件決定這條 instruction 要不要生效,用來取代 branch。課本只在 elaboration 提到 ARMv8 的 conditional select(
CSEL):依條件把兩個來源 register 之一寫進目的 register,程式就能少一些 branch。
Pitfall:沒考慮 instruction set 的設計,會讓 pipeline 難做(page-131)很多 pipeline 的困難來自 instruction set 本身:
- 複雜的 instruction set(VAX、IA-32):instruction 長度與執行時間差很多,pipeline 的 stage 不平均,hazard 偵測也很複雜。解法是先翻譯成 micro-op 再 pipeline(DEC VAX 8500 最早這樣做,就是現在 i7 的做法),但翻譯與維持 micro-op 和原 instruction 的對應仍有成本;
- 複雜的 addressing mode:有些 addressing mode 會順便更新 register(例如存取完自動把 base register 加 1),一條 instruction 寫兩個 register,hazard 偵測變複雜;有些要多次存取 memory(例如 address 本身要先從 memory 讀出來,memory indirection),pipeline 很難順暢地流動;
- Delayed branch:delay slot 的長度寫死在 ISA 裡,原本為五級 pipeline 設計成 1 條;但進階的 pipeline branch delay 長得多,1 個 slot 遠遠不夠,ISA 卻得永遠維持這個語意。
課本的例子:同樣的製程下,ISA 較新的 DEC Alpha 比 DEC NVAX 快兩倍以上;另一個研究比較 MIPS M/2000 與 DEC VAX 8700,MIPS 執行的 instruction 比較多,但 VAX 平均花 2.7 倍的 clock cycle,所以 MIPS 比較快。
page-132 Concluding Remarks(§4.16)
- ISA 影響 datapath 與 control 的設計,datapath 與 control 也反過來影響 ISA 的設計。 這章的 datapath 是從 RISC-V 的 instruction 一步步推出來的;而 RISC-V 固定長度、規律的 format,是為了讓 pipeline 好做。
- Pipelining 用平行性提高 instruction throughput:每秒完成更多 instruction,但每條 instruction 的 latency 沒有變短。
- Hazard 有三種:structural、data、control(整理在下表)。
- Multiple issue 與 dynamic scheduling 進一步挖掘 ILP,但程式裡的相依限制了能達到的平行度,而複雜的硬體讓處理器撞上 power wall。
| Hazard | 原因 | 這章的解法 |
|---|---|---|
| Structural | 兩條 instruction 搶同一個硬體 | 硬體分開(instruction / data memory 分開) |
| Data | 要用的值還沒算好或還沒寫回 | Forwarding;load-use 時 stall 1 cycle;compiler 重排 |
| Control | 還不知道 branch 跳不跳 | 把 branch 移到 ID、branch prediction、flush 猜錯的 instruction |
Pipelining 縮短 clock cycle,multiple issue 降低 CPI,兩者都在挖 ILP。1990 年代中期起,更長的 pipeline、multiple issue 與 dynamic scheduling 撐住了處理器 performance 每年約 60% 的成長,同時保留了循序的程式設計模型; 但最終撞上 power wall,業界只好轉向多處理器(第 6 章),在更粗的層級上找平行性。而依照 Amdahl’s Law,處理器變快之後,系統的另一部分會成為瓶頸——那就是第 5 章的主題:memory hierarchy。