Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This pass reassociates n-ary add expressions and eliminates the redundancy
10
// exposed by the reassociation.
11
//
12
// A motivating example:
13
//
14
//   void foo(int a, int b) {
15
//     bar(a + b);
16
//     bar((a + 2) + b);
17
//   }
18
//
19
// An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify
20
// the above code to
21
//
22
//   int t = a + b;
23
//   bar(t);
24
//   bar(t + 2);
25
//
26
// However, the Reassociate pass is unable to do that because it processes each
27
// instruction individually and believes (a + 2) + b is the best form according
28
// to its rank system.
29
//
30
// To address this limitation, NaryReassociate reassociates an expression in a
31
// form that reuses existing instructions. As a result, NaryReassociate can
32
// reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that
33
// (a + b) is computed before.
34
//
35
// NaryReassociate works as follows. For every instruction in the form of (a +
36
// b) + c, it checks whether a + c or b + c is already computed by a dominating
37
// instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b +
38
// c) + a and removes the redundancy accordingly. To efficiently look up whether
39
// an expression is computed before, we store each instruction seen and its SCEV
40
// into an SCEV-to-instruction map.
41
//
42
// Although the algorithm pattern-matches only ternary additions, it
43
// automatically handles many >3-ary expressions by walking through the function
44
// in the depth-first order. For example, given
45
//
46
//   (a + c) + d
47
//   ((a + b) + c) + d
48
//
49
// NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites
50
// ((a + c) + b) + d into ((a + c) + d) + b.
51
//
52
// Finally, the above dominator-based algorithm may need to be run multiple
53
// iterations before emitting optimal code. One source of this need is that we
54
// only split an operand when it is used only once. The above algorithm can
55
// eliminate an instruction and decrease the usage count of its operands. As a
56
// result, an instruction that previously had multiple uses may become a
57
// single-use instruction and thus eligible for split consideration. For
58
// example,
59
//
60
//   ac = a + c
61
//   ab = a + b
62
//   abc = ab + c
63
//   ab2 = ab + b
64
//   ab2c = ab2 + c
65
//
66
// In the first iteration, we cannot reassociate abc to ac+b because ab is used
67
// twice. However, we can reassociate ab2c to abc+b in the first iteration. As a
68
// result, ab2 becomes dead and ab will be used only once in the second
69
// iteration.
70
//
71
// Limitations and TODO items:
72
//
73
// 1) We only considers n-ary adds and muls for now. This should be extended
74
// and generalized.
75
//
76
//===----------------------------------------------------------------------===//
77
78
#include "llvm/Transforms/Scalar/NaryReassociate.h"
79
#include "llvm/ADT/DepthFirstIterator.h"
80
#include "llvm/ADT/SmallVector.h"
81
#include "llvm/Analysis/AssumptionCache.h"
82
#include "llvm/Analysis/ScalarEvolution.h"
83
#include "llvm/Analysis/TargetLibraryInfo.h"
84
#include "llvm/Analysis/TargetTransformInfo.h"
85
#include "llvm/Transforms/Utils/Local.h"
86
#include "llvm/Analysis/ValueTracking.h"
87
#include "llvm/IR/BasicBlock.h"
88
#include "llvm/IR/Constants.h"
89
#include "llvm/IR/DataLayout.h"
90
#include "llvm/IR/DerivedTypes.h"
91
#include "llvm/IR/Dominators.h"
92
#include "llvm/IR/Function.h"
93
#include "llvm/IR/GetElementPtrTypeIterator.h"
94
#include "llvm/IR/IRBuilder.h"
95
#include "llvm/IR/InstrTypes.h"
96
#include "llvm/IR/Instruction.h"
97
#include "llvm/IR/Instructions.h"
98
#include "llvm/IR/Module.h"
99
#include "llvm/IR/Operator.h"
100
#include "llvm/IR/PatternMatch.h"
101
#include "llvm/IR/Type.h"
102
#include "llvm/IR/Value.h"
103
#include "llvm/IR/ValueHandle.h"
104
#include "llvm/Pass.h"
105
#include "llvm/Support/Casting.h"
106
#include "llvm/Support/ErrorHandling.h"
107
#include "llvm/Transforms/Scalar.h"
108
#include <cassert>
109
#include <cstdint>
110
111
using namespace llvm;
112
using namespace PatternMatch;
113
114
#define DEBUG_TYPE "nary-reassociate"
115
116
namespace {
117
118
class NaryReassociateLegacyPass : public FunctionPass {
119
public:
120
  static char ID;
121
122
2.90k
  NaryReassociateLegacyPass() : FunctionPass(ID) {
123
2.90k
    initializeNaryReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
124
2.90k
  }
125
126
2.88k
  bool doInitialization(Module &M) override {
127
2.88k
    return false;
128
2.88k
  }
129
130
  bool runOnFunction(Function &F) override;
131
132
2.88k
  void getAnalysisUsage(AnalysisUsage &AU) const override {
133
2.88k
    AU.addPreserved<DominatorTreeWrapperPass>();
134
2.88k
    AU.addPreserved<ScalarEvolutionWrapperPass>();
135
2.88k
    AU.addPreserved<TargetLibraryInfoWrapperPass>();
136
2.88k
    AU.addRequired<AssumptionCacheTracker>();
137
2.88k
    AU.addRequired<DominatorTreeWrapperPass>();
138
2.88k
    AU.addRequired<ScalarEvolutionWrapperPass>();
139
2.88k
    AU.addRequired<TargetLibraryInfoWrapperPass>();
140
2.88k
    AU.addRequired<TargetTransformInfoWrapperPass>();
141
2.88k
    AU.setPreservesCFG();
142
2.88k
  }
143
144
private:
145
  NaryReassociatePass Impl;
146
};
147
148
} // end anonymous namespace
149
150
char NaryReassociateLegacyPass::ID = 0;
151
152
36.0k
INITIALIZE_PASS_BEGIN(NaryReassociateLegacyPass, "nary-reassociate",
153
36.0k
                      "Nary reassociation", false, false)
