neg

RISC-V neg Pseudo-Instruction Details

Assembler pseudo-instruction

Negate (two's complement) pseudo-instruction, expands to sub rd, x0, rs. Computes 0 - rs to obtain the arithmetic negation of rs. Common for sign flipping, absolute value pre-computation, and subtraction optimization.

What You Write
neg rd, rs
Typical Real Expansion
sub rd, x0, rs

What This Pseudo Instruction Is Saving You From Writing

More intuitive than sub rd, x0, rs for expressing negation. Compilers commonly use neg to implement the unary minus operator and optimize a - b into a + neg(b).

neg primarily means "Negate, 0-rs in two's complement". It is assembler-level shorthand; when debugging, auditing, or reading machine code, reason from the real expansion and relocation semantics listed on this page.

Official Semantics Checklist

The official assembly manual treats neg as an assembler-level pseudo-instruction or alias; hardware executes the expanded real instruction sequence.
The real semantics come from the ISA definitions of SUB and the other expanded instructions, not from a separate neg hardware opcode.

How To Read The Expansion

Step 1
Assembler expands to sub rd, x0, rs.
Step 2
SUB computes x0(0) - rs, yielding the two's complement negation of rs.

What You May See In objdump / Disassembly

sub rd, x0, rs shown as neg rd, rs in disassembly.

Official References And Reading Order

This page treats pseudo-instructions as assembler-level aliases or macros: first read what real instructions they expand to, then use the official ISA manual for the behavior of those real instructions. ABI, relocation, and linker-relaxation details follow the psABI document.

When To Think Of It First

Negate a value (unary minus operator -x)
Implement C language negation
Absolute value computation (abs): get sign bit via srai, then neg
Intermediate step in subtraction-to-addition optimization

Pitfalls / Common Confusions

Negating the minimum negative value overflows — e.g., on RV32, neg(0x80000000) = 0x80000000 (no trap, result equals itself)
Negation result can be used with branches for overflow detection in range checks
neg operates on full XLEN width; on RV64, mind the upper 32 bits

FAQ

Is neg a real RISC-V instruction?

neg is an assembler pseudo-instruction or alias, not a separate hardware opcode. The “Typical Real Expansion” section lists the official expansion, and behavior is defined by the expanded ISA instructions.

What is the main trap when using neg?

Negating the minimum negative value overflows — e.g., on RV32, neg(0x80000000) = 0x80000000 (no trap, result equals itself)