Kyle Hsieh (謝阿Sa)
    • 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 New
    • 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 Note Insights Versions and GitHub Sync 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # More RISC, RISC-V functions > Reference [Computer Architecture (Fall 2021) Week4](/s-RaYQGiRuCeUEA0cZtTAw) ## Pseudo instructions - What do we need pseudo instructions? 1. consideration of different architecture supports - good for *retargetting* to several hardwares 2. for human readablility - Examples - `mv` dst,reg1; # translates into addi dst,reg1,0 - Load Immediate (`li`) - Loads 32-bit immediate into `dst` ``` li dst, imm # utilized addi, lui ``` - Load Address (`la`) ``` la dst, label # auipc dst, <offset to la ``` - No Operation (nop) - For pipeline stall - Full list of RISC-V supported pseudo instructions is on the [greensheet](https://github.com/jameslzhu/riscv-card/blob/master/riscv-card.pdf) ## C to RISC-V Practice - Example: "Fast String Copy", which illustrates how to translate: - dereference of pointers - single `while` loop - Exit condition is an equality test C code: ```c= /* Copy string from p to q */ char *p, *q; while((*q++ = *p++) != ‘\0’) ; ``` Start with code skeleton: ``` # copy String p to q # p→s0, q→s1 (char* pointers) Loop: # t0 = *p # *q = t0 # p = p + 1 # q = q + 1 # if *p==0, go to Exit j Loop # go to Loop Exit: ``` Finished code: ``` # copy String p to q # p→s0, q→s1 (char* pointers) Loop: lb t0,0(s0) # t0 = *p sb t0,0(s1) # *q = $t0 addi s0,s0,1 # p = p + 1 addi s1,s1,1 # q = q + 1 beq t0,x0,Exit # if *p==0, go to Exit j Loop # go to Loop Exit: # N chars in p => N*6 instructions ``` :information_source: What if`lb` sign extends? --> Not a problem Because the data type of the pointers are pointed here which is `char ` , only one byte. The `sb` instruction only writes a single byte, so the sign extension is ignored. We can shorten the code by using `bne` on loop condition ``` # copy String p to q # p→s0, q→s1 (char* pointers) Loop: lb t0,0(s0) # t0 = *p sb t0,0(s1) # *q = $t0 addi s0,s0,1 # p = p + 1 addi s1,s1,1 # q = q + 1 bnq t0,x0,Loop # change to if *p!=0, go to Loop Exit: # N chars in p => N*6 instructions ## RISC-V functions ### 1. Put parameters in a place where function can access them - a0-a7 for function arguments, a0-a1 for return values - sp: "stack pointer" - Holds the current memory address of the "bottom" of the stack ### 2. Transfer control to function - by `jump` instructions ### 3. Acquire (local) storage resources needed for function :notes: ~~unlike Stack pointer(sp) in *Intel* architecture is hold the address of the **top** of the stack, sp in RISC-V arch~~, holds the address of the ==bottom== of the stack. #### difference with Intel arch.? - on Intel side > Reference other course in UCB[^first], which is related to 61C but introducing x86 - on RISC-V side > Further reference Cornel Univ. CS 3240[^second] the calling convention is nearly the same; the differences are name of registers and instructions, ==to be worth mentioning, RISC systems often omit the Frame pointer==: > **RISC systems often omit this register** because it is not necessary with the RISC stack design. For example, in RISC-V, `FP` is sometimes renamed `s0` and used as a general-purpose register[^first]. #### The usage of frame pointer: - On **7. Execute the function.** Since frame pointer is always pointing at the top of the stack frame, it can be used as a point of reference to find other variables on the stack (e.g. in x86, the arguments will be located starting at the address stored in ebp, plus 8) ![](https://i.imgur.com/dQB6TZX.png) - On **8. Move esp up.** Once the function is ready to return, we increment esp to point to the top of the stack frame (ebp). ``` foo: ... # Step 8. Move esp up to ebp mov %ebp, %esp # AT&T: src, dst ... ``` - Why FP *not* necessary with the RISC stack design? - Recall: Registers way faster than memory, so use them whenever possible - a0–a7: eight argument registers to pass parameters - SP could be restored by **adding framesize directly** ![](https://hackmd.io/_uploads/H1rKlFyTq.png) ### 4. Perform desired task of the function #### Which registers can we use? - Problem: how does the function know which registers are safe to use? - it's defined in ABI, is a matter of caller and callee relationship - the high-level program languages can be ran on the the same hardwares if they follow the same ABI - Use `Stack Frames` to isolate register use of function calls - Calling Convention on Greencard ![](https://i.imgur.com/mgl9RoN.png) #### Stack Before, During, After Call ![](https://i.imgur.com/tZ0I7t2.png) #### Examples - Using Saved Registers on **CalleE** ![](https://i.imgur.com/htVzFLD.png) - Using Volatile Registers on **CalleR** ![](https://i.imgur.com/xiKA3LK.png) #### Choosing Your Registers - Minimize register footprint - Optimize to reduce number of registers you need to save by choosing which registers to use in a function - Only save when you absolutely have to - Function does NOT call another function - Use only **t0-t6** and there is nothing to save! - Function calls other function(s) - **Values you need throughout go in s0-s11**, others go in t0-t6 - At each function call, check number **arguments and return values** for *whether you or not you need to save* ### 5. Put result value in a place where calling code can access it and restore any registers you used; release local storage ### 6. Return control to point of origin, since a function can be called from several points in a program - like step2, by `jump` instructions [^first]: [x86 function calls in UCB CS161 Computer Security](https://textbook.cs161.org/memory-safety/x86.html#28-x86-function-calls) [^second]: [RISC-V Calling Convention Cornel Univ. CS 3410: Computer System Organization and Programming, Spring 2019](https://www.cs.cornell.edu/courses/cs3410/2019sp/schedule/slides/10-calling-notes.pdf)

    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