Compilation method for compiling C language source code into RISC-V assembly code

By performing lexical, syntactic, and semantic analysis on C language source code, a runtime environment and intermediate representation of RISC-V assembly code are generated, solving the problem that general-purpose compilers cannot efficiently adapt to the RISC-V architecture, and improving network processing performance and execution efficiency.

CN121832955APending Publication Date: 2026-04-10CHINA SOUTHERN POWER GRID COMPANY
View PDF 0 Cites 1 Cited by

Patent Information

Application Number
CN202511815374.3
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-12-04
Publication Date
2026-04-10

AI Technical Summary

Technical Problem

General-purpose compilers cannot efficiently adapt to the instruction set of the RISC-V architecture, resulting in redundant code size, long execution cycle and high power consumption. Furthermore, they incur significant performance overhead when processing high-frequency, small-sized network data packets, making it difficult to meet the needs of network processing scenarios.

Method used

A compilation method is provided that generates a target abstract syntax tree through lexical analysis, syntax analysis, and semantic analysis, constructs a runtime environment for RISC-V assembly code, generates intermediate code and control flow graph, and finally generates efficient RISC-V assembly code.

Benefits of technology

It improves the execution efficiency of assembly code, reduces performance overhead, adapts to RISC-V custom instruction mapping, and enhances network processing performance.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121832955A_ABST
    Figure CN121832955A_ABST
Patent Text Reader

Abstract

The invention discloses a compiling method for compiling a C language source code into an RISC-V assembly code. The method comprises the following steps: acquiring a C language source code; performing lexical analysis on the C language source code to generate a mark flow; performing syntactic analysis on the mark flow, and constructing an abstract syntax tree; performing semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; constructing a runtime environment of the RISC-V assembly code; generating an intermediate code and a control flow diagram corresponding to the intermediate code according to a rule in the runtime environment and the target abstract syntax tree; generating a target code by using the intermediate code and the control flow diagram corresponding to the intermediate code; according to the technical scheme, the intermediate representation more adaptive to RISC-V custom instruction mapping can be generated, so that the execution efficiency of assembly codes is improved; and meanwhile, by designing a lightweight runtime environment, the performance overhead is further reduced.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The present application relates to the field of network communication and processor technology, and in particular to a compiling method for compiling C language source code into RISC-V assembly code. BACKGROUND

[0002] With the popularization of smart grid and distributed energy, power communication network needs to process various special protocols such as IEC 61850, IEEE C37.118, and manufacturer-defined protocols. If the traditional network device is constructed based on fixed-function special integrated circuits (ASIC) or general-purpose central processing units (CPU), it is difficult to flexibly and efficiently adapt to the rapid iteration and evolution of these protocols. As a high-level data plane programming language, the programming protocol-independent packet processor (P4) language supports dynamically describing the processing logic of data packets by defining packet header formats, data packet parsers, match-action tables and other core elements, thereby realizing protocol-independent programmable data plane design. At the same time, the fifth generation reduced instruction set computer (RISC-V) has become an ideal technology platform for implementing high-performance and low-power protocol processing hardware due to its open source, customizable and extensible technical characteristics.

[0003] The standard C language code to RISC-V architecture target program compilation process: with the help of a general-purpose GCC compiler, a standard RISC-V compilation tool chain is used, and general optimization options are enabled to compile and process C code.

[0004] The general-purpose compiler cannot efficiently adapt to the instruction set extensions customized for network processing scenarios of the RISC-V architecture, resulting in problems such as code volume redundancy, long execution period and high power consumption. In addition, the runtime environment built by the general-purpose compiler is developed for general program design scenarios, and its execution logic includes unnecessary context saving and register operation processes. In the scenario of processing high-frequency and small-size network data packets, such redundant operations will introduce significant performance overhead, which seriously restricts the performance of the RISC-V architecture in the field of network processing. SUMMARY

[0005] The present application provides a compiling method for compiling C language source code into RISC-V assembly code, which can generate an intermediate representation more suitable for mapping RISC-V custom instructions, thereby improving the execution efficiency of the assembly code. At the same time, by designing a lightweight runtime environment, the performance overhead is further reduced.

[0006] According to an aspect of the present application, a compiling method for compiling C language source code into RISC-V assembly code is provided, which comprises:

[0007] obtaining C language source code;

[0008] performing lexical analysis on the C language source code to generate a token stream; wherein the token stream is formed by tokens corresponding to characters in the C language source code in sequence;

[0009] performing syntax analysis on the token stream to construct an abstract syntax tree;

[0010] performing semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; wherein the target abstract syntax tree is a syntax tree structure formed by adding semantic attributes to each node on the basis of the abstract syntax tree;

[0011] constructing a runtime environment of RISC-V assembly code;

[0012] generating intermediate code and a control flow graph corresponding to the intermediate code according to rules in the runtime environment and the target abstract syntax tree;

[0013] generating target code using the intermediate code and the control flow graph corresponding to the intermediate code; wherein the target code is implemented in the form of RISC-V assembly language code.

[0014] According to another aspect of the present application, a compiling device for compiling C language source code into RISC-V assembly code is provided, which comprises:

[0015] a C language source code obtaining unit for obtaining C language source code;

[0016] a token stream generating unit for performing lexical analysis on the C language source code to generate a token stream; wherein the token stream is formed by tokens corresponding to characters in the C language source code in sequence;

[0017] an abstract syntax tree constructing unit for performing syntax analysis on the token stream to construct an abstract syntax tree;

[0018] a target abstract syntax tree generating unit for performing semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; wherein the target abstract syntax tree is a syntax tree structure formed by adding semantic attributes to each node on the basis of the abstract syntax tree;

[0019] a runtime environment constructing unit for constructing a runtime environment of RISC-V assembly code;

[0020] An intermediate code generation unit is configured to generate intermediate code and a control flow graph corresponding to the intermediate code according to rules in the runtime environment and the target abstract syntax tree.

[0021] A target code generation unit is configured to generate target code by using the intermediate code and the control flow graph corresponding to the intermediate code, wherein the target code is implemented in the form of RISC-V assembly language code.

[0022] According to another aspect of the present application, an electronic device is provided, which comprises:

[0023] at least one processor; and a memory connected to the at least one processor in communication; wherein the memory stores a computer program executable by the at least one processor, and the computer program is executed by the at least one processor to enable the at least one processor to perform the compiling method for compiling C language source code into RISC-V assembly code according to any one of the embodiments of the present application.

[0024] According to another aspect of the present application, a computer readable storage medium is provided, which stores computer instructions for enabling a processor to perform the compiling method for compiling C language source code into RISC-V assembly code according to any one of the embodiments of the present application when executed by the processor.

[0025] The technical solution of the embodiments of the present application comprises the following steps: obtaining C language source code; performing lexical analysis on the C language source code to generate a token stream; performing syntax analysis on the token stream to construct an abstract syntax tree; performing semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; constructing a runtime environment of RISC-V assembly code; generating intermediate code and a control flow graph corresponding to the intermediate code according to rules in the runtime environment and the target abstract syntax tree; and generating target code by using the intermediate code and the control flow graph corresponding to the intermediate code. The technical solution can generate intermediate representation more suitable for RISC-V custom instruction mapping, thereby improving the execution efficiency of assembly code; and further reduces performance overhead by designing a lightweight runtime environment.

[0026] It should be understood that the content described in this part is not intended to identify key or important features of the embodiments of the present application, nor to limit the scope of the present application. Other features of the present application will become apparent through the following description. BRIEF DESCRIPTION OF DRAWINGS

