羅紹豪
    • 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` ## Fibonacci number ([Leetcode509](https://leetcode.com/problems/fibonacci-number/)) The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. ## Implementation You can find the source code [here](https://github.com/airpodspro/computr-architecture) ### C code ```clike= #include <stdio.h> void F(int); int main(){ num = 5; fib = F(num); printf("the number of F("%d") ="%d, num, fib); } F(int n){ fibpre = 0, fib = 1, temp; for(int i = 2; i <= num; i++){ temp = fib; fib += fibpre; fibpre = temp; } return fib; } ``` #### **Code explain:** Give a number of n in function F(n), at first we define the initial number of fibpre and fib as F(0) and F(1) in the function, then we start calculating the F(n) we wanted by the loop, it will first keep the original number of *fib* in the `temp` ( Ex : keep F(1) in `temp` ), then calculate the new `fib` by using `fib` += `fibpre` ( Ex : `fib` = F(0) + F(1) ), its also the define of calculating Fibonacci number ( sum of the two preceding ones ), so now we get the number of F(2) in `fib`, then we replace the value of `fibpre` as the original `fib` we kept in `temp` ( know as F(1) ), we now get the F(2) in `fib` and the F(1) in `fibpre` for the next loop of calculating F(3). ### Assembly code We can change the number of n in F(n) by replacing the number behind num, in the latter case we take 5 as an example ```cpp= .data num: .word 5 .text main: la s0, num # s0 = num address lw s0, 0(s0) # load in the number at the address li s1, 1 # load immediate 1 in s1 blt s0, s1, end # see if the answer is fib[0] or fib[1] sub s1, s0, s1 # get number of doing loop li t0, 0 # set initiall prefib li s0, 1 # set initial fib loop: mv t1, s0 # keep original fib add s0, s0, t0 # calculate next fib mv t0, t1 # replace prefib by original fib addi s1, s1, -1 # count how many times left bgt s1, zero, loop # if s1 > 0 go back loop end: mv a0, s0 # print result li a7, 1 ecall exit: ``` ## Analysis We run the code by using [Ripes](https://github.com/mortbopet/Ripes) simulator ### Pseudo instruction When we write the assembly code in Ripes, it will automatically generate the pseudo instuctions ``` 00000000 <main>: 0: 10000417 auipc x8 0x10000 4: 00040413 addi x8 x8 0 8: 00042403 lw x8 0 x8 c: 00100493 addi x9 x0 1 10: 02944263 blt x8 x9 36 <end> 14: 409404b3 sub x9 x8 x9 18: 00000293 addi x5 x0 0 1c: 00100413 addi x8 x0 1 00000020 <loop>: 20: 00040313 addi x6 x8 0 24: 00540433 add x8 x8 x5 28: 00030293 addi x5 x6 0 2c: fff48493 addi x9 x9 -1 30: fe9048e3 blt x0 x9 -16 <loop> 00000034 <end>: 34: 00040513 addi x10 x8 0 38: 00100893 addi x17 x0 1 3c: 00000073 ecall ``` ### 5-stage RISC-V processor ![](https://i.imgur.com/pwyeqXH.jpg) There are 5 stages in RISC-V processor * Instruction fetch(IF) * Instruction decode(ID) * Execute(EX) * Memory access(MEM) * Register write back(WB) each stages are seperated by pipeline register. We take instruction `lw s0, 0(s0)` as an example to explain what will it actually do in these 5 stages. #### **1. Instruction fetch (IF)** In this stage, it will fetch the machine code of instruction in the insruction memory, also plus 4 to get the next pc ![](https://i.imgur.com/ZDK6FIk.jpg) * The address of the insruction is `0x0000002c` * We input the address and get `instr` as `0xfff48493` * We plus 4 to the address then we got the address of the next instruction as`0x00000030` #### **2. Instruction decode (ID)** In this stage, it will decode the machine code, and also find out the value of in need register ![](https://i.imgur.com/LCf2fjI.jpg) * Instruction `0xfff48493` is decoded to 4 parts * `opcode` = `ADDI` * `Wr idx` = `0x09` * `R1 idx` = `0x09` * `R2 idx` = `0x1f` * `0x0000002c` and `0x00000030` are send to this stage to make sure there is no flush to this stage, if it occures, then we will need them. In this case, they are not using. * `Reg 1 ` and `Reg 2` is the value of `R1 idx` and `R2 idx`, `Reg 1` = `0x0000004`, `Reg 2` = `0x00000000` * There is also an immediate -1 in the instruction, so we get `0xffffffff` by the `imm.` * #### **3. Execution (EX)** In this stage, we will execute things using ALU and also decide if it will jump when it is a branch instruction ![](https://i.imgur.com/cREaImJ.jpg) * The ID/EX pipeline register provides `0x00000004`, `0x00000000`, and `0xffffffff` for ALU * We will chose the two inputs of ALU `Op1` and `Op2`, in this case `Op1` = `0x00000004`,`Op2` = `0xffffffff` * ALU will do math to calculae `Res`, `Res` = `0x00000004` + `0xffffffff` = `0x00000003`. * This instruction isn't a branch instruction, so we don't use Branch #### **4. Memory access (MEM)** In this stage we will access the memory if it need the value in data memory. ![](https://i.imgur.com/m1Xrntw.jpg) We don't need the value in data memory in this instruction, but it will still pass MEM stage. There is another example that will access data memory ![](https://i.imgur.com/Pl7GxnA.jpg) This is the instruction `lw x8 0 x8` in MEM stage, it gets the value`0x00000005` by input address `0x10000000` #### **5. Register write back (WB)** In this stage we will write the register value if needed ![](https://i.imgur.com/OXF72xL.jpg) * We pass the value in `Res` to `Wr data`, `0x09` to `Wr idx` * `Wr data` = `0x00000003`, `Wr idx` = `0x09` * We write `0x00000003` back to `0x09` as an update of looping number After all these stage are done, the register is updated like this: ![](https://i.imgur.com/sukHoEK.jpg) After executing the whole program, the registers are updated like this: ![](https://i.imgur.com/oH2Ys5c.jpg) ![](https://i.imgur.com/9WdlpqF.jpg) The result is in console ![](https://i.imgur.com/Jz8nVkV.jpg) This is the pipeline diagram of the code ![](https://i.imgur.com/s9gKjXr.jpg) We can see there are few places with unfinish instructions ![](https://i.imgur.com/Y9EAQ4K.jpg) it is because there is a branch instruction in front of them, when the branch decided to jump, it will flush the instructions which execute after it. ## Reference [Classic RISC pipeline - Wikipedia](https://en.wikipedia.org/wiki/Classic_RISC_pipeline)

    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