154
36.0k
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
155
36.0k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
156
36.0k
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
157
36.0k
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
158
36.0k
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
159
36.0k
INITIALIZE_PASS_END(NaryReassociateLegacyPass, "nary-reassociate",
160
                    "Nary reassociation", false, false)
161
162
2.90k
FunctionPass *llvm::createNaryReassociatePass() {
163
2.90k
  return new NaryReassociateLegacyPass();
164
2.90k
}
165
166
28.2k
bool NaryReassociateLegacyPass::runOnFunction(Function &F) {
167
28.2k
  if (skipFunction(F))
168
8
    return false;
169
28.2k
170
28.2k
  auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
171
28.2k
  auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
172
28.2k
  auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
173
28.2k
  auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
174
28.2k
  auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
175
28.2k
176
28.2k
  return Impl.runImpl(F, AC, DT, SE, TLI, TTI);
177
28.2k
}
178
179
PreservedAnalyses NaryReassociatePass::run(Function &F,
180
17
                                           FunctionAnalysisManager &AM) {
181
17
  auto *AC = &AM.getResult<AssumptionAnalysis>(F);
182
17
  auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
183
17
  auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
184
17
  auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
185
17
  auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
186
17
187
17
  if (!runImpl(F, AC, DT, SE, TLI, TTI))
188
4
    return PreservedAnalyses::all();
189
13
190
13
  PreservedAnalyses PA;
191
13
  PA.preserveSet<CFGAnalyses>();
192
13
  PA.preserve<ScalarEvolutionAnalysis>();
193
13
  return PA;
194
13
}
195
196
bool NaryReassociatePass::runImpl(Function &F, AssumptionCache *AC_,
197
                                  DominatorTree *DT_, ScalarEvolution *SE_,
198
                                  TargetLibraryInfo *TLI_,
199
28.2k
                                  TargetTransformInfo *TTI_) {
200
28.2k
  AC = AC_;
201
28.2k
  DT = DT_;
202
28.2k
  SE = SE_;
203
28.2k
  TLI = TLI_;
204
28.2k
  TTI = TTI_;
205
28.2k
  DL = &F.getParent()->getDataLayout();
206
28.2k
207
28.2k
  bool Changed = false, ChangedInThisIteration;
208
28.3k
  do {
209
28.3k
    ChangedInThisIteration = doOneIteration(F);
210
28.3k
    Changed |= ChangedInThisIteration;
211
28.3k
  } while (ChangedInThisIteration);
212
28.2k
  return Changed;
213
28.2k
}
214
215
// Whitelist the instruction types NaryReassociate handles for now.
216
72.0k
static bool isPotentiallyNaryReassociable(Instruction *I) {
217
72.0k
  switch (I->getOpcode()) {
218
72.0k
  case Instruction::Add:
219
22.7k
  case Instruction::GetElementPtr:
220
22.7k
  case Instruction::Mul:
221
22.7k
    return true;
222
49.3k
  default:
223
49.3k
    return false;
224
72.0k
  }
225
72.0k
}
226
227
28.3k
bool NaryReassociatePass::doOneIteration(Function &F) {
228
28.3k
  bool Changed = false;
229
28.3k
  SeenExprs.clear();
230
28.3k
  // Process the basic blocks in a depth first traversal of the dominator
231
28.3k
  // tree. This order ensures that all bases of a candidate are in Candidates
232
28.3k
  // when we process it.
233
31.3k
  for (const auto Node : depth_first(DT)) {
234
31.3k
    BasicBlock *BB = Node->getBlock();
235
211k
    for (auto I = BB->begin(); I != BB->end(); 
++I180k
) {
236
180k
      if (SE->isSCEVable(I->getType()) && 
isPotentiallyNaryReassociable(&*I)72.0k
) {
237
22.7k
        const SCEV *OldSCEV = SE->getSCEV(&*I);
238
22.7k
        if (Instruction *NewI = tryReassociate(&*I)) {
239
118
          Changed = true;
240
118
          SE->forgetValue(&*I);
241
118
          I->replaceAllUsesWith(NewI);
242
118
          WeakVH NewIExist = NewI;
243
118
          // If SeenExprs/NewIExist contains I's WeakTrackingVH/WeakVH, that
244
118
          // entry will be replaced with nullptr if deleted.
245
118
          RecursivelyDeleteTriviallyDeadInstructions(&*I, TLI);
246
118
          if (!NewIExist) {
247
1
            // Rare occation where the new instruction (NewI) have been removed,
248
1
            // probably due to parts of the input code was dead from the
249
1
            // beginning, reset the iterator and start over from the beginning
250
1
            I = BB->begin();
251
1
            continue;
252
1
          }
253
117
          I = NewI->getIterator();
254
117
        }
255
22.7k
        // Add the rewritten instruction to SeenExprs; the original instruction
256
22.7k
        // is deleted.
257
22.7k
        const SCEV *NewSCEV = SE->getSCEV(&*I);
258
22.7k
        SeenExprs[NewSCEV].push_back(WeakTrackingVH(&*I));
259
22.7k
        // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
260
22.7k
        // is equivalent to I. However, ScalarEvolution::getSCEV may
261
22.7k
        // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose
262
22.7k
        // we reassociate
263
22.7k
        //   I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
264
22.7k
        // to
265
22.7k
        //   NewI = &a[sext(i)] + sext(j).
266
22.7k
        //
267
22.7k
        // ScalarEvolution computes
268
22.7k
        //   getSCEV(I)    = a + 4 * sext(i + j)
269
22.7k
        //   getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
270
22.7k
        // which are different SCEVs.
271
22.7k
        //
272
22.7k
        // To alleviate this issue of ScalarEvolution not always capturing
273
22.7k
        // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
274
22.7k
        // map both SCEV before and after tryReassociate(I) to I.
275
22.7k
        //
276
22.7k
        // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
277
22.7k
        if (NewSCEV != OldSCEV)
278
10
          SeenExprs[OldSCEV].push_back(WeakTrackingVH(&*I));
279
22.7k
      }
280
180k
    }
281
31.3k
  }
282
28.3k
  return Changed;
283
28.3k
}
284
285
22.7k
Instruction *NaryReassociatePass::tryReassociate(Instruction *I) {
286
22.7k
  switch (I->getOpcode()) {
287
22.7k
  case Instruction::Add:
288
7.20k
  case Instruction::Mul:
289
7.20k
    return tryReassociateBinaryOp(cast<BinaryOperator>(I));
290
15.5k
  case Instruction::GetElementPtr:
291
15.5k
    return tryReassociateGEP(cast<GetElementPtrInst>(I));
292
7.20k
  default:
293
0
    llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
294
22.7k
  }
295
22.7k
}
296
297
static bool isGEPFoldable(GetElementPtrInst *GEP,
298
15.5k
                          const TargetTransformInfo *TTI) {
299
15.5k
  SmallVector<const Value*, 4> Indices;
300
32.7k
  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); 
