LLVM 24.0.0git
HexagonLoopIdiomRecognition.cpp
Go to the documentation of this file.
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
10#include "Hexagon.h"
11#include "llvm/ADT/APInt.h"
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/StringRef.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"
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"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/IntrinsicsHexagon.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/PassManager.h"
47#include "llvm/IR/Type.h"
48#include "llvm/IR/User.h"
49#include "llvm/IR/Value.h"
51#include "llvm/Pass.h"
55#include "llvm/Support/Debug.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(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(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(0), cl::desc("Threshold (in bytes) for the runtime "
91 "check guarding the memmove."));
92
94 "compile-time-mem-idiom-threshold", cl::Hidden, cl::init(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(true),
100 cl::desc("Only enable generating memmove in non-nested loops"));
101
103 "disable-hexagon-volatile-memcpy", cl::Hidden, cl::init(false),
104 cl::desc("Enable Hexagon-specific memcpy for volatile destination."));
105
106static cl::opt<unsigned> SimplifyLimit("hlir-simplify-limit", cl::init(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,
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>();
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(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(V).second)
186 Q.push_back(V);
187 }
188
189 Value *pop_front_val() {
190 Value *V = Q.front();
191 Q.pop_front();
192 S.erase(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
252 raw_ostream &operator<<(raw_ostream &OS, const PE &P) {
253 P.C.print(OS, 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)
264INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
265INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
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>(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(Op);
287 }
288}
289
290void Simplifier::Context::print(raw_ostream &OS, const Value *V) const {
291 const auto *U = dyn_cast<const Instruction>(V);
292 if (!U) {
293 OS << V << '(' << *V << ')';
294 return;
295 }
296
297 if (U->getParent()) {
298 OS << U << '(';
299 U->printAsOperand(OS, 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, 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(Exp);
324
325 while (!Q.empty()) {
326 Value *V = Q.pop_front_val();
327 if (M.contains(V))
328 continue;
329 if (Instruction *U = dyn_cast<Instruction>(V)) {
330 if (isa<PHINode>(U) || U->getParent() != Block)
331 continue;
332 for (Value *Op : U->operands())
333 Q.push_back(Op);
334 M.insert({U, U->clone()});
335 }
336 }
337
338 for (std::pair<Value*,Value*> P : M) {
339 Instruction *U = cast<Instruction>(P.second);
340 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
341 auto F = M.find(U->getOperand(i));
342 if (F != M.end())
343 U->setOperand(i, F->second);
344 }
345 }
346
347 auto R = M.find(Exp);
348 assert(R != M.end());
349 Root = R->second;
350
351 record(Root);
352 use(Root);
353}
354
355void Simplifier::Context::record(Value *V) {
356 auto Record = [this](Instruction *U) -> bool {
357 Clones.insert(U);
358 return true;
359 };
360 traverse(V, Record);
361}
362
363void Simplifier::Context::use(Value *V) {
364 auto Use = [this](Instruction *U) -> bool {
365 Used.insert(U);
366 return true;
367 };
368 traverse(V, Use);
369}
370
371void Simplifier::Context::unuse(Value *V) {
372 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != nullptr)
373 return;
374
375 auto Unuse = [this](Instruction *U) -> bool {
376 if (!U->use_empty())
377 return false;
378 Used.erase(U);
379 return true;
380 };
381 traverse(V, 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(Tree);
392 while (!Q.empty()) {
393 Instruction *U = dyn_cast<Instruction>(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, NewV);
401 unuse(OldV);
402 } else {
403 Q.push_back(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(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(NewV);
425 while (!Q.empty()) {
426 Value *V = Q.pop_front_val();
428 if (!U || U->getParent())
429 continue;
430 if (Value *DupV = find(Root, V)) {
431 if (DupV != V)
432 NewV = subst(NewV, V, DupV);
433 } else {
434 for (Value *Op : U->operands())
435 Q.push_back(Op);
436 }
437 }
438
439 // Now, simply replace OldV with NewV in Root.
440 Root = subst(Root, OldV, NewV);
441 use(Root);
442}
443
444void Simplifier::Context::cleanup() {
445 for (Value *V : Clones) {
447 if (!U->getParent())
448 U->dropAllReferences();
449 }
450
451 for (Value *V : Clones) {
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(J))
463 return false;
464 if (isa<PHINode>(I))
465 return I->isIdenticalTo(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>(OpI);
472 auto *InJ = dyn_cast<const Instruction>(OpJ);
473 if (InI && InJ) {
474 if (!equal(InI, 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 {
484 WorkListType Q;
485 Q.push_back(Tree);
486
487 while (!Q.empty()) {
488 Value *V = Q.pop_front_val();
489 if (V == Sub)
490 return V;
492 if (!U || U->getParent())
493 continue;
494 if (SubI && equal(SubI, U))
495 return U;
496 assert(!isa<PHINode>(U));
497 for (Value *Op : U->operands())
498 Q.push_back(Op);
499 }
500 return nullptr;
501}
502
503void Simplifier::Context::link(Instruction *I, BasicBlock *B,
505 if (I->getParent())
506 return;
507
508 for (Value *Op : I->operands()) {
509 if (Instruction *OpI = dyn_cast<Instruction>(Op))
510 link(OpI, B, At);
511 }
512
513 I->insertInto(B, At);
514}
515
516Value *Simplifier::Context::materialize(BasicBlock *B,
518 if (Instruction *RootI = dyn_cast<Instruction>(Root))
519 link(RootI, B, At);
520 return Root;
521}
522
523Value *Simplifier::simplify(Context &C) {
524 WorkListType Q;
525 Q.push_back(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>(Q.pop_front_val());
533 if (!U || U->getParent() || !C.Used.count(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(W);
542 C.replace(U, W);
543 Q.push_back(C.Root);
544 break;
545 }
546 if (!Changed) {
547 for (Value *Op : U->operands())
548 Q.push_back(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(Ctx, 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(PI, PE) != 2)
632 return nullptr;
633 BasicBlock *PB = (*PI == BB) ? *std::next(PI) : *PI;
634
635 for (auto I = BB->begin(), E = BB->end(); I != E && isa<PHINode>(I); ++I) {
636 auto *PN = cast<PHINode>(I);
637 Value *InitV = PN->getIncomingValueForBlock(PB);
638 if (!isa<ConstantInt>(InitV) || !cast<ConstantInt>(InitV)->isZero())
639 continue;
640 Value *IterV = PN->getIncomingValueForBlock(BB);
641 auto *BO = dyn_cast<BinaryOperator>(IterV);
642 if (!BO)
643 continue;
644 if (BO->getOpcode() != Instruction::Add)
645 continue;
646 Value *IncV = nullptr;
647 if (BO->getOperand(0) == PN)
648 IncV = BO->getOperand(1);
649 else if (BO->getOperand(1) == PN)
650 IncV = BO->getOperand(0);
651 if (IncV == nullptr)
652 continue;
653
654 if (auto *T = dyn_cast<ConstantInt>(IncV))
655 if (T->isOne())
656 return PN;
657 }
658 return nullptr;
659}
660
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>(TheUse.getUser()))
666 if (BB == II->getParent())
667 II->replaceUsesOfWith(I, 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(CondV, m_ICmp(P, m_And(m_Value(A), m_Value(B)), m_Value(C))) &&
690 !match(CondV, m_ICmp(P, m_Value(C), m_And(m_Value(A), m_Value(B)))))
691 return false;
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(A, m_Shl(m_One(), m_Specific(CIV)))) {
700 Sh1 = A;
701 X = B;
702 } else if (match(B, m_Shl(m_One(), m_Specific(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(C, 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(ShouldXoredV, m_Xor(m_Value(Y), m_Value(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(ShouldSameV, 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(U, m_c_Xor(m_Specific(SelI), m_Value(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(T, m_Shl(m_Value(Q), m_Specific(CIV))) &&
773 !match(T, m_Shl(m_ZExt(m_Value(Q)), m_ZExt(m_Specific(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(CondV, m_c_ICmp(P, m_Value(C), m_Zero()))) {
806 return false;
807 // Matched: select C == 0 ? ... : ...
808 // select C != 0 ? ... : ...
809 TrueIfZero = (P == CmpInst::ICMP_EQ);
810 } else if (match(CondV, m_c_ICmp(P, m_Value(C), m_One()))) {
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(C, m_And(m_Value(X), 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(TrueV, m_LShr(m_Value(R), m_One())))
830 return false;
831 // Matched: select +++ ? (R >> 1) : ...
832 if (!match(FalseV, m_c_Xor(m_Specific(TrueV), m_Value(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(FalseV, m_LShr(m_Value(R), m_One())))
840 return false;
841 // Matched: select +++ ? ... : (R >> 1)
842 if (!match(TrueV, m_c_Xor(m_Specific(FalseV), m_Value(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>(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
962bool 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).
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>(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(1))
1007 In->mutateType(DestTy);
1008 unsigned DestBW = DestTy->getBitWidth();
1009
1010 // Handle PHIs.
1011 if (PHINode *P = dyn_cast<PHINode>(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>(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(InV, DestTy);
1025 P->setIncomingValue(i, InV);
1026 }
1027 }
1028 } else if (ZExtInst *Z = dyn_cast<ZExtInst>(In)) {
1029 Value *Op = Z->getOperand(0);
1030 if (Op->getType() == Z->getType())
1031 Z->replaceAllUsesWith(Op);
1032 Z->eraseFromParent();
1033 return;
1034 }
1035 if (TruncInst *T = dyn_cast<TruncInst>(In)) {
1036 IntegerType *TruncTy = cast<IntegerType>(OrigTy);
1037 Value *Mask = ConstantInt::get(DestTy, (1u << TruncTy->getBitWidth()) - 1);
1038 Value *And = IRBuilder<>(In).CreateAnd(T->getOperand(0), Mask);
1039 T->replaceAllUsesWith(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>(In->getOperand(i)))
1047 if (CI->getBitWidth() < DestBW)
1048 In->setOperand(i, ConstantInt::get(DestTy, 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>(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(&In, DestTy))
1077 return false;
1078
1079 // Perform the promotion.
1080 SmallVector<Instruction *> LoopIns(llvm::make_pointer_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.
1087 for (auto I = ExitB->begin(); I != End; ++I) {
1088 PHINode *P = dyn_cast<PHINode>(I);
1089 if (!P)
1090 break;
1091 Type *Ty0 = P->getIncomingValue(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(Ty0);
1097 Value *T = IRBuilder<>(End).CreateTrunc(P, PTy);
1098 // In order for the RAUW to work, the types of P and T must match.
1099 P->mutateType(PTy);
1100 P->replaceAllUsesWith(T);
1101 // Final update of the P's type.
1102 P->mutateType(Ty0);
1103 cast<Instruction>(T)->setOperand(0, 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>(Out)->getParent();
1117 bool HadPhi = false;
1118
1119 for (auto *U : Out->users()) {
1120 auto *I = dyn_cast<Instruction>(&*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>(I);
1129 if (IsPhi && HadPhi)
1130 return false;
1131 HadPhi |= IsPhi;
1132 if (!Cycle.insert(I))
1133 return false;
1134 if (findCycle(I, In, Cycle))
1135 break;
1136 Cycle.remove(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>(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(Cycle[J]);
1163
1164 ValueSeq &Second = IsE ? Early : Late;
1165 Second.insert(Cycle[I]);
1166 for (++I; I < N; ++I) {
1167 Value *V = Cycle[I];
1168 if (DivI == V || isa<PHINode>(V))
1169 break;
1170 Second.insert(V);
1171 }
1172
1173 for (; I < N; ++I)
1174 First.insert(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(1), *FV = UseI->getOperand(2);
1184 if (Early.count(TV) || Early.count(FV)) {
1185 if (Late.count(TV) || Late.count(FV))
1186 return false;
1187 Early.insert(UseI);
1188 } else if (Late.count(TV) || Late.count(FV)) {
1189 if (Early.count(TV) || Early.count(FV))
1190 return false;
1191 Late.insert(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(&*I))
1204 AL = false;
1205 else if (Late.count(&*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(UseI);
1224 else
1225 Late.insert(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>(V->getType());
1249 if (!T)
1250 return false;
1251
1252 KnownBits Known(T->getBitWidth());
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>(V))
1262 return C->getValue().countl_zero() >= IterCount;
1263
1264 if (auto *I = dyn_cast<Instruction>(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(1);
1285 return true;
1286}
1287
1288bool PolynomialMultiplyRecognize::convertShiftsToLeft(BasicBlock *LoopB,
1289 BasicBlock *ExitB, unsigned IterCount) {
1290 Value *CIV = getCountIV(LoopB);
1291 if (CIV == nullptr)
1292 return false;
1293 auto *CIVTy = dyn_cast<IntegerType>(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(&I, m_LShr(m_Value(V), m_One())))
1306 continue;
1307 ValueSeq C;
1308 if (!findCycle(&I, V, C))
1309 continue;
1310
1311 // Found a cycle.
1312 C.insert(&I);
1313 classifyCycle(&I, C, Early, Late);
1314 Cycled.insert_range(C);
1315 RShifts.insert(&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>(V->getType()))
1324 return false;
1325 auto *R = cast<Instruction>(V);
1326 // If the instruction does not commute with shifts, the loop cannot
1327 // be unshifted.
1328 if (!commutesWithShift(R))
1329 return false;
1330 for (User *U : R->users()) {
1331 auto *T = cast<Instruction>(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(T) || isa<PHINode>(T))
1336 continue;
1337
1338 Users.insert(T);
1339 if (!classifyInst(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>(Internal[i]);
1352 if (!R)
1353 continue;
1354 for (Value *Op : R->operands()) {
1355 auto *T = dyn_cast<Instruction>(Op);
1356 if (T && T->getParent() != LoopB)
1357 Inputs.insert(Op);
1358 else
1359 Internal.insert(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(std::make_pair(V, Ty));
1380 if (Inserted)
1381 H->second = IRB.CreateIntCast(V, Ty, 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>(I) || !Users.count(&*I))
1389 continue;
1390
1391 // Match lshr x, 1.
1392 Value *V = nullptr;
1393 if (match(&*I, m_LShr(m_Value(V), m_One()))) {
1394 replaceAllUsesOfWithIn(&*I, V, 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, Op))
1402 continue;
1403 if (Users.count(Op))
1404 continue;
1405 // Skip shifting zeros.
1407 continue;
1408 // Check if we have already generated a shift for this value.
1409 auto F = ShiftMap.find(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>(ShVal->getType());
1418 auto *ATy = cast<IntegerType>(ShAmt->getType());
1419 if (Late.count(&*I))
1420 ShVal = IRB.CreateShl(Op, ConstantInt::get(VTy, 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(ShVal, ShAmt);
1431 ShiftMap.insert(std::make_pair(Op, W));
1432 }
1433 I->replaceUsesOfWith(Op, 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>(P))
1445 break;
1446 auto *PN = cast<PHINode>(P);
1447 Value *U = PN->getIncomingValueForBlock(LoopB);
1448 if (!Users.count(U))
1449 continue;
1450 Value *S = IRB.CreateLShr(PN, ConstantInt::get(PN->getType(), IterCount));
1451 PN->replaceAllUsesWith(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>(S)->replaceUsesOfWith(S, PN);
1457 }
1458
1459 return true;
1460}
1461
1462void PolynomialMultiplyRecognize::cleanupLoopBody(BasicBlock *LoopB) {
1463 for (auto &I : *LoopB)
1464 if (Value *SV = simplifyInstruction(&I, {DL, &TLI, &DT}))
1465 I.replaceAllUsesWith(SV);
1466
1467 for (Instruction &I : llvm::make_early_inc_range(*LoopB))
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, 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(P, PV.M);
1526
1527 // Create a bit mask to clear the high bits beyond IterCount.
1528 auto *BMI = ConstantInt::get(P->getType(), APInt::getLowBitsSet(32, IC));
1529
1530 if (PV.IterCount != 32)
1531 P = B.CreateAnd(P, BMI);
1532
1533 if (PV.Inv) {
1534 auto *QI = dyn_cast<ConstantInt>(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(Tmp) & M;
1541 auto *QVI = ConstantInt::get(QI->getType(), QV);
1542 P = B.CreateCall(PMF, {P, QVI});
1543 P = B.CreateTrunc(P, QI->getType());
1544 if (IC != 32)
1545 P = B.CreateAnd(P, BMI);
1546 }
1547
1548 Value *R = B.CreateCall(PMF, {P, Q});
1549
1550 if (PV.M != nullptr)
1551 R = B.CreateXor(R, B.CreateIntCast(P0, R->getType(), false));
1552
1553 return R;
1554}
1555
1556static bool hasZeroSignBit(const Value *V) {
1557 if (const auto *CI = dyn_cast<const ConstantInt>(V))
1558 return CI->getValue().isNonNegative();
1560 if (!I)
1561 return false;
1562 switch (I->getOpcode()) {
1563 case Instruction::LShr:
1564 if (const auto SI = dyn_cast<const ConstantInt>(I->getOperand(1)))
1565 return SI->getZExtValue() > 0;
1566 return false;
1567 case Instruction::Or:
1568 case Instruction::Xor:
1569 return hasZeroSignBit(I->getOperand(0)) &&
1570 hasZeroSignBit(I->getOperand(1));
1571 case Instruction::And:
1572 return hasZeroSignBit(I->getOperand(0)) ||
1573 hasZeroSignBit(I->getOperand(1));
1574 }
1575 return false;
1576}
1577
1578void PolynomialMultiplyRecognize::setupPreSimplifier(Simplifier &S) {
1579 S.addRule("sink-zext",
1580 // Sink zext past bitwise operations.
1581 [](Instruction *I, Module &M) -> Value * {
1582 if (I->getOpcode() != Instruction::ZExt)
1583 return nullptr;
1584 Instruction *T = dyn_cast<Instruction>(I->getOperand(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(
1598 B.CreateZExt(T->getOperand(0), I->getType()),
1599 B.CreateZExt(T->getOperand(1), I->getType()));
1600 });
1601 S.addRule("xor/and -> and/xor",
1602 // (xor (and x a) (and y a)) -> (and (xor x y) a)
1603 [](Instruction *I, Module &M) -> Value * {
1604 if (I->getOpcode() != Instruction::Xor)
1605 return nullptr;
1606 Instruction *And0 = dyn_cast<Instruction>(I->getOperand(0));
1607 Instruction *And1 = dyn_cast<Instruction>(I->getOperand(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(1) != And1->getOperand(1))
1614 return nullptr;
1615 IRBuilder<> B(M);
1616 return B.CreateAnd(
1617 B.CreateXor(And0->getOperand(0), And1->getOperand(0)),
1618 And0->getOperand(1));
1619 });
1620 S.addRule(
1621 "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 [](Instruction *I, Module &M) -> Value * {
1625 BinaryOperator *BO = dyn_cast<BinaryOperator>(I);
1626 if (!BO)
1627 return nullptr;
1629 if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(0))) {
1630 IRBuilder<> B(M);
1631 Value *X = Sel->getTrueValue(), *Y = Sel->getFalseValue();
1632 Value *Z = BO->getOperand(1);
1633 return B.CreateSelect(Sel->getCondition(), B.CreateBinOp(Op, X, Z),
1634 B.CreateBinOp(Op, Y, Z));
1635 }
1636 if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(1))) {
1637 IRBuilder<> B(M);
1638 Value *X = BO->getOperand(0);
1639 Value *Y = Sel->getTrueValue(), *Z = Sel->getFalseValue();
1640 return B.CreateSelect(Sel->getCondition(), B.CreateBinOp(Op, X, Y),
1641 B.CreateBinOp(Op, X, Z));
1642 }
1643 return nullptr;
1644 });
1645 S.addRule(
1646 "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 [](Instruction *I, Module &M) -> Value * {
1650 SelectInst *Sel = dyn_cast<SelectInst>(I);
1651 if (!Sel)
1652 return nullptr;
1653 IRBuilder<> B(M);
1654 Value *C = Sel->getCondition();
1655 if (SelectInst *Sel0 = dyn_cast<SelectInst>(Sel->getTrueValue())) {
1656 if (Sel0->getCondition() == C)
1657 return B.CreateSelect(C, Sel0->getTrueValue(),
1658 Sel->getFalseValue());
1659 }
1660 if (SelectInst *Sel1 = dyn_cast<SelectInst>(Sel->getFalseValue())) {
1661 if (Sel1->getCondition() == C)
1662 return B.CreateSelect(C, Sel->getTrueValue(),
1663 Sel1->getFalseValue());
1664 }
1665 return nullptr;
1666 });
1667 S.addRule("or-signbit -> xor-signbit",
1668 // (or (lshr x 1) 0x800.0) -> (xor (lshr x 1) 0x800.0)
1669 [](Instruction *I, Module &M) -> Value * {
1670 if (I->getOpcode() != Instruction::Or)
1671 return nullptr;
1672 ConstantInt *Msb = dyn_cast<ConstantInt>(I->getOperand(1));
1673 if (!Msb || !Msb->getValue().isSignMask())
1674 return nullptr;
1675 if (!hasZeroSignBit(I->getOperand(0)))
1676 return nullptr;
1677 return IRBuilder<>(M).CreateXor(I->getOperand(0), Msb);
1678 });
1679 S.addRule("sink lshr into binop",
1680 // (lshr (BitOp x y) c) -> (BitOp (lshr x c) (lshr y c))
1681 [](Instruction *I, Module &M) -> Value * {
1682 if (I->getOpcode() != Instruction::LShr)
1683 return nullptr;
1684 BinaryOperator *BitOp =
1685 dyn_cast<BinaryOperator>(I->getOperand(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(1);
1698 return B.CreateBinOp(BitOp->getOpcode(),
1699 B.CreateLShr(BitOp->getOperand(0), S),
1700 B.CreateLShr(BitOp->getOperand(1), S));
1701 });
1702 S.addRule("expose bitop-const",
1703 // (BitOp1 (BitOp2 x a) b) -> (BitOp2 x (BitOp1 a b))
1704 [](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>(I);
1715 if (!BitOp1 || !IsBitOp(BitOp1->getOpcode()))
1716 return nullptr;
1717 BinaryOperator *BitOp2 =
1719 if (!BitOp2 || !IsBitOp(BitOp2->getOpcode()))
1720 return nullptr;
1721 ConstantInt *CA = dyn_cast<ConstantInt>(BitOp2->getOperand(1));
1722 ConstantInt *CB = dyn_cast<ConstantInt>(BitOp1->getOperand(1));
1723 if (!CA || !CB)
1724 return nullptr;
1725 IRBuilder<> B(M);
1726 Value *X = BitOp2->getOperand(0);
1727 return B.CreateBinOp(BitOp2->getOpcode(), X,
1728 B.CreateBinOp(BitOp1->getOpcode(), CA, CB));
1729 });
1730 S.addRule("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 [](Instruction *I, Module &M) -> Value * {
1734 SelectInst *Sel = dyn_cast<SelectInst>(I);
1735 if (!Sel)
1736 return nullptr;
1737 Value *C = Sel->getCondition();
1738 Value *X;
1739 using namespace PatternMatch;
1740 if (!(match(C, m_Trunc(m_Value(X))) ||
1741 match(C, m_Not(m_Trunc(m_Value(X))))))
1742 return nullptr;
1743
1744 IRBuilder<> B(M);
1745 Type *Ty = X->getType();
1746 Value *And = B.CreateAnd(X, ConstantInt::get(Ty, 1));
1747 Value *Icmp = B.CreateICmp(isa<TruncInst>(C) ? ICmpInst::ICMP_NE
1748 : ICmpInst::ICMP_EQ,
1749 And, ConstantInt::get(Ty, 0));
1750 return B.CreateSelect(Icmp, Sel->getTrueValue(),
1751 Sel->getFalseValue());
1752 });
1753}
1754
1755void PolynomialMultiplyRecognize::setupPostSimplifier(Simplifier &S) {
1756 S.addRule("(and (xor (and x a) y) b) -> (and (xor x y) b), if b == b&a",
1757 [](Instruction *I, Module &M) -> Value * {
1758 if (I->getOpcode() != Instruction::And)
1759 return nullptr;
1760 Instruction *Xor = dyn_cast<Instruction>(I->getOperand(0));
1761 ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(1));
1762 if (!Xor || !C0)
1763 return nullptr;
1764 if (Xor->getOpcode() != Instruction::Xor)
1765 return nullptr;
1766 Instruction *And0 = dyn_cast<Instruction>(Xor->getOperand(0));
1767 Instruction *And1 = dyn_cast<Instruction>(Xor->getOperand(1));
1768 // Pick the first non-null and.
1769 if (!And0 || And0->getOpcode() != Instruction::And)
1770 std::swap(And0, And1);
1771 ConstantInt *C1 = dyn_cast<ConstantInt>(And0->getOperand(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(B.CreateXor(And0->getOperand(0), And1), 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(CurLoop);
1806 return false;
1807 if (auto *CV = dyn_cast<SCEVConstant>(CT))
1808 IterCount = CV->getValue()->getZExtValue() + 1;
1809
1810 Value *CIV = getCountIV(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>(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>(&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>(T)) ? cast<SelectInst>(T) : SI;
1844 LLVM_DEBUG(dbgs() << "scanSelect(pre-scan): " << PE(C, SelI) << '\n');
1845 if (scanSelect(SelI, LoopB, EntryB, CIV, PV, true)) {
1846 FoundPreScan = true;
1847 if (SelI != SI) {
1848 Value *NewSel = C.materialize(LoopB, SI->getIterator());
1849 SI->replaceAllUsesWith(NewSel);
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>(&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>(T);
1878 if (SelI != SI) {
1879 Value *NewSel = C.materialize(LoopB, SI->getIterator());
1880 SI->replaceAllUsesWith(NewSel);
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>(&In);
1895 if (!SelI)
1896 continue;
1897 LLVM_DEBUG(dbgs() << "scanSelect: " << *SelI << '\n');
1898 FoundScan = scanSelect(SelI, LoopB, EntryB, CIV, PV, 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(PM, PV.Res->getType(), false);
1925
1926 PV.Res->replaceAllUsesWith(PM);
1927 PV.Res->eraseFromParent();
1928 return true;
1929}
1930
1931int HexagonLoopIdiomRecognize::getSCEVStride(const SCEVAddRecExpr *S) {
1932 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(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(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>(SE->getSCEV(StorePtr));
1954 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) {
1955 ORE.emit([&]() {
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(StoreEv);
1966 if (Stride == 0)
1967 return false;
1968 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
1969 if (StoreSize != unsigned(std::abs(Stride))) {
1970 ORE.emit([&]() {
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>(SI->getValueOperand());
1980 if (!LI || !LI->isSimple()) {
1981 ORE.emit([&]() {
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>(SE->getSCEV(LoadPtr));
1994 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) {
1995 ORE.emit([&]() {
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(1) != LoadEv->getOperand(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
2016 const SCEV *BECount, unsigned StoreSize,
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.
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>(BECount))
2027 AccessSize = LocationSize::precise((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(&I) == 0 &&
2039 isModOrRefSet(AA.getModRefInfo(&I, 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>(&I))
2050 if (isLegalStore(CurLoop, SI))
2051 Stores.push_back(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>(SE->getSCEV(StorePtr));
2062 unsigned Stride = getSCEVStride(StoreEv);
2063 unsigned StoreSize = DL->getTypeStoreSize(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>(SI->getValueOperand());
2071 auto *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(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, 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(StoreEv->getStart(),
2090 Builder.getPtrTy(SI->getPointerAddressSpace()), 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(BECountTy) > 32) {
2101CleanupAndExit:
2102 // If we generated new code for the base pointer, clean up.
2103 Expander.clear();
2104 if (StoreBasePtr && (LoadBasePtr != StoreBasePtr)) {
2106 StoreBasePtr = nullptr;
2107 }
2108 if (LoadBasePtr) {
2110 LoadBasePtr = nullptr;
2111 }
2112 return false;
2113 }
2114 }
2115
2116 SmallPtrSet<Instruction*, 2> Ignore1;
2117 Ignore1.insert(SI);
2118 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
2119 StoreSize, *AA, Ignore1)) {
2120 // Check if the load is the offending instruction.
2121 Ignore1.insert(LI);
2122 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
2123 BECount, StoreSize, *AA, Ignore1)) {
2124 // Still bad. Nothing we can do.
2125 ORE.emit([&]() {
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([&]() {
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(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(SI);
2158 Insts.push_back(LI);
2159 if (!coverLoop(CurLoop, Insts)) {
2160 ORE.emit([&]() {
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([&]() {
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([&]() {
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(LoadEv->getStart(),
2190 Builder.getPtrTy(LI->getPointerAddressSpace()), ExpPt);
2191
2192 SmallPtrSet<Instruction*, 2> Ignore2;
2193 Ignore2.insert(SI);
2194 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
2195 StoreSize, *AA, Ignore2))
2196 goto CleanupAndExit;
2197
2198 // Check the stride.
2199 bool StridePos = getSCEVStride(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(BECount, IntPtrTy);
2221 DebugLoc DLoc = SI->getDebugLoc();
2222
2223 const SCEV *NumBytesS =
2224 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
2225 if (StoreSize != 1)
2226 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
2228 Value *NumBytes = Expander.expandCodeFor(NumBytesS, IntPtrTy, ExpPt);
2229 if (Instruction *In = dyn_cast<Instruction>(NumBytes))
2230 if (Value *Simp = simplifyInstruction(In, {*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>(NumBytes)) {
2238 uint64_t C = CI->getZExtValue();
2239 if (Threshold != 0 && C < Threshold)
2240 goto CleanupAndExit;
2242 goto CleanupAndExit;
2243 }
2244
2245 BasicBlock *Header = CurLoop->getHeader();
2246 Function *Func = Header->getParent();
2247 Loop *ParentL = LF->getLoopFor(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(Ctx, HeaderName+".rtli.ph",
2253 Func, Header);
2254 if (ParentL)
2255 ParentL->addBasicBlockToLoop(NewPreheader, *LF);
2256 IRBuilder<>(NewPreheader).CreateBr(Header);
2257 for (auto &In : *Header) {
2258 PHINode *PN = dyn_cast<PHINode>(&In);
2259 if (!PN)
2260 break;
2261 int bx = PN->getBasicBlockIndex(Preheader);
2262 if (bx >= 0)
2263 PN->setIncomingBlock(bx, NewPreheader);
2264 }
2265 DT->addNewBlock(NewPreheader, Preheader);
2266 DT->changeImmediateDominator(Header, 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(LoadBasePtr, IntPtrTy);
2275 Value *SA = Builder.CreatePtrToInt(StoreBasePtr, IntPtrTy);
2276 Value *LowA = StridePos ? SA : LA;
2277 Value *HighA = StridePos ? LA : SA;
2278 Value *CmpA = Builder.CreateICmpULT(LowA, 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(LowA, HighA);
2284 Value *CmpD = Builder.CreateICmpSLE(NumBytes, Dist);
2285 Value *CmpEither = Builder.CreateOr(Cond, CmpD);
2286 Cond = CmpEither;
2287
2288 if (Threshold != 0) {
2289 Type *Ty = NumBytes->getType();
2290 Value *Thr = ConstantInt::get(Ty, Threshold);
2291 Value *CmpB = Builder.CreateICmpULT(Thr, NumBytes);
2292 Value *CmpBoth = Builder.CreateAnd(Cond, CmpB);
2293 Cond = CmpBoth;
2294 }
2295 BasicBlock *MemmoveB = BasicBlock::Create(Ctx, Header->getName()+".rtli",
2296 Func, NewPreheader);
2297 if (ParentL)
2298 ParentL->addBasicBlockToLoop(MemmoveB, *LF);
2299 Instruction *OldT = Preheader->getTerminator();
2300 Builder.CreateCondBr(Cond, MemmoveB, NewPreheader);
2301 OldT->eraseFromParent();
2302 Preheader->setName(Preheader->getName()+".old");
2303 DT->addNewBlock(MemmoveB, Preheader);
2304 // Find the new immediate dominator of the exit block.
2305 BasicBlock *ExitD = Preheader;
2306 for (BasicBlock *PB : predecessors(ExitB)) {
2307 ExitD = DT->findNearestCommonDominator(ExitD, 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(Preheader, ExitD)) {
2316 DomTreeNode *BN = DT->getNode(ExitB);
2317 DomTreeNode *DN = DT->getNode(ExitD);
2318 BN->setIDom(DN);
2319 }
2320
2321 // Add a call to memmove to the conditional block.
2322 IRBuilder<> CondBuilder(MemmoveB);
2323 CondBuilder.CreateBr(ExitB);
2324 CondBuilder.SetInsertPoint(MemmoveB->getTerminator());
2325
2326 if (DestVolatile) {
2327 Type *Int32Ty = Type::getInt32Ty(Ctx);
2328 Type *PtrTy = PointerType::get(Ctx, 0);
2329 Type *VoidTy = Type::getVoidTy(Ctx);
2330 Module *M = Func->getParent();
2331
2332 // FIXME: This should check if the call is supported
2333 StringRef HexagonVolatileMemcpyName =
2335 RTLIB::impl_hexagon_memcpy_forward_vp4cp4n2);
2336 FunctionCallee Fn = M->getOrInsertFunction(
2337 HexagonVolatileMemcpyName, VoidTy, PtrTy, PtrTy, Int32Ty);
2338
2339 const SCEV *OneS = SE->getConstant(Int32Ty, 1);
2340 const SCEV *BECount32 = SE->getTruncateOrZeroExtend(BECount, Int32Ty);
2341 const SCEV *NumWordsS = SE->getAddExpr(BECount32, OneS, SCEV::FlagNUW);
2342 Value *NumWords = Expander.expandCodeFor(NumWordsS, Int32Ty,
2343 MemmoveB->getTerminator());
2344 if (Instruction *In = dyn_cast<Instruction>(NumWords))
2345 if (Value *Simp = simplifyInstruction(In, {*DL, TLI, DT}))
2346 NumWords = Simp;
2347
2348 NewCall = CondBuilder.CreateCall(Fn,
2349 {StoreBasePtr, LoadBasePtr, NumWords});
2350 } else {
2351 NewCall = CondBuilder.CreateMemMove(
2352 StoreBasePtr, SI->getAlign(), LoadBasePtr, LI->getAlign(), NumBytes);
2353 }
2354 } else {
2355 NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlign(), LoadBasePtr,
2356 LI->getAlign(), NumBytes);
2357 // Okay, the memcpy has been formed. Zap the original store and
2358 // anything that feeds into it.
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([&]() {
2372 return OptimizationRemark(DEBUG_TYPE, "LoopToMemmove", DLoc,
2373 CurLoop->getHeader())
2374 << "converted loop to memmove";
2375 });
2376 } else {
2377 ORE.emit([&]() {
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(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) {
2405 if (!OpI)
2406 continue;
2407 BasicBlock *PB = OpI->getParent();
2408 if (!LoopBlocks.count(PB))
2409 continue;
2410 Worklist.insert(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) {
2421 continue;
2422 if (!Worklist.count(&In) && In.mayHaveSideEffects())
2423 return false;
2424 for (auto *K : In.users()) {
2426 if (!UseI)
2427 continue;
2428 BasicBlock *UseB = UseI->getParent();
2429 if (LF->getLoopFor(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(BB, EB);
2448 };
2449 if (!all_of(ExitBlocks, 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([&]() {
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(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([&]() {
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(LibFunc_memcpy);
2523 HasMemmove = TLI->has(LibFunc_memmove);
2524
2525 if (SE->hasLoopInvariantBackedgeTakenCount(L))
2526 return runOnCountableLoop(L);
2527
2528 ORE.emit([&]() {
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 *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
2552 return new HexagonLoopIdiomRecognizeLegacyPass();
2553}
2554
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)
2564}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ATTRIBUTE_USED
Definition Compiler.h:238
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Resource Access
This file defines the DenseMap class.
#define DEBUG_TYPE
hexagon bit simplify
static cl::opt< unsigned > SimplifyLimit("hlir-simplify-limit", cl::init(10000), cl::Hidden, cl::desc("Maximum number of simplification steps in HLIR"))
static cl::opt< bool > DisableMemcpyIdiom("disable-memcpy-idiom", cl::Hidden, cl::init(false), cl::desc("Disable generation of memcpy in loop idiom recognition"))
static void replaceAllUsesOfWithIn(Value *I, Value *J, BasicBlock *BB)
static cl::opt< unsigned > RuntimeMemSizeThreshold("runtime-mem-idiom-threshold", cl::Hidden, cl::init(0), cl::desc("Threshold (in bytes) for the runtime " "check guarding the memmove."))
static cl::opt< bool > HexagonVolatileMemcpy("disable-hexagon-volatile-memcpy", cl::Hidden, cl::init(false), cl::desc("Enable Hexagon-specific memcpy for volatile destination."))
static cl::opt< bool > DisableMemmoveIdiom("disable-memmove-idiom", cl::Hidden, cl::init(false), cl::desc("Disable generation of memmove in loop idiom recognition"))
static cl::opt< unsigned > CompileTimeMemSizeThreshold("compile-time-mem-idiom-threshold", cl::Hidden, cl::init(64), cl::desc("Threshold (in bytes) to perform the transformation, if the " "runtime loop count (mem transfer size) is known at compile-time."))
static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, const SCEV *BECount, unsigned StoreSize, AliasAnalysis &AA, SmallPtrSetImpl< Instruction * > &Ignored)
mayLoopAccessLocation - Return true if the specified loop might access the specified pointer location...
static bool hasZeroSignBit(const Value *V)
static cl::opt< bool > OnlyNonNestedMemmove("only-nonnested-memmove-idiom", cl::Hidden, cl::init(true), cl::desc("Only enable generating memmove in non-nested loops"))
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
Move duplicate certain instructions close to their use
Definition Localizer.cpp:77
This header provides classes for managing per-loop analyses.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
Machine Check Debug Module
This file provides utility analysis objects describing memory locations.
#define T
uint64_t IntrinsicInst * II
#define P(N)
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
const SmallVectorImpl< MachineOperand > & Cond
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
LLVM_ABI AnalysisUsage & addRequiredID(const void *ID)
Definition Pass.cpp:292
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
@ ICMP_NE
not equal
Definition InstrTypes.h:762
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
void setIDom(DomTreeNodeBase *NewIDom)
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
bool empty() const
Definition Function.h:844
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
user_iterator user_begin()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
bool isSimple() const
Align getAlign() const
Return the alignment of the access that is being performed.
static LocationSize precise(uint64_t Value)
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Representation for a specific memory location.
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
void setIncomingBlock(unsigned i, BasicBlock *BB)
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class represents a constant integer value.
SCEVUse getOperand(unsigned i) const
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
Provides information about what library functions are available for the current target.
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:526
@ Known
Known to have no common set bits.
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr from_range_t from_range
Pass * createHexagonLoopIdiomPass()
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI char & LCSSAID
Definition LCSSA.cpp:545
LLVM_ABI char & LoopSimplifyID
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.