Non-splat vectors will often not fold by default. You should **not** try to
make them fold, unless doing so does not add **any** additional complexity.
You should still add the test though, even if it does not fold.
### Flag tests
If your transform involves instructions that can have poison-generating flags,
such as `nuw` and `nsw` on `add`, you should test how these interact with the
transform.
If your transform *requires* a certain flag for correctness, make sure to add
negative tests missing the required flag.
If your transform doesn't require flags for correctness, you should have tests
for preservation behavior. If the input instructions have certain flags, are
they preserved in the output instructions, if it is valid to preserve them?
(This depends on the transform. Check with alive2.)
The same also applies to fast-math-flags (FMF). In that case, please always
test specific flags like `nnan`, `nsz` or `reassoc`, rather than the umbrella
`fast` flag.
### Other tests
The test categories mentioned above are non-exhaustive. There may be more tests
to be added, depending on the instructions involved in the transform. Some
examples:
* For folds involving memory accesses like load/store, check that scalable vectors and non-byte-size types (like i3) are handled correctly. Also check that volatile/atomic are handled.
* For folds that interact with the bitwidth in some non-trivial way, check an illegal type like i13. Also confirm that the transform is correct for i1.
* For folds that involve phis, you may want to check that the case of multiple incoming values from one block is handled correctly.
## Proofs
Your pull request description should contain one or more
[alive2 proofs](https://alive2.llvm.org/ce/) for the correctness of the
proposed transform.
### Basics
Proofs are written using LLVM IR, by specifying a `@src` and `@tgt` function.
It is possible to include multiple proofs in a single file by giving the src
and tgt functions matching suffixes.
For example, here is a pair of proofs that both `(x-y)+y` and `(x+y)-y` can
be simplified to `x` ([online](https://alive2.llvm.org/ce/z/MsPPGz)):
```llvm
define i8 @src_add_sub(i8 %x, i8 %y) {
%add = add i8 %x, %y
%sub = sub i8 %add, %y
ret i8 %sub
}
define i8 @tgt_add_sub(i8 %x, i8 %y) {
ret i8 %x
}
define i8 @src_sub_add(i8 %x, i8 %y) {
%sub = sub i8 %x, %y
%add = add i8 %sub, %y
ret i8 %add
}
define i8 @tgt_sub_add(i8 %x, i8 %y) {
ret i8 %x
}
```
### Use generic values in proofs
Proofs should operate on generic values, rather than specific constants, to the degree that this is possible.
For example, if we want to fold `X s/ C s< X` to `X s> 0`, the following would
be a *bad* proof:
```llvm
; Don't do this!
define i1 @src(i8 %x) {
%div = sdiv i8 %x, 123
%cmp = icmp slt i8 %div, %x
ret i1 %cmp
}
define i1 @tgt(i8 %x) {
%cmp = icmp sgt i8 %x, 0
ret i1 %cmp
}
```
This is because it only proves that the transform is correct for the specific
constant 123. Maybe there are some constants for which the transform is
incorrect?
The correct way to write this proof is as follows
([online](https://alive2.llvm.org/ce/z/acjwb6)):
```llvm
define i1 @src(i8 %x, i8 %C) {
%precond = icmp ne i8 %C, 1
call void @llvm.assume(i1 %precond)
%div = sdiv i8 %x, %C
%cmp = icmp slt i8 %div, %x
ret i1 %cmp
}
define i1 @tgt(i8 %x, i8 %C) {
%cmp = icmp sgt i8 %x, 0
ret i1 %cmp
}
```
Note that the `@llvm.assume` intrinsic is used to specify pre-conditions for
the transform. In this case, the proof will fail unless we specify `C != 1` as
a pre-condition.
It should be emphasized that there is, in general, no expectation that the
IR in the proofs will be transformed by the implemented fold. In the above
example, the transform would only apply if `%C` is actually a constant, but we
need to use non-constants in the proof.
### Common pre-conditions
Here are some examples of common preconditions.
```llvm
; %x is non-negative:
%nonneg = icmp sgt i8 %x, -1
call void @llvm.assume(i1 %nonneg)
; %x is a power of two:
%ctpop = call i8 @llvm.ctpop.i8(i8 %x)
%pow2 = icmp eq i8 %x, 1
call void @llvm.assume(i1 %pow2)
; %x is a power of two or zero:
%ctpop = call i8 @llvm.ctpop.i8(i8 %x)
%pow2orzero = icmp ult i8 %x, 2
call void @llvm.assume(i1 %pow2orzero)
; Adding %x and %y does not overflow in a signed sense:
Alive2 proofs will sometimes produce a timeout with the following message:
```
Alive2 timed out while processing your query.
There are a few things you can try:
- remove extraneous instructions, if any
- reduce variable widths, for example to i16, i8, or i4
- add the --disable-undef-input command line flag, which
allows Alive2 to assume that arguments to your IR are not
undef. This is, in general, unsound: it can cause Alive2
to miss bugs.
```
This is good advice, follow it!
Reducing the bitwidth usually helps. For floating point numbers, you can use
the `half` type for bitwidth reduction purposes. For pointers, you can reduce
the bitwidth by specifying a custom data layout:
```llvm
; For 16-bit pointers
target datalayout = "p:16:16"
```
If reducing the bitwidth does not help, try `-disable-undef-input`. This will
often significantly improve performance, but also implies that the correctness
of the transform with `undef` values is no longer verified. This is usually
fine if the transform does not increase the number of uses of any value.
Finally, it's possible to build alive2 locally and use `-smt-to=<m>` to verify
the proof with a larger timeout. If you don't want to do this (or it still
does not work), please submit the proof you have despite the timeout.
## Implementation
### Real-world usefulness
There is a very large number of transforms that *could* be implemented, but
only a tiny fraction of them are useful for real-world code.
Transforms that do not have real-world usefulness provide *negative* value to
the LLVM project, by taking up valuable reviewer time, increasing code
complexity and increasing compile-time overhead.
We do not require explicit proof of real-world usefulness for every transform
-- in most cases the usefulness is fairly "obvious". However, the question may
come up for complex or unusual folds. Keep this in mind when chosing what you
work on.
In particular, fixes for fuzzer-generated missed optimization reports will
likely be rejected if there is no evidence of real-world usefulness.
### Pick the correct optimization pass
There are a number of passes and utilities in the InstCombine family, and it
is important to pick the right place when implementing a fold.
*`ConstantFolding`: For folding instructions with constant arguments to a constant. (Mainly relevant for intrinsics.)
*`ValueTracking`: For analyzing instructions, e.g. for known bits, non-zero, etc. Tests should usually use `-passes=instsimplify`.
*`InstructionSimplify`: For folds that do not create new instructions (either fold to existing value or constant).
*`InstCombine`: For folds that create or modify instructions.
*`AggressiveInstCombine`: For folds that are expensive, or violate InstCombine requirements.
*`VectorCombine`: For folds of vector operations that require target-dependent cost-modelling.
Sometimes, folds that logically belong in InstSimplify are placed in InstCombine instead, for example because they are too expensive, or because they are structurally simpler to implement in InstCombine.
For example, if a fold produces new instructions in some cases but returns an existing value in others, it may be preferable to keep all cases in InstCombine, rather than trying to split them among InstCombine and InstSimplify.
### Canonicalization and target-independence
InstCombine is a target-independent canonicalization pass. This means that it
tries to bring IR into a "canonical form" that other optimizations (both inside
and outside of InstCombine) can rely on. For this reason, the chosen canonical
form needs to be the same for all targets, and not depend on target-specific
cost modelling.
In many cases, "canonicalization" and "optimization" coincide. For example, if
we convert `x * 2` into `x << 1`, this both makes the IR more canonical
(because there is now only one way to express the same operation, rather than
two) and faster (because shifts will usually have lower latency than
multiplies).
However, there are also canonicalizations that don't serve any direct
optimization purpose. For example, InstCombine will canonicalize non-strict
predicates like `ule` to strict predicates like `ult`. `icmp ule i8 %x, 7`
becomes `icmp ult i8 %x, 8`. This is not an optimization in any meaningful
sense, but it does reduce the number of cases that other transforms need to
handle.
If some canonicalization is not profitable for a specific target, then a reverse
transform needs to be added in the backend. Patches to disable specific
InstCombine transforms on certain targets, or to drive them using
target-specific cost-modelling, **will not be accepted**. The only permitted
target-dependence is on DataLayout and TargetLibraryInfo.
The use of TargetTransformInfo is only allowed for hooks for target-specific
intrinsics, such as `TargetTransformInfo::instCombineIntrinsic()`. These are
already inherently target-dependent anyway.
For vector-specific transforms that require cost-modelling, the VectorCombine
pass can be used instead. In very rare circumstances, if there are no other
alternatives, target-dependent transforms may be accepted into
AggressiveInstCombine.
### PatternMatch
Many transforms make use of the matching infrastructure defined in