++I17.2k
)
301
17.2k
    Indices.push_back(*I);
302
15.5k
  return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
303
15.5k
                         Indices) == TargetTransformInfo::TCC_Free;
304
15.5k
}
305
306
15.5k
Instruction *NaryReassociatePass::tryReassociateGEP(GetElementPtrInst *GEP) {
307
15.5k
  // Not worth reassociating GEP if it is foldable.
308
15.5k
  if (isGEPFoldable(GEP, TTI))
309
5.92k
    return nullptr;
310
9.62k
311
9.62k
  gep_type_iterator GTI = gep_type_begin(*GEP);
312
19.9k
  for (unsigned I = 1, E = GEP->getNumOperands(); I != E; 
++I, ++GTI10.3k
) {
313
10.4k
    if (GTI.isSequential()) {
314
10.3k
      if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1,
315
91
                                                  GTI.getIndexedType())) {
316
91
        return NewGEP;
317
91
      }
318
10.3k
    }
319
10.4k
  }
320
9.62k
  
return nullptr9.52k
;
321
9.62k
}
322
323
bool NaryReassociatePass::requiresSignExtension(Value *Index,
324
233
                                                GetElementPtrInst *GEP) {
325
233
  unsigned PointerSizeInBits =
326
233
      DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
327
233
  return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
328
233
}
329
330
GetElementPtrInst *
331
NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
332
10.3k
                                              unsigned I, Type *IndexedType) {
333
10.3k
  Value *IndexToSplit = GEP->getOperand(I + 1);
334
10.3k
  if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) {
335
5.35k
    IndexToSplit = SExt->getOperand(0);
336
5.35k
  } else 
