1//===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===//
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// This pass hoists expressions from branches to a common dominator. It uses
10// GVN (global value numbering) to discover expressions computing the same
11// values. The primary goals of code-hoisting are:
12// 1. To reduce the code size.
13// 2. In some cases reduce critical path (by exposing more ILP).
14//
15// The algorithm factors out the reachability of values such that multiple
16// queries to find reachability of values are fast. This is based on finding the
17// ANTIC points in the CFG which do not change during hoisting. The ANTIC points
18// are basically the dominance-frontiers in the inverse graph. So we introduce a
19// data structure (CHI nodes) to keep track of values flowing out of a basic
20// block. We only do this for values with multiple occurrences in the function
21// as they are the potential hoistable candidates. This approach allows us to
22// hoist instructions to a basic block with more than two successors, as well as
23// deal with infinite loops in a trivial way.
24//
25// Limitations: This pass does not hoist fully redundant expressions because
26// they are already handled by GVN-PRE. It is advisable to run gvn-hoist before
27// and after gvn-pre because gvn-pre creates opportunities for more instructions
28// to be hoisted.
29//
30// Hoisting may affect the performance in some cases. To mitigate that, hoisting
31// is disabled in the following cases.
32// 1. Scalars across calls.
33// 2. geps when corresponding load/store cannot be hoisted.
34//===----------------------------------------------------------------------===//
35
36#include "llvm/Transforms/Scalar/GVNHoist.h"
37#include "ScalarOptions.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/DenseSet.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/iterator_range.h"
45#include "llvm/Analysis/AliasAnalysis.h"
46#include "llvm/Analysis/GlobalsModRef.h"
47#include "llvm/Analysis/IteratedDominanceFrontier.h"
48#include "llvm/Analysis/MemorySSA.h"
49#include "llvm/Analysis/MemorySSAUpdater.h"
50#include "llvm/Analysis/PostDominators.h"
51#include "llvm/Analysis/ValueTracking.h"
52#include "llvm/IR/Argument.h"
53#include "llvm/IR/BasicBlock.h"
54#include "llvm/IR/CFG.h"
55#include "llvm/IR/Constants.h"
56#include "llvm/IR/Dominators.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/Instruction.h"
59#include "llvm/IR/Instructions.h"
60#include "llvm/IR/IntrinsicInst.h"
61#include "llvm/IR/LLVMContext.h"
62#include "llvm/IR/PassManager.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/User.h"
65#include "llvm/IR/Value.h"
66#include "llvm/Support/Casting.h"
67#include "llvm/Support/Debug.h"
68#include "llvm/Support/raw_ostream.h"
69#include "llvm/Transforms/Scalar/GVNValueTable.h"
70#include "llvm/Transforms/Utils/Local.h"
71#include <algorithm>
72#include <cassert>
73#include <memory>
74#include <utility>
75#include <vector>
76
77using namespace llvm;
78
79#define DEBUG_TYPE "gvn-hoist"
80
81STATISTIC(NumHoisted, "Number of instructions hoisted");
82STATISTIC(NumRemoved, "Number of instructions removed");
83STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
84STATISTIC(NumLoadsRemoved, "Number of loads removed");
85STATISTIC(NumStoresHoisted, "Number of stores hoisted");
86STATISTIC(NumStoresRemoved, "Number of stores removed");
87STATISTIC(NumCallsHoisted, "Number of calls hoisted");
88STATISTIC(NumCallsRemoved, "Number of calls removed");
89
90namespace llvm {
91
92using BBSideEffectsSet = DenseMap<const BasicBlock *, bool>;
93using SmallVecInsn = SmallVector<Instruction *, 4>;
94using SmallVecImplInsn = SmallVectorImpl<Instruction *>;
95
96// Each element of a hoisting list contains the basic block where to hoist and
97// a list of instructions to be hoisted.
98using HoistingPointInfo = std::pair<BasicBlock *, SmallVecInsn>;
99
100using HoistingPointList = SmallVector<HoistingPointInfo, 4>;
101
102// A map from a pair of VNs to all the instructions with those VNs.
103using VNType = std::pair<unsigned, uintptr_t>;
104
105using VNtoInsns = DenseMap<VNType, SmallVector<Instruction *, 4>>;
106
107// CHI keeps information about values flowing out of a basic block. It is
108// similar to PHI but in the inverse graph, and used for outgoing values on each
109// edge. For conciseness, it is computed only for instructions with multiple
110// occurrences in the CFG because they are the only hoistable candidates.
111// A (CHI[{V, B, I1}, {V, C, I2}]
112// / \
113// / \
114// B(I1) C (I2)
115// The Value number for both I1 and I2 is V, the CHI node will save the
116// instruction as well as the edge where the value is flowing to.
117struct CHIArg {
118 VNType VN;
119
120 // Edge destination (shows the direction of flow), may not be where the I is.
121 BasicBlock *Dest;
122
123 // The instruction (VN) which uses the values flowing out of CHI.
124 Instruction *I;
125
126 bool operator==(const CHIArg &A) const { return VN == A.VN; }
127 bool operator!=(const CHIArg &A) const { return !(*this == A); }
128};
129
130using CHIIt = SmallVectorImpl<CHIArg>::iterator;
131using CHIArgs = iterator_range<CHIIt>;
132using OutValuesType = DenseMap<BasicBlock *, SmallVector<CHIArg, 2>>;
133using InValuesType =
134 DenseMap<BasicBlock *, SmallVector<std::pair<VNType, Instruction *>, 2>>;
135
136// An invalid value number Used when inserting a single value number into
137// VNtoInsns.
138enum : uintptr_t { InvalidVN = ~(uintptr_t)2 };
139
140// Records all scalar instructions candidate for code hoisting.
141class InsnInfo {
142 VNtoInsns VNtoScalars;
143
144public:
145 // Inserts I and its value number in VNtoScalars.
146 void insert(Instruction *I, GVNValueTable &VN) {
147 // Scalar instruction.
148 unsigned V = VN.lookupOrAdd(V: I);
149 VNtoScalars[{V, InvalidVN}].push_back(Elt: I);
150 }
151
152 const VNtoInsns &getVNTable() const { return VNtoScalars; }
153};
154
155// Records all load instructions candidate for code hoisting.
156class LoadInfo {
157 VNtoInsns VNtoLoads;
158
159public:
160 // Insert Load and the value number of its memory address in VNtoLoads.
161 void insert(LoadInst *Load, GVNValueTable &VN) {
162 if (Load->isSimple()) {
163 unsigned V = VN.lookupOrAdd(V: Load->getPointerOperand());
164 // With opaque pointers we may have loads from the same pointer with
165 // different result types, which should be disambiguated.
166 VNtoLoads[{V, (uintptr_t)Load->getType()}].push_back(Elt: Load);
167 }
168 }
169
170 const VNtoInsns &getVNTable() const { return VNtoLoads; }
171};
172
173// Records all store instructions candidate for code hoisting.
174class StoreInfo {
175 VNtoInsns VNtoStores;
176
177public:
178 // Insert the Store and a hash number of the store address and the stored
179 // value in VNtoStores.
180 void insert(StoreInst *Store, GVNValueTable &VN) {
181 if (!Store->isSimple())
182 return;
183 // Hash the store address and the stored value.
184 Value *Ptr = Store->getPointerOperand();
185 Value *Val = Store->getValueOperand();
186 VNtoStores[{VN.lookupOrAdd(V: Ptr), VN.lookupOrAdd(V: Val)}].push_back(Elt: Store);
187 }
188
189 const VNtoInsns &getVNTable() const { return VNtoStores; }
190};
191
192// Records all call instructions candidate for code hoisting.
193class CallInfo {
194 VNtoInsns VNtoCallsScalars;
195 VNtoInsns VNtoCallsLoads;
196 VNtoInsns VNtoCallsStores;
197
198public:
199 // Insert Call and its value numbering in one of the VNtoCalls* containers.
200 void insert(CallInst *Call, GVNValueTable &VN) {
201 // A call that doesNotAccessMemory is handled as a Scalar,
202 // onlyReadsMemory will be handled as a Load instruction,
203 // all other calls will be handled as stores.
204 unsigned V = VN.lookupOrAdd(V: Call);
205 auto Entry = std::make_pair(x&: V, y: InvalidVN);
206
207 if (Call->doesNotAccessMemory())
208 VNtoCallsScalars[Entry].push_back(Elt: Call);
209 else if (Call->onlyReadsMemory())
210 VNtoCallsLoads[Entry].push_back(Elt: Call);
211 else
212 VNtoCallsStores[Entry].push_back(Elt: Call);
213 }
214
215 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
216 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
217 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
218};
219
220// This pass hoists common computations across branches sharing common
221// dominator. The primary goal is to reduce the code size, and in some
222// cases reduce critical path (by exposing more ILP).
223class GVNHoist {
224public:
225 GVNHoist(DominatorTree *DT, PostDominatorTree *PDT, AliasAnalysis *AA,
226 MemorySSA *MSSA)
227 : Opts(ScalarOptions::Global), DT(DT), PDT(PDT), AA(AA), MSSA(MSSA),
228 MSSAUpdater(std::make_unique<MemorySSAUpdater>(args&: MSSA)) {
229 MSSA->ensureOptimizedUses();
230 }
231
232 bool run(Function &F);
233
234 // Copied from NewGVN.cpp
235 // This function provides global ranking of operations so that we can place
236 // them in a canonical order. Note that rank alone is not necessarily enough
237 // for a complete ordering, as constants all have the same rank. However,
238 // generally, we will simplify an operation with all constants so that it
239 // doesn't matter what order they appear in.
240 unsigned int rank(const Value *V) const;
241
242private:
243 const ScalarOptions &Opts;
244 GVNValueTable VN;
245 DominatorTree *DT;
246 PostDominatorTree *PDT;
247 AliasAnalysis *AA;
248 MemorySSA *MSSA;
249 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
250 DenseMap<const Value *, unsigned> DFSNumber;
251 BBSideEffectsSet BBSideEffects;
252 DenseSet<const BasicBlock *> HoistBarrier;
253 SmallVector<BasicBlock *, 32> IDFBlocks;
254 unsigned NumFuncArgs;
255 const bool HoistingGeps = false;
256
257 enum InsKind { Unknown, Scalar, Load, Store };
258
259 // Return true when there are exception handling in BB.
260 bool hasEH(const BasicBlock *BB);
261
262 // Return true when I1 appears before I2 in the instructions of BB.
263 bool firstInBB(const Instruction *I1, const Instruction *I2) {
264 assert(I1->getParent() == I2->getParent());
265 unsigned I1DFS = DFSNumber.lookup(Val: I1);
266 unsigned I2DFS = DFSNumber.lookup(Val: I2);
267 assert(I1DFS && I2DFS);
268 return I1DFS < I2DFS;
269 }
270
271 // Return true when there are memory uses of Def in BB.
272 bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
273 const BasicBlock *BB);
274
275 bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
276 int &NBBsOnAllPaths);
277
278 // Return true when there are exception handling or loads of memory Def
279 // between Def and NewPt. This function is only called for stores: Def is
280 // the MemoryDef of the store to be hoisted.
281
282 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
283 // return true when the counter NBBsOnAllPaths reaces 0, except when it is
284 // initialized to -1 which is unlimited.
285 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
286 int &NBBsOnAllPaths);
287
288 // Return true when there are exception handling between HoistPt and BB.
289 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
290 // return true when the counter NBBsOnAllPaths reaches 0, except when it is
291 // initialized to -1 which is unlimited.
292 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
293 int &NBBsOnAllPaths);
294
295 // Return true when it is safe to hoist a memory load or store U from OldPt
296 // to NewPt.
297 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
298 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths);
299
300 // Return true when it is safe to hoist scalar instructions from all blocks in
301 // WL to HoistBB.
302 bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB,
303 int &NBBsOnAllPaths) {
304 return !hasEHOnPath(HoistPt: HoistBB, SrcBB: BB, NBBsOnAllPaths);
305 }
306
307 // In the inverse CFG, the dominance frontier of basic block (BB) is the
308 // point where ANTIC needs to be computed for instructions which are going
309 // to be hoisted. Since this point does not change during gvn-hoist,
310 // we compute it only once (on demand).
311 // The ides is inspired from:
312 // "Partial Redundancy Elimination in SSA Form"
313 // ROBERT KENNEDY, SUN CHAN, SHIN-MING LIU, RAYMOND LO, PENG TU and FRED CHOW
314 // They use similar idea in the forward graph to find fully redundant and
315 // partially redundant expressions, here it is used in the inverse graph to
316 // find fully anticipable instructions at merge point (post-dominator in
317 // the inverse CFG).
318 // Returns the edge via which an instruction in BB will get the values from.
319
320 // Returns true when the values are flowing out to each edge.
321 bool valueAnticipable(CHIArgs C, Instruction *TI) const;
322
323 // Check if it is safe to hoist values tracked by CHI in the range
324 // [Begin, End) and accumulate them in Safe.
325 void checkSafety(CHIArgs C, BasicBlock *BB, InsKind K,
326 SmallVectorImpl<CHIArg> &Safe);
327
328 using RenameStackType = DenseMap<VNType, SmallVector<Instruction *, 2>>;
329
330 // Push all the VNs corresponding to BB into RenameStack.
331 void fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
332 RenameStackType &RenameStack);
333
334 void fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
335 RenameStackType &RenameStack);
336
337 // Walk the post-dominator tree top-down and use a stack for each value to
338 // store the last value you see. When you hit a CHI from a given edge, the
339 // value to use as the argument is at the top of the stack, add the value to
340 // CHI and pop.
341 void insertCHI(InValuesType &ValueBBs, OutValuesType &CHIBBs) {
342 auto Root = PDT->getNode(BB: nullptr);
343 if (!Root)
344 return;
345 // Depth first walk on PDom tree to fill the CHIargs at each PDF.
346 for (auto *Node : depth_first(G: Root)) {
347 BasicBlock *BB = Node->getBlock();
348 if (!BB)
349 continue;
350
351 RenameStackType RenameStack;
352 // Collect all values in BB and push to stack.
353 fillRenameStack(BB, ValueBBs, RenameStack);
354
355 // Fill outgoing values in each CHI corresponding to BB.
356 fillChiArgs(BB, CHIBBs, RenameStack);
357 }
358 }
359
360 // Walk all the CHI-nodes to find ones which have a empty-entry and remove
361 // them Then collect all the instructions which are safe to hoist and see if
362 // they form a list of anticipable values. OutValues contains CHIs
363 // corresponding to each basic block.
364 void findHoistableCandidates(OutValuesType &CHIBBs, InsKind K,
365 HoistingPointList &HPL);
366
367 // Compute insertion points for each values which can be fully anticipated at
368 // a dominator. HPL contains all such values.
369 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
370 InsKind K) {
371 // Sort VNs based on their rankings
372 std::vector<VNType> Ranks;
373 for (const auto &Entry : Map) {
374 Ranks.push_back(x: Entry.first);
375 }
376
377 // TODO: Remove fully-redundant expressions.
378 // Get instruction from the Map, assume that all the Instructions
379 // with same VNs have same rank (this is an approximation).
380 llvm::sort(C&: Ranks, Comp: [this, &Map](const VNType &r1, const VNType &r2) {
381 return (rank(V: *Map.lookup(Val: r1).begin()) < rank(V: *Map.lookup(Val: r2).begin()));
382 });
383
384 // - Sort VNs according to their rank, and start with lowest ranked VN
385 // - Take a VN and for each instruction with same VN
386 // - Find the dominance frontier in the inverse graph (PDF)
387 // - Insert the chi-node at PDF
388 // - Remove the chi-nodes with missing entries
389 // - Remove values from CHI-nodes which do not truly flow out, e.g.,
390 // modified along the path.
391 // - Collect the remaining values that are still anticipable
392 SmallVector<BasicBlock *, 2> IDFBlocks;
393 ReverseIDFCalculator IDFs(*PDT);
394 OutValuesType OutValue;
395 InValuesType InValue;
396 for (const auto &R : Ranks) {
397 const SmallVecInsn &V = Map.lookup(Val: R);
398 if (V.size() < 2)
399 continue;
400 const VNType &VN = R;
401 SmallPtrSet<BasicBlock *, 2> VNBlocks;
402 for (const auto &I : V) {
403 BasicBlock *BBI = I->getParent();
404 if (!hasEH(BB: BBI))
405 VNBlocks.insert(Ptr: BBI);
406 }
407 // Compute the Post Dominance Frontiers of each basic block
408 // The dominance frontier of a live block X in the reverse
409 // control graph is the set of blocks upon which X is control
410 // dependent. The following sequence computes the set of blocks
411 // which currently have dead terminators that are control
412 // dependence sources of a block which is in NewLiveBlocks.
413 IDFs.setDefiningBlocks(VNBlocks);
414 IDFBlocks.clear();
415 IDFs.calculate(IDFBlocks);
416
417 // Make a map of BB vs instructions to be hoisted.
418 for (unsigned i = 0; i < V.size(); ++i) {
419 InValue[V[i]->getParent()].push_back(Elt: std::make_pair(x: VN, y: V[i]));
420 }
421 // Insert empty CHI node for this VN. This is used to factor out
422 // basic blocks where the ANTIC can potentially change.
423 CHIArg EmptyChi = {.VN: VN, .Dest: nullptr, .I: nullptr};
424 for (auto *IDFBB : IDFBlocks) {
425 for (unsigned i = 0; i < V.size(); ++i) {
426 // Ignore spurious PDFs.
427 if (DT->properlyDominates(A: IDFBB, B: V[i]->getParent())) {
428 OutValue[IDFBB].push_back(Elt: EmptyChi);
429 LLVM_DEBUG(dbgs() << "\nInserting a CHI for BB: "
430 << IDFBB->getName() << ", for Insn: " << *V[i]);
431 }
432 }
433 }
434 }
435
436 // Insert CHI args at each PDF to iterate on factored graph of
437 // control dependence.
438 insertCHI(ValueBBs&: InValue, CHIBBs&: OutValue);
439 // Using the CHI args inserted at each PDF, find fully anticipable values.
440 findHoistableCandidates(CHIBBs&: OutValue, K, HPL);
441 }
442
443 // Return true when all operands of Instr are available at insertion point
444 // HoistPt. When limiting the number of hoisted expressions, one could hoist
445 // a load without hoisting its access function. So before hoisting any
446 // expression, make sure that all its operands are available at insert point.
447 bool allOperandsAvailable(const Instruction *I,
448 const BasicBlock *HoistPt) const;
449
450 // Same as allOperandsAvailable with recursive check for GEP operands.
451 bool allGepOperandsAvailable(const Instruction *I,
452 const BasicBlock *HoistPt) const;
453
454 // Make all operands of the GEP available.
455 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
456 const SmallVecInsn &InstructionsToHoist,
457 Instruction *Gep) const;
458
459 void updateAlignment(Instruction *I, Instruction *Repl);
460
461 // Remove all the instructions in Candidates and replace their usage with
462 // Repl. Returns the number of instructions removed.
463 unsigned rauw(const SmallVecInsn &Candidates, Instruction *Repl,
464 MemoryUseOrDef *NewMemAcc);
465
466 // Replace all Memory PHI usage with NewMemAcc.
467 void raMPHIuw(MemoryUseOrDef *NewMemAcc);
468
469 // Remove all other instructions and replace them with Repl.
470 unsigned removeAndReplace(const SmallVecInsn &Candidates, Instruction *Repl,
471 BasicBlock *DestBB, bool MoveAccess);
472
473 // In the case Repl is a load or a store, we make all their GEPs
474 // available: GEPs are not hoisted by default to avoid the address
475 // computations to be hoisted without the associated load or store.
476 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
477 const SmallVecInsn &InstructionsToHoist) const;
478
479 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL);
480
481 // Hoist all expressions. Returns Number of scalars hoisted
482 // and number of non-scalars hoisted.
483 std::pair<unsigned, unsigned> hoistExpressions(Function &F);
484};
485
486bool GVNHoist::run(Function &F) {
487 NumFuncArgs = F.arg_size();
488 VN.setDomTree(DT);
489 VN.setAliasAnalysis(AA);
490 // TODO: Is this actually needed?
491 VN.setMemorySSA(M: MSSA, MSSAEnabled: true);
492 bool Res = false;
493 // Perform DFS Numbering of instructions.
494 unsigned BBI = 0;
495 for (const BasicBlock *BB : depth_first(G: &F.getEntryBlock())) {
496 DFSNumber[BB] = ++BBI;
497 unsigned I = 0;
498 for (const auto &Inst : *BB)
499 DFSNumber[&Inst] = ++I;
500 }
501
502 int ChainLength = 0;
503
504 // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
505 while (true) {
506 if (Opts.gvn_hoist_max_chain_length != -1 &&
507 ++ChainLength >= Opts.gvn_hoist_max_chain_length)
508 return Res;
509
510 auto HoistStat = hoistExpressions(F);
511 if (HoistStat.first + HoistStat.second == 0)
512 return Res;
513
514 if (HoistStat.second > 0)
515 // To address a limitation of the current GVN, we need to rerun the
516 // hoisting after we hoisted loads or stores in order to be able to
517 // hoist all scalars dependent on the hoisted ld/st.
518 VN.clear();
519
520 Res = true;
521 }
522
523 return Res;
524}
525
526unsigned int GVNHoist::rank(const Value *V) const {
527 // Prefer constants to undef to anything else
528 // Undef is a constant, have to check it first.
529 // Prefer smaller constants to constantexprs
530 if (isa<ConstantExpr>(Val: V))
531 return 2;
532 if (isa<UndefValue>(Val: V))
533 return 1;
534 if (isa<Constant>(Val: V))
535 return 0;
536 else if (auto *A = dyn_cast<Argument>(Val: V))
537 return 3 + A->getArgNo();
538
539 // Need to shift the instruction DFS by number of arguments + 3 to account
540 // for the constant and argument ranking above.
541 auto Result = DFSNumber.lookup(Val: V);
542 if (Result > 0)
543 return 4 + NumFuncArgs + Result;
544 // Unreachable or something else, just return a really large number.
545 return ~0;
546}
547
548bool GVNHoist::hasEH(const BasicBlock *BB) {
549 auto [It, Inserted] = BBSideEffects.try_emplace(Key: BB);
550 if (!Inserted)
551 return It->second;
552
553 if (BB->isEHPad() || BB->hasAddressTaken()) {
554 It->second = true;
555 return true;
556 }
557
558 if (BB->getTerminator()->mayThrow()) {
559 It->second = true;
560 return true;
561 }
562
563 return false;
564}
565
566bool GVNHoist::hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
567 const BasicBlock *BB) {
568 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
569 if (!Acc)
570 return false;
571
572 Instruction *OldPt = Def->getMemoryInst();
573 const BasicBlock *OldBB = OldPt->getParent();
574 const BasicBlock *NewBB = NewPt->getParent();
575 bool ReachedNewPt = false;
576
577 for (const MemoryAccess &MA : *Acc)
578 if (const MemoryUse *MU = dyn_cast<MemoryUse>(Val: &MA)) {
579 Instruction *Insn = MU->getMemoryInst();
580
581 // Do not check whether MU aliases Def when MU occurs after OldPt.
582 if (BB == OldBB && firstInBB(I1: OldPt, I2: Insn))
583 break;
584
585 // Do not check whether MU aliases Def when MU occurs before NewPt.
586 if (BB == NewBB) {
587 if (!ReachedNewPt) {
588 if (firstInBB(I1: Insn, I2: NewPt))
589 continue;
590 ReachedNewPt = true;
591 }
592 }
593 if (MemorySSAUtil::defClobbersUseOrDef(MD: Def, MU, AA&: *AA))
594 return true;
595 }
596
597 return false;
598}
599
600bool GVNHoist::hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
601 int &NBBsOnAllPaths) {
602 // Stop walk once the limit is reached.
603 if (NBBsOnAllPaths == 0)
604 return true;
605
606 // Impossible to hoist with exceptions on the path.
607 if (hasEH(BB))
608 return true;
609
610 // No such instruction after HoistBarrier in a basic block was
611 // selected for hoisting so instructions selected within basic block with
612 // a hoist barrier can be hoisted.
613 if ((BB != SrcBB) && HoistBarrier.count(V: BB))
614 return true;
615
616 return false;
617}
618
619bool GVNHoist::hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
620 int &NBBsOnAllPaths) {
621 const BasicBlock *NewBB = NewPt->getParent();
622 const BasicBlock *OldBB = Def->getBlock();
623 assert(DT->dominates(NewBB, OldBB) && "invalid path");
624 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
625 "def does not dominate new hoisting point");
626
627 // Walk all basic blocks reachable in depth-first iteration on the inverse
628 // CFG from OldBB to NewBB. These blocks are all the blocks that may be
629 // executed between the execution of NewBB and OldBB. Hoisting an expression
630 // from OldBB into NewBB has to be safe on all execution paths.
631 for (auto I = idf_begin(G: OldBB), E = idf_end(G: OldBB); I != E;) {
632 const BasicBlock *BB = *I;
633 if (BB == NewBB) {
634 // Stop traversal when reaching HoistPt.
635 I.skipChildren();
636 continue;
637 }
638
639 if (hasEHhelper(BB, SrcBB: OldBB, NBBsOnAllPaths))
640 return true;
641
642 // Check that we do not move a store past loads.
643 if (hasMemoryUse(NewPt, Def, BB))
644 return true;
645
646 // -1 is unlimited number of blocks on all paths.
647 if (NBBsOnAllPaths != -1)
648 --NBBsOnAllPaths;
649
650 ++I;
651 }
652
653 return false;
654}
655
656bool GVNHoist::hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
657 int &NBBsOnAllPaths) {
658 assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
659
660 // Walk all basic blocks reachable in depth-first iteration on
661 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
662 // blocks that may be executed between the execution of NewHoistPt and
663 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
664 // on all execution paths.
665 for (auto I = idf_begin(G: SrcBB), E = idf_end(G: SrcBB); I != E;) {
666 const BasicBlock *BB = *I;
667 if (BB == HoistPt) {
668 // Stop traversal when reaching NewHoistPt.
669 I.skipChildren();
670 continue;
671 }
672
673 if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths))
674 return true;
675
676 // -1 is unlimited number of blocks on all paths.
677 if (NBBsOnAllPaths != -1)
678 --NBBsOnAllPaths;
679
680 ++I;
681 }
682
683 return false;
684}
685
686bool GVNHoist::safeToHoistLdSt(const Instruction *NewPt,
687 const Instruction *OldPt, MemoryUseOrDef *U,
688 GVNHoist::InsKind K, int &NBBsOnAllPaths) {
689 // In place hoisting is safe.
690 if (NewPt == OldPt)
691 return true;
692
693 const BasicBlock *NewBB = NewPt->getParent();
694 const BasicBlock *OldBB = OldPt->getParent();
695 const BasicBlock *UBB = U->getBlock();
696
697 // Check for dependences on the Memory SSA.
698 MemoryAccess *D = U->getDefiningAccess();
699 BasicBlock *DBB = D->getBlock();
700 if (DT->properlyDominates(A: NewBB, B: DBB))
701 // Cannot move the load or store to NewBB above its definition in DBB.
702 return false;
703
704 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(MA: D))
705 if (auto *UD = dyn_cast<MemoryUseOrDef>(Val: D))
706 if (!firstInBB(I1: UD->getMemoryInst(), I2: NewPt))
707 // Cannot move the load or store to NewPt above its definition in D.
708 return false;
709
710 // Check for unsafe hoistings due to side effects.
711 if (K == InsKind::Store) {
712 if (hasEHOrLoadsOnPath(NewPt, Def: cast<MemoryDef>(Val: U), NBBsOnAllPaths))
713 return false;
714 } else if (hasEHOnPath(HoistPt: NewBB, SrcBB: OldBB, NBBsOnAllPaths))
715 return false;
716
717 if (UBB == NewBB) {
718 if (DT->properlyDominates(A: DBB, B: NewBB))
719 return true;
720 assert(UBB == DBB);
721 assert(MSSA->locallyDominates(D, U));
722 }
723
724 // No side effects: it is safe to hoist.
725 return true;
726}
727
728bool GVNHoist::valueAnticipable(CHIArgs C, Instruction *TI) const {
729 if (TI->getNumSuccessors() > (unsigned)size(Range&: C))
730 return false; // Not enough args in this CHI.
731
732 for (auto CHI : C) {
733 // Find if all the edges have values flowing out of BB.
734 if (!llvm::is_contained(Range: successors(I: TI), Element: CHI.Dest))
735 return false;
736 }
737 return true;
738}
739
740void GVNHoist::checkSafety(CHIArgs C, BasicBlock *BB, GVNHoist::InsKind K,
741 SmallVectorImpl<CHIArg> &Safe) {
742 int NumBBsOnAllPaths = Opts.gvn_hoist_max_bbs;
743 const Instruction *T = BB->getTerminator();
744 for (auto CHI : C) {
745 Instruction *Insn = CHI.I;
746 if (!Insn) // No instruction was inserted in this CHI.
747 continue;
748 // If the Terminator is some kind of "exotic terminator" that produces a
749 // value (such as InvokeInst, CallBrInst, or CatchSwitchInst) which the CHI
750 // uses, it is not safe to hoist the use above the def.
751 if (!T->use_empty() && is_contained(Range: Insn->operands(), Element: cast<const Value>(Val: T)))
752 continue;
753 if (K == InsKind::Scalar) {
754 if (safeToHoistScalar(HoistBB: BB, BB: Insn->getParent(), NBBsOnAllPaths&: NumBBsOnAllPaths))
755 Safe.push_back(Elt: CHI);
756 } else {
757 if (MemoryUseOrDef *UD = MSSA->getMemoryAccess(I: Insn))
758 if (safeToHoistLdSt(NewPt: T, OldPt: Insn, U: UD, K, NBBsOnAllPaths&: NumBBsOnAllPaths))
759 Safe.push_back(Elt: CHI);
760 }
761 }
762}
763
764void GVNHoist::fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
765 GVNHoist::RenameStackType &RenameStack) {
766 auto it1 = ValueBBs.find(Val: BB);
767 if (it1 != ValueBBs.end()) {
768 // Iterate in reverse order to keep lower ranked values on the top.
769 LLVM_DEBUG(dbgs() << "\nVisiting: " << BB->getName()
770 << " for pushing instructions on stack";);
771 for (std::pair<VNType, Instruction *> &VI : reverse(C&: it1->second)) {
772 // Get the value of instruction I
773 LLVM_DEBUG(dbgs() << "\nPushing on stack: " << *VI.second);
774 RenameStack[VI.first].push_back(Elt: VI.second);
775 }
776 }
777}
778
779void GVNHoist::fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
780 GVNHoist::RenameStackType &RenameStack) {
781 // For each *predecessor* (because Post-DOM) of BB check if it has a CHI
782 for (auto *Pred : predecessors(BB)) {
783 auto P = CHIBBs.find(Val: Pred);
784 if (P == CHIBBs.end()) {
785 continue;
786 }
787 LLVM_DEBUG(dbgs() << "\nLooking at CHIs in: " << Pred->getName(););
788 // A CHI is found (BB -> Pred is an edge in the CFG)
789 // Pop the stack until Top(V) = Ve.
790 auto &VCHI = P->second;
791 for (auto It = VCHI.begin(), E = VCHI.end(); It != E;) {
792 CHIArg &C = *It;
793 if (!C.Dest) {
794 auto si = RenameStack.find(Val: C.VN);
795 // The Basic Block where CHI is must dominate the value we want to
796 // track in a CHI. In the PDom walk, there can be values in the
797 // stack which are not control dependent e.g., nested loop.
798 if (si != RenameStack.end() && si->second.size() &&
799 DT->properlyDominates(A: Pred, B: si->second.back()->getParent())) {
800 C.Dest = BB; // Assign the edge
801 C.I = si->second.pop_back_val(); // Assign the argument
802 LLVM_DEBUG(dbgs()
803 << "\nCHI Inserted in BB: " << C.Dest->getName() << *C.I
804 << ", VN: " << C.VN.first << ", " << C.VN.second);
805 }
806 // Move to next CHI of a different value
807 It = std::find_if(first: It, last: VCHI.end(), pred: not_equal_to(Arg&: *It));
808 } else
809 ++It;
810 }
811 }
812}
813
814void GVNHoist::findHoistableCandidates(OutValuesType &CHIBBs,
815 GVNHoist::InsKind K,
816 HoistingPointList &HPL) {
817 auto cmpVN = [](const CHIArg &A, const CHIArg &B) { return A.VN < B.VN; };
818
819 // CHIArgs now have the outgoing values, so check for anticipability and
820 // accumulate hoistable candidates in HPL.
821 for (auto &A : CHIBBs) {
822 BasicBlock *BB = A.first;
823 SmallVectorImpl<CHIArg> &CHIs = A.second;
824 // Vector of PHIs contains PHIs for different instructions.
825 // Sort the args according to their VNs, such that identical
826 // instructions are together.
827 llvm::stable_sort(Range&: CHIs, C: cmpVN);
828 auto TI = BB->getTerminator();
829 auto B = CHIs.begin();
830 // [PreIt, PHIIt) form a range of CHIs which have identical VNs.
831 auto PHIIt = llvm::find_if(Range&: CHIs, P: not_equal_to(Arg&: *B));
832 auto PrevIt = CHIs.begin();
833 while (PrevIt != PHIIt) {
834 // Collect values which satisfy safety checks.
835 SmallVector<CHIArg, 2> Safe;
836 // We check for safety first because there might be multiple values in
837 // the same path, some of which are not safe to be hoisted, but overall
838 // each edge has at least one value which can be hoisted, making the
839 // value anticipable along that path.
840 checkSafety(C: make_range(x: PrevIt, y: PHIIt), BB, K, Safe);
841
842 // List of safe values should be anticipable at TI.
843 if (valueAnticipable(C: make_range(x: Safe.begin(), y: Safe.end()), TI)) {
844 HPL.push_back(Elt: {BB, SmallVecInsn()});
845 SmallVecInsn &V = HPL.back().second;
846 for (auto B : Safe)
847 V.push_back(Elt: B.I);
848 }
849
850 // Check other VNs
851 PrevIt = PHIIt;
852 PHIIt = std::find_if(first: PrevIt, last: CHIs.end(),
853 pred: [PrevIt](CHIArg &A) { return A != *PrevIt; });
854 }
855 }
856}
857
858bool GVNHoist::allOperandsAvailable(const Instruction *I,
859 const BasicBlock *HoistPt) const {
860 for (const Use &Op : I->operands())
861 if (const auto *Inst = dyn_cast<Instruction>(Val: &Op))
862 if (!DT->dominates(A: Inst->getParent(), B: HoistPt))
863 return false;
864
865 return true;
866}
867
868bool GVNHoist::allGepOperandsAvailable(const Instruction *I,
869 const BasicBlock *HoistPt) const {
870 for (const Use &Op : I->operands())
871 if (const auto *Inst = dyn_cast<Instruction>(Val: &Op))
872 if (!DT->dominates(A: Inst->getParent(), B: HoistPt)) {
873 if (const GetElementPtrInst *GepOp =
874 dyn_cast<GetElementPtrInst>(Val: Inst)) {
875 if (!allGepOperandsAvailable(I: GepOp, HoistPt))
876 return false;
877 // Gep is available if all operands of GepOp are available.
878 } else {
879 // Gep is not available if it has operands other than GEPs that are
880 // defined in blocks not dominating HoistPt.
881 return false;
882 }
883 }
884 return true;
885}
886
887void GVNHoist::makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
888 const SmallVecInsn &InstructionsToHoist,
889 Instruction *Gep) const {
890 assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available");
891
892 Instruction *ClonedGep = Gep->clone();
893 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
894 if (Instruction *Op = dyn_cast<Instruction>(Val: Gep->getOperand(i))) {
895 // Check whether the operand is already available.
896 if (DT->dominates(A: Op->getParent(), B: HoistPt))
897 continue;
898
899 // As a GEP can refer to other GEPs, recursively make all the operands
900 // of this GEP available at HoistPt.
901 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Val: Op))
902 makeGepsAvailable(Repl: ClonedGep, HoistPt, InstructionsToHoist, Gep: GepOp);
903 }
904
905 // Copy Gep and replace its uses in Repl with ClonedGep.
906 ClonedGep->insertBefore(InsertPos: HoistPt->getTerminator()->getIterator());
907
908 // Conservatively discard any optimization hints, they may differ on the
909 // other paths.
910 ClonedGep->dropUnknownNonDebugMetadata();
911
912 // If we have optimization hints which agree with each other along different
913 // paths, preserve them.
914 for (const Instruction *OtherInst : InstructionsToHoist) {
915 const GetElementPtrInst *OtherGep;
916 if (auto *OtherLd = dyn_cast<LoadInst>(Val: OtherInst))
917 OtherGep = cast<GetElementPtrInst>(Val: OtherLd->getPointerOperand());
918 else
919 OtherGep = cast<GetElementPtrInst>(
920 Val: cast<StoreInst>(Val: OtherInst)->getPointerOperand());
921 ClonedGep->andIRFlags(V: OtherGep);
922
923 // Merge debug locations of GEPs, because the hoisted GEP replaces those
924 // in branches. When cloning, ClonedGep preserves the debug location of
925 // Gepd, so Gep is skipped to avoid merging it twice.
926 if (OtherGep != Gep) {
927 ClonedGep->applyMergedLocation(LocA: ClonedGep->getDebugLoc(),
928 LocB: OtherGep->getDebugLoc());
929 }
930 }
931
932 // Replace uses of Gep with ClonedGep in Repl.
933 Repl->replaceUsesOfWith(From: Gep, To: ClonedGep);
934}
935
936void GVNHoist::updateAlignment(Instruction *I, Instruction *Repl) {
937 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Val: Repl)) {
938 ReplacementLoad->setAlignment(
939 std::min(a: ReplacementLoad->getAlign(), b: cast<LoadInst>(Val: I)->getAlign()));
940 ++NumLoadsRemoved;
941 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Val: Repl)) {
942 ReplacementStore->setAlignment(
943 std::min(a: ReplacementStore->getAlign(), b: cast<StoreInst>(Val: I)->getAlign()));
944 ++NumStoresRemoved;
945 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Val: Repl)) {
946 ReplacementAlloca->setAlignment(std::max(a: ReplacementAlloca->getAlign(),
947 b: cast<AllocaInst>(Val: I)->getAlign()));
948 } else if (isa<CallInst>(Val: Repl)) {
949 ++NumCallsRemoved;
950 }
951}
952
953unsigned GVNHoist::rauw(const SmallVecInsn &Candidates, Instruction *Repl,
954 MemoryUseOrDef *NewMemAcc) {
955 unsigned NR = 0;
956 for (Instruction *I : Candidates) {
957 if (I != Repl) {
958 ++NR;
959 updateAlignment(I, Repl);
960 if (NewMemAcc) {
961 // Update the uses of the old MSSA access with NewMemAcc.
962 MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
963 OldMA->replaceAllUsesWith(V: NewMemAcc);
964 MSSAUpdater->removeMemoryAccess(OldMA);
965 } else if (MemoryAccess *OldMA = MSSA->getMemoryAccess(I)) {
966 MSSAUpdater->removeMemoryAccess(OldMA);
967 }
968
969 combineMetadataForCSE(K: Repl, J: I, DoesKMove: true);
970 Repl->andIRFlags(V: I);
971 I->replaceAllUsesWith(V: Repl);
972 I->eraseFromParent();
973 }
974 }
975 return NR;
976}
977
978void GVNHoist::raMPHIuw(MemoryUseOrDef *NewMemAcc) {
979 SmallPtrSet<MemoryPhi *, 4> UsePhis;
980 for (User *U : NewMemAcc->users())
981 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(Val: U))
982 UsePhis.insert(Ptr: Phi);
983
984 for (MemoryPhi *Phi : UsePhis) {
985 auto In = Phi->incoming_values();
986 if (llvm::all_of(Range&: In, P: equal_to(Arg&: NewMemAcc))) {
987 Phi->replaceAllUsesWith(V: NewMemAcc);
988 MSSAUpdater->removeMemoryAccess(Phi);
989 }
990 }
991}
992
993unsigned GVNHoist::removeAndReplace(const SmallVecInsn &Candidates,
994 Instruction *Repl, BasicBlock *DestBB,
995 bool MoveAccess) {
996 MemoryUseOrDef *NewMemAcc = MSSA->getMemoryAccess(I: Repl);
997 if (MoveAccess && NewMemAcc) {
998 // The definition of this ld/st will not change: ld/st hoisting is
999 // legal when the ld/st is not moved past its current definition.
1000 MSSAUpdater->moveToPlace(What: NewMemAcc, BB: DestBB, Where: MemorySSA::BeforeTerminator);
1001 }
1002
1003 // Replace all other instructions with Repl with memory access NewMemAcc.
1004 unsigned NR = rauw(Candidates, Repl, NewMemAcc);
1005
1006 // Remove MemorySSA phi nodes with the same arguments.
1007 if (NewMemAcc)
1008 raMPHIuw(NewMemAcc);
1009 return NR;
1010}
1011
1012bool GVNHoist::makeGepOperandsAvailable(
1013 Instruction *Repl, BasicBlock *HoistPt,
1014 const SmallVecInsn &InstructionsToHoist) const {
1015 // Check whether the GEP of a ld/st can be synthesized at HoistPt.
1016 GetElementPtrInst *Gep = nullptr;
1017 Instruction *Val = nullptr;
1018 if (auto *Ld = dyn_cast<LoadInst>(Val: Repl)) {
1019 Gep = dyn_cast<GetElementPtrInst>(Val: Ld->getPointerOperand());
1020 } else if (auto *St = dyn_cast<StoreInst>(Val: Repl)) {
1021 Gep = dyn_cast<GetElementPtrInst>(Val: St->getPointerOperand());
1022 Val = dyn_cast<Instruction>(Val: St->getValueOperand());
1023 // Check that the stored value is available.
1024 if (Val) {
1025 if (isa<GetElementPtrInst>(Val)) {
1026 // Check whether we can compute the GEP at HoistPt.
1027 if (!allGepOperandsAvailable(I: Val, HoistPt))
1028 return false;
1029 } else if (!DT->dominates(A: Val->getParent(), B: HoistPt))
1030 return false;
1031 }
1032 }
1033
1034 // Check whether we can compute the Gep at HoistPt.
1035 if (!Gep || !allGepOperandsAvailable(I: Gep, HoistPt))
1036 return false;
1037
1038 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
1039
1040 if (Val && isa<GetElementPtrInst>(Val))
1041 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep: Val);
1042
1043 return true;
1044}
1045
1046std::pair<unsigned, unsigned> GVNHoist::hoist(HoistingPointList &HPL) {
1047 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
1048 for (const HoistingPointInfo &HP : HPL) {
1049 // Find out whether we already have one of the instructions in HoistPt,
1050 // in which case we do not have to move it.
1051 BasicBlock *DestBB = HP.first;
1052 const SmallVecInsn &InstructionsToHoist = HP.second;
1053 Instruction *Repl = nullptr;
1054 for (Instruction *I : InstructionsToHoist)
1055 if (I->getParent() == DestBB)
1056 // If there are two instructions in HoistPt to be hoisted in place:
1057 // update Repl to be the first one, such that we can rename the uses
1058 // of the second based on the first.
1059 if (!Repl || firstInBB(I1: I, I2: Repl))
1060 Repl = I;
1061
1062 // Keep track of whether we moved the instruction so we know whether we
1063 // should move the MemoryAccess.
1064 bool MoveAccess = true;
1065 if (Repl) {
1066 // Repl is already in HoistPt: it remains in place.
1067 assert(allOperandsAvailable(Repl, DestBB) &&
1068 "instruction depends on operands that are not available");
1069 MoveAccess = false;
1070 } else {
1071 // When we do not find Repl in HoistPt, select the first in the list
1072 // and move it to HoistPt.
1073 Repl = InstructionsToHoist.front();
1074
1075 // We can move Repl in HoistPt only when all operands are available.
1076 // The order in which hoistings are done may influence the availability
1077 // of operands.
1078 if (!allOperandsAvailable(I: Repl, HoistPt: DestBB)) {
1079 // When HoistingGeps there is nothing more we can do to make the
1080 // operands available: just continue.
1081 if (HoistingGeps)
1082 continue;
1083
1084 // When not HoistingGeps we need to copy the GEPs.
1085 if (!makeGepOperandsAvailable(Repl, HoistPt: DestBB, InstructionsToHoist))
1086 continue;
1087 }
1088
1089 // Move the instruction at the end of HoistPt.
1090 Instruction *Last = DestBB->getTerminator();
1091 if (auto *MUD = MSSA->getMemoryAccess(I: Repl))
1092 MSSAUpdater->moveToPlace(What: MUD, BB: DestBB, Where: MemorySSA::BeforeTerminator);
1093 Repl->moveBefore(InsertPos: Last->getIterator());
1094
1095 DFSNumber[Repl] = DFSNumber[Last]++;
1096 }
1097
1098 // Drop debug location as per debug info update guide.
1099 Repl->dropLocation();
1100 NR += removeAndReplace(Candidates: InstructionsToHoist, Repl, DestBB, MoveAccess);
1101
1102 if (isa<LoadInst>(Val: Repl))
1103 ++NL;
1104 else if (isa<StoreInst>(Val: Repl))
1105 ++NS;
1106 else if (isa<CallInst>(Val: Repl))
1107 ++NC;
1108 else // Scalar
1109 ++NI;
1110 }
1111
1112 if (MSSA && VerifyMemorySSA)
1113 MSSA->verifyMemorySSA();
1114
1115 NumHoisted += NL + NS + NC + NI;
1116 NumRemoved += NR;
1117 NumLoadsHoisted += NL;
1118 NumStoresHoisted += NS;
1119 NumCallsHoisted += NC;
1120 return {NI, NL + NC + NS};
1121}
1122
1123std::pair<unsigned, unsigned> GVNHoist::hoistExpressions(Function &F) {
1124 InsnInfo II;
1125 LoadInfo LI;
1126 StoreInfo SI;
1127 CallInfo CI;
1128 for (BasicBlock *BB : depth_first(G: &F.getEntryBlock())) {
1129 int InstructionNb = 0;
1130 for (Instruction &I1 : *BB) {
1131 // If I1 cannot guarantee progress, subsequent instructions
1132 // in BB cannot be hoisted anyways.
1133 if (!isGuaranteedToTransferExecutionToSuccessor(I: &I1)) {
1134 HoistBarrier.insert(V: BB);
1135 break;
1136 }
1137 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
1138 // deeper may increase the register pressure and compilation time.
1139 if (Opts.gvn_hoist_max_depth != -1 &&
1140 InstructionNb++ >= Opts.gvn_hoist_max_depth)
1141 break;
1142
1143 // Do not value number terminator instructions.
1144 if (I1.isTerminator())
1145 break;
1146
1147 if (auto *Load = dyn_cast<LoadInst>(Val: &I1))
1148 LI.insert(Load, VN);
1149 else if (auto *Store = dyn_cast<StoreInst>(Val: &I1))
1150 SI.insert(Store, VN);
1151 else if (auto *Call = dyn_cast<CallInst>(Val: &I1)) {
1152 if (auto *Intr = dyn_cast<IntrinsicInst>(Val: Call)) {
1153 if (Intr->getIntrinsicID() == Intrinsic::assume ||
1154 Intr->getIntrinsicID() == Intrinsic::sideeffect)
1155 continue;
1156 }
1157 if (Call->mayHaveSideEffects())
1158 break;
1159
1160 if (Call->isConvergent())
1161 break;
1162
1163 CI.insert(Call, VN);
1164 } else if (HoistingGeps || !isa<GetElementPtrInst>(Val: &I1))
1165 // Do not hoist scalars past calls that may write to memory because
1166 // that could result in spills later. geps are handled separately.
1167 // TODO: We can relax this for targets like AArch64 as they have more
1168 // registers than X86.
1169 II.insert(I: &I1, VN);
1170 }
1171 }
1172
1173 HoistingPointList HPL;
1174 computeInsertionPoints(Map: II.getVNTable(), HPL, K: InsKind::Scalar);
1175 computeInsertionPoints(Map: LI.getVNTable(), HPL, K: InsKind::Load);
1176 computeInsertionPoints(Map: SI.getVNTable(), HPL, K: InsKind::Store);
1177 computeInsertionPoints(Map: CI.getScalarVNTable(), HPL, K: InsKind::Scalar);
1178 computeInsertionPoints(Map: CI.getLoadVNTable(), HPL, K: InsKind::Load);
1179 computeInsertionPoints(Map: CI.getStoreVNTable(), HPL, K: InsKind::Store);
1180 return hoist(HPL);
1181}
1182
1183} // end namespace llvm
1184
1185PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
1186 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
1187 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(IR&: F);
1188 AliasAnalysis &AA = AM.getResult<AAManager>(IR&: F);
1189 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(IR&: F).getMSSA();
1190 GVNHoist G(&DT, &PDT, &AA, &MSSA);
1191 if (!G.run(F))
1192 return PreservedAnalyses::all();
1193
1194 PreservedAnalyses PA;
1195 PA.preserve<DominatorTreeAnalysis>();
1196 PA.preserve<MemorySSAAnalysis>();
1197 return PA;
1198}
1199