On 05/11/15 23:02, Rena wrote: > On Nov 5, 2015 3:53 PM, "David Brown" <david.brown@xxxxxxxxxxxx > <mailto:david.brown@xxxxxxxxxxxx>> wrote: >> >> There has been some discussions going on in the comp.lang.c newsgroup > about how far compilers are allowed to go regarding optimisation using > their knowledge of undefined behaviour (i.e., if a piece of code has > undefined behaviour, the compiler can assume that the user does not care > about the result in that case, and can therefore do whatever it wants in > order to generate faster code). >> >> (Sorry about the length of this question - it is a difficult topic.) >> >> >> >> I would like to know where the gcc developers stand on this - how can > the rules of the standards be interpreted? And how /should/ they be > interpreted? Does gcc aim for the most efficient code, or for the > principle of least astonishment? >> >> For example, consider this requirement: >> >> Write a function "int foo(int x)" that will call "bar(x)" if x is less > than 50000. Then if x is less than 1000, return x*x*x - otherwise > return any integer. (Assume 32-bit int's, no traps or other "funny > stuff" on the target.) >> >> It seems reasonable to write: >> >> int foo(int x) { >> if (x < 50000) bar(x); >> return x*x*x; >> } >> >> For x greater than 1290, the cubing is going to overflow and generate > a mathematically incorrect answer. But that's okay - we don't care > about the result in such cases. >> >> The question is, can the compiler reason like this: >> >> If x > 1290, then undefined behaviour will occur. The user clearly > doesn't care what happens when x > 1290. Therefore, we can assume that > x <= 1290. Therefore, x < 50000. Therefore, there is no need to check > the conditional, and bar(x) can be called directly. >> >> The point here is that if the code hits undefined behaviour, then the > behaviour of the entire program is undefined. Thus the undefined > behaviour in "x*x*x" can work backwards. > > Would it not be feasible, if the compiler is clever enough to know that > the x < 50000 check can only be true in cases of undefined behavior, to > emit a warning? Whenever the question is "what should the compiler do > with this suspicious/faulty code", my answer is usually "complain about > it", especially if it's the only answer that won't generate a program > that behaves contrary to its author's expectations. > Certainly warning messages would be very useful here. It is difficult to know exactly what criteria should be used for when a warning is appropriate, but if the compiler uses undefined behaviour to eliminate code, then perhaps a warning is appropriate. There certainly should be warnings if the optimisation from undefined behaviour works backwards in time (such as in this example).