1//===- HexagonLoopIdiomRecognition.cpp ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "HexagonLoopIdiomRecognition.h"
10#include "Hexagon.h"
11#include "llvm/ADT/APInt.h"
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/SetVector.h"
14#include "llvm/ADT/SmallPtrSet.h"
15#include "llvm/ADT/SmallVector.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/Analysis/AliasAnalysis.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/LoopAnalysisManager.h"
20#include "llvm/Analysis/LoopInfo.h"
21#include "llvm/Analysis/LoopPass.h"
22#include "llvm/Analysis/MemoryLocation.h"
23#include "llvm/Analysis/OptimizationRemarkEmitter.h"
24#include "llvm/Analysis/ScalarEvolution.h"
25#include "llvm/Analysis/ScalarEvolutionExpressions.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
28#include "llvm/IR/Attributes.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Constant.h"
31#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DebugLoc.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.h"
40#include "llvm/IR/Instructions.h"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/IntrinsicsHexagon.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/PassManager.h"
45#include "llvm/IR/PatternMatch.h"
46#include "llvm/IR/RuntimeLibcalls.h"
47#include "llvm/IR/Type.h"
48#include "llvm/IR/User.h"
49#include "llvm/IR/Value.h"
50#include "llvm/InitializePasses.h"
51#include "llvm/Pass.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/Debug.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/KnownBits.h"
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/TargetParser/Triple.h"
60#include "llvm/Transforms/Scalar.h"
61#include "llvm/Transforms/Utils.h"
62#include "llvm/Transforms/Utils/Local.h"
63#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
64#include <algorithm>
65#include <array>
66#include <cassert>
67#include <cstdint>
68#include <cstdlib>
69#include <deque>
70#include <functional>
71#include <iterator>
72#include <map>
73#include <set>
74#include <utility>
75#include <vector>
76
77#define DEBUG_TYPE "hexagon-lir"
78
79using namespace llvm;
80
81static cl::opt<bool> DisableMemcpyIdiom("disable-memcpy-idiom",
82 cl::Hidden, cl::init(Val: false),
83 cl::desc("Disable generation of memcpy in loop idiom recognition"));
84
85static cl::opt<bool> DisableMemmoveIdiom("disable-memmove-idiom",
86 cl::Hidden, cl::init(Val: false),
87 cl::desc("Disable generation of memmove in loop idiom recognition"));
88
89static cl::opt<unsigned> RuntimeMemSizeThreshold("runtime-mem-idiom-threshold",
90 cl::Hidden, cl::init(Val: 0), cl::desc("Threshold (in bytes) for the runtime "
91 "check guarding the memmove."));
92
93static cl::opt<unsigned> CompileTimeMemSizeThreshold(
94 "compile-time-mem-idiom-threshold", cl::Hidden, cl::init(Val: 64),
95 cl::desc("Threshold (in bytes) to perform the transformation, if the "
96 "runtime loop count (mem transfer size) is known at compile-time."));
97
98static cl::opt<bool> OnlyNonNestedMemmove("only-nonnested-memmove-idiom",
99 cl::Hidden, cl::init(Val: true),
100 cl::desc("Only enable generating memmove in non-nested loops"));
101
102static cl::opt<bool> HexagonVolatileMemcpy(
103 "disable-hexagon-volatile-memcpy", cl::Hidden, cl::init(Val: false),
104 cl::desc("Enable Hexagon-specific memcpy for volatile destination."));
105
106static cl::opt<unsigned> SimplifyLimit("hlir-simplify-limit", cl::init(Val: 10000),
107 cl::Hidden, cl::desc("Maximum number of simplification steps in HLIR"));
108
109namespace {
110
111class HexagonLoopIdiomRecognize {
112public:
113 explicit HexagonLoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
114 LoopInfo *LF, const TargetLibraryInfo *TLI,
115 ScalarEvolution *SE,
116 OptimizationRemarkEmitter &ORE)
117 : AA(AA), DT(DT), LF(LF), TLI(TLI), SE(SE), ORE(ORE) {}
118
119 bool run(Loop *L);
120
121private:
122 int getSCEVStride(const SCEVAddRecExpr *StoreEv);
123 bool isLegalStore(Loop *CurLoop, StoreInst *SI);
124 void collectStores(Loop *CurLoop, BasicBlock *BB,
125 SmallVectorImpl<StoreInst *> &Stores);
126 bool processCopyingStore(Loop *CurLoop, StoreInst *SI, const SCEV *BECount);
127 bool coverLoop(Loop *L, SmallVectorImpl<Instruction *> &Insts) const;
128 bool runOnLoopBlock(Loop *CurLoop, BasicBlock *BB, const SCEV *BECount,
129 SmallVectorImpl<BasicBlock *> &ExitBlocks);
130 bool runOnCountableLoop(Loop *L);
131
132 AliasAnalysis *AA;
133 const DataLayout *DL;
134 DominatorTree *DT;
135 LoopInfo *LF;
136 const TargetLibraryInfo *TLI;
137 ScalarEvolution *SE;
138 OptimizationRemarkEmitter &ORE;
139 bool HasMemcpy, HasMemmove;
140};
141
142class HexagonLoopIdiomRecognizeLegacyPass : public LoopPass {
143public:
144 static char ID;
145
146 explicit HexagonLoopIdiomRecognizeLegacyPass() : LoopPass(ID) {}
147
148 StringRef getPassName() const override {
149 return "Recognize Hexagon-specific loop idioms";
150 }
151
152 void getAnalysisUsage(AnalysisUsage &AU) const override {
153 AU.addRequired<LoopInfoWrapperPass>();
154 AU.addRequiredID(ID&: LoopSimplifyID);
155 AU.addRequiredID(ID&: LCSSAID);
156 AU.addRequired<AAResultsWrapperPass>();
157 AU.addRequired<ScalarEvolutionWrapperPass>();
158 AU.addRequired<DominatorTreeWrapperPass>();
159 AU.addRequired<TargetLibraryInfoWrapperPass>();
160 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
161 AU.addPreserved<TargetLibraryInfoWrapperPass>();
162 }
163
164 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
165};
166
167struct Simplifier {
168 struct Rule {
169 using FuncType = std::function<Value *(Instruction *, Module &)>;
170 Rule(StringRef N, FuncType F) : Name(N), Fn(F) {}
171 StringRef Name; // For debugging.
172 FuncType Fn;
173 };
174
175 void addRule(StringRef N, const Rule::FuncType &F) {
176 Rules.push_back(x: Rule(N, F));
177 }
178
179private:
180 struct WorkListType {
181 WorkListType() = default;
182
183 void push_back(Value *V) {
184 // Do not push back duplicates.
185 if (S.insert(x: V).second)
186 Q.push_back(x: V);
187 }
188
189 Value *pop_front_val() {
190 Value *V = Q.front();
191 Q.pop_front();
192 S.erase(x: V);
193 return V;
194 }
195
196 bool empty() const { return Q.empty(); }
197
198 private:
199 std::deque<Value *> Q;
200 std::set<Value *> S;
201 };
202
203 using ValueSetType = std::set<Value *>;
204
205 std::vector<Rule> Rules;
206
207public:
208 struct Context {
209 using ValueMapType = DenseMap<Value *, Value *>;
210
211 Value *Root;
212 ValueSetType Used; // The set of all cloned values used by Root.
213 ValueSetType Clones; // The set of all cloned values.
214 Module &M;
215
216 Context(Instruction *Exp) : M(*Exp->getModule()) { initialize(Exp); }
217
218 ~Context() { cleanup(); }
219
220 void print(raw_ostream &OS, const Value *V) const;
221 Value *materialize(BasicBlock *B, BasicBlock::iterator At);
222
223 private:
224 friend struct Simplifier;
225
226 void initialize(Instruction *Exp);
227 void cleanup();
228
229 template <typename FuncT> void traverse(Value *V, FuncT F);
230 void record(Value *V);
231 void use(Value *V);
232 void unuse(Value *V);
233
234 bool equal(const Instruction *I, const Instruction *J) const;
235 Value *find(Value *Tree, Value *Sub) const;
236 Value *subst(Value *Tree, Value *OldV, Value *NewV);
237 void replace(Value *OldV, Value *NewV);
238 void link(Instruction *I, BasicBlock *B, BasicBlock::iterator At);
239 };
240
241 Value *simplify(Context &C);
242};
243
244 struct PE {
245 PE(const Simplifier::Context &c, Value *v = nullptr) : C(c), V(v) {}
246
247 const Simplifier::Context &C;
248 const Value *V;
249 };
250
251 LLVM_ATTRIBUTE_USED
252 raw_ostream &operator<<(raw_ostream &OS, const PE &P) {
253 P.C.print(OS, V: P.V ? P.V : P.C.Root);
254 return OS;
255 }
256
257} // end anonymous namespace
258
259char HexagonLoopIdiomRecognizeLegacyPass::ID = 0;
260
261INITIALIZE_PASS_BEGIN(HexagonLoopIdiomRecognizeLegacyPass, "hexagon-loop-idiom",
262 "Recognize Hexagon-specific loop idioms", false, false)
263INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
264INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
265INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
266INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
267INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
268INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
269INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
270INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
271INITIALIZE_PASS_END(HexagonLoopIdiomRecognizeLegacyPass, "hexagon-loop-idiom",
272 "Recognize Hexagon-specific loop idioms", false, false)
273
274template <typename FuncT>
275void Simplifier::Context::traverse(Value *V, FuncT F) {
276 WorkListType Q;
277 Q.push_back(V);
278
279 while (!Q.empty()) {
280 Instruction *U = dyn_cast<Instruction>(Val: Q.pop_front_val());
281 if (!U || U->getParent())
282 continue;
283 if (!F(U))
284 continue;
285 for (Value *Op : U->operands())
286 Q.push_back(V: Op);
287 }
288}
289
290void Simplifier::Context::print(raw_ostream &OS, const Value *V) const {
291 const auto *U = dyn_cast<const Instruction>(Val: V);
292 if (!U) {
293 OS << V << '(' << *V << ')';
294 return;
295 }
296
297 if (U->getParent()) {
298 OS << U << '(';
299 U->printAsOperand(O&: OS, PrintType: true);
300 OS << ')';
301 return;
302 }
303
304 unsigned N = U->getNumOperands();
305 if (N != 0)
306 OS << U << '(';
307 OS << U->getOpcodeName();
308 for (const Value *Op : U->operands()) {
309 OS << ' ';
310 print(OS, V: Op);
311 }
312 if (N != 0)
313 OS << ')';
314}
315
316void Simplifier::Context::initialize(Instruction *Exp) {
317 // Perform a deep clone of the expression, set Root to the root
318 // of the clone, and build a map from the cloned values to the
319 // original ones.
320 ValueMapType M;
321 BasicBlock *Block = Exp->getParent();
322 WorkListType Q;
323 Q.push_back(V: Exp);
324
325 while (!Q.empty()) {
326 Value *V = Q.pop_front_val();
327 if (M.contains(Val: V))
328 continue;
329 if (Instruction *U = dyn_cast<Instruction>(Val: V)) {
330 if (isa<PHINode>(Val: U) || U->getParent() != Block)
331 continue;
332 for (Value *Op : U->operands())
333 Q.push_back(V: Op);
334 M.insert(KV: {U, U->clone()});
335 }
336 }
337
338 for (std::pair<Value*,Value*> P : M) {
339 Instruction *U = cast<Instruction>(Val: P.second);
340 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
341 auto F = M.find(Val: U->getOperand(i));
342 if (F != M.end())
343 U->setOperand(i, Val: F->second);
344 }
345 }
346
347 auto R = M.find(Val: Exp);
348 assert(R != M.end());
349 Root = R->second;
350
351 record(V: Root);
352 use(V: Root);
353}
354
355void Simplifier::Context::record(Value *V) {
356 auto Record = [this](Instruction *U) -> bool {
357 Clones.insert(x: U);
358 return true;
359 };
360 traverse(V, F: Record);
361}
362
363void Simplifier::Context::use(Value *V) {
364 auto Use = [this](Instruction *U) -> bool {
365 Used.insert(x: U);
366 return true;
367 };
368 traverse(V, F: Use);
369}
370
371void Simplifier::Context::unuse(Value *V) {
372 if (!isa<Instruction>(Val: V) || cast<Instruction>(Val: V)->getParent() != nullptr)
373 return;
374
375 auto Unuse = [this](Instruction *U) -> bool {
376 if (!U->use_empty())
377 return false;
378 Used.erase(x: U);
379 return true;
380 };
381 traverse(V, F: Unuse);
382}
383
384Value *Simplifier::Context::subst(Value *Tree, Value *OldV, Value *NewV) {
385 if (Tree == OldV)
386 return NewV;
387 if (OldV == NewV)
388 return Tree;
389
390 WorkListType Q;
391 Q.push_back(V: Tree);
392 while (!Q.empty()) {
393 Instruction *U = dyn_cast<Instruction>(Val: Q.pop_front_val());
394 // If U is not an instruction, or it's not a clone, skip it.
395 if (!U || U->getParent())
396 continue;
397 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
398 Value *Op = U->getOperand(i);
399 if (Op == OldV) {
400 U->setOperand(i, Val: NewV);
401 unuse(V: OldV);
402 } else {
403 Q.push_back(V: Op);
404 }
405 }
406 }
407 return Tree;
408}
409
410void Simplifier::Context::replace(Value *OldV, Value *NewV) {
411 if (Root == OldV) {
412 Root = NewV;
413 use(V: Root);
414 return;
415 }
416
417 // NewV may be a complex tree that has just been created by one of the
418 // transformation rules. We need to make sure that it is commoned with
419 // the existing Root to the maximum extent possible.
420 // Identify all subtrees of NewV (including NewV itself) that have
421 // equivalent counterparts in Root, and replace those subtrees with
422 // these counterparts.
423 WorkListType Q;
424 Q.push_back(V: NewV);
425 while (!Q.empty()) {
426 Value *V = Q.pop_front_val();
427 Instruction *U = dyn_cast<Instruction>(Val: V);
428 if (!U || U->getParent())
429 continue;
430 if (Value *DupV = find(Tree: Root, Sub: V)) {
431 if (DupV != V)
432 NewV = subst(Tree: NewV, OldV: V, NewV: DupV);
433 } else {
434 for (Value *Op : U->operands())
435 Q.push_back(V: Op);
436 }
437 }
438
439 // Now, simply replace OldV with NewV in Root.
440 Root = subst(Tree: Root, OldV, NewV);
441 use(V: Root);
442}
443
444void Simplifier::Context::cleanup() {
445 for (Value *V : Clones) {
446 Instruction *U = cast<Instruction>(Val: V);
447 if (!U->getParent())
448 U->dropAllReferences();
449 }
450
451 for (Value *V : Clones) {
452 Instruction *U = cast<Instruction>(Val: V);
453 if (!U->getParent())
454 U->deleteValue();
455 }
456}
457
458bool Simplifier::Context::equal(const Instruction *I,
459 const Instruction *J) const {
460 if (I == J)
461 return true;
462 if (!I->isSameOperationAs(I: J))
463 return false;
464 if (isa<PHINode>(Val: I))
465 return I->isIdenticalTo(I: J);
466
467 for (unsigned i = 0, n = I->getNumOperands(); i != n; ++i) {
468 Value *OpI = I->getOperand(i), *OpJ = J->getOperand(i);
469 if (OpI == OpJ)
470 continue;
471 auto *InI = dyn_cast<const Instruction>(Val: OpI);
472 auto *InJ = dyn_cast<const Instruction>(Val: OpJ);
473 if (InI && InJ) {
474 if (!equal(I: InI, J: InJ))
475 return false;
476 } else if (InI != InJ || !InI)
477 return false;
478 }
479 return true;
480}
481
482Value *Simplifier::Context::find(Value *Tree, Value *Sub) const {
483 Instruction *SubI = dyn_cast<Instruction>(Val: Sub);
484 WorkListType Q;
485 Q.push_back(V: Tree);
486
487 while (!Q.empty()) {
488 Value *V = Q.pop_front_val();
489 if (V == Sub)
490 return V;
491 Instruction *U = dyn_cast<Instruction>(Val: V);
492 if (!U || U->getParent())
493 continue;
494 if (SubI && equal(I: SubI, J: U))
495 return U;
496 assert(!isa<PHINode>(U));
497 for (Value *Op : U->operands())
498 Q.push_back(V: Op);
499 }
500 return nullptr;
501}
502
503void Simplifier::Context::link(Instruction *I, BasicBlock *B,
504 BasicBlock::iterator At) {
505 if (I->getParent())
506 return;
507
508 for (Value *Op : I->operands()) {
509 if (Instruction *OpI = dyn_cast<Instruction>(Val: Op))
510 link(I: OpI, B, At);
511 }
512
513 I->insertInto(ParentBB: B, It: At);
514}
515
516Value *Simplifier::Context::materialize(BasicBlock *B,
517 BasicBlock::iterator At) {
518 if (Instruction *RootI = dyn_cast<Instruction>(Val: Root))
519 link(I: RootI, B, At);
520 return Root;
521}
522
523Value *Simplifier::simplify(Context &C) {
524 WorkListType Q;
525 Q.push_back(V: C.Root);
526 unsigned Count = 0;
527 const unsigned Limit = SimplifyLimit;
528
529 while (!Q.empty()) {
530 if (Count++ >= Limit)
531 break;
532 Instruction *U = dyn_cast<Instruction>(Val: Q.pop_front_val());
533 if (!U || U->getParent() || !C.Used.count(x: U))
534 continue;
535 bool Changed = false;
536 for (Rule &R : Rules) {
537 Value *W = R.Fn(U, C.M);
538 if (!W)
539 continue;
540 Changed = true;
541 C.record(V: W);
542 C.replace(OldV: U, NewV: W);
543 Q.push_back(V: C.Root);
544 break;
545 }
546 if (!Changed) {
547 for (Value *Op : U->operands())
548 Q.push_back(V: Op);
549 }
550 }
551 return Count < Limit ? C.Root : nullptr;
552}
553
554//===----------------------------------------------------------------------===//
555//
556// Implementation of PolynomialMultiplyRecognize
557//
558//===----------------------------------------------------------------------===//
559
560namespace {
561
562 class PolynomialMultiplyRecognize {
563 public:
564 explicit PolynomialMultiplyRecognize(Loop *loop, const DataLayout &dl,
565 const DominatorTree &dt, const TargetLibraryInfo &tli,
566 ScalarEvolution &se)
567 : CurLoop(loop), DL(dl), DT(dt), TLI(tli), SE(se) {}
568
569 bool recognize();
570
571 private:
572 using ValueSeq = SetVector<Value *>;
573
574 IntegerType *getPmpyType() const {
575 LLVMContext &Ctx = CurLoop->getHeader()->getParent()->getContext();
576 return IntegerType::get(C&: Ctx, NumBits: 32);
577 }
578
579 bool isPromotableTo(Value *V, IntegerType *Ty);
580 void promoteTo(Instruction *In, IntegerType *DestTy, BasicBlock *LoopB);
581 bool promoteTypes(BasicBlock *LoopB, BasicBlock *ExitB);
582
583 Value *getCountIV(BasicBlock *BB);
584 bool findCycle(Value *Out, Value *In, ValueSeq &Cycle);
585 void classifyCycle(Instruction *DivI, ValueSeq &Cycle, ValueSeq &Early,
586 ValueSeq &Late);
587 bool classifyInst(Instruction *UseI, ValueSeq &Early, ValueSeq &Late);
588 bool commutesWithShift(Instruction *I);
589 bool highBitsAreZero(Value *V, unsigned IterCount);
590 bool keepsHighBitsZero(Value *V, unsigned IterCount);
591 bool isOperandShifted(Instruction *I, Value *Op);
592 bool convertShiftsToLeft(BasicBlock *LoopB, BasicBlock *ExitB,
593 unsigned IterCount);
594 void cleanupLoopBody(BasicBlock *LoopB);
595
596 struct ParsedValues {
597 ParsedValues() = default;
598
599 Value *M = nullptr;
600 Value *P = nullptr;
601 Value *Q = nullptr;
602 Value *R = nullptr;
603 Value *X = nullptr;
604 Instruction *Res = nullptr;
605 unsigned IterCount = 0;
606 bool Left = false;
607 bool Inv = false;
608 };
609
610 bool matchLeftShift(SelectInst *SelI, Value *CIV, ParsedValues &PV);
611 bool matchRightShift(SelectInst *SelI, ParsedValues &PV);
612 bool scanSelect(SelectInst *SI, BasicBlock *LoopB, BasicBlock *PrehB,
613 Value *CIV, ParsedValues &PV, bool PreScan);
614 unsigned getInverseMxN(unsigned QP);
615 Value *generate(BasicBlock::iterator At, ParsedValues &PV);
616
617 void setupPreSimplifier(Simplifier &S);
618 void setupPostSimplifier(Simplifier &S);
619
620 Loop *CurLoop;
621 const DataLayout &DL;
622 const DominatorTree &DT;
623 const TargetLibraryInfo &TLI;
624 ScalarEvolution &SE;
625 };
626
627} // end anonymous namespace
628
629Value *PolynomialMultiplyRecognize::getCountIV(BasicBlock *BB) {
630 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
631 if (std::distance(first: PI, last: PE) != 2)
632 return nullptr;
633 BasicBlock *PB = (*PI == BB) ? *std::next(x: PI) : *PI;
634
635 for (auto I = BB->begin(), E = BB->end(); I != E && isa<PHINode>(Val: I); ++I) {
636 auto *PN = cast<PHINode>(Val&: I);
637 Value *InitV = PN->getIncomingValueForBlock(BB: PB);
638 if (!isa<ConstantInt>(Val: InitV) || !cast<ConstantInt>(Val: InitV)->isZero())
639 continue;
640 Value *IterV = PN->getIncomingValueForBlock(BB);
641 auto *BO = dyn_cast<BinaryOperator>(Val: IterV);
642 if (!BO)
643 continue;
644 if (BO->getOpcode() != Instruction::Add)
645 continue;
646 Value *IncV = nullptr;
647 if (BO->getOperand(i_nocapture: 0) == PN)
648 IncV = BO->getOperand(i_nocapture: 1);
649 else if (BO->getOperand(i_nocapture: 1) == PN)
650 IncV = BO->getOperand(i_nocapture: 0);
651 if (IncV == nullptr)
652 continue;
653
654 if (auto *T = dyn_cast<ConstantInt>(Val: IncV))
655 if (T->isOne())
656 return PN;
657 }
658 return nullptr;
659}
660
661static void replaceAllUsesOfWithIn(Value *I, Value *J, BasicBlock *BB) {
662 for (auto UI = I->user_begin(), UE = I->user_end(); UI != UE;) {
663 Use &TheUse = UI.getUse();
664 ++UI;
665 if (auto *II = dyn_cast<Instruction>(Val: TheUse.getUser()))
666 if (BB == II->getParent())
667 II->replaceUsesOfWith(From: I, To: J);
668 }
669}
670
671bool PolynomialMultiplyRecognize::matchLeftShift(SelectInst *SelI,
672 Value *CIV, ParsedValues &PV) {
673 // Match the following:
674 // select (X & (1 << i)) != 0 ? R ^ (Q << i) : R
675 // select (X & (1 << i)) == 0 ? R : R ^ (Q << i)
676 // The condition may also check for equality with the masked value, i.e
677 // select (X & (1 << i)) == (1 << i) ? R ^ (Q << i) : R
678 // select (X & (1 << i)) != (1 << i) ? R : R ^ (Q << i);
679
680 Value *CondV = SelI->getCondition();
681 Value *TrueV = SelI->getTrueValue();
682 Value *FalseV = SelI->getFalseValue();
683
684 using namespace PatternMatch;
685
686 CmpPredicate P;
687 Value *A = nullptr, *B = nullptr, *C = nullptr;
688
689 if (!match(V: CondV, P: m_ICmp(Pred&: P, L: m_And(L: m_Value(V&: A), R: m_Value(V&: B)), R: m_Value(V&: C))) &&
690 !match(V: CondV, P: m_ICmp(Pred&: P, L: m_Value(V&: C), R: m_And(L: m_Value(V&: A), R: m_Value(V&: B)))))
691 return false;
692 if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
693 return false;
694 // Matched: select (A & B) == C ? ... : ...
695 // select (A & B) != C ? ... : ...
696
697 Value *X = nullptr, *Sh1 = nullptr;
698 // Check (A & B) for (X & (1 << i)):
699 if (match(V: A, P: m_Shl(L: m_One(), R: m_Specific(V: CIV)))) {
700 Sh1 = A;
701 X = B;
702 } else if (match(V: B, P: m_Shl(L: m_One(), R: m_Specific(V: CIV)))) {
703 Sh1 = B;
704 X = A;
705 } else {
706 // TODO: Could also check for an induction variable containing single
707 // bit shifted left by 1 in each iteration.
708 return false;
709 }
710
711 bool TrueIfZero;
712
713 // Check C against the possible values for comparison: 0 and (1 << i):
714 if (match(V: C, P: m_Zero()))
715 TrueIfZero = (P == CmpInst::ICMP_EQ);
716 else if (C == Sh1)
717 TrueIfZero = (P == CmpInst::ICMP_NE);
718 else
719 return false;
720
721 // So far, matched:
722 // select (X & (1 << i)) ? ... : ...
723 // including variations of the check against zero/non-zero value.
724
725 Value *ShouldSameV = nullptr, *ShouldXoredV = nullptr;
726 if (TrueIfZero) {
727 ShouldSameV = TrueV;
728 ShouldXoredV = FalseV;
729 } else {
730 ShouldSameV = FalseV;
731 ShouldXoredV = TrueV;
732 }
733
734 Value *Q = nullptr, *R = nullptr, *Y = nullptr, *Z = nullptr;
735 Value *T = nullptr;
736 if (match(V: ShouldXoredV, P: m_Xor(L: m_Value(V&: Y), R: m_Value(V&: Z)))) {
737 // Matched: select +++ ? ... : Y ^ Z
738 // select +++ ? Y ^ Z : ...
739 // where +++ denotes previously checked matches.
740 if (ShouldSameV == Y)
741 T = Z;
742 else if (ShouldSameV == Z)
743 T = Y;
744 else
745 return false;
746 R = ShouldSameV;
747 // Matched: select +++ ? R : R ^ T
748 // select +++ ? R ^ T : R
749 // depending on TrueIfZero.
750
751 } else if (match(V: ShouldSameV, P: m_Zero())) {
752 // Matched: select +++ ? 0 : ...
753 // select +++ ? ... : 0
754 if (!SelI->hasOneUse())
755 return false;
756 T = ShouldXoredV;
757 // Matched: select +++ ? 0 : T
758 // select +++ ? T : 0
759
760 Value *U = *SelI->user_begin();
761 if (!match(V: U, P: m_c_Xor(L: m_Specific(V: SelI), R: m_Value(V&: R))))
762 return false;
763 // Matched: xor (select +++ ? 0 : T), R
764 // xor (select +++ ? T : 0), R
765 } else
766 return false;
767
768 // The xor input value T is isolated into its own match so that it could
769 // be checked against an induction variable containing a shifted bit
770 // (todo).
771 // For now, check against (Q << i).
772 if (!match(V: T, P: m_Shl(L: m_Value(V&: Q), R: m_Specific(V: CIV))) &&
773 !match(V: T, P: m_Shl(L: m_ZExt(Op: m_Value(V&: Q)), R: m_ZExt(Op: m_Specific(V: CIV)))))
774 return false;
775 // Matched: select +++ ? R : R ^ (Q << i)
776 // select +++ ? R ^ (Q << i) : R
777
778 PV.X = X;
779 PV.Q = Q;
780 PV.R = R;
781 PV.Left = true;
782 return true;
783}
784
785bool PolynomialMultiplyRecognize::matchRightShift(SelectInst *SelI,
786 ParsedValues &PV) {
787 // Match the following:
788 // select (X & 1) != 0 ? (R >> 1) ^ Q : (R >> 1)
789 // select (X & 1) == 0 ? (R >> 1) : (R >> 1) ^ Q
790 // The condition may also check for equality with the masked value, i.e
791 // select (X & 1) == 1 ? (R >> 1) ^ Q : (R >> 1)
792 // select (X & 1) != 1 ? (R >> 1) : (R >> 1) ^ Q
793
794 Value *CondV = SelI->getCondition();
795 Value *TrueV = SelI->getTrueValue();
796 Value *FalseV = SelI->getFalseValue();
797
798 using namespace PatternMatch;
799
800 Value *C = nullptr;
801 CmpPredicate P;
802 bool TrueIfZero;
803
804 if (match(V: CondV, P: m_c_ICmp(Pred&: P, L: m_Value(V&: C), R: m_Zero()))) {
805 if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
806 return false;
807 // Matched: select C == 0 ? ... : ...
808 // select C != 0 ? ... : ...
809 TrueIfZero = (P == CmpInst::ICMP_EQ);
810 } else if (match(V: CondV, P: m_c_ICmp(Pred&: P, L: m_Value(V&: C), R: m_One()))) {
811 if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE)
812 return false;
813 // Matched: select C == 1 ? ... : ...
814 // select C != 1 ? ... : ...
815 TrueIfZero = (P == CmpInst::ICMP_NE);
816 } else
817 return false;
818
819 Value *X = nullptr;
820 if (!match(V: C, P: m_And(L: m_Value(V&: X), R: m_One())))
821 return false;
822 // Matched: select (X & 1) == +++ ? ... : ...
823 // select (X & 1) != +++ ? ... : ...
824
825 Value *R = nullptr, *Q = nullptr;
826 if (TrueIfZero) {
827 // The select's condition is true if the tested bit is 0.
828 // TrueV must be the shift, FalseV must be the xor.
829 if (!match(V: TrueV, P: m_LShr(L: m_Value(V&: R), R: m_One())))
830 return false;
831 // Matched: select +++ ? (R >> 1) : ...
832 if (!match(V: FalseV, P: m_c_Xor(L: m_Specific(V: TrueV), R: m_Value(V&: Q))))
833 return false;
834 // Matched: select +++ ? (R >> 1) : (R >> 1) ^ Q
835 // with commuting ^.
836 } else {
837 // The select's condition is true if the tested bit is 1.
838 // TrueV must be the xor, FalseV must be the shift.
839 if (!match(V: FalseV, P: m_LShr(L: m_Value(V&: R), R: m_One())))
840 return false;
841 // Matched: select +++ ? ... : (R >> 1)
842 if (!match(V: TrueV, P: m_c_Xor(L: m_Specific(V: FalseV), R: m_Value(V&: Q))))
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
855bool PolynomialMultiplyRecognize::scanSelect(SelectInst *SelI,
856 BasicBlock *LoopB, BasicBlock *PrehB, Value *CIV, ParsedValues &PV,
857 bool PreScan) {
858 using namespace PatternMatch;
859
860 // 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>(Val: PV.R);
904 if (!RPhi)
905 return false;
906 if (SelI != RPhi->getIncomingValueForBlock(BB: 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(V: 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(V: PV.X, P: m_Xor(L: m_Value(V&: X1), R: m_Value(V&: X2))))
924 return false;
925 auto *I1 = dyn_cast<Instruction>(Val: X1);
926 auto *I2 = dyn_cast<Instruction>(Val: 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(BB: 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>(Val: 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
962bool PolynomialMultiplyRecognize::isPromotableTo(Value *Val,
963 IntegerType *DestTy) {
964 IntegerType *T = dyn_cast<IntegerType>(Val: 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 case Instruction::Trunc:
989 return true;
990 case Instruction::ICmp:
991 if (CmpInst *CI = cast<CmpInst>(Val: In))
992 return CI->isEquality() || CI->isUnsigned();
993 llvm_unreachable("Cast failed unexpectedly");
994 case Instruction::Add:
995 return In->hasNoSignedWrap() && In->hasNoUnsignedWrap();
996 }
997 return false;
998}
999
1000void PolynomialMultiplyRecognize::promoteTo(Instruction *In,
1001 IntegerType *DestTy, BasicBlock *LoopB) {
1002 Type *OrigTy = In->getType();
1003 assert(!OrigTy->isVoidTy() && "Invalid instruction to promote");
1004
1005 // Leave boolean values alone.
1006 if (!In->getType()->isIntegerTy(BitWidth: 1))
1007 In->mutateType(Ty: DestTy);
1008 unsigned DestBW = DestTy->getBitWidth();
1009
1010 // Handle PHIs.
1011 if (PHINode *P = dyn_cast<PHINode>(Val: In)) {
1012 unsigned N = P->getNumIncomingValues();
1013 for (unsigned i = 0; i != N; ++i) {
1014 BasicBlock *InB = P->getIncomingBlock(i);
1015 if (InB == LoopB)
1016 continue;
1017 Value *InV = P->getIncomingValue(i);
1018 IntegerType *Ty = cast<IntegerType>(Val: InV->getType());
1019 // Do not promote values in PHI nodes of type i1.
1020 if (Ty != P->getType()) {
1021 // If the value type does not match the PHI type, the PHI type
1022 // must have been promoted.
1023 assert(Ty->getBitWidth() < DestBW);
1024 InV = IRBuilder<>(InB->getTerminator()).CreateZExt(V: InV, DestTy);
1025 P->setIncomingValue(i, V: InV);
1026 }
1027 }
1028 } else if (ZExtInst *Z = dyn_cast<ZExtInst>(Val: In)) {
1029 Value *Op = Z->getOperand(i_nocapture: 0);
1030 if (Op->getType() == Z->getType())
1031 Z->replaceAllUsesWith(V: Op);
1032 Z->eraseFromParent();
1033 return;
1034 }
1035 if (TruncInst *T = dyn_cast<TruncInst>(Val: In)) {
1036 IntegerType *TruncTy = cast<IntegerType>(Val: OrigTy);
1037 Value *Mask = ConstantInt::get(Ty: DestTy, V: (1u << TruncTy->getBitWidth()) - 1);
1038 Value *And = IRBuilder<>(In).CreateAnd(LHS: T->getOperand(i_nocapture: 0), RHS: Mask);
1039 T->replaceAllUsesWith(V: And);
1040 T->eraseFromParent();
1041 return;
1042 }
1043
1044 // Promote immediates.
1045 for (unsigned i = 0, n = In->getNumOperands(); i != n; ++i) {
1046 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: In->getOperand(i)))
1047 if (CI->getBitWidth() < DestBW)
1048 In->setOperand(i, Val: ConstantInt::get(Ty: DestTy, V: CI->getZExtValue()));
1049 }
1050}
1051
1052bool PolynomialMultiplyRecognize::promoteTypes(BasicBlock *LoopB,
1053 BasicBlock *ExitB) {
1054 assert(LoopB);
1055 // Skip loops where the exit block has more than one predecessor. The values
1056 // coming from the loop block will be promoted to another type, and so the
1057 // values coming into the exit block from other predecessors would also have
1058 // to be promoted.
1059 if (!ExitB || (ExitB->getSinglePredecessor() != LoopB))
1060 return false;
1061 IntegerType *DestTy = getPmpyType();
1062 // Check if the exit values have types that are no wider than the type
1063 // that we want to promote to.
1064 unsigned DestBW = DestTy->getBitWidth();
1065 for (PHINode &P : ExitB->phis()) {
1066 if (P.getNumIncomingValues() != 1)
1067 return false;
1068 assert(P.getIncomingBlock(0) == LoopB);
1069 IntegerType *T = dyn_cast<IntegerType>(Val: P.getType());
1070 if (!T || T->getBitWidth() > DestBW)
1071 return false;
1072 }
1073
1074 // Check all instructions in the loop.
1075 for (Instruction &In : *LoopB)
1076 if (!In.isTerminator() && !isPromotableTo(Val: &In, DestTy))
1077 return false;
1078
1079 // Perform the promotion.
1080 SmallVector<Instruction *> LoopIns(llvm::make_pointer_range(Range&: *LoopB));
1081 for (Instruction *In : LoopIns)
1082 if (!In->isTerminator())
1083 promoteTo(In, DestTy, LoopB);
1084
1085 // Fix up the PHI nodes in the exit block.
1086 BasicBlock::iterator End = ExitB->getFirstNonPHIIt();
1087 for (auto I = ExitB->begin(); I != End; ++I) {
1088 PHINode *P = dyn_cast<PHINode>(Val&: I);
1089 if (!P)
1090 break;
1091 Type *Ty0 = P->getIncomingValue(i: 0)->getType();
1092 Type *PTy = P->getType();
1093 if (PTy != Ty0) {
1094 assert(Ty0 == DestTy);
1095 // In order to create the trunc, P must have the promoted type.
1096 P->mutateType(Ty: Ty0);
1097 Value *T = IRBuilder<>(End).CreateTrunc(V: P, DestTy: PTy);
1098 // In order for the RAUW to work, the types of P and T must match.
1099 P->mutateType(Ty: PTy);
1100 P->replaceAllUsesWith(V: T);
1101 // Final update of the P's type.
1102 P->mutateType(Ty: Ty0);
1103 cast<Instruction>(Val: T)->setOperand(i: 0, Val: P);
1104 }
1105 }
1106
1107 return true;
1108}
1109
1110bool PolynomialMultiplyRecognize::findCycle(Value *Out, Value *In,
1111 ValueSeq &Cycle) {
1112 // Out = ..., In, ...
1113 if (Out == In)
1114 return true;
1115
1116 auto *BB = cast<Instruction>(Val: Out)->getParent();
1117 bool HadPhi = false;
1118
1119 for (auto *U : Out->users()) {
1120 auto *I = dyn_cast<Instruction>(Val: &*U);
1121 if (I == nullptr || I->getParent() != BB)
1122 continue;
1123 // Make sure that there are no multi-iteration cycles, e.g.
1124 // p1 = phi(p2)
1125 // p2 = phi(p1)
1126 // The cycle p1->p2->p1 would span two loop iterations.
1127 // Check that there is only one phi in the cycle.
1128 bool IsPhi = isa<PHINode>(Val: I);
1129 if (IsPhi && HadPhi)
1130 return false;
1131 HadPhi |= IsPhi;
1132 if (!Cycle.insert(X: I))
1133 return false;
1134 if (findCycle(Out: I, In, Cycle))
1135 break;
1136 Cycle.remove(X: I);
1137 }
1138 return !Cycle.empty();
1139}
1140
1141void PolynomialMultiplyRecognize::classifyCycle(Instruction *DivI,
1142 ValueSeq &Cycle, ValueSeq &Early, ValueSeq &Late) {
1143 // All the values in the cycle that are between the phi node and the
1144 // divider instruction will be classified as "early", all other values
1145 // will be "late".
1146
1147 bool IsE = true;
1148 unsigned I, N = Cycle.size();
1149 for (I = 0; I < N; ++I) {
1150 Value *V = Cycle[I];
1151 if (DivI == V)
1152 IsE = false;
1153 else if (!isa<PHINode>(Val: V))
1154 continue;
1155 // Stop if found either.
1156 break;
1157 }
1158 // "I" is the index of either DivI or the phi node, whichever was first.
1159 // "E" is "false" or "true" respectively.
1160 ValueSeq &First = !IsE ? Early : Late;
1161 for (unsigned J = 0; J < I; ++J)
1162 First.insert(X: Cycle[J]);
1163
1164 ValueSeq &Second = IsE ? Early : Late;
1165 Second.insert(X: Cycle[I]);
1166 for (++I; I < N; ++I) {
1167 Value *V = Cycle[I];
1168 if (DivI == V || isa<PHINode>(Val: V))
1169 break;
1170 Second.insert(X: V);
1171 }
1172
1173 for (; I < N; ++I)
1174 First.insert(X: Cycle[I]);
1175}
1176
1177bool PolynomialMultiplyRecognize::classifyInst(Instruction *UseI,
1178 ValueSeq &Early, ValueSeq &Late) {
1179 // Select is an exception, since the condition value does not have to be
1180 // classified in the same way as the true/false values. The true/false
1181 // values do have to be both early or both late.
1182 if (UseI->getOpcode() == Instruction::Select) {
1183 Value *TV = UseI->getOperand(i: 1), *FV = UseI->getOperand(i: 2);
1184 if (Early.count(key: TV) || Early.count(key: FV)) {
1185 if (Late.count(key: TV) || Late.count(key: FV))
1186 return false;
1187 Early.insert(X: UseI);
1188 } else if (Late.count(key: TV) || Late.count(key: FV)) {
1189 if (Early.count(key: TV) || Early.count(key: FV))
1190 return false;
1191 Late.insert(X: UseI);
1192 }
1193 return true;
1194 }
1195
1196 // Not sure what would be the example of this, but the code below relies
1197 // on having at least one operand.
1198 if (UseI->getNumOperands() == 0)
1199 return true;
1200
1201 bool AE = true, AL = true;
1202 for (auto &I : UseI->operands()) {
1203 if (Early.count(key: &*I))
1204 AL = false;
1205 else if (Late.count(key: &*I))
1206 AE = false;
1207 }
1208 // If the operands appear "all early" and "all late" at the same time,
1209 // then it means that none of them are actually classified as either.
1210 // This is harmless.
1211 if (AE && AL)
1212 return true;
1213 // Conversely, if they are neither "all early" nor "all late", then
1214 // we have a mixture of early and late operands that is not a known
1215 // exception.
1216 if (!AE && !AL)
1217 return false;
1218
1219 // Check that we have covered the two special cases.
1220 assert(AE != AL);
1221
1222 if (AE)
1223 Early.insert(X: UseI);
1224 else
1225 Late.insert(X: UseI);
1226 return true;
1227}
1228
1229bool PolynomialMultiplyRecognize::commutesWithShift(Instruction *I) {
1230 switch (I->getOpcode()) {
1231 case Instruction::And:
1232 case Instruction::Or:
1233 case Instruction::Xor:
1234 case Instruction::LShr:
1235 case Instruction::Shl:
1236 case Instruction::Select:
1237 case Instruction::ICmp:
1238 case Instruction::PHI:
1239 break;
1240 default:
1241 return false;
1242 }
1243 return true;
1244}
1245
1246bool PolynomialMultiplyRecognize::highBitsAreZero(Value *V,
1247 unsigned IterCount) {
1248 auto *T = dyn_cast<IntegerType>(Val: V->getType());
1249 if (!T)
1250 return false;
1251
1252 KnownBits Known(T->getBitWidth());
1253 computeKnownBits(V, Known, DL);
1254 return Known.countMinLeadingZeros() >= IterCount;
1255}
1256
1257bool PolynomialMultiplyRecognize::keepsHighBitsZero(Value *V,
1258 unsigned IterCount) {
1259 // Assume that all inputs to the value have the high bits zero.
1260 // Check if the value itself preserves the zeros in the high bits.
1261 if (auto *C = dyn_cast<ConstantInt>(Val: V))
1262 return C->getValue().countl_zero() >= IterCount;
1263
1264 if (auto *I = dyn_cast<Instruction>(Val: V)) {
1265 switch (I->getOpcode()) {
1266 case Instruction::And:
1267 case Instruction::Or:
1268 case Instruction::Xor:
1269 case Instruction::LShr:
1270 case Instruction::Select:
1271 case Instruction::ICmp:
1272 case Instruction::PHI:
1273 case Instruction::ZExt:
1274 return true;
1275 }
1276 }
1277
1278 return false;
1279}
1280
1281bool PolynomialMultiplyRecognize::isOperandShifted(Instruction *I, Value *Op) {
1282 unsigned Opc = I->getOpcode();
1283 if (Opc == Instruction::Shl || Opc == Instruction::LShr)
1284 return Op != I->getOperand(i: 1);
1285 return true;
1286}
1287
1288bool PolynomialMultiplyRecognize::convertShiftsToLeft(BasicBlock *LoopB,
1289 BasicBlock *ExitB, unsigned IterCount) {
1290 Value *CIV = getCountIV(BB: LoopB);
1291 if (CIV == nullptr)
1292 return false;
1293 auto *CIVTy = dyn_cast<IntegerType>(Val: CIV->getType());
1294 if (CIVTy == nullptr)
1295 return false;
1296
1297 ValueSeq RShifts;
1298 ValueSeq Early, Late, Cycled;
1299
1300 // Find all value cycles that contain logical right shifts by 1.
1301 for (Instruction &I : *LoopB) {
1302 using namespace PatternMatch;
1303
1304 Value *V = nullptr;
1305 if (!match(V: &I, P: m_LShr(L: m_Value(V), R: m_One())))
1306 continue;
1307 ValueSeq C;
1308 if (!findCycle(Out: &I, In: V, Cycle&: C))
1309 continue;
1310
1311 // Found a cycle.
1312 C.insert(X: &I);
1313 classifyCycle(DivI: &I, Cycle&: C, Early, Late);
1314 Cycled.insert_range(R&: C);
1315 RShifts.insert(X: &I);
1316 }
1317
1318 // Find the set of all values affected by the shift cycles, i.e. all
1319 // cycled values, and (recursively) all their users.
1320 ValueSeq Users(llvm::from_range, Cycled);
1321 for (unsigned i = 0; i < Users.size(); ++i) {
1322 Value *V = Users[i];
1323 if (!isa<IntegerType>(Val: V->getType()))
1324 return false;
1325 auto *R = cast<Instruction>(Val: V);
1326 // If the instruction does not commute with shifts, the loop cannot
1327 // be unshifted.
1328 if (!commutesWithShift(I: R))
1329 return false;
1330 for (User *U : R->users()) {
1331 auto *T = cast<Instruction>(Val: U);
1332 // Skip users from outside of the loop. They will be handled later.
1333 // Also, skip the right-shifts and phi nodes, since they mix early
1334 // and late values.
1335 if (T->getParent() != LoopB || RShifts.count(key: T) || isa<PHINode>(Val: T))
1336 continue;
1337
1338 Users.insert(X: T);
1339 if (!classifyInst(UseI: T, Early, Late))
1340 return false;
1341 }
1342 }
1343
1344 if (Users.empty())
1345 return false;
1346
1347 // Verify that high bits remain zero.
1348 ValueSeq Internal(llvm::from_range, Users);
1349 ValueSeq Inputs;
1350 for (unsigned i = 0; i < Internal.size(); ++i) {
1351 auto *R = dyn_cast<Instruction>(Val: Internal[i]);
1352 if (!R)
1353 continue;
1354 for (Value *Op : R->operands()) {
1355 auto *T = dyn_cast<Instruction>(Val: Op);
1356 if (T && T->getParent() != LoopB)
1357 Inputs.insert(X: Op);
1358 else
1359 Internal.insert(X: Op);
1360 }
1361 }
1362 for (Value *V : Inputs)
1363 if (!highBitsAreZero(V, IterCount))
1364 return false;
1365 for (Value *V : Internal)
1366 if (!keepsHighBitsZero(V, IterCount))
1367 return false;
1368
1369 // Finally, the work can be done. Unshift each user.
1370 IRBuilder<> IRB(LoopB);
1371 std::map<Value*,Value*> ShiftMap;
1372
1373 using CastMapType = std::map<std::pair<Value *, Type *>, Value *>;
1374
1375 CastMapType CastMap;
1376
1377 auto upcast = [](CastMapType &CM, IRBuilder<> &IRB, Value *V,
1378 IntegerType *Ty) -> Value * {
1379 auto [H, Inserted] = CM.try_emplace(k: std::make_pair(x&: V, y&: Ty));
1380 if (Inserted)
1381 H->second = IRB.CreateIntCast(V, DestTy: Ty, isSigned: false);
1382 return H->second;
1383 };
1384
1385 for (auto I = LoopB->begin(), E = LoopB->end(); I != E; ++I) {
1386 using namespace PatternMatch;
1387
1388 if (isa<PHINode>(Val: I) || !Users.count(key: &*I))
1389 continue;
1390
1391 // Match lshr x, 1.
1392 Value *V = nullptr;
1393 if (match(V: &*I, P: m_LShr(L: m_Value(V), R: m_One()))) {
1394 replaceAllUsesOfWithIn(I: &*I, J: V, BB: LoopB);
1395 continue;
1396 }
1397 // For each non-cycled operand, replace it with the corresponding
1398 // value shifted left.
1399 for (auto &J : I->operands()) {
1400 Value *Op = J.get();
1401 if (!isOperandShifted(I: &*I, Op))
1402 continue;
1403 if (Users.count(key: Op))
1404 continue;
1405 // Skip shifting zeros.
1406 if (isa<ConstantInt>(Val: Op) && cast<ConstantInt>(Val: Op)->isZero())
1407 continue;
1408 // Check if we have already generated a shift for this value.
1409 auto F = ShiftMap.find(x: Op);
1410 Value *W = (F != ShiftMap.end()) ? F->second : nullptr;
1411 if (W == nullptr) {
1412 IRB.SetInsertPoint(&*I);
1413 // First, the shift amount will be CIV or CIV+1, depending on
1414 // whether the value is early or late. Instead of creating CIV+1,
1415 // do a single shift of the value.
1416 Value *ShAmt = CIV, *ShVal = Op;
1417 auto *VTy = cast<IntegerType>(Val: ShVal->getType());
1418 auto *ATy = cast<IntegerType>(Val: ShAmt->getType());
1419 if (Late.count(key: &*I))
1420 ShVal = IRB.CreateShl(LHS: Op, RHS: ConstantInt::get(Ty: VTy, V: 1));
1421 // Second, the types of the shifted value and the shift amount
1422 // must match.
1423 if (VTy != ATy) {
1424 if (VTy->getBitWidth() < ATy->getBitWidth())
1425 ShVal = upcast(CastMap, IRB, ShVal, ATy);
1426 else
1427 ShAmt = upcast(CastMap, IRB, ShAmt, VTy);
1428 }
1429 // Ready to generate the shift and memoize it.
1430 W = IRB.CreateShl(LHS: ShVal, RHS: ShAmt);
1431 ShiftMap.insert(x: std::make_pair(x&: Op, y&: W));
1432 }
1433 I->replaceUsesOfWith(From: Op, To: W);
1434 }
1435 }
1436
1437 // Update the users outside of the loop to account for having left
1438 // shifts. They would normally be shifted right in the loop, so shift
1439 // them right after the loop exit.
1440 // Take advantage of the loop-closed SSA form, which has all the post-
1441 // loop values in phi nodes.
1442 IRB.SetInsertPoint(ExitB->getFirstInsertionPt());
1443 for (auto P = ExitB->begin(), Q = ExitB->end(); P != Q; ++P) {
1444 if (!isa<PHINode>(Val: P))
1445 break;
1446 auto *PN = cast<PHINode>(Val&: P);
1447 Value *U = PN->getIncomingValueForBlock(BB: LoopB);
1448 if (!Users.count(key: U))
1449 continue;
1450 Value *S = IRB.CreateLShr(LHS: PN, RHS: ConstantInt::get(Ty: PN->getType(), V: IterCount));
1451 PN->replaceAllUsesWith(V: S);
1452 // The above RAUW will create
1453 // S = lshr S, IterCount
1454 // so we need to fix it back into
1455 // S = lshr PN, IterCount
1456 cast<User>(Val: S)->replaceUsesOfWith(From: S, To: PN);
1457 }
1458
1459 return true;
1460}
1461
1462void PolynomialMultiplyRecognize::cleanupLoopBody(BasicBlock *LoopB) {
1463 for (auto &I : *LoopB)
1464 if (Value *SV = simplifyInstruction(I: &I, Q: {DL, &TLI, &DT}))
1465 I.replaceAllUsesWith(V: SV);
1466
1467 for (Instruction &I : llvm::make_early_inc_range(Range&: *LoopB))
1468 RecursivelyDeleteTriviallyDeadInstructions(V: &I, TLI: &TLI);
1469}
1470
1471unsigned PolynomialMultiplyRecognize::getInverseMxN(unsigned QP) {
1472 // Arrays of coefficients of Q and the inverse, C.
1473 // Q[i] = coefficient at x^i.
1474 std::array<char,32> Q, C;
1475
1476 for (unsigned i = 0; i < 32; ++i) {
1477 Q[i] = QP & 1;
1478 QP >>= 1;
1479 }
1480 assert(Q[0] == 1);
1481
1482 // Find C, such that
1483 // (Q[n]*x^n + ... + Q[1]*x + Q[0]) * (C[n]*x^n + ... + C[1]*x + C[0]) = 1
1484 //
1485 // For it to have a solution, Q[0] must be 1. Since this is Z2[x], the
1486 // operations * and + are & and ^ respectively.
1487 //
1488 // Find C[i] recursively, by comparing i-th coefficient in the product
1489 // with 0 (or 1 for i=0).
1490 //
1491 // C[0] = 1, since C[0] = Q[0], and Q[0] = 1.
1492 C[0] = 1;
1493 for (unsigned i = 1; i < 32; ++i) {
1494 // Solve for C[i] in:
1495 // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i]Q[0] = 0
1496 // This is equivalent to
1497 // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i] = 0
1498 // which is
1499 // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] = C[i]
1500 unsigned T = 0;
1501 for (unsigned j = 0; j < i; ++j)
1502 T = T ^ (C[j] & Q[i-j]);
1503 C[i] = T;
1504 }
1505
1506 unsigned QV = 0;
1507 for (unsigned i = 0; i < 32; ++i)
1508 if (C[i])
1509 QV |= (1 << i);
1510
1511 return QV;
1512}
1513
1514Value *PolynomialMultiplyRecognize::generate(BasicBlock::iterator At,
1515 ParsedValues &PV) {
1516 IRBuilder<> B(&*At);
1517 Module *M = At->getParent()->getParent()->getParent();
1518 Function *PMF =
1519 Intrinsic::getOrInsertDeclaration(M, id: Intrinsic::hexagon_M4_pmpyw);
1520
1521 Value *P = PV.P, *Q = PV.Q, *P0 = P;
1522 unsigned IC = PV.IterCount;
1523
1524 if (PV.M != nullptr)
1525 P0 = P = B.CreateXor(LHS: P, RHS: PV.M);
1526
1527 // Create a bit mask to clear the high bits beyond IterCount.
1528 auto *BMI = ConstantInt::get(Ty: P->getType(), V: APInt::getLowBitsSet(numBits: 32, loBitsSet: IC));
1529
1530 if (PV.IterCount != 32)
1531 P = B.CreateAnd(LHS: P, RHS: BMI);
1532
1533 if (PV.Inv) {
1534 auto *QI = dyn_cast<ConstantInt>(Val: PV.Q);
1535 assert(QI && QI->getBitWidth() <= 32);
1536
1537 // Again, clearing bits beyond IterCount.
1538 unsigned M = (1 << PV.IterCount) - 1;
1539 unsigned Tmp = (QI->getZExtValue() | 1) & M;
1540 unsigned QV = getInverseMxN(QP: Tmp) & M;
1541 auto *QVI = ConstantInt::get(Ty: QI->getType(), V: QV);
1542 P = B.CreateCall(Callee: PMF, Args: {P, QVI});
1543 P = B.CreateTrunc(V: P, DestTy: QI->getType());
1544 if (IC != 32)
1545 P = B.CreateAnd(LHS: P, RHS: BMI);
1546 }
1547
1548 Value *R = B.CreateCall(Callee: PMF, Args: {P, Q});
1549
1550 if (PV.M != nullptr)
1551 R = B.CreateXor(LHS: R, RHS: B.CreateIntCast(V: P0, DestTy: R->getType(), isSigned: false));
1552
1553 return R;
1554}
1555
1556static bool hasZeroSignBit(const Value *V) {
1557 if (const auto *CI = dyn_cast<const ConstantInt>(Val: V))
1558 return CI->getValue().isNonNegative();
1559 const Instruction *I = dyn_cast<const Instruction>(Val: V);
1560 if (!I)
1561 return false;
1562 switch (I->getOpcode()) {
1563 case Instruction::LShr:
1564 if (const auto SI = dyn_cast<const ConstantInt>(Val: I->getOperand(i: 1)))
1565 return SI->getZExtValue() > 0;
1566 return false;
1567 case Instruction::Or:
1568 case Instruction::Xor:
1569 return hasZeroSignBit(V: I->getOperand(i: 0)) &&
1570 hasZeroSignBit(V: I->getOperand(i: 1));
1571 case Instruction::And:
1572 return hasZeroSignBit(V: I->getOperand(i: 0)) ||
1573 hasZeroSignBit(V: I->getOperand(i: 1));
1574 }
1575 return false;
1576}
1577
1578void PolynomialMultiplyRecognize::setupPreSimplifier(Simplifier &S) {
1579 S.addRule(N: "sink-zext",
1580 // Sink zext past bitwise operations.
1581 F: [](Instruction *I, Module &M) -> Value * {
1582 if (I->getOpcode() != Instruction::ZExt)
1583 return nullptr;
1584 Instruction *T = dyn_cast<Instruction>(Val: I->getOperand(i: 0));
1585 if (!T)
1586 return nullptr;
1587 switch (T->getOpcode()) {
1588 case Instruction::And:
1589 case Instruction::Or:
1590 case Instruction::Xor:
1591 break;
1592 default:
1593 return nullptr;
1594 }
1595 IRBuilder<> B(M);
1596 return B.CreateBinOp(
1597 Opc: cast<BinaryOperator>(Val: T)->getOpcode(),
1598 LHS: B.CreateZExt(V: T->getOperand(i: 0), DestTy: I->getType()),
1599 RHS: B.CreateZExt(V: T->getOperand(i: 1), DestTy: I->getType()));
1600 });
1601 S.addRule(N: "xor/and -> and/xor",
1602 // (xor (and x a) (and y a)) -> (and (xor x y) a)
1603 F: [](Instruction *I, Module &M) -> Value * {
1604 if (I->getOpcode() != Instruction::Xor)
1605 return nullptr;
1606 Instruction *And0 = dyn_cast<Instruction>(Val: I->getOperand(i: 0));
1607 Instruction *And1 = dyn_cast<Instruction>(Val: I->getOperand(i: 1));
1608 if (!And0 || !And1)
1609 return nullptr;
1610 if (And0->getOpcode() != Instruction::And ||
1611 And1->getOpcode() != Instruction::And)
1612 return nullptr;
1613 if (And0->getOperand(i: 1) != And1->getOperand(i: 1))
1614 return nullptr;
1615 IRBuilder<> B(M);
1616 return B.CreateAnd(
1617 LHS: B.CreateXor(LHS: And0->getOperand(i: 0), RHS: And1->getOperand(i: 0)),
1618 RHS: And0->getOperand(i: 1));
1619 });
1620 S.addRule(
1621 N: "sink binop into select",
1622 // (Op (select c x y) z) -> (select c (Op x z) (Op y z))
1623 // (Op x (select c y z)) -> (select c (Op x y) (Op x z))
1624 F: [](Instruction *I, Module &M) -> Value * {
1625 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: I);
1626 if (!BO)
1627 return nullptr;
1628 Instruction::BinaryOps Op = BO->getOpcode();
1629 if (SelectInst *Sel = dyn_cast<SelectInst>(Val: BO->getOperand(i_nocapture: 0))) {
1630 IRBuilder<> B(M);
1631 Value *X = Sel->getTrueValue(), *Y = Sel->getFalseValue();
1632 Value *Z = BO->getOperand(i_nocapture: 1);
1633 return B.CreateSelect(C: Sel->getCondition(), True: B.CreateBinOp(Opc: Op, LHS: X, RHS: Z),
1634 False: B.CreateBinOp(Opc: Op, LHS: Y, RHS: Z));
1635 }
1636 if (SelectInst *Sel = dyn_cast<SelectInst>(Val: BO->getOperand(i_nocapture: 1))) {
1637 IRBuilder<> B(M);
1638 Value *X = BO->getOperand(i_nocapture: 0);
1639 Value *Y = Sel->getTrueValue(), *Z = Sel->getFalseValue();
1640 return B.CreateSelect(C: Sel->getCondition(), True: B.CreateBinOp(Opc: Op, LHS: X, RHS: Y),
1641 False: B.CreateBinOp(Opc: Op, LHS: X, RHS: Z));
1642 }
1643 return nullptr;
1644 });
1645 S.addRule(
1646 N: "fold select-select",
1647 // (select c (select c x y) z) -> (select c x z)
1648 // (select c x (select c y z)) -> (select c x z)
1649 F: [](Instruction *I, Module &M) -> Value * {
1650 SelectInst *Sel = dyn_cast<SelectInst>(Val: I);
1651 if (!Sel)
1652 return nullptr;
1653 IRBuilder<> B(M);
1654 Value *C = Sel->getCondition();
1655 if (SelectInst *Sel0 = dyn_cast<SelectInst>(Val: Sel->getTrueValue())) {
1656 if (Sel0->getCondition() == C)
1657 return B.CreateSelect(C, True: Sel0->getTrueValue(),
1658 False: Sel->getFalseValue());
1659 }
1660 if (SelectInst *Sel1 = dyn_cast<SelectInst>(Val: Sel->getFalseValue())) {
1661 if (Sel1->getCondition() == C)
1662 return B.CreateSelect(C, True: Sel->getTrueValue(),
1663 False: Sel1->getFalseValue());
1664 }
1665 return nullptr;
1666 });
1667 S.addRule(N: "or-signbit -> xor-signbit",
1668 // (or (lshr x 1) 0x800.0) -> (xor (lshr x 1) 0x800.0)
1669 F: [](Instruction *I, Module &M) -> Value * {
1670 if (I->getOpcode() != Instruction::Or)
1671 return nullptr;
1672 ConstantInt *Msb = dyn_cast<ConstantInt>(Val: I->getOperand(i: 1));
1673 if (!Msb || !Msb->getValue().isSignMask())
1674 return nullptr;
1675 if (!hasZeroSignBit(V: I->getOperand(i: 0)))
1676 return nullptr;
1677 return IRBuilder<>(M).CreateXor(LHS: I->getOperand(i: 0), RHS: Msb);
1678 });
1679 S.addRule(N: "sink lshr into binop",
1680 // (lshr (BitOp x y) c) -> (BitOp (lshr x c) (lshr y c))
1681 F: [](Instruction *I, Module &M) -> Value * {
1682 if (I->getOpcode() != Instruction::LShr)
1683 return nullptr;
1684 BinaryOperator *BitOp =
1685 dyn_cast<BinaryOperator>(Val: I->getOperand(i: 0));
1686 if (!BitOp)
1687 return nullptr;
1688 switch (BitOp->getOpcode()) {
1689 case Instruction::And:
1690 case Instruction::Or:
1691 case Instruction::Xor:
1692 break;
1693 default:
1694 return nullptr;
1695 }
1696 IRBuilder<> B(M);
1697 Value *S = I->getOperand(i: 1);
1698 return B.CreateBinOp(Opc: BitOp->getOpcode(),
1699 LHS: B.CreateLShr(LHS: BitOp->getOperand(i_nocapture: 0), RHS: S),
1700 RHS: B.CreateLShr(LHS: BitOp->getOperand(i_nocapture: 1), RHS: S));
1701 });
1702 S.addRule(N: "expose bitop-const",
1703 // (BitOp1 (BitOp2 x a) b) -> (BitOp2 x (BitOp1 a b))
1704 F: [](Instruction *I, Module &M) -> Value * {
1705 auto IsBitOp = [](unsigned Op) -> bool {
1706 switch (Op) {
1707 case Instruction::And:
1708 case Instruction::Or:
1709 case Instruction::Xor:
1710 return true;
1711 }
1712 return false;
1713 };
1714 BinaryOperator *BitOp1 = dyn_cast<BinaryOperator>(Val: I);
1715 if (!BitOp1 || !IsBitOp(BitOp1->getOpcode()))
1716 return nullptr;
1717 BinaryOperator *BitOp2 =
1718 dyn_cast<BinaryOperator>(Val: BitOp1->getOperand(i_nocapture: 0));
1719 if (!BitOp2 || !IsBitOp(BitOp2->getOpcode()))
1720 return nullptr;
1721 ConstantInt *CA = dyn_cast<ConstantInt>(Val: BitOp2->getOperand(i_nocapture: 1));
1722 ConstantInt *CB = dyn_cast<ConstantInt>(Val: BitOp1->getOperand(i_nocapture: 1));
1723 if (!CA || !CB)
1724 return nullptr;
1725 IRBuilder<> B(M);
1726 Value *X = BitOp2->getOperand(i_nocapture: 0);
1727 return B.CreateBinOp(Opc: BitOp2->getOpcode(), LHS: X,
1728 RHS: B.CreateBinOp(Opc: BitOp1->getOpcode(), LHS: CA, RHS: CB));
1729 });
1730 S.addRule(N: "select with trunc cond to select with icmp cond",
1731 // select (trunc x to i1) -> select (icmp ne (and x, 1), 0)
1732 // select (xor (trunc x to i1) 1) -> select (icmp eq (and x, 1), 0)
1733 F: [](Instruction *I, Module &M) -> Value * {
1734 SelectInst *Sel = dyn_cast<SelectInst>(Val: I);
1735 if (!Sel)
1736 return nullptr;
1737 Value *C = Sel->getCondition();
1738 Value *X;
1739 using namespace PatternMatch;
1740 if (!(match(V: C, P: m_Trunc(Op: m_Value(V&: X))) ||
1741 match(V: C, P: m_Not(V: m_Trunc(Op: m_Value(V&: X))))))
1742 return nullptr;
1743
1744 IRBuilder<> B(M);
1745 Type *Ty = X->getType();
1746 Value *And = B.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty, V: 1));
1747 Value *Icmp = B.CreateICmp(P: isa<TruncInst>(Val: C) ? ICmpInst::ICMP_NE
1748 : ICmpInst::ICMP_EQ,
1749 LHS: And, RHS: ConstantInt::get(Ty, V: 0));
1750 return B.CreateSelect(C: Icmp, True: Sel->getTrueValue(),
1751 False: Sel->getFalseValue());
1752 });
1753}
1754
1755void PolynomialMultiplyRecognize::setupPostSimplifier(Simplifier &S) {
1756 S.addRule(N: "(and (xor (and x a) y) b) -> (and (xor x y) b), if b == b&a",
1757 F: [](Instruction *I, Module &M) -> Value * {
1758 if (I->getOpcode() != Instruction::And)
1759 return nullptr;
1760 Instruction *Xor = dyn_cast<Instruction>(Val: I->getOperand(i: 0));
1761 ConstantInt *C0 = dyn_cast<ConstantInt>(Val: I->getOperand(i: 1));
1762 if (!Xor || !C0)
1763 return nullptr;
1764 if (Xor->getOpcode() != Instruction::Xor)
1765 return nullptr;
1766 Instruction *And0 = dyn_cast<Instruction>(Val: Xor->getOperand(i: 0));
1767 Instruction *And1 = dyn_cast<Instruction>(Val: Xor->getOperand(i: 1));
1768 // Pick the first non-null and.
1769 if (!And0 || And0->getOpcode() != Instruction::And)
1770 std::swap(a&: And0, b&: And1);
1771 ConstantInt *C1 = dyn_cast<ConstantInt>(Val: And0->getOperand(i: 1));
1772 if (!C1)
1773 return nullptr;
1774 uint32_t V0 = C0->getZExtValue();
1775 uint32_t V1 = C1->getZExtValue();
1776 if (V0 != (V0 & V1))
1777 return nullptr;
1778 IRBuilder<> B(M);
1779 return B.CreateAnd(LHS: B.CreateXor(LHS: And0->getOperand(i: 0), RHS: And1), RHS: C0);
1780 });
1781}
1782
1783bool PolynomialMultiplyRecognize::recognize() {
1784 LLVM_DEBUG(dbgs() << "Starting PolynomialMultiplyRecognize on loop\n"
1785 << *CurLoop << '\n');
1786 // Restrictions:
1787 // - The loop must consist of a single block.
1788 // - The iteration count must be known at compile-time.
1789 // - The loop must have an induction variable starting from 0, and
1790 // incremented in each iteration of the loop.
1791 BasicBlock *LoopB = CurLoop->getHeader();
1792 LLVM_DEBUG(dbgs() << "Loop header:\n" << *LoopB);
1793
1794 if (LoopB != CurLoop->getLoopLatch())
1795 return false;
1796 BasicBlock *ExitB = CurLoop->getExitBlock();
1797 if (ExitB == nullptr)
1798 return false;
1799 BasicBlock *EntryB = CurLoop->getLoopPreheader();
1800 if (EntryB == nullptr)
1801 return false;
1802
1803 unsigned IterCount = 0;
1804 const SCEV *CT = SE.getBackedgeTakenCount(L: CurLoop);
1805 if (isa<SCEVCouldNotCompute>(Val: CT))
1806 return false;
1807 if (auto *CV = dyn_cast<SCEVConstant>(Val: CT))
1808 IterCount = CV->getValue()->getZExtValue() + 1;
1809
1810 Value *CIV = getCountIV(BB: LoopB);
1811 if (CIV == nullptr)
1812 return false;
1813 ParsedValues PV;
1814 Simplifier PreSimp;
1815 PV.IterCount = IterCount;
1816 LLVM_DEBUG(dbgs() << "Loop IV: " << *CIV << "\nIterCount: " << IterCount
1817 << '\n');
1818
1819 setupPreSimplifier(PreSimp);
1820
1821 // Perform a preliminary scan of select instructions to see if any of them
1822 // looks like a generator of the polynomial multiply steps. Assume that a
1823 // loop can only contain a single transformable operation, so stop the
1824 // traversal after the first reasonable candidate was found.
1825 // XXX: Currently this approach can modify the loop before being 100% sure
1826 // that the transformation can be carried out.
1827 bool FoundPreScan = false;
1828 auto FeedsPHI = [LoopB](const Value *V) -> bool {
1829 for (const Value *U : V->users()) {
1830 if (const auto *P = dyn_cast<const PHINode>(Val: U))
1831 if (P->getParent() == LoopB)
1832 return true;
1833 }
1834 return false;
1835 };
1836 for (Instruction &In : *LoopB) {
1837 SelectInst *SI = dyn_cast<SelectInst>(Val: &In);
1838 if (!SI || !FeedsPHI(SI))
1839 continue;
1840
1841 Simplifier::Context C(SI);
1842 Value *T = PreSimp.simplify(C);
1843 SelectInst *SelI = (T && isa<SelectInst>(Val: T)) ? cast<SelectInst>(Val: T) : SI;
1844 LLVM_DEBUG(dbgs() << "scanSelect(pre-scan): " << PE(C, SelI) << '\n');
1845 if (scanSelect(SelI, LoopB, PrehB: EntryB, CIV, PV, PreScan: true)) {
1846 FoundPreScan = true;
1847 if (SelI != SI) {
1848 Value *NewSel = C.materialize(B: LoopB, At: SI->getIterator());
1849 SI->replaceAllUsesWith(V: NewSel);
1850 RecursivelyDeleteTriviallyDeadInstructions(V: SI, TLI: &TLI);
1851 }
1852 break;
1853 }
1854 }
1855
1856 if (!FoundPreScan) {
1857 LLVM_DEBUG(dbgs() << "Have not found candidates for pmpy\n");
1858 return false;
1859 }
1860
1861 if (!PV.Left) {
1862 // The right shift version actually only returns the higher bits of
1863 // the result (each iteration discards the LSB). If we want to convert it
1864 // to a left-shifting loop, the working data type must be at least as
1865 // wide as the target's pmpy instruction.
1866 if (!promoteTypes(LoopB, ExitB))
1867 return false;
1868 // Run post-promotion simplifications.
1869 Simplifier PostSimp;
1870 setupPostSimplifier(PostSimp);
1871 for (Instruction &In : *LoopB) {
1872 SelectInst *SI = dyn_cast<SelectInst>(Val: &In);
1873 if (!SI || !FeedsPHI(SI))
1874 continue;
1875 Simplifier::Context C(SI);
1876 Value *T = PostSimp.simplify(C);
1877 SelectInst *SelI = dyn_cast_or_null<SelectInst>(Val: T);
1878 if (SelI != SI) {
1879 Value *NewSel = C.materialize(B: LoopB, At: SI->getIterator());
1880 SI->replaceAllUsesWith(V: NewSel);
1881 RecursivelyDeleteTriviallyDeadInstructions(V: SI, TLI: &TLI);
1882 }
1883 break;
1884 }
1885
1886 if (!convertShiftsToLeft(LoopB, ExitB, IterCount))
1887 return false;
1888 cleanupLoopBody(LoopB);
1889 }
1890
1891 // Scan the loop again, find the generating select instruction.
1892 bool FoundScan = false;
1893 for (Instruction &In : *LoopB) {
1894 SelectInst *SelI = dyn_cast<SelectInst>(Val: &In);
1895 if (!SelI)
1896 continue;
1897 LLVM_DEBUG(dbgs() << "scanSelect: " << *SelI << '\n');
1898 FoundScan = scanSelect(SelI, LoopB, PrehB: EntryB, CIV, PV, PreScan: false);
1899 if (FoundScan)
1900 break;
1901 }
1902 assert(FoundScan);
1903
1904 LLVM_DEBUG({
1905 StringRef PP = (PV.M ? "(P+M)" : "P");
1906 if (!PV.Inv)
1907 dbgs() << "Found pmpy idiom: R = " << PP << ".Q\n";
1908 else
1909 dbgs() << "Found inverse pmpy idiom: R = (" << PP << "/Q).Q) + "
1910 << PP << "\n";
1911 dbgs() << " Res:" << *PV.Res << "\n P:" << *PV.P << "\n";
1912 if (PV.M)
1913 dbgs() << " M:" << *PV.M << "\n";
1914 dbgs() << " Q:" << *PV.Q << "\n";
1915 dbgs() << " Iteration count:" << PV.IterCount << "\n";
1916 });
1917
1918 BasicBlock::iterator At(EntryB->getTerminator());
1919 Value *PM = generate(At, PV);
1920 if (PM == nullptr)
1921 return false;
1922
1923 if (PM->getType() != PV.Res->getType())
1924 PM = IRBuilder<>(&*At).CreateIntCast(V: PM, DestTy: PV.Res->getType(), isSigned: false);
1925
1926 PV.Res->replaceAllUsesWith(V: PM);
1927 PV.Res->eraseFromParent();
1928 return true;
1929}
1930
1931int HexagonLoopIdiomRecognize::getSCEVStride(const SCEVAddRecExpr *S) {
1932 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Val: S->getOperand(i: 1)))
1933 return SC->getAPInt().getSExtValue();
1934 return 0;
1935}
1936
1937bool HexagonLoopIdiomRecognize::isLegalStore(Loop *CurLoop, StoreInst *SI) {
1938 // Allow volatile stores if HexagonVolatileMemcpy is enabled.
1939 if (!(SI->isVolatile() && HexagonVolatileMemcpy) && !SI->isSimple())
1940 return false;
1941
1942 Value *StoredVal = SI->getValueOperand();
1943 Value *StorePtr = SI->getPointerOperand();
1944
1945 // Reject stores that are so large that they overflow an unsigned.
1946 uint64_t SizeInBits = DL->getTypeSizeInBits(Ty: StoredVal->getType());
1947 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
1948 return false;
1949
1950 // See if the pointer expression is an AddRec like {base,+,1} on the current
1951 // loop, which indicates a strided store. If we have something else, it's a
1952 // random store we can't handle.
1953 auto *StoreEv = dyn_cast<SCEVAddRecExpr>(Val: SE->getSCEV(V: StorePtr));
1954 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) {
1955 ORE.emit(RemarkBuilder: [&]() {
1956 return OptimizationRemarkMissed(DEBUG_TYPE, "NonAffineStorePtr",
1957 SI->getDebugLoc(), SI->getParent())
1958 << "store pointer is not an affine AddRec";
1959 });
1960 return false;
1961 }
1962
1963 // Check to see if the stride matches the size of the store. If so, then we
1964 // know that every byte is touched in the loop.
1965 int Stride = getSCEVStride(S: StoreEv);
1966 if (Stride == 0)
1967 return false;
1968 unsigned StoreSize = DL->getTypeStoreSize(Ty: SI->getValueOperand()->getType());
1969 if (StoreSize != unsigned(std::abs(x: Stride))) {
1970 ORE.emit(RemarkBuilder: [&]() {
1971 return OptimizationRemarkMissed(DEBUG_TYPE, "StrideSizeMismatch",
1972 SI->getDebugLoc(), SI->getParent())
1973 << "stride does not match store size";
1974 });
1975 return false;
1976 }
1977
1978 // The store must be feeding a non-volatile load.
1979 LoadInst *LI = dyn_cast<LoadInst>(Val: SI->getValueOperand());
1980 if (!LI || !LI->isSimple()) {
1981 ORE.emit(RemarkBuilder: [&]() {
1982 return OptimizationRemarkMissed(DEBUG_TYPE, "StoreNotFeedingLoad",
1983 SI->getDebugLoc(), SI->getParent())
1984 << "store value is not a simple load";
1985 });
1986 return false;
1987 }
1988
1989 // See if the pointer expression is an AddRec like {base,+,1} on the current
1990 // loop, which indicates a strided load. If we have something else, it's a
1991 // random load we can't handle.
1992 Value *LoadPtr = LI->getPointerOperand();
1993 auto *LoadEv = dyn_cast<SCEVAddRecExpr>(Val: SE->getSCEV(V: LoadPtr));
1994 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) {
1995 ORE.emit(RemarkBuilder: [&]() {
1996 return OptimizationRemarkMissed(DEBUG_TYPE, "NonAffineLoadPtr",
1997 LI->getDebugLoc(), LI->getParent())
1998 << "load pointer is not an affine AddRec";
1999 });
2000 return false;
2001 }
2002
2003 // The store and load must share the same stride.
2004 if (StoreEv->getOperand(i: 1) != LoadEv->getOperand(i: 1))
2005 return false;
2006
2007 // Success. This store can be converted into a memcpy.
2008 return true;
2009}
2010
2011/// mayLoopAccessLocation - Return true if the specified loop might access the
2012/// specified pointer location, which is a loop-strided access. The 'Access'
2013/// argument specifies what the verboten forms of access are (read or write).
2014static bool
2015mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
2016 const SCEV *BECount, unsigned StoreSize,
2017 AliasAnalysis &AA,
2018 SmallPtrSetImpl<Instruction *> &Ignored) {
2019 // Get the location that may be stored across the loop. Since the access
2020 // is strided positively through memory, we say that the modified location
2021 // starts at the pointer and has infinite size.
2022 LocationSize AccessSize = LocationSize::afterPointer();
2023
2024 // If the loop iterates a fixed number of times, we can refine the access
2025 // size to be exactly the size of the memset, which is (BECount+1)*StoreSize
2026 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(Val: BECount))
2027 AccessSize = LocationSize::precise(Value: (BECst->getValue()->getZExtValue() + 1) *
2028 StoreSize);
2029
2030 // TODO: For this to be really effective, we have to dive into the pointer
2031 // operand in the store. Store to &A[i] of 100 will always return may alias
2032 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
2033 // which will then no-alias a store to &A[100].
2034 MemoryLocation StoreLoc(Ptr, AccessSize);
2035
2036 for (auto *B : L->blocks())
2037 for (auto &I : *B)
2038 if (Ignored.count(Ptr: &I) == 0 &&
2039 isModOrRefSet(MRI: AA.getModRefInfo(I: &I, OptLoc: StoreLoc) & Access))
2040 return true;
2041
2042 return false;
2043}
2044
2045void HexagonLoopIdiomRecognize::collectStores(Loop *CurLoop, BasicBlock *BB,
2046 SmallVectorImpl<StoreInst*> &Stores) {
2047 Stores.clear();
2048 for (Instruction &I : *BB)
2049 if (StoreInst *SI = dyn_cast<StoreInst>(Val: &I))
2050 if (isLegalStore(CurLoop, SI))
2051 Stores.push_back(Elt: SI);
2052}
2053
2054bool HexagonLoopIdiomRecognize::processCopyingStore(Loop *CurLoop,
2055 StoreInst *SI, const SCEV *BECount) {
2056 assert((SI->isSimple() || (SI->isVolatile() && HexagonVolatileMemcpy)) &&
2057 "Expected only non-volatile stores, or Hexagon-specific memcpy"
2058 "to volatile destination.");
2059
2060 Value *StorePtr = SI->getPointerOperand();
2061 auto *StoreEv = cast<SCEVAddRecExpr>(Val: SE->getSCEV(V: StorePtr));
2062 unsigned Stride = getSCEVStride(S: StoreEv);
2063 unsigned StoreSize = DL->getTypeStoreSize(Ty: SI->getValueOperand()->getType());
2064 if (Stride != StoreSize)
2065 return false;
2066
2067 // See if the pointer expression is an AddRec like {base,+,1} on the current
2068 // loop, which indicates a strided load. If we have something else, it's a
2069 // random load we can't handle.
2070 auto *LI = cast<LoadInst>(Val: SI->getValueOperand());
2071 auto *LoadEv = cast<SCEVAddRecExpr>(Val: SE->getSCEV(V: LI->getPointerOperand()));
2072
2073 // The trip count of the loop and the base pointer of the addrec SCEV is
2074 // guaranteed to be loop invariant, which means that it should dominate the
2075 // header. This allows us to insert code for it in the preheader.
2076 BasicBlock *Preheader = CurLoop->getLoopPreheader();
2077 Instruction *ExpPt = Preheader->getTerminator();
2078 IRBuilder<> Builder(ExpPt);
2079 SCEVExpander Expander(*SE, "hexagon-loop-idiom");
2080
2081 Type *IntPtrTy = Builder.getIntPtrTy(DL: *DL, AddrSpace: SI->getPointerAddressSpace());
2082
2083 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
2084 // this into a memcpy/memmove in the loop preheader now if we want. However,
2085 // this would be unsafe to do if there is anything else in the loop that may
2086 // read or write the memory region we're storing to. For memcpy, this
2087 // includes the load that feeds the stores. Check for an alias by generating
2088 // the base address and checking everything.
2089 Value *StoreBasePtr = Expander.expandCodeFor(SH: StoreEv->getStart(),
2090 Ty: Builder.getPtrTy(AddrSpace: SI->getPointerAddressSpace()), I: ExpPt);
2091 Value *LoadBasePtr = nullptr;
2092
2093 bool Overlap = false;
2094 bool DestVolatile = SI->isVolatile();
2095 Type *BECountTy = BECount->getType();
2096
2097 if (DestVolatile) {
2098 // The trip count must fit in i32, since it is the type of the "num_words"
2099 // argument to hexagon_memcpy_forward_vp4cp4n2.
2100 if (StoreSize != 4 || DL->getTypeSizeInBits(Ty: BECountTy) > 32) {
2101CleanupAndExit:
2102 // If we generated new code for the base pointer, clean up.
2103 Expander.clear();
2104 if (StoreBasePtr && (LoadBasePtr != StoreBasePtr)) {
2105 RecursivelyDeleteTriviallyDeadInstructions(V: StoreBasePtr, TLI);
2106 StoreBasePtr = nullptr;
2107 }
2108 if (LoadBasePtr) {
2109 RecursivelyDeleteTriviallyDeadInstructions(V: LoadBasePtr, TLI);
2110 LoadBasePtr = nullptr;
2111 }
2112 return false;
2113 }
2114 }
2115
2116 SmallPtrSet<Instruction*, 2> Ignore1;
2117 Ignore1.insert(Ptr: SI);
2118 if (mayLoopAccessLocation(Ptr: StoreBasePtr, Access: ModRefInfo::ModRef, L: CurLoop, BECount,
2119 StoreSize, AA&: *AA, Ignored&: Ignore1)) {
2120 // Check if the load is the offending instruction.
2121 Ignore1.insert(Ptr: LI);
2122 if (mayLoopAccessLocation(Ptr: StoreBasePtr, Access: ModRefInfo::ModRef, L: CurLoop,
2123 BECount, StoreSize, AA&: *AA, Ignored&: Ignore1)) {
2124 // Still bad. Nothing we can do.
2125 ORE.emit(RemarkBuilder: [&]() {
2126 return OptimizationRemarkMissed(DEBUG_TYPE, "MemoryAlias",
2127 SI->getDebugLoc(), SI->getParent())
2128 << "memory aliasing prevents memcpy/memmove";
2129 });
2130 goto CleanupAndExit;
2131 }
2132 // It worked with the load ignored.
2133 Overlap = true;
2134 }
2135
2136 if (!Overlap) {
2137 if (DisableMemcpyIdiom || !HasMemcpy) {
2138 ORE.emit(RemarkBuilder: [&]() {
2139 return OptimizationRemarkMissed(DEBUG_TYPE, "MemcpyDisabled",
2140 SI->getDebugLoc(), SI->getParent())
2141 << "memcpy idiom is disabled or unavailable";
2142 });
2143 goto CleanupAndExit;
2144 }
2145 } else {
2146 // Don't generate memmove if this function will be inlined. This is
2147 // because the caller will undergo this transformation after inlining.
2148 Function *Func = CurLoop->getHeader()->getParent();
2149 if (Func->hasFnAttribute(Kind: Attribute::AlwaysInline))
2150 goto CleanupAndExit;
2151
2152 // In case of a memmove, the call to memmove will be executed instead
2153 // of the loop, so we need to make sure that there is nothing else in
2154 // the loop than the load, store and instructions that these two depend
2155 // on.
2156 SmallVector<Instruction*,2> Insts;
2157 Insts.push_back(Elt: SI);
2158 Insts.push_back(Elt: LI);
2159 if (!coverLoop(L: CurLoop, Insts)) {
2160 ORE.emit(RemarkBuilder: [&]() {
2161 return OptimizationRemarkMissed(DEBUG_TYPE, "ExtraLoopInstructions",
2162 SI->getDebugLoc(), SI->getParent())
2163 << "loop contains instructions beyond load/store pair";
2164 });
2165 goto CleanupAndExit;
2166 }
2167
2168 if (DisableMemmoveIdiom || !HasMemmove) {
2169 ORE.emit(RemarkBuilder: [&]() {
2170 return OptimizationRemarkMissed(DEBUG_TYPE, "MemmoveDisabled",
2171 SI->getDebugLoc(), SI->getParent())
2172 << "memmove idiom is disabled or unavailable";
2173 });
2174 goto CleanupAndExit;
2175 }
2176 bool IsNested = CurLoop->getParentLoop() != nullptr;
2177 if (IsNested && OnlyNonNestedMemmove) {
2178 ORE.emit(RemarkBuilder: [&]() {
2179 return OptimizationRemarkMissed(DEBUG_TYPE, "NestedLoop",
2180 SI->getDebugLoc(), SI->getParent())
2181 << "memmove skipped for nested loop";
2182 });
2183 goto CleanupAndExit;
2184 }
2185 }
2186
2187 // For a memcpy, we have to make sure that the input array is not being
2188 // mutated by the loop.
2189 LoadBasePtr = Expander.expandCodeFor(SH: LoadEv->getStart(),
2190 Ty: Builder.getPtrTy(AddrSpace: LI->getPointerAddressSpace()), I: ExpPt);
2191
2192 SmallPtrSet<Instruction*, 2> Ignore2;
2193 Ignore2.insert(Ptr: SI);
2194 if (mayLoopAccessLocation(Ptr: LoadBasePtr, Access: ModRefInfo::Mod, L: CurLoop, BECount,
2195 StoreSize, AA&: *AA, Ignored&: Ignore2))
2196 goto CleanupAndExit;
2197
2198 // Check the stride.
2199 bool StridePos = getSCEVStride(S: LoadEv) >= 0;
2200
2201 // Currently, the volatile memcpy only emulates traversing memory forward.
2202 if (!StridePos && DestVolatile)
2203 goto CleanupAndExit;
2204
2205 bool RuntimeCheck = (Overlap || DestVolatile);
2206
2207 BasicBlock *ExitB;
2208 if (RuntimeCheck) {
2209 // The runtime check needs a single exit block.
2210 SmallVector<BasicBlock*, 8> ExitBlocks;
2211 CurLoop->getUniqueExitBlocks(ExitBlocks);
2212 if (ExitBlocks.size() != 1)
2213 goto CleanupAndExit;
2214 ExitB = ExitBlocks[0];
2215 }
2216
2217 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
2218 // pointer size if it isn't already.
2219 LLVMContext &Ctx = SI->getContext();
2220 BECount = SE->getTruncateOrZeroExtend(V: BECount, Ty: IntPtrTy);
2221 DebugLoc DLoc = SI->getDebugLoc();
2222
2223 const SCEV *NumBytesS =
2224 SE->getAddExpr(LHS: BECount, RHS: SE->getOne(Ty: IntPtrTy), Flags: SCEV::FlagNUW);
2225 if (StoreSize != 1)
2226 NumBytesS = SE->getMulExpr(LHS: NumBytesS, RHS: SE->getConstant(Ty: IntPtrTy, V: StoreSize),
2227 Flags: SCEV::FlagNUW);
2228 Value *NumBytes = Expander.expandCodeFor(SH: NumBytesS, Ty: IntPtrTy, I: ExpPt);
2229 if (Instruction *In = dyn_cast<Instruction>(Val: NumBytes))
2230 if (Value *Simp = simplifyInstruction(I: In, Q: {*DL, TLI, DT}))
2231 NumBytes = Simp;
2232
2233 CallInst *NewCall;
2234
2235 if (RuntimeCheck) {
2236 unsigned Threshold = RuntimeMemSizeThreshold;
2237 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: NumBytes)) {
2238 uint64_t C = CI->getZExtValue();
2239 if (Threshold != 0 && C < Threshold)
2240 goto CleanupAndExit;
2241 if (C < CompileTimeMemSizeThreshold)
2242 goto CleanupAndExit;
2243 }
2244
2245 BasicBlock *Header = CurLoop->getHeader();
2246 Function *Func = Header->getParent();
2247 Loop *ParentL = LF->getLoopFor(BB: Preheader);
2248 StringRef HeaderName = Header->getName();
2249
2250 // Create a new (empty) preheader, and update the PHI nodes in the
2251 // header to use the new preheader.
2252 BasicBlock *NewPreheader = BasicBlock::Create(Context&: Ctx, Name: HeaderName+".rtli.ph",
2253 Parent: Func, InsertBefore: Header);
2254 if (ParentL)
2255 ParentL->addBasicBlockToLoop(NewBB: NewPreheader, LI&: *LF);
2256 IRBuilder<>(NewPreheader).CreateBr(Dest: Header);
2257 for (auto &In : *Header) {
2258 PHINode *PN = dyn_cast<PHINode>(Val: &In);
2259 if (!PN)
2260 break;
2261 int bx = PN->getBasicBlockIndex(BB: Preheader);
2262 if (bx >= 0)
2263 PN->setIncomingBlock(i: bx, BB: NewPreheader);
2264 }
2265 DT->addNewBlock(BB: NewPreheader, DomBB: Preheader);
2266 DT->changeImmediateDominator(BB: Header, NewBB: NewPreheader);
2267
2268 // Check for safe conditions to execute memmove.
2269 // If stride is positive, copying things from higher to lower addresses
2270 // is equivalent to memmove. For negative stride, it's the other way
2271 // around. Copying forward in memory with positive stride may not be
2272 // same as memmove since we may be copying values that we just stored
2273 // in some previous iteration.
2274 Value *LA = Builder.CreatePtrToInt(V: LoadBasePtr, DestTy: IntPtrTy);
2275 Value *SA = Builder.CreatePtrToInt(V: StoreBasePtr, DestTy: IntPtrTy);
2276 Value *LowA = StridePos ? SA : LA;
2277 Value *HighA = StridePos ? LA : SA;
2278 Value *CmpA = Builder.CreateICmpULT(LHS: LowA, RHS: HighA);
2279 Value *Cond = CmpA;
2280
2281 // Check for distance between pointers. Since the case LowA < HighA
2282 // is checked for above, assume LowA >= HighA.
2283 Value *Dist = Builder.CreateSub(LHS: LowA, RHS: HighA);
2284 Value *CmpD = Builder.CreateICmpSLE(LHS: NumBytes, RHS: Dist);
2285 Value *CmpEither = Builder.CreateOr(LHS: Cond, RHS: CmpD);
2286 Cond = CmpEither;
2287
2288 if (Threshold != 0) {
2289 Type *Ty = NumBytes->getType();
2290 Value *Thr = ConstantInt::get(Ty, V: Threshold);
2291 Value *CmpB = Builder.CreateICmpULT(LHS: Thr, RHS: NumBytes);
2292 Value *CmpBoth = Builder.CreateAnd(LHS: Cond, RHS: CmpB);
2293 Cond = CmpBoth;
2294 }
2295 BasicBlock *MemmoveB = BasicBlock::Create(Context&: Ctx, Name: Header->getName()+".rtli",
2296 Parent: Func, InsertBefore: NewPreheader);
2297 if (ParentL)
2298 ParentL->addBasicBlockToLoop(NewBB: MemmoveB, LI&: *LF);
2299 Instruction *OldT = Preheader->getTerminator();
2300 Builder.CreateCondBr(Cond, True: MemmoveB, False: NewPreheader);
2301 OldT->eraseFromParent();
2302 Preheader->setName(Preheader->getName()+".old");
2303 DT->addNewBlock(BB: MemmoveB, DomBB: Preheader);
2304 // Find the new immediate dominator of the exit block.
2305 BasicBlock *ExitD = Preheader;
2306 for (BasicBlock *PB : predecessors(BB: ExitB)) {
2307 ExitD = DT->findNearestCommonDominator(A: ExitD, B: PB);
2308 if (!ExitD)
2309 break;
2310 }
2311 // If the prior immediate dominator of ExitB was dominated by the
2312 // old preheader, then the old preheader becomes the new immediate
2313 // dominator. Otherwise don't change anything (because the newly
2314 // added blocks are dominated by the old preheader).
2315 if (ExitD && DT->dominates(A: Preheader, B: ExitD)) {
2316 DomTreeNode *BN = DT->getNode(BB: ExitB);
2317 DomTreeNode *DN = DT->getNode(BB: ExitD);
2318 BN->setIDom(DN);
2319 }
2320
2321 // Add a call to memmove to the conditional block.
2322 IRBuilder<> CondBuilder(MemmoveB);
2323 CondBuilder.CreateBr(Dest: ExitB);
2324 CondBuilder.SetInsertPoint(MemmoveB->getTerminator());
2325
2326 if (DestVolatile) {
2327 Type *Int32Ty = Type::getInt32Ty(C&: Ctx);
2328 Type *PtrTy = PointerType::get(C&: Ctx, AddressSpace: 0);
2329 Type *VoidTy = Type::getVoidTy(C&: Ctx);
2330 Module *M = Func->getParent();
2331
2332 // FIXME: This should check if the call is supported
2333 StringRef HexagonVolatileMemcpyName =
2334 RTLIB::RuntimeLibcallsInfo::getLibcallImplName(
2335 CallImpl: RTLIB::impl_hexagon_memcpy_forward_vp4cp4n2);
2336 FunctionCallee Fn = M->getOrInsertFunction(
2337 Name: HexagonVolatileMemcpyName, RetTy: VoidTy, Args: PtrTy, Args: PtrTy, Args: Int32Ty);
2338
2339 const SCEV *OneS = SE->getConstant(Ty: Int32Ty, V: 1);
2340 const SCEV *BECount32 = SE->getTruncateOrZeroExtend(V: BECount, Ty: Int32Ty);
2341 const SCEV *NumWordsS = SE->getAddExpr(LHS: BECount32, RHS: OneS, Flags: SCEV::FlagNUW);
2342 Value *NumWords = Expander.expandCodeFor(SH: NumWordsS, Ty: Int32Ty,
2343 I: MemmoveB->getTerminator());
2344 if (Instruction *In = dyn_cast<Instruction>(Val: NumWords))
2345 if (Value *Simp = simplifyInstruction(I: In, Q: {*DL, TLI, DT}))
2346 NumWords = Simp;
2347
2348 NewCall = CondBuilder.CreateCall(Callee: Fn,
2349 Args: {StoreBasePtr, LoadBasePtr, NumWords});
2350 } else {
2351 NewCall = CondBuilder.CreateMemMove(
2352 Dst: StoreBasePtr, DstAlign: SI->getAlign(), Src: LoadBasePtr, SrcAlign: LI->getAlign(), Size: NumBytes);
2353 }
2354 } else {
2355 NewCall = Builder.CreateMemCpy(Dst: StoreBasePtr, DstAlign: SI->getAlign(), Src: LoadBasePtr,
2356 SrcAlign: LI->getAlign(), Size: NumBytes);
2357 // Okay, the memcpy has been formed. Zap the original store and
2358 // anything that feeds into it.
2359 RecursivelyDeleteTriviallyDeadInstructions(V: SI, TLI);
2360 }
2361
2362 NewCall->setDebugLoc(DLoc);
2363
2364 LLVM_DEBUG(dbgs() << " Formed " << (Overlap ? "memmove: " : "memcpy: ")
2365 << *NewCall << "\n"
2366 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
2367 << " from store ptr=" << *StoreEv << " at: " << *SI
2368 << "\n");
2369
2370 if (Overlap) {
2371 ORE.emit(RemarkBuilder: [&]() {
2372 return OptimizationRemark(DEBUG_TYPE, "LoopToMemmove", DLoc,
2373 CurLoop->getHeader())
2374 << "converted loop to memmove";
2375 });
2376 } else {
2377 ORE.emit(RemarkBuilder: [&]() {
2378 return OptimizationRemark(DEBUG_TYPE, "LoopToMemcpy", DLoc,
2379 CurLoop->getHeader())
2380 << "converted loop to memcpy";
2381 });
2382 }
2383
2384 return true;
2385}
2386
2387// Check if the instructions in Insts, together with their dependencies
2388// cover the loop in the sense that the loop could be safely eliminated once
2389// the instructions in Insts are removed.
2390bool HexagonLoopIdiomRecognize::coverLoop(Loop *L,
2391 SmallVectorImpl<Instruction*> &Insts) const {
2392 SmallPtrSet<BasicBlock *, 8> LoopBlocks;
2393 LoopBlocks.insert_range(R: L->blocks());
2394
2395 SetVector<Instruction *> Worklist(llvm::from_range, Insts);
2396
2397 // Collect all instructions from the loop that the instructions in Insts
2398 // depend on (plus their dependencies, etc.). These instructions will
2399 // constitute the expression trees that feed those in Insts, but the trees
2400 // will be limited only to instructions contained in the loop.
2401 for (unsigned i = 0; i < Worklist.size(); ++i) {
2402 Instruction *In = Worklist[i];
2403 for (auto I = In->op_begin(), E = In->op_end(); I != E; ++I) {
2404 Instruction *OpI = dyn_cast<Instruction>(Val: I);
2405 if (!OpI)
2406 continue;
2407 BasicBlock *PB = OpI->getParent();
2408 if (!LoopBlocks.count(Ptr: PB))
2409 continue;
2410 Worklist.insert(X: OpI);
2411 }
2412 }
2413
2414 // Scan all instructions in the loop, if any of them have a user outside
2415 // of the loop, or outside of the expressions collected above, then either
2416 // the loop has a side-effect visible outside of it, or there are
2417 // instructions in it that are not involved in the original set Insts.
2418 for (auto *B : L->blocks()) {
2419 for (auto &In : *B) {
2420 if (isa<UncondBrInst, CondBrInst>(Val: In))
2421 continue;
2422 if (!Worklist.count(key: &In) && In.mayHaveSideEffects())
2423 return false;
2424 for (auto *K : In.users()) {
2425 Instruction *UseI = dyn_cast<Instruction>(Val: K);
2426 if (!UseI)
2427 continue;
2428 BasicBlock *UseB = UseI->getParent();
2429 if (LF->getLoopFor(BB: UseB) != L)
2430 return false;
2431 }
2432 }
2433 }
2434
2435 return true;
2436}
2437
2438/// runOnLoopBlock - Process the specified block, which lives in a counted loop
2439/// with the specified backedge count. This block is known to be in the current
2440/// loop and not in any subloops.
2441bool HexagonLoopIdiomRecognize::runOnLoopBlock(Loop *CurLoop, BasicBlock *BB,
2442 const SCEV *BECount, SmallVectorImpl<BasicBlock*> &ExitBlocks) {
2443 // We can only promote stores in this block if they are unconditionally
2444 // executed in the loop. For a block to be unconditionally executed, it has
2445 // to dominate all the exit blocks of the loop. Verify this now.
2446 auto DominatedByBB = [this,BB] (BasicBlock *EB) -> bool {
2447 return DT->dominates(A: BB, B: EB);
2448 };
2449 if (!all_of(Range&: ExitBlocks, P: DominatedByBB))
2450 return false;
2451
2452 bool MadeChange = false;
2453 // Look for store instructions, which may be optimized to memset/memcpy.
2454 SmallVector<StoreInst*,8> Stores;
2455 collectStores(CurLoop, BB, Stores);
2456
2457 // Optimize the store into a memcpy, if it feeds an similarly strided load.
2458 for (auto &SI : Stores)
2459 MadeChange |= processCopyingStore(CurLoop, SI, BECount);
2460
2461 return MadeChange;
2462}
2463
2464bool HexagonLoopIdiomRecognize::runOnCountableLoop(Loop *L) {
2465 PolynomialMultiplyRecognize PMR(L, *DL, *DT, *TLI, *SE);
2466 if (PMR.recognize()) {
2467 ORE.emit(RemarkBuilder: [&]() {
2468 return OptimizationRemark(DEBUG_TYPE, "PolynomialMultiply",
2469 L->getStartLoc(), L->getHeader())
2470 << "recognized polynomial multiply idiom";
2471 });
2472 return true;
2473 }
2474
2475 if (!HasMemcpy && !HasMemmove)
2476 return false;
2477
2478 const SCEV *BECount = SE->getBackedgeTakenCount(L);
2479 assert(!isa<SCEVCouldNotCompute>(BECount) &&
2480 "runOnCountableLoop() called on a loop without a predictable"
2481 "backedge-taken count");
2482
2483 SmallVector<BasicBlock *, 8> ExitBlocks;
2484 L->getUniqueExitBlocks(ExitBlocks);
2485
2486 bool Changed = false;
2487
2488 // Scan all the blocks in the loop that are not in subloops.
2489 for (auto *BB : L->getBlocks()) {
2490 // Ignore blocks in subloops.
2491 if (LF->getLoopFor(BB) != L)
2492 continue;
2493 Changed |= runOnLoopBlock(CurLoop: L, BB, BECount, ExitBlocks);
2494 }
2495
2496 return Changed;
2497}
2498
2499bool HexagonLoopIdiomRecognize::run(Loop *L) {
2500 const Module &M = *L->getHeader()->getParent()->getParent();
2501 if (M.getTargetTriple().getArch() != Triple::hexagon)
2502 return false;
2503
2504 // If the loop could not be converted to canonical form, it must have an
2505 // indirectbr in it, just give up.
2506 if (!L->getLoopPreheader()) {
2507 ORE.emit(RemarkBuilder: [&]() {
2508 return OptimizationRemarkMissed(DEBUG_TYPE, "NoPreheader",
2509 L->getStartLoc(), L->getHeader())
2510 << "loop not in canonical form (no preheader)";
2511 });
2512 return false;
2513 }
2514
2515 // Disable loop idiom recognition if the function's name is a common idiom.
2516 StringRef Name = L->getHeader()->getParent()->getName();
2517 if (Name == "memset" || Name == "memcpy" || Name == "memmove")
2518 return false;
2519
2520 DL = &L->getHeader()->getDataLayout();
2521
2522 HasMemcpy = TLI->has(F: LibFunc_memcpy);
2523 HasMemmove = TLI->has(F: LibFunc_memmove);
2524
2525 if (SE->hasLoopInvariantBackedgeTakenCount(L))
2526 return runOnCountableLoop(L);
2527
2528 ORE.emit(RemarkBuilder: [&]() {
2529 return OptimizationRemarkMissed(DEBUG_TYPE, "NonCountableLoop",
2530 L->getStartLoc(), L->getHeader())
2531 << "backedge-taken count is not loop-invariant";
2532 });
2533 return false;
2534}
2535
2536bool HexagonLoopIdiomRecognizeLegacyPass::runOnLoop(Loop *L,
2537 LPPassManager &LPM) {
2538 if (skipLoop(L))
2539 return false;
2540
2541 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2542 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2543 auto *LF = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2544 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
2545 F: *L->getHeader()->getParent());
2546 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2547 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2548 return HexagonLoopIdiomRecognize(AA, DT, LF, TLI, SE, ORE).run(L);
2549}
2550
2551Pass *llvm::createHexagonLoopIdiomPass() {
2552 return new HexagonLoopIdiomRecognizeLegacyPass();
2553}
2554
2555PreservedAnalyses
2556HexagonLoopIdiomRecognitionPass::run(Loop &L, LoopAnalysisManager &AM,
2557 LoopStandardAnalysisResults &AR,
2558 LPMUpdater &U) {
2559 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
2560 return HexagonLoopIdiomRecognize(&AR.AA, &AR.DT, &AR.LI, &AR.TLI, &AR.SE, ORE)
2561 .run(L: &L)
2562 ? getLoopPassPreservedAnalyses()
2563 : PreservedAnalyses::all();
2564}
2565