LLVM 24.0.0git
ARMParallelDSP.cpp
Go to the documentation of this file.
1//===- ARMParallelDSP.cpp - Parallel DSP Pass -----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Armv6 introduced instructions to perform 32-bit SIMD operations. The
11/// purpose of this pass is do some IR pattern matching to create ACLE
12/// DSP intrinsics, which map on these 32-bit SIMD operations.
13/// This pass runs only when unaligned accesses is supported/enabled.
14//
15//===----------------------------------------------------------------------===//
16
17#include "ARM.h"
18#include "ARMSubtarget.h"
20#include "llvm/ADT/Statistic.h"
27#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/IntrinsicsARM.h"
30#include "llvm/IR/Module.h"
31#include "llvm/IR/NoFolder.h"
33#include "llvm/Pass.h"
34#include "llvm/Support/Debug.h"
37
38using namespace llvm;
39using namespace PatternMatch;
40
41#define DEBUG_TYPE "arm-parallel-dsp"
42
43STATISTIC(NumSMLAD , "Number of smlad instructions generated");
44
45namespace {
46 struct MulCandidate;
47 class Reduction;
48
49 using MulCandList = SmallVector<std::unique_ptr<MulCandidate>, 8>;
50 using MemInstList = SmallVectorImpl<LoadInst*>;
52
53 // 'MulCandidate' holds the multiplication instructions that are candidates
54 // for parallel execution.
55 struct MulCandidate {
56 Instruction *Root;
57 Value* LHS;
58 Value* RHS;
59 bool Exchange = false;
60 bool Paired = false;
61 SmallVector<LoadInst*, 2> VecLd; // Container for loads to widen.
62
63 MulCandidate(Instruction *I, Value *lhs, Value *rhs) :
64 Root(I), LHS(lhs), RHS(rhs) { }
65
66 bool HasTwoLoadInputs() const {
67 return isa<LoadInst>(LHS) && isa<LoadInst>(RHS);
68 }
69
70 LoadInst *getBaseLoad() const {
71 return VecLd.front();
72 }
73 };
74
75 /// Represent a sequence of multiply-accumulate operations with the aim to
76 /// perform the multiplications in parallel.
77 class Reduction {
78 Instruction *Root = nullptr;
79 Value *Acc = nullptr;
80 MulCandList Muls;
81 MulPairList MulPairs;
82 SetVector<Instruction*> Adds;
83
84 public:
85 Reduction() = delete;
86
87 Reduction (Instruction *Add) : Root(Add) { }
88
89 /// Record an Add instruction that is a part of the this reduction.
90 void InsertAdd(Instruction *I) { Adds.insert(I); }
91
92 /// Create MulCandidates, each rooted at a Mul instruction, that is a part
93 /// of this reduction.
94 void InsertMuls() {
95 auto GetMulOperand = [](Value *V) -> Instruction* {
96 if (auto *SExt = dyn_cast<SExtInst>(V)) {
97 if (auto *I = dyn_cast<Instruction>(SExt->getOperand(0)))
98 if (I->getOpcode() == Instruction::Mul)
99 return I;
100 } else if (auto *I = dyn_cast<Instruction>(V)) {
101 if (I->getOpcode() == Instruction::Mul)
102 return I;
103 }
104 return nullptr;
105 };
106
107 auto InsertMul = [this](Instruction *I) {
108 Value *LHS = cast<Instruction>(I->getOperand(0))->getOperand(0);
109 Value *RHS = cast<Instruction>(I->getOperand(1))->getOperand(0);
110 Muls.push_back(std::make_unique<MulCandidate>(I, LHS, RHS));
111 };
112
113 for (auto *Add : Adds) {
114 if (Add == Acc)
115 continue;
116 if (auto *Mul = GetMulOperand(Add->getOperand(0)))
117 InsertMul(Mul);
118 if (auto *Mul = GetMulOperand(Add->getOperand(1)))
119 InsertMul(Mul);
120 }
121 }
122
123 /// Add the incoming accumulator value, returns true if a value had not
124 /// already been added. Returning false signals to the user that this
125 /// reduction already has a value to initialise the accumulator.
126 bool InsertAcc(Value *V) {
127 if (Acc)
128 return false;
129 Acc = V;
130 return true;
131 }
132
133 /// Set two MulCandidates, rooted at muls, that can be executed as a single
134 /// parallel operation.
135 void AddMulPair(MulCandidate *Mul0, MulCandidate *Mul1,
136 bool Exchange = false) {
137 LLVM_DEBUG(dbgs() << "Pairing:\n"
138 << *Mul0->Root << "\n"
139 << *Mul1->Root << "\n");
140 Mul0->Paired = true;
141 Mul1->Paired = true;
142 if (Exchange)
143 Mul1->Exchange = true;
144 MulPairs.push_back(std::make_pair(Mul0, Mul1));
145 }
146
147 /// Return the add instruction which is the root of the reduction.
148 Instruction *getRoot() { return Root; }
149
150 bool is64Bit() const { return Root->getType()->isIntegerTy(64); }
151
152 Type *getType() const { return Root->getType(); }
153
154 /// Return the incoming value to be accumulated. This maybe null.
155 Value *getAccumulator() { return Acc; }
156
157 /// Return the set of adds that comprise the reduction.
158 SetVector<Instruction*> &getAdds() { return Adds; }
159
160 /// Return the MulCandidate, rooted at mul instruction, that comprise the
161 /// the reduction.
162 MulCandList &getMuls() { return Muls; }
163
164 /// Return the MulCandidate, rooted at mul instructions, that have been
165 /// paired for parallel execution.
166 MulPairList &getMulPairs() { return MulPairs; }
167
168 /// To finalise, replace the uses of the root with the intrinsic call.
169 void UpdateRoot(Instruction *SMLAD) {
170 Root->replaceAllUsesWith(SMLAD);
171 }
172
173 void dump() {
174 LLVM_DEBUG(dbgs() << "Reduction:\n";
175 for (auto *Add : Adds)
176 LLVM_DEBUG(dbgs() << *Add << "\n");
177 for (auto &Mul : Muls)
178 LLVM_DEBUG(dbgs() << *Mul->Root << "\n"
179 << " " << *Mul->LHS << "\n"
180 << " " << *Mul->RHS << "\n");
181 LLVM_DEBUG(if (Acc) dbgs() << "Acc in: " << *Acc << "\n")
182 );
183 }
184 };
185
186 class WidenedLoad {
187 LoadInst *NewLd = nullptr;
189
190 public:
191 WidenedLoad(SmallVectorImpl<LoadInst*> &Lds, LoadInst *Wide)
192 : NewLd(Wide) {
193 append_range(Loads, Lds);
194 }
195 LoadInst *getLoad() {
196 return NewLd;
197 }
198 };
199
200 class ARMParallelDSP : public FunctionPass {
201 ScalarEvolution *SE;
202 AliasAnalysis *AA;
203 TargetLibraryInfo *TLI;
204 DominatorTree *DT;
205 const DataLayout *DL;
206 Module *M;
207 const ARMOptions *CLOpts;
208 std::map<LoadInst*, LoadInst*> LoadPairs;
209 SmallPtrSet<LoadInst*, 4> OffsetLoads;
210 std::map<LoadInst*, std::unique_ptr<WidenedLoad>> WideLoads;
211
212 template<unsigned>
213 bool IsNarrowSequence(Value *V);
214 bool Search(Value *V, BasicBlock *BB, Reduction &R);
215 bool RecordMemoryOps(BasicBlock *BB);
216 void InsertParallelMACs(Reduction &Reduction);
217 bool AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1, MemInstList &VecMem);
218 LoadInst* CreateWideLoad(MemInstList &Loads, IntegerType *LoadTy);
219 bool CreateParallelPairs(Reduction &R);
220
221 /// Try to match and generate: SMLAD, SMLADX - Signed Multiply Accumulate
222 /// Dual performs two signed 16x16-bit multiplications. It adds the
223 /// products to a 32-bit accumulate operand. Optionally, the instruction can
224 /// exchange the halfwords of the second operand before performing the
225 /// arithmetic.
226 bool MatchSMLAD(Function &F);
227
228 public:
229 static char ID;
230
231 ARMParallelDSP() : FunctionPass(ID) { }
232
233 void getAnalysisUsage(AnalysisUsage &AU) const override {
234 FunctionPass::getAnalysisUsage(AU);
235 AU.addRequired<ScalarEvolutionWrapperPass>();
236 AU.addRequired<AAResultsWrapperPass>();
237 AU.addRequired<TargetLibraryInfoWrapperPass>();
238 AU.addRequired<DominatorTreeWrapperPass>();
239 AU.addRequired<TargetPassConfig>();
240 AU.addPreserved<ScalarEvolutionWrapperPass>();
241 AU.addPreserved<GlobalsAAWrapperPass>();
242 AU.setPreservesCFG();
243 }
244
245 bool runOnFunction(Function &F) override {
246 if (skipFunction(F))
247 return false;
248
249 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
250 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
251 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
252 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
253 auto &TPC = getAnalysis<TargetPassConfig>();
254
255 M = F.getParent();
256 DL = &M->getDataLayout();
257
258 auto &TM = TPC.getTM<TargetMachine>();
259 auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
260 CLOpts = &ST->getCLOpts();
261 if (CLOpts->disable_arm_parallel_dsp)
262 return false;
263
264 if (!ST->allowsUnalignedMem()) {
265 LLVM_DEBUG(dbgs() << "Unaligned memory access not supported: not "
266 "running pass ARMParallelDSP\n");
267 return false;
268 }
269
270 if (!ST->hasDSP()) {
271 LLVM_DEBUG(dbgs() << "DSP extension not enabled: not running pass "
272 "ARMParallelDSP\n");
273 return false;
274 }
275
276 if (!ST->isLittle()) {
277 LLVM_DEBUG(dbgs() << "Only supporting little endian: not running pass "
278 << "ARMParallelDSP\n");
279 return false;
280 }
281
282 LLVM_DEBUG(dbgs() << "\n== Parallel DSP pass ==\n");
283 LLVM_DEBUG(dbgs() << " - " << F.getName() << "\n\n");
284
285 bool Changes = MatchSMLAD(F);
286 return Changes;
287 }
288 };
289}
290
291bool ARMParallelDSP::AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1,
292 MemInstList &VecMem) {
293 if (!Ld0 || !Ld1)
294 return false;
295
296 auto It = LoadPairs.find(Ld0);
297 if (It == LoadPairs.end() || It->second != Ld1)
298 return false;
299
300 LLVM_DEBUG(dbgs() << "Loads are sequential and valid:\n";
301 dbgs() << "Ld0:"; Ld0->dump();
302 dbgs() << "Ld1:"; Ld1->dump();
303 );
304
305 VecMem.clear();
306 VecMem.push_back(Ld0);
307 VecMem.push_back(Ld1);
308 return true;
309}
310
311// MaxBitwidth: the maximum supported bitwidth of the elements in the DSP
312// instructions, which is set to 16. So here we should collect all i8 and i16
313// narrow operations.
314// TODO: we currently only collect i16, and will support i8 later, so that's
315// why we check that types are equal to MaxBitWidth, and not <= MaxBitWidth.
316template<unsigned MaxBitWidth>
317bool ARMParallelDSP::IsNarrowSequence(Value *V) {
318 if (auto *SExt = dyn_cast<SExtInst>(V)) {
319 if (SExt->getSrcTy()->getIntegerBitWidth() != MaxBitWidth)
320 return false;
321
322 if (auto *Ld = dyn_cast<LoadInst>(SExt->getOperand(0))) {
323 // Check that this load could be paired.
324 return LoadPairs.count(Ld) || OffsetLoads.count(Ld);
325 }
326 }
327 return false;
328}
329
330/// Iterate through the block and record base, offset pairs of loads which can
331/// be widened into a single load.
332bool ARMParallelDSP::RecordMemoryOps(BasicBlock *BB) {
334 SmallVector<Instruction*, 8> Writes;
335 LoadPairs.clear();
336 WideLoads.clear();
337
338 // Collect loads and instruction that may write to memory. For now we only
339 // record loads which are simple, sign-extended and have a single user.
340 // TODO: Allow zero-extended loads.
341 for (auto &I : *BB) {
342 if (I.mayWriteToMemory())
343 Writes.push_back(&I);
344 auto *Ld = dyn_cast<LoadInst>(&I);
345 if (!Ld || !Ld->isSimple() ||
346 !Ld->hasOneUse() || !isa<SExtInst>(Ld->user_back()))
347 continue;
348 Loads.push_back(Ld);
349 }
350
351 if (Loads.empty() || Loads.size() > CLOpts->parallel_dsp_load_limit)
352 return false;
353
354 using InstSet = std::set<Instruction*>;
355 using DepMap = std::map<Instruction*, InstSet>;
356 DepMap RAWDeps;
357
358 // Record any writes that may alias a load.
360 for (auto *Write : Writes) {
361 for (auto *Read : Loads) {
362 MemoryLocation ReadLoc =
363 MemoryLocation(Read->getPointerOperand(), Size);
364
365 if (!isModOrRefSet(AA->getModRefInfo(Write, ReadLoc)))
366 continue;
367 if (Write->comesBefore(Read))
368 RAWDeps[Read].insert(Write);
369 }
370 }
371
372 // Check whether there's not a write between the two loads which would
373 // prevent them from being safely merged.
374 auto SafeToPair = [&](LoadInst *Base, LoadInst *Offset) {
375 bool BaseFirst = Base->comesBefore(Offset);
376 LoadInst *Dominator = BaseFirst ? Base : Offset;
377 LoadInst *Dominated = BaseFirst ? Offset : Base;
378
379 if (auto It = RAWDeps.find(Dominated); It != RAWDeps.end()) {
380 InstSet &WritesBefore = It->second;
381
382 for (auto *Before : WritesBefore) {
383 // We can't move the second load backward, past a write, to merge
384 // with the first load.
385 if (Dominator->comesBefore(Before))
386 return false;
387 }
388 }
389 return true;
390 };
391
392 // Record base, offset load pairs.
393 for (auto *Base : Loads) {
394 for (auto *Offset : Loads) {
395 if (Base == Offset || OffsetLoads.count(Offset))
396 continue;
397
398 if (isConsecutiveAccess(Base, Offset, *DL, *SE) &&
399 SafeToPair(Base, Offset)) {
400 LoadPairs[Base] = Offset;
401 OffsetLoads.insert(Offset);
402 break;
403 }
404 }
405 }
406
407 LLVM_DEBUG(if (!LoadPairs.empty()) {
408 dbgs() << "Consecutive load pairs:\n";
409 for (auto &MapIt : LoadPairs) {
410 LLVM_DEBUG(dbgs() << *MapIt.first << ", "
411 << *MapIt.second << "\n");
412 }
413 });
414 return LoadPairs.size() > 1;
415}
416
417// Search recursively back through the operands to find a tree of values that
418// form a multiply-accumulate chain. The search records the Add and Mul
419// instructions that form the reduction and allows us to find a single value
420// to be used as the initial input to the accumulator.
421bool ARMParallelDSP::Search(Value *V, BasicBlock *BB, Reduction &R) {
422 // If we find a non-instruction, try to use it as the initial accumulator
423 // value. This may have already been found during the search in which case
424 // this function will return false, signaling a search fail.
425 auto *I = dyn_cast<Instruction>(V);
426 if (!I)
427 return R.InsertAcc(V);
428
429 if (I->getParent() != BB)
430 return false;
431
432 switch (I->getOpcode()) {
433 default:
434 break;
435 case Instruction::PHI:
436 // Could be the accumulator value.
437 return R.InsertAcc(V);
438 case Instruction::Add: {
439 // Adds should be adding together two muls, or another add and a mul to
440 // be within the mac chain. One of the operands may also be the
441 // accumulator value at which point we should stop searching.
442 R.InsertAdd(I);
443 Value *LHS = I->getOperand(0);
444 Value *RHS = I->getOperand(1);
445 bool ValidLHS = Search(LHS, BB, R);
446 bool ValidRHS = Search(RHS, BB, R);
447
448 if (ValidLHS && ValidRHS)
449 return true;
450
451 // Ensure we don't add the root as the incoming accumulator.
452 if (R.getRoot() == I)
453 return false;
454
455 return R.InsertAcc(I);
456 }
457 case Instruction::Mul: {
458 Value *MulOp0 = I->getOperand(0);
459 Value *MulOp1 = I->getOperand(1);
460 return IsNarrowSequence<16>(MulOp0) && IsNarrowSequence<16>(MulOp1);
461 }
462 case Instruction::SExt:
463 return Search(I->getOperand(0), BB, R);
464 }
465 return false;
466}
467
468// The pass needs to identify integer add/sub reductions of 16-bit vector
469// multiplications.
470// To use SMLAD:
471// 1) we first need to find integer add then look for this pattern:
472//
473// acc0 = ...
474// ld0 = load i16
475// sext0 = sext i16 %ld0 to i32
476// ld1 = load i16
477// sext1 = sext i16 %ld1 to i32
478// mul0 = mul %sext0, %sext1
479// ld2 = load i16
480// sext2 = sext i16 %ld2 to i32
481// ld3 = load i16
482// sext3 = sext i16 %ld3 to i32
483// mul1 = mul i32 %sext2, %sext3
484// add0 = add i32 %mul0, %acc0
485// acc1 = add i32 %add0, %mul1
486//
487// Which can be selected to:
488//
489// ldr r0
490// ldr r1
491// smlad r2, r0, r1, r2
492//
493// If constants are used instead of loads, these will need to be hoisted
494// out and into a register.
495//
496// If loop invariants are used instead of loads, these need to be packed
497// before the loop begins.
498//
499bool ARMParallelDSP::MatchSMLAD(Function &F) {
500 bool Changed = false;
501
502 for (auto &BB : F) {
503 SmallPtrSet<Instruction*, 4> AllAdds;
504 if (!RecordMemoryOps(&BB))
505 continue;
506
507 for (Instruction &I : reverse(BB)) {
508 if (I.getOpcode() != Instruction::Add)
509 continue;
510
511 if (AllAdds.count(&I))
512 continue;
513
514 const auto *Ty = I.getType();
515 if (!Ty->isIntegerTy(32) && !Ty->isIntegerTy(64))
516 continue;
517
518 Reduction R(&I);
519 if (!Search(&I, &BB, R))
520 continue;
521
522 R.InsertMuls();
523 LLVM_DEBUG(dbgs() << "After search, Reduction:\n"; R.dump());
524
525 if (!CreateParallelPairs(R))
526 continue;
527
528 InsertParallelMACs(R);
529 Changed = true;
530 AllAdds.insert_range(R.getAdds());
531 LLVM_DEBUG(dbgs() << "BB after inserting parallel MACs:\n" << BB);
532 }
533 }
534
535 return Changed;
536}
537
538bool ARMParallelDSP::CreateParallelPairs(Reduction &R) {
539
540 // Not enough mul operations to make a pair.
541 if (R.getMuls().size() < 2)
542 return false;
543
544 // Check that the muls operate directly upon sign extended loads.
545 for (auto &MulCand : R.getMuls()) {
546 if (!MulCand->HasTwoLoadInputs())
547 return false;
548 }
549
550 auto CanPair = [&](Reduction &R, MulCandidate *PMul0, MulCandidate *PMul1) {
551 // The first elements of each vector should be loads with sexts. If we
552 // find that its two pairs of consecutive loads, then these can be
553 // transformed into two wider loads and the users can be replaced with
554 // DSP intrinsics.
555 auto Ld0 = static_cast<LoadInst*>(PMul0->LHS);
556 auto Ld1 = static_cast<LoadInst*>(PMul1->LHS);
557 auto Ld2 = static_cast<LoadInst*>(PMul0->RHS);
558 auto Ld3 = static_cast<LoadInst*>(PMul1->RHS);
559
560 // Check that each mul is operating on two different loads.
561 if (Ld0 == Ld2 || Ld1 == Ld3)
562 return false;
563
564 if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd)) {
565 if (AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
566 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
567 R.AddMulPair(PMul0, PMul1);
568 return true;
569 } else if (AreSequentialLoads(Ld3, Ld2, PMul1->VecLd)) {
570 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
571 LLVM_DEBUG(dbgs() << " exchanging Ld2 and Ld3\n");
572 R.AddMulPair(PMul0, PMul1, true);
573 return true;
574 }
575 } else if (AreSequentialLoads(Ld1, Ld0, PMul0->VecLd) &&
576 AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
577 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
578 LLVM_DEBUG(dbgs() << " exchanging Ld0 and Ld1\n");
579 LLVM_DEBUG(dbgs() << " and swapping muls\n");
580 // Only the second operand can be exchanged, so swap the muls.
581 R.AddMulPair(PMul1, PMul0, true);
582 return true;
583 }
584 return false;
585 };
586
587 MulCandList &Muls = R.getMuls();
588 const unsigned Elems = Muls.size();
589 for (unsigned i = 0; i < Elems; ++i) {
590 MulCandidate *PMul0 = static_cast<MulCandidate*>(Muls[i].get());
591 if (PMul0->Paired)
592 continue;
593
594 for (unsigned j = 0; j < Elems; ++j) {
595 if (i == j)
596 continue;
597
598 MulCandidate *PMul1 = static_cast<MulCandidate*>(Muls[j].get());
599 if (PMul1->Paired)
600 continue;
601
602 const Instruction *Mul0 = PMul0->Root;
603 const Instruction *Mul1 = PMul1->Root;
604 if (Mul0 == Mul1)
605 continue;
606
607 assert(PMul0 != PMul1 && "expected different chains");
608
609 if (CanPair(R, PMul0, PMul1))
610 break;
611 }
612 }
613 return !R.getMulPairs().empty();
614}
615
616void ARMParallelDSP::InsertParallelMACs(Reduction &R) {
617
618 auto CreateSMLAD = [&](LoadInst* WideLd0, LoadInst *WideLd1,
619 Value *Acc, bool Exchange,
620 Instruction *InsertAfter) {
621 // Replace the reduction chain with an intrinsic call
622
623 Value* Args[] = { WideLd0, WideLd1, Acc };
624 Function *SMLAD = nullptr;
625 if (Exchange)
626 SMLAD =
627 Acc->getType()->isIntegerTy(32)
628 ? Intrinsic::getOrInsertDeclaration(M, Intrinsic::arm_smladx)
630 else
631 SMLAD = Acc->getType()->isIntegerTy(32)
632 ? Intrinsic::getOrInsertDeclaration(M, Intrinsic::arm_smlad)
633 : Intrinsic::getOrInsertDeclaration(M, Intrinsic::arm_smlald);
634
635 IRBuilder<NoFolder> Builder(InsertAfter->getIterator());
636 Instruction *Call = Builder.CreateCall(SMLAD, Args);
637 NumSMLAD++;
638 return Call;
639 };
640
641 // Return the instruction after the dominated instruction.
642 auto GetInsertPoint = [this](Value *A, Value *B) {
644 "expected at least one instruction");
645
646 Value *V = nullptr;
647 if (!isa<Instruction>(A))
648 V = B;
649 else if (!isa<Instruction>(B))
650 V = A;
651 else
653
655 };
656
657 Value *Acc = R.getAccumulator();
658
659 // For any muls that were discovered but not paired, accumulate their values
660 // as before.
661 IRBuilder<NoFolder> Builder(R.getRoot()->getParent());
662 MulCandList &MulCands = R.getMuls();
663 for (auto &MulCand : MulCands) {
664 if (MulCand->Paired)
665 continue;
666
667 Instruction *Mul = cast<Instruction>(MulCand->Root);
668 LLVM_DEBUG(dbgs() << "Accumulating unpaired mul: " << *Mul << "\n");
669
670 if (R.getType() != Mul->getType()) {
671 assert(R.is64Bit() && "expected 64-bit result");
672 Builder.SetInsertPoint(&*++BasicBlock::iterator(Mul));
673 Mul = cast<Instruction>(Builder.CreateSExt(Mul, R.getRoot()->getType()));
674 }
675
676 if (!Acc) {
677 Acc = Mul;
678 continue;
679 }
680
681 // If Acc is the original incoming value to the reduction, it could be a
682 // phi. But the phi will dominate Mul, meaning that Mul will be the
683 // insertion point.
684 Builder.SetInsertPoint(GetInsertPoint(Mul, Acc));
685 Acc = Builder.CreateAdd(Mul, Acc);
686 }
687
688 if (!Acc) {
689 Acc = R.is64Bit() ?
690 ConstantInt::get(IntegerType::get(M->getContext(), 64), 0) :
691 ConstantInt::get(IntegerType::get(M->getContext(), 32), 0);
692 } else if (Acc->getType() != R.getType()) {
693 Builder.SetInsertPoint(R.getRoot());
694 Acc = Builder.CreateSExt(Acc, R.getType());
695 }
696
697 // Roughly sort the mul pairs in their program order.
698 llvm::sort(R.getMulPairs(), [](auto &PairA, auto &PairB) {
699 const Instruction *A = PairA.first->Root;
700 const Instruction *B = PairB.first->Root;
701 return A->comesBefore(B);
702 });
703
704 IntegerType *Ty = IntegerType::get(M->getContext(), 32);
705 for (auto &Pair : R.getMulPairs()) {
706 MulCandidate *LHSMul = Pair.first;
707 MulCandidate *RHSMul = Pair.second;
708 LoadInst *BaseLHS = LHSMul->getBaseLoad();
709 LoadInst *BaseRHS = RHSMul->getBaseLoad();
710 auto LIt = WideLoads.find(BaseLHS);
711 LoadInst *WideLHS = LIt != WideLoads.end()
712 ? LIt->second->getLoad()
713 : CreateWideLoad(LHSMul->VecLd, Ty);
714 auto RIt = WideLoads.find(BaseRHS);
715 LoadInst *WideRHS = RIt != WideLoads.end()
716 ? RIt->second->getLoad()
717 : CreateWideLoad(RHSMul->VecLd, Ty);
718
719 Instruction *InsertAfter = GetInsertPoint(WideLHS, WideRHS);
720 InsertAfter = GetInsertPoint(InsertAfter, Acc);
721 Acc = CreateSMLAD(WideLHS, WideRHS, Acc, RHSMul->Exchange, InsertAfter);
722 }
723 R.UpdateRoot(cast<Instruction>(Acc));
724}
725
726LoadInst* ARMParallelDSP::CreateWideLoad(MemInstList &Loads,
727 IntegerType *LoadTy) {
728 assert(Loads.size() == 2 && "currently only support widening two loads");
729
730 LoadInst *Base = Loads[0];
731 LoadInst *Offset = Loads[1];
732
733 Instruction *BaseSExt = dyn_cast<SExtInst>(Base->user_back());
734 Instruction *OffsetSExt = dyn_cast<SExtInst>(Offset->user_back());
735
736 assert((BaseSExt && OffsetSExt)
737 && "Loads should have a single, extending, user");
738
739 std::function<void(Value*, Value*)> MoveBefore =
740 [&](Value *A, Value *B) -> void {
742 return;
743
744 auto *Source = cast<Instruction>(A);
745 auto *Sink = cast<Instruction>(B);
746
747 if (DT->dominates(Source, Sink) ||
748 Source->getParent() != Sink->getParent() ||
749 isa<PHINode>(Source) || isa<PHINode>(Sink))
750 return;
751
752 Source->moveBefore(Sink->getIterator());
753 for (auto &Op : Source->operands())
754 MoveBefore(Op, Source);
755 };
756
757 // Insert the load at the point of the original dominating load.
758 LoadInst *DomLoad = DT->dominates(Base, Offset) ? Base : Offset;
760
761 // Create the wide load, while making sure to maintain the original alignment
762 // as this prevents ldrd from being generated when it could be illegal due to
763 // memory alignment.
764 Value *VecPtr = Base->getPointerOperand();
765 LoadInst *WideLoad = IRB.CreateAlignedLoad(LoadTy, VecPtr, Base->getAlign());
766
767 // Make sure everything is in the correct order in the basic block.
768 MoveBefore(Base->getPointerOperand(), VecPtr);
769 MoveBefore(VecPtr, WideLoad);
770
771 // From the wide load, create two values that equal the original two loads.
772 // Loads[0] needs trunc while Loads[1] needs a lshr and trunc.
773 // TODO: Support big-endian as well.
774 Value *Bottom = IRB.CreateTrunc(WideLoad, Base->getType());
775 Value *NewBaseSExt = IRB.CreateSExt(Bottom, BaseSExt->getType());
776 BaseSExt->replaceAllUsesWith(NewBaseSExt);
777
778 IntegerType *OffsetTy = cast<IntegerType>(Offset->getType());
779 Value *ShiftVal = ConstantInt::get(LoadTy, OffsetTy->getBitWidth());
780 Value *Top = IRB.CreateLShr(WideLoad, ShiftVal);
781 Value *Trunc = IRB.CreateTrunc(Top, OffsetTy);
782 Value *NewOffsetSExt = IRB.CreateSExt(Trunc, OffsetSExt->getType());
783 OffsetSExt->replaceAllUsesWith(NewOffsetSExt);
784
785 LLVM_DEBUG(dbgs() << "From Base and Offset:\n"
786 << *Base << "\n" << *Offset << "\n"
787 << "Created Wide Load:\n"
788 << *WideLoad << "\n"
789 << *Bottom << "\n"
790 << *NewBaseSExt << "\n"
791 << *Top << "\n"
792 << *Trunc << "\n"
793 << *NewOffsetSExt << "\n");
794 WideLoads.emplace(std::make_pair(Base,
795 std::make_unique<WidenedLoad>(Loads, WideLoad)));
796 return WideLoad;
797}
798
800 return new ARMParallelDSP();
801}
802
803char ARMParallelDSP::ID = 0;
804
805INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp",
806 "Transform functions to use DSP intrinsics", false, false)
807INITIALIZE_PASS_END(ARMParallelDSP, "arm-parallel-dsp",
808 "Transform functions to use DSP intrinsics", false, false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static DeltaTreeNode * getRoot(void *Root)
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
Module.h This file contains the declarations for the Module class.
loop Loop Strength Reduction
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#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
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Target-Independent Code Generator Pass Configuration Options pass.
static bool is64Bit(const char *name)
Value * RHS
Value * LHS
BinaryOperator * Mul
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
PointerType * getType() const
Global values are always pointers.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
An instruction for reading from memory.
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
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 replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
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
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
@ Mul
Product of integers.
@ Add
Sum of integers.
LLVM_ABI bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Pass * createARMParallelDSPPass()
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.