[PATCH] [SimplifyCFG] Teach when it is profitable to speculate calls to @llvm.cttz/ctlz.

Andrea Di Biagio Andrea_DiBiagio at sn.scee.net
Wed Dec 17 03:55:34 PST 2014


Hi Quentin, Hal, David,

thanks a lot for the useful feedback!.

In http://reviews.llvm.org/D6679#102065, @qcolombet wrote:

> Hi Andrea,
>
> > On X86 (not x86-64) targets with no LZCNT/TZCNT and no CMOV instructions, the backend would futher expand the conditional moves introducing machine basic blocks. Basically it would revert this optimization re-introducing the if-else structure.
>
>
> Have you checked that the output assembly is the same (or equivalent) performance-wise on such targets?


So, I checked the output assembly for those targets. At first I thought that the codegen was equivalent performance-wise. But I was wrong, since there is unfortunately an important difference: the count leading/trailing zeros instruction is now always dominating the control flow. Therefore, it would always be speculatively executed. 
While this is ok for the case where we the input value is known not to be zero (since BSF/BSR would be executed anyway), this is sub-optimal for the case where the value is zero.

Before this patch, with a value of zero in input to cttz/ctlz, the instructions dynamically executed would have been:

  "TEST+conditional branch+propagation of constant"

With this patch, we would execute instead:

  "BSF/BSR+conditional branch+propagation of constant".

bsf/bsr would be able to set the rFLAGS, so the backend avoids inserting an extra TEST. However, BSF/BSR is much slower (it may be microcoded on old x86 targets...). So, I am afraid that my patch would slow down the code for x86 with no CMOV.

I'll see if I can move this logic in CodeGenPrepare as suggested by Hal.

My idea is to do the following (if you agree):

- move this logic into CodeGenPrepare;
- guard the code against a check on the subtarget (something like 'isCheapToSpeculateCttzCtlz').
  - On X86 that method would return true if we have TZCNT/LZCNT or if we have feature CMOV.

Thanks again for your time.
I'll prepare a new patch.

Cheers,
Andrea


http://reviews.llvm.org/D6679

EMAIL PREFERENCES
  http://reviews.llvm.org/settings/panel/emailpreferences/






More information about the llvm-commits mailing list