# ISA進階操作 ## Immediate 在 assembly 語言中,Immediate 是指出現在代碼中的數字常數。 例: `f = g + 10` c語言 `addi $s0, $s1, 10` assembly 語言 addi 指令的語法與 add 指令相似,唯一的區別是最後的參數是一個數字而不是一個 register。 MIPS assembly 語言中沒有專門的“減去 Immediate ”的指令,可以使用一個負數的 Immediate 來實現 例: `f = g - 1` c語言 `addi $s2, $s1, -1` assembly 語言 ## MIPS Instruction Format MIPS Instruction Format 將每條指令分為 32 bits,其中定義了三種基本的Instruction Format,以滿足不同指令的需求: 1. R-format: 用於操作 register 的指令。 * 例如:`add $t0, $s1, $s2` 就是一條 R-format 指令。 2. I-format: 用於 immediate 和一些載入/存儲指令(因為 offset 算 immediate)。 * 例如:`addi $t0, $s1, 10` 就是一條 I-format 指令。 3. J-format(J型格式): 用於跳轉指令。 * 例如:`j Label` 就是一條 J-format 指令。 ### R-Format ![image](https://hackmd.io/_uploads/Hk1PLL0tT.png) 指令的格式主要包含以下字段: * opcode(操作碼): 指定指令類型。所有 R-Format 指令的 opcode 都設為 0。 * funct(功能碼): 與 opcode 結合以完全指定指令的操作。 * rs(源 register ): 通常用來指定包含第一個 operand 的 register 。 * rt(目標 register ): 通常用來指定包含第二個 operand 的 register 。 * rd(目的 register ): 通常用來指定接收計算結果的 register 。 R-Format 指令中的 register 字段有一些注意事項: * 每個 register 字段正好為 5 bits, 這意味著它可以指定範圍在 0 到 31 的任何無符號整數。這種結構確保了足夠的 bit 以指定全部的 register 。 * 它包含了 bits 移位指令將要左移或右移的 bit 數。由於一個 32 位的字左移或右移超過 31 位是無意義的,因此這個字段僅使用 5 bits。 例: `add $t0, $s1, $s2` ![image](https://hackmd.io/_uploads/B1en5ICY6.png) 二進制表示為:000000 10001 10010 01000 00000 100000 ### I-format ![image](https://hackmd.io/_uploads/ryTl6I0Ka.png) * opcode: addi 操作碼對應到 8。 * rs(源 register ): $22 對應到 rs 欄位。 * rt(目標 register ): $21 對應到 rt 欄位。 * immediate: -50 被視為有符號整數,轉換為二進制。 ![image](https://hackmd.io/_uploads/Hk34pLRFa.png) ## Logical Operations ![image](https://hackmd.io/_uploads/rkkpJvAtp.png) ### Shift Left Logical (sll) 將 rt 中的 bits 向左移動 `shamt` 位,移動的空白位置用 0 填充。 相當於將 rt 乘以 2 的 `shamt` 次方。 例: shift left by 8 bits `sll $t2, $s0, 8` * 操作名稱:sll * 接收值的 register:$t2 * 第一個operand(register):$s0 * shift amount(常數):8 ![image](https://hackmd.io/_uploads/rJHyKDAtT.png) 這樣的操作相當於將原始數乘以 2 的 8 次方(256) ### Shift Right Logical (srl) 操作:將 rt 中的 bits 向右移動 shamt 位,移動的空白位置用 0 填充。 應用:相當於將 rt 除以 2 的 shamt 次方。 例: shift right by 8 bits `srl $t2, $s0, 8` * 操作名稱:sll * 接收值的 register:$t2 * 第一個operand(register):$s0 * shift amount(常數):8 ![image](https://hackmd.io/_uploads/rJrQYDRKp.png) 這樣的操作相當於將原始數除以 2 的 8 次方(256) ### shift right arithmetic(sra) 與srl相似,不同的是空出的 bits 由符號位填充。如果是正數,就用 0 填充,如果是負數,就用 1 填充。 ![image](https://hackmd.io/_uploads/ByTaFPRK6.png) ![image](https://hackmd.io/_uploads/SkYCFPRK6.png) ### AND Operations 這個操作將 $t1 和 $t2 register 中的對應 bits 進行 AND 運算 `and $t0, $t1, $t2` ![image](https://hackmd.io/_uploads/Hk0yhwRKT.png) ### OR Operations 這個操作將 $t1 和 $t2 register 中的對應 bits 進行 OR 運算 `OR $t0, $t1, $t2` ![image](https://hackmd.io/_uploads/Bk9-3PRY6.png) ### NOT Operations 這個操作將 $t1 和 $zero register 中的對應 bit 進行 NOR 運算,結果存儲在 $t0 register 中。 * a NOR b == NOT ( a OR b ) `nor $t0, $t1, $zero` ![image](https://hackmd.io/_uploads/B1sBJOAKp.png) $zero register 始終包含值為 0 的常數 將一個 register 的值與零進行 NOR 運算時,實際上就是對 register 的每個 bit 進行 NOT 操作。