Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. So @eddyb and me talked about this, and this comment summarizes that.
  2.  
  3. @eddyb proposes a `bench_input` function with the operational semantics of the identity function, that the optimizer is encouraged / hinted to treat as an _unknown pure_ function (think `extern { const fn bench_input<T>(T) -> T; }`).
  4.  
  5. That is, the statement `bench_input(expr);` can be completely optimized away. Given:
  6.  
  7. ```rust
  8. let mut v = Vec::with_capacity(1);
  9. v.push(1);
  10. let v = bench_input(v);
  11. v[0];
  12. ```
  13.  
  14. the bound check in `v[0]` cannot be removed because `bench_input` could return any vector (e.g. `Vec::new()`). Also, because the return value depends on the input, the write of `1` to memory in the `push` must be flushed before calling `bench_input`.
  15.  
  16. However, because the `v[0];` result is not used, that could be optimized away, and because `v` is not used, and `bench_input` is pure, actually the whole snippet can be optimized away.
  17.  
  18. To prevent that from happening, @eddyb proposes to add `bench_output(x)`, which has the same operational semantics as `mem::forget`: it leaks its value, runs no destructors, but which the optimizer is encouraged to treat as an _unknown_ function with read-only side-effects that depend on `x`.
  19.  
  20. With that, one can change the snippet above to:
  21.  
  22. ```rust
  23. let mut v = Vec::with_capacity(1);
  24. v.push(1);
  25. let v = bench_input(v);
  26. bench_output(v[0]);
  27. ```
  28.  
  29. to prevent the code from being removed.
  30.  
  31. Note: `bench_output` cannot be implemented as `fn bench_output<T>(x: T) { bench_input(x); }`, because that would mean that it can be removed. It must therefore be a special API.
  32.  
  33. Something like `black_box`, as proposed in this RFC, would then be implemented as:
  34.  
  35. ```rust
  36. fn black_box<T>(x: T) -> T {
  37. bench_output(&x);
  38. bench_input(x)
  39. }
  40. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement