The MASM Forum

General => The Campus => Topic started by: Elegant on June 27, 2015, 04:57:08 PM

Title: add and sub with x64 registers
Post by: Elegant on June 27, 2015, 04:57:08 PM
Hi, I'm passing an integer to my assembly procedure which is going into rcx and on the stack I have a dword that we'll call stride for this example. I need to add and/or sub stride from rcx:

add rcx,stride

Obviously this doesn't work. My question is if the correct solution is to use ecx instead:

add ecx,stride

or if I need to put stride into it's own register like r9 then add it similar to the below:


movsxd r9,stride
add rcx,r9


If anyone can tell me which is the most appropriate solution it would be much appreciated!
Title: Re: add and sub with x64 registers
Post by: rrr314159 on June 27, 2015, 06:51:21 PM
This is best:

add ecx,stride

Title: Re: add and sub with x64 registers
Post by: sinsi on June 27, 2015, 07:01:10 PM
Depends on what the result should be, 32- or 64-bit.

;assuming unsigned
  add ecx,stride ;32-bit

  mov eax,stride ;zeroes upper 32 bits
  add rcx,rax    ;64-bit


If it's on the stack, you should be pushing it as a qword anyway (for Windows at least) to keep the stack 8-aligned.
Title: Re: add and sub with x64 registers
Post by: rrr314159 on June 27, 2015, 07:27:00 PM
@sinsi,

add ecx,stride

works with signed variables also. But you're right, it's no good if you want to use the upper 32 bits - I was assuming he didn't. But in that case you should use his second solution,

movsxd r9,stride
add rcx,r9

instead of

mov ecx, stride ; (or add ecx, stride)

which loses the upper 32 bits

So, Elegant, evidently the correct answer is to use your first alternative if you're only doing 32-bit computations, otherwise you must use your second alternative
Title: Re: add and sub with x64 registers
Post by: Elegant on June 28, 2015, 11:16:08 AM
Perfect, thanks! This was to help port some x86 code to x64. I was pushing the int-type values as dwords to asm; the max value I can ever see being sent over is probably 8000~ and that's VERY unlikely. Definitely going to keep that in mind going forward unless it provides better performance to add them as 64-bit.
Title: Re: add and sub with x64 registers
Post by: rrr314159 on June 28, 2015, 12:05:18 PM
doubt there's any difference at all 32 vs. 64 bit add, especially registers. qwords in memory can possibly affect cache performance, apart from that it's irrelevant.

BTW you can use the link option /LARGEADDRESSAWARE:NO, makes it very easy to convert from X86 because all addresses can remain 32 bit. See my "invoke_macros" in 64 bit forum: "nvk" automatically converts to 64 bit for Windows functions, so I almost never have to use 64 bit data unless I need the large numbers. Windows functions, as you undoubtedly know already, always require 64 bit handles, addresses and pointers