blob: cd5b54b35cee68bdbddfe3ae9e4a0e2308a67983 [file] [log] [blame]
James Molloya9290632017-05-25 12:51:11 +00001//===- GVNSink.cpp - sink expressions into successors -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file GVNSink.cpp
11/// This pass attempts to sink instructions into successors, reducing static
12/// instruction count and enabling if-conversion.
13///
14/// We use a variant of global value numbering to decide what can be sunk.
15/// Consider:
16///
17/// [ %a1 = add i32 %b, 1 ] [ %c1 = add i32 %d, 1 ]
18/// [ %a2 = xor i32 %a1, 1 ] [ %c2 = xor i32 %c1, 1 ]
19/// \ /
20/// [ %e = phi i32 %a2, %c2 ]
21/// [ add i32 %e, 4 ]
22///
23///
24/// GVN would number %a1 and %c1 differently because they compute different
25/// results - the VN of an instruction is a function of its opcode and the
26/// transitive closure of its operands. This is the key property for hoisting
27/// and CSE.
28///
29/// What we want when sinking however is for a numbering that is a function of
30/// the *uses* of an instruction, which allows us to answer the question "if I
31/// replace %a1 with %c1, will it contribute in an equivalent way to all
32/// successive instructions?". The PostValueTable class in GVN provides this
33/// mapping.
34///
35//===----------------------------------------------------------------------===//
36
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/DenseMapInfo.h"
39#include "llvm/ADT/DenseSet.h"
40#include "llvm/ADT/Hashing.h"
41#include "llvm/ADT/Optional.h"
42#include "llvm/ADT/PostOrderIterator.h"
43#include "llvm/ADT/SCCIterator.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/Statistic.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/Analysis/GlobalsModRef.h"
48#include "llvm/Analysis/MemorySSA.h"
49#include "llvm/Analysis/PostDominators.h"
50#include "llvm/Analysis/TargetTransformInfo.h"
51#include "llvm/Analysis/ValueTracking.h"
52#include "llvm/IR/Instructions.h"
53#include "llvm/IR/Verifier.h"
54#include "llvm/Support/MathExtras.h"
55#include "llvm/Transforms/Scalar.h"
56#include "llvm/Transforms/Scalar/GVN.h"
57#include "llvm/Transforms/Scalar/GVNExpression.h"
58#include "llvm/Transforms/Utils/BasicBlockUtils.h"
59#include "llvm/Transforms/Utils/Local.h"
60#include <unordered_set>
61using namespace llvm;
62
63#define DEBUG_TYPE "gvn-sink"
64
65STATISTIC(NumRemoved, "Number of instructions removed");
66
67namespace {
68
69static bool isMemoryInst(const Instruction *I) {
70 return isa<LoadInst>(I) || isa<StoreInst>(I) ||
71 (isa<InvokeInst>(I) && !cast<InvokeInst>(I)->doesNotAccessMemory()) ||
72 (isa<CallInst>(I) && !cast<CallInst>(I)->doesNotAccessMemory());
73}
74
75/// Iterates through instructions in a set of blocks in reverse order from the
76/// first non-terminator. For example (assume all blocks have size n):
77/// LockstepReverseIterator I([B1, B2, B3]);
78/// *I-- = [B1[n], B2[n], B3[n]];
79/// *I-- = [B1[n-1], B2[n-1], B3[n-1]];
80/// *I-- = [B1[n-2], B2[n-2], B3[n-2]];
81/// ...
82///
83/// It continues until all blocks have been exhausted. Use \c getActiveBlocks()
84/// to
85/// determine which blocks are still going and the order they appear in the
86/// list returned by operator*.
87class LockstepReverseIterator {
88 ArrayRef<BasicBlock *> Blocks;
89 SmallPtrSet<BasicBlock *, 4> ActiveBlocks;
90 SmallVector<Instruction *, 4> Insts;
91 bool Fail;
92
93public:
94 LockstepReverseIterator(ArrayRef<BasicBlock *> Blocks) : Blocks(Blocks) {
95 reset();
96 }
97
98 void reset() {
99 Fail = false;
100 ActiveBlocks.clear();
101 for (BasicBlock *BB : Blocks)
102 ActiveBlocks.insert(BB);
103 Insts.clear();
104 for (BasicBlock *BB : Blocks) {
105 if (BB->size() <= 1) {
106 // Block wasn't big enough - only contained a terminator.
107 ActiveBlocks.erase(BB);
108 continue;
109 }
110 Insts.push_back(BB->getTerminator()->getPrevNode());
111 }
112 if (Insts.empty())
113 Fail = true;
114 }
115
116 bool isValid() const { return !Fail; }
117 ArrayRef<Instruction *> operator*() const { return Insts; }
118 SmallPtrSet<BasicBlock *, 4> &getActiveBlocks() { return ActiveBlocks; }
119
120 void restrictToBlocks(SmallPtrSetImpl<BasicBlock *> &Blocks) {
121 for (auto II = Insts.begin(); II != Insts.end();) {
122 if (std::find(Blocks.begin(), Blocks.end(), (*II)->getParent()) ==
123 Blocks.end()) {
124 ActiveBlocks.erase((*II)->getParent());
125 II = Insts.erase(II);
126 } else {
127 ++II;
128 }
129 }
130 }
131
132 void operator--() {
133 if (Fail)
134 return;
135 SmallVector<Instruction *, 4> NewInsts;
136 for (auto *Inst : Insts) {
137 if (Inst == &Inst->getParent()->front())
138 ActiveBlocks.erase(Inst->getParent());
139 else
140 NewInsts.push_back(Inst->getPrevNode());
141 }
142 if (NewInsts.empty()) {
143 Fail = true;
144 return;
145 }
146 Insts = NewInsts;
147 }
148};
149
150//===----------------------------------------------------------------------===//
151
152/// Candidate solution for sinking. There may be different ways to
153/// sink instructions, differing in the number of instructions sunk,
154/// the number of predecessors sunk from and the number of PHIs
155/// required.
156struct SinkingInstructionCandidate {
157 unsigned NumBlocks;
158 unsigned NumInstructions;
159 unsigned NumPHIs;
160 unsigned NumMemoryInsts;
161 int Cost = -1;
162 SmallVector<BasicBlock *, 4> Blocks;
163
164 void calculateCost(unsigned NumOrigPHIs, unsigned NumOrigBlocks) {
165 unsigned NumExtraPHIs = NumPHIs - NumOrigPHIs;
166 unsigned SplitEdgeCost = (NumOrigBlocks > NumBlocks) ? 2 : 0;
167 Cost = (NumInstructions * (NumBlocks - 1)) -
168 (NumExtraPHIs *
169 NumExtraPHIs) // PHIs are expensive, so make sure they're worth it.
170 - SplitEdgeCost;
171 }
172 bool operator>=(const SinkingInstructionCandidate &Other) const {
173 return Cost >= Other.Cost;
174 }
175};
176
177llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
178 const SinkingInstructionCandidate &C) {
179 OS << "<Candidate Cost=" << C.Cost << " #Blocks=" << C.NumBlocks
180 << " #Insts=" << C.NumInstructions << " #PHIs=" << C.NumPHIs << ">";
181 return OS;
182}
183
184//===----------------------------------------------------------------------===//
185
186/// Describes a PHI node that may or may not exist. These track the PHIs
187/// that must be created if we sunk a sequence of instructions. It provides
188/// a hash function for efficient equality comparisons.
189class ModelledPHI {
190 SmallVector<Value *, 4> Values;
191 SmallVector<BasicBlock *, 4> Blocks;
192
193public:
194 ModelledPHI() {}
195 ModelledPHI(const PHINode *PN) {
196 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I)
197 Blocks.push_back(PN->getIncomingBlock(I));
198 std::sort(Blocks.begin(), Blocks.end());
199
200 // This assumes the PHI is already well-formed and there aren't conflicting
201 // incoming values for the same block.
202 for (auto *B : Blocks)
203 Values.push_back(PN->getIncomingValueForBlock(B));
204 }
205 /// Create a dummy ModelledPHI that will compare unequal to any other ModelledPHI
206 /// without the same ID.
207 /// \note This is specifically for DenseMapInfo - do not use this!
208 static ModelledPHI createDummy(unsigned ID) {
209 ModelledPHI M;
210 M.Values.push_back(reinterpret_cast<Value*>(ID));
211 return M;
212 }
213
214 /// Create a PHI from an array of incoming values and incoming blocks.
215 template <typename VArray, typename BArray>
216 ModelledPHI(const VArray &V, const BArray &B) {
217 std::copy(V.begin(), V.end(), std::back_inserter(Values));
218 std::copy(B.begin(), B.end(), std::back_inserter(Blocks));
219 }
220
221 /// Create a PHI from [I[OpNum] for I in Insts].
222 template <typename BArray>
223 ModelledPHI(ArrayRef<Instruction *> Insts, unsigned OpNum, const BArray &B) {
224 std::copy(B.begin(), B.end(), std::back_inserter(Blocks));
225 for (auto *I : Insts)
226 Values.push_back(I->getOperand(OpNum));
227 }
228
229 /// Restrict the PHI's contents down to only \c NewBlocks.
230 /// \c NewBlocks must be a subset of \c this->Blocks.
231 void restrictToBlocks(const SmallPtrSetImpl<BasicBlock *> &NewBlocks) {
232 auto BI = Blocks.begin();
233 auto VI = Values.begin();
234 while (BI != Blocks.end()) {
235 assert(VI != Values.end());
236 if (std::find(NewBlocks.begin(), NewBlocks.end(), *BI) ==
237 NewBlocks.end()) {
238 BI = Blocks.erase(BI);
239 VI = Values.erase(VI);
240 } else {
241 ++BI;
242 ++VI;
243 }
244 }
245 assert(Blocks.size() == NewBlocks.size());
246 }
247
248 ArrayRef<Value *> getValues() const { return Values; }
249
250 bool areAllIncomingValuesSame() const {
251 return all_of(Values, [&](Value *V) { return V == Values[0]; });
252 }
253 bool areAllIncomingValuesSameType() const {
254 return all_of(
255 Values, [&](Value *V) { return V->getType() == Values[0]->getType(); });
256 }
257 bool areAnyIncomingValuesConstant() const {
258 return any_of(Values, [&](Value *V) { return isa<Constant>(V); });
259 }
260 // Hash functor
261 unsigned hash() const {
262 return (unsigned)hash_combine_range(Values.begin(), Values.end());
263 }
264 bool operator==(const ModelledPHI &Other) const {
265 return Values == Other.Values && Blocks == Other.Blocks;
266 }
267};
268
269template <typename ModelledPHI> struct DenseMapInfo {
270 static inline ModelledPHI &getEmptyKey() {
271 static ModelledPHI Dummy = ModelledPHI::createDummy(0);
272 return Dummy;
273 }
274 static inline ModelledPHI &getTombstoneKey() {
275 static ModelledPHI Dummy = ModelledPHI::createDummy(1);
276 return Dummy;
277 }
278 static unsigned getHashValue(const ModelledPHI &V) { return V.hash(); }
279 static bool isEqual(const ModelledPHI &LHS, const ModelledPHI &RHS) {
280 return LHS == RHS;
281 }
282};
283
284typedef DenseSet<ModelledPHI, DenseMapInfo<ModelledPHI>> ModelledPHISet;
285
286//===----------------------------------------------------------------------===//
287// ValueTable
288//===----------------------------------------------------------------------===//
289// This is a value number table where the value number is a function of the
290// *uses* of a value, rather than its operands. Thus, if VN(A) == VN(B) we know
291// that the program would be equivalent if we replaced A with PHI(A, B).
292//===----------------------------------------------------------------------===//
293
294/// A GVN expression describing how an instruction is used. The operands
295/// field of BasicExpression is used to store uses, not operands.
296///
297/// This class also contains fields for discriminators used when determining
298/// equivalence of instructions with sideeffects.
299class InstructionUseExpr : public GVNExpression::BasicExpression {
300 unsigned MemoryUseOrder = -1;
301 bool Volatile = false;
302
303public:
304 InstructionUseExpr(Instruction *I, ArrayRecycler<Value *> &R,
305 BumpPtrAllocator &A)
306 : GVNExpression::BasicExpression(I->getNumUses()) {
307 allocateOperands(R, A);
308 setOpcode(I->getOpcode());
309 setType(I->getType());
310
311 for (auto &U : I->uses())
312 op_push_back(U.getUser());
313 std::sort(op_begin(), op_end());
314 }
315 void setMemoryUseOrder(unsigned MUO) { MemoryUseOrder = MUO; }
316 void setVolatile(bool V) { Volatile = V; }
317
318 virtual hash_code getHashValue() const {
319 return hash_combine(GVNExpression::BasicExpression::getHashValue(),
320 MemoryUseOrder, Volatile);
321 }
322
323 template <typename Function> hash_code getHashValue(Function MapFn) {
324 hash_code H =
325 hash_combine(getOpcode(), getType(), MemoryUseOrder, Volatile);
326 for (auto *V : operands())
327 H = hash_combine(H, MapFn(V));
328 return H;
329 }
330};
331
332class ValueTable {
333 DenseMap<Value *, uint32_t> ValueNumbering;
334 DenseMap<GVNExpression::Expression *, uint32_t> ExpressionNumbering;
335 DenseMap<size_t, uint32_t> HashNumbering;
336 BumpPtrAllocator Allocator;
337 ArrayRecycler<Value *> Recycler;
338 uint32_t nextValueNumber;
339
340 /// Create an expression for I based on its opcode and its uses. If I
341 /// touches or reads memory, the expression is also based upon its memory
342 /// order - see \c getMemoryUseOrder().
343 InstructionUseExpr *createExpr(Instruction *I) {
344 InstructionUseExpr *E =
345 new (Allocator) InstructionUseExpr(I, Recycler, Allocator);
346 if (isMemoryInst(I))
347 E->setMemoryUseOrder(getMemoryUseOrder(I));
348
349 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
350 CmpInst::Predicate Predicate = C->getPredicate();
351 E->setOpcode((C->getOpcode() << 8) | Predicate);
352 }
353 return E;
354 }
355
356 /// Helper to compute the value number for a memory instruction
357 /// (LoadInst/StoreInst), including checking the memory ordering and
358 /// volatility.
359 template <class Inst> InstructionUseExpr *createMemoryExpr(Inst *I) {
360 if (isStrongerThanUnordered(I->getOrdering()) || I->isAtomic())
361 return nullptr;
362 InstructionUseExpr *E = createExpr(I);
363 E->setVolatile(I->isVolatile());
364 return E;
365 }
366
367public:
368 /// Returns the value number for the specified value, assigning
369 /// it a new number if it did not have one before.
370 uint32_t lookupOrAdd(Value *V) {
371 auto VI = ValueNumbering.find(V);
372 if (VI != ValueNumbering.end())
373 return VI->second;
374
375 if (!isa<Instruction>(V)) {
376 ValueNumbering[V] = nextValueNumber;
377 return nextValueNumber++;
378 }
379
380 Instruction *I = cast<Instruction>(V);
381 InstructionUseExpr *exp = nullptr;
382 switch (I->getOpcode()) {
383 case Instruction::Load:
384 exp = createMemoryExpr(cast<LoadInst>(I));
385 break;
386 case Instruction::Store:
387 exp = createMemoryExpr(cast<StoreInst>(I));
388 break;
389 case Instruction::Call:
390 case Instruction::Invoke:
391 case Instruction::Add:
392 case Instruction::FAdd:
393 case Instruction::Sub:
394 case Instruction::FSub:
395 case Instruction::Mul:
396 case Instruction::FMul:
397 case Instruction::UDiv:
398 case Instruction::SDiv:
399 case Instruction::FDiv:
400 case Instruction::URem:
401 case Instruction::SRem:
402 case Instruction::FRem:
403 case Instruction::Shl:
404 case Instruction::LShr:
405 case Instruction::AShr:
406 case Instruction::And:
407 case Instruction::Or:
408 case Instruction::Xor:
409 case Instruction::ICmp:
410 case Instruction::FCmp:
411 case Instruction::Trunc:
412 case Instruction::ZExt:
413 case Instruction::SExt:
414 case Instruction::FPToUI:
415 case Instruction::FPToSI:
416 case Instruction::UIToFP:
417 case Instruction::SIToFP:
418 case Instruction::FPTrunc:
419 case Instruction::FPExt:
420 case Instruction::PtrToInt:
421 case Instruction::IntToPtr:
422 case Instruction::BitCast:
423 case Instruction::Select:
424 case Instruction::ExtractElement:
425 case Instruction::InsertElement:
426 case Instruction::ShuffleVector:
427 case Instruction::InsertValue:
428 case Instruction::GetElementPtr:
429 exp = createExpr(I);
430 break;
431 default:
432 break;
433 }
434
435 if (!exp) {
436 ValueNumbering[V] = nextValueNumber;
437 return nextValueNumber++;
438 }
439
440 uint32_t e = ExpressionNumbering[exp];
441 if (!e) {
442 hash_code H = exp->getHashValue([=](Value *V) { return lookupOrAdd(V); });
443 auto I = HashNumbering.find(H);
444 if (I != HashNumbering.end()) {
445 e = I->second;
446 } else {
447 e = nextValueNumber++;
448 HashNumbering[H] = e;
449 ExpressionNumbering[exp] = e;
450 }
451 }
452 ValueNumbering[V] = e;
453 return e;
454 }
455
456 /// Returns the value number of the specified value. Fails if the value has
457 /// not yet been numbered.
458 uint32_t lookup(Value *V) const {
459 auto VI = ValueNumbering.find(V);
460 assert(VI != ValueNumbering.end() && "Value not numbered?");
461 return VI->second;
462 }
463
464 /// Removes all value numberings and resets the value table.
465 void clear() {
466 ValueNumbering.clear();
467 ExpressionNumbering.clear();
468 HashNumbering.clear();
469 Recycler.clear(Allocator);
470 nextValueNumber = 1;
471 }
472
473 ValueTable() : nextValueNumber(1) {}
474
475 /// \c Inst uses or touches memory. Return an ID describing the memory state
476 /// at \c Inst such that if getMemoryUseOrder(I1) == getMemoryUseOrder(I2),
477 /// the exact same memory operations happen after I1 and I2.
478 ///
479 /// This is a very hard problem in general, so we use domain-specific
480 /// knowledge that we only ever check for equivalence between blocks sharing a
481 /// single immediate successor that is common, and when determining if I1 ==
482 /// I2 we will have already determined that next(I1) == next(I2). This
483 /// inductive property allows us to simply return the value number of the next
484 /// instruction that defines memory.
485 uint32_t getMemoryUseOrder(Instruction *Inst) {
486 auto *BB = Inst->getParent();
487 for (auto I = std::next(Inst->getIterator()), E = BB->end();
488 I != E && !I->isTerminator(); ++I) {
489 if (!isMemoryInst(&*I))
490 continue;
491 if (isa<LoadInst>(&*I))
492 continue;
493 CallInst *CI = dyn_cast<CallInst>(&*I);
494 if (CI && CI->onlyReadsMemory())
495 continue;
496 InvokeInst *II = dyn_cast<InvokeInst>(&*I);
497 if (II && II->onlyReadsMemory())
498 continue;
499 return lookupOrAdd(&*I);
500 }
501 return 0;
502 }
503};
504
505//===----------------------------------------------------------------------===//
506
507class GVNSink {
508public:
509 GVNSink() : VN() {}
510 bool run(Function &F) {
511 DEBUG(dbgs() << "GVNSink: running on function @" << F.getName() << "\n");
512
513 unsigned NumSunk = 0;
514 ReversePostOrderTraversal<Function*> RPOT(&F);
515 for (auto *N : RPOT)
516 NumSunk += sinkBB(N);
517
518 return NumSunk > 0;
519 }
520
521private:
522 ValueTable VN;
523
524 bool isInstructionBlacklisted(Instruction *I) {
525 // These instructions may change or break semantics if moved.
526 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
527 I->getType()->isTokenTy())
528 return true;
529 return false;
530 }
531
532 /// The main heuristic function. Analyze the set of instructions pointed to by
533 /// LRI and return a candidate solution if these instructions can be sunk, or
534 /// None otherwise.
535 Optional<SinkingInstructionCandidate> analyzeInstructionForSinking(
536 LockstepReverseIterator &LRI, unsigned &InstNum, unsigned &MemoryInstNum,
537 ModelledPHISet &NeededPHIs, SmallPtrSetImpl<Value *> &PHIContents);
538
539 /// Create a ModelledPHI for each PHI in BB, adding to PHIs.
540 void analyzeInitialPHIs(BasicBlock *BB, ModelledPHISet &PHIs,
541 SmallPtrSetImpl<Value *> &PHIContents) {
542 for (auto &I : *BB) {
543 auto *PN = dyn_cast<PHINode>(&I);
544 if (!PN)
545 return;
546
547 auto MPHI = ModelledPHI(PN);
548 PHIs.insert(MPHI);
549 for (auto *V : MPHI.getValues())
550 PHIContents.insert(V);
551 }
552 }
553
554 /// The main instruction sinking driver. Set up state and try and sink
555 /// instructions into BBEnd from its predecessors.
556 unsigned sinkBB(BasicBlock *BBEnd);
557
558 /// Perform the actual mechanics of sinking an instruction from Blocks into
559 /// BBEnd, which is their only successor.
560 void sinkLastInstruction(ArrayRef<BasicBlock *> Blocks, BasicBlock *BBEnd);
561
562 /// Remove PHIs that all have the same incoming value.
563 void foldPointlessPHINodes(BasicBlock *BB) {
564 auto I = BB->begin();
565 while (PHINode *PN = dyn_cast<PHINode>(I++)) {
566 if (!all_of(PN->incoming_values(),
567 [&](const Value *V) { return V == PN->getIncomingValue(0); }))
568 continue;
569 if (PN->getIncomingValue(0) != PN)
570 PN->replaceAllUsesWith(PN->getIncomingValue(0));
571 else
572 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
573 PN->eraseFromParent();
574 }
575 }
576};
577
578Optional<SinkingInstructionCandidate> GVNSink::analyzeInstructionForSinking(
579 LockstepReverseIterator &LRI, unsigned &InstNum, unsigned &MemoryInstNum,
580 ModelledPHISet &NeededPHIs, SmallPtrSetImpl<Value *> &PHIContents) {
581 auto Insts = *LRI;
582 DEBUG(dbgs() << " -- Analyzing instruction set: [\n"; for (auto *I
583 : Insts) {
584 I->dump();
585 } dbgs() << " ]\n";);
586
587 DenseMap<uint32_t, unsigned> VNums;
588 for (auto *I : Insts) {
589 uint32_t N = VN.lookupOrAdd(I);
590 DEBUG(dbgs() << " VN=" << utohexstr(N) << " for" << *I << "\n");
591 if (N == ~0U)
592 return None;
593 VNums[N]++;
594 }
595 unsigned VNumToSink =
596 std::max_element(VNums.begin(), VNums.end(),
597 [](const std::pair<uint32_t, unsigned> &I,
598 const std::pair<uint32_t, unsigned> &J) {
599 return I.second < J.second;
600 })
601 ->first;
602
603 if (VNums[VNumToSink] == 1)
604 // Can't sink anything!
605 return None;
606
607 // Now restrict the number of incoming blocks down to only those with
608 // VNumToSink.
609 auto &ActivePreds = LRI.getActiveBlocks();
610 unsigned InitialActivePredSize = ActivePreds.size();
611 SmallVector<Instruction *, 4> NewInsts;
612 for (auto *I : Insts) {
613 if (VN.lookup(I) != VNumToSink)
614 ActivePreds.erase(I->getParent());
615 else
616 NewInsts.push_back(I);
617 }
618 for (auto *I : NewInsts)
619 if (isInstructionBlacklisted(I))
620 return None;
621
622 // If we've restricted the incoming blocks, restrict all needed PHIs also
623 // to that set.
624 bool RecomputePHIContents = false;
625 if (ActivePreds.size() != InitialActivePredSize) {
626 ModelledPHISet NewNeededPHIs;
627 for (auto P : NeededPHIs) {
628 P.restrictToBlocks(ActivePreds);
629 NewNeededPHIs.insert(P);
630 }
631 NeededPHIs = NewNeededPHIs;
632 LRI.restrictToBlocks(ActivePreds);
633 RecomputePHIContents = true;
634 }
635
636 // The sunk instruction's results.
637 ModelledPHI NewPHI(NewInsts, ActivePreds);
638
639 // Does sinking this instruction render previous PHIs redundant?
640 if (NeededPHIs.find(NewPHI) != NeededPHIs.end()) {
641 NeededPHIs.erase(NewPHI);
642 RecomputePHIContents = true;
643 }
644
645 if (RecomputePHIContents) {
646 // The needed PHIs have changed, so recompute the set of all needed
647 // values.
648 PHIContents.clear();
649 for (auto &PHI : NeededPHIs)
650 PHIContents.insert(PHI.getValues().begin(), PHI.getValues().end());
651 }
652
653 // Is this instruction required by a later PHI that doesn't match this PHI?
654 // if so, we can't sink this instruction.
655 for (auto *V : NewPHI.getValues())
656 if (PHIContents.count(V))
657 // V exists in this PHI, but the whole PHI is different to NewPHI
658 // (else it would have been removed earlier). We cannot continue
659 // because this isn't representable.
660 return None;
661
662 // Which operands need PHIs?
663 // FIXME: If any of these fail, we should partition up the candidates to
664 // try and continue making progress.
665 Instruction *I0 = NewInsts[0];
666 for (unsigned OpNum = 0, E = I0->getNumOperands(); OpNum != E; ++OpNum) {
667 ModelledPHI PHI(NewInsts, OpNum, ActivePreds);
668 if (PHI.areAllIncomingValuesSame())
669 continue;
670 if (!canReplaceOperandWithVariable(I0, OpNum))
671 // We can 't create a PHI from this instruction!
672 return None;
673 if (NeededPHIs.count(PHI))
674 continue;
675 if (!PHI.areAllIncomingValuesSameType())
676 return None;
677 // Don't create indirect calls! The called value is the final operand.
678 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OpNum == E - 1 &&
679 PHI.areAnyIncomingValuesConstant())
680 return None;
681
682 NeededPHIs.reserve(NeededPHIs.size());
683 NeededPHIs.insert(PHI);
684 PHIContents.insert(PHI.getValues().begin(), PHI.getValues().end());
685 }
686
687 if (isMemoryInst(NewInsts[0]))
688 ++MemoryInstNum;
689
690 SinkingInstructionCandidate Cand;
691 Cand.NumInstructions = ++InstNum;
692 Cand.NumMemoryInsts = MemoryInstNum;
693 Cand.NumBlocks = ActivePreds.size();
694 Cand.NumPHIs = NeededPHIs.size();
695 for (auto *C : ActivePreds)
696 Cand.Blocks.push_back(C);
697
698 return Cand;
699}
700
701unsigned GVNSink::sinkBB(BasicBlock *BBEnd) {
702 DEBUG(dbgs() << "GVNSink: running on basic block ";
703 BBEnd->printAsOperand(dbgs()); dbgs() << "\n");
704 SmallVector<BasicBlock *, 4> Preds;
705 for (auto *B : predecessors(BBEnd)) {
706 auto *T = B->getTerminator();
707 if (isa<BranchInst>(T) || isa<SwitchInst>(T))
708 Preds.push_back(B);
709 else
710 return 0;
711 }
712 if (Preds.size() < 2)
713 return 0;
714 std::sort(Preds.begin(), Preds.end());
715
716 unsigned NumOrigPreds = Preds.size();
717 // We can only sink instructions through unconditional branches.
718 for (auto I = Preds.begin(); I != Preds.end();) {
719 if ((*I)->getTerminator()->getNumSuccessors() != 1)
720 I = Preds.erase(I);
721 else
722 ++I;
723 }
724
725 LockstepReverseIterator LRI(Preds);
726 SmallVector<SinkingInstructionCandidate, 4> Candidates;
727 unsigned InstNum = 0, MemoryInstNum = 0;
728 ModelledPHISet NeededPHIs;
729 SmallPtrSet<Value *, 4> PHIContents;
730 analyzeInitialPHIs(BBEnd, NeededPHIs, PHIContents);
731 unsigned NumOrigPHIs = NeededPHIs.size();
732
733 while (LRI.isValid()) {
734 auto Cand = analyzeInstructionForSinking(LRI, InstNum, MemoryInstNum,
735 NeededPHIs, PHIContents);
736 if (!Cand)
737 break;
738 Cand->calculateCost(NumOrigPHIs, Preds.size());
739 Candidates.emplace_back(*Cand);
740 --LRI;
741 }
742
743 std::stable_sort(
744 Candidates.begin(), Candidates.end(),
745 [](const SinkingInstructionCandidate &A,
746 const SinkingInstructionCandidate &B) { return A >= B; });
747 DEBUG(dbgs() << " -- Sinking candidates:\n"; for (auto &C
748 : Candidates) dbgs()
749 << " " << C << "\n";);
750
751 // Pick the top candidate, as long it is positive!
752 if (Candidates.empty() || Candidates.front().Cost <= 0)
753 return 0;
754 auto C = Candidates.front();
755
756 DEBUG(dbgs() << " -- Sinking: " << C << "\n");
757 BasicBlock *InsertBB = BBEnd;
758 if (C.Blocks.size() < NumOrigPreds) {
759 DEBUG(dbgs() << " -- Splitting edge to "; BBEnd->printAsOperand(dbgs());
760 dbgs() << "\n");
761 InsertBB = SplitBlockPredecessors(BBEnd, C.Blocks, ".gvnsink.split");
762 if (!InsertBB) {
763 DEBUG(dbgs() << " -- FAILED to split edge!\n");
764 // Edge couldn't be split.
765 return 0;
766 }
767 }
768
769 for (unsigned I = 0; I < C.NumInstructions; ++I)
770 sinkLastInstruction(C.Blocks, InsertBB);
771
772 return C.NumInstructions;
773}
774
775void GVNSink::sinkLastInstruction(ArrayRef<BasicBlock *> Blocks,
776 BasicBlock *BBEnd) {
777 SmallVector<Instruction *, 4> Insts;
778 for (BasicBlock *BB : Blocks)
779 Insts.push_back(BB->getTerminator()->getPrevNode());
780 Instruction *I0 = Insts.front();
781
782 SmallVector<Value *, 4> NewOperands;
783 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
784 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
785 return I->getOperand(O) != I0->getOperand(O);
786 });
787 if (!NeedPHI) {
788 NewOperands.push_back(I0->getOperand(O));
789 continue;
790 }
791
792 // Create a new PHI in the successor block and populate it.
793 auto *Op = I0->getOperand(O);
794 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
795 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
796 Op->getName() + ".sink", &BBEnd->front());
797 for (auto *I : Insts)
798 PN->addIncoming(I->getOperand(O), I->getParent());
799 NewOperands.push_back(PN);
800 }
801
802 // Arbitrarily use I0 as the new "common" instruction; remap its operands
803 // and move it to the start of the successor block.
804 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
805 I0->getOperandUse(O).set(NewOperands[O]);
806 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
807
808 // Update metadata and IR flags.
809 for (auto *I : Insts)
810 if (I != I0) {
811 combineMetadataForCSE(I0, I);
812 I0->andIRFlags(I);
813 }
814
815 for (auto *I : Insts)
816 if (I != I0)
817 I->replaceAllUsesWith(I0);
818 foldPointlessPHINodes(BBEnd);
819
820 // Finally nuke all instructions apart from the common instruction.
821 for (auto *I : Insts)
822 if (I != I0)
823 I->eraseFromParent();
824
825 NumRemoved += Insts.size() - 1;
826}
827
828////////////////////////////////////////////////////////////////////////////////
829// Pass machinery / boilerplate
830
831class GVNSinkLegacyPass : public FunctionPass {
832public:
833 static char ID;
834
835 GVNSinkLegacyPass() : FunctionPass(ID) {
836 initializeGVNSinkLegacyPassPass(*PassRegistry::getPassRegistry());
837 }
838
839 bool runOnFunction(Function &F) override {
840 if (skipFunction(F))
841 return false;
842 GVNSink G;
843 return G.run(F);
844 }
845
846 void getAnalysisUsage(AnalysisUsage &AU) const override {
847 AU.addPreserved<GlobalsAAWrapperPass>();
848 }
849};
850} // namespace
851
852PreservedAnalyses GVNSinkPass::run(Function &F, FunctionAnalysisManager &AM) {
853 GVNSink G;
854 if (!G.run(F))
855 return PreservedAnalyses::all();
856
857 PreservedAnalyses PA;
858 PA.preserve<GlobalsAA>();
859 return PA;
860}
861
862char GVNSinkLegacyPass::ID = 0;
863INITIALIZE_PASS_BEGIN(GVNSinkLegacyPass, "gvn-sink",
864 "Early GVN sinking of Expressions", false, false)
865INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
866INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
867INITIALIZE_PASS_END(GVNSinkLegacyPass, "gvn-sink",
868 "Early GVN sinking of Expressions", false, false)
869
870FunctionPass *llvm::createGVNSinkPass() { return new GVNSinkLegacyPass(); }