www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/09/09/05:43:52

From: "Hargreaves, Shawn" <shawnh AT probe DOT co DOT uk>
To: "'djgpp AT delorie DOT com'" <djgpp AT delorie DOT com>
Subject: Re: [Q] ASM
Date: Tue, 09 Sep 97 10:37:00 PDT
Message-ID: <341589F5@relay.probe.co.uk>
Encoding: 31 TEXT

M. Schulter writes:
> Ah, this explains Brennan's trick for multiplying _quickly_ by n+1,   
where
> n is the scale factor, e.g.

The LEA instruction, sometimes combined with a few shifts, is hugely
useful for any sort of multiplication by a constant. Fortunately for us,
gcc knows all about this trick, and will use it in place of an actual
multiplication whenever this is possible (ie. when one of the operands
is known at compile time). For example, the function:

int mul27add3(int n)
{
    return n*27+3;
}

compiled with -O3, -m486, -fomit-frame-pointer, produces the code:

_mul27add3:
    movl 4(%esp),%eax  // eax = n
    leal (%eax,%eax,2),%eax // eax = n*3
    leal 3(%eax,%eax,8),%eax // eax = n*27+3
    ret

I'm in awe of whoever wrote the code to perform that particular type of
optimisation: it's easy enough to do by hand for a specific case, but
making the compiler do it for any arbitrary expression can't have been
easy :-)

 Shawn Hargreaves.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019