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