Search code examples
compiler-optimizationwatcom

Poor C optimization in Watcom


I am using Watcom C compiler (wcc) version 2.0. I compile this simple code with many optimizations enabled, but the resulting ASM seems very unoptimized to me.

int test(int x) {

    return x ? 1 : 2;
}

Compiling with 8086 as target, fastest possible optimizations (-otexan).

wcc test.c -i="C:\Data\Projects\WATCOM/h" -otexan -d2 -bt=dos -fo=.obj -mc

Then disassembling with:

wdis test.obj -s > test.dasm

Resulting assembler looks like this:

...
    return x ? 1 : 2;
02C7  83 7E FA 00            cmp        word ptr -0x6[bp],0x0000
02CB  74 03                  je         L$39
02CD  E9 02 00               jmp        L$40
02D0                L$39:
02D0  EB 07                  jmp        L$41
02D2                L$40:
02D2  C7 46 FE 01 00         mov        word ptr -0x2[bp],0x0001
02D7  EB 05                  jmp        L$42
02D9                L$41:
02D9  C7 46 FE 02 00         mov        word ptr -0x2[bp],0x0002
02DE                L$42:
02DE  8B 46 FE               mov        ax,word ptr -0x2[bp]
02E1  89 46 FC               mov        word ptr -0x4[bp],ax
02E4  8B 46 FC               mov        ax,word ptr -0x4[bp]
...

These jumps look heavily un-optimized to me. I would expect less unnecessary jumps and maybe putting result directly to AX without putting it under BP location there and back (last two lines).

    cmp      word ptr -0x6[bp],0x0000
    jz       L$39
    mov      ax,0x0001
    jmp      L$40
L$39:
    mov      ax,0x0002
L$40:
    ...

Am I missing something there? Is wcc ignoring my switches for some reason? Thanks.


Solution

  • Problem is the -d2 switch that generates detailed debug info. It probably inserts unnecessary lines to correspond to original C file's lines (to be able to put hardware breakpoints there, maybe?). I put -d1 instead and voila:

    01A0              test_:
    01A0  85 C0           test      ax,ax
    01A2  74 04           je        L$15
    01A4  B8 01 00        mov       ax,0x0001
    01A7  C3              ret
    01A8              L$15:
    01A8  B8 02 00        mov       ax,0x0002
    01AB  C3              ret