Jason Lin (SmallHanley)
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Lab1: RV32I Simulator ###### tags: `Computer Architecture 2020` The lab is to understand how instructions work along with Ripes simulator. It starts from the small program, Factorial number, with recursion, and go on to study each stage of 5-stage-pipeline and hazards. ## Factorial Number The Factorial number sequence is a recursive method to define: $\ \ \ \ \ \ F_0=0,\ F_1=1$ and $\ \ \ \ \ \ F_n=F_{n-1} + F_{n-2}$ for $n>1$ ## Inplement in C code ```cpp= #include<stdio.h> int fib(int n){ if(n <= 1){ return n; } else{ return fib(n - 1) + fib(n - 2); } } int main(void){ int n = 12; printf("Fibonacci(%d) = %d", n, fib(n)); return 0; } ``` ## RISC-V asm with recursion ```clike= .data argument: .word 12 str1: .string "Fibonacci(" str2: .string ") = " .text main: # initial value lw a0, argument # n = 12 li s0, 1 # for comparison with n (n <= 1) jal ra, fib # call fib(12) mv a1, a0 # a1 : final falue lw a0, argument # a0 : argument jal ra, printResult # print result j exit # go to exit fib: ble a0, s0, L1 # if(n <= 1) addi sp, sp, -12 # push the stack sw ra, 8(sp) # store return address sw a0, 4(sp) # store argument n addi a0, a0, -1 # argument = n - 1 jal ra, fib # call fib(n - 1) sw a0, 0(sp) # store return value of fib(n - 1) lw a0, 4(sp) # load argument n addi a0, a0, -2 # argument = n - 2 jal ra, fib # call fib(n - 2) lw t0, 0(sp) # load return value of fib(n - 1) add a0, a0, t0 # fib(n - 1) + fib(n - 2) lw ra, 8(sp) # load return address addi sp, sp, 12 # pop the stack ret # return L1: ret # return printResult: # Fibonacci(12) = 89 mv t0, a0 mv t1, a1 la a0, str1 li a7, 4 ecall # print string str1 mv a0, t0 li a7, 1 ecall # print int argument n la a0, str2 li a7, 4 ecall # print string str2 mv a0, t1 li a7, 1 ecall # print int result ret exit: li a7, 12 ecall # exit ``` After running the code, it will print `Fibonacci(10) = 55` on the console, with argument = 10. ## Ripes simulator ### Pipeline The pipeline architecture consists of 5 stages (IF, ID, EX, MEM, WB) in the simulator, the following is the function of each stage: * **IF (Instruction fetch)** In IF stage, we can get PC (program counter), which comes from either the last instruction addr. (PC) plus 4 or Arithmetic Logic Unit (ALU) if there is a branch instr. in EX stage like beq jal ,and so on. Then, instruction will be fetched depending on the PC from the instr. memory. <br> ![](https://i.imgur.com/BY3xrrr.png) We can see PC = 0x04, and fetches 0x0052503 in instr. memory, which means `lw x10 0(x10)` in asm. After fetching instr. PC will plus 4 = 0x08. <br> ![](https://i.imgur.com/o4sg4h9.png) If instr. in the EX stage is branch instr., PC will come from the result of ALU, and change the MUX (multiplexer) input. * **ID (Instruction decode)** In ID stage, the decoder will decode the instruction, determine the input of each MUX, and then the register file will be read to prepare for the next stage. * **EX (Execute)** EX stage is where the computation occurs. The stage consists of ALU and Branch. * The ALU is responsible for computing the math operation, the boolean operation, and even the PC of the branch instruction. * The Branch will use data from register to determine if the Branch taken or not. ![](https://i.imgur.com/fvHVFc1.png) The `addi` instruction, the two operand 0x000002d0 and 0x00000000 come from Reg1 and Imm data, respectively, and get the result 0x000002d0. <br> ![](https://i.imgur.com/tAoKvX3.png) This is `bge` instruction. Because Reg1 is greater than Reg2, set Branch taken = true, and change the PC. * **MEM (Memory access)** In MEM stage, we can access memory through instruction such as sw, lw, etc. ![](https://i.imgur.com/HX1fe82.png) This is `sw` instruction, it will set MemWrite = true and then store 0xc , into addr. 0x7fffffe8. <br> ![](https://i.imgur.com/W0Gub2F.png) This is `lw` instruction, it will get value from 0x7fffff98 and then write the value back to the register. * **WB (Writeback)** After the instruction `lw x10 0(x2)` mentioned in the above picture, the data 0x00000001 will write back to the register x10(t0). ![](https://i.imgur.com/8dBpjz9.png) ### Pipeline Hazards & Solutions Pipeline hazards are the problems that it cannot execute the next instruction in the next cycle. There are three kinds of hazards, data hazards, structural hazards, and control hazards. Here, I will use the simultor to show about data hazards and control hazards and how the simulator solves the problems. * **Data Hazard** Data hazards typically result from data dependency. In this architecture, RAW (Read after Write) is the main reason that causes data hazards. The following are two examples. * `addi x2 x2 -16` `sw x1 8(x2)` In this case, CPU will write data back to x2 in WB stage, but x2 is needed in EX stage of the next instruction. So, it is too late to wait for data write back to register. To solve the problem, the simulator use forwarding from EX/MEM directly to ALU. ![](https://i.imgur.com/FIsqW39.png) The yellow line is the path of forwarding. ![](https://i.imgur.com/RBXFb5S.png) We can see that x2 in the register file hasn't been changed, it still maintains 0x7ffffff0 because the data hasn't written back yet. But, the Op1 of ALU has already changed to 0x7fffffe0 * **Control Hazard** Control hazards happen when there is a branch instruction like beq, bne, etc. The next instruction can be determined only after the EX stage of the branch instruction. To solve the problem, the simulator use a static prediction that always predicts no branch happens. By this way, the pipeline can successfully do without any stall if the prefiction is correct. However, it sometimes make an incorrect prediction like the following two picture. ![](https://i.imgur.com/TjLmxvA.png) ![](https://i.imgur.com/jQHwDiD.png) In the EX stage, if the branch happens, CPU will set Branch taken signaal into true, and the next two instructions it predicts should be discarded. So if prediction is not correct, the pipeline still has to undergo 2-cycle `nop`. ## 問題 ![](https://i.imgur.com/kHqvqW8.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully