0

Is it possible to change the code the compiler create in the exe file?

I am trying to change the output code of the compiler like that:

The code that I am writing in the cpp file is:

a++;

And the compiler generate it the the folowing code:

INC [a]

How can I change it to this:

ADD [a],1

I want that the compiler will do it every time the compiler compile this statement and that is why the asm statement do not work.Also I want to change it only on one platform.

I am sure that the compiler generate the code based on a template so how can I change it(if I can)?

  • 1
    Even with optimizations turned off, chances are most compilers will opt for `INC` instead of `ADD 1`. Is there a specific reason why you want your compiler to prefer the latter to the former? – Frédéric Hamidi May 23 '14 at 09:36
  • Which compiler? If add is faster than inc on some processor, asking the compiler to tune for this processor may be sufficient. – Marc Glisse May 23 '14 at 09:36
  • 8
    _'I am sure that the compiler generate the code based on a template'_ Nope! It doesn't work like this, it's a much more complex process than template substitution. – πάντα ῥεῖ May 23 '14 at 09:36
  • I want to do this for more complex statement. It was just an example. Except that I think that the code taken from a template because it is the same all the time except the number(like in for) – user13342203 May 23 '14 at 09:42
  • 5
    If you want to control the output code, write the `asm` yourself. – StoryTeller - Unslander Monica May 23 '14 at 09:45
  • "On some micro-architectures, with some instruction streams, INC will incur a "partial flags update stall" (because it updates some of the flags while preserving the others). ADD sets the value of all of the flags, and so does not risk such a stall." http://stackoverflow.com/questions/13383407/is-add-1-really-faster-than-inc-x86 – phuclv May 23 '14 at 09:49
  • @StoryTeller you need to edit the compiler, not the assembler, to emit `add` instead of `inc` – phuclv May 23 '14 at 09:49
  • 2
    @LưuVĩnhPhúc, or you can just write [inline assembly](http://en.wikipedia.org/wiki/Inline_assembler) – StoryTeller - Unslander Monica May 23 '14 at 09:55
  • If you need to dwelve on such details, you might write the assembly for every platform you need. From the C++ or C point of view, there's no such thing as an assembly. – Bartek Banachewicz May 23 '14 at 10:56
  • But I can see the assembly code in the debug and it is the same for every loop or if or other statement. – user13342203 May 23 '14 at 11:26

1 Answers1

2

Just use inline assembly. For example in GCC:

#ifdef PLATFORM_X86
    __asm__ ( "addl $1, %0" : "=r"(a) : : "memory" );
#else
    a++;
#endif
ikh
  • 10,119
  • 1
  • 31
  • 70