if (ZExtInst *5.03k
ZExt5.03k
= dyn_cast<ZExtInst>(IndexToSplit)) {
337
134
    // zext can be treated as sext if the source is non-negative.
338
134
    if (isKnownNonNegative(ZExt->getOperand(0), *DL, 0, AC, GEP, DT))
339
116
      IndexToSplit = ZExt->getOperand(0);
340
134
  }
341
10.3k
342
10.3k
  if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
343
233
    // If the I-th index needs sext and the underlying add is not equipped with
344
233
    // nsw, we cannot split the add because
345
233
    //   sext(LHS + RHS) != sext(LHS) + sext(RHS).
346
233
    if (requiresSignExtension(IndexToSplit, GEP) &&
347
233
        computeOverflowForSignedAdd(AO, *DL, AC, GEP, DT) !=
348
43
            OverflowResult::NeverOverflows)
349
9
      return nullptr;
350
224
351
224
    Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
352
224
    // IndexToSplit = LHS + RHS.
353
224
    if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
354
87
      return NewGEP;
355
137
    // Symmetrically, try IndexToSplit = RHS + LHS.
356
137
    if (LHS != RHS) {
357
137
      if (auto *NewGEP =
358
4
              tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
359
4
        return NewGEP;
360
10.2k
    }
361
137
  }
362
10.2k
  return nullptr;
363
10.2k
}
364
365
GetElementPtrInst *
366
NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
367
                                              unsigned I, Value *LHS,
368
361
                                              Value *RHS, Type *IndexedType) {
369
361
  // Look for GEP's closest dominator that has the same SCEV as GEP except that
370
361
  // the I-th index is replaced with LHS.
371
361
  SmallVector<const SCEV *, 4> IndexExprs;
372
962
  for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); 
++Index601
)
373
601
    IndexExprs.push_back(SE->getSCEV(*Index));
374
361
  // Replace the I-th index with LHS.
375
361
  IndexExprs[I] = SE->getSCEV(LHS);
