timestamp
stringlengths 26
26
| segment
stringlengths 8
9
| dump
stringlengths 10
52
| url
stringlengths 22
23
| image_urls
sequencelengths 0
0
| content
stringlengths 882
10.6k
|
---|---|---|---|---|---|
2023-07-18T10:37:52.211712 | segment0 | 1 Introduction | RV32ISPEC.pdf#segment0 | [] | 1 Introduction RISC-V (pronounced “risk-five”) is a new instruction-set architecture (ISA) that was originallydesigned to support computer architecture research and education, but which we now hope willalso become a standard free and open architecture for industry implementations. Our goals indefining RISC-V include:•A completelyopenISA that is freely available to academia and industry.•ArealISA suitable for direct native hardware implementation, not just simulation or binarytranslation.•An ISA that avoids “over-architecting” for a particular microarchitecture style (e.g., mi-crocoded, in-order, decoupled, out-of-order) or implementation technology (e.g., full-custom,ASIC, FPGA), but which allows e cient implementation in any of these.•An ISA separated into asmallbase integer ISA, usable by itself as a base for customizedaccelerators or for educational purposes, and optional standard extensions, to support general-purpose software development.•Support for the revised 2008 IEEE-754 floating-point standard [7].•An ISA supporting extensive ISA extensions and specialized variants.•Both 32-bit and 64-bit address space variants for applications, operating system kernels, andhardware implementations.•An ISA with support for highly-parallel multicore or manycore implementations, includingheterogeneous multiprocessors.•Optionalvariable-length instructionsto both expand available instruction encoding space andto support an optionaldense instruction encodingfor improved performance, static code size,and energy e ciency.•A fully virtualizable ISA to ease hypervisor development.•An ISA that simplifies experiments with new privileged architecture designs.Commentary on our design decisions is formatted as in this paragraph. This non-normative textcan be skipped if the reader is only interested in the specification itself.The name RISC-V was chosen to represent the fifth major RISC ISA design from UC Berkeley(RISC-I [15], RISC-II [8], SOAR [21], and SPUR [11] were the first four). We also pun on theuse of the Roman numeral “V” to signify “variations” and “vectors”, as support for a range of architecture research, including various data-parallel accelerators, is an explicit goal of the ISAdesign.The RISC-V ISA is defined avoiding implementation details as much as possible (although com-mentary is included on implementation-driven decisions) and should be read as the software-visibleinterface to a wide variety of implementations rather than as the design of a particular hardwareartifact. The RISC-V manual is structured in two volumes. This volume covers the design ofthe baseunprivilegedinstructions, including optional unprivileged ISA extensions. Unprivilegedinstructions are those that are generally usable in all privilege modes in all privileged architectures,though behavior might vary depending on privilege mode and privilege architecture. The secondvolume provides the design of the first (“classic”) privileged architecture. The manuals use IEC80000-13:2008 conventions, with a byte of 8 bits.In the unprivileged ISA design, we tried to remove any dependence on particular microarchi-tectural features, such as cache line size, or on privileged architecture details, such as pagetranslation. This is both for simplicity and to allow maximum flexibility for alternative microar-chitectures or alternative privileged architectures. |
2023-07-18T10:37:52.211915 | segment1 | 1.1 RISC-V Hardware Platform Terminology | RV32ISPEC.pdf#segment1 | [] | 1.1 RISC-V Hardware Platform Terminology A RISC-V hardware platform can contain one or more RISC-V-compatible processing cores to-gether with other non-RISC-V-compatible cores, fixed-function accelerators, various physical mem-ory structures, I/O devices, and an interconnect structure to allow the components to communicate.A component is termed acoreif it contains an independent instruction fetch unit. A RISC-V-compatible core might support multiple RISC-V-compatible hardware threads, orharts, throughmultithreading.A RISC-V core might have additional specialized instruction-set extensions or an addedcoprocessor.We use the termcoprocessorto refer to a unit that is attached to a RISC-V core and is mostlysequenced by a RISC-V instruction stream, but which contains additional architectural state andinstruction-set extensions, and possibly some limited autonomy relative to the primary RISC-Vinstruction stream.We use the termacceleratorto refer to either a non-programmable fixed-function unit or a core thatcan operate autonomously but is specialized for certain tasks. In RISC-V systems, we expect manyprogrammable accelerators will be RISC-V-based cores with specialized instruction-set extensionsand/or customized coprocessors. An important class of RISC-V accelerators are I/O accelerators,which o✏oad I/O processing tasks from the main application cores.The system-level organization of a RISC-V hardware platform can range from a single-core micro-controller to a many-thousand-node cluster of shared-memory manycore server nodes. Even smallsystems-on-a-chip might be structured as a hierarchy of multicomputers and/or multiprocessors tomodularize development e↵ort or to provide secure isolation between subsystems. |
2023-07-18T10:37:52.212045 | segment2 | 1.2 RISC-V Software Execution Environments and Harts | RV32ISPEC.pdf#segment2 | [] | 1.2 RISC-V Software Execution Environments and HartsThe behavior of a RISC-V program depends on the execution environment in which it runs. ARISC-V execution environment interface (EEI) defines the initial state of the program, the numberand type of harts in the environment including the privilege modes supported by the harts, theaccessibility and attributes of memory and I/O regions, the behavior of all legal instructions exe-cuted on each hart (i.e., the ISA is one component of the EEI), and the handling of any interruptsor exceptions raised during execution including environment calls. Examples of EEIs include theLinux application binary interface (ABI), or the RISC-V supervisor binary interface (SBI). Theimplementation of a RISC-V execution environment can be pure hardware, pure software, or acombination of hardware and software. For example, opcode traps and software emulation can beused to implement functionality not provided in hardware. Examples of execution environmentimplementations include:•“Bare metal” hardware platforms where harts are directly implemented by physical processorthreads and instructions have full access to the physical address space. The hardware platformdefines an execution environment that begins at power-on reset.•RISC-V operating systems that provide multiple user-level execution environments by mul-tiplexing user-level harts onto available physical processor threads and by controlling accessto memory via virtual memory.•RISC-V hypervisors that provide multiple supervisor-level execution environments for guestoperating systems.•RISC-V emulators, such as Spike, QEMU or rv8, which emulate RISC-V harts on an under-lying x86 system, and which can provide either a user-level or a supervisor-level executionenvironment.A bare hardware platform can be considered to define an EEI, where the accessible harts, memory,and other devices populate the environment, and the initial state is that at power-on reset.Generally, most software is designed to use a more abstract interface to the hardware, as moreabstract EEIs provide greater portability across di↵erent hardware platforms. Often EEIs arelayered on top of one another, where one higher-level EEI uses another lower-level EEI.From the perspective of software running in a given execution environment, a hart is a resource thatautonomously fetches and executes RISC-V instructions within that execution environment. In thisrespect, a hart behaves like a hardware thread resource even if time-multiplexed onto real hardwareby the execution environment. Some EEIs support the creation and destruction of additional harts,for example, via environment calls to fork new harts.The execution environment is responsible for ensuring the eventual forward progress of each of itsharts. For a given hart, that responsibility is suspended while the hart is exercising a mechanismthat explicitly waits for an event, such as the wait-for-interrupt instruction defined in Volume IIof this specification; and that responsibility ends if the hart is terminated. The following eventsconstitute forward progress:•The retirement of an instruction.•A trap, as defined in Section1.6. Any other event defined by an extension to constitute forward progress.The term hart was introduced in the work on Lithe [13,14] to provide a term to represent anabstract execution resource as opposed to a software thread programming abstraction.The important distinction between a hardware thread (hart) and a software thread contextis that the software running inside an execution environment is not responsible for causingprogress of each of its harts; that is the responsibility of the outer execution environment. Sothe environment’s harts operate like hardware threads from the perspective of the software insidethe execution environment.An execution environment implementation might time-multiplex a set of guest harts ontofewer host harts provided by its own execution environment but must do so in a way that guestharts operate like independent hardware threads. In particular, if there are more guest harts thanhost harts then the execution environment must be able to preempt the guest harts and must notwait indefinitely for guest software on a guest hart to ”yield” control of the guest hart. |
2023-07-18T10:37:52.212242 | segment3 | 1.3 RISC-V ISA Overview | RV32ISPEC.pdf#segment3 | [] | 1.3 RISC-V ISA Overview A RISC-V ISA is defined as a base integer ISA, which must be present in any implementation, plusoptional extensions to the base ISA. The base integer ISAs are very similar to that of the earlyRISC processors except with no branch delay slots and with support for optional variable-lengthinstruction encodings. A base is carefully restricted to a minimal set of instructions su cient toprovide a reasonable target for compilers, assemblers, linkers, and operating systems (with addi-tional privileged operations), and so provides a convenient ISA and software toolchain “skeleton”around which more customized processor ISAs can be built.Although it is convenient to speak oftheRISC-V ISA, RISC-V is actually a family of related ISAs,of which there are currently four base ISAs. Each base integer instruction set is characterized bythe width of the integer registers and the corresponding size of the address space and by the numberof integer registers. There are two primary base integer variants, RV32I and RV64I, described inChapters2and5, which provide 32-bit or 64-bit address spaces respectively. We use the termXLEN to refer to the width of an integer register in bits (either 32 or 64). Chapter4describesthe RV32E subset variant of the RV32I base instruction set, which has been added to supportsmall microcontrollers, and which has half the number of integer registers. Chapter6sketches afuture RV128I variant of the base integer instruction set supporting a flat 128-bit address space(XLEN=128). The base integer instruction sets use a two’s-complement representation for signedinteger values.Although 64-bit address spaces are a requirement for larger systems, we believe 32-bit addressspaces will remain adequate for many embedded and client devices for decades to come and willbe desirable to lower memory tra c and energy consumption. In addition, 32-bit address spacesare su cient for educational purposes. A larger flat 128-bit address space might eventually berequired, so we ensured this could be accommodated within the RISC-V ISA framework.The four base ISAs in RISC-V are treated as distinct base ISAs. A common question is whyis there not a single ISA, and in particular, why is RV32I not a strict subset of RV64I? Someearlier ISA designs (SPARC, MIPS) adopted a strict superset policy when increasing addressspace size to support running existing 32-bit binaries on new 64-bit hardware. The main advantage of explicitly separating base ISAs is that each base ISA can be opti-mized for its needs without requiring to support all the operations needed for other base ISAs.For example, RV64I can omit instructions and CSRs that are only needed to cope with the nar-rower registers in RV32I. The RV32I variants can use encoding space otherwise reserved forinstructions only required by wider address-space variants.The main disadvantage of not treating the design as a single ISA is that it complicatesthe hardware needed to emulate one base ISA on another (e.g., RV32I on RV64I). However,di↵erences in addressing and illegal instruction traps generally mean some mode switch wouldbe required in hardware in any case even with full superset instruction encodings, and the di↵erentRISC-V base ISAs are similar enough that supporting multiple versions is relatively low cost.Although some have proposed that the strict superset design would allow legacy 32-bit librariesto be linked with 64-bit code, this is impractical in practice, even with compatible encodings, dueto the di↵erences in software calling conventions and system-call interfaces.The RISC-V privileged architecture provides fields inmisato control the unprivileged ISA ateach level to support emulating di↵erent base ISAs on the same hardware. We note that newerSPARC and MIPS ISA revisions have deprecated support for running 32-bit code unchanged on64-bit systems.A related question is why there is a di↵erent encoding for 32-bit adds in RV32I (ADD) andRV64I (ADDW)? The ADDW opcode could be used for 32-bit adds in RV32I and ADDD for64-bit adds in RV64I, instead of the existing design which uses the same opcode ADD for 32-bit adds in RV32I and 64-bit adds in RV64I with a di↵erent opcode ADDW for 32-bit adds inRV64I. This would also be more consistent with the use of the same LW opcode for 32-bit loadin both RV32I and RV64I. The very first versions of RISC-V ISA did have a variant of thisalternate design, but the RISC-V design was changed to the current choice in January 2011.Our focus was on supporting 32-bit integers in the 64-bit ISA not on providing compatibilitywith the 32-bit ISA, and the motivation was to remove the asymmetry that arose from havingnot all opcodes in RV32I have a *W su x (e.g., ADDW, but AND not ANDW). In hindsight,this was perhaps not well-justified and a consequence of designing both ISAs at the same timeas opposed to adding one later to sit on top of another, and also from a belief we had to foldplatform requirements into the ISA spec which would imply that all the RV32I instructions wouldhave been required in RV64I. It is too late to change the encoding now, but this is also of littlepractical consequence for the reasons stated above.It has been noted we could enable the *W variants as an extension to RV32I systems toprovide a common encoding across RV64I and a future RV32 variant.RISC-V has been designed to support extensive customization and specialization. Each base integerISA can be extended with one or more optional instruction-set extensions, and we divide each RISC-V instruction-set encoding space (and related encoding spaces such as the CSRs) into three disjointcategories:standard,reserved, andcustom. Standard encodings are defined by the Foundation,and shall not conflict with other standard extensions for the same base ISA. Reserved encodingsare currently not defined but are saved for future standard extensions. We use the termnon-standardto describe an extension that is not defined by the Foundation. Custom encodings shallnever be used for standard extensions and are made available for vendor-specific non-standardextensions. We use the termnon-conformingto describe a non-standard extension that uses eithera standard or a reserved encoding (i.e., custom extensions arenotnon-conforming). Instruction-setextensions are generally shared but may provide slightly di↵erent functionality depending on thebase ISA. Chapter26describes various ways of extending the RISC-V ISA. We have also developeda naming convention for RISC-V base instructions and instruction-set extensions, described indetail in Chapter27.To support more general software development, a set of standard extensions are defined to provideinteger multiply/divide, atomic operations, and single and double-precision floating-point arithmetic. The base integer ISA is named “I” (prefixed by RV32 or RV64 depending on integer registerwidth), and contains integer computational instructions, integer loads, integer stores, and control-flow instructions. The standard integer multiplication and division extension is named “M”, andadds instructions to multiply and divide values held in the integer registers. The standard atomicinstruction extension, denoted by “A”, adds instructions that atomically read, modify, and writememory for inter-processor synchronization. The standard single-precision floating-point exten-sion, denoted by “F”, adds floating-point registers, single-precision computational instructions, andsingle-precision loads and stores. The standard double-precision floating-point extension, denotedby “D”, expands the floating-point registers, and adds double-precision computational instruc-tions, loads, and stores. The standard “C” compressed instruction extension provides narrower16-bit forms of common instructions.Beyond the base integer ISA and the standard GC extensions, we believe it is rare that a newinstruction will provide a significant benefit for all applications, although it may be very beneficialfor a certain domain. As energy e ciency concerns are forcing greater specialization, we believe itis important to simplify the required portion of an ISA specification. Whereas other architecturesusually treat their ISA as a single entity, which changes to a new version as instructions are addedover time, RISC-V will endeavor to keep the base and each standard extension constant over time,and instead layer new instructions as further optional extensions. For example, the base integerISAs will continue as fully supported standalone ISAs, regardless of any subsequent extensions. |
2023-07-18T10:37:52.212436 | segment4 | 1.4 Memory | RV32ISPEC.pdf#segment4 | [] | 1.4 Memory A RISC-V hart has a single byte-addressable address space of 2XLENbytes for all memory accesses.Awordof memory is defined as 32 bits (4 bytes). Correspondingly, ahalfwordis 16 bits (2 bytes), adoublewordis 64 bits (8 bytes), and aquadwordis 128 bits (16 bytes). The memory address space iscircular, so that the byte at address 2XLEN 1 is adjacent to the byte at address zero. Accordingly,memory address computations done by the hardware ignore overflow and instead wrap aroundmodulo 2XLEN.The execution environment determines the mapping of hardware resources into a hart’s addressspace. Di↵erent address ranges of a hart’s address space may (1) be vacant, or (2) containmainmemory, or (3) contain one or moreI/O devices. Reads and writes of I/O devices may havevisible side e↵ects, but accesses to main memory cannot. Although it is possible for the executionenvironment to call everything in a hart’s address space an I/O device, it is usually expected thatsome portion will be specified as main memory.When a RISC-V platform has multiple harts, the address spaces of any two harts may be entirelythe same, or entirely di↵erent, or may be partly di↵erent but sharing some subset of resources,mapped into the same or di↵erent address ranges.For a purely “bare metal” environment, all harts may see an identical address space, accessedentirely by physical addresses. However, when the execution environment includes an operatingsystem employing address translation, it is common for each hart to be given a virtual addressspace that is largely or entirely its own. Executing each RISC-V machine instruction entails one or more memory accesses, subdivided intoimplicitandexplicitaccesses. For each instruction executed, animplicitmemory read (instructionfetch) is done to obtain the encoded instruction to execute. Many RISC-V instructions performno further memory accesses beyond instruction fetch. Specific load and store instructions performanexplicitread or write of memory at an address determined by the instruction. The executionenvironment may dictate that instruction execution performs otherimplicitmemory accesses (suchas to implement address translation) beyond those documented for the unprivileged ISA.The execution environment determines what portions of the non-vacant address space are accessiblefor each kind of memory access. For example, the set of locations that can be implicitly read forinstruction fetch may or may not have any overlap with the set of locations that can be explicitlyread by a load instruction; and the set of locations that can be explicitly written by a storeinstruction may be only a subset of locations that can be read. Ordinarily, if an instructionattempts to access memory at an inaccessible address, an exception is raised for the instruction.Vacant locations in the address space are never accessible.Except when specified otherwise, implicit reads that do not raise an exception and that have noside e↵ects may occur arbitrarily early and speculatively, even before the machine could possiblyprove that the read will be needed. For instance, a valid implementation could attempt to read allof main memory at the earliest opportunity, cache as many fetchable (executable) bytes as possiblefor later instruction fetches, and avoid reading main memory for instruction fetches ever again.To ensure that certain implicit reads are ordered only after writes to the same memory locations,software must execute specific fence or cache-control instructions defined for this purpose (such asthe FENCE.I instruction defined in Chapter3).The memory accesses (implicit or explicit) made by a hart may appear to occur in a di↵erent orderas perceived by another hart or by any other agent that can access the same memory. This perceivedreordering of memory accesses is always constrained, however, by the applicable memory consistencymodel. The default memory consistency model for RISC-V is the RISC-V Weak Memory Ordering(RVWMO), defined in Chapter14and in appendices. Optionally, an implementation may adoptthe stronger model of Total Store Ordering, as defined in Chapter23. The execution environmentmay also add constraints that further limit the perceived reordering of memory accesses. Since theRVWMO model is the weakest model allowed for any RISC-V implementation, software written forthis model is compatible with the actual memory consistency rules of all RISC-V implementations.As with implicit reads, software must execute fence or cache-control instructions to ensure specificordering of memory accesses beyond the requirements of the assumed memory consistency modeland execution environment. |
2023-07-18T10:37:52.212565 | segment5 | 1.5 Base Instruction-Length Encoding | RV32ISPEC.pdf#segment5 | [] | 1.5 Base Instruction-Length Encoding The base RISC-V ISA has fixed-length 32-bit instructions that must be naturally aligned on 32-bitboundaries. However, the standard RISC-V encoding scheme is designed to support ISA extensionswith variable-length instructions, where each instruction can be any number of 16-bit instructionparcelsin length and parcels are naturally aligned on 16-bit boundaries. The standard compressedISA extension described in Chapter16reduces code size by providing compressed 16-bit instructionsand relaxes the alignment constraints to allow all instructions (16 bit and 32 bit) to be aligned onany 16-bit boundary to improve code density. We use the term IALIGN (measured in bits) to refer to the instruction-address alignment constraintthe implementation enforces. IALIGN is 32 bits in the base ISA, but some ISA extensions, includingthe compressed ISA extension, relax IALIGN to 16 bits. IALIGN may not take on any value otherthan 16 or 32.We use the term ILEN (measured in bits) to refer to the maximum instruction length supportedby an implementation, and which is always a multiple of IALIGN. For implementations supportingonly a base instruction set, ILEN is 32 bits. Implementations supporting longer instructions havelarger values of ILEN.Figure1.1illustrates the standard RISC-V instruction-length encoding convention. All the 32-bitinstructions in the base ISA have their lowest two bits set to11. The optional compressed 16-bitinstruction-set extensions have their lowest two bits equal to00,01, or10.Expanded Instruction-Length EncodingA portion of the 32-bit instruction-encoding space has been tentatively allocated for instructionslonger than 32 bits. The entirety of this space is reserved at this time, and the following proposalfor encoding instructions longer than 32 bits is not considered frozen.Standard instruction-set extensions encoded with more than 32 bits have additional low-order bitsset to1, with the conventions for 48-bit and 64-bit lengths shown in Figure1.1. Instruction lengthsbetween 80 bits and 176 bits are encoded using a 3-bit field in bits [14:12] giving the number of16-bit words in addition to the first 5⇥16-bit words. The encoding with bits [14:12] set to111isreserved for future longer instruction encodings.xxxxxxxxxxxxxxaa16-bit (aa6=11)xxxxxxxxxxxxxxxxxxxxxxxxxxxbbb1132-bit (bbb6=111)···xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx01111148-bit···xxxxxxxxxxxxxxxxxxxxxxxxxxxxx011111164-bit···xxxxxxxxxxxxxxxxxxxxxnnnxxxxx1111111(80+16*nnn)-bit,nnn6=111···xxxxxxxxxxxxxxxxxxxxx111xxxxx1111111Reserved for 192-bitsByte Address: base+4 base+2 baseFigure 1.1: RISC-V instruction length encoding. Only the 16-bit and 32-bit encodings are consid-ered frozen at this time.Given the code size and energy savings of a compressed format, we wanted to build in supportfor a compressed format to the ISA encoding scheme rather than adding this as an afterthought,but to allow simpler implementations we didn’t want to make the compressed format mandatory.We also wanted to optionally allow longer instructions to support experimentation and larger instruction-set extensions. Although our encoding convention required a tighter encoding of thecore RISC-V ISA, this has several beneficial e↵ects.An implementation of the standard IMAFD ISA need only hold the most-significant 30 bits ininstruction caches (a 6.25% saving). On instruction cache refills, any instructions encounteredwith either low bit clear should be recoded into illegal 30-bit instructions before storing in thecache to preserve illegal instruction exception behavior.Perhaps more importantly, by condensing our base ISA into a subset of the 32-bit instructionword, we leave more space available for non-standard and custom extensions. In particular,the base RV32I ISA uses less than 1/8 of the encoding space in the 32-bit instruction word.As described in Chapter26, an implementation that does not require support for the standardcompressed instruction extension can map 3 additional non-conforming 30-bit instruction spacesinto the 32-bit fixed-width format, while preserving support for standard 32-bit instruction-setextensions. Further, if the implementation also does not need instructions>32-bits in length, itcan recover a further four major opcodes for non-conforming extensions.Encodings with bits [15:0] all zeros are defined as illegal instructions. These instructions are con-sidered to be of minimal length: 16 bits if any 16-bit instruction-set extension is present, otherwise32 bits. The encoding with bits [ILEN-1:0] all ones is also illegal; this instruction is considered tobe ILEN bits long.We consider it a feature that any length of instruction containing all zero bits is not legal, asthis quickly traps erroneous jumps into zeroed memory regions. Similarly, we also reserve theinstruction encoding containing all ones to be an illegal instruction, to catch the other commonpattern observed with unprogrammed non-volatile memory devices, disconnected memory buses,or broken memory devices.Software can rely on a naturally aligned 32-bit word containing zero to act as an illegalinstruction on all RISC-V implementations, to be used by software where an illegal instructionis explicitly desired. Defining a corresponding known illegal value for all ones is more di cultdue to the variable-length encoding. Software cannot generally use the illegal value of ILEN bitsof all 1s, as software might not know ILEN for the eventual target machine (e.g., if softwareis compiled into a standard binary library used by many di↵erent machines). Defining a 32-bitword of all ones as illegal was also considered, as all machines must support a 32-bit instructionsize, but this requires the instruction-fetch unit on machines with ILEN>32 report an illegalinstruction exception rather than access fault when such an instruction borders a protectionboundary, complicating variable-instruction-length fetch and decode.RISC-V base ISAs have either little-endian or big-endian memory systems, with the privilegedarchitecture further defining bi-endian operation. Instructions are stored in memory as a sequenceof 16-bit little-endian parcels, regardless of memory system endianness. Parcels forming one in-struction are stored at increasing halfword addresses, with the lowest-addressed parcel holding thelowest-numbered bits in the instruction specification.We originally chose little-endian byte ordering for the RISC-V memory system because little-endian systems are currently dominant commercially (all x86 systems; iOS, Android, and Win-dows for ARM). A minor point is that we have also found little-endian memory systems to bemore natural for hardware designers. However, certain application areas, such as IP networking,operate on big-endian data structures, and certain legacy code bases have been built assumingbig-endian processors, so we have defined big-endian and bi-endian variants of RISC-V.We have to fix the order in which instruction parcels are stored in memory, independentof memory system endianness, to ensure that the length-encoding bits always appear first inhalfword address order. This allows the length of a variable-length instruction to be quickly determined by an instruction-fetch unit by examining only the first few bits of the first 16-bitinstruction parcel.We further make the instruction parcels themselves little-endian to decouple the instructionencoding from the memory system endianness altogether. This design benefits both softwaretooling and bi-endian hardware. Otherwise, for instance, a RISC-V assembler or disassemblerwould always need to know the intended active endianness, despite that in bi-endian systems, theendianness mode might change dynamically during execution. In contrast, by giving instructionsa fixed endianness, it is sometimes possible for carefully written software to be endianness-agnostic even in binary form, much like position-independent code.The choice to have instructions be only little-endian does have consequences, however, forRISC-V software that encodes or decodes machine instructions. Big-endian JIT compilers, forexample, must swap the byte order when storing to instruction memory.Once we had decided to fix on a little-endian instruction encoding, this naturally led toplacing the length-encoding bits in the LSB positions of the instruction format to avoid breakingup opcode fields. |
2023-07-18T10:37:52.212748 | segment6 | 1.6 Exceptions, Traps, and Interrupts | RV32ISPEC.pdf#segment6 | [] | 1.6 Exceptions, Traps, and Interrupts We use the termexceptionto refer to an unusual condition occurring at run time associated withan instruction in the current RISC-V hart. We use the terminterruptto refer to an externalasynchronous event that may cause a RISC-V hart to experience an unexpected transfer of control.We use the termtrapto refer to the transfer of control to a trap handler caused by either anexception or an interrupt.The instruction descriptions in following chapters describe conditions that can raise an exceptionduring execution. The general behavior of most RISC-V EEIs is that a trap to some handler occurswhen an exception is signaled on an instruction (except for floating-point exceptions, which, inthe standard floating-point extensions, do not cause traps). The manner in which interrupts aregenerated, routed to, and enabled by a hart depends on the EEI.Our use of “exception” and “trap” is compatible with that in the IEEE-754 floating-point stan-dard.How traps are handled and made visible to software running on the hart depends on the enclosingexecution environment. From the perspective of software running inside an execution environment,traps encountered by a hart at runtime can have four di↵erent e↵ects:Contained Trap:The trap is visible to, and handled by, software running inside the executionenvironment. For example, in an EEI providing both supervisor and user mode on harts,an ECALL by a user-mode hart will generally result in a transfer of control to a supervisor-mode handler running on the same hart. Similarly, in the same environment, when a hart isinterrupted, an interrupt handler will be run in supervisor mode on the hart.Requested Trap:The trap is a synchronous exception that is an explicit call to the executionenvironment requesting an action on behalf of software inside the execution environment. Anexample is a system call. In this case, execution may or may not resume on the hart afterthe requested action is taken by the execution environment. For example, a system call couldremove the hart or cause an orderly termination of the entire execution environment. Invisible Trap:The trap is handled transparently by the execution environment and executionresumes normally after the trap is handled. Examples include emulating missing instructions,handling non-resident page faults in a demand-paged virtual-memory system, or handlingdevice interrupts for a di↵erent job in a multiprogrammed machine. In these cases, thesoftware running inside the execution environment is not aware of the trap (we ignore timinge↵ects in these definitions).Fatal Trap:The trap represents a fatal failure and causes the execution environment to terminateexecution. Examples include failing a virtual-memory page-protection check or allowing awatchdog timer to expire. Each EEI should define how execution is terminated and reportedto an external environment.The following table shows the characteristics of each kind of trap:ContainedRequestedInvisibleFatalExecution terminates?NN1NYSoftware is oblivious?NNYY2Handled by environment?NYYYTable 1.1: Characteristics of traps. Notes: 1) termination may be requested; 2) imprecise fataltraps might be observable by software.The EEI defines for each trap whether it is handled precisely, though the recommendation is tomaintain preciseness where possible. Contained and requested traps can be observed to be impreciseby software inside the execution environment. Invisible traps, by definition, cannot be observed tobe precise or imprecise by software running inside the execution environment. Fatal traps can beobserved to be imprecise by software running inside the execution environment, if known-errorfulinstructions do not cause immediate termination.Because this document describes unprivileged instructions, traps are rarely mentioned. Architec-tural means to handle contained traps are defined in the privileged architecture manual, along withother features to support richer EEIs. Unprivileged instructions that are defined solely to causerequested traps are documented here. Invisible traps are, by their nature, out of scope for thisdocument. Instruction encodings that are not defined here and not defined by some other meansmay cause a fatal trap. |
2023-07-18T10:37:52.212935 | segment7 | 1.7 UNSPECIFIED Behaviors and Values | RV32ISPEC.pdf#segment7 | [] | 1.7 UNSPECIFIED Behaviors and Values The architecture fully describes what implementations must do and any constraints on what theymay do. In cases where the architecture intentionally does not constrain implementations, the termunspecifiedis explicitly used.The termunspecifiedrefers to a behavior or value that is intentionally unconstrained. Thedefinition of these behaviors or values is open to extensions, platform standards, or implementations.Extensions, platform standards, or implementation documentation may provide normative contentto further constrain cases that the base architecture defines asunspecified.Like the base architecture, extensions should fully describe allowable behavior and values anduse the termunspecifiedfor cases that are intentionally unconstrained. These cases may beconstrained or defined by other extensions, platform standards, or implementations. |
2023-07-18T10:37:52.213045 | segment8 | 2 RV32I Base Integer Instruction Set,Version 2.1 | RV32ISPEC.pdf#segment8 | [] | 2 RV32I Base Integer Instruction Set,Version 2.1 This chapter describes version 2.0 of the RV32I base integer instruction set.RV32I was designed to be su cient to form a compiler target and to support modern operatingsystem environments. The ISA was also designed to reduce the hardware required in a minimalimplementation. RV32I contains 40 unique instructions, though a simple implementation mightcover the ECALL/EBREAK instructions with a single SYSTEM hardware instruction that al-ways traps and might be able to implement the FENCE instruction as a NOP, reducing baseinstruction count to 38 total. RV32I can emulate almost any other ISA extension (except the Aextension, which requires additional hardware support for atomicity).In practice, a hardware implementation including the machine-mode privileged architecturewill also require the 6 CSR instructions.Subsets of the base integer ISA might be useful for pedagogical purposes, but the base hasbeen defined such that there should be little incentive to subset a real hardware implementationbeyond omitting support for misaligned memory accesses and treating all SYSTEM instructionsas a single trap.Most of the commentary for RV32I also applies to the RV64I base. |
2023-07-18T10:37:52.213229 | segment9 | 2.1 Programmers' Model for Base Integer ISA | RV32ISPEC.pdf#segment9 | [] | 2.1 Programmers’ Model for Base Integer ISA Figure2.1shows the unprivileged state for the base integer ISA. For RV32I, the 32xregistersare each 32 bits wide, i.e., XLEN=32. Registerx0is hardwired with all bits equal to 0. Generalpurpose registersx1–x31hold values that various instructions interpret as a collection of Booleanvalues, or as two’s complement signed binary integers or unsigned binary integers.There is one additional unprivileged register: the program counterpcholds the address of thecurrent instruction.XLEN-1 0x0 / zerox1x2x3x4x5x6x7x8x9x10x11x12x13x14x15x16x17x18x19x20x21x22x23x24x25x26x27x28x29x30x31XLENXLEN-1 0pcXLENFigure 2.1: RISC-V base unprivileged integer register state.There is no dedicated stack pointer or subroutine return address link register in the Base IntegerISA; the instruction encoding allows anyxregister to be used for these purposes. However, thestandard software calling convention uses registerx1to hold the return address for a call, withregisterx5available as an alternate link register. The standard calling convention uses registerx2as the stack pointer.Hardware might choose to accelerate function calls and returns that usex1orx5.S e e t h edescriptions of the JAL and JALR instructions.The optional compressed 16-bit instruction format is designed around the assumption thatx1is the return address register andx2is the stack pointer. Software using other conventionswill operate correctly but may have greater code size.The number of available architectural registers can have large impacts on code size, performance,and energy consumption. Although 16 registers would arguably be su cient for an integer ISArunning compiled code, it is impossible to encode a complete ISA with 16 registers in 16-bit instructions using a 3-address format. Although a 2-address format would be possible, it wouldincrease instruction count and lower e ciency. We wanted to avoid intermediate instructionsizes (such as Xtensa’s 24-bit instructions) to simplify base hardware implementations, and oncea 32-bit instruction size was adopted, it was straightforward to support 32 integer registers. Alarger number of integer registers also helps performance on high-performance code, where therecan be extensive use of loop unrolling, software pipelining, and cache tiling.For these reasons, we chose a conventional size of 32 integer registers for the base ISA. Dy-namic register usage tends to be dominated by a few frequently accessed registers, and regfile im-plementations can be optimized to reduce access energy for the frequently accessed registers [20].The optional compressed 16-bit instruction format mostly only accesses 8 registers and hence canprovide a dense instruction encoding, while additional instruction-set extensions could supporta much larger register space (either flat or hierarchical) if desired.For resource-constrained embedded applications, we have defined the RV32E subset, whichonly has 16 registers (Chapter4). |
2023-07-18T10:37:52.213418 | segment10 | 2.2 Base Instruction Formats | RV32ISPEC.pdf#segment10 | [] | 2.2 Base Instruction Formats In the base RV32I ISA, there are four core instruction formats (R/I/S/U), as shown in Figure2.2.All are a fixed 32 bits in length and must be aligned on a four-byte boundary in memory. Aninstruction-address-misaligned exception is generated on a taken branch or unconditional jumpif the target address is not four-byte aligned. This exception is reported on the branch or jumpinstruction, not on the target instruction. No instruction-address-misaligned exception is generatedfor a conditional branch that is not taken.The alignment constraint for base ISA instructions is relaxed to a two-byte boundary wheninstruction extensions with 16-bit lengths or other odd multiples of 16-bit lengths are added(i.e., IALIGN=16).Instruction-address-misaligned exceptions are reported on the branch or jump that wouldcause instruction misalignment to help debugging, and to simplify hardware design for systemswith IALIGN=32, where these are the only places where misalignment can occur.The behavior upon decoding a reserved instruction isunspecified.Some platforms may require that opcodes reserved for standard use raise an illegal-instructionexception. Other platforms may permit reserved opcode space be used for non-conforming exten-sions.The RISC-V ISA keeps the source (rs1andrs2) and destination (rd) registers at the same positionin all formats to simplify decoding. Except for the 5-bit immediates used in CSR instructions(Chapter9), immediates are always sign-extended, and are generally packed towards the leftmostavailable bits in the instruction and have been allocated to reduce hardware complexity. In partic-ular, the sign bit for all immediates is always in bit 31 of the instruction to speed sign-extensioncircuitry.Decoding register specifiers is usually on the critical paths in implementations, and so the in-struction format was chosen to keep all register specifiers at the same position in all formats atthe expense of having to move immediate bits across formats (a property shared with RISC-IVaka. SPUR [11]). 31 25 24 20 19 15 14 12 11 7 6 0funct7rs2rs1funct3rdopcodeR-typeimm[11:0]rs1funct3rdopcodeI-typeimm[11:5]rs2rs1funct3imm[4:0]opcodeS-typeimm[31:12]rdopcodeU-typeFigure 2.2: RISC-V base instruction formats. Each immediate subfield is labeled with the bitposition (imm[x]) in the immediate value being produced, rather than the bit position within theinstruction’s immediate field as is usually done.In practice, most immediates are either small or require all XLEN bits. We chose an asym-metric immediate split (12 bits in regular instructions plus a special load-upper-immediate in-struction with 20 bits) to increase the opcode space available for regular instructions.Immediates are sign-extended because we did not observe a benefit to using zero-extensionfor some immediates as in the MIPS ISA and wanted to keep the ISA as simple as possible. |
2023-07-18T10:37:52.213598 | segment11 | 2.3 Immediate Encoding Variants | RV32ISPEC.pdf#segment11 | [] | 2.3 Immediate Encoding Variants There are a further two variants of the instruction formats (B/J) based on the handling of imme-diates, as shown in Figure2.3.31 30 25 24 21 20 19 15 14 12 11 8 7 6 0funct7rs2rs1funct3rdopcodeR-typeimm[11:0]rs1funct3rdopcodeI-typeimm[11:5]rs2rs1funct3imm[4:0]opcodeS-typeimm[12]imm[10:5]rs2rs1funct3imm[4:1]imm[11]opcodeB-typeimm[31:12]rdopcodeU-typeimm[20]imm[10:1]imm[11]imm[19:12]rdopcodeJ-typeFigure 2.3: RISC-V base instruction formats showing immediate variants.The only di↵erence between the S and B formats is that the 12-bit immediate field is used to encodebranch o↵sets in multiples of 2 in the B format. Instead of shifting all bits in the instruction-encodedimmediate left by one in hardware as is conventionally done, the middle bits (imm[10:1]) and signbit stay in fixed positions, while the lowest bit in S format (inst[7]) encodes a high-order bit in Bformat. Similarly, the only di↵erence between the U and J formats is that the 20-bit immediate is shiftedleft by 12 bits to form U immediates and by 1 bit to form J immediates. The location of instructionbits in the U and J format immediates is chosen to maximize overlap with the other formats andwith each other.Figure2.4shows the immediates produced by each of the base instruction formats, and is labeledto show which instruction bit (inst[y]) produces each bit of the immediate value.31 30 20 19 12 11 10 5 4 1 0— inst[31] —inst[30:25]inst[24:21]inst[20]I-immediate— inst[31] —inst[30:25]inst[11:8]inst[7]S-immediate— inst[31] —inst[7]inst[30:25]inst[11:8]0B-immediateinst[31]inst[30:20]inst[19:12]—0—U-immediate— inst[31] —inst[19:12]inst[20]inst[30:25]inst[24:21]0J-immediateFigure 2.4: Types of immediate produced by RISC-V instructions. The fields are labeled with theinstruction bits used to construct their value. Sign extension always uses inst[31].Sign-extension is one of the most critical operations on immediates (particularly for XLEN>32),and in RISC-V the sign bit for all immediates is always held in bit 31 of the instruction to allowsign-extension to proceed in parallel with instruction decoding.Although more complex implementations might have separate adders for branch and jumpcalculations and so would not benefit from keeping the location of immediate bits constant acrosstypes of instruction, we wanted to reduce the hardware cost of the simplest implementations. Byrotating bits in the instruction encoding of B and J immediates instead of using dynamic hard-ware muxes to multiply the immediate by 2, we reduce instruction signal fanout and immediatemux costs by around a factor of 2. The scrambled immediate encoding will add negligible timeto static or ahead-of-time compilation. For dynamic generation of instructions, there is somesmall additional overhead, but the most common short forward branches have straightforwardimmediate encodings. |
2023-07-18T10:37:52.213692 | segment12 | 2.4 Integer Computational Instructions | RV32ISPEC.pdf#segment12 | [] | 2.4 Integer Computational Instructions Most integer computational instructions operate on XLEN bits of values held in the integer registerfile. Integer computational instructions are either encoded as register-immediate operations usingthe I-type format or as register-register operations using the R-type format. The destination isregisterrdfor both register-immediate and register-register instructions. No integer computationalinstructions cause arithmetic exceptions.We did not include special instruction-set support for overflow checks on integer arithmeticoperations in the base instruction set, as many overflow checks can be cheaply implemented using RISC-V branches. Overflow checking for unsigned addition requires only a single additionalbranch instruction after the addition:add t0, t1, t2; bltu t0, t1, overflow.For signed addition, if one operand’s sign is known, overflow checking requires only a singlebranch after the addition:addi t0, t1, +imm; blt t0, t1, overflow. This covers thecommon case of addition with an immediate operand.For general signed addition, three additional instructions after the addition are required,leveraging the observation that the sum should be less than one of the operands if and only if theother operand is negative.add t0, t1, t2slti t3, t2, 0slt t4, t0, t1bne t3, t4, overflowIn RV64I, checks of 32-bit signed additions can be optimized further by comparing the results ofADD and ADDW on the operands.Integer Register-Immediate Instructions31 20 19 15 14 12 11 7 6 0imm[11:0]rs1funct3rdopcode12 5 3 5 7I-immediate[11:0] src ADDI/SLTI[U] dest OP-IMMI-immediate[11:0] src ANDI/ORI/XORI dest OP-IMMADDI adds the sign-extended 12-bit immediate to registerrs1. Arithmetic overflow is ignored andthe result is simply the low XLEN bits of the result. ADDIrd, rs1, 0is used to implement the MVrd, rs1assembler pseudoinstruction.SLTI (set less than immediate) places the value 1 in registerrdif registerrs1is less than the sign-extended immediate when both are treated as signed numbers, else 0 is written tord.S L T I U i ssimilar but compares the values as unsigned numbers (i.e., the immediate is first sign-extended toXLEN bits then treated as an unsigned number). Note, SLTIUrd, rs1, 1setsrdto 1 ifrs1equalszero, otherwise setsrdto 0 (assembler pseudoinstruction SEQZrd, rs).ANDI, ORI, XORI are logical operations that perform bitwise AND, OR, and XOR on registerrs1and the sign-extended 12-bit immediate and place the result inrd. Note, XORIrd, rs1, -1performsa bitwise logical inversion of registerrs1(assembler pseudoinstruction NOTrd, rs).31 25 24 20 19 15 14 12 11 7 6 0imm[11:5]imm[4:0]rs1funct3rdopcode75 535 70000000 shamt[4:0] src SLLI dest OP-IMM0000000 shamt[4:0] src SRLI dest OP-IMM0100000 shamt[4:0] src SRAI dest OP-IMMShifts by a constant are encoded as a specialization of the I-type format. The operand to be shiftedis inrs1, and the shift amount is encoded in the lower 5 bits of the I-immediate field. The rightshift type is encoded in bit 30. SLLI is a logical left shift (zeros are shifted into the lower bits); SRLI is a logical right shift (zeros are shifted into the upper bits); and SRAI is an arithmetic rightshift (the original sign bit is copied into the vacated upper bits).31 12 11 7 6 0imm[31:12]rdopcode20 5 7U-immediate[31:12] dest LUIU-immediate[31:12] dest AUIPCLUI (load upper immediate) is used to build 32-bit constants and uses the U-type format. LUIplaces the U-immediate value in the top 20 bits of the destination registerrd,fi l l i n gi nt h el o w e s t12 bits with zeros.AUIPC (add upper immediate topc)i su s e dt ob u i l dpc-relative addresses and uses the U-typeformat. AUIPC forms a 32-bit o↵set from the 20-bit U-immediate, filling in the lowest 12 bits withzeros, adds this o↵set to the address of the AUIPC instruction, then places the result in registerrd.The AUIPC instruction supports two-instruction sequences to access arbitrary o↵sets from thePC for both control-flow transfers and data accesses. The combination of an AUIPC and the12-bit immediate in a JALR can transfer control to any 32-bit PC-relative address, while anAUIPC plus the 12-bit immediate o↵set in regular load or store instructions can access any32-bit PC-relative data address.The current PC can be obtained by setting the U-immediate to 0. Although a JAL +4instruction could also be used to obtain the local PC (of the instruction following the JAL),it might cause pipeline breaks in simpler microarchitectures or pollute BTB structures in morecomplex microarchitectures.Integer Register-Register OperationsRV32I defines several arithmetic R-type operations. All operations read thers1andrs2registersas source operands and write the result into registerrd.T h efunct7andfunct3fields select thetype of operation.31 25 24 20 19 15 14 12 11 7 6 0funct7rs2rs1funct3rdopcode75 535 70000000 src2 src1 ADD/SLT/SLTU dest OP0000000 src2 src1 AND/OR/XOR dest OP0000000 src2 src1 SLL/SRL dest OP0100000 src2 src1 SUB/SRA dest OPADD performs the addition ofrs1andrs2. SUB performs the subtraction ofrs2fromrs1.O v e r fl o w sare ignored and the low XLEN bits of results are written to the destinationrd. SLT and SLTUperform signed and unsigned compares respectively, writing 1 tordifrs1<rs2, 0 otherwise. Note,SLTUrd,x0,rs2setsrdto 1 ifrs2is not equal to zero, otherwise setsrdto zero (assemblerpseudoinstruction SNEZrd, rs). AND, OR, and XOR perform bitwise logical operations.SLL, SRL, and SRA perform logical left, logical right, and arithmetic right shifts on the value inregisterrs1by the shift amount held in the lower 5 bits of registerrs2.NOP Instruction31 20 19 15 14 12 11 7 6 0imm[11:0]rs1funct3rdopcode12 5 3 5 70 0 ADDI 0 OP-IMMThe NOP instruction does not change any architecturally visible state, except for advancing thepcand incrementing any applicable performance counters. NOP is encoded as ADDIx0, x0, 0.NOPs can be used to align code segments to microarchitecturally significant address boundaries,or to leave space for inline code modifications. Although there are many possible ways to encodea NOP, we define a canonical NOP encoding to allow microarchitectural optimizations as well asfor more readable disassembly output. The other NOP encodings are made available for HINTinstructions (Section2.9).ADDI was chosen for the NOP encoding as this is most likely to take fewest resources toexecute across a range of systems (if not optimized away in decode). In particular, the instructiononly reads one register. Also, an ADDI functional unit is more likely to be available in asuperscalar design as adds are the most common operation. In particular, address-generationfunctional units can execute ADDI using the same hardware needed for base+o↵set addresscalculations, while register-register ADD or logical/shift operations require additional hardware. |
2023-07-18T10:37:52.213884 | segment13 | 2.5 Control Transfer Instructions | RV32ISPEC.pdf#segment13 | [] | 2.5 Control Transfer Instructions RV32I provides two types of control transfer instructions: unconditional jumps and conditionalbranches. Control transfer instructions in RV32I donothave architecturally visible delay slots.Unconditional JumpsThe jump and link (JAL) instruction uses the J-type format, where the J-immediate encodes asigned o↵set in multiples of 2 bytes. The o↵set is sign-extended and added to the address of thejump instruction to form the jump target address. Jumps can therefore target a±1 MiB range.JAL stores the address of the instruction following the jump (pc+4) into registerrd. The standardsoftware calling convention usesx1as the return address register andx5as an alternate link register.The alternate link register supports calling millicode routines (e.g., those to save and restoreregisters in compressed code) while preserving the regular return address register. The registerx5was chosen as the alternate link register as it maps to a temporary in the standard callingconvention, and has an encoding that is only one bit di↵erent than the regular link register. Plain unconditional jumps (assembler pseudoinstruction J) are encoded as a JAL withrd=x0.31 30 21 20 19 12 11 7 6 0imm[20]imm[10:1]imm[11]imm[19:12]rdopcode1 10 1 8 5 7o↵set[20:1] dest JALThe indirect jump instruction JALR (jump and link register) uses the I-type encoding. The targetaddress is obtained by adding the sign-extended 12-bit I-immediate to the registerrs1,t h e ns e t t i n gthe least-significant bit of the result to zero. The address of the instruction following the jump(pc+4) is written to registerrd. Registerx0can be used as the destination if the result is notrequired.31 20 19 15 14 12 11 7 6 0imm[11:0]rs1funct3rdopcode12 5 3 5 7o↵set[11:0] base 0 dest JALRThe unconditional jump instructions all use PC-relative addressing to help support position-independent code. The JALR instruction was defined to enable a two-instruction sequence tojump anywhere in a 32-bit absolute address range. A LUI instruction can first loadrs1with theupper 20 bits of a target address, then JALR can add in the lower bits. Similarly, AUIPC thenJALR can jump anywhere in a 32-bitpc-relative address range.Note that the JALR instruction does not treat the 12-bit immediate as multiples of 2 bytes,unlike the conditional branch instructions. This avoids one more immediate format in hardware.In practice, most uses of JALR will have either a zero immediate or be paired with a LUI orAUIPC, so the slight reduction in range is not significant.Clearing the least-significant bit when calculating the JALR target address both simplifiesthe hardware slightly and allows the low bit of function pointers to be used to store auxiliaryinformation. Although there is potentially a slight loss of error checking in this case, in practicejumps to an incorrect instruction address will usually quickly raise an exception.When used with a basers1=x0, JALR can be used to implement a single instruction subrou-tine call to the lowest 2 KiB or highest 2 KiB address region from anywhere in the address space,which could be used to implement fast calls to a small runtime library. Alternatively, an ABIcould dedicate a general-purpose register to point to a library elsewhere in the address space.The JAL and JALR instructions will generate an instruction-address-misaligned exception if thetarget address is not aligned to a four-byte boundary.Instruction-address-misaligned exceptions are not possible on machines that support extensionswith 16-bit aligned instructions, such as the compressed instruction-set extension, C.Return-address prediction stacks are a common feature of high-performance instruction-fetch units,but require accurate detection of instructions used for procedure calls and returns to be e↵ective.For RISC-V, hints as to the instructions’ usage are encoded implicitly via the register numbersused. A JAL instruction should push the return address onto a return-address stack (RAS) onlywhenrd=x1/x5. JALR instructions should push/pop a RAS as shown in the Table2.1.Some other ISAs added explicit hint bits to their indirect-jump instructions to guide return-address stack manipulation. We use implicit hinting tied to register numbers and the callingconvention to reduce the encoding space used for these hints. rdrs1rs1=rdRAS action!link!link-none!linklink-poplink!link-pushlinklink0pop, then pushlinklink1pushTable 2.1: Return-address stack prediction hints encoded in register specifiers used in the instruc-tion. In the above,linkis true when the register is eitherx1orx5.When two di↵erent link registers (x1andx5) are given asrs1andrd, then the RASis both popped and pushed to support coroutines. Ifrs1andrdare the same link regis-ter (eitherx1orx5), the RAS is only pushed to enable macro-op fusion of the sequences:lui ra, imm20; jalr ra, imm12(ra)andauipc ra, imm20; jalr ra, imm12(ra)Conditional BranchesAll branch instructions use the B-type instruction format. The 12-bit B-immediate encodes signedo↵sets in multiples of 2 bytes. The o↵set is sign-extended and added to the address of the branchinstruction to give the target address. The conditional branch range is±4K i B .31 30 25 24 20 19 15 14 12 11 8 7 6 0imm[12]imm[10:5]rs2rs1funct3imm[4:1]imm[11]opcode16 5 5 34 1 7o↵set[12|10:5] src2 src1 BEQ/BNE o↵set[11|4:1] BRANCHo↵set[12|10:5] src2 src1 BLT[U] o↵set[11|4:1] BRANCHo↵set[12|10:5] src2 src1 BGE[U] o↵set[11|4:1] BRANCHBranch instructions compare two registers. BEQ and BNE take the branch if registersrs1andrs2are equal or unequal respectively. BLT and BLTU take the branch ifrs1is less thanrs2,u s i n gsigned and unsigned comparison respectively. BGE and BGEU take the branch ifrs1is greaterthan or equal tors2, using signed and unsigned comparison respectively. Note, BGT, BGTU,BLE, and BLEU can be synthesized by reversing the operands to BLT, BLTU, BGE, and BGEU,respectively.Signed array bounds may be checked with a single BLTU instruction, since any negative indexwill compare greater than any nonnegative bound.Software should be optimized such that the sequential code path is the most common path, withless-frequently taken code paths placed out of line. Software should also assume that backwardbranches will be predicted taken and forward branches as not taken, at least the first time they areencountered. Dynamic predictors should quickly learn any predictable branch behavior.Unlike some other architectures, the RISC-V jump (JAL withrd=x0) instruction should alwaysbe used for unconditional branches instead of a conditional branch instruction with an always-true condition. RISC-V jumps are also PC-relative and support a much wider o↵set range thanbranches, and will not pollute conditional-branch prediction tables. The conditional branches were designed to include arithmetic comparison operations between tworegisters (as also done in PA-RISC, Xtensa, and MIPS R6), rather than use condition codes(x86, ARM, SPARC, PowerPC), or to only compare one register against zero (Alpha, MIPS),or two registers only for equality (MIPS). This design was motivated by the observation that acombined compare-and-branch instruction fits into a regular pipeline, avoids additional conditioncode state or use of a temporary register, and reduces static code size and dynamic instructionfetch tra c. Another point is that comparisons against zero require non-trivial circuit delay(especially after the move to static logic in advanced processes) and so are almost as expensive asarithmetic magnitude compares. Another advantage of a fused compare-and-branch instructionis that branches are observed earlier in the front-end instruction stream, and so can be predictedearlier. There is perhaps an advantage to a design with condition codes in the case where multiplebranches can be taken based on the same condition codes, but we believe this case to be relativelyrare.We considered but did not include static branch hints in the instruction encoding. Thesecan reduce the pressure on dynamic predictors, but require more instruction encoding space andsoftware profiling for best results, and can result in poor performance if production runs do notmatch profiling runs.We considered but did not include conditional moves or predicated instructions, which cane↵ectively replace unpredictable short forward branches. Conditional moves are the simpler ofthe two, but are di cult to use with conditional code that might cause exceptions (memoryaccesses and floating-point operations). Predication adds additional flag state to a system, addi-tional instructions to set and clear flags, and additional encoding overhead on every instruction.Both conditional move and predicated instructions add complexity to out-of-order microarchitec-tures, adding an implicit third source operand due to the need to copy the original value of thedestination architectural register into the renamed destination physical register if the predicateis false. Also, static compile-time decisions to use predication instead of branches can resultin lower performance on inputs not included in the compiler training set, especially given thatunpredictable branches are rare, and becoming rarer as branch prediction techniques improve.We note that various microarchitectural techniques exist to dynamically convert unpredictableshort forward branches into internally predicated code to avoid the cost of flushing pipelineson a branch mispredict [6,10,9] and have been implemented in commercial processors [17].The simplest techniques just reduce the penalty of recovering from a mispredicted short forwardbranch by only flushing instructions in the branch shadow instead of the entire fetch pipeline,or by fetching instructions from both sides using wide instruction fetch or idle instruction fetchslots. More complex techniques for out-of-order cores add internal predicates on instructions inthe branch shadow, with the internal predicate value written by the branch instruction, allowingthe branch and following instructions to be executed speculatively and out-of-order with respectto other code [17].The conditional branch instructions will generate an instruction-address-misaligned exception if thetarget address is not aligned to a four-byte boundary and the branch condition evaluates to true.If the branch condition evaluates to false, the instruction-address-misaligned exception will not beraised.Instruction-address-misaligned exceptions are not possible on machines that support extensionswith 16-bit aligned instructions, such as the compressed instruction-set extension, C. |
2023-07-18T10:37:52.214067 | segment14 | 2.6 Load and Store Instructions | RV32ISPEC.pdf#segment14 | [] | 2.6 Load and Store Instructions RV32I is a load-store architecture, where only load and store instructions access memory andarithmetic instructions only operate on CPU registers. RV32I provides a 32-bit address space thatis byte-addressed. The EEI will define what portions of the address space are legal to access withwhich instructions (e.g., some addresses might be read only, or support word access only). Loadswith a destination ofx0must still raise any exceptions and cause any other side e↵ects even thoughthe load value is discarded.The EEI will define whether the memory system is little-endian or big-endian. In RISC-V, endian-ness is byte-address invariant.In a system for which endianness is byte-address invariant, the following property holds: if abyte is stored to memory at some address in some endianness, then a byte-sized load from thataddress in any endianness returns the stored value.In a little-endian configuration, multibyte stores write the least-significant register byte atthe lowest memory byte address, followed by the other register bytes in ascending order of theirsignificance. Loads similarly transfer the contents of the lesser memory byte addresses to theless-significant register bytes.In a big-endian configuration, multibyte stores write the most-significant register byte at thelowest memory byte address, followed by the other register bytes in descending order of theirsignificance. Loads similarly transfer the contents of the greater memory byte addresses to theless-significant register bytes.31 20 19 15 14 12 11 7 6 0imm[11:0]rs1funct3rdopcode12 5 3 5 7o↵set[11:0] base width dest LOAD31 25 24 20 19 15 14 12 11 7 6 0imm[11:5]rs2rs1funct3imm[4:0]opcode75 5 3 57o↵set[11:5] src base width o↵set[4:0] STORELoad and store instructions transfer a value between the registers and memory. Loads are encodedin the I-type format and stores are S-type. The e↵ective address is obtained by adding registerrs1to the sign-extended 12-bit o↵set. Loads copy a value from memory to registerrd. Stores copy thevalue in registerrs2to memory.The LW instruction loads a 32-bit value from memory intord. LH loads a 16-bit value from memory,then sign-extends to 32-bits before storing inrd. LHU loads a 16-bit value from memory but thenzero extends to 32-bits before storing inrd. LB and LBU are defined analogously for 8-bit values.The SW, SH, and SB instructions store 32-bit, 16-bit, and 8-bit values from the low bits of registerrs2to memory.Regardless of EEI, loads and stores whose e↵ective addresses are naturally aligned shall not raisean address-misaligned exception. Loads and stores where the e↵ective address is not naturally aligned to the referenced datatype (i.e., on a four-byte boundary for 32-bit accesses, and a two-byteboundary for 16-bit accesses) have behavior dependent on the EEI.An EEI may guarantee that misaligned loads and stores are fully supported, and so the software run-ning inside the execution environment will never experience a contained or fatal address-misalignedtrap. In this case, the misaligned loads and stores can be handled in hardware, or via an invisibletrap into the execution environment implementation, or possibly a combination of hardware andinvisible trap depending on address.An EEI may not guarantee misaligned loads and stores are handled invisibly. In this case, loadsand stores that are not naturally aligned may either complete execution successfully or raise anexception. The exception raised can be either an address-misaligned exception or an access-faultexception. For a memory access that would otherwise be able to complete except for the misalign-ment, an access exception can be raised instead of an address-misaligned exception if the misalignedaccess should not be emulated, e.g., if accesses to the memory region have side e↵ects. When anEEI does not guarantee misaligned loads and stores are handled invisibly, the EEI must define ifexceptions caused by address misalignment result in a contained trap (allowing software runninginside the execution environment to handle the trap) or a fatal trap (terminating execution).Misaligned accesses are occasionally required when porting legacy code, and help performance onapplications when using any form of packed-SIMD extension or handling externally packed datastructures. Our rationale for allowing EEIs to choose to support misaligned accesses via theregular load and store instructions is to simplify the addition of misaligned hardware support.One option would have been to disallow misaligned accesses in the base ISA and then providesome separate ISA support for misaligned accesses, either special instructions to help softwarehandle misaligned accesses or a new hardware addressing mode for misaligned accesses. Specialinstructions are di cult to use, complicate the ISA, and often add new processor state (e.g.,SPARC VIS align address o↵set register) or complicate access to existing processor state (e.g.,MIPS LWL/LWR partial register writes). In addition, for loop-oriented packed-SIMD code,the extra overhead when operands are misaligned motivates software to provide multiple formsof loop depending on operand alignment, which complicates code generation and adds to loopstartup overhead. New misaligned hardware addressing modes take considerable space in theinstruction encoding or require very simplified addressing modes (e.g., register indirect only).Even when misaligned loads and stores complete successfully, these accesses might run extremelyslowly depending on the implementation (e.g., when implemented via an invisible trap). Further-more, whereas naturally aligned loads and stores are guaranteed to execute atomically, misalignedloads and stores might not, and hence require additional synchronization to ensure atomicity.We do not mandate atomicity for misaligned accesses so execution environment implementa-tions can use an invisible machine trap and a software handler to handle some or all misalignedaccesses. If hardware misaligned support is provided, software can exploit this by simply usingregular load and store instructions. Hardware can then automatically optimize accesses depend-ing on whether runtime addresses are aligned. |
2023-07-18T10:37:52.214247 | segment15 | 2.7 Memory Ordering Instructions | RV32ISPEC.pdf#segment15 | [] | 2.7 Memory Ordering Instructions 31 28 27 26 25 24 23 22 21 20 19 15 14 12 11 7 6 0fmPIPOPRPWSISOSRSWrs1funct3rdopcode41 1 1 1 1111 5 3 5 7FM predecessor successor 0 FENCE 0 MISC-MEMThe FENCE instruction is used to order device I/O and memory accesses as viewed by other RISC-V harts and external devices or coprocessors. Any combination of device input (I), device output(O), memory reads (R), and memory writes (W) may be ordered with respect to any combinationof the same. Informally, no other RISC-V hart or external device can observe any operation in thesuccessorset following a FENCE before any operation in thepredecessorset preceding the FENCE.Chapter14provides a precise description of the RISC-V memory consistency model.The EEI will define what I/O operations are possible, and in particular, which memory addresseswhen accessed by load and store instructions will be treated and ordered as device input anddevice output operations respectively rather than memory reads and writes. For example, memory-mapped I/O devices will typically be accessed with uncached loads and stores that are ordered usingthe I and O bits rather than the R and W bits. Instruction-set extensions might also describe newI/O instructions that will also be ordered using the I and O bits in a FENCE.fmfieldMnemonicMeaning0000noneNormal Fence1000TSOWith FENCE RW,RW: exclude write-to-read orderingOtherwise:Reserved for future use.otherReserved for future use.Table 2.2: Fence mode encoding.The fence mode fieldfmdefines the semantics of the FENCE. A FENCE withfm=0000 orders allmemory operations in its predecessor set before all memory operations in its successor set.The optional FENCE.TSO instruction is encoded as a FENCE instruction withfm=1000,predeces-sor=RW, andsuccessor=RW. FENCE.TSO orders all load operations in its predecessor set beforeall memory operations in its successor set, and all store operations in its predecessor set before allstore operations in its successor set. This leaves non-AMO store operations in the FENCE.TSO’spredecessor set unordered with non-AMO loads in its successor set.The FENCE.TSO encoding was added as an optional extension to the original base FENCEinstruction encoding. The base definition requires that implementations ignore any set bits andtreat the FENCE as global, and so this is a backwards-compatible extension.The unused fields in the FENCE instructions—rs1andrd—are reserved for finer-grain fences infuture extensions. For forward compatibility, base implementations shall ignore these fields, andstandard software shall zero these fields. Likewise, manyfmand predecessor/successor set settingsin Table2.2are also reserved for future use. Base implementations shall treat all such reserved configurations as normal fences withfm=0000, and standard software shall use only non-reservedconfigurations.We chose a relaxed memory model to allow high performance from simple machine implementa-tions and from likely future coprocessor or accelerator extensions. We separate out I/O orderingfrom memory R/W ordering to avoid unnecessary serialization within a device-driver hart andalso to support alternative non-memory paths to control added coprocessors or I/O devices.Simple implementations may additionally ignore thepredecessorandsuccessorfields and alwaysexecute a conservative fence on all operations. |
2023-07-18T10:37:52.214398 | segment16 | 2.8 Environment Call and Breakpoints | RV32ISPEC.pdf#segment16 | [] | 2.8 Environment Call and Breakpoints SYSTEM instructions are used to access system functionality that might require privileged ac-cess and are encoded using the I-type instruction format. These can be divided into two mainclasses: those that atomically read-modify-write control and status registers (CSRs), and all otherpotentially privileged instructions. CSR instructions are described in Chapter9, and the baseunprivileged instructions are described in the following section.The SYSTEM instructions are defined to allow simpler implementations to always trap to asingle software trap handler. More sophisticated implementations might execute more of eachsystem instruction in hardware.31 20 19 15 14 12 11 7 6 0funct12rs1funct3rdopcode12 5 3 5 7ECALL 0 PRIV 0 SYSTEMEBREAK 0 PRIV 0 SYSTEMThese two instructions cause a precise requested trap to the supporting execution environment.The ECALL instruction is used to make a service request to the execution environment. The EEIwill define how parameters for the service request are passed, but usually these will be in definedlocations in the integer register file.The EBREAK instruction is used to return control to a debugging environment.ECALL and EBREAK were previously named SCALL and SBREAK. The instructions havethe same functionality and encoding, but were renamed to reflect that they can be used moregenerally than to call a supervisor-level operating system or debugger.EBREAK was primarily designed to be used by a debugger to cause execution to stop and fallback into the debugger. EBREAK is also used by the standard gcc compiler to mark code pathsthat should not be executed.Another use of EBREAK is to support “semihosting”, where the execution environment in-cludes a debugger that can provide services over an alternate system call interface built aroundthe EBREAK instruction. Because the RISC-V base ISA does not provide more than one EBREAK instruction, RISC-V semihosting uses a special sequence of instructions to distin-guish a semihosting EBREAK from a debugger inserted EBREAK.slli x0, x0, 0x1f # Entry NOPebreak # Break to debuggersrai x0, x0, 7 # NOP encoding the semihosting call number 7Note that these three instructions must be 32-bit-wide instructions, i.e., they mustn’t be amongthe compressed 16-bit instructions described in Chapter16.The shift NOP instructions are still considered available for use as HINTS.Semihosting is a form of service call and would be more naturally encoded as an ECALLusing an existing ABI, but this would require the debugger to be able to intercept ECALLs, whichis a newer addition to the debug standard. We intend to move over to using ECALLs with astandard ABI, in which case, semihosting can share a service ABI with an existing standard.We note that ARM processors have also moved to using SVC instead of BKPT for semi-hosting calls in newer designs. |
2023-07-18T10:37:52.214677 | segment17 | 2.9 HINT Instructions | RV32ISPEC.pdf#segment17 | [] | 2.9 HINT Instructions RV32I reserves a large encoding space for HINT instructions, which are usually used to commu-nicate performance hints to the microarchitecture. HINTs are encoded as integer computationalinstructions withrd=x0. Hence, like the NOP instruction, HINTs do not change any architecturallyvisible state, except for advancing thepcand any applicable performance counters. Implementa-tions are always allowed to ignore the encoded hints.This HINT encoding has been chosen so that simple implementations can ignore HINTs alto-gether, and instead execute a HINT as a regular computational instruction that happens not tomutate the architectural state. For example, ADD is a HINT if the destination register isx0;t h efive-bitrs1andrs2fields encode arguments to the HINT. However, a simple implementation cansimply execute the HINT as an ADD ofrs1andrs2that writesx0, which has no architecturallyvisible e↵ect.Table2.3lists all RV32I HINT code points. 91% of the HINT space is reserved for standard HINTs,but none are presently defined. The remainder of the HINT space is reserved for custom HINTs:no standard HINTs will ever be defined in this subspace.No standard hints are presently defined. We anticipate standard hints to eventually includememory-system spatial and temporal locality hints, branch prediction hints, thread-schedulinghints, security tags, and instrumentation flags for simulation/emulation.
InstructionConstraintsCode PointsPurposeLUIrd=x0220Reserved for future standard useAUIPCrd=x0220ADDIrd=x0, and either217 1rs16=x0orimm6=0ANDIrd=x0217ORIrd=x0217XORIrd=x0217ADDrd=x0210SUBrd=x0210ANDrd=x0210ORrd=x0210XORrd=x0210SLLrd=x0210SRLrd=x0210SRArd=x0210FENCEpred=0 orsucc=025 1SLTIrd=x0217Reserved for custom useSLTIUrd=x0217SLLIrd=x0210SRLIrd=x0210SRAIrd=x0210SLTrd=x0210SLTUrd=x0210Table 2.3: RV32I HINT instructions. |
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 3