Why Can’t Large Constants Always Fit Inside CPU Instructions?
In assembly, you often see instructions like:
ADD R0, R0, #5
Here #5 is embedded directly inside the instruction.
This is called Immediate Addressing.
But what happens if we write the following C code?
x = x + 100000;
Instead of placing the value directly inside the instruction, the CPU may generate something like:
LDR R1, =100000
ADD R0, R0, R1
Why can’t the processor simply execute:
ADD R0, R0, #100000
The Reason: Instruction Size Is Limited
Most ARM instructions are 32 bits wide.
Those 32 bits must encode several pieces of information:
the operation (ADD, SUB, MOV, etc.)
the destination register
the source register
the immediate value
Conceptually, the instruction looks like this:
[ opcode | registers | immediate value ]
Since the instruction must store multiple fields, only a limited number of bits remain for the constant.
As a result, very large numbers cannot always fit directly inside the instruction.
What Happens When the Constant Is Too Large?
When the constant cannot be encoded directly, the compiler loads it first:
LDR R1, =100000
ADD R0, R0, R1
Now the CPU performs the operation in two steps:
Load the constant into a register
Use that register in the arithmetic instruction
This is why some operations require extra instructions.
Key Insight
Large constants cannot always fit inside CPU instructions because instruction size is limited.
To handle this, processors use techniques such as:
loading constants from memory
constructing constants using multiple instructions
Understanding this explains why seemingly simple operations sometimes produce multiple assembly instructions.
Comments
Post a Comment
Thanks for reading through the Embedded Systems World.
Feel free to ask questions or share your thoughts on the topic.