Iann2000
    • 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
      • Invitee
    • 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
    • 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 Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync 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
Invitee
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
# Assignment2: RISC-V Toolchain contributed By < [SUE3K](https://github.com/SUE3K/computer_architecture_hw1/tree/main) > ## linkedlist "linked list" is a common data structure ![](https://hackmd.io/_uploads/SyTmRzgWa.png) ![](https://hackmd.io/_uploads/Sks4Cfxbp.png) As shown in the two diagrams above, the concept is to use nodes to record, represent, and store data. Each node has three components: Data, Pointer, and Address. Additionally, each node's pointer points to the address of the next node, continuing until it points to Null, signifying the end of this simple linked list. The time complexity is **O(N)** ## Count leading zero To calculate the number of consecutive zeros, counting from the Most Significant Bit (MSB) towards the right, until the first encountered '1' in a binary number Ex: **0000000000000010 =14** ## Motivation For this assignment, I choose the program Sum of Leading Zeros in Linked List by CLZ 劉智恩. This topic was chosen for its academic challenge, optimization potential, real-world applications, and the opportunity to gain a deeper understanding of low-level programming and computer architecture. ## Implement ### Original C code ```c #include <stdint.h> #include <stdio.h> #include <stdlib.h> // using malloc functions // def linkedlist structure typedef struct Node { uint32_t data; // 32 bits unsigned integers struct Node* next; } Node; // calculate 32bits unsigned int count of leading zeros uint16_t count_leading_zeros(uint32_t x) { x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); /* count ones (population count) */ x -= ((x >> 1) & 0x55555555); x = ((x >> 2) & 0x33333333) + (x & 0x33333333); x = ((x >> 4) + x) & 0x0f0f0f0f; x += (x >> 8); x += (x >> 16); return (32 - (x & 0x1f)); // 32 bits unsigned int leading zeors } // calculate all linkedlists node clz and sum uint64_t sum_of_leading_zeros(Node* head) { uint64_t sum = 0; while (head != NULL) { uint16_t leadingZeros = count_leading_zeros(head->data); sum += leadingZeros; head = head->next; } return sum; } int main() { // create a simple linked list Node* head = NULL; Node* node1 = malloc(sizeof(Node)); node1->data = 23; node1->next = NULL; head = node1; Node* node2 = malloc(sizeof(Node)); node2->data = 15; node2->next = NULL; node1->next = node2; Node* node3 = malloc(sizeof(Node)); node3->data = 1 ; node3->next = NULL; node2->next = node3; // calculate sum of linkedlist node leading zeors for 32bits unsigned integers uint32_t totalLeadingZeros = sum_of_leading_zeros(head); printf("Sum of Leading Zeros: %llu\n", totalLeadingZeros); // release linked list node memory while (head != NULL) { Node* temp = head; head = head->next; free(temp); } return 0; } ``` ### Modified C code ```c #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> // using malloc functions // count cycle typedef uint64_t ticks; static inline ticks getticks(void) { uint64_t result; uint32_t l, h, h2; asm volatile( "rdcycleh %0\n" "rdcycle %1\n" "rdcycleh %2\n" "sub %0, %0, %2\n" "seqz %0, %0\n" "sub %0, zero, %0\n" "and %1, %1, %0\n" : "=r"(h), "=r"(l), "=r"(h2)); result = (((uint64_t) h) << 32) | ((uint64_t) l); return result; } // def linkedlist structure typedef struct Node { uint32_t data; // 32 bits unsigned integers struct Node* next; } Node; // calculate 32bits unsigned int count of leading zeros uint16_t count_leading_zeros(uint32_t x) { x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); /* count ones (population count) */ x -= ((x >> 1) & 0x55555555); x = ((x >> 2) & 0x33333333) + (x & 0x33333333); x = ((x >> 4) + x) & 0x0f0f0f0f; x += (x >> 8); x += (x >> 16); return (32 - (x & 0x1f)); // 32 bits unsigned int leading zeors } // calculate all linkedlists node clz and sum uint64_t sum_of_leading_zeros(Node* head) { uint64_t sum = 0; while (head != NULL) { uint16_t leadingZeros = count_leading_zeros(head->data); sum += leadingZeros; head = head->next; } return sum; } int main() { ticks t0 = getticks(); // create a simple linked list Node* head = NULL; Node* node1 = malloc(sizeof(Node)); node1->data = 23; node1->next = NULL; head = node1; Node* node2 = malloc(sizeof(Node)); node2->data = 15; node2->next = NULL; node1->next = node2; Node* node3 = malloc(sizeof(Node)); node3->data = 1 ; node3->next = NULL; node2->next = node3; // calculate sum of linkedlist node leading zeors for 32bits unsigned integers uint64_t totalLeadingZeros = sum_of_leading_zeros(head); printf("Sum of Leading Zeros: %llu\n", totalLeadingZeros); // release linked list node memory while (head != NULL) { Node* temp = head; head = head->next; free(temp); } ticks t1 = getticks(); printf("elapsed cycle: %" PRIu64 "\n", t1 - t0); //cycle number return 0; } ``` ### Makefile we need to adjust original makefile from asm-hello ```shell .PHONY: clean include /home/ianli/rv32emu/mk/toolchain.mk CFLAGS = -march=rv32i -mabi=ilp32 -O3 ASFLAGS = -march=rv32i -mabi=ilp32 LDFLAGS = --oformat=elf32-littleriscv %.S: %.c $(CROSS_COMPILE)gcc $(CFLAGS) -o $@ -S $< %.o: %.S $(CROSS_COMPILE)as $(ASFLAGS) -o $@ $< all: hw1_liu.elf hw1_liu.S: hw1_liu.c $(CROSS_COMPILE)gcc $(CFLAGS) -o $@ -S $< hw1_liu.elf: hw1_liu.o $(CROSS_COMPILE)gcc -o $@ $< clean: $(RM) hw1_liu.elf hw1_liu.o hw1_liu.S ``` so we can "make", generate .s .o and .elf <s> ![](https://hackmd.io/_uploads/rk-NZqjMa.png) </s> :::warning Don't put the screenshots which contain plain text only. :notes: jserv ::: ### Output cycle count we need to add "ticks" into our code for counting cycle. ### after we modified ```c #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> // using malloc functions // count cycle typedef uint64_t ticks; static inline ticks getticks(void) { uint64_t result; uint32_t l, h, h2; asm volatile( "rdcycleh %0\n" "rdcycle %1\n" "rdcycleh %2\n" "sub %0, %0, %2\n" "seqz %0, %0\n" "sub %0, zero, %0\n" "and %1, %1, %0\n" : "=r"(h), "=r"(l), "=r"(h2)); result = (((uint64_t) h) << 32) | ((uint64_t) l); return result; } // def linkedlist structure typedef struct Node { uint32_t data; // 32 bits unsigned integers struct Node* next; } Node; // calculate 32bits unsigned int count of leading zeros uint16_t count_leading_zeros(uint32_t x) { x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); /* count ones (population count) */ x -= ((x >> 1) & 0x55555555); x = ((x >> 2) & 0x33333333) + (x & 0x33333333); x = ((x >> 4) + x) & 0x0f0f0f0f; x += (x >> 8); x += (x >> 16); return (32 - (x & 0x1f)); // 32 bits unsigned int leading zeors } // calculate all linkedlists node clz and sum uint64_t sum_of_leading_zeros(Node* head) { uint64_t sum = 0; while (head != NULL) { uint16_t leadingZeros = count_leading_zeros(head->data); sum += leadingZeros; head = head->next; } return sum; } int main() { ticks t0 = getticks(); // create a simple linked list Node* head = NULL; Node* node1 = malloc(sizeof(Node)); node1->data = 23; node1->next = NULL; head = node1; Node* node2 = malloc(sizeof(Node)); node2->data = 15; node2->next = NULL; node1->next = node2; Node* node3 = malloc(sizeof(Node)); node3->data = 1; node3->next = NULL; node2->next = node3; // calculate sum of linkedlist node leading zeors for 32bits unsigned integers uint64_t totalLeadingZeros = sum_of_leading_zeros(head); printf("Sum of Leading Zeros: %ld\n", totalLeadingZeros); // release linked list node memory while (head != NULL) { Node* temp = head; head = head->next; free(temp); } ticks t1 = getticks(); printf("elapsed cycle: %" PRIu64 "\n", t1 - t0); //cycle number return 0; } ``` ### Obtain the O0-3 O0: ![](https://hackmd.io/_uploads/H1SNDcszT.png) :::danger Avoid using screenshots that solely contain plain text. Here are the reasons why: 1. Text-based content is more efficiently searchable than having to browse through images iteratively. 2. The rendering engine of HackMD can consistently generate well-structured layouts with annotated text instead of relying on arbitrary pictures. 3. It provides a more accessible and user-friendly experience for individuals with visual impairments. :notes: jserv ::: show the ELF Header ``` riscv-none-elf-readelf -h asm-hw2/hw1_liu.elf ``` ``` ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: RISC-V Version: 0x1 Entry point address: 0x100c2 Start of program headers: 52 (bytes into file) Start of section headers: 69404 (bytes into file) Flags: 0x1, RVC, soft-float ABI Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 3 Size of section headers: 40 (bytes) Number of section headers: 15 Section header string table index: 14 ``` show the text size ``` riscv-none-elf-size asm-hw2/hw1_liu.elf ``` size ``` text data bss dec hex filename 51958 1876 1528 55362 d842 asm-hw2/hw1_liu.elf ``` O1: ![](https://hackmd.io/_uploads/B1Mw39sz6.png) ``` ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: RISC-V Version: 0x1 Entry point address: 0x100c2 Start of program headers: 52 (bytes into file) Start of section headers: 69404 (bytes into file) Flags: 0x1, RVC, soft-float ABI Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 3 Size of section headers: 40 (bytes) Number of section headers: 15 Section header string table index: 14 ``` size ``` text data bss dec hex filename 51470 1876 1528 54874 d65a asm-hw2/hw1_liu.elf ``` O2: ![](https://hackmd.io/_uploads/B1jw2cjGT.png) ``` ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: RISC-V Version: 0x1 Entry point address: 0x101a2 Start of program headers: 52 (bytes into file) Start of section headers: 69420 (bytes into file) Flags: 0x1, RVC, soft-float ABI Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 3 Size of section headers: 40 (bytes) Number of section headers: 15 Section header string table index: 14 ``` size ``` text data bss dec hex filename 51566 1876 1528 54970 d6ba asm-hw2/hw1_liu.elf ``` O3: ![](https://hackmd.io/_uploads/H1zOncsfT.png) ``` ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: RISC-V Version: 0x1 Entry point address: 0x10276 Start of program headers: 52 (bytes into file) Start of section headers: 69396 (bytes into file) Flags: 0x1, RVC, soft-float ABI Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 3 Size of section headers: 40 (bytes) Number of section headers: 15 Section header string table index: 14 ``` size ``` text data bss dec hex filename 51744 1876 1528 55148 d76c asm-hw2/hw1_liu.elf ``` ### handwrite assembly I try to reducing some text size original ``` srli t0,s0,1 or s0,s0,t0 srli t0,s0,2 or s0,s0,t0 srli t0,s0,4 or s0,s0,t0 srli t0,s0,8 or s0,s0,t0 srli t0,s0,16 or s0,s0,t0 ``` after optimize ``` li s3, 1 li s4, 0 li s5, 5 counter: beq s4, x0, op_main sll s3, s3, s4 op_main: addi s4, s4, 1 srl t0,s0, s3 or s0,s0,t0 bne s4, s5, counter ``` and try to add some intruction into the makefile ``` GCCFLAGS := -fdata-sections -ffunction-sections LDFLAGS := -Wl,--gc-sections ``` ## result | version | cycle count | text | |---------|-------------|---------| |-O0|3123|51958| |-O1|2868|51470| |-O2|2838|51566| |-O3|2831|51744| :::warning Show me the handwritten RISC-V assembly code. :notes: jserv :::

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