Search code examples
assemblyx86nasmaddressing-mode

Assembly - Do implicit calculations change the opcode?


When I have an operation like mov eax, [input+10]:

Does it have a different opcode than this operation:

mov eax, [input] (considering that input now has the value of former input+10)?


Solution

  • These two instructions should generate the exact same machine code.

    That's because 'input' is a symbol which stands for an address, and the constant '10' is added to it by the assembler. In both cases, the instruction is mov register, [displacement]. The addressing mode being used is called "Direct", a.k.a. "Displacement-Only".

    The CPU does not have any addressing mode (nor special opcode) for mov register, [displacement + offset].

    (And it would not make any sense to support such an addressing mode, because both displacement and offset are constants.)

    EDIT:

    A special case arises when 'input' is declared as exportable in one assembly file, and then it gets imported in another assembly file where you try to add an offset to it. In this case, the assembler will not know the exact value of 'input' when assembling your instruction, so it would then be up to the linker to figure out the value of the operand during linkage time, or up to the loader to figure it out during program-load time. There are two possibilities: Either these tools (the combination of assembler + linker) have means of handling this, or they do not.

    • If they do have means of handling this, then the object code emitted by the assembler may look slightly different in the '.obj' file, but the resulting bit pattern once your executable has been loaded into memory and starts running should still be exactly the same.

    • If the tools have no means of handling this, your assembler should be giving you an error that it does not know how to add '10' to 'input' because 'input' is an external symbol.