376
361
  if (isKnownNonNegative(LHS, *DL, 0, AC, GEP, DT) &&
377
361
      DL->getTypeSizeInBits(LHS->getType()) <
378
279
          DL->getTypeSizeInBits(GEP->getOperand(I)->getType())) {
379
31
    // Zero-extend LHS if it is non-negative. InstCombine canonicalizes sext to
380
31
    // zext if the source operand is proved non-negative. We should do that
381
31
    // consistently so that CandidateExpr more likely appears before. See
382
31
    // @reassociate_gep_assume for an example of this canonicalization.
383
31
    IndexExprs[I] =
384
31
        SE->getZeroExtendExpr(IndexExprs[I], GEP->getOperand(I)->getType());
385
31
  }
386
361
  const SCEV *CandidateExpr = SE->getGEPExpr(cast<GEPOperator>(GEP),
387
361
                                             IndexExprs);
388
361
389
361
  Value *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
390
361
  if (Candidate == nullptr)
391
270
    return nullptr;
392
91
393
91
  IRBuilder<> Builder(GEP);
394
91
  // Candidate does not necessarily have the same pointer type as GEP. Use
395
91
  // bitcast or pointer cast to make sure they have the same type, so that the
396
91
  // later RAUW doesn't complain.
397
91
  Candidate = Builder.CreateBitOrPointerCast(Candidate, GEP->getType());
398
91
  assert(Candidate->getType() == GEP->getType());
399
91
400
91
  // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
401
91
  uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
402
91
  Type *ElementType = GEP->getResultElementType();
403
91
  uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
404
91
  // Another less rare case: because I is not necessarily the last index of the
405
91
  // GEP, the size of the type at the I-th index (IndexedSize) is not
406
91
  // necessarily divisible by ElementSize. For example,
407
91
  //
408
91
  // #pragma pack(1)
409
91
  // struct S {
410
91
  //   int a[3];
411
91
  //   int64 b[8];
412
91
  // };
413
91
  // #pragma pack()
414
91
  //
415
91
  // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
416
91
  //
417
91
  // TODO: bail out on this case for now. We could emit uglygep.
418
91
  if (IndexedSize % ElementSize != 0)
419
0
    return nullptr;
420
91
421
91
  // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
422
91
  Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
423
91
  if (RHS->getType() != IntPtrTy)
424
31
    RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
