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/ScalarEvolutionExpressions.h"
84#include "llvm/Analysis/TargetLibraryInfo.h"
85#include "llvm/Analysis/TargetTransformInfo.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/InitializePasses.h"
105#include "llvm/Pass.h"
106#include "llvm/Support/Casting.h"
107#include "llvm/Support/ErrorHandling.h"
108#include "llvm/Transforms/Scalar.h"
109#include "llvm/Transforms/Utils/Local.h"
110#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
111#include <cassert>
112#include <cstdint>
113
114using namespace llvm;
115using namespace PatternMatch;
116
117#define DEBUG_TYPE "nary-reassociate"
118
119namespace {
120
121class NaryReassociateLegacyPass : public FunctionPass {
122public:
123 static char ID;
124
125 NaryReassociateLegacyPass() : FunctionPass(ID) {
126 initializeNaryReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
127 }
128
129 bool doInitialization(Module &M) override {
130 return false;
131 }
132
133 bool runOnFunction(Function &F) override;
134
135 void getAnalysisUsage(AnalysisUsage &AU) const override {
136 AU.addPreserved<DominatorTreeWrapperPass>();
137 AU.addPreserved<ScalarEvolutionWrapperPass>();
138 AU.addPreserved<TargetLibraryInfoWrapperPass>();
139 AU.addRequired<AssumptionCacheTracker>();
140 AU.addRequired<DominatorTreeWrapperPass>();
141 AU.addRequired<ScalarEvolutionWrapperPass>();
142 AU.addRequired<TargetLibraryInfoWrapperPass>();
143 AU.addRequired<TargetTransformInfoWrapperPass>();
144 AU.setPreservesCFG();
145 }
146
147private:
148 NaryReassociatePass Impl;
149};
150
151} // end anonymous namespace
152
153char NaryReassociateLegacyPass::ID = 0;
154
155INITIALIZE_PASS_BEGIN(NaryReassociateLegacyPass, "nary-reassociate",
156 "Nary reassociation", false, false)
157INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
158INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
159INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
160INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
161INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
162INITIALIZE_PASS_END(NaryReassociateLegacyPass, "nary-reassociate",
163 "Nary reassociation", false, false)
164
165FunctionPass *llvm::createNaryReassociatePass() {
166 return new NaryReassociateLegacyPass();
167}
168
169bool NaryReassociateLegacyPass::runOnFunction(Function &F) {
170 if (skipFunction(F))
171 return false;
172
173 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
174 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
175 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
176 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
177 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
178
179 return Impl.runImpl(F, AC_: AC, DT_: DT, SE_: SE, TLI_: TLI, TTI_: TTI);
180}
181
182PreservedAnalyses NaryReassociatePass::run(Function &F,
183 FunctionAnalysisManager &AM) {
184 auto *AC = &AM.getResult<AssumptionAnalysis>(IR&: F);
185 auto *DT = &AM.getResult<DominatorTreeAnalysis>(IR&: F);
186 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(IR&: F);
187 auto *TLI = &AM.getResult<TargetLibraryAnalysis>(IR&: F);
188 auto *TTI = &AM.getResult<TargetIRAnalysis>(IR&: F);
189
190 if (!runImpl(F, AC_: AC, DT_: DT, SE_: SE, TLI_: TLI, TTI_: TTI))
191 return PreservedAnalyses::all();
192
193 PreservedAnalyses PA;
194 PA.preserveSet<CFGAnalyses>();
195 PA.preserve<ScalarEvolutionAnalysis>();
196 return PA;
197}
198
199bool NaryReassociatePass::runImpl(Function &F, AssumptionCache *AC_,
200 DominatorTree *DT_, ScalarEvolution *SE_,
201 TargetLibraryInfo *TLI_,
202 TargetTransformInfo *TTI_) {
203 AC = AC_;
204 DT = DT_;
205 SE = SE_;
206 TLI = TLI_;
207 TTI = TTI_;
208 DL = &F.getDataLayout();
209
210 bool Changed = false, ChangedInThisIteration;
211 do {
212 ChangedInThisIteration = doOneIteration(F);
213 Changed |= ChangedInThisIteration;
214 } while (ChangedInThisIteration);
215 return Changed;
216}
217
218bool NaryReassociatePass::doOneIteration(Function &F) {
219 bool Changed = false;
220 SeenExprs.clear();
221 // Process the basic blocks in a depth first traversal of the dominator
222 // tree. This order ensures that all bases of a candidate are in Candidates
223 // when we process it.
224 SmallVector<WeakTrackingVH, 16> DeadInsts;
225 for (const auto Node : depth_first(G: DT)) {
226 BasicBlock *BB = Node->getBlock();
227 for (Instruction &OrigI : *BB) {
228 SCEVUse OrigSCEV = nullptr;
229 if (Instruction *NewI = tryReassociate(I: &OrigI, OrigSCEV)) {
230 Changed = true;
231 OrigI.replaceAllUsesWith(V: NewI);
232
233 // Add 'OrigI' to the list of dead instructions.
234 DeadInsts.push_back(Elt: WeakTrackingVH(&OrigI));
235 // Add the rewritten instruction to SeenExprs; the original
236 // instruction is deleted.
237 SCEVUse NewSCEV = SE->getSCEV(V: NewI);
238 SeenExprs[NewSCEV].push_back(Elt: WeakTrackingVH(NewI));
239
240 // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
241 // is equivalent to I. However, ScalarEvolution::getSCEV may
242 // weaken nsw causing NewSCEV not to equal OldSCEV. For example,
243 // suppose we reassociate
244 // I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
245 // to
246 // NewI = &a[sext(i)] + sext(j).
247 //
248 // ScalarEvolution computes
249 // getSCEV(I) = a + 4 * sext(i + j)
250 // getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
251 // which are different SCEVs.
252 //
253 // To alleviate this issue of ScalarEvolution not always capturing
254 // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
255 // map both SCEV before and after tryReassociate(I) to I.
256 //
257 // This improvement is exercised in @reassociate_gep_nsw in
258 // nary-gep.ll.
259 if (NewSCEV != OrigSCEV)
260 SeenExprs[OrigSCEV].push_back(Elt: WeakTrackingVH(NewI));
261 } else if (OrigSCEV)
262 SeenExprs[OrigSCEV].push_back(Elt: WeakTrackingVH(&OrigI));
263 }
264 }
265 // Delete all dead instructions from 'DeadInsts'.
266 // Please note ScalarEvolution is updated along the way.
267 RecursivelyDeleteTriviallyDeadInstructionsPermissive(
268 DeadInsts, TLI, MSSAU: nullptr, AboutToDeleteCallback: [this](Value *V) { SE->forgetValue(V); });
269
270 return Changed;
271}
272
273Instruction *NaryReassociatePass::tryReassociate(Instruction *I,
274 SCEVUse &OrigSCEV) {
275
276 if (!SE->isSCEVable(Ty: I->getType()))
277 return nullptr;
278
279 switch (I->getOpcode()) {
280 case Instruction::Add:
281 case Instruction::Mul:
282 OrigSCEV = SE->getSCEV(V: I);
283 return tryReassociateBinaryOp(I: cast<BinaryOperator>(Val: I));
284 case Instruction::GetElementPtr:
285 OrigSCEV = SE->getSCEV(V: I);
286 return tryReassociateGEP(GEP: cast<GetElementPtrInst>(Val: I));
287 default:
288 break;
289 }
290
291 // Try to match signed/unsigned Min/Max.
292 if (match(V: I, P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value()))) {
293 OrigSCEV = SE->getSCEV(V: I);
294 return dyn_cast_or_null<Instruction>(
295 Val: tryReassociateMinOrMax(I: cast<IntrinsicInst>(Val: I)));
296 }
297
298 return nullptr;
299}
300
301static bool isGEPFoldable(GetElementPtrInst *GEP,
302 const TargetTransformInfo *TTI) {
303 SmallVector<const Value *, 4> Indices(GEP->indices());
304 return TTI->getGEPCost(PointeeType: GEP->getSourceElementType(), Ptr: GEP->getPointerOperand(),
305 Operands: Indices) == TargetTransformInfo::TCC_Free;
306}
307
308Instruction *NaryReassociatePass::tryReassociateGEP(GetElementPtrInst *GEP) {
309 // Not worth reassociating GEP if it is foldable.
310 if (isGEPFoldable(GEP, TTI))
311 return nullptr;
312
313 gep_type_iterator GTI = gep_type_begin(GEP: *GEP);
314 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
315 if (GTI.isSequential()) {
316 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I: I - 1,
317 IndexedType: GTI.getIndexedType())) {
318 return NewGEP;
319 }
320 }
321 }
322 return nullptr;
323}
324
325bool NaryReassociatePass::requiresSignExtension(Value *Index,
326 GetElementPtrInst *GEP) {
327 unsigned IndexSizeInBits =
328 DL->getIndexSizeInBits(AS: GEP->getType()->getPointerAddressSpace());
329 return cast<IntegerType>(Val: Index->getType())->getBitWidth() < IndexSizeInBits;
330}
331
332GetElementPtrInst *
333NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
334 unsigned I, Type *IndexedType) {
335 SimplifyQuery SQ(*DL, DT, AC, GEP);
336 Value *IndexToSplit = GEP->getOperand(i_nocapture: I + 1);
337 if (SExtInst *SExt = dyn_cast<SExtInst>(Val: IndexToSplit)) {
338 IndexToSplit = SExt->getOperand(i_nocapture: 0);
339 } else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(Val: IndexToSplit)) {
340 // zext can be treated as sext if the source is non-negative.
341 if (isKnownNonNegative(V: ZExt->getOperand(i_nocapture: 0), SQ))
342 IndexToSplit = ZExt->getOperand(i_nocapture: 0);
343 }
344
345 if (AddOperator *AO = dyn_cast<AddOperator>(Val: IndexToSplit)) {
346 // If the I-th index needs sext and the underlying add is not equipped with
347 // nsw, we cannot split the add because
348 // sext(LHS + RHS) != sext(LHS) + sext(RHS).
349 if (requiresSignExtension(Index: IndexToSplit, GEP) &&
350 computeOverflowForSignedAdd(Add: AO, SQ) != OverflowResult::NeverOverflows)
351 return nullptr;
352
353 Value *LHS = AO->getOperand(i_nocapture: 0), *RHS = AO->getOperand(i_nocapture: 1);
354 // IndexToSplit = LHS + RHS.
355 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
356 return NewGEP;
357 // Symmetrically, try IndexToSplit = RHS + LHS.
358 if (LHS != RHS) {
359 if (auto *NewGEP =
360 tryReassociateGEPAtIndex(GEP, I, LHS: RHS, RHS: LHS, IndexedType))
361 return NewGEP;
362 }
363 }
364 return nullptr;
365}
366
367GetElementPtrInst *
368NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
369 unsigned I, Value *LHS,
370 Value *RHS, Type *IndexedType) {
371 // Look for GEP's closest dominator that has the same SCEV as GEP except that
372 // the I-th index is replaced with LHS.
373 SmallVector<SCEVUse, 4> IndexExprs;
374 for (Use &Index : GEP->indices())
375 IndexExprs.push_back(Elt: SE->getSCEV(V: Index));
376 // Replace the I-th index with LHS.
377 IndexExprs[I] = SE->getSCEV(V: LHS);
378 Type *GEPArgType = SE->getEffectiveSCEVType(Ty: GEP->getOperand(i_nocapture: I)->getType());
379 Type *LHSType = SE->getEffectiveSCEVType(Ty: LHS->getType());
380 size_t LHSSize = DL->getTypeSizeInBits(Ty: LHSType).getFixedValue();
381 size_t GEPArgSize = DL->getTypeSizeInBits(Ty: GEPArgType).getFixedValue();
382 if (isKnownNonNegative(V: LHS, SQ: SimplifyQuery(*DL, DT, AC, GEP)) &&
383 LHSSize < GEPArgSize) {
384 // Zero-extend LHS if it is non-negative. InstCombine canonicalizes sext to
385 // zext if the source operand is proved non-negative. We should do that
386 // consistently so that CandidateExpr more likely appears before. See
387 // @reassociate_gep_assume for an example of this canonicalization.
388 IndexExprs[I] = SE->getZeroExtendExpr(Op: IndexExprs[I], Ty: GEPArgType);
389 }
390 SCEVUse CandidateExpr = SE->getGEPExpr(GEP: cast<GEPOperator>(Val: GEP), IndexExprs);
391
392 Value *Candidate = findClosestMatchingDominator(CandidateExpr, Dominatee: GEP);
393 if (Candidate == nullptr)
394 return nullptr;
395
396 IRBuilder<> Builder(GEP);
397 // Candidate should have the same pointer type as GEP.
398 assert(Candidate->getType() == GEP->getType());
399
400 // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
401 uint64_t IndexedSize = DL->getTypeAllocSize(Ty: IndexedType);
402 Type *ElementType = GEP->getResultElementType();
403 uint64_t ElementSize = DL->getTypeAllocSize(Ty: ElementType);
404 // Another less rare case: because I is not necessarily the last index of the
405 // GEP, the size of the type at the I-th index (IndexedSize) is not
406 // necessarily divisible by ElementSize. For example,
407 //
408 // #pragma pack(1)
409 // struct S {
410 // int a[3];
411 // int64 b[8];
412 // };
413 // #pragma pack()
414 //
415 // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
416 //
417 // TODO: bail out on this case for now. We could emit uglygep.
418 if (ElementSize == 0 || IndexedSize % ElementSize != 0)
419 return nullptr;
420
421 // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
422 Type *PtrIdxTy = DL->getIndexType(PtrTy: GEP->getType());
423 if (RHS->getType() != PtrIdxTy)
424 RHS = Builder.CreateSExtOrTrunc(V: RHS, DestTy: PtrIdxTy);
425 if (IndexedSize != ElementSize) {
426 RHS = Builder.CreateMul(
427 LHS: RHS, RHS: ConstantInt::get(Ty: PtrIdxTy, V: IndexedSize / ElementSize));
428 }
429 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(
430 Val: Builder.CreateGEP(Ty: GEP->getResultElementType(), Ptr: Candidate, IdxList: RHS));
431 NewGEP->setIsInBounds(GEP->isInBounds());
432 NewGEP->takeName(V: GEP);
433 return NewGEP;
434}
435
436Instruction *NaryReassociatePass::tryReassociateBinaryOp(BinaryOperator *I) {
437 Value *LHS = I->getOperand(i_nocapture: 0), *RHS = I->getOperand(i_nocapture: 1);
438 // There is no need to reassociate 0.
439 if (SE->getSCEV(V: I)->isZero())
440 return nullptr;
441 if (auto *NewI = tryReassociateBinaryOp(LHS, RHS, I))
442 return NewI;
443 if (auto *NewI = tryReassociateBinaryOp(LHS: RHS, RHS: LHS, I))
444 return NewI;
445 return nullptr;
446}
447
448Instruction *NaryReassociatePass::tryReassociateBinaryOp(Value *LHS, Value *RHS,
449 BinaryOperator *I) {
450 Value *A = nullptr, *B = nullptr;
451 // To be conservative, we reassociate I only when it is the only user of (A op
452 // B).
453 if (LHS->hasOneUse() && matchTernaryOp(I, V: LHS, Op1&: A, Op2&: B)) {
454 // I = (A op B) op RHS
455 // = (A op RHS) op B or (B op RHS) op A
456 SCEVUse AExpr = SE->getSCEV(V: A), BExpr = SE->getSCEV(V: B);
457 SCEVUse RHSExpr = SE->getSCEV(V: RHS);
458 if (BExpr != RHSExpr) {
459 if (auto *NewI =
460 tryReassociatedBinaryOp(LHS: getBinarySCEV(I, LHS: AExpr, RHS: RHSExpr), RHS: B, I))
461 return NewI;
462 }
463 if (AExpr != RHSExpr) {
464 if (auto *NewI =
465 tryReassociatedBinaryOp(LHS: getBinarySCEV(I, LHS: BExpr, RHS: RHSExpr), RHS: A, I))
466 return NewI;
467 }
468 }
469 return nullptr;
470}
471
472Instruction *NaryReassociatePass::tryReassociatedBinaryOp(SCEVUse LHSExpr,
473 Value *RHS,
474 BinaryOperator *I) {
475 // Look for the closest dominator LHS of I that computes LHSExpr, and replace
476 // I with LHS op RHS.
477 auto *LHS = findClosestMatchingDominator(CandidateExpr: LHSExpr, Dominatee: I);
478 if (LHS == nullptr)
479 return nullptr;
480
481 Instruction *NewI = nullptr;
482 switch (I->getOpcode()) {
483 case Instruction::Add:
484 NewI = BinaryOperator::CreateAdd(V1: LHS, V2: RHS, Name: "", InsertBefore: I->getIterator());
485 break;
486 case Instruction::Mul:
487 NewI = BinaryOperator::CreateMul(V1: LHS, V2: RHS, Name: "", InsertBefore: I->getIterator());
488 break;
489 default:
490 llvm_unreachable("Unexpected instruction.");
491 }
492 NewI->setDebugLoc(I->getDebugLoc());
493 NewI->takeName(V: I);
494 return NewI;
495}
496
497bool NaryReassociatePass::matchTernaryOp(BinaryOperator *I, Value *V,
498 Value *&Op1, Value *&Op2) {
499 switch (I->getOpcode()) {
500 case Instruction::Add:
501 return match(V, P: m_Add(L: m_Value(V&: Op1), R: m_Value(V&: Op2)));
502 case Instruction::Mul:
503 return match(V, P: m_Mul(L: m_Value(V&: Op1), R: m_Value(V&: Op2)));
504 default:
505 llvm_unreachable("Unexpected instruction.");
506 }
507 return false;
508}
509
510SCEVUse NaryReassociatePass::getBinarySCEV(BinaryOperator *I, SCEVUse LHS,
511 SCEVUse RHS) {
512 switch (I->getOpcode()) {
513 case Instruction::Add:
514 return SE->getAddExpr(LHS, RHS);
515 case Instruction::Mul:
516 return SE->getMulExpr(LHS, RHS);
517 default:
518 llvm_unreachable("Unexpected instruction.");
519 }
520 return nullptr;
521}
522
523Instruction *
524NaryReassociatePass::findClosestMatchingDominator(SCEVUse CandidateExpr,
525 Instruction *Dominatee) {
526 auto Pos = SeenExprs.find(Val: CandidateExpr);
527 if (Pos == SeenExprs.end())
528 return nullptr;
529
530 auto &Candidates = Pos->second;
531 // Because we process the basic blocks in pre-order of the dominator tree, a
532 // candidate that doesn't dominate the current instruction won't dominate any
533 // future instruction either. Therefore, we pop it out of the stack. This
534 // optimization makes the algorithm O(n).
535 while (!Candidates.empty()) {
536 // Candidates stores WeakTrackingVHs, so a candidate can be nullptr if it's
537 // removed during rewriting.
538 if (Value *Candidate = Candidates.pop_back_val()) {
539 Instruction *CandidateInstruction = cast<Instruction>(Val: Candidate);
540 if (!DT->dominates(Def: CandidateInstruction, User: Dominatee))
541 continue;
542
543 // Make sure that the instruction is safe to reuse without introducing
544 // poison.
545 SmallVector<Instruction *> DropPoisonGeneratingInsts;
546 if (!SE->canReuseInstruction(S: CandidateExpr, I: CandidateInstruction,
547 DropPoisonGeneratingInsts))
548 continue;
549
550 for (Instruction *I : DropPoisonGeneratingInsts)
551 I->dropPoisonGeneratingAnnotations();
552
553 return CandidateInstruction;
554 }
555 }
556 return nullptr;
557}
558
559static SCEVTypes convertToSCEVType(Intrinsic::ID IntrinID) {
560 switch (IntrinID) {
561 case Intrinsic::smax:
562 return scSMaxExpr;
563 case Intrinsic::umax:
564 return scUMaxExpr;
565 case Intrinsic::smin:
566 return scSMinExpr;
567 case Intrinsic::umin:
568 return scUMinExpr;
569 default:
570 llvm_unreachable("Can't convert MinMax pattern to SCEV type");
571 return scUnknown;
572 }
573}
574
575Value *NaryReassociatePass::tryReassociateMinOrMax(IntrinsicInst *I) {
576 Value *LHS = I->getArgOperand(i: 0);
577 Value *RHS = I->getArgOperand(i: 1);
578 if (auto *RHSI = dyn_cast<IntrinsicInst>(Val: RHS);
579 RHSI && RHSI->getIntrinsicID() == I->getIntrinsicID())
580 std::swap(a&: LHS, b&: RHS);
581 auto *LHSI = dyn_cast<IntrinsicInst>(Val: LHS);
582 if (!LHSI || LHSI->getIntrinsicID() != I->getIntrinsicID())
583 return nullptr;
584
585 Value *A = LHSI->getArgOperand(i: 0), *B = LHSI->getArgOperand(i: 1);
586
587 if (LHS->hasNUsesOrMore(N: 3) ||
588 // The optimization is profitable only if LHS can be removed in the end.
589 // In other words LHS should be used (directly or indirectly) by I only.
590 llvm::any_of(Range: LHS->users(), P: [&](auto *U) {
591 return U != I && !(U->hasOneUser() && *U->users().begin() == I);
592 }))
593 return nullptr;
594
595 auto tryCombination = [&](Value *A, SCEVUse AExpr, Value *B, SCEVUse BExpr,
596 Value *C, SCEVUse CExpr) -> Value * {
597 SmallVector<SCEVUse, 2> Ops1{BExpr, AExpr};
598 SCEVTypes SCEVType = convertToSCEVType(IntrinID: I->getIntrinsicID());
599 SCEVUse R1Expr = SE->getMinMaxExpr(Kind: SCEVType, Operands&: Ops1);
600
601 Instruction *R1MinMax = findClosestMatchingDominator(CandidateExpr: R1Expr, Dominatee: I);
602
603 if (!R1MinMax)
604 return nullptr;
605
606 LLVM_DEBUG(dbgs() << "NARY: Found common sub-expr: " << *R1MinMax << "\n");
607
608 SmallVector<SCEVUse, 2> Ops2{SE->getUnknown(V: C), SE->getUnknown(V: R1MinMax)};
609 SCEVUse R2Expr = SE->getMinMaxExpr(Kind: SCEVType, Operands&: Ops2);
610
611 SCEVExpander Expander(*SE, "nary-reassociate");
612 Value *NewMinMax = Expander.expandCodeFor(SH: R2Expr, Ty: I->getType(), I);
613 NewMinMax->setName(Twine(I->getName()).concat(Suffix: ".nary"));
614
615 LLVM_DEBUG(dbgs() << "NARY: Deleting: " << *I << "\n"
616 << "NARY: Inserting: " << *NewMinMax << "\n");
617 return NewMinMax;
618 };
619
620 SCEVUse AExpr = SE->getSCEV(V: A);
621 SCEVUse BExpr = SE->getSCEV(V: B);
622 SCEVUse RHSExpr = SE->getSCEV(V: RHS);
623
624 if (BExpr != RHSExpr) {
625 // Try (A op RHS) op B
626 if (auto *NewMinMax = tryCombination(A, AExpr, RHS, RHSExpr, B, BExpr))
627 return NewMinMax;
628 }
629
630 if (AExpr != RHSExpr) {
631 // Try (RHS op B) op A
632 if (auto *NewMinMax = tryCombination(RHS, RHSExpr, B, BExpr, A, AExpr))
633 return NewMinMax;
634 }
635
636 return nullptr;
637}
638