blob: 16e50c2d2030ec479c1bf313706af4baec4d7599 [file] [log] [blame]
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001//===- AggressiveInstCombine.cpp ------------------------------------------===//
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 file implements the aggressive expression pattern combiner classes.
11// Currently, it handles expression patterns for:
12// * Truncate instruction
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
17#include "AggressiveInstCombineInternal.h"
18#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Analysis/BasicAliasAnalysis.h"
20#include "llvm/Analysis/GlobalsModRef.h"
21#include "llvm/Analysis/TargetLibraryInfo.h"
Sanjay Pateld2025a22018-05-01 21:02:09 +000022#include "llvm/Analysis/Utils/Local.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000023#include "llvm/IR/DataLayout.h"
Amjad Aboudd895bff2018-01-31 10:41:31 +000024#include "llvm/IR/Dominators.h"
Sanjay Pateld2025a22018-05-01 21:02:09 +000025#include "llvm/IR/IRBuilder.h"
David Blaikieba47dd12018-04-24 15:40:07 +000026#include "llvm/IR/LegacyPassManager.h"
Sanjay Pateld2025a22018-05-01 21:02:09 +000027#include "llvm/IR/PatternMatch.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000028#include "llvm/Pass.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000029using namespace llvm;
Sanjay Pateld2025a22018-05-01 21:02:09 +000030using namespace PatternMatch;
Amjad Aboudf1f57a32018-01-25 12:06:32 +000031
32#define DEBUG_TYPE "aggressive-instcombine"
33
34namespace {
35/// Contains expression pattern combiner logic.
36/// This class provides both the logic to combine expression patterns and
37/// combine them. It differs from InstCombiner class in that each pattern
38/// combiner runs only once as opposed to InstCombine's multi-iteration,
39/// which allows pattern combiner to have higher complexity than the O(1)
40/// required by the instruction combiner.
41class AggressiveInstCombinerLegacyPass : public FunctionPass {
42public:
43 static char ID; // Pass identification, replacement for typeid
44
45 AggressiveInstCombinerLegacyPass() : FunctionPass(ID) {
46 initializeAggressiveInstCombinerLegacyPassPass(
47 *PassRegistry::getPassRegistry());
48 }
49
50 void getAnalysisUsage(AnalysisUsage &AU) const override;
51
52 /// Run all expression pattern optimizations on the given /p F function.
53 ///
54 /// \param F function to optimize.
55 /// \returns true if the IR is changed.
56 bool runOnFunction(Function &F) override;
57};
58} // namespace
59
Sanjay Patelac3951a2018-05-09 23:08:15 +000060/// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and
61/// the bit indexes (Mask) needed by a masked compare. If we're matching a chain
62/// of 'and' ops, then we also need to capture the fact that we saw an
63/// "and X, 1", so that's an extra return value for that case.
64struct MaskOps {
65 Value *Root;
66 APInt Mask;
67 bool MatchAndChain;
68 bool FoundAnd1;
69
70 MaskOps(unsigned BitWidth, bool MatchAnds) :
71 Root(nullptr), Mask(APInt::getNullValue(BitWidth)),
72 MatchAndChain(MatchAnds), FoundAnd1(false) {}
73};
74
75/// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a
76/// chain of 'and' or 'or' instructions looking for shift ops of a common source
77/// value. Examples:
78/// or (or (or X, (X >> 3)), (X >> 5)), (X >> 8)
79/// returns { X, 0x129 }
80/// and (and (X >> 1), 1), (X >> 4)
81/// returns { X, 0x12 }
82static bool matchAndOrChain(Value *V, MaskOps &MOps) {
Sanjay Pateld2025a22018-05-01 21:02:09 +000083 Value *Op0, *Op1;
Sanjay Patelac3951a2018-05-09 23:08:15 +000084 if (MOps.MatchAndChain) {
85 // Recurse through a chain of 'and' operands. This requires an extra check
86 // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere
87 // in the chain to know that all of the high bits are cleared.
88 if (match(V, m_And(m_Value(Op0), m_One()))) {
89 MOps.FoundAnd1 = true;
90 return matchAndOrChain(Op0, MOps);
91 }
92 if (match(V, m_And(m_Value(Op0), m_Value(Op1))))
93 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
94 } else {
95 // Recurse through a chain of 'or' operands.
96 if (match(V, m_Or(m_Value(Op0), m_Value(Op1))))
97 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
98 }
Sanjay Pateld2025a22018-05-01 21:02:09 +000099
100 // We need a shift-right or a bare value representing a compare of bit 0 of
101 // the original source operand.
102 Value *Candidate;
103 uint64_t BitIndex = 0;
104 if (!match(V, m_LShr(m_Value(Candidate), m_ConstantInt(BitIndex))))
105 Candidate = V;
106
107 // Initialize result source operand.
Sanjay Patelac3951a2018-05-09 23:08:15 +0000108 if (!MOps.Root)
109 MOps.Root = Candidate;
Sanjay Pateld2025a22018-05-01 21:02:09 +0000110
111 // Fill in the mask bit derived from the shift constant.
Sanjay Patelac3951a2018-05-09 23:08:15 +0000112 MOps.Mask.setBit(BitIndex);
113 return MOps.Root == Candidate;
Sanjay Pateld2025a22018-05-01 21:02:09 +0000114}
115
Sanjay Patelac3951a2018-05-09 23:08:15 +0000116/// Match patterns that correspond to "any-bits-set" and "all-bits-set".
117/// These will include a chain of 'or' or 'and'-shifted bits from a
118/// common source value:
119/// and (or (lshr X, C), ...), 1 --> (X & CMask) != 0
120/// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask
121/// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns
122/// that differ only with a final 'not' of the result. We expect that final
123/// 'not' to be folded with the compare that we create here (invert predicate).
124static bool foldAnyOrAllBitsSet(Instruction &I) {
125 // The 'any-bits-set' ('or' chain) pattern is simpler to match because the
126 // final "and X, 1" instruction must be the final op in the sequence.
127 bool MatchAllBitsSet;
128 if (match(&I, m_c_And(m_OneUse(m_And(m_Value(), m_Value())), m_Value())))
129 MatchAllBitsSet = true;
130 else if (match(&I, m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One())))
131 MatchAllBitsSet = false;
132 else
Sanjay Pateld2025a22018-05-01 21:02:09 +0000133 return false;
134
Sanjay Patelac3951a2018-05-09 23:08:15 +0000135 MaskOps MOps(I.getType()->getScalarSizeInBits(), MatchAllBitsSet);
136 if (MatchAllBitsSet) {
137 if (!matchAndOrChain(cast<BinaryOperator>(&I), MOps) || !MOps.FoundAnd1)
138 return false;
139 } else {
140 if (!matchAndOrChain(cast<BinaryOperator>(&I)->getOperand(0), MOps))
141 return false;
142 }
Sanjay Pateld2025a22018-05-01 21:02:09 +0000143
Sanjay Patelac3951a2018-05-09 23:08:15 +0000144 // The pattern was found. Create a masked compare that replaces all of the
145 // shift and logic ops.
Sanjay Pateld2025a22018-05-01 21:02:09 +0000146 IRBuilder<> Builder(&I);
Sanjay Patelac3951a2018-05-09 23:08:15 +0000147 Constant *Mask = ConstantInt::get(I.getType(), MOps.Mask);
148 Value *And = Builder.CreateAnd(MOps.Root, Mask);
149 Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask) :
150 Builder.CreateIsNotNull(And);
151 Value *Zext = Builder.CreateZExt(Cmp, I.getType());
Sanjay Pateld2025a22018-05-01 21:02:09 +0000152 I.replaceAllUsesWith(Zext);
153 return true;
154}
155
156/// This is the entry point for folds that could be implemented in regular
157/// InstCombine, but they are separated because they are not expected to
158/// occur frequently and/or have more than a constant-length pattern match.
159static bool foldUnusualPatterns(Function &F, DominatorTree &DT) {
160 bool MadeChange = false;
161 for (BasicBlock &BB : F) {
162 // Ignore unreachable basic blocks.
163 if (!DT.isReachableFromEntry(&BB))
164 continue;
165 // Do not delete instructions under here and invalidate the iterator.
Sanjay Patelac3951a2018-05-09 23:08:15 +0000166 // Walk the block backwards for efficiency. We're matching a chain of
167 // use->defs, so we're more likely to succeed by starting from the bottom.
168 // Also, we want to avoid matching partial patterns.
169 // TODO: It would be more efficient if we removed dead instructions
170 // iteratively in this loop rather than waiting until the end.
171 for (Instruction &I : make_range(BB.rbegin(), BB.rend()))
172 MadeChange |= foldAnyOrAllBitsSet(I);
Sanjay Pateld2025a22018-05-01 21:02:09 +0000173 }
174
175 // We're done with transforms, so remove dead instructions.
176 if (MadeChange)
177 for (BasicBlock &BB : F)
178 SimplifyInstructionsInBlock(&BB);
179
180 return MadeChange;
181}
182
183/// This is the entry point for all transforms. Pass manager differences are
184/// handled in the callers of this function.
185static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT) {
186 bool MadeChange = false;
187 const DataLayout &DL = F.getParent()->getDataLayout();
188 TruncInstCombine TIC(TLI, DL, DT);
189 MadeChange |= TIC.run(F);
190 MadeChange |= foldUnusualPatterns(F, DT);
191 return MadeChange;
192}
193
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000194void AggressiveInstCombinerLegacyPass::getAnalysisUsage(
195 AnalysisUsage &AU) const {
196 AU.setPreservesCFG();
Amjad Aboudd895bff2018-01-31 10:41:31 +0000197 AU.addRequired<DominatorTreeWrapperPass>();
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000198 AU.addRequired<TargetLibraryInfoWrapperPass>();
199 AU.addPreserved<AAResultsWrapperPass>();
200 AU.addPreserved<BasicAAWrapperPass>();
Amjad Aboudd895bff2018-01-31 10:41:31 +0000201 AU.addPreserved<DominatorTreeWrapperPass>();
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000202 AU.addPreserved<GlobalsAAWrapperPass>();
203}
204
205bool AggressiveInstCombinerLegacyPass::runOnFunction(Function &F) {
206 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Sanjay Pateld2025a22018-05-01 21:02:09 +0000207 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
208 return runImpl(F, TLI, DT);
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000209}
210
211PreservedAnalyses AggressiveInstCombinePass::run(Function &F,
212 FunctionAnalysisManager &AM) {
213 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
Sanjay Pateld2025a22018-05-01 21:02:09 +0000214 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
215 if (!runImpl(F, TLI, DT)) {
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000216 // No changes, all analyses are preserved.
217 return PreservedAnalyses::all();
Sanjay Pateld2025a22018-05-01 21:02:09 +0000218 }
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000219 // Mark all the analyses that instcombine updates as preserved.
220 PreservedAnalyses PA;
221 PA.preserveSet<CFGAnalyses>();
222 PA.preserve<AAManager>();
223 PA.preserve<GlobalsAA>();
224 return PA;
225}
226
227char AggressiveInstCombinerLegacyPass::ID = 0;
228INITIALIZE_PASS_BEGIN(AggressiveInstCombinerLegacyPass,
229 "aggressive-instcombine",
230 "Combine pattern based expressions", false, false)
Amjad Aboudd895bff2018-01-31 10:41:31 +0000231INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000232INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
233INITIALIZE_PASS_END(AggressiveInstCombinerLegacyPass, "aggressive-instcombine",
234 "Combine pattern based expressions", false, false)
235
Craig Topperd4eb2072018-04-24 00:05:21 +0000236// Initialization Routines
237void llvm::initializeAggressiveInstCombine(PassRegistry &Registry) {
238 initializeAggressiveInstCombinerLegacyPassPass(Registry);
239}
240
Craig Topper1bcb2582018-04-24 00:39:29 +0000241void LLVMInitializeAggressiveInstCombiner(LLVMPassRegistryRef R) {
242 initializeAggressiveInstCombinerLegacyPassPass(*unwrap(R));
243}
244
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000245FunctionPass *llvm::createAggressiveInstCombinerPass() {
246 return new AggressiveInstCombinerLegacyPass();
247}
David Blaikieba47dd12018-04-24 15:40:07 +0000248
249void LLVMAddAggressiveInstCombinerPass(LLVMPassManagerRef PM) {
250 unwrap(PM)->add(createAggressiveInstCombinerPass());
251}