425
91
  if (IndexedSize != ElementSize) {
426
2
    RHS = Builder.CreateMul(
427
2
        RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
428
2
  }
429
91
  GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(
430
91
      Builder.CreateGEP(GEP->getResultElementType(), Candidate, RHS));
431
91
  NewGEP->setIsInBounds(GEP->isInBounds());
432
91
  NewGEP->takeName(GEP);
433
91
  return NewGEP;
434
91
}
435
436
7.20k
Instruction *NaryReassociatePass::tryReassociateBinaryOp(BinaryOperator *I) {
437
7.20k
  Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
438
7.20k
  // There is no need to reassociate 0.
439
7.20k
  if (SE->getSCEV(I)->isZero())
440
2
    return nullptr;
441
7.19k
  if (auto *NewI = tryReassociateBinaryOp(LHS, RHS, I))
442
24
    return NewI;
443
7.17k
  if (auto *NewI = tryReassociateBinaryOp(RHS, LHS, I))
444
3
    return NewI;
445
7.17k
  return nullptr;
446
7.17k
}
447
448
Instruction *NaryReassociatePass::tryReassociateBinaryOp(Value *LHS, Value *RHS,
449
14.3k
                                                         BinaryOperator *I) {
450
14.3k
  Value *A = nullptr, *B = nullptr;
451
14.3k
  // To be conservative, we reassociate I only when it is the only user of (A op
452
14.3k
  // B).
453
14.3k
  if (LHS->hasOneUse() && 
matchTernaryOp(I, LHS, A, B)10.4k
) {
454
1.31k
    // I = (A op B) op RHS
455
1.31k
    //   = (A op RHS) op B or (B op RHS) op A
456
1.31k
    const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
457
1.31k
    const SCEV *RHSExpr = SE->getSCEV(RHS);
458
1.31k
    if (BExpr != RHSExpr) {
459
1.31k
      if (auto *NewI =
460
25
              tryReassociatedBinaryOp(getBinarySCEV(I, AExpr, RHSExpr), B, I))
461
25
        return NewI;
462
1.29k
    }
463
1.29k
    if (AExpr != RHSExpr) {
464
1.26k
      if (auto *NewI =
465
2
              tryReassociatedBinaryOp(getBinarySCEV(I, BExpr, RHSExpr), A, I))
466
2
        return NewI;
467
14.3k
    }
468
1.29k
  }
469
14.3k
  return nullptr;
470
14.3k
}
471
472
Instruction *NaryReassociatePass::tryReassociatedBinaryOp(const SCEV *LHSExpr,
473
                                                          Value *RHS,
474
2.57k
                                                          BinaryOperator *I) {
475
2.57k
  // Look for the closest dominator LHS of I that computes LHSExpr, and replace
476
2.57k
  // I with LHS op RHS.
477
2.57k
  auto *LHS = findClosestMatchingDominator(LHSExpr, I);
478
2.57k
  if (LHS == nullptr)
479
2.55k
    return nullptr;
480
27
481
27
  Instruction *NewI = nullptr;
482
27
  switch (I->getOpcode()) {
483
27
  case Instruction::Add:
484
25
    NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
485
25
    break;
486
27
  case Instruction::Mul:
487
2
    NewI = BinaryOperator::CreateMul(LHS, RHS, "", I);
488
2
    break;
489
27
  default:
490
0
    llvm_unreachable("Unexpected instruction.");
491
27
  }
492
27
  NewI->takeName(I);
493
27
  return NewI;
494
27
}
495
496
bool NaryReassociatePass::matchTernaryOp(BinaryOperator *I, Value *V,
497
10.4k
                                         Value *&Op1, Value *&Op2) {
498
10.4k
  switch (I->getOpcode()) {
499
10.4k
  case Instruction::Add:
500
6.66k
    return match(V, m_Add(m_Value(Op1), m_Value(Op2)));
501
10.4k
  case Instruction::Mul:
502
3.75k
    return match(V, m_Mul(m_Value(Op1), m_Value(Op2)));
503
10.4k
  default:
504
0
    llvm_unreachable("Unexpected instruction.");
505
0
  }
506
0
  return false;
507
0
}
508
509
const SCEV *NaryReassociatePass::getBinarySCEV(BinaryOperator *I,
510
                                               const SCEV *LHS,
511
2.57k
                                               const SCEV *RHS) {
512
2.57k
  switch (I->getOpcode()) {
513
2.57k
  case Instruction::Add:
514
2.39k
    return SE->getAddExpr(LHS, RHS);
515
2.57k
  case Instruction::Mul:
516
184
    return SE->getMulExpr(LHS, RHS);
517
2.57k
  default:
518
0
    llvm_unreachable("Unexpected instruction.");
519
0
  }
520
0
  return nullptr;
521
0
}
522
523
Instruction *
524
NaryReassociatePass::findClosestMatchingDominator(const SCEV *CandidateExpr,
525
2.93k
                                                  Instruction *Dominatee) {
526
2.93k
  auto Pos = SeenExprs.find(CandidateExpr);
527
2.93k
  if (Pos == SeenExprs.end())
528
2.81k
    return nullptr;
529
123
530
123
  auto &Candidates = Pos->second;
531
123
  // Because we process the basic blocks in pre-order of the dominator tree, a
532
123
  // candidate that doesn't dominate the current instruction won't dominate any
533
123
  // future instruction either. Therefore, we pop it out of the stack. This
534
123
  // optimization makes the algorithm O(n).
535
136
  while (!Candidates.empty()) {
536
131
    // Candidates stores WeakTrackingVHs, so a candidate can be nullptr if it's
537
131
    // removed
538
131
    // during rewriting.
539
131
    if (Value *Candidate = Candidates.back()) {
540
129
      Instruction *CandidateInstruction = cast<Instruction>(Candidate);
541
129
      if (DT->dominates(CandidateInstruction, Dominatee))
542
118
        return CandidateInstruction;
543
13
    }
544
13
    Candidates.pop_back();
545
13
  }
546
123
  
return nullptr5
;
547
123
}