LLVM 24.0.0git
GVNSink.cpp
Go to the documentation of this file.
1//===- GVNSink.cpp - sink expressions into successors ---------------------===//
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 GVNSink.cpp
10/// This pass attempts to sink instructions into successors, reducing static
11/// instruction count and enabling if-conversion.
12///
13/// We use a variant of global value numbering to decide what can be sunk.
14/// Consider:
15///
16/// [ %a1 = add i32 %b, 1 ] [ %c1 = add i32 %d, 1 ]
17/// [ %a2 = xor i32 %a1, 1 ] [ %c2 = xor i32 %c1, 1 ]
18/// \ /
19/// [ %e = phi i32 %a2, %c2 ]
20/// [ add i32 %e, 4 ]
21///
22///
23/// GVN would number %a1 and %c1 differently because they compute different
24/// results - the VN of an instruction is a function of its opcode and the
25/// transitive closure of its operands. This is the key property for hoisting
26/// and CSE.
27///
28/// What we want when sinking however is for a numbering that is a function of
29/// the *uses* of an instruction, which allows us to answer the question "if I
30/// replace %a1 with %c1, will it contribute in an equivalent way to all
31/// successive instructions?". The PostValueTable class in GVN provides this
32/// mapping.
33//
34//===----------------------------------------------------------------------===//
35
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/Hashing.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/SetVector.h"
45#include "llvm/ADT/Statistic.h"
47#include "llvm/IR/BasicBlock.h"
48#include "llvm/IR/CFG.h"
49#include "llvm/IR/Constants.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
54#include "llvm/IR/PassManager.h"
55#include "llvm/IR/Type.h"
56#include "llvm/IR/Use.h"
57#include "llvm/IR/Value.h"
63#include "llvm/Support/Debug.h"
70#include <cassert>
71#include <cstddef>
72#include <cstdint>
73#include <iterator>
74#include <utility>
75
76using namespace llvm;
77using namespace llvm::GVNExpression;
78
79#define DEBUG_TYPE "gvn-sink"
80
81STATISTIC(NumRemoved, "Number of instructions removed");
82
84 print(dbgs());
85 dbgs() << "\n";
86}
87
88static bool isMemoryInst(const Instruction *I) {
89 return isa<LoadInst>(I) || isa<StoreInst>(I) ||
90 (isa<InvokeInst>(I) && !cast<InvokeInst>(I)->doesNotAccessMemory()) ||
91 (isa<CallInst>(I) && !cast<CallInst>(I)->doesNotAccessMemory());
92}
93
94//===----------------------------------------------------------------------===//
95
96namespace {
97
98/// Candidate solution for sinking. There may be different ways to
99/// sink instructions, differing in the number of instructions sunk,
100/// the number of predecessors sunk from and the number of PHIs
101/// required.
102struct SinkingInstructionCandidate {
103 unsigned NumBlocks;
104 unsigned NumInstructions;
105 unsigned NumPHIs;
106 unsigned NumMemoryInsts;
107 int Cost = -1;
109
110 void calculateCost(unsigned NumOrigPHIs, unsigned NumOrigBlocks) {
111 unsigned NumExtraPHIs = NumPHIs - NumOrigPHIs;
112 unsigned SplitEdgeCost = (NumOrigBlocks > NumBlocks) ? 2 : 0;
113 Cost = (NumInstructions * (NumBlocks - 1)) -
114 (NumExtraPHIs *
115 NumExtraPHIs) // PHIs are expensive, so make sure they're worth it.
116 - SplitEdgeCost;
117 }
118
119 bool operator>(const SinkingInstructionCandidate &Other) const {
120 return Cost > Other.Cost;
121 }
122};
123
124//===----------------------------------------------------------------------===//
125
126/// Describes a PHI node that may or may not exist. These track the PHIs
127/// that must be created if we sunk a sequence of instructions. It provides
128/// a hash function for efficient equality comparisons.
129class ModelledPHI {
130 SmallVector<Value *, 4> Values;
132
133public:
134 ModelledPHI() = default;
135
136 ModelledPHI(const PHINode *PN,
137 const DenseMap<const BasicBlock *, unsigned> &BlockOrder) {
138 // BasicBlock comes first so we sort by basic block pointer order,
139 // then by value pointer order. No need to call `verifyModelledPHI`
140 // As the Values and Blocks are populated in a deterministic order.
141 using OpsType = std::pair<BasicBlock *, Value *>;
143 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I)
145
146 auto ComesBefore = [&](OpsType O1, OpsType O2) {
147 return BlockOrder.lookup(O1.first) < BlockOrder.lookup(O2.first);
148 };
149 // Sort in a deterministic order.
150 llvm::sort(Ops, ComesBefore);
151
152 for (auto &P : Ops) {
153 Blocks.push_back(P.first);
154 Values.push_back(P.second);
155 }
156 }
157
158 /// Create a dummy ModelledPHI that will compare unequal to any other ModelledPHI
159 /// without the same ID.
160 /// \note This is specifically for DenseMapInfo - do not use this!
161 static ModelledPHI createDummy(size_t ID) {
162 ModelledPHI M;
163 M.Values.push_back(reinterpret_cast<Value*>(ID));
164 return M;
165 }
166
167 void
168 verifyModelledPHI(const DenseMap<const BasicBlock *, unsigned> &BlockOrder) {
169 assert(Values.size() > 1 && Blocks.size() > 1 &&
170 "Modelling PHI with less than 2 values");
171 [[maybe_unused]] auto ComesBefore = [&](const BasicBlock *BB1,
172 const BasicBlock *BB2) {
173 return BlockOrder.lookup(BB1) < BlockOrder.lookup(BB2);
174 };
175 assert(llvm::is_sorted(Blocks, ComesBefore));
176 int C = 0;
177 for (const Value *V : Values) {
178 if (!isa<UndefValue>(V)) {
179 assert(cast<Instruction>(V)->getParent() == Blocks[C]);
180 (void)C;
181 }
182 C++;
183 }
184 }
185 /// Create a PHI from an array of incoming values and incoming blocks.
186 ModelledPHI(SmallVectorImpl<Instruction *> &V,
187 SmallSetVector<BasicBlock *, 4> &B,
188 const DenseMap<const BasicBlock *, unsigned> &BlockOrder) {
189 // The order of Values and Blocks are already ordered by the caller.
191 llvm::append_range(Blocks, B);
192 verifyModelledPHI(BlockOrder);
193 }
194
195 /// Create a PHI from [I[OpNum] for I in Insts].
196 /// TODO: Figure out a way to verifyModelledPHI in this constructor.
197 ModelledPHI(ArrayRef<Instruction *> Insts, unsigned OpNum,
198 SmallSetVector<BasicBlock *, 4> &B) {
199 llvm::append_range(Blocks, B);
200 for (auto *I : Insts)
201 Values.push_back(I->getOperand(OpNum));
202 }
203
204 /// Restrict the PHI's contents down to only \c NewBlocks.
205 /// \c NewBlocks must be a subset of \c this->Blocks.
206 void restrictToBlocks(const SmallSetVector<BasicBlock *, 4> &NewBlocks) {
207 auto BI = Blocks.begin();
208 auto VI = Values.begin();
209 while (BI != Blocks.end()) {
210 assert(VI != Values.end());
211 if (!NewBlocks.contains(*BI)) {
212 BI = Blocks.erase(BI);
213 VI = Values.erase(VI);
214 } else {
215 ++BI;
216 ++VI;
217 }
218 }
219 assert(Blocks.size() == NewBlocks.size());
220 }
221
222 ArrayRef<Value *> getValues() const { return Values; }
223
224 bool areAllIncomingValuesSame() const {
225 return llvm::all_equal(Values);
226 }
227
228 bool areAllIncomingValuesSameType() const {
229 return llvm::all_of(
230 Values, [&](Value *V) { return V->getType() == Values[0]->getType(); });
231 }
232
233 bool areAnyIncomingValuesConstant() const {
234 return llvm::any_of(Values, [&](Value *V) { return isa<Constant>(V); });
235 }
236
237 // Hash functor
238 unsigned hash() const {
239 // Is deterministic because Values are saved in a specific order.
240 return (unsigned)hash_combine_range(Values);
241 }
242
243 bool operator==(const ModelledPHI &Other) const {
244 return Values == Other.Values && Blocks == Other.Blocks;
245 }
246};
247} // namespace
248
249#ifndef NDEBUG
251 const SinkingInstructionCandidate &C) {
252 OS << "<Candidate Cost=" << C.Cost << " #Blocks=" << C.NumBlocks
253 << " #Insts=" << C.NumInstructions << " #PHIs=" << C.NumPHIs << ">";
254 return OS;
255}
256#endif
257
258template <> struct llvm::DenseMapInfo<ModelledPHI> {
259 static unsigned getHashValue(const ModelledPHI &V) { return V.hash(); }
260
261 static bool isEqual(const ModelledPHI &LHS, const ModelledPHI &RHS) {
262 return LHS == RHS;
263 }
264};
265
267
268namespace {
269
270//===----------------------------------------------------------------------===//
271// ValueTable
272//===----------------------------------------------------------------------===//
273// This is a value number table where the value number is a function of the
274// *uses* of a value, rather than its operands. Thus, if VN(A) == VN(B) we know
275// that the program would be equivalent if we replaced A with PHI(A, B).
276//===----------------------------------------------------------------------===//
277
278/// A GVN expression describing how an instruction is used. The operands
279/// field of BasicExpression is used to store uses, not operands.
280///
281/// This class also contains fields for discriminators used when determining
282/// equivalence of instructions with sideeffects.
283class InstructionUseExpr : public BasicExpression {
284 unsigned MemoryUseOrder = -1;
285 bool Volatile = false;
286 ArrayRef<int> ShuffleMask;
287
288public:
289 InstructionUseExpr(Instruction *I, ArrayRecycler<Value *> &R,
291 : BasicExpression(I->getNumUses()) {
292 allocateOperands(R, A);
293 setOpcode(I->getOpcode());
294 setType(I->getType());
295
297 ShuffleMask = SVI->getShuffleMask().copy(A);
298
299 for (Instruction *U : I->users())
300 op_push_back(U);
301 llvm::sort(operands());
302 }
303
304 void setMemoryUseOrder(unsigned MUO) { MemoryUseOrder = MUO; }
305 void setVolatile(bool V) { Volatile = V; }
306
307 hash_code getHashValue() const override {
308 return hash_combine(BasicExpression::getHashValue(), MemoryUseOrder,
309 Volatile, ShuffleMask);
310 }
311
312 template <typename Function> hash_code getHashValue(Function MapFn) {
313 hash_code H = hash_combine(getOpcode(), getType(), MemoryUseOrder, Volatile,
314 ShuffleMask);
315 for (auto *V : operands())
316 H = hash_combine(H, MapFn(V));
317 return H;
318 }
319};
320
321using BasicBlocksSet = SmallPtrSet<const BasicBlock *, 32>;
322
323class ValueTable {
324 DenseMap<Value *, uint32_t> ValueNumbering;
325 DenseMap<Expression *, uint32_t> ExpressionNumbering;
326 DenseMap<size_t, uint32_t> HashNumbering;
329 uint32_t nextValueNumber = 1;
330 BasicBlocksSet ReachableBBs;
331
332 /// Create an expression for I based on its opcode and its uses. If I
333 /// touches or reads memory, the expression is also based upon its memory
334 /// order - see \c getMemoryUseOrder().
335 InstructionUseExpr *createExpr(Instruction *I) {
336 InstructionUseExpr *E =
337 new (Allocator) InstructionUseExpr(I, Recycler, Allocator);
338 if (isMemoryInst(I))
339 E->setMemoryUseOrder(getMemoryUseOrder(I));
340
341 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
342 CmpInst::Predicate Predicate = C->getPredicate();
343 E->setOpcode((C->getOpcode() << 8) | Predicate);
344 }
345 return E;
346 }
347
348 /// Helper to compute the value number for a memory instruction
349 /// (LoadInst/StoreInst), including checking the memory ordering and
350 /// volatility.
351 template <class Inst> InstructionUseExpr *createMemoryExpr(Inst *I) {
352 if (isStrongerThanUnordered(I->getOrdering()) || I->isAtomic())
353 return nullptr;
354 InstructionUseExpr *E = createExpr(I);
355 E->setVolatile(I->isVolatile());
356 return E;
357 }
358
359public:
360 ValueTable() = default;
361
362 /// Set basic blocks reachable from entry block.
363 void setReachableBBs(const BasicBlocksSet &ReachableBBs) {
364 this->ReachableBBs = ReachableBBs;
365 }
366
367 /// Returns the value number for the specified value, assigning
368 /// it a new number if it did not have one before.
369 uint32_t lookupOrAdd(Value *V) {
370 auto VI = ValueNumbering.find(V);
371 if (VI != ValueNumbering.end())
372 return VI->second;
373
374 if (!isa<Instruction>(V)) {
375 ValueNumbering[V] = nextValueNumber;
376 return nextValueNumber++;
377 }
378
380 if (!ReachableBBs.contains(I->getParent()))
381 return ~0U;
382
383 InstructionUseExpr *exp = nullptr;
384 switch (I->getOpcode()) {
385 case Instruction::Load:
386 exp = createMemoryExpr(cast<LoadInst>(I));
387 break;
388 case Instruction::Store:
389 exp = createMemoryExpr(cast<StoreInst>(I));
390 break;
391 case Instruction::Call:
392 case Instruction::Invoke:
393 case Instruction::FNeg:
394 case Instruction::Add:
395 case Instruction::FAdd:
396 case Instruction::Sub:
397 case Instruction::FSub:
398 case Instruction::Mul:
399 case Instruction::FMul:
400 case Instruction::UDiv:
401 case Instruction::SDiv:
402 case Instruction::FDiv:
403 case Instruction::URem:
404 case Instruction::SRem:
405 case Instruction::FRem:
406 case Instruction::Shl:
407 case Instruction::LShr:
408 case Instruction::AShr:
409 case Instruction::And:
410 case Instruction::Or:
411 case Instruction::Xor:
412 case Instruction::ICmp:
413 case Instruction::FCmp:
414 case Instruction::Trunc:
415 case Instruction::ZExt:
416 case Instruction::SExt:
417 case Instruction::FPToUI:
418 case Instruction::FPToSI:
419 case Instruction::UIToFP:
420 case Instruction::SIToFP:
421 case Instruction::FPTrunc:
422 case Instruction::FPExt:
423 case Instruction::PtrToInt:
424 case Instruction::PtrToAddr:
425 case Instruction::IntToPtr:
426 case Instruction::BitCast:
427 case Instruction::AddrSpaceCast:
428 case Instruction::Select:
429 case Instruction::ExtractElement:
430 case Instruction::InsertElement:
431 case Instruction::ShuffleVector:
432 case Instruction::InsertValue:
433 case Instruction::GetElementPtr:
434 exp = createExpr(I);
435 break;
436 default:
437 break;
438 }
439
440 if (!exp) {
441 ValueNumbering[V] = nextValueNumber;
442 return nextValueNumber++;
443 }
444
445 uint32_t e = ExpressionNumbering[exp];
446 if (!e) {
447 hash_code H = exp->getHashValue([=](Value *V) { return lookupOrAdd(V); });
448 auto [I, Inserted] = HashNumbering.try_emplace(H, nextValueNumber);
449 e = I->second;
450 if (Inserted)
451 ExpressionNumbering[exp] = nextValueNumber++;
452 }
453 ValueNumbering[V] = e;
454 return e;
455 }
456
457 /// Returns the value number of the specified value. Fails if the value has
458 /// not yet been numbered.
459 uint32_t lookup(Value *V) const {
460 auto VI = ValueNumbering.find(V);
461 assert(VI != ValueNumbering.end() && "Value not numbered?");
462 return VI->second;
463 }
464
465 /// Removes all value numberings and resets the value table.
466 void clear() {
467 ValueNumbering.clear();
468 ExpressionNumbering.clear();
469 HashNumbering.clear();
471 nextValueNumber = 1;
472 }
473
474 /// \c Inst uses or touches memory. Return an ID describing the memory state
475 /// at \c Inst such that if getMemoryUseOrder(I1) == getMemoryUseOrder(I2),
476 /// the exact same memory operations happen after I1 and I2.
477 ///
478 /// This is a very hard problem in general, so we use domain-specific
479 /// knowledge that we only ever check for equivalence between blocks sharing a
480 /// single immediate successor that is common, and when determining if I1 ==
481 /// I2 we will have already determined that next(I1) == next(I2). This
482 /// inductive property allows us to simply return the value number of the next
483 /// instruction that defines memory.
484 uint32_t getMemoryUseOrder(Instruction *Inst) {
485 auto *BB = Inst->getParent();
486 for (auto I = std::next(Inst->getIterator()), E = BB->end();
487 I != E && !I->isTerminator(); ++I) {
488 if (!isMemoryInst(&*I))
489 continue;
490 if (isa<LoadInst>(&*I))
491 continue;
493 if (CI && CI->onlyReadsMemory())
494 continue;
496 if (II && II->onlyReadsMemory())
497 continue;
498 return lookupOrAdd(&*I);
499 }
500 return 0;
501 }
502};
503
504//===----------------------------------------------------------------------===//
505
506class GVNSink {
507public:
508 GVNSink() = default;
509
510 bool run(Function &F) {
511 LLVM_DEBUG(dbgs() << "GVNSink: running on function @" << F.getName()
512 << "\n");
513
514 unsigned NumSunk = 0;
516 VN.setReachableBBs(BasicBlocksSet(llvm::from_range, RPOT));
517 // Populate reverse post-order to order basic blocks in deterministic
518 // order. Any arbitrary ordering will work in this case as long as they are
519 // deterministic. The node ordering of newly created basic blocks
520 // are irrelevant because RPOT(for computing sinkable candidates) is also
521 // obtained ahead of time and only their order are relevant for this pass.
522 unsigned NodeOrdering = 0;
523 RPOTOrder[*RPOT.begin()] = ++NodeOrdering;
524 for (auto *BB : RPOT)
525 if (!pred_empty(BB))
526 RPOTOrder[BB] = ++NodeOrdering;
527 for (auto *N : RPOT)
528 NumSunk += sinkBB(N);
529
530 return NumSunk > 0;
531 }
532
533private:
534 ValueTable VN;
536
537 bool shouldAvoidSinkingInstruction(Instruction *I) {
538 // These instructions may change or break semantics if moved.
539 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
540 I->getType()->isTokenTy())
541 return true;
542 return false;
543 }
544
545 /// The main heuristic function. Analyze the set of instructions pointed to by
546 /// LRI and return a candidate solution if these instructions can be sunk, or
547 /// std::nullopt otherwise.
548 std::optional<SinkingInstructionCandidate>
549 analyzeInstructionForSinking(LockstepReverseIterator<false> &LRI,
550 unsigned &InstNum, unsigned &MemoryInstNum,
551 ModelledPHISet &NeededPHIs,
552 SmallPtrSetImpl<Value *> &PHIContents);
553
554 /// Create a ModelledPHI for each PHI in BB, adding to PHIs.
555 void analyzeInitialPHIs(BasicBlock *BB, ModelledPHISet &PHIs,
556 SmallPtrSetImpl<Value *> &PHIContents) {
557 for (PHINode &PN : BB->phis()) {
558 auto MPHI = ModelledPHI(&PN, RPOTOrder);
559 PHIs.insert(MPHI);
560 PHIContents.insert_range(MPHI.getValues());
561 }
562 }
563
564 /// The main instruction sinking driver. Set up state and try and sink
565 /// instructions into BBEnd from its predecessors.
566 unsigned sinkBB(BasicBlock *BBEnd);
567
568 /// Perform the actual mechanics of sinking an instruction from Blocks into
569 /// BBEnd, which is their only successor.
571
572 /// Remove PHIs that all have the same incoming value.
573 void foldPointlessPHINodes(BasicBlock *BB) {
574 auto I = BB->begin();
575 while (PHINode *PN = dyn_cast<PHINode>(I++)) {
576 if (!llvm::all_of(PN->incoming_values(), [&](const Value *V) {
577 return V == PN->getIncomingValue(0);
578 }))
579 continue;
580 if (PN->getIncomingValue(0) != PN)
582 else
584 PN->eraseFromParent();
585 }
586 }
587};
588} // namespace
589
590std::optional<SinkingInstructionCandidate>
591GVNSink::analyzeInstructionForSinking(LockstepReverseIterator<false> &LRI,
592 unsigned &InstNum,
593 unsigned &MemoryInstNum,
594 ModelledPHISet &NeededPHIs,
595 SmallPtrSetImpl<Value *> &PHIContents) {
596 auto Insts = *LRI;
597 LLVM_DEBUG(dbgs() << " -- Analyzing instruction set: [\n"; for (auto *I
598 : Insts) {
599 I->dump();
600 } dbgs() << " ]\n";);
601
602 DenseMap<uint32_t, unsigned> VNums;
603 for (auto *I : Insts) {
604 uint32_t N = VN.lookupOrAdd(I);
605 LLVM_DEBUG(dbgs() << " VN=" << Twine::utohexstr(N) << " for" << *I << "\n");
606 if (N == ~0U)
607 return std::nullopt;
608 VNums[N]++;
609 }
610 unsigned VNumToSink =
611 llvm::max_element(VNums, [](const auto &L, const auto &R) {
612 return L.second < R.second;
613 })->first;
614
615 if (VNums[VNumToSink] == 1)
616 // Can't sink anything!
617 return std::nullopt;
618
619 // Now restrict the number of incoming blocks down to only those with
620 // VNumToSink.
621 auto &ActivePreds = LRI.getActiveBlocks();
622 unsigned InitialActivePredSize = ActivePreds.size();
623 SmallVector<Instruction *, 4> NewInsts;
624 for (auto *I : Insts) {
625 if (VN.lookup(I) != VNumToSink)
626 ActivePreds.remove(I->getParent());
627 else
628 NewInsts.push_back(I);
629 }
630 for (auto *I : NewInsts)
631 if (shouldAvoidSinkingInstruction(I))
632 return std::nullopt;
633
634 // If we've restricted the incoming blocks, restrict all needed PHIs also
635 // to that set.
636 bool RecomputePHIContents = false;
637 if (ActivePreds.size() != InitialActivePredSize) {
638 ModelledPHISet NewNeededPHIs;
639 for (auto P : NeededPHIs) {
640 P.restrictToBlocks(ActivePreds);
641 NewNeededPHIs.insert(P);
642 }
643 NeededPHIs = NewNeededPHIs;
644 LRI.restrictToBlocks(ActivePreds);
645 RecomputePHIContents = true;
646 }
647
648 // The sunk instruction's results.
649 ModelledPHI NewPHI(NewInsts, ActivePreds, RPOTOrder);
650
651 // Does sinking this instruction render previous PHIs redundant?
652 if (NeededPHIs.remove(NewPHI))
653 RecomputePHIContents = true;
654
655 if (RecomputePHIContents) {
656 // The needed PHIs have changed, so recompute the set of all needed
657 // values.
658 PHIContents.clear();
659 for (auto &PHI : NeededPHIs)
660 PHIContents.insert_range(PHI.getValues());
661 }
662
663 // Is this instruction required by a later PHI that doesn't match this PHI?
664 // if so, we can't sink this instruction.
665 for (auto *V : NewPHI.getValues())
666 if (PHIContents.count(V))
667 // V exists in this PHI, but the whole PHI is different to NewPHI
668 // (else it would have been removed earlier). We cannot continue
669 // because this isn't representable.
670 return std::nullopt;
671
672 // Which operands need PHIs?
673 // FIXME: If any of these fail, we should partition up the candidates to
674 // try and continue making progress.
675 Instruction *I0 = NewInsts[0];
676
677 auto isNotSameOperation = [&I0](Instruction *I) {
678 return !I0->isSameOperationAs(I);
679 };
680
681 if (any_of(NewInsts, isNotSameOperation))
682 return std::nullopt;
683
684 for (unsigned OpNum = 0, E = I0->getNumOperands(); OpNum != E; ++OpNum) {
685 ModelledPHI PHI(NewInsts, OpNum, ActivePreds);
686 if (PHI.areAllIncomingValuesSame())
687 continue;
688 if (!canReplaceOperandWithVariable(I0, OpNum))
689 // We can 't create a PHI from this instruction!
690 return std::nullopt;
691 if (NeededPHIs.count(PHI))
692 continue;
693 if (!PHI.areAllIncomingValuesSameType())
694 return std::nullopt;
695 // Don't create indirect calls! The called value is the final operand.
696 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OpNum == E - 1 &&
697 PHI.areAnyIncomingValuesConstant())
698 return std::nullopt;
699
700 NeededPHIs.insert(PHI);
701 PHIContents.insert_range(PHI.getValues());
702 }
703
704 if (isMemoryInst(NewInsts[0]))
705 ++MemoryInstNum;
706
707 SinkingInstructionCandidate Cand;
708 Cand.NumInstructions = ++InstNum;
709 Cand.NumMemoryInsts = MemoryInstNum;
710 Cand.NumBlocks = ActivePreds.size();
711 Cand.NumPHIs = NeededPHIs.size();
712 append_range(Cand.Blocks, ActivePreds);
713
714 return Cand;
715}
716
717unsigned GVNSink::sinkBB(BasicBlock *BBEnd) {
718 LLVM_DEBUG(dbgs() << "GVNSink: running on basic block ";
719 BBEnd->printAsOperand(dbgs()); dbgs() << "\n");
721 for (auto *B : predecessors(BBEnd)) {
722 // Bailout on basic blocks without predecessor(PR42346).
723 if (!RPOTOrder.count(B))
724 return 0;
725 auto *T = B->getTerminator();
727 Preds.push_back(B);
728 else
729 return 0;
730 }
731 if (Preds.size() < 2)
732 return 0;
733 auto ComesBefore = [this](const BasicBlock *BB1, const BasicBlock *BB2) {
734 return RPOTOrder.lookup(BB1) < RPOTOrder.lookup(BB2);
735 };
736 // Sort in a deterministic order.
737 llvm::sort(Preds, ComesBefore);
738
739 unsigned NumOrigPreds = Preds.size();
740 // We can only sink instructions through unconditional branches.
741 llvm::erase_if(Preds, [](BasicBlock *BB) {
742 return BB->getTerminator()->getNumSuccessors() != 1;
743 });
744
745 LockstepReverseIterator<false> LRI(Preds);
747 unsigned InstNum = 0, MemoryInstNum = 0;
748 ModelledPHISet NeededPHIs;
749 SmallPtrSet<Value *, 4> PHIContents;
750 analyzeInitialPHIs(BBEnd, NeededPHIs, PHIContents);
751 unsigned NumOrigPHIs = NeededPHIs.size();
752
753 while (LRI.isValid()) {
754 auto Cand = analyzeInstructionForSinking(LRI, InstNum, MemoryInstNum,
755 NeededPHIs, PHIContents);
756 if (!Cand)
757 break;
758 Cand->calculateCost(NumOrigPHIs, Preds.size());
759 Candidates.emplace_back(*Cand);
760 --LRI;
761 }
762
763 llvm::stable_sort(Candidates, std::greater<SinkingInstructionCandidate>());
764 LLVM_DEBUG(dbgs() << " -- Sinking candidates:\n"; for (auto &C
765 : Candidates) dbgs()
766 << " " << C << "\n";);
767
768 // Pick the top candidate, as long it is positive!
769 if (Candidates.empty() || Candidates.front().Cost <= 0)
770 return 0;
771 auto C = Candidates.front();
772
773 LLVM_DEBUG(dbgs() << " -- Sinking: " << C << "\n");
774 BasicBlock *InsertBB = BBEnd;
775 if (C.Blocks.size() < NumOrigPreds) {
776 LLVM_DEBUG(dbgs() << " -- Splitting edge to ";
777 BBEnd->printAsOperand(dbgs()); dbgs() << "\n");
778 InsertBB = SplitBlockPredecessors(BBEnd, C.Blocks, ".gvnsink.split");
779 if (!InsertBB) {
780 LLVM_DEBUG(dbgs() << " -- FAILED to split edge!\n");
781 // Edge couldn't be split.
782 return 0;
783 }
784 }
785
786 for (unsigned I = 0; I < C.NumInstructions; ++I)
787 sinkLastInstruction(C.Blocks, InsertBB);
788
789 return C.NumInstructions;
790}
791
792void GVNSink::sinkLastInstruction(ArrayRef<BasicBlock *> Blocks,
793 BasicBlock *BBEnd) {
794 SmallVector<Instruction *, 4> Insts;
795 for (BasicBlock *BB : Blocks)
796 Insts.push_back(BB->getTerminator()->getPrevNode());
797 Instruction *I0 = Insts.front();
798
799 SmallVector<Value *, 4> NewOperands;
800 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
801 bool NeedPHI = llvm::any_of(Insts, [&I0, O](const Instruction *I) {
802 return I->getOperand(O) != I0->getOperand(O);
803 });
804 if (!NeedPHI) {
805 NewOperands.push_back(I0->getOperand(O));
806 continue;
807 }
808
809 // Create a new PHI in the successor block and populate it.
810 auto *Op = I0->getOperand(O);
811 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
812 auto *PN =
813 PHINode::Create(Op->getType(), Insts.size(), Op->getName() + ".sink");
814 PN->insertBefore(BBEnd->begin());
815 for (auto *I : Insts)
816 PN->addIncoming(I->getOperand(O), I->getParent());
817 NewOperands.push_back(PN);
818 }
819
820 // Arbitrarily use I0 as the new "common" instruction; remap its operands
821 // and move it to the start of the successor block.
822 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
823 I0->getOperandUse(O).set(NewOperands[O]);
824 I0->moveBefore(BBEnd->getFirstInsertionPt());
825
826 // Update metadata and IR flags.
827 for (auto *I : Insts)
828 if (I != I0) {
829 combineMetadataForCSE(I0, I, true);
830 I0->andIRFlags(I);
831 }
832
833 for (auto *I : Insts)
834 if (I != I0) {
835 I->replaceAllUsesWith(I0);
836 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
837 }
838 foldPointlessPHINodes(BBEnd);
839
840 // Finally nuke all instructions apart from the common instruction.
841 for (auto *I : Insts)
842 if (I != I0)
843 I->eraseFromParent();
844
845 NumRemoved += Insts.size() - 1;
846}
847
849 GVNSink G;
850 if (!G.run(F))
851 return PreservedAnalyses::all();
852
854}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
This file defines the BumpPtrAllocator interface.
Atomic ordering constants.
static const Function * getParent(const Value *V)
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_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
The header file for the GVN pass that contains expression handling classes.
SetVector< ModelledPHI > ModelledPHISet
Definition GVNSink.cpp:266
This file provides the interface for the GVNSink pass.
This is the interface for a simple mod/ref and alias analysis over globals.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
#define T
uint64_t IntrinsicInst * II
#define P(N)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
Basic Register Allocator
static bool isMemoryInst(const MachineInstr &MI)
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
static void sinkLastInstruction(ArrayRef< BasicBlock * > Blocks)
This file defines the SmallPtrSet class.
This file defines the SmallVector 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
Recycle small arrays allocated from a BumpPtrAllocator.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:508
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 Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
bool onlyReadsMemory(unsigned OpNo) const
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
hash_code getHashValue() const override
LLVM_DUMP_METHOD void dump() const
Definition GVNSink.cpp:83
void print(raw_ostream &OS) const
LLVM_ABI bool isSameOperationAs(const Instruction *I, unsigned flags=0) const LLVM_READONLY
This function determines if the specified instruction executes the same operation as the current one.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
Invoke instruction.
Iterates through instructions in a set of blocks in reverse order from the first non-terminator.
void restrictToBlocks(SmallSetVector< BasicBlock *, 4 > &Blocks)
SmallSetVector< BasicBlock *, 4 > & getActiveBlocks()
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Recycler - This class manages a linked-list of deallocated nodes and facilitates reusing deallocated ...
Definition Recycler.h:37
void clear(AllocatorType &Allocator)
clear - Release all the tracked allocations to the allocator.
Definition Recycler.h:75
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This instruction constructs a fixed permutation of two input vectors.
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)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
LLVM_ABI void set(Value *Val)
Definition Value.h:876
const Use & getOperandUse(unsigned i) const
Definition User.h:220
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 replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
An opaque object representing a hash code.
Definition Hashing.h:77
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
SmallVector< ValueIDNum, 0 > ValueTable
Type for a table of values in a block.
raw_ostream & operator<<(raw_ostream &OS, const Expression &E)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2132
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
InstructionCost Cost
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
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
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
bool isStrongerThanUnordered(AtomicOrdering AO)
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool operator>(int64_t V1, const APSInt &V2)
Definition APSInt.h:361
LLVM_READONLY LLVM_ABI std::optional< APFloat > exp(const APFloat &X, RoundingMode RM=APFloat::rmNearestTiesToEven, APFloat::opStatus *Status=nullptr)
Implement IEEE 754-2019 exp functions.
Definition APFloat.cpp:6496
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
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
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
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Definition Local.cpp:3658
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
auto predecessors(const MachineBasicBlock *BB)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
#define N
static bool isEqual(const ModelledPHI &LHS, const ModelledPHI &RHS)
Definition GVNSink.cpp:261
static unsigned getHashValue(const ModelledPHI &V)
Definition GVNSink.cpp:259
An information struct used to provide DenseMap with the various necessary components for a given valu...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition GVNSink.cpp:848