Why Does GCC LEA EIZ?

 

Now to the topic at hand. I was disassembling some code the other day (just using objdump, nothing fancy) and I noticed a weird pattern emitted by GCC.

billm@plums:~$ objdump -d /bin/ls | less ... 8049ba9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi ...

This pattern appears all over the place (though sometimes with other registers subsituted for edi). Mostly I’ve noticed it in between functions (after one returns and before the next begins) but it also appears within function bodies.

What does this instruction do? The weirdo syntax makes it particularly difficult to determine. Apparently %eiz is a pseudo-register that just evaluates to zero at all times (like r0 on MIPS). I decoded the same instruction using an older version of objdump, and it instead gave the more normal result “lea 0×0(%edi),%edi”. I think the binutils people must pull a lot of all-nighters to make their crazy AT&T syntax even more inscrutable with each new version. Why can’t we just use Intel syntax? It seems way more intuitive to me.

Returning to the problem at hand, the instruction “lea 0×0(%edi),%edi” still doesn’t make much sense. Why would you ever want to load the effective address of [edi] into edi? This is semantically equivalent to “mov edi, edi”, or, more simply, to a NOP.

I eventually found a mailing list post by binutils guru Ian Lance Taylor that reveals the answer. Sometimes GCC inserts NOP instructions into the code stream to ensure proper alignment and stuff like that. The NOP instruction takes one byte, so you would think that you could just add as many as needed. But according to Ian Lance Taylor, it’s faster for the chip to execute one long instruction than many short instructions. So rather than inserting seven NOP instructions, they instead use one bizarro LEA, which uses up seven bytes and is semantically equivalent to a NOP.

I must admit to being a bit confused still. Most of the time, these semantic NOPs are not executed so you might as well use regular NOPs. Occasionally, the LEAs do occur in places where they might be executed, but in those cases I don’t always understand why a NOP is needed. Sometimes the next instruction after the NOP is a branch target, and so I can understand that the compiler might want the CPU to start loading those instructions on a cache line boundary if possible. But sometimes the instruction after the NOP is not a branch target. In that case, why is there a random NOP in the instruction stream? It just seems wasteful of cache. Perhaps someone can enlighten me.

Anyway, wasn’t that interesting?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值