blob: 2646d0bcbf47e3a6f07c5cbb0c2330a25ccf4fc9 [file] [log] [blame]
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001//===- HexagonLoopIdiomRecognition.cpp ------------------------------------===//
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002//
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#define DEBUG_TYPE "hexagon-lir"
11
Eugene Zelenko4d060b72017-07-29 00:56:56 +000012#include "llvm/ADT/APInt.h"
13#include "llvm/ADT/DenseMap.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000014#include "llvm/ADT/SetVector.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000015#include "llvm/ADT/SmallPtrSet.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000016#include "llvm/ADT/SmallSet.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Triple.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000020#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000022#include "llvm/Analysis/LoopInfo.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000023#include "llvm/Analysis/LoopPass.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000024#include "llvm/Analysis/MemoryLocation.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000025#include "llvm/Analysis/ScalarEvolution.h"
26#include "llvm/Analysis/ScalarEvolutionExpander.h"
27#include "llvm/Analysis/ScalarEvolutionExpressions.h"
28#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000030#include "llvm/IR/Attributes.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Constant.h"
33#include "llvm/IR/Constants.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000034#include "llvm/IR/DataLayout.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000035#include "llvm/IR/DebugLoc.h"
36#include "llvm/IR/DerivedTypes.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000037#include "llvm/IR/Dominators.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000038#include "llvm/IR/Function.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000039#include "llvm/IR/IRBuilder.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000040#include "llvm/IR/InstrTypes.h"
41#include "llvm/IR/Instruction.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/IR/Intrinsics.h"
45#include "llvm/IR/Module.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000046#include "llvm/IR/PatternMatch.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000047#include "llvm/IR/Type.h"
48#include "llvm/IR/User.h"
49#include "llvm/IR/Value.h"
50#include "llvm/Pass.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Compiler.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000054#include "llvm/Support/Debug.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000055#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000056#include "llvm/Support/KnownBits.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000057#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000058#include "llvm/Transforms/Scalar.h"
59#include "llvm/Transforms/Utils/Local.h"
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000060#include <algorithm>
61#include <array>
Eugene Zelenko4d060b72017-07-29 00:56:56 +000062#include <cassert>
63#include <cstdint>
64#include <cstdlib>
65#include <deque>
66#include <functional>
67#include <iterator>
68#include <map>
69#include <set>
70#include <utility>
71#include <vector>
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +000072
73using namespace llvm;
74
75static cl::opt<bool> DisableMemcpyIdiom("disable-memcpy-idiom",
76 cl::Hidden, cl::init(false),
77 cl::desc("Disable generation of memcpy in loop idiom recognition"));
78
79static cl::opt<bool> DisableMemmoveIdiom("disable-memmove-idiom",
80 cl::Hidden, cl::init(false),
81 cl::desc("Disable generation of memmove in loop idiom recognition"));
82
83static cl::opt<unsigned> RuntimeMemSizeThreshold("runtime-mem-idiom-threshold",
84 cl::Hidden, cl::init(0), cl::desc("Threshold (in bytes) for the runtime "
85 "check guarding the memmove."));
86
87static cl::opt<unsigned> CompileTimeMemSizeThreshold(
88 "compile-time-mem-idiom-threshold", cl::Hidden, cl::init(64),
89 cl::desc("Threshold (in bytes) to perform the transformation, if the "
90 "runtime loop count (mem transfer size) is known at compile-time."));
91
92static cl::opt<bool> OnlyNonNestedMemmove("only-nonnested-memmove-idiom",
93 cl::Hidden, cl::init(true),
94 cl::desc("Only enable generating memmove in non-nested loops"));
95
96cl::opt<bool> HexagonVolatileMemcpy("disable-hexagon-volatile-memcpy",
97 cl::Hidden, cl::init(false),
98 cl::desc("Enable Hexagon-specific memcpy for volatile destination."));
99
Krzysztof Parzyszek51fd5402017-06-01 18:00:47 +0000100static cl::opt<unsigned> SimplifyLimit("hlir-simplify-limit", cl::init(10000),
101 cl::Hidden, cl::desc("Maximum number of simplification steps in HLIR"));
102
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000103static const char *HexagonVolatileMemcpyName
104 = "hexagon_memcpy_forward_vp4cp4n2";
105
106
107namespace llvm {
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000108
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000109 void initializeHexagonLoopIdiomRecognizePass(PassRegistry&);
110 Pass *createHexagonLoopIdiomPass();
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000111
112} // end namespace llvm
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000113
114namespace {
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000115
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000116 class HexagonLoopIdiomRecognize : public LoopPass {
117 public:
118 static char ID;
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000119
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000120 explicit HexagonLoopIdiomRecognize() : LoopPass(ID) {
121 initializeHexagonLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
122 }
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000123
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000124 StringRef getPassName() const override {
125 return "Recognize Hexagon-specific loop idioms";
126 }
127
128 void getAnalysisUsage(AnalysisUsage &AU) const override {
129 AU.addRequired<LoopInfoWrapperPass>();
130 AU.addRequiredID(LoopSimplifyID);
131 AU.addRequiredID(LCSSAID);
132 AU.addRequired<AAResultsWrapperPass>();
133 AU.addPreserved<AAResultsWrapperPass>();
134 AU.addRequired<ScalarEvolutionWrapperPass>();
135 AU.addRequired<DominatorTreeWrapperPass>();
136 AU.addRequired<TargetLibraryInfoWrapperPass>();
137 AU.addPreserved<TargetLibraryInfoWrapperPass>();
138 }
139
140 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
141
142 private:
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000143 int getSCEVStride(const SCEVAddRecExpr *StoreEv);
144 bool isLegalStore(Loop *CurLoop, StoreInst *SI);
145 void collectStores(Loop *CurLoop, BasicBlock *BB,
146 SmallVectorImpl<StoreInst*> &Stores);
147 bool processCopyingStore(Loop *CurLoop, StoreInst *SI, const SCEV *BECount);
148 bool coverLoop(Loop *L, SmallVectorImpl<Instruction*> &Insts) const;
149 bool runOnLoopBlock(Loop *CurLoop, BasicBlock *BB, const SCEV *BECount,
150 SmallVectorImpl<BasicBlock*> &ExitBlocks);
151 bool runOnCountableLoop(Loop *L);
152
153 AliasAnalysis *AA;
154 const DataLayout *DL;
155 DominatorTree *DT;
156 LoopInfo *LF;
157 const TargetLibraryInfo *TLI;
158 ScalarEvolution *SE;
159 bool HasMemcpy, HasMemmove;
160 };
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000161
162 struct Simplifier {
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +0000163 struct Rule {
164 using FuncType = std::function<Value* (Instruction*, LLVMContext&)>;
165 Rule(StringRef N, FuncType F) : Name(N), Fn(F) {}
166 StringRef Name; // For debugging.
167 FuncType Fn;
168 };
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000169
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +0000170 void addRule(StringRef N, const Rule::FuncType &F) {
171 Rules.push_back(Rule(N, F));
172 }
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000173
174 private:
175 struct WorkListType {
176 WorkListType() = default;
177
178 void push_back(Value* V) {
179 // Do not push back duplicates.
180 if (!S.count(V)) { Q.push_back(V); S.insert(V); }
181 }
182
183 Value *pop_front_val() {
184 Value *V = Q.front(); Q.pop_front(); S.erase(V);
185 return V;
186 }
187
188 bool empty() const { return Q.empty(); }
189
190 private:
191 std::deque<Value*> Q;
192 std::set<Value*> S;
193 };
194
195 using ValueSetType = std::set<Value *>;
196
197 std::vector<Rule> Rules;
198
199 public:
200 struct Context {
201 using ValueMapType = DenseMap<Value *, Value *>;
202
203 Value *Root;
204 ValueSetType Used; // The set of all cloned values used by Root.
205 ValueSetType Clones; // The set of all cloned values.
206 LLVMContext &Ctx;
207
208 Context(Instruction *Exp)
209 : Ctx(Exp->getParent()->getParent()->getContext()) {
210 initialize(Exp);
211 }
212
213 ~Context() { cleanup(); }
214
215 void print(raw_ostream &OS, const Value *V) const;
216 Value *materialize(BasicBlock *B, BasicBlock::iterator At);
217
218 private:
219 friend struct Simplifier;
220
221 void initialize(Instruction *Exp);
222 void cleanup();
223
224 template <typename FuncT> void traverse(Value *V, FuncT F);
225 void record(Value *V);
226 void use(Value *V);
227 void unuse(Value *V);
228
229 bool equal(const Instruction *I, const Instruction *J) const;
230 Value *find(Value *Tree, Value *Sub) const;
231 Value *subst(Value *Tree, Value *OldV, Value *NewV);
232 void replace(Value *OldV, Value *NewV);
233 void link(Instruction *I, BasicBlock *B, BasicBlock::iterator At);
234 };
235
236 Value *simplify(Context &C);
237 };
238
239 struct PE {
240 PE(const Simplifier::Context &c, Value *v = nullptr) : C(c), V(v) {}
241
242 const Simplifier::Context &C;
243 const Value *V;
244 };
245
246 raw_ostream &operator<< (raw_ostream &OS, const PE &P) LLVM_ATTRIBUTE_USED;
247 raw_ostream &operator<< (raw_ostream &OS, const PE &P) {
248 P.C.print(OS, P.V ? P.V : P.C.Root);
249 return OS;
250 }
251
252} // end anonymous namespace
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000253
254char HexagonLoopIdiomRecognize::ID = 0;
255
256INITIALIZE_PASS_BEGIN(HexagonLoopIdiomRecognize, "hexagon-loop-idiom",
257 "Recognize Hexagon-specific loop idioms", false, false)
258INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
259INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
260INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
261INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
262INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
263INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
264INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
265INITIALIZE_PASS_END(HexagonLoopIdiomRecognize, "hexagon-loop-idiom",
266 "Recognize Hexagon-specific loop idioms", false, false)
267
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000268template <typename FuncT>
269void Simplifier::Context::traverse(Value *V, FuncT F) {
270 WorkListType Q;
271 Q.push_back(V);
272
273 while (!Q.empty()) {
Krzysztof Parzyszek10fbac02017-03-23 23:01:22 +0000274 Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000275 if (!U || U->getParent())
276 continue;
277 if (!F(U))
278 continue;
279 for (Value *Op : U->operands())
280 Q.push_back(Op);
281 }
282}
283
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000284void Simplifier::Context::print(raw_ostream &OS, const Value *V) const {
285 const auto *U = dyn_cast<const Instruction>(V);
286 if (!U) {
287 OS << V << '(' << *V << ')';
288 return;
289 }
290
291 if (U->getParent()) {
292 OS << U << '(';
293 U->printAsOperand(OS, true);
294 OS << ')';
295 return;
296 }
297
298 unsigned N = U->getNumOperands();
299 if (N != 0)
300 OS << U << '(';
301 OS << U->getOpcodeName();
302 for (const Value *Op : U->operands()) {
303 OS << ' ';
304 print(OS, Op);
305 }
306 if (N != 0)
307 OS << ')';
308}
309
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000310void Simplifier::Context::initialize(Instruction *Exp) {
311 // Perform a deep clone of the expression, set Root to the root
312 // of the clone, and build a map from the cloned values to the
313 // original ones.
314 ValueMapType M;
315 BasicBlock *Block = Exp->getParent();
316 WorkListType Q;
317 Q.push_back(Exp);
318
319 while (!Q.empty()) {
Krzysztof Parzyszek10fbac02017-03-23 23:01:22 +0000320 Value *V = Q.pop_front_val();
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000321 if (M.find(V) != M.end())
322 continue;
323 if (Instruction *U = dyn_cast<Instruction>(V)) {
324 if (isa<PHINode>(U) || U->getParent() != Block)
325 continue;
326 for (Value *Op : U->operands())
327 Q.push_back(Op);
328 M.insert({U, U->clone()});
329 }
330 }
331
332 for (std::pair<Value*,Value*> P : M) {
333 Instruction *U = cast<Instruction>(P.second);
334 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
335 auto F = M.find(U->getOperand(i));
336 if (F != M.end())
337 U->setOperand(i, F->second);
338 }
339 }
340
341 auto R = M.find(Exp);
342 assert(R != M.end());
343 Root = R->second;
344
345 record(Root);
346 use(Root);
347}
348
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000349void Simplifier::Context::record(Value *V) {
350 auto Record = [this](Instruction *U) -> bool {
351 Clones.insert(U);
352 return true;
353 };
354 traverse(V, Record);
355}
356
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000357void Simplifier::Context::use(Value *V) {
358 auto Use = [this](Instruction *U) -> bool {
359 Used.insert(U);
360 return true;
361 };
362 traverse(V, Use);
363}
364
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000365void Simplifier::Context::unuse(Value *V) {
366 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != nullptr)
367 return;
368
369 auto Unuse = [this](Instruction *U) -> bool {
370 if (!U->use_empty())
371 return false;
372 Used.erase(U);
373 return true;
374 };
375 traverse(V, Unuse);
376}
377
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000378Value *Simplifier::Context::subst(Value *Tree, Value *OldV, Value *NewV) {
379 if (Tree == OldV)
380 return NewV;
381 if (OldV == NewV)
382 return Tree;
383
384 WorkListType Q;
385 Q.push_back(Tree);
386 while (!Q.empty()) {
Krzysztof Parzyszek10fbac02017-03-23 23:01:22 +0000387 Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000388 // If U is not an instruction, or it's not a clone, skip it.
389 if (!U || U->getParent())
390 continue;
391 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
392 Value *Op = U->getOperand(i);
393 if (Op == OldV) {
394 U->setOperand(i, NewV);
395 unuse(OldV);
396 } else {
397 Q.push_back(Op);
398 }
399 }
400 }
401 return Tree;
402}
403
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000404void Simplifier::Context::replace(Value *OldV, Value *NewV) {
405 if (Root == OldV) {
406 Root = NewV;
407 use(Root);
408 return;
409 }
410
411 // NewV may be a complex tree that has just been created by one of the
412 // transformation rules. We need to make sure that it is commoned with
413 // the existing Root to the maximum extent possible.
414 // Identify all subtrees of NewV (including NewV itself) that have
415 // equivalent counterparts in Root, and replace those subtrees with
416 // these counterparts.
417 WorkListType Q;
418 Q.push_back(NewV);
419 while (!Q.empty()) {
Krzysztof Parzyszek10fbac02017-03-23 23:01:22 +0000420 Value *V = Q.pop_front_val();
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000421 Instruction *U = dyn_cast<Instruction>(V);
422 if (!U || U->getParent())
423 continue;
424 if (Value *DupV = find(Root, V)) {
425 if (DupV != V)
426 NewV = subst(NewV, V, DupV);
427 } else {
428 for (Value *Op : U->operands())
429 Q.push_back(Op);
430 }
431 }
432
433 // Now, simply replace OldV with NewV in Root.
434 Root = subst(Root, OldV, NewV);
435 use(Root);
436}
437
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000438void Simplifier::Context::cleanup() {
439 for (Value *V : Clones) {
440 Instruction *U = cast<Instruction>(V);
441 if (!U->getParent())
442 U->dropAllReferences();
443 }
444
445 for (Value *V : Clones) {
446 Instruction *U = cast<Instruction>(V);
447 if (!U->getParent())
Reid Kleckner96ab8722017-05-18 17:24:10 +0000448 U->deleteValue();
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000449 }
450}
451
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000452bool Simplifier::Context::equal(const Instruction *I,
453 const Instruction *J) const {
454 if (I == J)
455 return true;
456 if (!I->isSameOperationAs(J))
457 return false;
458 if (isa<PHINode>(I))
459 return I->isIdenticalTo(J);
460
461 for (unsigned i = 0, n = I->getNumOperands(); i != n; ++i) {
462 Value *OpI = I->getOperand(i), *OpJ = J->getOperand(i);
463 if (OpI == OpJ)
464 continue;
465 auto *InI = dyn_cast<const Instruction>(OpI);
466 auto *InJ = dyn_cast<const Instruction>(OpJ);
467 if (InI && InJ) {
468 if (!equal(InI, InJ))
469 return false;
470 } else if (InI != InJ || !InI)
471 return false;
472 }
473 return true;
474}
475
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000476Value *Simplifier::Context::find(Value *Tree, Value *Sub) const {
477 Instruction *SubI = dyn_cast<Instruction>(Sub);
478 WorkListType Q;
479 Q.push_back(Tree);
480
481 while (!Q.empty()) {
Krzysztof Parzyszek10fbac02017-03-23 23:01:22 +0000482 Value *V = Q.pop_front_val();
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000483 if (V == Sub)
484 return V;
485 Instruction *U = dyn_cast<Instruction>(V);
486 if (!U || U->getParent())
487 continue;
488 if (SubI && equal(SubI, U))
489 return U;
490 assert(!isa<PHINode>(U));
491 for (Value *Op : U->operands())
492 Q.push_back(Op);
493 }
494 return nullptr;
495}
496
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000497void Simplifier::Context::link(Instruction *I, BasicBlock *B,
498 BasicBlock::iterator At) {
499 if (I->getParent())
500 return;
501
502 for (Value *Op : I->operands()) {
503 if (Instruction *OpI = dyn_cast<Instruction>(Op))
504 link(OpI, B, At);
505 }
506
507 B->getInstList().insert(At, I);
508}
509
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000510Value *Simplifier::Context::materialize(BasicBlock *B,
511 BasicBlock::iterator At) {
512 if (Instruction *RootI = dyn_cast<Instruction>(Root))
513 link(RootI, B, At);
514 return Root;
515}
516
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000517Value *Simplifier::simplify(Context &C) {
518 WorkListType Q;
519 Q.push_back(C.Root);
Krzysztof Parzyszek10fbac02017-03-23 23:01:22 +0000520 unsigned Count = 0;
Krzysztof Parzyszek51fd5402017-06-01 18:00:47 +0000521 const unsigned Limit = SimplifyLimit;
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000522
523 while (!Q.empty()) {
Krzysztof Parzyszek10fbac02017-03-23 23:01:22 +0000524 if (Count++ >= Limit)
525 break;
526 Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000527 if (!U || U->getParent() || !C.Used.count(U))
528 continue;
529 bool Changed = false;
530 for (Rule &R : Rules) {
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +0000531 Value *W = R.Fn(U, C.Ctx);
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000532 if (!W)
533 continue;
534 Changed = true;
535 C.record(W);
536 C.replace(U, W);
537 Q.push_back(C.Root);
538 break;
539 }
540 if (!Changed) {
541 for (Value *Op : U->operands())
542 Q.push_back(Op);
543 }
544 }
Krzysztof Parzyszek51fd5402017-06-01 18:00:47 +0000545 return Count < Limit ? C.Root : nullptr;
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000546}
547
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000548//===----------------------------------------------------------------------===//
549//
550// Implementation of PolynomialMultiplyRecognize
551//
552//===----------------------------------------------------------------------===//
553
554namespace {
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000555
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000556 class PolynomialMultiplyRecognize {
557 public:
558 explicit PolynomialMultiplyRecognize(Loop *loop, const DataLayout &dl,
559 const DominatorTree &dt, const TargetLibraryInfo &tli,
560 ScalarEvolution &se)
561 : CurLoop(loop), DL(dl), DT(dt), TLI(tli), SE(se) {}
562
563 bool recognize();
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000564
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000565 private:
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000566 using ValueSeq = SetVector<Value *>;
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000567
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000568 IntegerType *getPmpyType() const {
569 LLVMContext &Ctx = CurLoop->getHeader()->getParent()->getContext();
570 return IntegerType::get(Ctx, 32);
571 }
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000572
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000573 bool isPromotableTo(Value *V, IntegerType *Ty);
574 void promoteTo(Instruction *In, IntegerType *DestTy, BasicBlock *LoopB);
575 bool promoteTypes(BasicBlock *LoopB, BasicBlock *ExitB);
576
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000577 Value *getCountIV(BasicBlock *BB);
578 bool findCycle(Value *Out, Value *In, ValueSeq &Cycle);
579 void classifyCycle(Instruction *DivI, ValueSeq &Cycle, ValueSeq &Early,
580 ValueSeq &Late);
581 bool classifyInst(Instruction *UseI, ValueSeq &Early, ValueSeq &Late);
582 bool commutesWithShift(Instruction *I);
583 bool highBitsAreZero(Value *V, unsigned IterCount);
584 bool keepsHighBitsZero(Value *V, unsigned IterCount);
585 bool isOperandShifted(Instruction *I, Value *Op);
586 bool convertShiftsToLeft(BasicBlock *LoopB, BasicBlock *ExitB,
587 unsigned IterCount);
588 void cleanupLoopBody(BasicBlock *LoopB);
589
590 struct ParsedValues {
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000591 ParsedValues() = default;
592
593 Value *M = nullptr;
594 Value *P = nullptr;
595 Value *Q = nullptr;
596 Value *R = nullptr;
597 Value *X = nullptr;
598 Instruction *Res = nullptr;
599 unsigned IterCount = 0;
600 bool Left = false;
601 bool Inv = false;
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000602 };
603
604 bool matchLeftShift(SelectInst *SelI, Value *CIV, ParsedValues &PV);
605 bool matchRightShift(SelectInst *SelI, ParsedValues &PV);
606 bool scanSelect(SelectInst *SI, BasicBlock *LoopB, BasicBlock *PrehB,
607 Value *CIV, ParsedValues &PV, bool PreScan);
608 unsigned getInverseMxN(unsigned QP);
609 Value *generate(BasicBlock::iterator At, ParsedValues &PV);
610
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000611 void setupSimplifier();
612
613 Simplifier Simp;
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000614 Loop *CurLoop;
615 const DataLayout &DL;
616 const DominatorTree &DT;
617 const TargetLibraryInfo &TLI;
618 ScalarEvolution &SE;
619 };
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000620
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000621} // end anonymous namespace
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000622
623Value *PolynomialMultiplyRecognize::getCountIV(BasicBlock *BB) {
624 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
625 if (std::distance(PI, PE) != 2)
626 return nullptr;
627 BasicBlock *PB = (*PI == BB) ? *std::next(PI) : *PI;
628
629 for (auto I = BB->begin(), E = BB->end(); I != E && isa<PHINode>(I); ++I) {
630 auto *PN = cast<PHINode>(I);
631 Value *InitV = PN->getIncomingValueForBlock(PB);
632 if (!isa<ConstantInt>(InitV) || !cast<ConstantInt>(InitV)->isZero())
633 continue;
634 Value *IterV = PN->getIncomingValueForBlock(BB);
635 if (!isa<BinaryOperator>(IterV))
636 continue;
637 auto *BO = dyn_cast<BinaryOperator>(IterV);
638 if (BO->getOpcode() != Instruction::Add)
639 continue;
640 Value *IncV = nullptr;
641 if (BO->getOperand(0) == PN)
642 IncV = BO->getOperand(1);
643 else if (BO->getOperand(1) == PN)
644 IncV = BO->getOperand(0);
645 if (IncV == nullptr)
646 continue;
647
648 if (auto *T = dyn_cast<ConstantInt>(IncV))
649 if (T->getZExtValue() == 1)
650 return PN;
651 }
652 return nullptr;
653}
654
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000655static void replaceAllUsesOfWithIn(Value *I, Value *J, BasicBlock *BB) {
656 for (auto UI = I->user_begin(), UE = I->user_end(); UI != UE;) {
657 Use &TheUse = UI.getUse();
658 ++UI;
659 if (auto *II = dyn_cast<Instruction>(TheUse.getUser()))
660 if (BB == II->getParent())
661 II->replaceUsesOfWith(I, J);
662 }
663}
664
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000665bool PolynomialMultiplyRecognize::matchLeftShift(SelectInst *SelI,
666 Value *CIV, ParsedValues &PV) {
667 // Match the following:
668 // select (X & (1 << i)) != 0 ? R ^ (Q << i) : R
669 // select (X & (1 << i)) == 0 ? R : R ^ (Q << i)
670 // The condition may also check for equality with the masked value, i.e
671 // select (X & (1 << i)) == (1 << i) ? R ^ (Q << i) : R
672 // select (X & (1 << i)) != (1 << i) ? R : R ^ (Q << i);
673
674 Value *CondV = SelI->getCondition();
675 Value *TrueV = SelI->getTrueValue();
676 Value *FalseV = SelI->getFalseValue();
677
678 using namespace PatternMatch;
679
680 CmpInst::Predicate P;
681 Value *A = nullptr, *B = nullptr, *C = nullptr;
682
683 if (!match(CondV, m_ICmp(P, m_And(m_Value(A), m_Value(B)), m_Value(C))) &&
684 !match(CondV, m_ICmp(P, m_Value(C), m_And(m_Value(A), m_Value(B)))))
685 return false;
686 if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
687 return false;
688 // Matched: select (A & B) == C ? ... : ...
689 // select (A & B) != C ? ... : ...
690
691 Value *X = nullptr, *Sh1 = nullptr;
692 // Check (A & B) for (X & (1 << i)):
693 if (match(A, m_Shl(m_One(), m_Specific(CIV)))) {
694 Sh1 = A;
695 X = B;
696 } else if (match(B, m_Shl(m_One(), m_Specific(CIV)))) {
697 Sh1 = B;
698 X = A;
699 } else {
700 // TODO: Could also check for an induction variable containing single
701 // bit shifted left by 1 in each iteration.
702 return false;
703 }
704
705 bool TrueIfZero;
706
707 // Check C against the possible values for comparison: 0 and (1 << i):
708 if (match(C, m_Zero()))
709 TrueIfZero = (P == CmpInst::ICMP_EQ);
710 else if (C == Sh1)
711 TrueIfZero = (P == CmpInst::ICMP_NE);
712 else
713 return false;
714
715 // So far, matched:
716 // select (X & (1 << i)) ? ... : ...
717 // including variations of the check against zero/non-zero value.
718
719 Value *ShouldSameV = nullptr, *ShouldXoredV = nullptr;
720 if (TrueIfZero) {
721 ShouldSameV = TrueV;
722 ShouldXoredV = FalseV;
723 } else {
724 ShouldSameV = FalseV;
725 ShouldXoredV = TrueV;
726 }
727
728 Value *Q = nullptr, *R = nullptr, *Y = nullptr, *Z = nullptr;
729 Value *T = nullptr;
730 if (match(ShouldXoredV, m_Xor(m_Value(Y), m_Value(Z)))) {
731 // Matched: select +++ ? ... : Y ^ Z
732 // select +++ ? Y ^ Z : ...
733 // where +++ denotes previously checked matches.
734 if (ShouldSameV == Y)
735 T = Z;
736 else if (ShouldSameV == Z)
737 T = Y;
738 else
739 return false;
740 R = ShouldSameV;
741 // Matched: select +++ ? R : R ^ T
742 // select +++ ? R ^ T : R
743 // depending on TrueIfZero.
744
745 } else if (match(ShouldSameV, m_Zero())) {
746 // Matched: select +++ ? 0 : ...
747 // select +++ ? ... : 0
748 if (!SelI->hasOneUse())
749 return false;
750 T = ShouldXoredV;
751 // Matched: select +++ ? 0 : T
752 // select +++ ? T : 0
753
754 Value *U = *SelI->user_begin();
755 if (!match(U, m_Xor(m_Specific(SelI), m_Value(R))) &&
756 !match(U, m_Xor(m_Value(R), m_Specific(SelI))))
757 return false;
758 // Matched: xor (select +++ ? 0 : T), R
759 // xor (select +++ ? T : 0), R
760 } else
761 return false;
762
763 // The xor input value T is isolated into its own match so that it could
764 // be checked against an induction variable containing a shifted bit
765 // (todo).
766 // For now, check against (Q << i).
767 if (!match(T, m_Shl(m_Value(Q), m_Specific(CIV))) &&
768 !match(T, m_Shl(m_ZExt(m_Value(Q)), m_ZExt(m_Specific(CIV)))))
769 return false;
770 // Matched: select +++ ? R : R ^ (Q << i)
771 // select +++ ? R ^ (Q << i) : R
772
773 PV.X = X;
774 PV.Q = Q;
775 PV.R = R;
776 PV.Left = true;
777 return true;
778}
779
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000780bool PolynomialMultiplyRecognize::matchRightShift(SelectInst *SelI,
781 ParsedValues &PV) {
782 // Match the following:
783 // select (X & 1) != 0 ? (R >> 1) ^ Q : (R >> 1)
784 // select (X & 1) == 0 ? (R >> 1) : (R >> 1) ^ Q
785 // The condition may also check for equality with the masked value, i.e
786 // select (X & 1) == 1 ? (R >> 1) ^ Q : (R >> 1)
787 // select (X & 1) != 1 ? (R >> 1) : (R >> 1) ^ Q
788
789 Value *CondV = SelI->getCondition();
790 Value *TrueV = SelI->getTrueValue();
791 Value *FalseV = SelI->getFalseValue();
792
793 using namespace PatternMatch;
794
795 Value *C = nullptr;
796 CmpInst::Predicate P;
797 bool TrueIfZero;
798
799 if (match(CondV, m_ICmp(P, m_Value(C), m_Zero())) ||
800 match(CondV, m_ICmp(P, m_Zero(), m_Value(C)))) {
801 if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
802 return false;
803 // Matched: select C == 0 ? ... : ...
804 // select C != 0 ? ... : ...
805 TrueIfZero = (P == CmpInst::ICMP_EQ);
806 } else if (match(CondV, m_ICmp(P, m_Value(C), m_One())) ||
807 match(CondV, m_ICmp(P, m_One(), m_Value(C)))) {
808 if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
809 return false;
810 // Matched: select C == 1 ? ... : ...
811 // select C != 1 ? ... : ...
812 TrueIfZero = (P == CmpInst::ICMP_NE);
813 } else
814 return false;
815
816 Value *X = nullptr;
817 if (!match(C, m_And(m_Value(X), m_One())) &&
818 !match(C, m_And(m_One(), m_Value(X))))
819 return false;
820 // Matched: select (X & 1) == +++ ? ... : ...
821 // select (X & 1) != +++ ? ... : ...
822
823 Value *R = nullptr, *Q = nullptr;
824 if (TrueIfZero) {
825 // The select's condition is true if the tested bit is 0.
826 // TrueV must be the shift, FalseV must be the xor.
827 if (!match(TrueV, m_LShr(m_Value(R), m_One())))
828 return false;
829 // Matched: select +++ ? (R >> 1) : ...
830 if (!match(FalseV, m_Xor(m_Specific(TrueV), m_Value(Q))) &&
831 !match(FalseV, m_Xor(m_Value(Q), m_Specific(TrueV))))
832 return false;
833 // Matched: select +++ ? (R >> 1) : (R >> 1) ^ Q
834 // with commuting ^.
835 } else {
836 // The select's condition is true if the tested bit is 1.
837 // TrueV must be the xor, FalseV must be the shift.
838 if (!match(FalseV, m_LShr(m_Value(R), m_One())))
839 return false;
840 // Matched: select +++ ? ... : (R >> 1)
841 if (!match(TrueV, m_Xor(m_Specific(FalseV), m_Value(Q))) &&
842 !match(TrueV, m_Xor(m_Value(Q), m_Specific(FalseV))))
843 return false;
844 // Matched: select +++ ? (R >> 1) ^ Q : (R >> 1)
845 // with commuting ^.
846 }
847
848 PV.X = X;
849 PV.Q = Q;
850 PV.R = R;
851 PV.Left = false;
852 return true;
853}
854
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000855bool PolynomialMultiplyRecognize::scanSelect(SelectInst *SelI,
856 BasicBlock *LoopB, BasicBlock *PrehB, Value *CIV, ParsedValues &PV,
857 bool PreScan) {
858 using namespace PatternMatch;
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000859
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +0000860 // The basic pattern for R = P.Q is:
861 // for i = 0..31
862 // R = phi (0, R')
863 // if (P & (1 << i)) ; test-bit(P, i)
864 // R' = R ^ (Q << i)
865 //
866 // Similarly, the basic pattern for R = (P/Q).Q - P
867 // for i = 0..31
868 // R = phi(P, R')
869 // if (R & (1 << i))
870 // R' = R ^ (Q << i)
871
872 // There exist idioms, where instead of Q being shifted left, P is shifted
873 // right. This produces a result that is shifted right by 32 bits (the
874 // non-shifted result is 64-bit).
875 //
876 // For R = P.Q, this would be:
877 // for i = 0..31
878 // R = phi (0, R')
879 // if ((P >> i) & 1)
880 // R' = (R >> 1) ^ Q ; R is cycled through the loop, so it must
881 // else ; be shifted by 1, not i.
882 // R' = R >> 1
883 //
884 // And for the inverse:
885 // for i = 0..31
886 // R = phi (P, R')
887 // if (R & 1)
888 // R' = (R >> 1) ^ Q
889 // else
890 // R' = R >> 1
891
892 // The left-shifting idioms share the same pattern:
893 // select (X & (1 << i)) ? R ^ (Q << i) : R
894 // Similarly for right-shifting idioms:
895 // select (X & 1) ? (R >> 1) ^ Q
896
897 if (matchLeftShift(SelI, CIV, PV)) {
898 // If this is a pre-scan, getting this far is sufficient.
899 if (PreScan)
900 return true;
901
902 // Need to make sure that the SelI goes back into R.
903 auto *RPhi = dyn_cast<PHINode>(PV.R);
904 if (!RPhi)
905 return false;
906 if (SelI != RPhi->getIncomingValueForBlock(LoopB))
907 return false;
908 PV.Res = SelI;
909
910 // If X is loop invariant, it must be the input polynomial, and the
911 // idiom is the basic polynomial multiply.
912 if (CurLoop->isLoopInvariant(PV.X)) {
913 PV.P = PV.X;
914 PV.Inv = false;
915 } else {
916 // X is not loop invariant. If X == R, this is the inverse pmpy.
917 // Otherwise, check for an xor with an invariant value. If the
918 // variable argument to the xor is R, then this is still a valid
919 // inverse pmpy.
920 PV.Inv = true;
921 if (PV.X != PV.R) {
922 Value *Var = nullptr, *Inv = nullptr, *X1 = nullptr, *X2 = nullptr;
923 if (!match(PV.X, m_Xor(m_Value(X1), m_Value(X2))))
924 return false;
925 auto *I1 = dyn_cast<Instruction>(X1);
926 auto *I2 = dyn_cast<Instruction>(X2);
927 if (!I1 || I1->getParent() != LoopB) {
928 Var = X2;
929 Inv = X1;
930 } else if (!I2 || I2->getParent() != LoopB) {
931 Var = X1;
932 Inv = X2;
933 } else
934 return false;
935 if (Var != PV.R)
936 return false;
937 PV.M = Inv;
938 }
939 // The input polynomial P still needs to be determined. It will be
940 // the entry value of R.
941 Value *EntryP = RPhi->getIncomingValueForBlock(PrehB);
942 PV.P = EntryP;
943 }
944
945 return true;
946 }
947
948 if (matchRightShift(SelI, PV)) {
949 // If this is an inverse pattern, the Q polynomial must be known at
950 // compile time.
951 if (PV.Inv && !isa<ConstantInt>(PV.Q))
952 return false;
953 if (PreScan)
954 return true;
955 // There is no exact matching of right-shift pmpy.
956 return false;
957 }
958
959 return false;
960}
961
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000962bool PolynomialMultiplyRecognize::isPromotableTo(Value *Val,
963 IntegerType *DestTy) {
964 IntegerType *T = dyn_cast<IntegerType>(Val->getType());
965 if (!T || T->getBitWidth() > DestTy->getBitWidth())
966 return false;
967 if (T->getBitWidth() == DestTy->getBitWidth())
968 return true;
969 // Non-instructions are promotable. The reason why an instruction may not
970 // be promotable is that it may produce a different result if its operands
971 // and the result are promoted, for example, it may produce more non-zero
972 // bits. While it would still be possible to represent the proper result
973 // in a wider type, it may require adding additional instructions (which
974 // we don't want to do).
975 Instruction *In = dyn_cast<Instruction>(Val);
976 if (!In)
977 return true;
978 // The bitwidth of the source type is smaller than the destination.
979 // Check if the individual operation can be promoted.
980 switch (In->getOpcode()) {
981 case Instruction::PHI:
982 case Instruction::ZExt:
983 case Instruction::And:
984 case Instruction::Or:
985 case Instruction::Xor:
986 case Instruction::LShr: // Shift right is ok.
987 case Instruction::Select:
988 return true;
989 case Instruction::ICmp:
990 if (CmpInst *CI = cast<CmpInst>(In))
991 return CI->isEquality() || CI->isUnsigned();
992 llvm_unreachable("Cast failed unexpectedly");
993 case Instruction::Add:
994 return In->hasNoSignedWrap() && In->hasNoUnsignedWrap();
995 }
996 return false;
997}
998
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +0000999void PolynomialMultiplyRecognize::promoteTo(Instruction *In,
1000 IntegerType *DestTy, BasicBlock *LoopB) {
1001 // Leave boolean values alone.
1002 if (!In->getType()->isIntegerTy(1))
1003 In->mutateType(DestTy);
1004 unsigned DestBW = DestTy->getBitWidth();
1005
1006 // Handle PHIs.
1007 if (PHINode *P = dyn_cast<PHINode>(In)) {
1008 unsigned N = P->getNumIncomingValues();
1009 for (unsigned i = 0; i != N; ++i) {
1010 BasicBlock *InB = P->getIncomingBlock(i);
1011 if (InB == LoopB)
1012 continue;
1013 Value *InV = P->getIncomingValue(i);
1014 IntegerType *Ty = cast<IntegerType>(InV->getType());
1015 // Do not promote values in PHI nodes of type i1.
1016 if (Ty != P->getType()) {
1017 // If the value type does not match the PHI type, the PHI type
1018 // must have been promoted.
1019 assert(Ty->getBitWidth() < DestBW);
1020 InV = IRBuilder<>(InB->getTerminator()).CreateZExt(InV, DestTy);
1021 P->setIncomingValue(i, InV);
1022 }
1023 }
1024 } else if (ZExtInst *Z = dyn_cast<ZExtInst>(In)) {
1025 Value *Op = Z->getOperand(0);
1026 if (Op->getType() == Z->getType())
1027 Z->replaceAllUsesWith(Op);
1028 Z->eraseFromParent();
1029 return;
1030 }
1031
1032 // Promote immediates.
1033 for (unsigned i = 0, n = In->getNumOperands(); i != n; ++i) {
1034 if (ConstantInt *CI = dyn_cast<ConstantInt>(In->getOperand(i)))
1035 if (CI->getType()->getBitWidth() < DestBW)
1036 In->setOperand(i, ConstantInt::get(DestTy, CI->getZExtValue()));
1037 }
1038}
1039
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001040bool PolynomialMultiplyRecognize::promoteTypes(BasicBlock *LoopB,
1041 BasicBlock *ExitB) {
1042 assert(LoopB);
1043 // Skip loops where the exit block has more than one predecessor. The values
1044 // coming from the loop block will be promoted to another type, and so the
1045 // values coming into the exit block from other predecessors would also have
1046 // to be promoted.
1047 if (!ExitB || (ExitB->getSinglePredecessor() != LoopB))
1048 return false;
1049 IntegerType *DestTy = getPmpyType();
1050 // Check if the exit values have types that are no wider than the type
1051 // that we want to promote to.
1052 unsigned DestBW = DestTy->getBitWidth();
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001053 for (PHINode &P : ExitB->phis()) {
1054 if (P.getNumIncomingValues() != 1)
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001055 return false;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001056 assert(P.getIncomingBlock(0) == LoopB);
1057 IntegerType *T = dyn_cast<IntegerType>(P.getType());
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001058 if (!T || T->getBitWidth() > DestBW)
1059 return false;
1060 }
1061
1062 // Check all instructions in the loop.
1063 for (Instruction &In : *LoopB)
1064 if (!In.isTerminator() && !isPromotableTo(&In, DestTy))
1065 return false;
1066
1067 // Perform the promotion.
1068 std::vector<Instruction*> LoopIns;
1069 std::transform(LoopB->begin(), LoopB->end(), std::back_inserter(LoopIns),
1070 [](Instruction &In) { return &In; });
1071 for (Instruction *In : LoopIns)
1072 promoteTo(In, DestTy, LoopB);
1073
1074 // Fix up the PHI nodes in the exit block.
1075 Instruction *EndI = ExitB->getFirstNonPHI();
1076 BasicBlock::iterator End = EndI ? EndI->getIterator() : ExitB->end();
1077 for (auto I = ExitB->begin(); I != End; ++I) {
1078 PHINode *P = dyn_cast<PHINode>(I);
1079 if (!P)
1080 break;
1081 Type *Ty0 = P->getIncomingValue(0)->getType();
1082 Type *PTy = P->getType();
1083 if (PTy != Ty0) {
1084 assert(Ty0 == DestTy);
1085 // In order to create the trunc, P must have the promoted type.
1086 P->mutateType(Ty0);
1087 Value *T = IRBuilder<>(ExitB, End).CreateTrunc(P, PTy);
1088 // In order for the RAUW to work, the types of P and T must match.
1089 P->mutateType(PTy);
1090 P->replaceAllUsesWith(T);
1091 // Final update of the P's type.
1092 P->mutateType(Ty0);
1093 cast<Instruction>(T)->setOperand(0, P);
1094 }
1095 }
1096
1097 return true;
1098}
1099
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001100bool PolynomialMultiplyRecognize::findCycle(Value *Out, Value *In,
1101 ValueSeq &Cycle) {
1102 // Out = ..., In, ...
1103 if (Out == In)
1104 return true;
1105
1106 auto *BB = cast<Instruction>(Out)->getParent();
1107 bool HadPhi = false;
1108
1109 for (auto U : Out->users()) {
1110 auto *I = dyn_cast<Instruction>(&*U);
1111 if (I == nullptr || I->getParent() != BB)
1112 continue;
1113 // Make sure that there are no multi-iteration cycles, e.g.
1114 // p1 = phi(p2)
1115 // p2 = phi(p1)
1116 // The cycle p1->p2->p1 would span two loop iterations.
1117 // Check that there is only one phi in the cycle.
1118 bool IsPhi = isa<PHINode>(I);
1119 if (IsPhi && HadPhi)
1120 return false;
1121 HadPhi |= IsPhi;
1122 if (Cycle.count(I))
1123 return false;
1124 Cycle.insert(I);
1125 if (findCycle(I, In, Cycle))
1126 break;
1127 Cycle.remove(I);
1128 }
1129 return !Cycle.empty();
1130}
1131
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001132void PolynomialMultiplyRecognize::classifyCycle(Instruction *DivI,
1133 ValueSeq &Cycle, ValueSeq &Early, ValueSeq &Late) {
1134 // All the values in the cycle that are between the phi node and the
1135 // divider instruction will be classified as "early", all other values
1136 // will be "late".
1137
1138 bool IsE = true;
1139 unsigned I, N = Cycle.size();
1140 for (I = 0; I < N; ++I) {
1141 Value *V = Cycle[I];
1142 if (DivI == V)
1143 IsE = false;
1144 else if (!isa<PHINode>(V))
1145 continue;
1146 // Stop if found either.
1147 break;
1148 }
1149 // "I" is the index of either DivI or the phi node, whichever was first.
1150 // "E" is "false" or "true" respectively.
1151 ValueSeq &First = !IsE ? Early : Late;
1152 for (unsigned J = 0; J < I; ++J)
1153 First.insert(Cycle[J]);
1154
1155 ValueSeq &Second = IsE ? Early : Late;
1156 Second.insert(Cycle[I]);
1157 for (++I; I < N; ++I) {
1158 Value *V = Cycle[I];
1159 if (DivI == V || isa<PHINode>(V))
1160 break;
1161 Second.insert(V);
1162 }
1163
1164 for (; I < N; ++I)
1165 First.insert(Cycle[I]);
1166}
1167
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001168bool PolynomialMultiplyRecognize::classifyInst(Instruction *UseI,
1169 ValueSeq &Early, ValueSeq &Late) {
1170 // Select is an exception, since the condition value does not have to be
1171 // classified in the same way as the true/false values. The true/false
1172 // values do have to be both early or both late.
1173 if (UseI->getOpcode() == Instruction::Select) {
1174 Value *TV = UseI->getOperand(1), *FV = UseI->getOperand(2);
1175 if (Early.count(TV) || Early.count(FV)) {
1176 if (Late.count(TV) || Late.count(FV))
1177 return false;
1178 Early.insert(UseI);
1179 } else if (Late.count(TV) || Late.count(FV)) {
1180 if (Early.count(TV) || Early.count(FV))
1181 return false;
1182 Late.insert(UseI);
1183 }
1184 return true;
1185 }
1186
1187 // Not sure what would be the example of this, but the code below relies
1188 // on having at least one operand.
1189 if (UseI->getNumOperands() == 0)
1190 return true;
1191
1192 bool AE = true, AL = true;
1193 for (auto &I : UseI->operands()) {
1194 if (Early.count(&*I))
1195 AL = false;
1196 else if (Late.count(&*I))
1197 AE = false;
1198 }
1199 // If the operands appear "all early" and "all late" at the same time,
1200 // then it means that none of them are actually classified as either.
1201 // This is harmless.
1202 if (AE && AL)
1203 return true;
1204 // Conversely, if they are neither "all early" nor "all late", then
1205 // we have a mixture of early and late operands that is not a known
1206 // exception.
1207 if (!AE && !AL)
1208 return false;
1209
1210 // Check that we have covered the two special cases.
1211 assert(AE != AL);
1212
1213 if (AE)
1214 Early.insert(UseI);
1215 else
1216 Late.insert(UseI);
1217 return true;
1218}
1219
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001220bool PolynomialMultiplyRecognize::commutesWithShift(Instruction *I) {
1221 switch (I->getOpcode()) {
1222 case Instruction::And:
1223 case Instruction::Or:
1224 case Instruction::Xor:
1225 case Instruction::LShr:
1226 case Instruction::Shl:
1227 case Instruction::Select:
1228 case Instruction::ICmp:
1229 case Instruction::PHI:
1230 break;
1231 default:
1232 return false;
1233 }
1234 return true;
1235}
1236
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001237bool PolynomialMultiplyRecognize::highBitsAreZero(Value *V,
1238 unsigned IterCount) {
1239 auto *T = dyn_cast<IntegerType>(V->getType());
1240 if (!T)
1241 return false;
1242
Craig Topperb45eabc2017-04-26 16:39:58 +00001243 KnownBits Known(T->getBitWidth());
1244 computeKnownBits(V, Known, DL);
Craig Topper8df66c62017-05-12 17:20:30 +00001245 return Known.countMinLeadingZeros() >= IterCount;
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001246}
1247
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001248bool PolynomialMultiplyRecognize::keepsHighBitsZero(Value *V,
1249 unsigned IterCount) {
1250 // Assume that all inputs to the value have the high bits zero.
1251 // Check if the value itself preserves the zeros in the high bits.
1252 if (auto *C = dyn_cast<ConstantInt>(V))
1253 return C->getValue().countLeadingZeros() >= IterCount;
1254
1255 if (auto *I = dyn_cast<Instruction>(V)) {
1256 switch (I->getOpcode()) {
1257 case Instruction::And:
1258 case Instruction::Or:
1259 case Instruction::Xor:
1260 case Instruction::LShr:
1261 case Instruction::Select:
1262 case Instruction::ICmp:
1263 case Instruction::PHI:
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001264 case Instruction::ZExt:
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001265 return true;
1266 }
1267 }
1268
1269 return false;
1270}
1271
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001272bool PolynomialMultiplyRecognize::isOperandShifted(Instruction *I, Value *Op) {
1273 unsigned Opc = I->getOpcode();
1274 if (Opc == Instruction::Shl || Opc == Instruction::LShr)
1275 return Op != I->getOperand(1);
1276 return true;
1277}
1278
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001279bool PolynomialMultiplyRecognize::convertShiftsToLeft(BasicBlock *LoopB,
1280 BasicBlock *ExitB, unsigned IterCount) {
1281 Value *CIV = getCountIV(LoopB);
1282 if (CIV == nullptr)
1283 return false;
1284 auto *CIVTy = dyn_cast<IntegerType>(CIV->getType());
1285 if (CIVTy == nullptr)
1286 return false;
1287
1288 ValueSeq RShifts;
1289 ValueSeq Early, Late, Cycled;
1290
1291 // Find all value cycles that contain logical right shifts by 1.
1292 for (Instruction &I : *LoopB) {
1293 using namespace PatternMatch;
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001294
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001295 Value *V = nullptr;
1296 if (!match(&I, m_LShr(m_Value(V), m_One())))
1297 continue;
1298 ValueSeq C;
1299 if (!findCycle(&I, V, C))
1300 continue;
1301
1302 // Found a cycle.
1303 C.insert(&I);
1304 classifyCycle(&I, C, Early, Late);
1305 Cycled.insert(C.begin(), C.end());
1306 RShifts.insert(&I);
1307 }
1308
1309 // Find the set of all values affected by the shift cycles, i.e. all
1310 // cycled values, and (recursively) all their users.
1311 ValueSeq Users(Cycled.begin(), Cycled.end());
1312 for (unsigned i = 0; i < Users.size(); ++i) {
1313 Value *V = Users[i];
1314 if (!isa<IntegerType>(V->getType()))
1315 return false;
1316 auto *R = cast<Instruction>(V);
1317 // If the instruction does not commute with shifts, the loop cannot
1318 // be unshifted.
1319 if (!commutesWithShift(R))
1320 return false;
1321 for (auto I = R->user_begin(), E = R->user_end(); I != E; ++I) {
1322 auto *T = cast<Instruction>(*I);
1323 // Skip users from outside of the loop. They will be handled later.
1324 // Also, skip the right-shifts and phi nodes, since they mix early
1325 // and late values.
1326 if (T->getParent() != LoopB || RShifts.count(T) || isa<PHINode>(T))
1327 continue;
1328
1329 Users.insert(T);
1330 if (!classifyInst(T, Early, Late))
1331 return false;
1332 }
1333 }
1334
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001335 if (Users.empty())
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001336 return false;
1337
1338 // Verify that high bits remain zero.
1339 ValueSeq Internal(Users.begin(), Users.end());
1340 ValueSeq Inputs;
1341 for (unsigned i = 0; i < Internal.size(); ++i) {
1342 auto *R = dyn_cast<Instruction>(Internal[i]);
1343 if (!R)
1344 continue;
1345 for (Value *Op : R->operands()) {
1346 auto *T = dyn_cast<Instruction>(Op);
1347 if (T && T->getParent() != LoopB)
1348 Inputs.insert(Op);
1349 else
1350 Internal.insert(Op);
1351 }
1352 }
1353 for (Value *V : Inputs)
1354 if (!highBitsAreZero(V, IterCount))
1355 return false;
1356 for (Value *V : Internal)
1357 if (!keepsHighBitsZero(V, IterCount))
1358 return false;
1359
1360 // Finally, the work can be done. Unshift each user.
1361 IRBuilder<> IRB(LoopB);
1362 std::map<Value*,Value*> ShiftMap;
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001363
1364 using CastMapType = std::map<std::pair<Value *, Type *>, Value *>;
1365
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001366 CastMapType CastMap;
1367
1368 auto upcast = [] (CastMapType &CM, IRBuilder<> &IRB, Value *V,
1369 IntegerType *Ty) -> Value* {
1370 auto H = CM.find(std::make_pair(V, Ty));
1371 if (H != CM.end())
1372 return H->second;
1373 Value *CV = IRB.CreateIntCast(V, Ty, false);
1374 CM.insert(std::make_pair(std::make_pair(V, Ty), CV));
1375 return CV;
1376 };
1377
1378 for (auto I = LoopB->begin(), E = LoopB->end(); I != E; ++I) {
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001379 using namespace PatternMatch;
1380
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001381 if (isa<PHINode>(I) || !Users.count(&*I))
1382 continue;
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001383
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001384 // Match lshr x, 1.
1385 Value *V = nullptr;
1386 if (match(&*I, m_LShr(m_Value(V), m_One()))) {
1387 replaceAllUsesOfWithIn(&*I, V, LoopB);
1388 continue;
1389 }
1390 // For each non-cycled operand, replace it with the corresponding
1391 // value shifted left.
1392 for (auto &J : I->operands()) {
1393 Value *Op = J.get();
1394 if (!isOperandShifted(&*I, Op))
1395 continue;
1396 if (Users.count(Op))
1397 continue;
1398 // Skip shifting zeros.
1399 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
1400 continue;
1401 // Check if we have already generated a shift for this value.
1402 auto F = ShiftMap.find(Op);
1403 Value *W = (F != ShiftMap.end()) ? F->second : nullptr;
1404 if (W == nullptr) {
1405 IRB.SetInsertPoint(&*I);
1406 // First, the shift amount will be CIV or CIV+1, depending on
1407 // whether the value is early or late. Instead of creating CIV+1,
1408 // do a single shift of the value.
1409 Value *ShAmt = CIV, *ShVal = Op;
1410 auto *VTy = cast<IntegerType>(ShVal->getType());
1411 auto *ATy = cast<IntegerType>(ShAmt->getType());
1412 if (Late.count(&*I))
1413 ShVal = IRB.CreateShl(Op, ConstantInt::get(VTy, 1));
1414 // Second, the types of the shifted value and the shift amount
1415 // must match.
1416 if (VTy != ATy) {
1417 if (VTy->getBitWidth() < ATy->getBitWidth())
1418 ShVal = upcast(CastMap, IRB, ShVal, ATy);
1419 else
1420 ShAmt = upcast(CastMap, IRB, ShAmt, VTy);
1421 }
1422 // Ready to generate the shift and memoize it.
1423 W = IRB.CreateShl(ShVal, ShAmt);
1424 ShiftMap.insert(std::make_pair(Op, W));
1425 }
1426 I->replaceUsesOfWith(Op, W);
1427 }
1428 }
1429
1430 // Update the users outside of the loop to account for having left
1431 // shifts. They would normally be shifted right in the loop, so shift
1432 // them right after the loop exit.
1433 // Take advantage of the loop-closed SSA form, which has all the post-
1434 // loop values in phi nodes.
1435 IRB.SetInsertPoint(ExitB, ExitB->getFirstInsertionPt());
1436 for (auto P = ExitB->begin(), Q = ExitB->end(); P != Q; ++P) {
1437 if (!isa<PHINode>(P))
1438 break;
1439 auto *PN = cast<PHINode>(P);
1440 Value *U = PN->getIncomingValueForBlock(LoopB);
1441 if (!Users.count(U))
1442 continue;
1443 Value *S = IRB.CreateLShr(PN, ConstantInt::get(PN->getType(), IterCount));
1444 PN->replaceAllUsesWith(S);
1445 // The above RAUW will create
1446 // S = lshr S, IterCount
1447 // so we need to fix it back into
1448 // S = lshr PN, IterCount
1449 cast<User>(S)->replaceUsesOfWith(S, PN);
1450 }
1451
1452 return true;
1453}
1454
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001455void PolynomialMultiplyRecognize::cleanupLoopBody(BasicBlock *LoopB) {
1456 for (auto &I : *LoopB)
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001457 if (Value *SV = SimplifyInstruction(&I, {DL, &TLI, &DT}))
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001458 I.replaceAllUsesWith(SV);
1459
1460 for (auto I = LoopB->begin(), N = I; I != LoopB->end(); I = N) {
1461 N = std::next(I);
1462 RecursivelyDeleteTriviallyDeadInstructions(&*I, &TLI);
1463 }
1464}
1465
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001466unsigned PolynomialMultiplyRecognize::getInverseMxN(unsigned QP) {
1467 // Arrays of coefficients of Q and the inverse, C.
1468 // Q[i] = coefficient at x^i.
1469 std::array<char,32> Q, C;
1470
1471 for (unsigned i = 0; i < 32; ++i) {
1472 Q[i] = QP & 1;
1473 QP >>= 1;
1474 }
1475 assert(Q[0] == 1);
1476
1477 // Find C, such that
1478 // (Q[n]*x^n + ... + Q[1]*x + Q[0]) * (C[n]*x^n + ... + C[1]*x + C[0]) = 1
1479 //
1480 // For it to have a solution, Q[0] must be 1. Since this is Z2[x], the
1481 // operations * and + are & and ^ respectively.
1482 //
1483 // Find C[i] recursively, by comparing i-th coefficient in the product
1484 // with 0 (or 1 for i=0).
1485 //
1486 // C[0] = 1, since C[0] = Q[0], and Q[0] = 1.
1487 C[0] = 1;
1488 for (unsigned i = 1; i < 32; ++i) {
1489 // Solve for C[i] in:
1490 // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i]Q[0] = 0
1491 // This is equivalent to
1492 // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i] = 0
1493 // which is
1494 // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] = C[i]
1495 unsigned T = 0;
1496 for (unsigned j = 0; j < i; ++j)
1497 T = T ^ (C[j] & Q[i-j]);
1498 C[i] = T;
1499 }
1500
1501 unsigned QV = 0;
1502 for (unsigned i = 0; i < 32; ++i)
1503 if (C[i])
1504 QV |= (1 << i);
1505
1506 return QV;
1507}
1508
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001509Value *PolynomialMultiplyRecognize::generate(BasicBlock::iterator At,
1510 ParsedValues &PV) {
1511 IRBuilder<> B(&*At);
1512 Module *M = At->getParent()->getParent()->getParent();
1513 Value *PMF = Intrinsic::getDeclaration(M, Intrinsic::hexagon_M4_pmpyw);
1514
1515 Value *P = PV.P, *Q = PV.Q, *P0 = P;
1516 unsigned IC = PV.IterCount;
1517
1518 if (PV.M != nullptr)
1519 P0 = P = B.CreateXor(P, PV.M);
1520
1521 // Create a bit mask to clear the high bits beyond IterCount.
1522 auto *BMI = ConstantInt::get(P->getType(), APInt::getLowBitsSet(32, IC));
1523
1524 if (PV.IterCount != 32)
1525 P = B.CreateAnd(P, BMI);
1526
1527 if (PV.Inv) {
1528 auto *QI = dyn_cast<ConstantInt>(PV.Q);
1529 assert(QI && QI->getBitWidth() <= 32);
1530
1531 // Again, clearing bits beyond IterCount.
1532 unsigned M = (1 << PV.IterCount) - 1;
1533 unsigned Tmp = (QI->getZExtValue() | 1) & M;
1534 unsigned QV = getInverseMxN(Tmp) & M;
1535 auto *QVI = ConstantInt::get(QI->getType(), QV);
1536 P = B.CreateCall(PMF, {P, QVI});
1537 P = B.CreateTrunc(P, QI->getType());
1538 if (IC != 32)
1539 P = B.CreateAnd(P, BMI);
1540 }
1541
1542 Value *R = B.CreateCall(PMF, {P, Q});
1543
1544 if (PV.M != nullptr)
1545 R = B.CreateXor(R, B.CreateIntCast(P0, R->getType(), false));
1546
1547 return R;
1548}
1549
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001550static bool hasZeroSignBit(const Value *V) {
1551 if (const auto *CI = dyn_cast<const ConstantInt>(V))
1552 return (CI->getType()->getSignBit() & CI->getSExtValue()) == 0;
1553 const Instruction *I = dyn_cast<const Instruction>(V);
1554 if (!I)
1555 return false;
1556 switch (I->getOpcode()) {
1557 case Instruction::LShr:
1558 if (const auto SI = dyn_cast<const ConstantInt>(I->getOperand(1)))
1559 return SI->getZExtValue() > 0;
1560 return false;
1561 case Instruction::Or:
1562 case Instruction::Xor:
1563 return hasZeroSignBit(I->getOperand(0)) &&
1564 hasZeroSignBit(I->getOperand(1));
1565 case Instruction::And:
1566 return hasZeroSignBit(I->getOperand(0)) ||
1567 hasZeroSignBit(I->getOperand(1));
1568 }
1569 return false;
1570}
1571
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001572void PolynomialMultiplyRecognize::setupSimplifier() {
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001573 Simp.addRule("sink-zext",
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001574 // Sink zext past bitwise operations.
1575 [](Instruction *I, LLVMContext &Ctx) -> Value* {
1576 if (I->getOpcode() != Instruction::ZExt)
1577 return nullptr;
1578 Instruction *T = dyn_cast<Instruction>(I->getOperand(0));
1579 if (!T)
1580 return nullptr;
1581 switch (T->getOpcode()) {
1582 case Instruction::And:
1583 case Instruction::Or:
1584 case Instruction::Xor:
1585 break;
1586 default:
1587 return nullptr;
1588 }
1589 IRBuilder<> B(Ctx);
1590 return B.CreateBinOp(cast<BinaryOperator>(T)->getOpcode(),
1591 B.CreateZExt(T->getOperand(0), I->getType()),
1592 B.CreateZExt(T->getOperand(1), I->getType()));
1593 });
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001594 Simp.addRule("xor/and -> and/xor",
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001595 // (xor (and x a) (and y a)) -> (and (xor x y) a)
1596 [](Instruction *I, LLVMContext &Ctx) -> Value* {
1597 if (I->getOpcode() != Instruction::Xor)
1598 return nullptr;
1599 Instruction *And0 = dyn_cast<Instruction>(I->getOperand(0));
1600 Instruction *And1 = dyn_cast<Instruction>(I->getOperand(1));
1601 if (!And0 || !And1)
1602 return nullptr;
1603 if (And0->getOpcode() != Instruction::And ||
1604 And1->getOpcode() != Instruction::And)
1605 return nullptr;
1606 if (And0->getOperand(1) != And1->getOperand(1))
1607 return nullptr;
1608 IRBuilder<> B(Ctx);
1609 return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1->getOperand(0)),
1610 And0->getOperand(1));
1611 });
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001612 Simp.addRule("sink binop into select",
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001613 // (Op (select c x y) z) -> (select c (Op x z) (Op y z))
1614 // (Op x (select c y z)) -> (select c (Op x y) (Op x z))
1615 [](Instruction *I, LLVMContext &Ctx) -> Value* {
1616 BinaryOperator *BO = dyn_cast<BinaryOperator>(I);
1617 if (!BO)
1618 return nullptr;
1619 Instruction::BinaryOps Op = BO->getOpcode();
1620 if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(0))) {
1621 IRBuilder<> B(Ctx);
1622 Value *X = Sel->getTrueValue(), *Y = Sel->getFalseValue();
1623 Value *Z = BO->getOperand(1);
1624 return B.CreateSelect(Sel->getCondition(),
1625 B.CreateBinOp(Op, X, Z),
1626 B.CreateBinOp(Op, Y, Z));
1627 }
1628 if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(1))) {
1629 IRBuilder<> B(Ctx);
1630 Value *X = BO->getOperand(0);
1631 Value *Y = Sel->getTrueValue(), *Z = Sel->getFalseValue();
1632 return B.CreateSelect(Sel->getCondition(),
1633 B.CreateBinOp(Op, X, Y),
1634 B.CreateBinOp(Op, X, Z));
1635 }
1636 return nullptr;
1637 });
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001638 Simp.addRule("fold select-select",
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001639 // (select c (select c x y) z) -> (select c x z)
1640 // (select c x (select c y z)) -> (select c x z)
1641 [](Instruction *I, LLVMContext &Ctx) -> Value* {
1642 SelectInst *Sel = dyn_cast<SelectInst>(I);
1643 if (!Sel)
1644 return nullptr;
1645 IRBuilder<> B(Ctx);
1646 Value *C = Sel->getCondition();
1647 if (SelectInst *Sel0 = dyn_cast<SelectInst>(Sel->getTrueValue())) {
1648 if (Sel0->getCondition() == C)
1649 return B.CreateSelect(C, Sel0->getTrueValue(), Sel->getFalseValue());
1650 }
1651 if (SelectInst *Sel1 = dyn_cast<SelectInst>(Sel->getFalseValue())) {
1652 if (Sel1->getCondition() == C)
1653 return B.CreateSelect(C, Sel->getTrueValue(), Sel1->getFalseValue());
1654 }
1655 return nullptr;
1656 });
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001657 Simp.addRule("or-signbit -> xor-signbit",
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001658 // (or (lshr x 1) 0x800.0) -> (xor (lshr x 1) 0x800.0)
1659 [](Instruction *I, LLVMContext &Ctx) -> Value* {
1660 if (I->getOpcode() != Instruction::Or)
1661 return nullptr;
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001662 ConstantInt *Msb = dyn_cast<ConstantInt>(I->getOperand(1));
1663 if (!Msb || Msb->getZExtValue() != Msb->getType()->getSignBit())
1664 return nullptr;
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001665 if (!hasZeroSignBit(I->getOperand(0)))
1666 return nullptr;
1667 return IRBuilder<>(Ctx).CreateXor(I->getOperand(0), Msb);
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001668 });
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001669 Simp.addRule("sink lshr into binop",
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001670 // (lshr (BitOp x y) c) -> (BitOp (lshr x c) (lshr y c))
1671 [](Instruction *I, LLVMContext &Ctx) -> Value* {
1672 if (I->getOpcode() != Instruction::LShr)
1673 return nullptr;
1674 BinaryOperator *BitOp = dyn_cast<BinaryOperator>(I->getOperand(0));
1675 if (!BitOp)
1676 return nullptr;
1677 switch (BitOp->getOpcode()) {
1678 case Instruction::And:
1679 case Instruction::Or:
1680 case Instruction::Xor:
1681 break;
1682 default:
1683 return nullptr;
1684 }
1685 IRBuilder<> B(Ctx);
1686 Value *S = I->getOperand(1);
1687 return B.CreateBinOp(BitOp->getOpcode(),
1688 B.CreateLShr(BitOp->getOperand(0), S),
1689 B.CreateLShr(BitOp->getOperand(1), S));
1690 });
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001691 Simp.addRule("expose bitop-const",
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001692 // (BitOp1 (BitOp2 x a) b) -> (BitOp2 x (BitOp1 a b))
1693 [](Instruction *I, LLVMContext &Ctx) -> Value* {
1694 auto IsBitOp = [](unsigned Op) -> bool {
1695 switch (Op) {
1696 case Instruction::And:
1697 case Instruction::Or:
1698 case Instruction::Xor:
1699 return true;
1700 }
1701 return false;
1702 };
1703 BinaryOperator *BitOp1 = dyn_cast<BinaryOperator>(I);
1704 if (!BitOp1 || !IsBitOp(BitOp1->getOpcode()))
1705 return nullptr;
1706 BinaryOperator *BitOp2 = dyn_cast<BinaryOperator>(BitOp1->getOperand(0));
1707 if (!BitOp2 || !IsBitOp(BitOp2->getOpcode()))
1708 return nullptr;
1709 ConstantInt *CA = dyn_cast<ConstantInt>(BitOp2->getOperand(1));
1710 ConstantInt *CB = dyn_cast<ConstantInt>(BitOp1->getOperand(1));
1711 if (!CA || !CB)
1712 return nullptr;
1713 IRBuilder<> B(Ctx);
1714 Value *X = BitOp2->getOperand(0);
1715 return B.CreateBinOp(BitOp2->getOpcode(), X,
1716 B.CreateBinOp(BitOp1->getOpcode(), CA, CB));
1717 });
1718}
1719
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001720bool PolynomialMultiplyRecognize::recognize() {
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001721 DEBUG(dbgs() << "Starting PolynomialMultiplyRecognize on loop\n"
1722 << *CurLoop << '\n');
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001723 // Restrictions:
1724 // - The loop must consist of a single block.
1725 // - The iteration count must be known at compile-time.
1726 // - The loop must have an induction variable starting from 0, and
1727 // incremented in each iteration of the loop.
1728 BasicBlock *LoopB = CurLoop->getHeader();
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001729 DEBUG(dbgs() << "Loop header:\n" << *LoopB);
1730
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001731 if (LoopB != CurLoop->getLoopLatch())
1732 return false;
1733 BasicBlock *ExitB = CurLoop->getExitBlock();
1734 if (ExitB == nullptr)
1735 return false;
1736 BasicBlock *EntryB = CurLoop->getLoopPreheader();
1737 if (EntryB == nullptr)
1738 return false;
1739
1740 unsigned IterCount = 0;
1741 const SCEV *CT = SE.getBackedgeTakenCount(CurLoop);
1742 if (isa<SCEVCouldNotCompute>(CT))
1743 return false;
1744 if (auto *CV = dyn_cast<SCEVConstant>(CT))
1745 IterCount = CV->getValue()->getZExtValue() + 1;
1746
1747 Value *CIV = getCountIV(LoopB);
1748 ParsedValues PV;
1749 PV.IterCount = IterCount;
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001750 DEBUG(dbgs() << "Loop IV: " << *CIV << "\nIterCount: " << IterCount << '\n');
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001751
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001752 setupSimplifier();
1753
1754 // Perform a preliminary scan of select instructions to see if any of them
1755 // looks like a generator of the polynomial multiply steps. Assume that a
1756 // loop can only contain a single transformable operation, so stop the
1757 // traversal after the first reasonable candidate was found.
1758 // XXX: Currently this approach can modify the loop before being 100% sure
1759 // that the transformation can be carried out.
1760 bool FoundPreScan = false;
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001761 auto FeedsPHI = [LoopB](const Value *V) -> bool {
1762 for (const Value *U : V->users()) {
1763 if (const auto *P = dyn_cast<const PHINode>(U))
1764 if (P->getParent() == LoopB)
1765 return true;
1766 }
1767 return false;
1768 };
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001769 for (Instruction &In : *LoopB) {
1770 SelectInst *SI = dyn_cast<SelectInst>(&In);
Krzysztof Parzyszek385a4e042017-11-07 17:05:54 +00001771 if (!SI || !FeedsPHI(SI))
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001772 continue;
1773
1774 Simplifier::Context C(SI);
1775 Value *T = Simp.simplify(C);
1776 SelectInst *SelI = (T && isa<SelectInst>(T)) ? cast<SelectInst>(T) : SI;
1777 DEBUG(dbgs() << "scanSelect(pre-scan): " << PE(C, SelI) << '\n');
1778 if (scanSelect(SelI, LoopB, EntryB, CIV, PV, true)) {
1779 FoundPreScan = true;
1780 if (SelI != SI) {
1781 Value *NewSel = C.materialize(LoopB, SI->getIterator());
1782 SI->replaceAllUsesWith(NewSel);
1783 RecursivelyDeleteTriviallyDeadInstructions(SI, &TLI);
1784 }
1785 break;
1786 }
1787 }
1788
1789 if (!FoundPreScan) {
1790 DEBUG(dbgs() << "Have not found candidates for pmpy\n");
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001791 return false;
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001792 }
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001793
1794 if (!PV.Left) {
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001795 // The right shift version actually only returns the higher bits of
1796 // the result (each iteration discards the LSB). If we want to convert it
1797 // to a left-shifting loop, the working data type must be at least as
1798 // wide as the target's pmpy instruction.
1799 if (!promoteTypes(LoopB, ExitB))
1800 return false;
Krzysztof Parzyszek9bd4d912017-06-13 13:51:49 +00001801 if (!convertShiftsToLeft(LoopB, ExitB, IterCount))
1802 return false;
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001803 cleanupLoopBody(LoopB);
1804 }
1805
Krzysztof Parzyszekd033d1f2017-03-21 17:09:27 +00001806 // Scan the loop again, find the generating select instruction.
1807 bool FoundScan = false;
1808 for (Instruction &In : *LoopB) {
1809 SelectInst *SelI = dyn_cast<SelectInst>(&In);
1810 if (!SelI)
1811 continue;
1812 DEBUG(dbgs() << "scanSelect: " << *SelI << '\n');
1813 FoundScan = scanSelect(SelI, LoopB, EntryB, CIV, PV, false);
1814 if (FoundScan)
1815 break;
1816 }
1817 assert(FoundScan);
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001818
1819 DEBUG({
1820 StringRef PP = (PV.M ? "(P+M)" : "P");
1821 if (!PV.Inv)
1822 dbgs() << "Found pmpy idiom: R = " << PP << ".Q\n";
1823 else
1824 dbgs() << "Found inverse pmpy idiom: R = (" << PP << "/Q).Q) + "
1825 << PP << "\n";
1826 dbgs() << " Res:" << *PV.Res << "\n P:" << *PV.P << "\n";
1827 if (PV.M)
1828 dbgs() << " M:" << *PV.M << "\n";
1829 dbgs() << " Q:" << *PV.Q << "\n";
1830 dbgs() << " Iteration count:" << PV.IterCount << "\n";
1831 });
1832
1833 BasicBlock::iterator At(EntryB->getTerminator());
1834 Value *PM = generate(At, PV);
1835 if (PM == nullptr)
1836 return false;
1837
1838 if (PM->getType() != PV.Res->getType())
1839 PM = IRBuilder<>(&*At).CreateIntCast(PM, PV.Res->getType(), false);
1840
1841 PV.Res->replaceAllUsesWith(PM);
1842 PV.Res->eraseFromParent();
1843 return true;
1844}
1845
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001846int HexagonLoopIdiomRecognize::getSCEVStride(const SCEVAddRecExpr *S) {
1847 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1848 return SC->getAPInt().getSExtValue();
1849 return 0;
1850}
1851
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001852bool HexagonLoopIdiomRecognize::isLegalStore(Loop *CurLoop, StoreInst *SI) {
Krzysztof Parzyszek35ce5da2017-01-27 20:40:14 +00001853 // Allow volatile stores if HexagonVolatileMemcpy is enabled.
1854 if (!(SI->isVolatile() && HexagonVolatileMemcpy) && !SI->isSimple())
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001855 return false;
1856
1857 Value *StoredVal = SI->getValueOperand();
1858 Value *StorePtr = SI->getPointerOperand();
1859
1860 // Reject stores that are so large that they overflow an unsigned.
1861 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
1862 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
1863 return false;
1864
1865 // See if the pointer expression is an AddRec like {base,+,1} on the current
1866 // loop, which indicates a strided store. If we have something else, it's a
1867 // random store we can't handle.
1868 auto *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1869 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
1870 return false;
1871
1872 // Check to see if the stride matches the size of the store. If so, then we
1873 // know that every byte is touched in the loop.
1874 int Stride = getSCEVStride(StoreEv);
1875 if (Stride == 0)
1876 return false;
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +00001877 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001878 if (StoreSize != unsigned(std::abs(Stride)))
1879 return false;
1880
1881 // The store must be feeding a non-volatile load.
1882 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
1883 if (!LI || !LI->isSimple())
1884 return false;
1885
1886 // See if the pointer expression is an AddRec like {base,+,1} on the current
1887 // loop, which indicates a strided load. If we have something else, it's a
1888 // random load we can't handle.
1889 Value *LoadPtr = LI->getPointerOperand();
1890 auto *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1891 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
1892 return false;
1893
1894 // The store and load must share the same stride.
1895 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
1896 return false;
1897
1898 // Success. This store can be converted into a memcpy.
1899 return true;
1900}
1901
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001902/// mayLoopAccessLocation - Return true if the specified loop might access the
1903/// specified pointer location, which is a loop-strided access. The 'Access'
1904/// argument specifies what the verboten forms of access are (read or write).
1905static bool
1906mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
1907 const SCEV *BECount, unsigned StoreSize,
1908 AliasAnalysis &AA,
1909 SmallPtrSetImpl<Instruction *> &Ignored) {
1910 // Get the location that may be stored across the loop. Since the access
1911 // is strided positively through memory, we say that the modified location
1912 // starts at the pointer and has infinite size.
1913 uint64_t AccessSize = MemoryLocation::UnknownSize;
1914
1915 // If the loop iterates a fixed number of times, we can refine the access
1916 // size to be exactly the size of the memset, which is (BECount+1)*StoreSize
1917 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
1918 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
1919
1920 // TODO: For this to be really effective, we have to dive into the pointer
1921 // operand in the store. Store to &A[i] of 100 will always return may alias
1922 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
1923 // which will then no-alias a store to &A[100].
1924 MemoryLocation StoreLoc(Ptr, AccessSize);
1925
1926 for (auto *B : L->blocks())
1927 for (auto &I : *B)
Alina Sbirlea63d22502017-12-05 20:12:23 +00001928 if (Ignored.count(&I) == 0 &&
Alina Sbirlea18fea012017-12-06 19:56:37 +00001929 isModOrRefSet(
1930 intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access)))
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001931 return true;
1932
1933 return false;
1934}
1935
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001936void HexagonLoopIdiomRecognize::collectStores(Loop *CurLoop, BasicBlock *BB,
1937 SmallVectorImpl<StoreInst*> &Stores) {
1938 Stores.clear();
1939 for (Instruction &I : *BB)
1940 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
1941 if (isLegalStore(CurLoop, SI))
1942 Stores.push_back(SI);
1943}
1944
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001945bool HexagonLoopIdiomRecognize::processCopyingStore(Loop *CurLoop,
1946 StoreInst *SI, const SCEV *BECount) {
Michael Kupersteine18aad32017-01-31 22:48:45 +00001947 assert((SI->isSimple() || (SI->isVolatile() && HexagonVolatileMemcpy)) &&
1948 "Expected only non-volatile stores, or Hexagon-specific memcpy"
1949 "to volatile destination.");
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001950
1951 Value *StorePtr = SI->getPointerOperand();
1952 auto *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1953 unsigned Stride = getSCEVStride(StoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +00001954 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00001955 if (Stride != StoreSize)
1956 return false;
1957
1958 // See if the pointer expression is an AddRec like {base,+,1} on the current
1959 // loop, which indicates a strided load. If we have something else, it's a
1960 // random load we can't handle.
1961 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
1962 auto *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
1963
1964 // The trip count of the loop and the base pointer of the addrec SCEV is
1965 // guaranteed to be loop invariant, which means that it should dominate the
1966 // header. This allows us to insert code for it in the preheader.
1967 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1968 Instruction *ExpPt = Preheader->getTerminator();
1969 IRBuilder<> Builder(ExpPt);
1970 SCEVExpander Expander(*SE, *DL, "hexagon-loop-idiom");
1971
1972 Type *IntPtrTy = Builder.getIntPtrTy(*DL, SI->getPointerAddressSpace());
1973
1974 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
1975 // this into a memcpy/memmove in the loop preheader now if we want. However,
1976 // this would be unsafe to do if there is anything else in the loop that may
1977 // read or write the memory region we're storing to. For memcpy, this
1978 // includes the load that feeds the stores. Check for an alias by generating
1979 // the base address and checking everything.
1980 Value *StoreBasePtr = Expander.expandCodeFor(StoreEv->getStart(),
1981 Builder.getInt8PtrTy(SI->getPointerAddressSpace()), ExpPt);
1982 Value *LoadBasePtr = nullptr;
1983
1984 bool Overlap = false;
1985 bool DestVolatile = SI->isVolatile();
1986 Type *BECountTy = BECount->getType();
1987
1988 if (DestVolatile) {
1989 // The trip count must fit in i32, since it is the type of the "num_words"
1990 // argument to hexagon_memcpy_forward_vp4cp4n2.
1991 if (StoreSize != 4 || DL->getTypeSizeInBits(BECountTy) > 32) {
1992CleanupAndExit:
1993 // If we generated new code for the base pointer, clean up.
1994 Expander.clear();
1995 if (StoreBasePtr && (LoadBasePtr != StoreBasePtr)) {
1996 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
1997 StoreBasePtr = nullptr;
1998 }
1999 if (LoadBasePtr) {
2000 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
2001 LoadBasePtr = nullptr;
2002 }
2003 return false;
2004 }
2005 }
2006
2007 SmallPtrSet<Instruction*, 2> Ignore1;
2008 Ignore1.insert(SI);
Alina Sbirlea193429f2017-12-07 22:41:34 +00002009 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002010 StoreSize, *AA, Ignore1)) {
2011 // Check if the load is the offending instruction.
2012 Ignore1.insert(LI);
Alina Sbirlea193429f2017-12-07 22:41:34 +00002013 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
2014 BECount, StoreSize, *AA, Ignore1)) {
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002015 // Still bad. Nothing we can do.
2016 goto CleanupAndExit;
2017 }
2018 // It worked with the load ignored.
2019 Overlap = true;
2020 }
2021
2022 if (!Overlap) {
2023 if (DisableMemcpyIdiom || !HasMemcpy)
2024 goto CleanupAndExit;
2025 } else {
2026 // Don't generate memmove if this function will be inlined. This is
2027 // because the caller will undergo this transformation after inlining.
2028 Function *Func = CurLoop->getHeader()->getParent();
2029 if (Func->hasFnAttribute(Attribute::AlwaysInline))
2030 goto CleanupAndExit;
2031
2032 // In case of a memmove, the call to memmove will be executed instead
2033 // of the loop, so we need to make sure that there is nothing else in
2034 // the loop than the load, store and instructions that these two depend
2035 // on.
2036 SmallVector<Instruction*,2> Insts;
2037 Insts.push_back(SI);
2038 Insts.push_back(LI);
2039 if (!coverLoop(CurLoop, Insts))
2040 goto CleanupAndExit;
2041
2042 if (DisableMemmoveIdiom || !HasMemmove)
2043 goto CleanupAndExit;
Eugene Zelenko4d060b72017-07-29 00:56:56 +00002044 bool IsNested = CurLoop->getParentLoop() != nullptr;
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002045 if (IsNested && OnlyNonNestedMemmove)
2046 goto CleanupAndExit;
2047 }
2048
2049 // For a memcpy, we have to make sure that the input array is not being
2050 // mutated by the loop.
2051 LoadBasePtr = Expander.expandCodeFor(LoadEv->getStart(),
2052 Builder.getInt8PtrTy(LI->getPointerAddressSpace()), ExpPt);
2053
2054 SmallPtrSet<Instruction*, 2> Ignore2;
2055 Ignore2.insert(SI);
Alina Sbirlea193429f2017-12-07 22:41:34 +00002056 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
2057 StoreSize, *AA, Ignore2))
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002058 goto CleanupAndExit;
2059
2060 // Check the stride.
2061 bool StridePos = getSCEVStride(LoadEv) >= 0;
2062
2063 // Currently, the volatile memcpy only emulates traversing memory forward.
2064 if (!StridePos && DestVolatile)
2065 goto CleanupAndExit;
2066
2067 bool RuntimeCheck = (Overlap || DestVolatile);
2068
2069 BasicBlock *ExitB;
2070 if (RuntimeCheck) {
2071 // The runtime check needs a single exit block.
2072 SmallVector<BasicBlock*, 8> ExitBlocks;
2073 CurLoop->getUniqueExitBlocks(ExitBlocks);
2074 if (ExitBlocks.size() != 1)
2075 goto CleanupAndExit;
2076 ExitB = ExitBlocks[0];
2077 }
2078
2079 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
2080 // pointer size if it isn't already.
2081 LLVMContext &Ctx = SI->getContext();
2082 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
2083 unsigned Alignment = std::min(SI->getAlignment(), LI->getAlignment());
2084 DebugLoc DLoc = SI->getDebugLoc();
2085
2086 const SCEV *NumBytesS =
2087 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
2088 if (StoreSize != 1)
2089 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
2090 SCEV::FlagNUW);
2091 Value *NumBytes = Expander.expandCodeFor(NumBytesS, IntPtrTy, ExpPt);
2092 if (Instruction *In = dyn_cast<Instruction>(NumBytes))
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002093 if (Value *Simp = SimplifyInstruction(In, {*DL, TLI, DT}))
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002094 NumBytes = Simp;
2095
2096 CallInst *NewCall;
2097
2098 if (RuntimeCheck) {
2099 unsigned Threshold = RuntimeMemSizeThreshold;
2100 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) {
2101 uint64_t C = CI->getZExtValue();
2102 if (Threshold != 0 && C < Threshold)
2103 goto CleanupAndExit;
2104 if (C < CompileTimeMemSizeThreshold)
2105 goto CleanupAndExit;
2106 }
2107
2108 BasicBlock *Header = CurLoop->getHeader();
2109 Function *Func = Header->getParent();
2110 Loop *ParentL = LF->getLoopFor(Preheader);
2111 StringRef HeaderName = Header->getName();
2112
2113 // Create a new (empty) preheader, and update the PHI nodes in the
2114 // header to use the new preheader.
2115 BasicBlock *NewPreheader = BasicBlock::Create(Ctx, HeaderName+".rtli.ph",
2116 Func, Header);
2117 if (ParentL)
2118 ParentL->addBasicBlockToLoop(NewPreheader, *LF);
2119 IRBuilder<>(NewPreheader).CreateBr(Header);
2120 for (auto &In : *Header) {
2121 PHINode *PN = dyn_cast<PHINode>(&In);
2122 if (!PN)
2123 break;
2124 int bx = PN->getBasicBlockIndex(Preheader);
2125 if (bx >= 0)
2126 PN->setIncomingBlock(bx, NewPreheader);
2127 }
2128 DT->addNewBlock(NewPreheader, Preheader);
2129 DT->changeImmediateDominator(Header, NewPreheader);
2130
2131 // Check for safe conditions to execute memmove.
2132 // If stride is positive, copying things from higher to lower addresses
2133 // is equivalent to memmove. For negative stride, it's the other way
2134 // around. Copying forward in memory with positive stride may not be
2135 // same as memmove since we may be copying values that we just stored
2136 // in some previous iteration.
2137 Value *LA = Builder.CreatePtrToInt(LoadBasePtr, IntPtrTy);
2138 Value *SA = Builder.CreatePtrToInt(StoreBasePtr, IntPtrTy);
2139 Value *LowA = StridePos ? SA : LA;
2140 Value *HighA = StridePos ? LA : SA;
2141 Value *CmpA = Builder.CreateICmpULT(LowA, HighA);
2142 Value *Cond = CmpA;
2143
Krzysztof Parzyszekc09a14e2017-08-24 11:59:53 +00002144 // Check for distance between pointers. Since the case LowA < HighA
2145 // is checked for above, assume LowA >= HighA.
2146 Value *Dist = Builder.CreateSub(LowA, HighA);
2147 Value *CmpD = Builder.CreateICmpSLE(NumBytes, Dist);
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002148 Value *CmpEither = Builder.CreateOr(Cond, CmpD);
2149 Cond = CmpEither;
2150
2151 if (Threshold != 0) {
2152 Type *Ty = NumBytes->getType();
2153 Value *Thr = ConstantInt::get(Ty, Threshold);
2154 Value *CmpB = Builder.CreateICmpULT(Thr, NumBytes);
2155 Value *CmpBoth = Builder.CreateAnd(Cond, CmpB);
2156 Cond = CmpBoth;
2157 }
2158 BasicBlock *MemmoveB = BasicBlock::Create(Ctx, Header->getName()+".rtli",
2159 Func, NewPreheader);
2160 if (ParentL)
2161 ParentL->addBasicBlockToLoop(MemmoveB, *LF);
2162 Instruction *OldT = Preheader->getTerminator();
2163 Builder.CreateCondBr(Cond, MemmoveB, NewPreheader);
2164 OldT->eraseFromParent();
2165 Preheader->setName(Preheader->getName()+".old");
2166 DT->addNewBlock(MemmoveB, Preheader);
2167 // Find the new immediate dominator of the exit block.
2168 BasicBlock *ExitD = Preheader;
2169 for (auto PI = pred_begin(ExitB), PE = pred_end(ExitB); PI != PE; ++PI) {
2170 BasicBlock *PB = *PI;
2171 ExitD = DT->findNearestCommonDominator(ExitD, PB);
2172 if (!ExitD)
2173 break;
2174 }
2175 // If the prior immediate dominator of ExitB was dominated by the
2176 // old preheader, then the old preheader becomes the new immediate
2177 // dominator. Otherwise don't change anything (because the newly
2178 // added blocks are dominated by the old preheader).
2179 if (ExitD && DT->dominates(Preheader, ExitD)) {
2180 DomTreeNode *BN = DT->getNode(ExitB);
2181 DomTreeNode *DN = DT->getNode(ExitD);
2182 BN->setIDom(DN);
2183 }
2184
2185 // Add a call to memmove to the conditional block.
2186 IRBuilder<> CondBuilder(MemmoveB);
2187 CondBuilder.CreateBr(ExitB);
2188 CondBuilder.SetInsertPoint(MemmoveB->getTerminator());
2189
2190 if (DestVolatile) {
2191 Type *Int32Ty = Type::getInt32Ty(Ctx);
2192 Type *Int32PtrTy = Type::getInt32PtrTy(Ctx);
2193 Type *VoidTy = Type::getVoidTy(Ctx);
2194 Module *M = Func->getParent();
2195 Constant *CF = M->getOrInsertFunction(HexagonVolatileMemcpyName, VoidTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002196 Int32PtrTy, Int32PtrTy, Int32Ty);
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002197 Function *Fn = cast<Function>(CF);
2198 Fn->setLinkage(Function::ExternalLinkage);
2199
2200 const SCEV *OneS = SE->getConstant(Int32Ty, 1);
2201 const SCEV *BECount32 = SE->getTruncateOrZeroExtend(BECount, Int32Ty);
2202 const SCEV *NumWordsS = SE->getAddExpr(BECount32, OneS, SCEV::FlagNUW);
2203 Value *NumWords = Expander.expandCodeFor(NumWordsS, Int32Ty,
2204 MemmoveB->getTerminator());
2205 if (Instruction *In = dyn_cast<Instruction>(NumWords))
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002206 if (Value *Simp = SimplifyInstruction(In, {*DL, TLI, DT}))
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002207 NumWords = Simp;
2208
2209 Value *Op0 = (StoreBasePtr->getType() == Int32PtrTy)
2210 ? StoreBasePtr
2211 : CondBuilder.CreateBitCast(StoreBasePtr, Int32PtrTy);
2212 Value *Op1 = (LoadBasePtr->getType() == Int32PtrTy)
2213 ? LoadBasePtr
2214 : CondBuilder.CreateBitCast(LoadBasePtr, Int32PtrTy);
2215 NewCall = CondBuilder.CreateCall(Fn, {Op0, Op1, NumWords});
2216 } else {
2217 NewCall = CondBuilder.CreateMemMove(StoreBasePtr, LoadBasePtr,
2218 NumBytes, Alignment);
2219 }
2220 } else {
2221 NewCall = Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr,
2222 NumBytes, Alignment);
2223 // Okay, the memcpy has been formed. Zap the original store and
2224 // anything that feeds into it.
2225 RecursivelyDeleteTriviallyDeadInstructions(SI, TLI);
2226 }
2227
2228 NewCall->setDebugLoc(DLoc);
2229
2230 DEBUG(dbgs() << " Formed " << (Overlap ? "memmove: " : "memcpy: ")
2231 << *NewCall << "\n"
2232 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
2233 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
2234
2235 return true;
2236}
2237
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002238// \brief Check if the instructions in Insts, together with their dependencies
2239// cover the loop in the sense that the loop could be safely eliminated once
2240// the instructions in Insts are removed.
2241bool HexagonLoopIdiomRecognize::coverLoop(Loop *L,
2242 SmallVectorImpl<Instruction*> &Insts) const {
2243 SmallSet<BasicBlock*,8> LoopBlocks;
2244 for (auto *B : L->blocks())
2245 LoopBlocks.insert(B);
2246
2247 SetVector<Instruction*> Worklist(Insts.begin(), Insts.end());
2248
2249 // Collect all instructions from the loop that the instructions in Insts
2250 // depend on (plus their dependencies, etc.). These instructions will
2251 // constitute the expression trees that feed those in Insts, but the trees
2252 // will be limited only to instructions contained in the loop.
2253 for (unsigned i = 0; i < Worklist.size(); ++i) {
2254 Instruction *In = Worklist[i];
2255 for (auto I = In->op_begin(), E = In->op_end(); I != E; ++I) {
2256 Instruction *OpI = dyn_cast<Instruction>(I);
2257 if (!OpI)
2258 continue;
2259 BasicBlock *PB = OpI->getParent();
2260 if (!LoopBlocks.count(PB))
2261 continue;
2262 Worklist.insert(OpI);
2263 }
2264 }
2265
2266 // Scan all instructions in the loop, if any of them have a user outside
2267 // of the loop, or outside of the expressions collected above, then either
2268 // the loop has a side-effect visible outside of it, or there are
2269 // instructions in it that are not involved in the original set Insts.
2270 for (auto *B : L->blocks()) {
2271 for (auto &In : *B) {
2272 if (isa<BranchInst>(In) || isa<DbgInfoIntrinsic>(In))
2273 continue;
2274 if (!Worklist.count(&In) && In.mayHaveSideEffects())
2275 return false;
2276 for (const auto &K : In.users()) {
2277 Instruction *UseI = dyn_cast<Instruction>(K);
2278 if (!UseI)
2279 continue;
2280 BasicBlock *UseB = UseI->getParent();
2281 if (LF->getLoopFor(UseB) != L)
2282 return false;
2283 }
2284 }
2285 }
2286
2287 return true;
2288}
2289
2290/// runOnLoopBlock - Process the specified block, which lives in a counted loop
2291/// with the specified backedge count. This block is known to be in the current
2292/// loop and not in any subloops.
2293bool HexagonLoopIdiomRecognize::runOnLoopBlock(Loop *CurLoop, BasicBlock *BB,
2294 const SCEV *BECount, SmallVectorImpl<BasicBlock*> &ExitBlocks) {
2295 // We can only promote stores in this block if they are unconditionally
2296 // executed in the loop. For a block to be unconditionally executed, it has
2297 // to dominate all the exit blocks of the loop. Verify this now.
2298 auto DominatedByBB = [this,BB] (BasicBlock *EB) -> bool {
2299 return DT->dominates(BB, EB);
2300 };
2301 if (!std::all_of(ExitBlocks.begin(), ExitBlocks.end(), DominatedByBB))
2302 return false;
2303
2304 bool MadeChange = false;
2305 // Look for store instructions, which may be optimized to memset/memcpy.
2306 SmallVector<StoreInst*,8> Stores;
2307 collectStores(CurLoop, BB, Stores);
2308
2309 // Optimize the store into a memcpy, if it feeds an similarly strided load.
2310 for (auto &SI : Stores)
2311 MadeChange |= processCopyingStore(CurLoop, SI, BECount);
2312
2313 return MadeChange;
2314}
2315
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002316bool HexagonLoopIdiomRecognize::runOnCountableLoop(Loop *L) {
2317 PolynomialMultiplyRecognize PMR(L, *DL, *DT, *TLI, *SE);
2318 if (PMR.recognize())
2319 return true;
2320
2321 if (!HasMemcpy && !HasMemmove)
2322 return false;
2323
2324 const SCEV *BECount = SE->getBackedgeTakenCount(L);
2325 assert(!isa<SCEVCouldNotCompute>(BECount) &&
2326 "runOnCountableLoop() called on a loop without a predictable"
2327 "backedge-taken count");
2328
2329 SmallVector<BasicBlock *, 8> ExitBlocks;
2330 L->getUniqueExitBlocks(ExitBlocks);
2331
2332 bool Changed = false;
2333
2334 // Scan all the blocks in the loop that are not in subloops.
2335 for (auto *BB : L->getBlocks()) {
2336 // Ignore blocks in subloops.
2337 if (LF->getLoopFor(BB) != L)
2338 continue;
2339 Changed |= runOnLoopBlock(L, BB, BECount, ExitBlocks);
2340 }
2341
2342 return Changed;
2343}
2344
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002345bool HexagonLoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
2346 const Module &M = *L->getHeader()->getParent()->getParent();
2347 if (Triple(M.getTargetTriple()).getArch() != Triple::hexagon)
2348 return false;
2349
2350 if (skipLoop(L))
2351 return false;
2352
2353 // If the loop could not be converted to canonical form, it must have an
2354 // indirectbr in it, just give up.
2355 if (!L->getLoopPreheader())
2356 return false;
2357
2358 // Disable loop idiom recognition if the function's name is a common idiom.
2359 StringRef Name = L->getHeader()->getParent()->getName();
2360 if (Name == "memset" || Name == "memcpy" || Name == "memmove")
2361 return false;
2362
2363 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2364 DL = &L->getHeader()->getModule()->getDataLayout();
2365 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2366 LF = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2367 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2368 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2369
2370 HasMemcpy = TLI->has(LibFunc_memcpy);
2371 HasMemmove = TLI->has(LibFunc_memmove);
2372
2373 if (SE->hasLoopInvariantBackedgeTakenCount(L))
2374 return runOnCountableLoop(L);
2375 return false;
2376}
2377
Krzysztof Parzyszekc8b94382017-01-26 21:41:10 +00002378Pass *llvm::createHexagonLoopIdiomPass() {
2379 return new HexagonLoopIdiomRecognize();
2380}