blob: c5bf2f28d1852fb406f33a1a88c9b65c593ce1e3 [file] [log] [blame]
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +00001//===- 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 +
Jingyue Wu8579b812015-04-17 00:25:10 +000039// 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.
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000042//
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//
Jingyue Wu8579b812015-04-17 00:25:10 +000053// 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//
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000072// Limitations and TODO items:
73//
Marcello Maggioni454faa82015-09-15 17:22:52 +000074// 1) We only considers n-ary adds and muls for now. This should be extended
75// and generalized.
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000076//
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000077//===----------------------------------------------------------------------===//
78
Wei Mi1cf58f82016-07-21 22:28:52 +000079#include "llvm/Transforms/Scalar/NaryReassociate.h"
Jingyue Wucf02ef32015-07-01 03:38:49 +000080#include "llvm/Analysis/ValueTracking.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000081#include "llvm/IR/Module.h"
82#include "llvm/IR/PatternMatch.h"
Jingyue Wucf02ef32015-07-01 03:38:49 +000083#include "llvm/Support/Debug.h"
84#include "llvm/Support/raw_ostream.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000085#include "llvm/Transforms/Scalar.h"
Jingyue Wu8579b812015-04-17 00:25:10 +000086#include "llvm/Transforms/Utils/Local.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000087using namespace llvm;
88using namespace PatternMatch;
89
90#define DEBUG_TYPE "nary-reassociate"
91
92namespace {
Wei Mi1cf58f82016-07-21 22:28:52 +000093class NaryReassociateLegacyPass : public FunctionPass {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000094public:
95 static char ID;
96
Wei Mi1cf58f82016-07-21 22:28:52 +000097 NaryReassociateLegacyPass() : FunctionPass(ID) {
98 initializeNaryReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000099 }
100
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000101 bool doInitialization(Module &M) override {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000102 return false;
103 }
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000104 bool runOnFunction(Function &F) override;
105
106 void getAnalysisUsage(AnalysisUsage &AU) const override {
107 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000108 AU.addPreserved<ScalarEvolutionWrapperPass>();
Jingyue Wu8579b812015-04-17 00:25:10 +0000109 AU.addPreserved<TargetLibraryInfoWrapperPass>();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000110 AU.addRequired<AssumptionCacheTracker>();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000111 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000112 AU.addRequired<ScalarEvolutionWrapperPass>();
Jingyue Wu8579b812015-04-17 00:25:10 +0000113 AU.addRequired<TargetLibraryInfoWrapperPass>();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000114 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000115 AU.setPreservesCFG();
116 }
117
118private:
Wei Mi1cf58f82016-07-21 22:28:52 +0000119 NaryReassociatePass Impl;
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000120};
121} // anonymous namespace
122
Wei Mi1cf58f82016-07-21 22:28:52 +0000123char NaryReassociateLegacyPass::ID = 0;
124INITIALIZE_PASS_BEGIN(NaryReassociateLegacyPass, "nary-reassociate",
125 "Nary reassociation", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000126INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000127INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000128INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Jingyue Wu8579b812015-04-17 00:25:10 +0000129INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000130INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Wei Mi1cf58f82016-07-21 22:28:52 +0000131INITIALIZE_PASS_END(NaryReassociateLegacyPass, "nary-reassociate",
132 "Nary reassociation", false, false)
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000133
134FunctionPass *llvm::createNaryReassociatePass() {
Wei Mi1cf58f82016-07-21 22:28:52 +0000135 return new NaryReassociateLegacyPass();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000136}
137
Wei Mi1cf58f82016-07-21 22:28:52 +0000138bool NaryReassociateLegacyPass::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000139 if (skipFunction(F))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000140 return false;
141
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000142 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Wei Mi1cf58f82016-07-21 22:28:52 +0000143 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
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000148 return Impl.runImpl(F, AC, DT, SE, TLI, TTI);
Wei Mi1cf58f82016-07-21 22:28:52 +0000149}
150
151PreservedAnalyses NaryReassociatePass::run(Function &F,
152 FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000153 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
Wei Mi1cf58f82016-07-21 22:28:52 +0000154 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
Chandler Carruth6acdca72017-01-24 12:55:57 +0000159 if (!runImpl(F, AC, DT, SE, TLI, TTI))
Wei Mi1cf58f82016-07-21 22:28:52 +0000160 return PreservedAnalyses::all();
161
Wei Mi1cf58f82016-07-21 22:28:52 +0000162 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000163 PA.preserveSet<CFGAnalyses>();
Wei Mi1cf58f82016-07-21 22:28:52 +0000164 PA.preserve<ScalarEvolutionAnalysis>();
Wei Mi1cf58f82016-07-21 22:28:52 +0000165 return PA;
166}
167
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000168bool NaryReassociatePass::runImpl(Function &F, AssumptionCache *AC_,
169 DominatorTree *DT_, ScalarEvolution *SE_,
Wei Mi1cf58f82016-07-21 22:28:52 +0000170 TargetLibraryInfo *TLI_,
171 TargetTransformInfo *TTI_) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000172 AC = AC_;
Wei Mi1cf58f82016-07-21 22:28:52 +0000173 DT = DT_;
174 SE = SE_;
175 TLI = TLI_;
176 TTI = TTI_;
177 DL = &F.getParent()->getDataLayout();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000178
Jingyue Wu8579b812015-04-17 00:25:10 +0000179 bool Changed = false, ChangedInThisIteration;
180 do {
181 ChangedInThisIteration = doOneIteration(F);
182 Changed |= ChangedInThisIteration;
183 } while (ChangedInThisIteration);
184 return Changed;
185}
186
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000187// Whitelist the instruction types NaryReassociate handles for now.
188static bool isPotentiallyNaryReassociable(Instruction *I) {
189 switch (I->getOpcode()) {
190 case Instruction::Add:
191 case Instruction::GetElementPtr:
Marcello Maggioni454faa82015-09-15 17:22:52 +0000192 case Instruction::Mul:
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000193 return true;
194 default:
195 return false;
196 }
197}
198
Wei Mi1cf58f82016-07-21 22:28:52 +0000199bool NaryReassociatePass::doOneIteration(Function &F) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000200 bool Changed = false;
201 SeenExprs.clear();
Daniel Berlina36f4632016-08-19 22:06:23 +0000202 // Process the basic blocks in a depth first traversal of the dominator
203 // tree. This order ensures that all bases of a candidate are in Candidates
204 // when we process it.
205 for (const auto Node : depth_first(DT)) {
206 BasicBlock *BB = Node->getBlock();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000207 for (auto I = BB->begin(); I != BB->end(); ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000208 if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(&*I)) {
209 const SCEV *OldSCEV = SE->getSCEV(&*I);
210 if (Instruction *NewI = tryReassociate(&*I)) {
Jingyue Wu8579b812015-04-17 00:25:10 +0000211 Changed = true;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000212 SE->forgetValue(&*I);
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000213 I->replaceAllUsesWith(NewI);
Jingyue Wudf1a1b12015-10-01 03:51:44 +0000214 // If SeenExprs constains I's WeakVH, that entry will be replaced with
215 // nullptr.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000216 RecursivelyDeleteTriviallyDeadInstructions(&*I, TLI);
217 I = NewI->getIterator();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000218 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000219 // Add the rewritten instruction to SeenExprs; the original instruction
220 // is deleted.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000221 const SCEV *NewSCEV = SE->getSCEV(&*I);
222 SeenExprs[NewSCEV].push_back(WeakVH(&*I));
Jingyue Wuc2a01462015-05-28 04:56:52 +0000223 // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
224 // is equivalent to I. However, ScalarEvolution::getSCEV may
225 // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose
226 // we reassociate
227 // I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
228 // to
229 // NewI = &a[sext(i)] + sext(j).
230 //
231 // ScalarEvolution computes
232 // getSCEV(I) = a + 4 * sext(i + j)
233 // getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
234 // which are different SCEVs.
235 //
236 // To alleviate this issue of ScalarEvolution not always capturing
237 // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
238 // map both SCEV before and after tryReassociate(I) to I.
239 //
240 // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
241 if (NewSCEV != OldSCEV)
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000242 SeenExprs[OldSCEV].push_back(WeakVH(&*I));
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000243 }
244 }
245 }
246 return Changed;
247}
248
Wei Mi1cf58f82016-07-21 22:28:52 +0000249Instruction *NaryReassociatePass::tryReassociate(Instruction *I) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000250 switch (I->getOpcode()) {
251 case Instruction::Add:
Marcello Maggioni454faa82015-09-15 17:22:52 +0000252 case Instruction::Mul:
253 return tryReassociateBinaryOp(cast<BinaryOperator>(I));
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000254 case Instruction::GetElementPtr:
255 return tryReassociateGEP(cast<GetElementPtrInst>(I));
256 default:
257 llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
258 }
259}
260
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000261static bool isGEPFoldable(GetElementPtrInst *GEP,
Jingyue Wu15f3e822016-07-08 21:48:05 +0000262 const TargetTransformInfo *TTI) {
263 SmallVector<const Value*, 4> Indices;
264 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
265 Indices.push_back(*I);
266 return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
267 Indices) == TargetTransformInfo::TCC_Free;
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000268}
269
Wei Mi1cf58f82016-07-21 22:28:52 +0000270Instruction *NaryReassociatePass::tryReassociateGEP(GetElementPtrInst *GEP) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000271 // Not worth reassociating GEP if it is foldable.
Jingyue Wu15f3e822016-07-08 21:48:05 +0000272 if (isGEPFoldable(GEP, TTI))
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000273 return nullptr;
274
275 gep_type_iterator GTI = gep_type_begin(*GEP);
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000276 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
277 if (GTI.isSequential()) {
278 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1,
279 GTI.getIndexedType())) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000280 return NewGEP;
281 }
282 }
283 }
284 return nullptr;
285}
286
Wei Mi1cf58f82016-07-21 22:28:52 +0000287bool NaryReassociatePass::requiresSignExtension(Value *Index,
288 GetElementPtrInst *GEP) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000289 unsigned PointerSizeInBits =
290 DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
291 return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
292}
293
294GetElementPtrInst *
Wei Mi1cf58f82016-07-21 22:28:52 +0000295NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
296 unsigned I, Type *IndexedType) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000297 Value *IndexToSplit = GEP->getOperand(I + 1);
Jingyue Wucf02ef32015-07-01 03:38:49 +0000298 if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000299 IndexToSplit = SExt->getOperand(0);
Jingyue Wucf02ef32015-07-01 03:38:49 +0000300 } else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(IndexToSplit)) {
301 // zext can be treated as sext if the source is non-negative.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000302 if (isKnownNonNegative(ZExt->getOperand(0), *DL, 0, AC, GEP, DT))
Jingyue Wucf02ef32015-07-01 03:38:49 +0000303 IndexToSplit = ZExt->getOperand(0);
304 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000305
306 if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
307 // If the I-th index needs sext and the underlying add is not equipped with
308 // nsw, we cannot split the add because
309 // sext(LHS + RHS) != sext(LHS) + sext(RHS).
Jingyue Wu10fcea52015-08-20 18:27:04 +0000310 if (requiresSignExtension(IndexToSplit, GEP) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000311 computeOverflowForSignedAdd(AO, *DL, AC, GEP, DT) !=
Jingyue Wu10fcea52015-08-20 18:27:04 +0000312 OverflowResult::NeverOverflows)
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000313 return nullptr;
Jingyue Wu10fcea52015-08-20 18:27:04 +0000314
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000315 Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
316 // IndexToSplit = LHS + RHS.
317 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
318 return NewGEP;
319 // Symmetrically, try IndexToSplit = RHS + LHS.
320 if (LHS != RHS) {
321 if (auto *NewGEP =
322 tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
323 return NewGEP;
324 }
325 }
326 return nullptr;
327}
328
Wei Mi1cf58f82016-07-21 22:28:52 +0000329GetElementPtrInst *
330NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
331 unsigned I, Value *LHS,
332 Value *RHS, Type *IndexedType) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000333 // Look for GEP's closest dominator that has the same SCEV as GEP except that
334 // the I-th index is replaced with LHS.
335 SmallVector<const SCEV *, 4> IndexExprs;
336 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
337 IndexExprs.push_back(SE->getSCEV(*Index));
338 // Replace the I-th index with LHS.
339 IndexExprs[I] = SE->getSCEV(LHS);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000340 if (isKnownNonNegative(LHS, *DL, 0, AC, GEP, DT) &&
Jingyue Wucf02ef32015-07-01 03:38:49 +0000341 DL->getTypeSizeInBits(LHS->getType()) <
342 DL->getTypeSizeInBits(GEP->getOperand(I)->getType())) {
343 // Zero-extend LHS if it is non-negative. InstCombine canonicalizes sext to
344 // zext if the source operand is proved non-negative. We should do that
345 // consistently so that CandidateExpr more likely appears before. See
346 // @reassociate_gep_assume for an example of this canonicalization.
347 IndexExprs[I] =
348 SE->getZeroExtendExpr(IndexExprs[I], GEP->getOperand(I)->getType());
349 }
Peter Collingbourne8dff0392016-11-13 06:59:50 +0000350 const SCEV *CandidateExpr = SE->getGEPExpr(cast<GEPOperator>(GEP),
351 IndexExprs);
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000352
Jingyue Wuba3ca762015-12-18 21:36:30 +0000353 Value *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000354 if (Candidate == nullptr)
355 return nullptr;
356
Jingyue Wuba3ca762015-12-18 21:36:30 +0000357 IRBuilder<> Builder(GEP);
358 // Candidate does not necessarily have the same pointer type as GEP. Use
359 // bitcast or pointer cast to make sure they have the same type, so that the
360 // later RAUW doesn't complain.
361 Candidate = Builder.CreateBitOrPointerCast(Candidate, GEP->getType());
362 assert(Candidate->getType() == GEP->getType());
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000363
364 // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
365 uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000366 Type *ElementType = GEP->getResultElementType();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000367 uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
368 // Another less rare case: because I is not necessarily the last index of the
369 // GEP, the size of the type at the I-th index (IndexedSize) is not
370 // necessarily divisible by ElementSize. For example,
371 //
372 // #pragma pack(1)
373 // struct S {
374 // int a[3];
375 // int64 b[8];
376 // };
377 // #pragma pack()
378 //
379 // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
380 //
381 // TODO: bail out on this case for now. We could emit uglygep.
382 if (IndexedSize % ElementSize != 0)
383 return nullptr;
384
385 // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
Jingyue Wuba3ca762015-12-18 21:36:30 +0000386 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000387 if (RHS->getType() != IntPtrTy)
388 RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
389 if (IndexedSize != ElementSize) {
390 RHS = Builder.CreateMul(
391 RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
392 }
393 GetElementPtrInst *NewGEP =
394 cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS));
395 NewGEP->setIsInBounds(GEP->isInBounds());
396 NewGEP->takeName(GEP);
397 return NewGEP;
398}
399
Wei Mi1cf58f82016-07-21 22:28:52 +0000400Instruction *NaryReassociatePass::tryReassociateBinaryOp(BinaryOperator *I) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000401 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Marcello Maggioni454faa82015-09-15 17:22:52 +0000402 if (auto *NewI = tryReassociateBinaryOp(LHS, RHS, I))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000403 return NewI;
Marcello Maggioni454faa82015-09-15 17:22:52 +0000404 if (auto *NewI = tryReassociateBinaryOp(RHS, LHS, I))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000405 return NewI;
406 return nullptr;
407}
408
Wei Mi1cf58f82016-07-21 22:28:52 +0000409Instruction *NaryReassociatePass::tryReassociateBinaryOp(Value *LHS, Value *RHS,
410 BinaryOperator *I) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000411 Value *A = nullptr, *B = nullptr;
Marcello Maggioni454faa82015-09-15 17:22:52 +0000412 // To be conservative, we reassociate I only when it is the only user of (A op
413 // B).
414 if (LHS->hasOneUse() && matchTernaryOp(I, LHS, A, B)) {
415 // I = (A op B) op RHS
416 // = (A op RHS) op B or (B op RHS) op A
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000417 const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
418 const SCEV *RHSExpr = SE->getSCEV(RHS);
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000419 if (BExpr != RHSExpr) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000420 if (auto *NewI =
421 tryReassociatedBinaryOp(getBinarySCEV(I, AExpr, RHSExpr), B, I))
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000422 return NewI;
423 }
424 if (AExpr != RHSExpr) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000425 if (auto *NewI =
426 tryReassociatedBinaryOp(getBinarySCEV(I, BExpr, RHSExpr), A, I))
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000427 return NewI;
428 }
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000429 }
430 return nullptr;
431}
432
Wei Mi1cf58f82016-07-21 22:28:52 +0000433Instruction *NaryReassociatePass::tryReassociatedBinaryOp(const SCEV *LHSExpr,
434 Value *RHS,
435 BinaryOperator *I) {
Jingyue Wu771dfe92015-04-16 18:42:31 +0000436 // Look for the closest dominator LHS of I that computes LHSExpr, and replace
Marcello Maggioni454faa82015-09-15 17:22:52 +0000437 // I with LHS op RHS.
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000438 auto *LHS = findClosestMatchingDominator(LHSExpr, I);
439 if (LHS == nullptr)
440 return nullptr;
441
Marcello Maggioni454faa82015-09-15 17:22:52 +0000442 Instruction *NewI = nullptr;
443 switch (I->getOpcode()) {
444 case Instruction::Add:
445 NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
446 break;
447 case Instruction::Mul:
448 NewI = BinaryOperator::CreateMul(LHS, RHS, "", I);
449 break;
450 default:
451 llvm_unreachable("Unexpected instruction.");
452 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000453 NewI->takeName(I);
454 return NewI;
455}
456
Wei Mi1cf58f82016-07-21 22:28:52 +0000457bool NaryReassociatePass::matchTernaryOp(BinaryOperator *I, Value *V,
458 Value *&Op1, Value *&Op2) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000459 switch (I->getOpcode()) {
460 case Instruction::Add:
461 return match(V, m_Add(m_Value(Op1), m_Value(Op2)));
462 case Instruction::Mul:
463 return match(V, m_Mul(m_Value(Op1), m_Value(Op2)));
464 default:
465 llvm_unreachable("Unexpected instruction.");
466 }
467 return false;
468}
469
Wei Mi1cf58f82016-07-21 22:28:52 +0000470const SCEV *NaryReassociatePass::getBinarySCEV(BinaryOperator *I,
471 const SCEV *LHS,
472 const SCEV *RHS) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000473 switch (I->getOpcode()) {
474 case Instruction::Add:
475 return SE->getAddExpr(LHS, RHS);
476 case Instruction::Mul:
477 return SE->getMulExpr(LHS, RHS);
478 default:
479 llvm_unreachable("Unexpected instruction.");
480 }
481 return nullptr;
482}
483
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000484Instruction *
Wei Mi1cf58f82016-07-21 22:28:52 +0000485NaryReassociatePass::findClosestMatchingDominator(const SCEV *CandidateExpr,
486 Instruction *Dominatee) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000487 auto Pos = SeenExprs.find(CandidateExpr);
488 if (Pos == SeenExprs.end())
489 return nullptr;
490
491 auto &Candidates = Pos->second;
492 // Because we process the basic blocks in pre-order of the dominator tree, a
Jingyue Wu771dfe92015-04-16 18:42:31 +0000493 // candidate that doesn't dominate the current instruction won't dominate any
494 // future instruction either. Therefore, we pop it out of the stack. This
495 // optimization makes the algorithm O(n).
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000496 while (!Candidates.empty()) {
Jingyue Wudf1a1b12015-10-01 03:51:44 +0000497 // Candidates stores WeakVHs, so a candidate can be nullptr if it's removed
498 // during rewriting.
499 if (Value *Candidate = Candidates.back()) {
500 Instruction *CandidateInstruction = cast<Instruction>(Candidate);
501 if (DT->dominates(CandidateInstruction, Dominatee))
502 return CandidateInstruction;
503 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000504 Candidates.pop_back();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000505 }
506 return nullptr;
507}