1# InstCombine contributor guide 2 3This guide lays out a series of rules that contributions to InstCombine should 4follow. **Following these rules will results in much faster PR approvals.** 5 6## Tests 7 8### Precommit tests 9 10Tests for new optimizations or miscompilation fixes should be pre-committed. 11This means that you first commit the test with CHECK lines showing the behavior 12*without* your change. Your actual change will then only contain CHECK line 13diffs relative to that baseline. 14 15This means that pull requests should generally contain two commits: First, 16one commit adding new tests with baseline check lines. Second, a commit with 17functional changes and test diffs. 18 19If the second commit in your PR does not contain test diffs, you did something 20wrong. Either you made a mistake when generating CHECK lines, or your tests are 21not actually affected by your patch. 22 23Exceptions: When fixing assertion failures or infinite loops, do not pre-commit 24tests. 25 26### Use `update_test_checks.py` 27 28CHECK lines should be generated using the `update_test_checks.py` script. Do 29**not** manually edit check lines after using it. 30 31Be sure to use the correct opt binary when using the script. For example, if 32your build directory is `build`, then you'll want to run: 33 34```sh 35llvm/utils/update_test_checks.py --opt-binary build/bin/opt \ 36 llvm/test/Transforms/InstCombine/the_test.ll 37``` 38 39Exceptions: Hand-written CHECK lines are allowed for debuginfo tests. 40 41### General testing considerations 42 43Place all tests relating to a transform into a single file. If you are adding 44a regression test for a crash/miscompile in an existing transform, find the 45file where the existing tests are located. A good way to do that is to comment 46out the transform and see which tests fail. 47 48Make tests minimal. Only test exactly the pattern being transformed. If your 49original motivating case is a larger pattern that your fold enables to 50optimize in some non-trivial way, you may add it as well -- however, the bulk 51of the test coverage should be minimal. 52 53Give tests short, but meaningful names. Don't call them `@test1`, `@test2` etc. 54For example, a test checking multi-use behavior of a fold involving the 55addition of two selects might be called `@add_of_selects_multi_use`. 56 57Add representative tests for each test category (discussed below), but don't 58test all combinations of everything. If you have multi-use tests, and you have 59commuted tests, you shouldn't also add commuted multi-use tests. 60 61Prefer to keep bit-widths for tests low to improve performance of proof checking using alive2. Using `i8` is better than `i128` where possible. 62 63### Add negative tests 64 65Make sure to add tests for which your transform does **not** apply. Start with 66one of the test cases that succeeds and then create a sequence of negative 67tests, such that **exactly one** different pre-condition of your transform is 68not satisfied in each test. 69 70### Add multi-use tests 71 72Add multi-use tests that ensures your transform does not increase instruction 73count if some instructions have additional uses. The standard pattern is to 74introduce extra uses with function calls: 75 76```llvm 77declare void @use(i8) 78 79define i8 @add_mul_const_multi_use(i8 %x) { 80 %add = add i8 %x, 1 81 call void @use(i8 %add) 82 %mul = mul i8 %add, 3 83 ret i8 %mul 84} 85``` 86 87Exceptions: For transform that only produce one instruction, multi-use tests 88may be omitted. 89 90### Add commuted tests 91 92If the transform involves commutative operations, add tests with commuted 93(swapped) operands. 94 95Make sure that the operand order stays intact in the CHECK lines of your 96pre-commited tests. You should not see something like this: 97 98```llvm 99; CHECK-NEXT: [[OR:%.*]] = or i8 [[X]], [[Y]] 100; ... 101%or = or i8 %y, %x 102``` 103 104If this happens, you may need to change one of the operands to have higher 105complexity (include the "thwart" comment in that case): 106 107```llvm 108%y2 = mul i8 %y, %y ; thwart complexity-based canonicalization 109%or = or i8 %y, %x 110``` 111 112### Add vector tests 113 114When possible, it is recommended to add at least one test that uses vectors 115instead of scalars. 116 117For patterns that include constants, we distinguish three kinds of tests. 118The first are "splat" vectors, where all the vector elements are the same. 119These tests *should* usually fold without additional effort. 120 121```llvm 122define <2 x i8> @add_mul_const_vec_splat(<2 x i8> %x) { 123 %add = add <2 x i8> %x, <i8 1, i8 1> 124 %mul = mul <2 x i8> %add, <i8 3, i8 3> 125 ret <2 x i8> %mul 126} 127``` 128 129A minor variant is to replace some of the splat elements with poison. These 130will often also fold without additional effort. 131 132```llvm 133define <2 x i8> @add_mul_const_vec_splat_poison(<2 x i8> %x) { 134 %add = add <2 x i8> %x, <i8 1, i8 poison> 135 %mul = mul <2 x i8> %add, <i8 3, i8 poison> 136 ret <2 x i8> %mul 137} 138``` 139 140Finally, you can have non-splat vectors, where the vector elements are not 141the same: 142 143```llvm 144define <2 x i8> @add_mul_const_vec_non_splat(<2 x i8> %x) { 145 %add = add <2 x i8> %x, <i8 1, i8 5> 146 %mul = mul <2 x i8> %add, <i8 3, i8 6> 147 ret <2 x i8> %mul 148} 149``` 150 151Non-splat vectors will often not fold by default. You should **not** try to 152make them fold, unless doing so does not add **any** additional complexity. 153You should still add the test though, even if it does not fold. 154 155### Flag tests 156 157If your transform involves instructions that can have poison-generating flags, 158such as `nuw` and `nsw` on `add`, you should test how these interact with the 159transform. 160 161If your transform *requires* a certain flag for correctness, make sure to add 162negative tests missing the required flag. 163 164If your transform doesn't require flags for correctness, you should have tests 165for preservation behavior. If the input instructions have certain flags, are 166they preserved in the output instructions, if it is valid to preserve them? 167(This depends on the transform. Check with alive2.) 168 169The same also applies to fast-math-flags (FMF). In that case, please always 170test specific flags like `nnan`, `nsz` or `reassoc`, rather than the umbrella 171`fast` flag. 172 173### Other tests 174 175The test categories mentioned above are non-exhaustive. There may be more tests 176to be added, depending on the instructions involved in the transform. Some 177examples: 178 179 * 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. 180 * 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. 181 * For folds that involve phis, you may want to check that the case of multiple incoming values from one block is handled correctly. 182 183## Proofs 184 185Your pull request description should contain one or more 186[alive2 proofs](https://alive2.llvm.org/ce/) for the correctness of the 187proposed transform. 188 189### Basics 190 191Proofs are written using LLVM IR, by specifying a `@src` and `@tgt` function. 192It is possible to include multiple proofs in a single file by giving the src 193and tgt functions matching suffixes. 194 195For example, here is a pair of proofs that both `(x-y)+y` and `(x+y)-y` can 196be simplified to `x` ([online](https://alive2.llvm.org/ce/z/MsPPGz)): 197 198```llvm 199define i8 @src_add_sub(i8 %x, i8 %y) { 200 %add = add i8 %x, %y 201 %sub = sub i8 %add, %y 202 ret i8 %sub 203} 204 205define i8 @tgt_add_sub(i8 %x, i8 %y) { 206 ret i8 %x 207} 208 209 210define i8 @src_sub_add(i8 %x, i8 %y) { 211 %sub = sub i8 %x, %y 212 %add = add i8 %sub, %y 213 ret i8 %add 214} 215 216define i8 @tgt_sub_add(i8 %x, i8 %y) { 217 ret i8 %x 218} 219``` 220 221### Use generic values in proofs 222 223Proofs should operate on generic values, rather than specific constants, to the degree that this is possible. 224 225For example, if we want to fold `X s/ C s< X` to `X s> 0`, the following would 226be a *bad* proof: 227 228```llvm 229; Don't do this! 230define i1 @src(i8 %x) { 231 %div = sdiv i8 %x, 123 232 %cmp = icmp slt i8 %div, %x 233 ret i1 %cmp 234} 235 236define i1 @tgt(i8 %x) { 237 %cmp = icmp sgt i8 %x, 0 238 ret i1 %cmp 239} 240``` 241 242This is because it only proves that the transform is correct for the specific 243constant 123. Maybe there are some constants for which the transform is 244incorrect? 245 246The correct way to write this proof is as follows 247([online](https://alive2.llvm.org/ce/z/acjwb6)): 248 249```llvm 250define i1 @src(i8 %x, i8 %C) { 251 %precond = icmp ne i8 %C, 1 252 call void @llvm.assume(i1 %precond) 253 %div = sdiv i8 %x, %C 254 %cmp = icmp slt i8 %div, %x 255 ret i1 %cmp 256} 257 258define i1 @tgt(i8 %x, i8 %C) { 259 %cmp = icmp sgt i8 %x, 0 260 ret i1 %cmp 261} 262``` 263 264Note that the `@llvm.assume` intrinsic is used to specify pre-conditions for 265the transform. In this case, the proof will fail unless we specify `C != 1` as 266a pre-condition. 267 268It should be emphasized that there is, in general, no expectation that the 269IR in the proofs will be transformed by the implemented fold. In the above 270example, the transform would only apply if `%C` is actually a constant, but we 271need to use non-constants in the proof. 272 273### Common pre-conditions 274 275Here are some examples of common preconditions. 276 277```llvm 278; %x is non-negative: 279%nonneg = icmp sgt i8 %x, -1 280call void @llvm.assume(i1 %nonneg) 281 282; %x is a power of two: 283%ctpop = call i8 @llvm.ctpop.i8(i8 %x) 284%pow2 = icmp eq i8 %x, 1 285call void @llvm.assume(i1 %pow2) 286 287; %x is a power of two or zero: 288%ctpop = call i8 @llvm.ctpop.i8(i8 %x) 289%pow2orzero = icmp ult i8 %x, 2 290call void @llvm.assume(i1 %pow2orzero) 291 292; Adding %x and %y does not overflow in a signed sense: 293%wo = call { i8, i1 } @llvm.sadd.with.overflow(i8 %x, i8 %y) 294%ov = extractvalue { i8, i1 } %wo, 1 295%ov.not = xor i1 %ov, true 296call void @llvm.assume(i1 %ov.not) 297``` 298 299### Timeouts 300 301Alive2 proofs will sometimes produce a timeout with the following message: 302 303``` 304Alive2 timed out while processing your query. 305There are a few things you can try: 306 307- remove extraneous instructions, if any 308 309- reduce variable widths, for example to i16, i8, or i4 310 311- add the --disable-undef-input command line flag, which 312 allows Alive2 to assume that arguments to your IR are not 313 undef. This is, in general, unsound: it can cause Alive2 314 to miss bugs. 315``` 316 317This is good advice, follow it! 318 319Reducing the bitwidth usually helps. For floating point numbers, you can use 320the `half` type for bitwidth reduction purposes. For pointers, you can reduce 321the bitwidth by specifying a custom data layout: 322 323```llvm 324; For 16-bit pointers 325target datalayout = "p:16:16" 326``` 327 328If reducing the bitwidth does not help, try `-disable-undef-input`. This will 329often significantly improve performance, but also implies that the correctness 330of the transform with `undef` values is no longer verified. This is usually 331fine if the transform does not increase the number of uses of any value. 332 333Finally, it's possible to build alive2 locally and use `-smt-to=<m>` to verify 334the proof with a larger timeout. If you don't want to do this (or it still 335does not work), please submit the proof you have despite the timeout. 336 337## Implementation 338 339### Real-world usefulness 340 341There is a very large number of transforms that *could* be implemented, but 342only a tiny fraction of them are useful for real-world code. 343 344Transforms that do not have real-world usefulness provide *negative* value to 345the LLVM project, by taking up valuable reviewer time, increasing code 346complexity and increasing compile-time overhead. 347 348We do not require explicit proof of real-world usefulness for every transform 349-- in most cases the usefulness is fairly "obvious". However, the question may 350come up for complex or unusual folds. Keep this in mind when chosing what you 351work on. 352 353In particular, fixes for fuzzer-generated missed optimization reports will 354likely be rejected if there is no evidence of real-world usefulness. 355 356### Pick the correct optimization pass 357 358There are a number of passes and utilities in the InstCombine family, and it 359is important to pick the right place when implementing a fold. 360 361 * `ConstantFolding`: For folding instructions with constant arguments to a constant. (Mainly relevant for intrinsics.) 362 * `ValueTracking`: For analyzing instructions, e.g. for known bits, non-zero, etc. Tests should usually use `-passes=instsimplify`. 363 * `InstructionSimplify`: For folds that do not create new instructions (either fold to existing value or constant). 364 * `InstCombine`: For folds that create or modify instructions. 365 * `AggressiveInstCombine`: For folds that are expensive, or violate InstCombine requirements. 366 * `VectorCombine`: For folds of vector operations that require target-dependent cost-modelling. 367 368Sometimes, 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. 369 370For 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. 371 372### Canonicalization and target-independence 373 374InstCombine is a target-independent canonicalization pass. This means that it 375tries to bring IR into a "canonical form" that other optimizations (both inside 376and outside of InstCombine) can rely on. For this reason, the chosen canonical 377form needs to be the same for all targets, and not depend on target-specific 378cost modelling. 379 380In many cases, "canonicalization" and "optimization" coincide. For example, if 381we convert `x * 2` into `x << 1`, this both makes the IR more canonical 382(because there is now only one way to express the same operation, rather than 383two) and faster (because shifts will usually have lower latency than 384multiplies). 385 386However, there are also canonicalizations that don't serve any direct 387optimization purpose. For example, InstCombine will canonicalize non-strict 388predicates like `ule` to strict predicates like `ult`. `icmp ule i8 %x, 7` 389becomes `icmp ult i8 %x, 8`. This is not an optimization in any meaningful 390sense, but it does reduce the number of cases that other transforms need to 391handle. 392 393If some canonicalization is not profitable for a specific target, then a reverse 394transform needs to be added in the backend. Patches to disable specific 395InstCombine transforms on certain targets, or to drive them using 396target-specific cost-modelling, **will not be accepted**. The only permitted 397target-dependence is on DataLayout and TargetLibraryInfo. 398 399The use of TargetTransformInfo is only allowed for hooks for target-specific 400intrinsics, such as `TargetTransformInfo::instCombineIntrinsic()`. These are 401already inherently target-dependent anyway. 402 403For vector-specific transforms that require cost-modelling, the VectorCombine 404pass can be used instead. In very rare circumstances, if there are no other 405alternatives, target-dependent transforms may be accepted into 406AggressiveInstCombine. 407 408### PatternMatch 409 410Many transforms make use of the matching infrastructure defined in 411[PatternMatch.h](https://github.com/llvm/llvm-project/blame/main/llvm/include/llvm/IR/PatternMatch.h). 412 413Here is a typical usage example: 414 415``` 416// Fold (A - B) + B and B + (A - B) to A. 417Value *A, *B; 418if (match(V, m_c_Add(m_Sub(m_Value(A), m_Value(B)), m_Deferred(B)))) 419 return A; 420``` 421 422And another: 423 424``` 425// Fold A + C1 == C2 to A == C1+C2 426Value *A; 427if (match(V, m_ICmp(Pred, m_Add(m_Value(A), m_APInt(C1)), m_APInt(C2))) && 428 ICmpInst::isEquality(Pred)) 429 return Builder.CreateICmp(Pred, A, 430 ConstantInt::get(A->getType(), *C1 + *C2)); 431``` 432 433Some common matchers are: 434 435 * `m_Value(A)`: Match any value and write it into `Value *A`. 436 * `m_Specific(A)`: Check that the operand equals A. Use this if A is 437 assigned **outside** the pattern. 438 * `m_Deferred(A)`: Check that the operand equals A. Use this if A is 439 assigned **inside** the pattern, for example via `m_Value(A)`. 440 * `m_APInt(C)`: Match a scalar integer constant or splat vector constant into 441 `const APInt *C`. Does not permit undef/poison values. 442 * `m_ImmConstant(C)`: Match any non-constant-expression constant into 443 `Constant *C`. 444 * `m_Constant(C)`: Match any constant into `Constant *C`. Don't use this unless 445 you know what you're doing. 446 * `m_Add(M1, M2)`, `m_Sub(M1, M2)`, etc: Match an add/sub/etc where the first 447 operand matches M1 and the second M2. 448 * `m_c_Add(M1, M2)`, etc: Match an add commutatively. The operands must match 449 either M1 and M2 or M2 and M1. Most instruction matchers have a commutative 450 variant. 451 * `m_ICmp(Pred, M1, M2)` and `m_c_ICmp(Pred, M1, M2)`: Match an icmp, writing 452 the predicate into `IcmpInst::Predicate Pred`. If the commutative version 453 is used, and the operands match in order M2, M1, then `Pred` will be the 454 swapped predicate. 455 * `m_OneUse(M)`: Check that the value only has one use, and also matches M. 456 For example `m_OneUse(m_Add(...))`. See the next section for more 457 information. 458 459See the header for the full list of available matchers. 460 461### InstCombine APIs 462 463InstCombine transforms are handled by `visitXYZ()` methods, where XYZ 464corresponds to the root instruction of your transform. If the outermost 465instruction of the pattern you are matching is an icmp, the fold will be 466located somewhere inside `visitICmpInst()`. 467 468The return value of the visit method is an instruction. You can either return 469a new instruction, in which case it will be inserted before the old one, and 470uses of the old one will be replaced by it. Or you can return the original 471instruction to indicate that *some* kind of change has been made. Finally, a 472nullptr return value indicates that no change occurred. 473 474For example, if your transform produces a single new icmp instruction, you could 475write the following: 476 477``` 478if (...) 479 return new ICmpInst(Pred, X, Y); 480``` 481 482In this case the main InstCombine loop takes care of inserting the instruction 483and replacing uses of the old instruction. 484 485Alternatively, you can also write it like this: 486 487``` 488if (...) 489 return replaceInstUsesWith(OrigI, Builder.CreateICmp(Pred, X, Y)); 490``` 491 492In this case `IRBuilder` will insert the instruction and `replaceInstUsesWith()` 493will replace the uses of the old instruction, and return it to indicate that 494a change occurred. 495 496Both forms are equivalent, and you can use whichever is more convenient in 497context. For example, it's common that folds are inside helper functions that 498return `Value *` and then `replaceInstUsesWith()` is invoked on the result of 499that helper. 500 501InstCombine makes use of a worklist, which needs to be correctly updated during 502transforms. This usually happens automatically, but there are some things to 503keep in mind: 504 505 * Don't use the `Value::replaceAllUsesWith()` API. Use InstCombine's 506 `replaceInstUsesWith()` helper instead. 507 * Don't use the `Instruction::eraseFromParent()` API. Use InstCombine's 508 `eraseInstFromFunction()` helper instead. (Explicitly erasing instruction 509 is usually not necessary, as side-effect free instructions without users 510 are automatically removed.) 511 * Apart from the "directly return an instruction" pattern above, use IRBUilder 512 to create all instruction. Do not manually create and insert them. 513 * When replacing operands or uses of instructions, use `replaceOperand()` 514 and `replaceUse()` instead of `setOperand()`. 515 516### Multi-use handling 517 518Transforms should usually not increase the total number of instructions. This 519is not a hard requirement: For example, it is usually worthwhile to replace a 520single division instruction with multiple other instructions. 521 522For example, if you have a transform that replaces two instructions, with two 523other instructions, this is (usually) only profitable if *both* the original 524instructions can be removed. To ensure that both instructions are removed, you 525need to add a one-use check for the inner instruction. 526 527One-use checks can be performed using the `m_OneUse()` matcher, or the 528`V->hasOneUse()` method. 529 530### Generalization 531 532Transforms can both be too specific (only handling some odd subset of patterns, 533leading to unexpected optimization cliffs) and too general (introducing 534complexity to handle cases with no real-world relevance). The right level of 535generality is quite subjective, so this section only provides some broad 536guidelines. 537 538 * Avoid transforms that are hardcoded to specific constants. Try to figure 539 out what the general rule for arbitrary constants is. 540 * Add handling for conjugate patterns. For example, if you implement a fold 541 for `icmp eq`, you almost certainly also want to support `icmp ne`, with the 542 inverse result. Similarly, if you implement a pattern for `and` of `icmp`s, 543 you should also handle the de-Morgan conjugate using `or`. 544 * Handle non-splat vector constants if doing so is free, but do not add 545 handling for them if it adds any additional complexity to the code. 546 * Do not handle non-canonical patterns, unless there is a specific motivation 547 to do so. For example, it may sometimes be worthwhile to handle a pattern 548 that would normally be converted into a different canonical form, but can 549 still occur in multi-use scenarios. This is fine to do if there is specific 550 real-world motivation, but you should not go out of your way to do this 551 otherwise. 552 * Sometimes the motivating pattern uses a constant value with certain 553 properties, but the fold can be generalized to non-constant values by making 554 use of ValueTracking queries. Whether this makes sense depends on the case, 555 but it's usually a good idea to only handle the constant pattern first, and 556 then generalize later if it seems useful. 557 558## Guidelines for reviewers 559 560 * Do not ask new contributors to implement non-splat vector support in code 561 reviews. If you think non-splat vector support for a fold is both 562 worthwhile and policy-compliant (that is, the handling would not result in 563 any appreciable increase in code complexity), implement it yourself in a 564 follow-up patch. 565