[0027] In order to more clearly illustrate the technical solutions in the embodiments of the present application, the drawings needed to be used in the embodiments description will be briefly introduced. Obviously, the drawings in the following description are only some embodiments of the present application, and other drawings can be obtained by those skilled in the art without any creative effort based on these drawings.

[0028] Figure 1 is a flow chart of a compiling method for compiling C language source code into RISC-V assembly code according to the first embodiment of the present application;

[0029] Figure 2 is a schematic diagram of a compiling method for compiling C language source code into RISC-V assembly code according to the second embodiment of the present application;

[0030] Figure 3 is a flow chart of another compiling method for compiling C language source code into RISC-V assembly code according to the second embodiment of the present application;

[0031] Figure 4 is a flow chart of still another compiling method for compiling C language source code into RISC-V assembly code according to the third embodiment of the present application;

[0032] Figure 5 is a schematic diagram of a compiling process for compiling C language source code into RISC-V assembly code according to the fourth embodiment of the present application;

[0033] Figure 6 is another schematic diagram of a compiling process for compiling C language source code into RISC-V assembly code according to the fifth embodiment of the present application;

[0034] Figure 7 is still another schematic diagram of a compiling process for compiling C language source code into RISC-V assembly code according to the sixth embodiment of the present application;

[0035] Figure 8 is a structural schematic diagram of a compiling device for compiling C language source code into RISC-V assembly code according to the seventh embodiment of the present application;

[0036] Figure 9 is a structural schematic diagram of an electronic device for implementing a compiling method for compiling C language source code into RISC-V assembly code according to the embodiment of the present application. DETAILED DESCRIPTION

[0037] In the following, the technical solutions in the embodiments of the present application will be described clearly and completely with reference to the drawings in the embodiments of the present application. Obviously, the described embodiments are only a part of the embodiments of the present application, rather than all the embodiments of the present application. Based on the embodiments in the present application, all other embodiments obtained by a person of ordinary skill in the art without creative work should belong to the protection scope of the present application.

[0038] It should be noted that the terms "original", "target" and the like in the specification and claims of the present application and the above-described drawings are used to distinguish similar objects, and do not necessarily describe a specific order or sequence. It should be understood that the data thus used can be interchanged under appropriate circumstances, so that the embodiments of the application described herein can be implemented in an order other than that illustrated or described herein. In addition, the terms "include" and "have" and any variations thereof are intended to cover non-exclusive inclusion, for example, a process, method, system, product or device including a series of steps or units does not necessarily have to be limited to those steps or units clearly listed, but can include other steps or units not clearly listed or inherent to these processes, methods, products or devices.

[0039] Embodiment one

[0040] Figure 1 It is a flowchart of a compiling method for compiling C language source code into RISC-V assembly code according to embodiment one of the present application. The present embodiment can be applicable to the case of compiling C language source code into RISC-V assembly code. The method can be executed by a compiling device for compiling C language source code into RISC-V assembly code. The compiling device for compiling C language source code into RISC-V assembly code can be realized in the form of hardware and / or software. The compiling device for compiling C language source code into RISC-V assembly code can be configured in a device. For example, the device can be a background server or other device with communication and computing capabilities. As shown in the figure, the method comprises: Figure 1

[0041] S101, obtaining C language source code.

[0042] In the present embodiment, the C language source code is a human-readable text file written in C language. It is a program logic description written according to the C language syntax rules, which contains instructions, data structures, algorithms and other contents to realize specific functions, and usually has the suffix.c (main code file) or.h (header file).

[0043] In the present scheme, the C language source code is obtained from the database.

[0044] ​S102. Perform lexical analysis on the C language source code to generate a token stream; wherein the token stream is formed by sequentially combining the tokens corresponding to each character in the C language source code.

