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