News for hackers. Stuff that matters.
Re:The Dangers of Super Smart Compilers by mikeash on Sunday December 20, 2015 @12:49PM (#10767665)
Doing "something sensible" sounds good, but it's hard to actually do. You can point out the sensible approach to specific examples, but writing the optimizer to take a "sensible approach" in all cases is hard.

For every example like this, where the programmer wants a NULL check to be done even when the value "can't be NULL," there's an opposite example where the programmer wants a NULL check to be elided because the value actually can't be NULL.

Taking advantage of undefined behavior isn't done because compiler writers are sadists who enjoy writing perverse implementations which rely on the letter of the law. It's done because it allows the compiler to generate better, faster code.

I think a lot of the trouble is that too many programmers learn C in a completely ad-hoc, informal fashion and never take the time to actually become familiar with the fundamentals of the language. People simply don't know how the language is specified, what operations are legal and what operations aren't, why there are illegal operations that the compiler won't (and can't) warn you about, etc.

C is definitely a dangerous language and is a difficult language to use well. But that's all the more reason people who plan to use it need to ensure they understand it.

More mandatory reading: http://blog.llvm.org/2011/05/what-every-c-programmer-should-...

Re:The Dangers of Super Smart Compilers by rwmj on Sunday December 20, 2015 @02:53PM (#10768065)
Surely the compiler could see that you've written some code (ie. not a macro expansion or whatever) and that the code is unreachable, and print some sort of dead code warning? That would have helped the poster, assuming he turns on and reads warnings.
Re:The Dangers of Super Smart Compilers by scott_s on Sunday December 20, 2015 @03:31PM (#10768192)
C and C++ applications include lots and lots of headers from the systems and third party libraries. Dead code is common in such circumstances, and programmers would drown in a sea of dead code eliminated warnings.
Re:The Dangers of Super Smart Compilers by rwmj on Monday December 21, 2015 @05:20AM (#10770439)
But you can still see: is the source of this code something the user has written in a .c file, or something that came from a header file or from macro expansion, and only warn about the former. Granted this is difficult, because LLVM is multi-layered, but it's not impossible in the general case.
Re:The Dangers of Super Smart Compilers by scott_s on Monday December 21, 2015 @10:37AM (#10771527)
I think it's extremely difficult, to the point of not being practical. When you get to the point of the compiler that it's applying these optimizations, that the code came from a .c or .h file has been long thrown away.
Re:The Dangers of Super Smart Compilers by andrewflnr on Sunday December 20, 2015 @01:05PM (#10767711)
> It's done because it allows the compiler to generate better, faster code.

Why? Why is this OK? You say doing "something reasonable" is hard, but it obviously doesn't include entirely ignoring code I wrote. That's basically saying "I see you did something weird there, but going to assume the rest of your code and ask the libraries you link to are perfectly standard-compliant, which lets me generate faster code here. I'm so smart!"

Default safe, not fast, wherever possible.

Re:The Dangers of Super Smart Compilers by mikeash on Sunday December 20, 2015 @01:21PM (#10767749)
Sure it does. A big part of optimization is specializing code to be fast by removing unimportant bits.

Here's a quick bad example:

    int computation(int *a, int *b) {
        if(a == NULL && b == NULL) return 0;
        if(a == NULL) return *b;
        if(b == NULL) return *a;
        return ...something with *a and *b...;
    }

    ...elsewhere...
    int a[1024];
    int b[1024];
    ...fetch data into a and b...
    int c[1024];
    for(int i = 0; i < 1024; i++)
        c = computation(a + i, b + i);
Would you want this code, compiled with full optimizations, to run slowly because it does four NULL checks every time through the loop? A good compiler will probably inline the computation and eliminate all the checks because the condition they're checking for can never happen. Is that a bad thing?
Re:The Dangers of Super Smart Compilers by nkurz on Sunday December 20, 2015 @02:24PM (#10767960)
This is a good example, and I think shows persuasively that it's good for a compiler to make logical assumptions about inputs when inlining code. But I think this is different than making optimizations by presuming the absence of undefined behavior when compiling the function itself.

Consider a programmer who feels it's clearer to dereference a and b once, rather than writing using * a and * b in the complicated math after the preliminary checks. And because they don't want to rely on C99 or distract by opening a new block, they put the conversion at the top of the function. Oh, and the new guy decided to add the "missile launch" code here.

    int computation(int *ptr_a, int *ptr_b) {
        int val_a = *a, val_b = *b;
        if(ptr_a == NULL && ptr_b == NULL) return 0;
        if(ptr_a == NULL) return val_b;
        if(ptr_b == NULL) return val_a;
        launch_missiles(); /* OK to put this here? */
        return ...something with val_a and val_b...;
    }

I think there is a reasonable argument that there is a difference between optimizing when a code path can be shown to never occur because of constrained inputs, and optimizing because behavior supposedly can be inferred from the absence of undefined behavior.

I'm fine with a literalist compiler that produces code that crashes when it immediately tries to dereference a NULL pointer, with one that produces code that does the safety checks but defers the load, but even if allowed by the spec[1] I don't think it's good behavior for a compiler to silently omit the safety checks and launch the missiles when passed a NULL.

[1] Is this undefined behavior according to the spec? I consider myself an expert C programmer, and I think it's undefined in C99, but I wouldn't bet that I've correctly understood the issues for the other dialects of C, muchless C++. Is a conforming compiler "allowed" to skip the safety checks and launch the missiles? I don't know, and thus defensively wouldn't write the code like this, but it would be nice to think that long-standing mission-critical code written by others won't suddenly stop working with a new release of the optimizing compiler.

Re:The Dangers of Super Smart Compilers by mikeash on Sunday December 20, 2015 @04:39PM (#10768397)
I agree that's a pretty good example the other way.

I'm pretty sure your snippet invokes nasal demons in all dialects. Dereferencing NULL is a pretty classic case where anything can happen once you do it. "Calling launch_missiles even though you don't want it to happen" is a subset of "anything," of course.

Consider what happens if you rearrange that example a bit, though. Let's say it's more like this:

    int computation(int *ptr_a, int *ptr_b) {
        if(ptr_a == NULL && ptr_b == NULL) return 0;
        if(ptr_a == NULL) return val_b;
        if(ptr_b == NULL) return val_a;
        launch_missiles(); /* OK to put this here? */
        return ...something with val_a and val_b...;
    }

    int otherComputation(int *ptr_a, int *ptr_b) {
        int val_a = *ptr_a, val_b = *ptr_b;
        int intermediate = computation(ptr_a, ptr_b);
        return ...something with val_a, val_b, and intermediate....;
    }
Then you call otherComputation in a tight loop. Should the compiler elide the NULL checks here, if computation gets inlined? otherComputation clearly requires that its parameters are non-NULL, so it should be fine to remove the checks. Failing to do so would be pretty annoying. It's clear that the inputs are constrained, and while you could fix it by factoring out the common code so that the NULL checks are explicitly optional, it would be best if the optimizer can handle it and not require us to rearrange our code to make it happy.

That's really what I'm getting at. There are clear examples where it's bad to assume undefined behavior cannot happen and optimize away checks. But there are also clear examples where it's exactly what you want to do. Can the optimizer reliably distinguish between these cases?

I think the best answer is to have tools available like the undefined behavior sanitizer which can catch these problems at runtime. You want the optimizer to make your code as fast as it legally can. Trying to tone it down is going to be error-prone, and safety checks that can't be counted on are dangerous. You might end up just moving the problem around: instead of code suddenly being optimized out because the compiler proved it can't run without invoking undefined behavior, you'll have code suddenly being optimized out because something changed that made the compiler think you intended it. By checking at runtime, you recast the problem from "does the programmer intend to pass in values which will result in undefined behavior?" to "does this code actually get called with such values?" That's way easier to check, should have zero false positives, and should have as few false negatives with good test coverage.

Re:The Dangers of Super Smart Compilers by nkurz on Sunday December 20, 2015 @05:25PM (#10768539)
Your otherComputation() example doesn't strike me as a clear cut case. My preference (and I agree that this is not required by spec) would be that the checks would be omitted only if the dereference has actually been executed, and not if the initialization has just been declared. Essentially, I think I'd like dereference of a NULL pointer to be defined behavior as far as generated code (the code must behave identically to how it would behave if the load was issued) while possibly undefined for the processor (crashing is valid, but returning a constant would be valid too). The compiler is allowed to reduce many checks to one by assuming consistency, but not allowed to ignore the checks altogether.

I'm pretty sure your snippet invokes nasal demons in all dialects. Dereferencing NULL is a pretty classic case where anything can happen once you do it.

Is the dereferencing itself undefined in all dialects, or is it only undefined if one later "evaluates" the dereferenced value? Or do some define evaluation differently? For example (to my surprise) a comment by 'lkasndasd' on the corresponding Reddit thread points out that &* ptr is never undefined behavior in C, since the address operator and the dereference operator cancel out even (explicitly) if ptr is NULL:

  6.5.3.2 Unary arithmetic operators, Semantics, paragraph 3:
  The unary & operator yields the address of its operand. 
  [...] If the operand is the result of a unary * operator, 
  neither that operator nor the & operator is evaluated and 
  the result is as if both were omitted, except that the 
  constraints on the operators still apply and the result is 
  not an lvalue.
  and footnote 102:
  Thus, &*E is equivalent to E (even if E is a null pointer) [...]
https://www.reddit.com/r/programming/comments/3xk6zj/the_dan...

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

Re:The Dangers of Super Smart Compilers by mikeash on Sunday December 20, 2015 @05:43PM (#10768609)
That quote is interesting, but the fact that they have to explicitly call it out implies to me that the mere act of writing the dereference is undefined behavior for NULL in all other cases.

I'm pretty sure the dereference is immediately UB (other than the case you quote here). Consider that when optimizations are off, that line will probably immediately execute a load instruction, generating a segfault.

Re:The Dangers of Super Smart Compilers by nkurz on Sunday December 20, 2015 @06:30PM (#10768771)
I thought it would be interesting to see how some different compilers actually behave here. This was my test program:

  nate@haswell:~/tmp$ cat deref.c
  /* gcc -fno-inline -O3 -g -Wall deref.c -o deref */
  /* (or as desired to show particular outcome) */

  #include <stdio.h>
  #include <stdlib.h>

  void deref_and_print(int *ptr) {
    int i = *ptr;  /* undefined behavior if ptr is NULL */
    if (ptr == NULL) printf("NULL\n");
    else printf("%d\n", i);
  }

  int main(int argc, char **argv) {
    int *ptr = NULL;
    if (argc <= 1) {
      printf("Usage: %s [arg]\n", argv[0]);
      printf(" Demonstrates undefined behavior if 'arg'");
      printf(" is not a positive integer\n");
      exit(1);
    }
    int i = atoi(argv[1]);
    if (i > 0) ptr = &i;
    deref_and_print(ptr);
    exit(0);
  }
As you guessed, icc, gcc, and clang all crash with a segfault for 'deref 0' when compiled with -O0. But more interestingly, when compiled with -O1, -O2, or -O3, clang prints "NULL", while icc and gcc continue to crash.
Re:The Dangers of Super Smart Compilers by mikeash on Sunday December 20, 2015 @07:34PM (#10768945)
Nice test. Surprising results for clang. I take it that it doesn't crash for you when it prints NULL? That's the case for me. I'd have thought it would either remove the NULL check and crash, or leave it in but continue to dereference NULL, and thus crash.
Re:The Dangers of Super Smart Compilers by saurik on Sunday December 20, 2015 @09:19PM (#10769227)
The code when it doesn't crash has been reorganized by the compiler so the indirection doesn't even happen until it is preparing the arguments for the printf, which is in an else after the NULL check. If you don't need the value of a computation in one of two sides of an if statement and you know there are no legitimate side effects (I say "legitimate", as crashing does not count) to the calculation, it makes sense to delay the execution of that logic until and unless you actually need it done. I thereby don't find either result surprising here: it is just a demonstration of different optimization decisions and abilities of the two compilers.
Re:The Dangers of Super Smart Compilers by andrewflnr on Sunday December 20, 2015 @08:20PM (#10769059)
Of course if the compiler can prove from my code that some invariant holds, I want it to optimize out the check. What I resent is the compiler deriving invariants from no other basis than "standard said so".
Re:The Dangers of Super Smart Compilers by mikeash on Sunday December 20, 2015 @08:29PM (#10769086)
There's no undefined behavior there. It's just an example of why one might want the compiler to entirely ignore code you wrote.

If you want to use undefined behavior to elide the NULL checks, consider:

    int computation(int *a, int *b) {
        if(a == NULL && b == NULL) return 0;
        if(a == NULL) return *b;
        if(b == NULL) return *a;
        return ...something with *a and *b...;
    }

    ...elsewhere...
    int *a = malloc(sizeof(*a) * 1024);
    int *b = malloc(sizeof(*a) * 1024);
    for(int i = 0; i < 1024; i++) {
        a[i] = i;
        b[i] = i * 2;
    }
    int c[1024];
    for(int i = 0; i < 1024; i++)
        c = computation(a + i, b + i);
The compiler is allowed to remove the NULL checks from an inlined computation here, since the code already dereferenced a and b in the initialization step. Failing to do so would make the code a lot slower, and this optimization seems completely reasonable to me.
Re:The Dangers of Super Smart Compilers by saurik on Sunday December 20, 2015 @09:16PM (#10769215)
But the person you are responding to specially said that they like it when the compiler determines things like this (where it is discernible from the code written that some of it is repetitive and unnecessary), and yet still has an issue when the compiler randomly goes and does something that can't be demonstrated from the code because, in their words, "the language said so".

My pet one of these is "this (by which I mean the pointer of the current object, not the demonstrative pronoun ;P) cannot be NULL". clang has started outputting messages to me that it will soon stop honoring my checks that this is not NULL, entirely removing them from my code, even in cases where this actually can be NULL and the code is not guaranteed to crash in some predictable way. If the language helped me guarantee that this was never NULL, that would be one thing, but it doesn't, and the compiler has decided, for reasons I don't understand, to remove one of the only mechanisms I currently have to detect, log, and mitigate.

References are a similar thing: it would be one thing if dereferencing a NULL pointer caused my program to crash, so clearly the NULL checks on the address of a reference are not useful. But it doesn't work like that. Dereferencing a NULL pointer returns a NULL reference that doesn't cause a crash until the pointer is used. This is actually kind of similar to weakly-linked symbols, where a declared function can have its address be NULL. This is a feature of linkers and the compiler and puts people in a regime where it sometimes makes a lot of sense to compare the address of an expression with NULL.

But somehow, this one is special; so special that even though the compiler knew what I wanted so clearly it felt the need to spit out a paragraph of nonsense at me to tell me that I should remove this check, and that it really didn't want this check in my code in the first place, if I was stupid enough to leave it in my code it was going to delete it for me. I just... I don't understand how that is even remotely reasonable behavior. If it was a side effect of the optimizer and there was no way to surmise what I wanted, then that would be one thing: but the compiler is detecting my code, and demanding that either I remove it myself or it will take control? WTF.

Re:The Dangers of Super Smart Compilers by __david__ on Sunday December 20, 2015 @04:14PM (#10768321)
> Default safe, not fast, wherever possible.

That is not the mantra of C. C is designed to be fast and almost all decisions will err towards speed rather than safety.

If you want a safety first language, check out Rust.

Re:The Dangers of Super Smart Compilers by Kristine1975 on Sunday December 20, 2015 @01:12PM (#10767728)
C and C++ are not safe programming languages, though, no matter what the compiler does or doesn't.