[0045] The core task of lexical analysis is to convert the character stream of source code into a meaningful token stream. A token is the smallest unit with independent syntactic meaning in a programming language; examples include keywords (such as if, for), identifiers (variable names, function names), constants (numbers, strings), and operators (+, ...). ), separators ({, ;), etc.

[0046] In this approach, the process of compiling C language source code into RISC-V assembly code is completed within a computer or server software development environment using a dedicated compilation toolchain. This toolchain, as the core execution entity during the development phase, works collaboratively with multiple internal software modules to not only convert C language source code into RISC-V assembly code but also to highly optimize the generated code, ultimately outputting a high-efficiency assembly program that conforms to the characteristics of the RISC-V architecture. Figure 2 This is a schematic diagram illustrating the compilation method for compiling C language source code into RISC-V assembly code provided in Embodiment 2 of this application, as shown below. Figure 2 As shown, the lexical analyzer in the toolchain is used to perform lexical analysis on the C language source code.

[0047] S103. Perform syntactic analysis on the tokenized stream and construct an abstract syntax tree.

[0048] Syntax analysis refers to the process of performing structural verification and hierarchical analysis on the tokenized stream output by lexical analysis according to predefined grammatical rules, determining whether it conforms to the grammatical norms of the language, and constructing a tree-like representation (abstract syntax tree) that reflects the grammatical structure.

[0049] Specifically, such as Figure 2 As shown, the syntax analysis of the token stream is performed by the parser in the toolchain to construct an abstract syntax tree.

[0050] S104. Perform semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; wherein, the target abstract syntax tree is a syntax tree structure formed by adding semantic attributes to each node based on the abstract syntax tree.

[0051] In this embodiment, semantic analysis involves performing context-dependent checks and attribute enhancements on the abstract syntax tree to ensure that the program conforms to the semantic rules of the language (such as type matching, scope constraints, consistency between identifier declaration and usage, etc.), and adding semantic attributes (such as type information, scope information, symbol references, constant values, etc.) to each node, ultimately generating a target abstract syntax tree with complete semantic information.

[0052] In this plan, such as Figure 2 As shown, the semantic analyzer in the toolchain is used to perform semantic analysis on the abstract syntax tree to generate the target abstract syntax tree.

[0053] S105. Construct the runtime environment for RISC-V assembly code.

[0054] In this embodiment, the runtime environment is built and runs after semantic analysis and before intermediate code generation. Its core task is to plan and define a set of rules for efficiently managing memory, executing functions, and accessing data on RISC-V hardware for the target code to be generated.

[0055] Specifically, such as Figure 2 The runtime environment is built using the runtime environment build manager in the toolchain.

[0056] S106. Based on the rules in the runtime environment and the target abstract syntax tree, generate intermediate code and the corresponding control flow graph.

[0057] In this embodiment, as Figure 2 As shown, the intermediate code generator receives the target abstract syntax tree and rules from the runtime environment build manager to generate an intermediate representation that is both hardware-independent and fully presents the optimized design to the compiler.

[0058] Specifically, by combining the established rules of the runtime environment with the structural features of the target abstract syntax tree, the system will complete the generation of intermediate code and simultaneously construct the control flow graph corresponding to the intermediate code, thereby realizing the structured transformation of syntactic logic into execution flow.

[0059] S107. Using the intermediate code and the control flow graph corresponding to the intermediate code, generate target code; wherein the target code is implemented in RISC-V assembly language.

[0060] Specifically, such as Figure 2 As shown, intermediate code and its corresponding control flow graph are used to perform instruction selection, register allocation, and instruction scheduling, ultimately outputting efficient RISC-V assembly code.

[0061] The technical solution of this invention involves: acquiring C language source code; performing lexical analysis on the C language source code to generate a tokenized stream; performing syntactic analysis on the tokenized stream to construct an abstract syntax tree (AST); performing semantic analysis on the AST to generate a target AST; constructing a runtime environment for RISC-V assembly code; generating intermediate code and its corresponding control flow graph based on the rules in the runtime environment and the target AST; and generating target code using the intermediate code and its corresponding control flow graph. By executing this technical solution, an intermediate representation more adapted to RISC-V custom instruction mapping can be generated, thereby improving the execution efficiency of assembly code; simultaneously, by designing a lightweight runtime environment, performance overhead is further reduced.

[0062] Example 2

[0063] Figure 3 This is a flowchart illustrating another compilation method for compiling C language source code into RISC-V assembly code, provided in Embodiment 2 of the present invention. The relationship between this embodiment and the above embodiments is a detailed description of the lexical analysis process. Figure 3 As shown, the method includes:

[0064] S301. Obtain the C language source code.

[0065] S302. Use a preset lexical analyzer to read the characters in the C language source code one by one in sequence.

[0066] In this scheme, the lexical analyzer in the toolchain is used to read the characters in the C language source code one by one in sequence to form an input character stream.

[0067] S303. Determine the tag corresponding to the character, and generate a tag stream based on the tag.

[0068] Specifically, starting from the initial state, the direction of subsequent state transitions is determined based on the characters read.

[0069] When a letter or underscore is encountered, the system enters the "identifier" state and continues to read subsequent letters, numbers, or underscore characters until a non-letter character is encountered. The collected string is then matched against the keyword table: if a match is successful, a "keyword" tag is generated; if a match fails, the string is matched against the symbol table. If a match is successful, an "identifier" tag is generated; otherwise, the string is entered into the symbol table (recording the identifier name, position, scope, and other initial attributes) and an "identifier" tag is generated.

[0070] When encountering numbers, it enters "constant" state, recognizes various format specifications for integers and floating-point numbers, and generates "literal constant" tags.

[0071] When encountering operators (such as +, -, &, |, etc.) or separators (such as (, , , ;, etc.), look-ahead judgment is required to distinguish compound operators (such as == and =, -> and -), and then the corresponding "operator" or "separator" mark is generated.

[0072] Whitespace characters (spaces, tabs, newlines, etc.) and comments will be recognized and skipped without generating any markers.

[0073] The above process continues until the last character of the C language source code is tokenized, at which point the lexical analysis process is complete, and a tokenized stream is finally generated.

[0074] Optionally, determining the tag corresponding to the character includes:

[0075] The character is matched with a preset symbol table and a keyword table to determine the tag corresponding to the character; wherein, the symbol table is used to store identifiers and the attribute information corresponding to the identifiers; the keyword table is used to store all keywords of the C language.

[0076] In this embodiment, a symbol table is a data structure used to store identifiers and their corresponding attribute information. It is usually implemented using a hash table as the core method, which can efficiently map identifiers to various attributes (such as type, scope, storage location, etc.) and support fast lookup, insertion and update operations.

[0077] Identifiers are identifiers such as variable names, function names, and type names. Preliminary attributes include the position where the identifier first appears in the code and whether it has been declared.

[0078] In this scheme, the keyword table is a pre-generated hash table that covers all C language keywords (such as int, if, while, etc.) as well as specific keywords extended for network processing requirements.

[0079] Keyword is a word built into the C language that has special meaning and cannot be used as an identifier. Extended specific keywords are words added for specific scenarios that have special syntactic meanings.

[0080] Furthermore, during lexical analysis, the symbol table and keyword table can be used to quickly determine whether the currently identified character sequence is a keyword or a regular identifier, ensuring that the special meaning of the keyword is not misused.

[0081] By accurately matching characters with a preset symbol table and keyword table, the corresponding mark is determined. The symbol table stores identifiers and their attribute information, and the keyword table covers all keywords in the C language. This enables rapid determination and classification of the type of characters, effectively improving the accuracy and efficiency of lexical analysis.

[0082] S304. Perform syntactic analysis on the tokenized stream and construct an abstract syntax tree.

[0083] S305. Perform semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; wherein, the target abstract syntax tree is a syntax tree structure formed by adding semantic attributes to each node based on the abstract syntax tree.

[0084] S306, Building the runtime environment for RISC-V assembly code.

[0085] S307. Based on the rules in the runtime environment and the target abstract syntax tree, generate intermediate code and the corresponding control flow graph.

[0086] S308. Using the intermediate code and the control flow graph corresponding to the intermediate code, generate target code; wherein the target code is implemented in RISC-V assembly language.

[0087] The technical solution of this invention involves: acquiring C language source code; sequentially reading characters from the C language source code using a preset lexical analyzer; determining the tokens corresponding to the characters and generating a token stream based on the tokens; performing syntactic analysis on the token stream to construct an abstract syntax tree (AST); performing semantic analysis on the AST to generate a target AST; constructing a runtime environment for RISC-V assembly code; generating intermediate code and its corresponding control flow graph based on the rules in the runtime environment and the target AST; and generating target code using the intermediate code and its corresponding control flow graph. By implementing this technical solution, the C language source code is systematically processed through lexical analysis, syntax analysis, and semantic analysis. This process gradually transforms the source code into a structured abstract syntax tree and optimizes it. Combined with the RISC-V assembly runtime environment, intermediate code and control flow graphs are generated, ultimately outputting the target code. This not only ensures the standardization and accuracy of the code conversion process, effectively reducing syntax errors and semantic ambiguity, but also enables cross-platform adaptation and compilation optimization through the intermediate presentation layer. This improves the execution efficiency and hardware compatibility of the target code. Furthermore, the clear layered processing flow facilitates debugging and maintenance, providing reliable support for the efficient compilation and execution of C language programs under the RISC-V architecture.

[0088] Example 3

[0089] Figure 4 This is a flowchart illustrating another compilation method for compiling C language source code into RISC-V assembly code, provided in Embodiment 3 of the present invention. The relationship between this embodiment and the above embodiments is a detailed description of the abstract syntax tree construction process. Figure 4 As shown, the method includes:

[0090] S401. Obtain the C language source code.

[0091] S402. Perform lexical analysis on the C language source code to generate a token stream; wherein the token stream is formed by sequentially combining the tokens corresponding to each character in the C language source code.

[0092] S403. Perform syntactic analysis on the token stream based on a preset parser to construct nodes of an abstract syntax tree.

[0093] In this embodiment, recursive descent parsing is used to implement syntax analysis. The core idea of ​​recursive descent parsing is to construct an independent parsing function for each non-terminal symbol in the grammar (such as "expression", "statement", "function definition"). The parsing process starts from the top-level "program" parsing function, which calls the "function definition" parsing function; the "function definition" parsing function may further call "declaration", "statement", and other parsing functions, thus completing the recursive parsing. Each parsing function consumes the corresponding token in the input token stream based on the currently read token and dynamically constructs nodes of the abstract syntax tree in memory.

[0094] S404. Determine the syntax rules corresponding to each tag in the tag stream; wherein the syntax rules are determined based on the context-free grammar of the C language.

[0095] In this embodiment, the syntax rules of the C language are built upon a context-free grammar. This grammar uses formal methods such as Backus-Noor normal form to precisely define the rules for combining tags into a legal program structure. For example, a typical rule can be expressed as: "An if statement consists of the if tag, a left parenthesis, an expression, a right parenthesis, a statement, and an optional else tag and another statement."

[0096] In this scheme, during the construction phase of the abstract syntax tree, the parser will trigger the corresponding syntax rules after recognizing specific keywords related to network packet processing.

[0097] S405. Based on the grammar rules, construct the grammar structure corresponding to the nodes of the abstract syntax tree.

[0098] Furthermore, a matching grammatical structure is constructed by triggering the corresponding grammatical rules, and customized attribute tags are added to the abstract syntax tree nodes in this structure.

[0099] If the subsequent tag stream of a specific keyword does not match the rule's expectation, the parser will immediately throw a syntax error.

[0100] In this embodiment, taking the data packet field extraction scenario as an example: when the function call get_field (a typical function used to extract fields in network data packet processing) is parsed and its input parameters include bit offset and length parameters, the parser will set a custom attribute label on the corresponding abstract syntax tree node, such as node.optimization_hint = BITFIELD_EXTRACTION (bit field extraction).

[0101] These attribute tags only carry key semantic intent information and do not change the original structure of the abstract syntax tree. This allows the syntax analysis module to go beyond simple syntax structure verification and become a component with preliminary pattern recognition capabilities. The high-level semantics contained in these attribute tags will provide optimization basis for the subsequent semantic analysis module and intermediate code generation module, guiding them to complete targeted optimization design for the RISC-V instruction set.

[0102] S406. Perform semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; wherein, the target abstract syntax tree is a syntax tree structure formed by adding semantic attributes to each node based on the abstract syntax tree.

[0103] S407, The runtime environment for building RISC-V assembly code.

[0104] S408. Based on the rules in the runtime environment and the target abstract syntax tree, generate intermediate code and the corresponding control flow graph.

[0105] S409. Using the intermediate code and the control flow graph corresponding to the intermediate code, generate target code; wherein the target code is implemented in RISC-V assembly language.

[0106] The technical solution of this invention involves: acquiring C language source code; performing lexical analysis on the C language source code to generate a tokenized stream; performing syntactic analysis on the tokenized stream to construct nodes and syntactic structure of an abstract syntax tree; performing semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; constructing a runtime environment for RISC-V assembly code; generating intermediate code and its corresponding control flow graph based on the rules in the runtime environment and the target abstract syntax tree; and generating target code using the intermediate code and its corresponding control flow graph. By implementing this technical solution, through this series of compilation processes from C language source code to RISC-V target code, not only can high-level language code be accurately translated into low-level hardware executable instructions, effectively achieving cross-level semantic mapping and instruction adaptation, but also the code's standardization and logical rationality can be verified layer by layer through lexical, syntactic, and semantic analysis, ensuring the code's correctness and robustness. Simultaneously, the construction of intermediate code and control flow graphs provides crucial support for code optimization, significantly improving the execution efficiency and resource utilization of the target code. Furthermore, the runtime environment adaptation based on the RISC-V architecture fully leverages the architecture's streamlined, efficient, and scalable characteristics, resulting in target code that combines high performance with hardware adaptability. This reduces the adaptation costs between software development and hardware execution, and lays a solid foundation for the efficient and stable operation of programs on the RISC-V platform.

[0107] Example 4

[0108] Figure 5 This is a schematic diagram illustrating the compilation process of compiling C language source code into RISC-V assembly code, as provided in Embodiment 4 of the present invention. The relationship between this embodiment and the above embodiments is a detailed description of the target abstract syntax tree construction process. Figure 5 As shown, the method includes:

[0109] S501. Obtain the C language source code.

[0110] S502. Perform lexical analysis on the C language source code to generate a token stream; wherein the token stream is formed by sequentially combining the tokens corresponding to each character in the C language source code.

[0111] S503. Perform syntax analysis on the tokenized stream and construct an abstract syntax tree.

[0112] S504. Perform semantic analysis on the abstract syntax tree using a preset semantic analyzer to obtain the semantic analysis results.

[0113] In this embodiment, the semantic analyzer traverses the abstract syntax tree, checks the source program's context-related attributes, ensures the program's logical consistency, and collects comprehensive information for code generation.

[0114] In this scheme, the semantic analyzer maintains a hierarchical symbol table structure. When entering a new scope (such as a function body, compound statement, etc.), a new symbol table is created and linked to the symbol table of the parent scope.

[0115] Specifically, when a variable or function declaration is encountered, its name, type, scope, and other detailed information are inserted into the symbol table of the current scope; when an identifier is encountered, the declaration is searched back level by level from the current scope to determine the specific meaning of the identifier.

[0116] Furthermore, a type system is a set of rules defined by a programming language. Its core function is to standardize the definition, classification, and interaction logic of data types. Specifically, it covers core content such as the operations allowed to be performed on different types of data, assignment rules, and type matching requirements for passing function parameters.

[0117] Type checking, a core task of the compiler's semantic analysis phase, refers to the process by which the compiler verifies the legality of data type usage in the source code according to the type system rules of the programming language. For example, it verifies whether integers and pointers can be directly added (this operation is explicitly prohibited in C, and the compiler will throw an error); it verifies the compatibility of data types on both sides of an assignment statement (e.g., executing `int a = "abc";` is an illegal operation, essentially a type mismatch); and it verifies whether the access methods of structure members are consistent with their defined type specifications.

[0118] Specifically, the semantic analyzer uses additional attribute tags passed from the syntax analysis phase to perform more stringent domain-specific semantic checks on the abstract syntax tree nodes. The high-level semantics carried in the attribute tags have a one-to-one mapping relationship with the corresponding check rules, and this mapping relationship is pre-configured within the semantic analyzer.

[0119] Marked as BITFIELD_EXTRACTION (Bit Field Extraction) Taking a node as an example, the semantic analyzer will perform the following additional checks: It checks whether the bit offset and length parameters are compile-time constants, which are prerequisites for generating RISC-V bit manipulation instructions. If the parameters meet the compile-time constant requirement, the compiler can directly generate the corresponding bit manipulation instructions; if not, the node is marked as requiring software processing or an error is thrown directly. It also checks whether the operation object (data packet buffer pointer) carries the correct const (pointing to read-only data) or volatile (pointing to modifiable data) attributes. Furthermore, for AST nodes related to the validity of data packet pointers, the semantic analyzer needs to sequentially perform pointer boundary validity checks, memory alignment checks of access addresses, and validity checks of the pointer's lifetime.

[0120] S505. If the semantic analysis result is passed, then determine the semantic attribute corresponding to the semantic analysis result.

[0121] Specifically, if the semantic analysis result is passed, the semantic analyzer will not only verify the correctness of the semantics, but also strengthen the optimization label of the node (such as further attaching the check result or check content), or convert it into more specific, backend-oriented semantic attributes (i.e., structured information that the code generator can directly use).

[0122] Furthermore, if the check fails, it generates more instructive error messages, such as "The offset extracted from the bit field must be a compile-time constant to accommodate hardware instruction optimizations." This mechanism directly guides developers to write code that is more suitable for the characteristics of the target hardware (RISC-V).

[0123] S506. Determine the target node corresponding to the semantic attribute; wherein, the target node is a node in the abstract syntax tree after semantic analysis.

[0124] In this scheme, the target node corresponding to the semantic attribute is determined by analyzing the semantic attribute.

[0125] S507. Add the semantic attribute to the attribute field of the target node to generate the target abstract syntax tree.

[0126] In this scheme, the output of the semantic parser is an abstract syntax tree that has undergone full type validation. The semantics of all identifiers in this tree have been parsed, and key nodes have been given enhanced semantic attributes. These attributes can be directly used to guide the backend optimization process. This fully-informed target abstract syntax tree will be delivered to the runtime environment build manager as the core input for the next stage of the compilation process.

[0127] Specifically, semantic attributes are embedded in the attribute fields of the target node, and the target abstract syntax tree is generated based on this operation.

[0128] S508 is the runtime environment for building RISC-V assembly code.

[0129] S509. Based on the rules in the runtime environment and the target abstract syntax tree, generate intermediate code and the corresponding control flow graph.

[0130] S510. Using the intermediate code and the control flow graph corresponding to the intermediate code, generate target code; wherein the target code is implemented in RISC-V assembly language.

[0131] The technical solution of this invention involves: acquiring C language source code; performing lexical analysis on the C language source code to generate a tokenized stream; performing syntactic analysis on the tokenized stream to construct an abstract syntax tree (AST); performing semantic analysis on the AST to generate a target AST; constructing a runtime environment for RISC-V assembly code; generating intermediate code and its corresponding control flow graph based on the rules in the runtime environment and the target AST; and generating target code using the intermediate code and its corresponding control flow graph. By executing this technical solution, not only is a precise mapping from high-level language to low-level assembly language achieved, ensuring the correctness and readability of the code conversion, but the compilation process is also optimized through layered processing and structured analysis, improving the execution efficiency and hardware compatibility of the target code. Simultaneously, it provides clear logical support for code debugging, optimization, and cross-platform portability, significantly enhancing the controllability and scalability of the compilation process.

[0132] Example 5

[0133] Figure 6 This is a schematic diagram illustrating another compilation process for compiling C language source code into RISC-V assembly code, provided in Embodiment 5 of the present invention. The relationship between this embodiment and the above embodiments is a detailed description of the runtime environment construction process. Figure 6 As shown, the method includes:

[0134] S601. Obtain the C language source code.

[0135] S602. Perform lexical analysis on the C language source code to generate a token stream; wherein the token stream is formed by sequentially combining the tokens corresponding to each character in the C language source code.

[0136] S603. Perform syntax analysis on the tokenized stream and construct an abstract syntax tree.

[0137] S604. Perform semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; wherein, the target abstract syntax tree is a syntax tree structure formed by adding semantic attributes to each node based on the abstract syntax tree.

[0138] S605. Construct a stack frame and registers; wherein the stack frame is a memory region allocated on the runtime stack during function calls.

[0139] In this embodiment, a stack frame is a memory region allocated on the runtime stack for each function call, used to store local data required for the function execution.

[0140] Registers are used to temporarily store data, instructions, addresses, or calculation results.

[0141] Specifically, stack frames and registers are built using compilers within the toolchain.

[0142] Optionally, construct a stack frame, including:

[0143] Traverse each function in the target abstract syntax tree and construct the control flow graph for each function;

[0144] Lifecycle and access frequency analysis are performed on each local variable in the control flow graph to redetermine the order of each local variable in the stack frame.

[0145] Specifically, the standardized stack frame layout adopted by general-purpose compilers belongs to a general and unified design paradigm, and does not perform customized optimizations for the data access characteristics within different functions. Specifically, different functions often have significant differences in the frequency, order, and method of accessing data (such as local variables and parameters) within the stack frame during runtime, but the standardized layout does not make adaptive adjustments: for example, even if a function does not actually need to use a frame pointer, the standardized layout will still reserve a fixed storage location for it; and even if the access frequency of local variables in a function is much higher than that of parameters, the address arrangement order of the two in the stack space will not be optimized or adjusted accordingly.

[0146] Furthermore, based on the general layout, a local variable rearrangement strategy based on lifecycle and access frequency analysis is introduced.

[0147] In this embodiment, the runtime environment build manager first receives the target abstract syntax tree (API); then it traverses each function definition in the API and constructs the control flow graph of that function. Subsequently, it performs lifecycle analysis and access frequency analysis on each local variable.

[0148] The core objective of lifecycle analysis is to determine the instruction range covered by each variable from its definition to its last use. This instruction range refers to the set of all instructions involved from the variable's definition to its last use; essentially, it is the "valid time period" of the variable defined by the order of instruction execution. For variables with short lifecycles, there is no need to allocate storage space on the stack (registers can be reused directly), or their stack space can be shared with other variables whose lifecycles do not overlap, thereby saving memory resources.

[0149] Access frequency analysis utilizes static analysis techniques (such as counting the number of times variables are accessed within loops and the frequency of variables appearing in branch structures) combined with domain tags attached to the P4 / C source code (such as pointer variables labeled as handling packet_header) to infer frequently accessed variables at runtime. In specific scenarios such as network processing, due to the frequent parsing of protocol fields, related variables naturally possess the characteristic of high-frequency access. These variables can be identified through tags attached to the target abstract tree syntax nodes.

[0150] Furthermore, the build manager can reorder the order of local variables in the stack frame. Its core optimization principle is to group variables with overlapping lifecycles and high-frequency access into adjacent memory locations as much as possible.

[0151] In its implementation, the build manager divides the variable set into different "clusters." Variables within a cluster have a high degree of overlap in their lifecycles and high access frequency. The layout algorithm prioritizes placing these "hot clusters" in the region with the smallest offset relative to the frame pointer.

[0152] The process involves using variables as nodes, generating edges when the lifecycles of two nodes overlap. Then, the frequency with which overlapping nodes are accessed every 100 executions within their respective basic blocks is calculated and used as the edge weight. Next, clustering is performed on the conflict graph to divide it into multiple clusters. Clusters are sorted based on the number of nodes within the cluster and the average edge weight; clusters ranked higher have smaller frame pointer offsets. This centralized access to adjacent memory addresses significantly improves CPU cache hit rate and reduces clock cycle overhead caused by waiting for memory accesses.

[0153] In the RISC-V instruction set, the addressing method using frame pointers combined with 12-bit signed immediate offsets is the most efficient. Placing frequently accessed variables within a small offset range ensures that the most compact instruction format is always used when generating load / store instructions, thereby reducing code size and speeding up instruction decoding and execution.

[0154] Optional, construct registers, including:

[0155] Traverse the target abstract syntax tree to extract all variables of the target abstract syntax tree;

[0156] Calculate the priority weight of each variable in the target abstract syntax tree;

[0157] Based on the priority weights, a corresponding register is allocated to each variable according to a preset register allocation strategy.

[0158] In this embodiment, general-purpose compilers typically employ complex global register allocation algorithms such as graph coloring. The core objective of such algorithms is to map variables in the program to physical registers, while strictly ensuring that at any point in the program's execution, two live variables will not be allocated to the same register. Although these algorithms possess powerful global optimization capabilities, their implementation logic is relatively complex, and in the process of pursuing the global optimal solution, they often struggle to provide sufficient priority guarantees for specific critical variables.

[0159] Furthermore, in terms of register allocation strategy, an allocation mechanism combining static priority and dynamic hints is adopted.

[0160] The build manager assigns a static priority weight to a variable based on its semantics and purpose. This weight can be conceptualized using a decision formula:

[0161] ;

[0162] in, Based on the weight of basic types, pointer type variables (such as pointers to packet buffers) typically receive the highest weight because access to them is fundamental to all other operations. Integers and floating-point numbers are next in weight. For access frequency weighting, high-frequency access variables identified in the analysis phase are given higher weights. Domain-specific weights are assigned, and the tags passed down from semantic analysis are directly quantized into weights based on a preset mapping relationship.

[0163] When performing actual register allocation (which is specifically executed in the subsequent intermediate code generation phase, but the strategy is formulated at this time), the allocator will strictly follow this priority model.

[0164] The highest priority variables are preferentially and forcibly allocated to the RISC-V's best-performing registers; for low-priority variables with short lifecycles and no conflicts, an attempt is made to keep them in registers; for low-priority variables that cannot be allocated to registers, they are "overflowed" into the previously optimized stack frame.

[0165] The runtime environment build manager alters the data access patterns of the target code by intelligently rearranging the stack frame layout based on access patterns and introducing a domain-knowledge-based static priority model for register allocation. This ensures the fastest data path for the most critical data structures and operations in power communication network processing, laying a solid and efficient foundation for the subsequent generation of highly optimized RISC-V code.

[0166] S606. Based on the rules in the runtime environment and the target abstract syntax tree, generate intermediate code and the corresponding control flow graph.

[0167] S607. Using the intermediate code and the control flow graph corresponding to the intermediate code, generate target code; wherein the target code is implemented in RISC-V assembly language.

[0168] The technical solution of this invention involves: acquiring C language source code; performing lexical analysis on the C language source code to generate a tokenized stream; performing syntactic analysis on the tokenized stream to construct an abstract syntax tree (AST); performing semantic analysis on the AST to generate a target AST; constructing stack frames and registers; generating intermediate code and its corresponding control flow graph based on rules in the runtime environment and the target AST; and generating target code using the intermediate code and its corresponding control flow graph. By executing this technical solution, the runtime environment construction module designs a compact stack frame structure and register allocation strategy specifically based on the business characteristics of the packet processing program. This optimization effectively reduces stack operation overhead and context switching system resource consumption during function calls, allowing a larger proportion of the processor's computation cycle to be allocated to the execution of business logic rather than system-level maintenance operations, thereby improving the core execution efficiency of packet processing.

[0169] Example 6

[0170] Figure 7 This is a schematic diagram illustrating another compilation process for compiling C language source code into RISC-V assembly code, as provided in Embodiment Six of the present invention. The relationship between this embodiment and the above embodiments is a detailed description of the target code generation process. Figure 7 As shown, the method includes:

[0171] S701. Obtain the C language source code.

[0172] S702. Perform lexical analysis on the C language source code to generate a token stream; wherein the token stream is formed by sequentially combining the tokens corresponding to each character in the C language source code.

[0173] S703. Perform syntax analysis on the tokenized stream and construct an abstract syntax tree.

[0174] S704. Perform semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; wherein, the target abstract syntax tree is a syntax tree structure formed by adding semantic attributes to each node based on the abstract syntax tree.

[0175] S705, the runtime environment for building RISC-V assembly code.

[0176] S706. Traverse the target abstract syntax tree and decompose the nodes in the target abstract syntax tree into intermediate code instructions.

[0177] The intermediate code generator breaks down complex nodes into intermediate code instructions by performing a post-order traversal of the target abstract syntax tree.

[0178] In this embodiment, the basic form of each three-address instruction is typically: result = operand1operator operand2. Here, result represents the storage location of the operation result; operand1 and operand2 are operands, which can include variables, constants, or temporary variables; and operator represents the specific operator.

[0179] S707. Divide the intermediate code instructions into basic blocks, and connect the basic blocks according to the jump instructions of each basic block to construct a control flow graph.

[0180] In this embodiment, intermediate code instructions are divided into multiple basic blocks. A basic block is a sequence of sequentially executed instructions with maximum validity; it has only one entry point (i.e., the first instruction of the block) and one exit point (i.e., the jump instruction of the block). By analyzing jump-type instructions (such as if, goto, while, etc.) in the program, these basic blocks can be interconnected to construct a control flow graph. In this graph, nodes correspond to basic blocks, and edges represent possible transfer paths of control flow.

[0181] Furthermore, customized processing is performed on the abstract syntax tree nodes with specific semantic tags to ultimately generate an intermediate representation that integrates high-level semantics (specifically, it is still a three-address code).

[0182] Specifically, when the intermediate code generator processes a node marked as BITFIELD_EXTRACTION (bit field extraction) by the semantic analysis module, it does not simply generate a standard sequence of shift and logical AND operations. Instead, it generates a dedicated intermediate code instruction carrying high-level semantics, such as BITFIELD_EXTRACT t_target, t_source, offset, length. Here, t_target is a temporary variable used to store the extraction result, t_source is a temporary variable to store the source data, offset represents the bit offset, and length is the length of the field to be extracted.

[0183] For an IPv4 checksum calculation function call AST node marked as CHECKSUM_IPV4 by the semantic analyzer, a traditional compiler typically generates dozens of three-address codes containing operations such as data loading, sign extension, numerical accumulation, and loop checks. However, the intermediate code generator, upon detecting this label, directly generates a concise three-address instruction: `t_checksum = CHECKSUM_IPV4 t_packet_start t_packet_length`. This instruction, in the form of a single three-address code, completely encapsulates the entire checksum calculation logic, significantly simplifying the complexity of the intermediate representation.

[0184] Furthermore, custom instructions like `BITFIELD_EXTRACT t_target, t_source, offset, length` essentially still fall under the three-address code category, following a structure of one operator, at most two source operands, and one target operand. This domain-specific operator design allows the compiler to simultaneously represent and optimize general computational logic and domain-specific computational logic within a unified and abstract framework.

[0185] Furthermore, these custom instructions are atomic operations in the three-address code, and they encapsulate the high-level semantic logic corresponding to the semantic tags. This provides clear and unambiguous optimization targets for the compiler backend optimization stage, which helps to improve the targeting and execution efficiency of optimization strategies.

[0186] After generating the initial three-address code and control flow graph, the intermediate code generator performs a series of optimization transformations.

[0187] A general-purpose compiler performs standard optimizations such as constant propagation, duplicate instruction elimination, and dead code removal. Building upon this, the following features are introduced:

[0188] Pattern recognition and instruction merging.

[0189] The intermediate code generator actively searches the control flow graph for optimizable patterns composed of previously generated intermediate instructions with high-level semantics.

[0190] Once a specific tag is detected, the generator does not enter the general code generation logic, but instead queries a predefined mapping table. This table defines which tag combinations correspond to which syntax structures and which custom intermediate instructions. Based on the mapping table, the generator outputs a corresponding three-address instruction with a specific operand code. For example, it might identify two consecutive bit field extraction operations with the same source and adjacent extracted fields. In this case, the module will merge these two separate BITFIELD_EXTRACT instructions into a wider extraction operation, or directly replace it with a more complex custom instruction BITFIELD_COMBINE. This significantly reduces the number of machine instructions that need to be generated. Cyclic Redundancy Check (CRC) is used for error detection in power communication. Its core operation is to look up a table or perform calculations based on the current CRC value and the new data byte. The generator recognizes the "load-calculate-pointer increment" cyclic pattern of CRC. To improve efficiency, it can merge multiple iterations of calculation, merging the byte-by-byte calculation loop into a 4-byte-by-4-byte calculation loop. (The RISC-V architecture's general-purpose register width determines the 4-byte-by-4-byte computation method. If its general-purpose register width were wider, it could be combined into a longer single-input computation.)

[0191] Targeted transformation of loops: Packet handlers contain numerous loops that iterate through packet bytes or process flow tables. This module will leverage domain knowledge for optimization:

[0192] For loops with a few known iterations at compile time (e.g., processing a fixed-size protocol header), the module performs loop unrolling, which copies the loop body multiple times, eliminating the overhead of loop control (condition checks, variable updates, and jumps). This is crucial for improving instruction-level parallelism. More expensive operations within the loop are replaced with less expensive ones. For example, multiplication of array elements within a loop is converted into addition using pointer increment. Because loops execute code repeatedly, the cost of operations is amplified N times in N iterations.

[0193] The intermediate code generator encapsulates high-level semantic intents into intermediate instructions and performs a series of intelligent optimizations based on domain knowledge and target hardware characteristics. This transforms the high-level abstraction of the network-oriented C language into a highly optimized, ready-to-use sequence of low-level operations, providing high-quality input for the target code generator.

[0194] S708. Map the intermediate code instructions to RISC-V assembly code instructions.

[0195] Specifically, a predefined pattern library is used to define the mapping rules from intermediate operations to target RISC-V instructions, converting operations of intermediate code instructions into corresponding RISC-V instruction sequences. This pattern library not only covers conventional mapping rules but also incorporates instruction patterns with advanced semantics customized for intermediate code. For specific intermediate code instructions, it can accurately map them to preset efficient instructions, thereby improving the efficiency and adaptability of instruction conversion.

[0196] S709. Based on the control flow graph, determine the dependencies corresponding to the RISC-V assembly code instructions.

[0197] In this scheme, a graph coloring register allocation algorithm is used. The virtual registers storing temporary variables in the intermediate code are regarded as nodes of a graph. If two virtual registers are both alive at the same time (i.e., their values ​​need to be preserved), an edge is established between them (called a "collision"). The goal of the allocator is to color each node (allocate a physical register), requiring that no two nodes connected by an edge can have the same color.

[0198] S710. Generate target code based on the RISC-V assembly code instructions and the dependencies.

[0199] In this embodiment, a Data Dependency Graph (DDG) is constructed, with instructions as nodes and dependencies as edges. This represents the target code, and the edge types cover three data dependencies: RAW (Read After Write), WAW (Write After Write), and WAR (Write After Read), as well as control dependencies. The scheduler executes a priority scheduling algorithm based on the DDG. Under the premise of satisfying all dependency constraints, it prioritizes the execution of ready instructions (those whose predecessor dependencies are satisfied) to maximize instruction-level parallelism.

[0200] The intermediate code conversion module follows the RISC-V instruction set specification, completing instruction mapping, register allocation, and addressing mode conversion to generate assembly code conforming to the RISC-V architecture. During the code generation phase, the instruction sequence is rearranged and optimized based on the DDG scheduling results to ensure that dependency constraints match the characteristics of RISC-V hardware (such as pipeline structure and memory access latency), ultimately outputting an efficient and valid assembly instruction stream.

[0201] The technical solution of this invention first obtains C language source code and performs lexical analysis to generate a tokenized stream; then, it performs syntactic analysis based on the tokenized stream to construct an abstract syntax tree (AST); subsequently, it performs semantic analysis on the AST to generate a target AST. Simultaneously, a runtime environment for RISC-V assembly code is established; by traversing the target AST, its nodes are decomposed into intermediate code instructions. These intermediate code instructions are divided into basic blocks, and based on the jump instructions of each basic block, the basic blocks are interconnected to construct a control flow graph; the intermediate code instructions are mapped to RISC-V assembly code instructions; based on the control flow graph, the dependencies between the RISC-V assembly code instructions are defined; and the target code is generated based on the RISC-V assembly code instructions and the aforementioned dependencies. By executing this technical solution, an intermediate representation more adapted to RISC-V custom instruction mapping can be generated, thereby improving the execution efficiency of assembly code; furthermore, by designing a lightweight runtime environment, performance overhead is reduced.

[0202] Example 7

[0203] Figure 8 This is a schematic diagram of a compilation device for compiling C language source code into RISC-V assembly code, as provided in Embodiment 7 of the present invention. Figure 8 As shown, the device includes:

[0204] C language source code acquisition unit 801 is used to acquire C language source code;

[0205] The token stream generation unit 802 is used to perform lexical analysis on the C language source code and generate a token stream; wherein, the token stream is formed by sequentially combining the tokens corresponding to each character in the C language source code;

[0206] Abstract syntax tree construction unit 803 is used to perform syntax analysis on the token stream and construct an abstract syntax tree;

[0207] The target abstract syntax tree generation unit 804 is used to perform semantic analysis on the abstract syntax tree to generate a target abstract syntax tree; wherein, the target abstract syntax tree is a syntax tree structure formed by adding semantic attributes to each node on the basis of the abstract syntax tree;

[0208] Runtime environment building unit 805 is used to build the runtime environment for RISC-V assembly code;

[0209] Intermediate code generation unit 806 is used to generate intermediate code and the corresponding control flow graph based on the rules in the runtime environment and the target abstract syntax tree;

[0210] The target code generation unit 807 is used to generate target code using the intermediate code and the control flow graph corresponding to the intermediate code; wherein the target code is implemented in the form of RISC-V assembly language.

[0211] Optionally, the tag stream generation unit 802 includes:

[0212] The character reading subunit is used to read the characters in the C language source code sequentially one by one using a preset lexical analyzer.

[0213] A tag stream generation subunit is used to determine the tag corresponding to the character and generate a tag stream based on the tag.

[0214] Optionally, the marker stream generates sub-units, specifically used for:

[0215] The character is matched with a preset symbol table and a keyword table to determine the tag corresponding to the character; wherein, the symbol table is used to store identifiers and the attribute information corresponding to the identifiers; the keyword table is used to store all keywords of the C language.

[0216] Optional, the Abstract Syntax Tree building unit 803 is specifically used for:

[0217] The tokenized stream is parsed using a preset lexical analyzer to construct nodes of an abstract syntax tree;

[0218] Determine the syntax rules corresponding to each tag in the tag stream; wherein the syntax rules are determined based on the context-free grammar of the C language;

[0219] Based on the grammar rules, construct the grammar structure corresponding to the nodes of the abstract syntax tree.

[0220] Optionally, the target abstract syntax tree generation unit 804 is specifically used for:

[0221] The abstract syntax tree is semantically analyzed using a preset semantic analyzer to obtain the semantic analysis results;

[0222] If the semantic analysis result is passed, then the semantic attribute corresponding to the semantic analysis result is determined;

[0223] Determine the target node corresponding to the semantic attribute; wherein, the target node is a node in the abstract syntax tree after semantic analysis;

[0224] Add the semantic attribute to the attribute field of the target node to generate the target abstract syntax tree.

[0225] Optionally, runtime environment building block 805 includes:

[0226] The runtime environment construction subunit is used to construct stack frames and registers; wherein, the stack frame is a memory region allocated on the runtime stack when a function is called.

[0227] Optional, runtime environment building subunit, specifically used for:

[0228] Traverse each function in the target abstract syntax tree and construct the control flow graph for each function;

[0229] Lifecycle and access frequency analysis are performed on each local variable in the control flow graph to redetermine the order of each local variable in the stack frame.

[0230] Optional, runtime environment building subunit, specifically used for:

[0231] Traverse the target abstract syntax tree to extract all variables of the target abstract syntax tree;

[0232] Calculate the priority weight of each variable in the target abstract syntax tree;

[0233] Based on the priority weights, a corresponding register is allocated to each variable according to a preset register allocation strategy.

[0234] Optionally, intermediate code generation unit 806 is specifically used for:

[0235] Traverse the target abstract syntax tree and decompose the nodes in the target abstract syntax tree into intermediate code instructions;

[0236] The intermediate code instructions are divided into basic blocks, and the basic blocks are connected together according to the jump instructions of each basic block to construct a control flow graph.

[0237] Optionally, the target code generation unit 807 is specifically used for:

[0238] Map the intermediate code instructions to RISC-V assembly code instructions;

[0239] Based on the control flow graph, the dependencies of the RISC-V assembly code instructions are determined;

[0240] The target code is generated based on the RISC-V assembly code instructions and the dependencies.

[0241] The compilation device for compiling C language source code into RISC-V assembly code provided in the embodiments of the present invention can execute the compilation method for compiling C language source code into RISC-V assembly code provided in any embodiment of the present invention, and has the corresponding functional modules and beneficial effects of the execution method.

[0242] Example 8

[0243] Figure 9 A schematic diagram of an electronic device 10, which can be used to implement embodiments of the present invention, is shown. The electronic device is intended to represent various forms of digital computers, such as laptop computers, desktop computers, workstations, personal digital assistants, servers, blade servers, mainframe computers, and other suitable computers. The electronic device can also represent various forms of mobile devices, such as personal digital processors, cellular phones, smartphones, wearable devices (e.g., helmets, glasses, watches, etc.), and other similar computing devices. The components shown herein, their connections and relationships, and their functions are merely illustrative and are not intended to limit the implementation of the invention described and / or claimed herein.

[0244] like Figure 9 As shown, the electronic device 10 includes at least one processor 11 and a memory, such as a read-only memory (ROM) 12 or a random access memory (RAM) 13, communicatively connected to the at least one processor 11. The memory stores computer programs executable by the at least one processor. The processor 11 can perform various appropriate actions and processes based on the computer program stored in the ROM 12 or loaded from storage unit 18 into the RAM 13. The RAM 13 can also store various programs and data required for the operation of the electronic device 10. The processor 11, ROM 12, and RAM 13 are interconnected via a bus 14. An input / output (I / O) interface 15 is also connected to the bus 14.

[0245] Multiple components in electronic device 10 are connected to I / O interface 15, including: input unit 16, such as keyboard, mouse, etc.; output unit 17, such as various types of displays, speakers, etc.; storage unit 18, such as disk, optical disk, etc.; and communication unit 19, such as network card, modem, wireless transceiver, etc. Communication unit 19 allows electronic device 10 to exchange information / data with other devices through computer networks such as the Internet and / or various telecommunications networks.

[0246] Processor 11 can be a variety of general-purpose and / or special-purpose processing components with processing and computing capabilities. Some examples of processor 11 include, but are not limited to, a central processing unit (CPU), a graphics processing unit (GPU), various special-purpose artificial intelligence (AI) computing chips, various processors running machine learning model algorithms, a digital signal processor (DSP), and any suitable processor, controller, microcontroller, etc. Processor 11 performs the various methods and processes described above, such as a compilation method for compiling C language source code into RISC-V assembly code.

[0247] In the context of this invention, a computer-readable storage medium can be a tangible medium that may contain or store a computer program for use by or in conjunction with an instruction execution system, apparatus, or device. A computer-readable storage medium may include, but is not limited to, electronic, magnetic, optical, electromagnetic, infrared, or semiconductor systems, apparatus, or devices, or any suitable combination thereof. Alternatively, a computer-readable storage medium may be a machine-readable signal medium. More specific examples of machine-readable storage media include electrical connections based on one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fibers, portable compact disk read-only memory (CD-ROM), optical storage devices, magnetic storage devices, or any suitable combination thereof.

[0248] To provide interaction with a user, the systems and techniques described herein can be implemented on an electronic device having: a display device (e.g., a CRT (cathode ray tube) or LCD (liquid crystal display) monitor) for displaying information to the user; and a keyboard and pointing device (e.g., a mouse or trackball) through which the user provides input to the electronic device. Other types of devices can also be used to provide interaction with the user; for example, feedback provided to the user can be any form of sensory feedback (e.g., visual feedback, auditory feedback, or tactile feedback); and input from the user can be received in any form (including sound input, voice input, or tactile input).

Claims

1. A compilation method for compiling C language source code into RISC-V assembly code, characterized in that, include: Obtain the C language source code; Lexical analysis is performed on the C language source code to generate a token stream; wherein the token stream is composed of the tokens corresponding to each character in the C language source code combined in sequence; Perform syntactic analysis on the tokenized stream to construct an abstract syntax tree; Semantic analysis is performed on the abstract syntax tree to generate a target abstract syntax tree; wherein, the target abstract syntax tree is a syntax tree structure formed by adding semantic attributes to each node based on the abstract syntax tree; Build a runtime environment for RISC-V assembly code; Based on the rules in the runtime environment and the target abstract syntax tree, intermediate code and the corresponding control flow graph are generated; The target code is generated using the intermediate code and the corresponding control flow graph; wherein the target code is implemented in RISC-V assembly language.

2. The method according to claim 1, characterized in that, Lexical analysis is performed on the C language source code to generate a token stream, including: The characters in the C language source code are read sequentially one by one using a preset lexical analyzer. Determine the tag corresponding to the character, and generate a tag stream based on the tag.

3. The method according to claim 2, characterized in that, Determining the tag corresponding to the character includes: The character is matched with a preset symbol table and a keyword table to determine the tag corresponding to the character; wherein, the symbol table is used to store identifiers and the attribute information corresponding to the identifiers; the keyword table is used to store all keywords of the C language.

4. The method according to claim 1, characterized in that, Performing syntactic analysis on the tokenized stream and constructing an abstract syntax tree includes: The token stream is parsed using a preset parser to construct nodes of an abstract syntax tree; Determine the syntax rules corresponding to each tag in the tag stream; wherein the syntax rules are determined based on the context-free grammar of the C language; Based on the grammar rules, construct the grammar structure corresponding to the nodes of the abstract syntax tree.

5. The method according to claim 1, characterized in that, Semantic analysis is performed on the abstract syntax tree to generate the target abstract syntax tree, including: The abstract syntax tree is semantically analyzed using a preset semantic analyzer to obtain the semantic analysis results; If the semantic analysis result is passed, then the semantic attribute corresponding to the semantic analysis result is determined; Determine the target node corresponding to the semantic attribute; wherein, the target node is a node in the abstract syntax tree after semantic analysis; Add the semantic attribute to the attribute field of the target node to generate the target abstract syntax tree.

6. The method according to claim 1, characterized in that, The runtime environment for building RISC-V assembly code includes: Construct a stack frame and registers; wherein the stack frame is a memory region allocated on the runtime stack when a function is called.

7. The method according to claim 6, characterized in that, Constructing a stack frame includes: Traverse each function in the target abstract syntax tree and construct the control flow graph for each function; Lifecycle and access frequency analysis are performed on each local variable in the control flow graph to redetermine the order of each local variable in the stack frame.

8. The method according to claim 6, characterized in that, Constructing registers includes: Traverse the target abstract syntax tree to extract all variables of the target abstract syntax tree; Calculate the priority weight of each variable in the target abstract syntax tree; Based on the priority weights, a corresponding register is allocated to each variable according to a preset register allocation strategy.

9. The method according to claim 1, characterized in that, Based on the rules in the runtime environment and the target abstract syntax tree, intermediate code and the corresponding control flow graph are generated, including: Traverse the target abstract syntax tree and decompose the nodes in the target abstract syntax tree into intermediate code instructions; The intermediate code instructions are divided into basic blocks, and the basic blocks are connected together according to the jump instructions of each basic block to construct a control flow graph.

10. The method according to claim 9, characterized in that, Using the intermediate code and the corresponding control flow graph, target code is generated, including: Map the intermediate code instructions to RISC-V assembly code instructions; Based on the control flow graph, the dependencies of the RISC-V assembly code instructions are determined; The target code is generated based on the RISC-V assembly code instructions and the dependencies.

Citation Information

Cited By

  • A visual interactive teaching experiment system and method based on C language program control

    CN122547324A