blob: 8b1fde0e89cbc1e19eaaae4e9843f412aeacf213 [file] [log] [blame]
Davide Italiano7e274e02016-12-22 16:03:48 +00001//===---- NewGVN.cpp - Global Value Numbering Pass --------------*- C++ -*-===//
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/// \file
10/// This file implements the new LLVM's Global Value Numbering pass.
11/// GVN partitions values computed by a function into congruence classes.
12/// Values ending up in the same congruence class are guaranteed to be the same
13/// for every execution of the program. In that respect, congruency is a
14/// compile-time approximation of equivalence of values at runtime.
15/// The algorithm implemented here uses a sparse formulation and it's based
16/// on the ideas described in the paper:
17/// "A Sparse Algorithm for Predicated Global Value Numbering" from
18/// Karthik Gargi.
19///
Daniel Berlindb3c7be2017-01-26 21:39:49 +000020/// A brief overview of the algorithm: The algorithm is essentially the same as
21/// the standard RPO value numbering algorithm (a good reference is the paper
22/// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
23/// The RPO algorithm proceeds, on every iteration, to process every reachable
24/// block and every instruction in that block. This is because the standard RPO
25/// algorithm does not track what things have the same value number, it only
26/// tracks what the value number of a given operation is (the mapping is
27/// operation -> value number). Thus, when a value number of an operation
28/// changes, it must reprocess everything to ensure all uses of a value number
29/// get updated properly. In constrast, the sparse algorithm we use *also*
30/// tracks what operations have a given value number (IE it also tracks the
31/// reverse mapping from value number -> operations with that value number), so
32/// that it only needs to reprocess the instructions that are affected when
33/// something's value number changes. The rest of the algorithm is devoted to
34/// performing symbolic evaluation, forward propagation, and simplification of
35/// operations based on the value numbers deduced so far.
36///
37/// We also do not perform elimination by using any published algorithm. All
38/// published algorithms are O(Instructions). Instead, we use a technique that
39/// is O(number of operations with the same value number), enabling us to skip
40/// trying to eliminate things that have unique value numbers.
Davide Italiano7e274e02016-12-22 16:03:48 +000041//===----------------------------------------------------------------------===//
42
43#include "llvm/Transforms/Scalar/NewGVN.h"
44#include "llvm/ADT/BitVector.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/DenseSet.h"
47#include "llvm/ADT/DepthFirstIterator.h"
48#include "llvm/ADT/Hashing.h"
49#include "llvm/ADT/MapVector.h"
50#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000051#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000052#include "llvm/ADT/SmallPtrSet.h"
53#include "llvm/ADT/SmallSet.h"
54#include "llvm/ADT/SparseBitVector.h"
55#include "llvm/ADT/Statistic.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include "llvm/Analysis/AliasAnalysis.h"
58#include "llvm/Analysis/AssumptionCache.h"
59#include "llvm/Analysis/CFG.h"
60#include "llvm/Analysis/CFGPrinter.h"
61#include "llvm/Analysis/ConstantFolding.h"
62#include "llvm/Analysis/GlobalsModRef.h"
63#include "llvm/Analysis/InstructionSimplify.h"
64#include "llvm/Analysis/Loads.h"
65#include "llvm/Analysis/MemoryBuiltins.h"
66#include "llvm/Analysis/MemoryDependenceAnalysis.h"
67#include "llvm/Analysis/MemoryLocation.h"
68#include "llvm/Analysis/PHITransAddr.h"
69#include "llvm/Analysis/TargetLibraryInfo.h"
70#include "llvm/Analysis/ValueTracking.h"
71#include "llvm/IR/DataLayout.h"
72#include "llvm/IR/Dominators.h"
73#include "llvm/IR/GlobalVariable.h"
74#include "llvm/IR/IRBuilder.h"
75#include "llvm/IR/IntrinsicInst.h"
76#include "llvm/IR/LLVMContext.h"
77#include "llvm/IR/Metadata.h"
78#include "llvm/IR/PatternMatch.h"
79#include "llvm/IR/PredIteratorCache.h"
80#include "llvm/IR/Type.h"
81#include "llvm/Support/Allocator.h"
82#include "llvm/Support/CommandLine.h"
83#include "llvm/Support/Debug.h"
84#include "llvm/Transforms/Scalar.h"
85#include "llvm/Transforms/Scalar/GVNExpression.h"
86#include "llvm/Transforms/Utils/BasicBlockUtils.h"
87#include "llvm/Transforms/Utils/Local.h"
88#include "llvm/Transforms/Utils/MemorySSA.h"
89#include "llvm/Transforms/Utils/SSAUpdater.h"
90#include <unordered_map>
91#include <utility>
92#include <vector>
93using namespace llvm;
94using namespace PatternMatch;
95using namespace llvm::GVNExpression;
96
97#define DEBUG_TYPE "newgvn"
98
99STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
100STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
101STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
102STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +0000103STATISTIC(NumGVNMaxIterations,
104 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000105STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
106STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
107STATISTIC(NumGVNAvoidedSortedLeaderChanges,
108 "Number of avoided sorted leader changes");
Daniel Berlin89fea6f2017-01-20 06:38:41 +0000109STATISTIC(NumGVNNotMostDominatingLeader,
110 "Number of times a member dominated it's new classes' leader");
Davide Italiano7e274e02016-12-22 16:03:48 +0000111
112//===----------------------------------------------------------------------===//
113// GVN Pass
114//===----------------------------------------------------------------------===//
115
116// Anchor methods.
117namespace llvm {
118namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000119Expression::~Expression() = default;
120BasicExpression::~BasicExpression() = default;
121CallExpression::~CallExpression() = default;
122LoadExpression::~LoadExpression() = default;
123StoreExpression::~StoreExpression() = default;
124AggregateValueExpression::~AggregateValueExpression() = default;
125PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000126}
127}
128
129// Congruence classes represent the set of expressions/instructions
130// that are all the same *during some scope in the function*.
131// That is, because of the way we perform equality propagation, and
132// because of memory value numbering, it is not correct to assume
133// you can willy-nilly replace any member with any other at any
134// point in the function.
135//
136// For any Value in the Member set, it is valid to replace any dominated member
137// with that Value.
138//
139// Every congruence class has a leader, and the leader is used to
140// symbolize instructions in a canonical way (IE every operand of an
141// instruction that is a member of the same congruence class will
142// always be replaced with leader during symbolization).
143// To simplify symbolization, we keep the leader as a constant if class can be
144// proved to be a constant value.
145// Otherwise, the leader is a randomly chosen member of the value set, it does
146// not matter which one is chosen.
147// Each congruence class also has a defining expression,
148// though the expression may be null. If it exists, it can be used for forward
149// propagation and reassociation of values.
150//
151struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000152 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000153 unsigned ID;
154 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000155 Value *RepLeader = nullptr;
Daniel Berlin26addef2017-01-20 21:04:30 +0000156 // If this is represented by a store, the value.
157 Value *RepStoredValue = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000158 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000159 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000160 // Actual members of this class.
161 MemberSet Members;
162
163 // True if this class has no members left. This is mainly used for assertion
164 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000165 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000166
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000167 // Number of stores in this congruence class.
168 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000169 int StoreCount = 0;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000170
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000171 // The most dominating leader after our current leader, because the member set
172 // is not sorted and is expensive to keep sorted all the time.
173 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
174
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000175 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000176 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000177 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000178};
179
180namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000181template <> struct DenseMapInfo<const Expression *> {
182 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000183 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000184 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
185 return reinterpret_cast<const Expression *>(Val);
186 }
187 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000188 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000189 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
190 return reinterpret_cast<const Expression *>(Val);
191 }
192 static unsigned getHashValue(const Expression *V) {
193 return static_cast<unsigned>(V->getHashValue());
194 }
195 static bool isEqual(const Expression *LHS, const Expression *RHS) {
196 if (LHS == RHS)
197 return true;
198 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
199 LHS == getEmptyKey() || RHS == getEmptyKey())
200 return false;
201 return *LHS == *RHS;
202 }
203};
Davide Italiano7e274e02016-12-22 16:03:48 +0000204} // end namespace llvm
205
206class NewGVN : public FunctionPass {
207 DominatorTree *DT;
208 const DataLayout *DL;
209 const TargetLibraryInfo *TLI;
210 AssumptionCache *AC;
211 AliasAnalysis *AA;
212 MemorySSA *MSSA;
213 MemorySSAWalker *MSSAWalker;
214 BumpPtrAllocator ExpressionAllocator;
215 ArrayRecycler<Value *> ArgRecycler;
216
217 // Congruence class info.
218 CongruenceClass *InitialClass;
219 std::vector<CongruenceClass *> CongruenceClasses;
220 unsigned NextCongruenceNum;
221
222 // Value Mappings.
223 DenseMap<Value *, CongruenceClass *> ValueToClass;
224 DenseMap<Value *, const Expression *> ValueToExpression;
225
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000226 // A table storing which memorydefs/phis represent a memory state provably
227 // equivalent to another memory state.
228 // We could use the congruence class machinery, but the MemoryAccess's are
229 // abstract memory states, so they can only ever be equivalent to each other,
230 // and not to constants, etc.
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000231 DenseMap<const MemoryAccess *, MemoryAccess *> MemoryAccessEquiv;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000232
Davide Italiano7e274e02016-12-22 16:03:48 +0000233 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000234 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000235 ExpressionClassMap ExpressionToClass;
236
237 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000238 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000239
240 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000241 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000242 DenseSet<BlockEdge> ReachableEdges;
243 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
244
245 // This is a bitvector because, on larger functions, we may have
246 // thousands of touched instructions at once (entire blocks,
247 // instructions with hundreds of uses, etc). Even with optimization
248 // for when we mark whole blocks as touched, when this was a
249 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
250 // the time in GVN just managing this list. The bitvector, on the
251 // other hand, efficiently supports test/set/clear of both
252 // individual and ranges, as well as "find next element" This
253 // enables us to use it as a worklist with essentially 0 cost.
254 BitVector TouchedInstructions;
255
256 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
257 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
258 DominatedInstRange;
259
260#ifndef NDEBUG
261 // Debugging for how many times each block and instruction got processed.
262 DenseMap<const Value *, unsigned> ProcessedCount;
263#endif
264
265 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000266 // This contains a mapping from Instructions to DFS numbers.
267 // The numbering starts at 1. An instruction with DFS number zero
268 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000269 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000270
271 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000272 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000273
274 // Deletion info.
275 SmallPtrSet<Instruction *, 8> InstructionsToErase;
276
277public:
278 static char ID; // Pass identification, replacement for typeid.
279 NewGVN() : FunctionPass(ID) {
280 initializeNewGVNPass(*PassRegistry::getPassRegistry());
281 }
282
283 bool runOnFunction(Function &F) override;
284 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000285 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000286
287private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000288 void getAnalysisUsage(AnalysisUsage &AU) const override {
289 AU.addRequired<AssumptionCacheTracker>();
290 AU.addRequired<DominatorTreeWrapperPass>();
291 AU.addRequired<TargetLibraryInfoWrapperPass>();
292 AU.addRequired<MemorySSAWrapperPass>();
293 AU.addRequired<AAResultsWrapperPass>();
294
295 AU.addPreserved<DominatorTreeWrapperPass>();
296 AU.addPreserved<GlobalsAAWrapperPass>();
297 }
298
299 // Expression handling.
300 const Expression *createExpression(Instruction *, const BasicBlock *);
301 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
302 const BasicBlock *);
303 PHIExpression *createPHIExpression(Instruction *);
304 const VariableExpression *createVariableExpression(Value *);
305 const ConstantExpression *createConstantExpression(Constant *);
306 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000307 const UnknownExpression *createUnknownExpression(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000308 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
309 const BasicBlock *);
310 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
311 MemoryAccess *, const BasicBlock *);
312
313 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
314 const BasicBlock *);
315 const AggregateValueExpression *
316 createAggregateValueExpression(Instruction *, const BasicBlock *);
317 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
318 const BasicBlock *);
319
320 // Congruence class handling.
321 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000322 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000323 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000324 return result;
325 }
326
327 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000328 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000329 CClass->Members.insert(Member);
330 ValueToClass[Member] = CClass;
331 return CClass;
332 }
333 void initializeCongruenceClasses(Function &F);
334
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000335 // Value number an Instruction or MemoryPhi.
336 void valueNumberMemoryPhi(MemoryPhi *);
337 void valueNumberInstruction(Instruction *);
338
Davide Italiano7e274e02016-12-22 16:03:48 +0000339 // Symbolic evaluation.
340 const Expression *checkSimplificationResults(Expression *, Instruction *,
341 Value *);
342 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
343 const Expression *performSymbolicLoadEvaluation(Instruction *,
344 const BasicBlock *);
345 const Expression *performSymbolicStoreEvaluation(Instruction *,
346 const BasicBlock *);
347 const Expression *performSymbolicCallEvaluation(Instruction *,
348 const BasicBlock *);
349 const Expression *performSymbolicPHIEvaluation(Instruction *,
350 const BasicBlock *);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000351 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To);
Davide Italiano7e274e02016-12-22 16:03:48 +0000352 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
353 const BasicBlock *);
354
355 // Congruence finding.
356 // Templated to allow them to work both on BB's and BB-edges.
357 template <class T>
358 Value *lookupOperandLeader(Value *, const User *, const T &) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000359 void performCongruenceFinding(Instruction *, const Expression *);
360 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000361 CongruenceClass *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000362 // Reachability handling.
363 void updateReachableEdge(BasicBlock *, BasicBlock *);
364 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000365 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000366 Value *findConditionEquivalence(Value *, BasicBlock *) const;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000367 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000368
369 // Elimination.
370 struct ValueDFS;
371 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000372 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000373
374 bool eliminateInstructions(Function &);
375 void replaceInstruction(Instruction *, Value *);
376 void markInstructionForDeletion(Instruction *);
377 void deleteInstructionsInBlock(BasicBlock *);
378
379 // New instruction creation.
380 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000381
382 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000383 void markUsersTouched(Value *);
384 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000385 void markLeaderChangeTouched(CongruenceClass *CC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000386
387 // Utilities.
388 void cleanupTables();
389 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
390 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000391 void verifyMemoryCongruency() const;
392 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000393};
394
395char NewGVN::ID = 0;
396
397// createGVNPass - The public interface to this file.
398FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
399
Davide Italianob1114092016-12-28 13:37:17 +0000400template <typename T>
401static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
402 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000403 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000404 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000405 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000406 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000407 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000408 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000409 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000410 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000411 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000412 return true;
413}
414
Davide Italianob1114092016-12-28 13:37:17 +0000415bool LoadExpression::equals(const Expression &Other) const {
416 return equalsLoadStoreHelper(*this, Other);
417}
Davide Italiano7e274e02016-12-22 16:03:48 +0000418
Davide Italianob1114092016-12-28 13:37:17 +0000419bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000420 bool Result = equalsLoadStoreHelper(*this, Other);
421 // Make sure that store vs store includes the value operand.
422 if (Result)
423 if (const auto *S = dyn_cast<StoreExpression>(&Other))
424 if (getStoredValue() != S->getStoredValue())
425 return false;
426 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000427}
428
429#ifndef NDEBUG
430static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000431 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000432}
433#endif
434
435INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
436INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
437INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
438INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
439INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
440INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
441INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
442INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
443
444PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000445 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000446 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000447 auto *E =
448 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000449
450 E->allocateOperands(ArgRecycler, ExpressionAllocator);
451 E->setType(I->getType());
452 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000453
Davide Italianob3886dd2017-01-25 23:37:49 +0000454 // Filter out unreachable phi operands.
455 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000456 return ReachableBlocks.count(PN->getIncomingBlock(U));
Davide Italianob3886dd2017-01-25 23:37:49 +0000457 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000458
459 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
460 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000461 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000462 if (U == PN)
463 return PN;
Daniel Berlind92e7f92017-01-07 00:01:42 +0000464 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PHIBlock);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000465 return lookupOperandLeader(U, I, BBE);
466 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000467 return E;
468}
469
470// Set basic expression info (Arguments, type, opcode) for Expression
471// E from Instruction I in block B.
472bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
473 const BasicBlock *B) {
474 bool AllConstant = true;
475 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
476 E->setType(GEP->getSourceElementType());
477 else
478 E->setType(I->getType());
479 E->setOpcode(I->getOpcode());
480 E->allocateOperands(ArgRecycler, ExpressionAllocator);
481
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000482 // Transform the operand array into an operand leader array, and keep track of
483 // whether all members are constant.
484 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000485 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000486 AllConstant &= isa<Constant>(Operand);
487 return Operand;
488 });
489
Davide Italiano7e274e02016-12-22 16:03:48 +0000490 return AllConstant;
491}
492
493const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
494 Value *Arg1, Value *Arg2,
495 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000496 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000497
498 E->setType(T);
499 E->setOpcode(Opcode);
500 E->allocateOperands(ArgRecycler, ExpressionAllocator);
501 if (Instruction::isCommutative(Opcode)) {
502 // Ensure that commutative instructions that only differ by a permutation
503 // of their operands get the same value number by sorting the operand value
504 // numbers. Since all commutative instructions have two operands it is more
505 // efficient to sort by hand rather than using, say, std::sort.
506 if (Arg1 > Arg2)
507 std::swap(Arg1, Arg2);
508 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000509 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
510 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000511
512 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
513 DT, AC);
514 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
515 return SimplifiedE;
516 return E;
517}
518
519// Take a Value returned by simplification of Expression E/Instruction
520// I, and see if it resulted in a simpler expression. If so, return
521// that expression.
522// TODO: Once finished, this should not take an Instruction, we only
523// use it for printing.
524const Expression *NewGVN::checkSimplificationResults(Expression *E,
525 Instruction *I, Value *V) {
526 if (!V)
527 return nullptr;
528 if (auto *C = dyn_cast<Constant>(V)) {
529 if (I)
530 DEBUG(dbgs() << "Simplified " << *I << " to "
531 << " constant " << *C << "\n");
532 NumGVNOpsSimplified++;
533 assert(isa<BasicExpression>(E) &&
534 "We should always have had a basic expression here");
535
536 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
537 ExpressionAllocator.Deallocate(E);
538 return createConstantExpression(C);
539 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
540 if (I)
541 DEBUG(dbgs() << "Simplified " << *I << " to "
542 << " variable " << *V << "\n");
543 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
544 ExpressionAllocator.Deallocate(E);
545 return createVariableExpression(V);
546 }
547
548 CongruenceClass *CC = ValueToClass.lookup(V);
549 if (CC && CC->DefiningExpr) {
550 if (I)
551 DEBUG(dbgs() << "Simplified " << *I << " to "
552 << " expression " << *V << "\n");
553 NumGVNOpsSimplified++;
554 assert(isa<BasicExpression>(E) &&
555 "We should always have had a basic expression here");
556 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
557 ExpressionAllocator.Deallocate(E);
558 return CC->DefiningExpr;
559 }
560 return nullptr;
561}
562
563const Expression *NewGVN::createExpression(Instruction *I,
564 const BasicBlock *B) {
565
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000566 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000567
568 bool AllConstant = setBasicExpressionInfo(I, E, B);
569
570 if (I->isCommutative()) {
571 // Ensure that commutative instructions that only differ by a permutation
572 // of their operands get the same value number by sorting the operand value
573 // numbers. Since all commutative instructions have two operands it is more
574 // efficient to sort by hand rather than using, say, std::sort.
575 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
576 if (E->getOperand(0) > E->getOperand(1))
577 E->swapOperands(0, 1);
578 }
579
580 // Perform simplificaiton
581 // TODO: Right now we only check to see if we get a constant result.
582 // We may get a less than constant, but still better, result for
583 // some operations.
584 // IE
585 // add 0, x -> x
586 // and x, x -> x
587 // We should handle this by simply rewriting the expression.
588 if (auto *CI = dyn_cast<CmpInst>(I)) {
589 // Sort the operand value numbers so x<y and y>x get the same value
590 // number.
591 CmpInst::Predicate Predicate = CI->getPredicate();
592 if (E->getOperand(0) > E->getOperand(1)) {
593 E->swapOperands(0, 1);
594 Predicate = CmpInst::getSwappedPredicate(Predicate);
595 }
596 E->setOpcode((CI->getOpcode() << 8) | Predicate);
597 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
598 // TODO: Since we noop bitcasts, we may need to check types before
599 // simplifying, so that we don't end up simplifying based on a wrong
600 // type assumption. We should clean this up so we can use constants of the
601 // wrong type
602
603 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
604 "Wrong types on cmp instruction");
605 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
606 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
607 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
608 *DL, TLI, DT, AC);
609 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
610 return SimplifiedE;
611 }
612 } else if (isa<SelectInst>(I)) {
613 if (isa<Constant>(E->getOperand(0)) ||
614 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
615 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
616 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
617 E->getOperand(2), *DL, TLI, DT, AC);
618 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
619 return SimplifiedE;
620 }
621 } else if (I->isBinaryOp()) {
622 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
623 *DL, TLI, DT, AC);
624 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
625 return SimplifiedE;
626 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
627 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
628 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
629 return SimplifiedE;
630 } else if (isa<GetElementPtrInst>(I)) {
631 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000632 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000633 *DL, TLI, DT, AC);
634 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
635 return SimplifiedE;
636 } else if (AllConstant) {
637 // We don't bother trying to simplify unless all of the operands
638 // were constant.
639 // TODO: There are a lot of Simplify*'s we could call here, if we
640 // wanted to. The original motivating case for this code was a
641 // zext i1 false to i8, which we don't have an interface to
642 // simplify (IE there is no SimplifyZExt).
643
644 SmallVector<Constant *, 8> C;
645 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000646 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000647
648 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
649 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
650 return SimplifiedE;
651 }
652 return E;
653}
654
655const AggregateValueExpression *
656NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
657 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000658 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000659 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
660 setBasicExpressionInfo(I, E, B);
661 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000662 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000663 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000664 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000665 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000666 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
667 setBasicExpressionInfo(EI, E, B);
668 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000669 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 return E;
671 }
672 llvm_unreachable("Unhandled type of aggregate value operation");
673}
674
Daniel Berlin85f91b02016-12-26 20:06:58 +0000675const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000676 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000677 E->setOpcode(V->getValueID());
678 return E;
679}
680
681const Expression *NewGVN::createVariableOrConstant(Value *V,
682 const BasicBlock *B) {
683 auto Leader = lookupOperandLeader(V, nullptr, B);
684 if (auto *C = dyn_cast<Constant>(Leader))
685 return createConstantExpression(C);
686 return createVariableExpression(Leader);
687}
688
Daniel Berlin85f91b02016-12-26 20:06:58 +0000689const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000690 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000691 E->setOpcode(C->getValueID());
692 return E;
693}
694
Daniel Berlin02c6b172017-01-02 18:00:53 +0000695const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
696 auto *E = new (ExpressionAllocator) UnknownExpression(I);
697 E->setOpcode(I->getOpcode());
698 return E;
699}
700
Davide Italiano7e274e02016-12-22 16:03:48 +0000701const CallExpression *NewGVN::createCallExpression(CallInst *CI,
702 MemoryAccess *HV,
703 const BasicBlock *B) {
704 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000705 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000706 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
707 setBasicExpressionInfo(CI, E, B);
708 return E;
709}
710
711// See if we have a congruence class and leader for this operand, and if so,
712// return it. Otherwise, return the operand itself.
713template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000714Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000715 CongruenceClass *CC = ValueToClass.lookup(V);
716 if (CC && (CC != InitialClass))
Daniel Berlin26addef2017-01-20 21:04:30 +0000717 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Davide Italiano7e274e02016-12-22 16:03:48 +0000718 return V;
719}
720
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000721MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
722 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
723 return Result ? Result : MA;
724}
725
Davide Italiano7e274e02016-12-22 16:03:48 +0000726LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
727 LoadInst *LI, MemoryAccess *DA,
728 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000729 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000730 E->allocateOperands(ArgRecycler, ExpressionAllocator);
731 E->setType(LoadType);
732
733 // Give store and loads same opcode so they value number together.
734 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000735 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000736 if (LI)
737 E->setAlignment(LI->getAlignment());
738
739 // TODO: Value number heap versions. We may be able to discover
740 // things alias analysis can't on it's own (IE that a store and a
741 // load have the same value, and thus, it isn't clobbering the load).
742 return E;
743}
744
745const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
746 MemoryAccess *DA,
747 const BasicBlock *B) {
Daniel Berlin26addef2017-01-20 21:04:30 +0000748 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand(), SI, B);
749 auto *E = new (ExpressionAllocator)
750 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000751 E->allocateOperands(ArgRecycler, ExpressionAllocator);
752 E->setType(SI->getValueOperand()->getType());
753
754 // Give store and loads same opcode so they value number together.
755 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000756 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000757
758 // TODO: Value number heap versions. We may be able to discover
759 // things alias analysis can't on it's own (IE that a store and a
760 // load have the same value, and thus, it isn't clobbering the load).
761 return E;
762}
763
Daniel Berlinb755aea2017-01-09 05:34:29 +0000764// Utility function to check whether the congruence class has a member other
765// than the given instruction.
766bool hasMemberOtherThanUs(const CongruenceClass *CC, Instruction *I) {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000767 // Either it has more than one store, in which case it must contain something
768 // other than us (because it's indexed by value), or if it only has one store
Daniel Berlinb755aea2017-01-09 05:34:29 +0000769 // right now, that member should not be us.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000770 return CC->StoreCount > 1 || CC->Members.count(I) == 0;
Daniel Berlinb755aea2017-01-09 05:34:29 +0000771}
772
Davide Italiano7e274e02016-12-22 16:03:48 +0000773const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
774 const BasicBlock *B) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000775 // Unlike loads, we never try to eliminate stores, so we do not check if they
776 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000777 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000778 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinde43ef92017-01-02 19:49:17 +0000779 // See if we are defined by a previous store expression, it already has a
780 // value, and it's the same value as our current store. FIXME: Right now, we
781 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000782 if (SI->isSimple()) {
Daniel Berlinde43ef92017-01-02 19:49:17 +0000783 // Get the expression, if any, for the RHS of the MemoryDef.
784 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
785 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
786 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000787 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000788 // Basically, check if the congruence class the store is in is defined by a
789 // store that isn't us, and has the same value. MemorySSA takes care of
790 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000791 // The RepStoredValue gets nulled if all the stores disappear in a class, so
792 // we don't need to check if the class contains a store besides us.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000793 if (CC && CC->DefiningExpr && isa<StoreExpression>(CC->DefiningExpr) &&
Daniel Berlin26addef2017-01-20 21:04:30 +0000794 CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand(), SI, B))
Daniel Berlin589cecc2017-01-02 18:00:46 +0000795 return createStoreExpression(SI, StoreRHS, B);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000796 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000797
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000798 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000799}
800
801const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
802 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000803 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000804
805 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000806 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000807 if (!LI->isSimple())
808 return nullptr;
809
Daniel Berlin85f91b02016-12-26 20:06:58 +0000810 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000811 // Load of undef is undef.
812 if (isa<UndefValue>(LoadAddressLeader))
813 return createConstantExpression(UndefValue::get(LI->getType()));
814
815 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
816
817 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
818 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
819 Instruction *DefiningInst = MD->getMemoryInst();
820 // If the defining instruction is not reachable, replace with undef.
821 if (!ReachableBlocks.count(DefiningInst->getParent()))
822 return createConstantExpression(UndefValue::get(LI->getType()));
823 }
824 }
825
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000826 const Expression *E =
827 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
828 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000829 return E;
830}
831
832// Evaluate read only and pure calls, and create an expression result.
833const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
834 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000835 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000836 if (AA->doesNotAccessMemory(CI))
837 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000838 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000839 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000840 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000841 }
842 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000843}
844
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000845// Update the memory access equivalence table to say that From is equal to To,
846// and return true if this is different from what already existed in the table.
847bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
Davide Italiano84126162017-01-02 18:41:34 +0000848 DEBUG(dbgs() << "Setting " << *From << " equivalent to ");
849 if (!To)
850 DEBUG(dbgs() << "itself");
851 else
852 DEBUG(dbgs() << *To);
853 DEBUG(dbgs() << "\n");
Daniel Berlin589cecc2017-01-02 18:00:46 +0000854 auto LookupResult = MemoryAccessEquiv.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000855 bool Changed = false;
856 // If it's already in the table, see if the value changed.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000857 if (LookupResult != MemoryAccessEquiv.end()) {
858 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000859 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000860 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000861 Changed = true;
862 } else if (!To) {
863 // It used to be equivalent to something, and now it's not.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000864 MemoryAccessEquiv.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000865 Changed = true;
866 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000867 } else {
868 assert(!To &&
869 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000870 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000871
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000872 return Changed;
873}
Davide Italiano7e274e02016-12-22 16:03:48 +0000874// Evaluate PHI nodes symbolically, and create an expression result.
875const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
876 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000877 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000878 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
879
880 // See if all arguaments are the same.
881 // We track if any were undef because they need special handling.
882 bool HasUndef = false;
883 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
884 if (Arg == I)
885 return false;
886 if (isa<UndefValue>(Arg)) {
887 HasUndef = true;
888 return false;
889 }
890 return true;
891 });
892 // If we are left with no operands, it's undef
893 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000894 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
895 << "\n");
896 E->deallocateOperands(ArgRecycler);
897 ExpressionAllocator.Deallocate(E);
898 return createConstantExpression(UndefValue::get(I->getType()));
899 }
Daniel Berlind92e7f92017-01-07 00:01:42 +0000900 Value *AllSameValue = *(Filtered.begin());
901 ++Filtered.begin();
902 // Can't use std::equal here, sadly, because filter.begin moves.
903 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
904 return V == AllSameValue;
905 })) {
906 // In LLVM's non-standard representation of phi nodes, it's possible to have
907 // phi nodes with cycles (IE dependent on other phis that are .... dependent
908 // on the original phi node), especially in weird CFG's where some arguments
909 // are unreachable, or uninitialized along certain paths. This can cause
910 // infinite loops during evaluation. We work around this by not trying to
911 // really evaluate them independently, but instead using a variable
912 // expression to say if one is equivalent to the other.
913 // We also special case undef, so that if we have an undef, we can't use the
914 // common value unless it dominates the phi block.
915 if (HasUndef) {
916 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +0000917 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +0000918 if (!DT->dominates(AllSameInst, I))
919 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000920 }
921
Davide Italiano7e274e02016-12-22 16:03:48 +0000922 NumGVNPhisAllSame++;
923 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
924 << "\n");
925 E->deallocateOperands(ArgRecycler);
926 ExpressionAllocator.Deallocate(E);
927 if (auto *C = dyn_cast<Constant>(AllSameValue))
928 return createConstantExpression(C);
929 return createVariableExpression(AllSameValue);
930 }
931 return E;
932}
933
934const Expression *
935NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
936 const BasicBlock *B) {
937 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
938 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
939 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
940 unsigned Opcode = 0;
941 // EI might be an extract from one of our recognised intrinsics. If it
942 // is we'll synthesize a semantically equivalent expression instead on
943 // an extract value expression.
944 switch (II->getIntrinsicID()) {
945 case Intrinsic::sadd_with_overflow:
946 case Intrinsic::uadd_with_overflow:
947 Opcode = Instruction::Add;
948 break;
949 case Intrinsic::ssub_with_overflow:
950 case Intrinsic::usub_with_overflow:
951 Opcode = Instruction::Sub;
952 break;
953 case Intrinsic::smul_with_overflow:
954 case Intrinsic::umul_with_overflow:
955 Opcode = Instruction::Mul;
956 break;
957 default:
958 break;
959 }
960
961 if (Opcode != 0) {
962 // Intrinsic recognized. Grab its args to finish building the
963 // expression.
964 assert(II->getNumArgOperands() == 2 &&
965 "Expect two args for recognised intrinsics.");
966 return createBinaryExpression(Opcode, EI->getType(),
967 II->getArgOperand(0),
968 II->getArgOperand(1), B);
969 }
970 }
971 }
972
973 return createAggregateValueExpression(I, B);
974}
975
976// Substitute and symbolize the value before value numbering.
977const Expression *NewGVN::performSymbolicEvaluation(Value *V,
978 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000979 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000980 if (auto *C = dyn_cast<Constant>(V))
981 E = createConstantExpression(C);
982 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
983 E = createVariableExpression(V);
984 } else {
985 // TODO: memory intrinsics.
986 // TODO: Some day, we should do the forward propagation and reassociation
987 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000988 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000989 switch (I->getOpcode()) {
990 case Instruction::ExtractValue:
991 case Instruction::InsertValue:
992 E = performSymbolicAggrValueEvaluation(I, B);
993 break;
994 case Instruction::PHI:
995 E = performSymbolicPHIEvaluation(I, B);
996 break;
997 case Instruction::Call:
998 E = performSymbolicCallEvaluation(I, B);
999 break;
1000 case Instruction::Store:
1001 E = performSymbolicStoreEvaluation(I, B);
1002 break;
1003 case Instruction::Load:
1004 E = performSymbolicLoadEvaluation(I, B);
1005 break;
1006 case Instruction::BitCast: {
1007 E = createExpression(I, B);
1008 } break;
1009
1010 case Instruction::Add:
1011 case Instruction::FAdd:
1012 case Instruction::Sub:
1013 case Instruction::FSub:
1014 case Instruction::Mul:
1015 case Instruction::FMul:
1016 case Instruction::UDiv:
1017 case Instruction::SDiv:
1018 case Instruction::FDiv:
1019 case Instruction::URem:
1020 case Instruction::SRem:
1021 case Instruction::FRem:
1022 case Instruction::Shl:
1023 case Instruction::LShr:
1024 case Instruction::AShr:
1025 case Instruction::And:
1026 case Instruction::Or:
1027 case Instruction::Xor:
1028 case Instruction::ICmp:
1029 case Instruction::FCmp:
1030 case Instruction::Trunc:
1031 case Instruction::ZExt:
1032 case Instruction::SExt:
1033 case Instruction::FPToUI:
1034 case Instruction::FPToSI:
1035 case Instruction::UIToFP:
1036 case Instruction::SIToFP:
1037 case Instruction::FPTrunc:
1038 case Instruction::FPExt:
1039 case Instruction::PtrToInt:
1040 case Instruction::IntToPtr:
1041 case Instruction::Select:
1042 case Instruction::ExtractElement:
1043 case Instruction::InsertElement:
1044 case Instruction::ShuffleVector:
1045 case Instruction::GetElementPtr:
1046 E = createExpression(I, B);
1047 break;
1048 default:
1049 return nullptr;
1050 }
1051 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001052 return E;
1053}
1054
1055// There is an edge from 'Src' to 'Dst'. Return true if every path from
1056// the entry block to 'Dst' passes via this edge. In particular 'Dst'
1057// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +00001058bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001059
1060 // While in theory it is interesting to consider the case in which Dst has
1061 // more than one predecessor, because Dst might be part of a loop which is
1062 // only reachable from Src, in practice it is pointless since at the time
1063 // GVN runs all such loops have preheaders, which means that Dst will have
1064 // been changed to have only one predecessor, namely Src.
1065 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1066 const BasicBlock *Src = E.getStart();
1067 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
1068 (void)Src;
1069 return Pred != nullptr;
1070}
1071
1072void NewGVN::markUsersTouched(Value *V) {
1073 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001074 for (auto *User : V->users()) {
1075 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001076 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001077 }
1078}
1079
1080void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1081 for (auto U : MA->users()) {
1082 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001083 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001084 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001085 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001086 }
1087}
1088
Daniel Berlin32f8d562017-01-07 16:55:14 +00001089// Touch the instructions that need to be updated after a congruence class has a
1090// leader change, and mark changed values.
1091void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1092 for (auto M : CC->Members) {
1093 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001094 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001095 LeaderChanges.insert(M);
1096 }
1097}
1098
1099// Move a value, currently in OldClass, to be part of NewClass
1100// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001101void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1102 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001103 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001104 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001105 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001106
1107 if (I == OldClass->NextLeader.first)
1108 OldClass->NextLeader = {nullptr, ~0U};
1109
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001110 // It's possible, though unlikely, for us to discover equivalences such
1111 // that the current leader does not dominate the old one.
1112 // This statistic tracks how often this happens.
1113 // We assert on phi nodes when this happens, currently, for debugging, because
1114 // we want to make sure we name phi node cycles properly.
1115 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1116 I != NewClass->RepLeader &&
1117 DT->properlyDominates(
1118 I->getParent(),
1119 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1120 ++NumGVNNotMostDominatingLeader;
1121 assert(!isa<PHINode>(I) &&
1122 "New class for instruction should not be dominated by instruction");
1123 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001124
1125 if (NewClass->RepLeader != I) {
1126 auto DFSNum = InstrDFS.lookup(I);
1127 if (DFSNum < NewClass->NextLeader.second)
1128 NewClass->NextLeader = {I, DFSNum};
1129 }
1130
1131 OldClass->Members.erase(I);
1132 NewClass->Members.insert(I);
1133 if (isa<StoreInst>(I)) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001134 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001135 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001136 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001137 assert(NewClass->StoreCount > 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001138 }
1139
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001140 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001141 // See if we destroyed the class or need to swap leaders.
1142 if (OldClass->Members.empty() && OldClass != InitialClass) {
1143 if (OldClass->DefiningExpr) {
1144 OldClass->Dead = true;
1145 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1146 << " from table\n");
1147 ExpressionToClass.erase(OldClass->DefiningExpr);
1148 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001149 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001150 // When the leader changes, the value numbering of
1151 // everything may change due to symbolization changes, so we need to
1152 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001153 DEBUG(dbgs() << "Leader change!\n");
1154 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001155 // Destroy the stored value if there are no more stores to represent it.
1156 if (OldClass->RepStoredValue != nullptr && OldClass->StoreCount == 0)
1157 OldClass->RepStoredValue = nullptr;
1158
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001159 // We don't need to sort members if there is only 1, and we don't care about
1160 // sorting the initial class because everything either gets out of it or is
1161 // unreachable.
1162 if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1163 OldClass->RepLeader = *(OldClass->Members.begin());
1164 } else if (OldClass->NextLeader.first) {
1165 ++NumGVNAvoidedSortedLeaderChanges;
1166 OldClass->RepLeader = OldClass->NextLeader.first;
1167 OldClass->NextLeader = {nullptr, ~0U};
1168 } else {
1169 ++NumGVNSortedLeaderChanges;
1170 // TODO: If this ends up to slow, we can maintain a dual structure for
1171 // member testing/insertion, or keep things mostly sorted, and sort only
1172 // here, or ....
1173 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1174 for (const auto X : OldClass->Members) {
1175 auto DFSNum = InstrDFS.lookup(X);
1176 if (DFSNum < MinDFS.second)
1177 MinDFS = {X, DFSNum};
1178 }
1179 OldClass->RepLeader = MinDFS.first;
1180 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001181 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001182 }
1183}
1184
Davide Italiano7e274e02016-12-22 16:03:48 +00001185// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001186void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1187 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001188 // This is guaranteed to return something, since it will at least find
1189 // INITIAL.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001190
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001191 CongruenceClass *IClass = ValueToClass[I];
1192 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001193 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001194 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001195
1196 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001197 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001198 EClass = ValueToClass[VE->getVariableValue()];
1199 } else {
1200 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1201
1202 // If it's not in the value table, create a new congruence class.
1203 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001204 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001205 auto place = lookupResult.first;
1206 place->second = NewClass;
1207
1208 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001209 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001210 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001211 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1212 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001213 NewClass->RepLeader = SI;
1214 NewClass->RepStoredValue =
Daniel Berlin32f8d562017-01-07 16:55:14 +00001215 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
1216 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001217 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001218 }
1219 assert(!isa<VariableExpression>(E) &&
1220 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001221
1222 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001223 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001224 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001225 << " and leader " << *(NewClass->RepLeader));
1226 if (NewClass->RepStoredValue)
1227 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1228 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001229 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1230 } else {
1231 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001232 if (isa<ConstantExpression>(E))
1233 assert(isa<Constant>(EClass->RepLeader) &&
1234 "Any class with a constant expression should have a "
1235 "constant leader");
1236
Davide Italiano7e274e02016-12-22 16:03:48 +00001237 assert(EClass && "Somehow don't have an eclass");
1238
1239 assert(!EClass->Dead && "We accidentally looked up a dead class");
1240 }
1241 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001242 bool ClassChanged = IClass != EClass;
1243 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001244 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001245 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1246 << "\n");
1247
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001248 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001249 moveValueToNewCongruenceClass(I, IClass, EClass);
1250 markUsersTouched(I);
1251 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
1252 // If this is a MemoryDef, we need to update the equivalence table. If
1253 // we determined the expression is congruent to a different memory
1254 // state, use that different memory state. If we determined it didn't,
1255 // we update that as well. Right now, we only support store
1256 // expressions.
1257 if (!isa<MemoryUse>(MA) && isa<StoreExpression>(E) &&
1258 EClass->Members.size() != 1) {
1259 auto *DefAccess = cast<StoreExpression>(E)->getDefiningAccess();
1260 setMemoryAccessEquivTo(MA, DefAccess != MA ? DefAccess : nullptr);
1261 } else {
1262 setMemoryAccessEquivTo(MA, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001263 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001264 markMemoryUsersTouched(MA);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001265 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001266 }
1267}
1268
1269// Process the fact that Edge (from, to) is reachable, including marking
1270// any newly reachable blocks and instructions for processing.
1271void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1272 // Check if the Edge was reachable before.
1273 if (ReachableEdges.insert({From, To}).second) {
1274 // If this block wasn't reachable before, all instructions are touched.
1275 if (ReachableBlocks.insert(To).second) {
1276 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1277 const auto &InstRange = BlockInstRange.lookup(To);
1278 TouchedInstructions.set(InstRange.first, InstRange.second);
1279 } else {
1280 DEBUG(dbgs() << "Block " << getBlockName(To)
1281 << " was reachable, but new edge {" << getBlockName(From)
1282 << "," << getBlockName(To) << "} to it found\n");
1283
1284 // We've made an edge reachable to an existing block, which may
1285 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1286 // they are the only thing that depend on new edges. Anything using their
1287 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001288 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001289 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001290
Davide Italiano7e274e02016-12-22 16:03:48 +00001291 auto BI = To->begin();
1292 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001293 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001294 ++BI;
1295 }
1296 }
1297 }
1298}
1299
1300// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1301// see if we know some constant value for it already.
1302Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1303 auto Result = lookupOperandLeader(Cond, nullptr, B);
1304 if (isa<Constant>(Result))
1305 return Result;
1306 return nullptr;
1307}
1308
1309// Process the outgoing edges of a block for reachability.
1310void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1311 // Evaluate reachability of terminator instruction.
1312 BranchInst *BR;
1313 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1314 Value *Cond = BR->getCondition();
1315 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1316 if (!CondEvaluated) {
1317 if (auto *I = dyn_cast<Instruction>(Cond)) {
1318 const Expression *E = createExpression(I, B);
1319 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1320 CondEvaluated = CE->getConstantValue();
1321 }
1322 } else if (isa<ConstantInt>(Cond)) {
1323 CondEvaluated = Cond;
1324 }
1325 }
1326 ConstantInt *CI;
1327 BasicBlock *TrueSucc = BR->getSuccessor(0);
1328 BasicBlock *FalseSucc = BR->getSuccessor(1);
1329 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1330 if (CI->isOne()) {
1331 DEBUG(dbgs() << "Condition for Terminator " << *TI
1332 << " evaluated to true\n");
1333 updateReachableEdge(B, TrueSucc);
1334 } else if (CI->isZero()) {
1335 DEBUG(dbgs() << "Condition for Terminator " << *TI
1336 << " evaluated to false\n");
1337 updateReachableEdge(B, FalseSucc);
1338 }
1339 } else {
1340 updateReachableEdge(B, TrueSucc);
1341 updateReachableEdge(B, FalseSucc);
1342 }
1343 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1344 // For switches, propagate the case values into the case
1345 // destinations.
1346
1347 // Remember how many outgoing edges there are to every successor.
1348 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1349
Davide Italiano7e274e02016-12-22 16:03:48 +00001350 Value *SwitchCond = SI->getCondition();
1351 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1352 // See if we were able to turn this switch statement into a constant.
1353 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001354 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001355 // We should be able to get case value for this.
1356 auto CaseVal = SI->findCaseValue(CondVal);
1357 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1358 // We proved the value is outside of the range of the case.
1359 // We can't do anything other than mark the default dest as reachable,
1360 // and go home.
1361 updateReachableEdge(B, SI->getDefaultDest());
1362 return;
1363 }
1364 // Now get where it goes and mark it reachable.
1365 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1366 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001367 } else {
1368 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1369 BasicBlock *TargetBlock = SI->getSuccessor(i);
1370 ++SwitchEdges[TargetBlock];
1371 updateReachableEdge(B, TargetBlock);
1372 }
1373 }
1374 } else {
1375 // Otherwise this is either unconditional, or a type we have no
1376 // idea about. Just mark successors as reachable.
1377 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1378 BasicBlock *TargetBlock = TI->getSuccessor(i);
1379 updateReachableEdge(B, TargetBlock);
1380 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001381
1382 // This also may be a memory defining terminator, in which case, set it
1383 // equivalent to nothing.
1384 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1385 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001386 }
1387}
1388
Daniel Berlin85f91b02016-12-26 20:06:58 +00001389// The algorithm initially places the values of the routine in the INITIAL
1390// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001391// class. The leader of INITIAL is the undetermined value `TOP`.
1392// When the algorithm has finished, values still in INITIAL are unreachable.
1393void NewGVN::initializeCongruenceClasses(Function &F) {
1394 // FIXME now i can't remember why this is 2
1395 NextCongruenceNum = 2;
1396 // Initialize all other instructions to be in INITIAL class.
1397 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001398 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001399 for (auto &B : F) {
1400 if (auto *MP = MSSA->getMemoryAccess(&B))
1401 MemoryAccessEquiv.insert({MP, MSSA->getLiveOnEntryDef()});
1402
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001403 for (auto &I : B) {
1404 InitialValues.insert(&I);
1405 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001406 // All memory accesses are equivalent to live on entry to start. They must
1407 // be initialized to something so that initial changes are noticed. For
1408 // the maximal answer, we initialize them all to be the same as
1409 // liveOnEntry. Note that to save time, we only initialize the
1410 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1411 // other expression can generate a memory equivalence. If we start
1412 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001413 if (isa<StoreInst>(&I)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001414 MemoryAccessEquiv.insert(
1415 {MSSA->getMemoryAccess(&I), MSSA->getLiveOnEntryDef()});
Davide Italianoeac05f62017-01-11 23:41:24 +00001416 ++InitialClass->StoreCount;
1417 assert(InitialClass->StoreCount > 0);
1418 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001419 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001420 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001421 InitialClass->Members.swap(InitialValues);
1422
1423 // Initialize arguments to be in their own unique congruence classes
1424 for (auto &FA : F.args())
1425 createSingletonCongruenceClass(&FA);
1426}
1427
1428void NewGVN::cleanupTables() {
1429 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1430 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1431 << CongruenceClasses[i]->Members.size() << " members\n");
1432 // Make sure we delete the congruence class (probably worth switching to
1433 // a unique_ptr at some point.
1434 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001435 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001436 }
1437
1438 ValueToClass.clear();
1439 ArgRecycler.clear(ExpressionAllocator);
1440 ExpressionAllocator.Reset();
1441 CongruenceClasses.clear();
1442 ExpressionToClass.clear();
1443 ValueToExpression.clear();
1444 ReachableBlocks.clear();
1445 ReachableEdges.clear();
1446#ifndef NDEBUG
1447 ProcessedCount.clear();
1448#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001449 InstrDFS.clear();
1450 InstructionsToErase.clear();
1451
1452 DFSToInstr.clear();
1453 BlockInstRange.clear();
1454 TouchedInstructions.clear();
1455 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001456 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001457}
1458
1459std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1460 unsigned Start) {
1461 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001462 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1463 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001464 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001465 }
1466
Davide Italiano7e274e02016-12-22 16:03:48 +00001467 for (auto &I : *B) {
1468 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001469 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001470 }
1471
1472 // All of the range functions taken half-open ranges (open on the end side).
1473 // So we do not subtract one from count, because at this point it is one
1474 // greater than the last instruction.
1475 return std::make_pair(Start, End);
1476}
1477
1478void NewGVN::updateProcessedCount(Value *V) {
1479#ifndef NDEBUG
1480 if (ProcessedCount.count(V) == 0) {
1481 ProcessedCount.insert({V, 1});
1482 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001483 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001484 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001485 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001486 }
1487#endif
1488}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001489// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1490void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1491 // If all the arguments are the same, the MemoryPhi has the same value as the
1492 // argument.
1493 // Filter out unreachable blocks from our operands.
1494 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1495 return ReachableBlocks.count(MP->getIncomingBlock(U));
1496 });
1497
1498 assert(Filtered.begin() != Filtered.end() &&
1499 "We should not be processing a MemoryPhi in a completely "
1500 "unreachable block");
1501
1502 // Transform the remaining operands into operand leaders.
1503 // FIXME: mapped_iterator should have a range version.
1504 auto LookupFunc = [&](const Use &U) {
1505 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1506 };
1507 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1508 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1509
1510 // and now check if all the elements are equal.
1511 // Sadly, we can't use std::equals since these are random access iterators.
1512 MemoryAccess *AllSameValue = *MappedBegin;
1513 ++MappedBegin;
1514 bool AllEqual = std::all_of(
1515 MappedBegin, MappedEnd,
1516 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1517
1518 if (AllEqual)
1519 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1520 else
1521 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1522
1523 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1524 markMemoryUsersTouched(MP);
1525}
1526
1527// Value number a single instruction, symbolically evaluating, performing
1528// congruence finding, and updating mappings.
1529void NewGVN::valueNumberInstruction(Instruction *I) {
1530 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001531
1532 // There's no need to call isInstructionTriviallyDead more than once on
1533 // an instruction. Therefore, once we know that an instruction is dead
1534 // we change its DFS number so that it doesn't get numbered again.
1535 if (InstrDFS[I] != 0 && isInstructionTriviallyDead(I, TLI)) {
1536 InstrDFS[I] = 0;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001537 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001538 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001539 return;
1540 }
1541 if (!I->isTerminator()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001542 const auto *Symbolized = performSymbolicEvaluation(I, I->getParent());
1543 // If we couldn't come up with a symbolic expression, use the unknown
1544 // expression
1545 if (Symbolized == nullptr)
1546 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001547 performCongruenceFinding(I, Symbolized);
1548 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001549 // Handle terminators that return values. All of them produce values we
1550 // don't currently understand.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001551 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001552 auto *Symbolized = createUnknownExpression(I);
1553 performCongruenceFinding(I, Symbolized);
1554 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001555 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1556 }
1557}
Davide Italiano7e274e02016-12-22 16:03:48 +00001558
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001559// Check if there is a path, using single or equal argument phi nodes, from
1560// First to Second.
1561bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1562 const MemoryAccess *Second) const {
1563 if (First == Second)
1564 return true;
1565
1566 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1567 auto *DefAccess = FirstDef->getDefiningAccess();
1568 return singleReachablePHIPath(DefAccess, Second);
1569 } else {
1570 auto *MP = cast<MemoryPhi>(First);
1571 auto ReachableOperandPred = [&](const Use &U) {
1572 return ReachableBlocks.count(MP->getIncomingBlock(U));
1573 };
1574 auto FilteredPhiArgs =
1575 make_filter_range(MP->operands(), ReachableOperandPred);
1576 SmallVector<const Value *, 32> OperandList;
1577 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1578 std::back_inserter(OperandList));
1579 bool Okay = OperandList.size() == 1;
1580 if (!Okay)
1581 Okay = std::equal(OperandList.begin(), OperandList.end(),
1582 OperandList.begin());
1583 if (Okay)
1584 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1585 return false;
1586 }
1587}
1588
Daniel Berlin589cecc2017-01-02 18:00:46 +00001589// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001590// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001591// subject to very rare false negatives. It is only useful for
1592// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001593void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001594 // Anything equivalent in the memory access table should be in the same
1595 // congruence class.
1596
1597 // Filter out the unreachable and trivially dead entries, because they may
1598 // never have been updated if the instructions were not processed.
1599 auto ReachableAccessPred =
1600 [&](const std::pair<const MemoryAccess *, MemoryAccess *> Pair) {
1601 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1602 if (!Result)
1603 return false;
1604 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1605 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1606 return true;
1607 };
1608
1609 auto Filtered = make_filter_range(MemoryAccessEquiv, ReachableAccessPred);
1610 for (auto KV : Filtered) {
1611 assert(KV.first != KV.second &&
1612 "We added a useless equivalence to the memory equivalence table");
1613 // Unreachable instructions may not have changed because we never process
1614 // them.
1615 if (!ReachableBlocks.count(KV.first->getBlock()))
1616 continue;
1617 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
1618 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second);
Davide Italiano67ada752017-01-02 19:03:16 +00001619 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001620 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001621 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1622 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1623 "The instructions for these memory operations should have "
1624 "been in the same congruence class or reachable through"
1625 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001626 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1627
1628 // We can only sanely verify that MemoryDefs in the operand list all have
1629 // the same class.
1630 auto ReachableOperandPred = [&](const Use &U) {
1631 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1632 isa<MemoryDef>(U);
1633
1634 };
1635 // All arguments should in the same class, ignoring unreachable arguments
1636 auto FilteredPhiArgs =
1637 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1638 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1639 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1640 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1641 const MemoryDef *MD = cast<MemoryDef>(U);
1642 return ValueToClass.lookup(MD->getMemoryInst());
1643 });
1644 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1645 PhiOpClasses.begin()) &&
1646 "All MemoryPhi arguments should be in the same class");
1647 }
1648 }
1649}
1650
Daniel Berlin85f91b02016-12-26 20:06:58 +00001651// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001652bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001653 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1654 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001655 bool Changed = false;
1656 DT = _DT;
1657 AC = _AC;
1658 TLI = _TLI;
1659 AA = _AA;
1660 MSSA = _MSSA;
1661 DL = &F.getParent()->getDataLayout();
1662 MSSAWalker = MSSA->getWalker();
1663
1664 // Count number of instructions for sizing of hash tables, and come
1665 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001666 unsigned ICount = 1;
1667 // Add an empty instruction to account for the fact that we start at 1
1668 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001669 // Note: We want RPO traversal of the blocks, which is not quite the same as
1670 // dominator tree order, particularly with regard whether backedges get
1671 // visited first or second, given a block with multiple successors.
1672 // If we visit in the wrong order, we will end up performing N times as many
1673 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001674 // The dominator tree does guarantee that, for a given dom tree node, it's
1675 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1676 // the siblings.
1677 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001678 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001679 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001680 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001681 auto *Node = DT->getNode(B);
1682 assert(Node && "RPO and Dominator tree should have same reachability");
1683 RPOOrdering[Node] = ++Counter;
1684 }
1685 // Sort dominator tree children arrays into RPO.
1686 for (auto &B : RPOT) {
1687 auto *Node = DT->getNode(B);
1688 if (Node->getChildren().size() > 1)
1689 std::sort(Node->begin(), Node->end(),
1690 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1691 return RPOOrdering[A] < RPOOrdering[B];
1692 });
1693 }
1694
1695 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1696 auto DFI = df_begin(DT->getRootNode());
1697 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1698 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001699 const auto &BlockRange = assignDFSNumbers(B, ICount);
1700 BlockInstRange.insert({B, BlockRange});
1701 ICount += BlockRange.second - BlockRange.first;
1702 }
1703
1704 // Handle forward unreachable blocks and figure out which blocks
1705 // have single preds.
1706 for (auto &B : F) {
1707 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001708 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001709 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1710 BlockInstRange.insert({&B, BlockRange});
1711 ICount += BlockRange.second - BlockRange.first;
1712 }
1713 }
1714
Daniel Berline0bd37e2016-12-29 22:15:12 +00001715 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001716 DominatedInstRange.reserve(F.size());
1717 // Ensure we don't end up resizing the expressionToClass map, as
1718 // that can be quite expensive. At most, we have one expression per
1719 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001720 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001721
1722 // Initialize the touched instructions to include the entry block.
1723 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1724 TouchedInstructions.set(InstRange.first, InstRange.second);
1725 ReachableBlocks.insert(&F.getEntryBlock());
1726
1727 initializeCongruenceClasses(F);
1728
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001729 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001730 // We start out in the entry block.
1731 BasicBlock *LastBlock = &F.getEntryBlock();
1732 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001733 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00001734 // Walk through all the instructions in all the blocks in RPO.
1735 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1736 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001737
1738 // This instruction was found to be dead. We don't bother looking
1739 // at it again.
1740 if (InstrNum == 0) {
1741 TouchedInstructions.reset(InstrNum);
1742 continue;
1743 }
1744
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001745 Value *V = DFSToInstr[InstrNum];
1746 BasicBlock *CurrBlock = nullptr;
1747
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001748 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001749 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001750 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001751 CurrBlock = MP->getBlock();
1752 else
1753 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001754
1755 // If we hit a new block, do reachability processing.
1756 if (CurrBlock != LastBlock) {
1757 LastBlock = CurrBlock;
1758 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1759 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1760
1761 // If it's not reachable, erase any touched instructions and move on.
1762 if (!BlockReachable) {
1763 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1764 DEBUG(dbgs() << "Skipping instructions in block "
1765 << getBlockName(CurrBlock)
1766 << " because it is unreachable\n");
1767 continue;
1768 }
1769 updateProcessedCount(CurrBlock);
1770 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001771
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001772 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001773 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1774 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001775 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001776 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001777 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001778 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001779 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001780 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001781 // Reset after processing (because we may mark ourselves as touched when
1782 // we propagate equalities).
1783 TouchedInstructions.reset(InstrNum);
1784 }
1785 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001786 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001787#ifndef NDEBUG
1788 verifyMemoryCongruency();
1789#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001790 Changed |= eliminateInstructions(F);
1791
1792 // Delete all instructions marked for deletion.
1793 for (Instruction *ToErase : InstructionsToErase) {
1794 if (!ToErase->use_empty())
1795 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1796
1797 ToErase->eraseFromParent();
1798 }
1799
1800 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001801 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1802 return !ReachableBlocks.count(&BB);
1803 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001804
1805 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1806 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001807 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001808 deleteInstructionsInBlock(&BB);
1809 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001810 }
1811
1812 cleanupTables();
1813 return Changed;
1814}
1815
1816bool NewGVN::runOnFunction(Function &F) {
1817 if (skipFunction(F))
1818 return false;
1819 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1820 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1821 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1822 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1823 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1824}
1825
Daniel Berlin85f91b02016-12-26 20:06:58 +00001826PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001827 NewGVN Impl;
1828
1829 // Apparently the order in which we get these results matter for
1830 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1831 // the same order here, just in case.
1832 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1833 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1834 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1835 auto &AA = AM.getResult<AAManager>(F);
1836 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1837 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1838 if (!Changed)
1839 return PreservedAnalyses::all();
1840 PreservedAnalyses PA;
1841 PA.preserve<DominatorTreeAnalysis>();
1842 PA.preserve<GlobalsAA>();
1843 return PA;
1844}
1845
1846// Return true if V is a value that will always be available (IE can
1847// be placed anywhere) in the function. We don't do globals here
1848// because they are often worse to put in place.
1849// TODO: Separate cost from availability
1850static bool alwaysAvailable(Value *V) {
1851 return isa<Constant>(V) || isa<Argument>(V);
1852}
1853
1854// Get the basic block from an instruction/value.
1855static BasicBlock *getBlockForValue(Value *V) {
1856 if (auto *I = dyn_cast<Instruction>(V))
1857 return I->getParent();
1858 return nullptr;
1859}
1860
1861struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001862 int DFSIn = 0;
1863 int DFSOut = 0;
1864 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001865 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001866 Value *Val = nullptr;
1867 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001868
1869 bool operator<(const ValueDFS &Other) const {
1870 // It's not enough that any given field be less than - we have sets
1871 // of fields that need to be evaluated together to give a proper ordering.
1872 // For example, if you have;
1873 // DFS (1, 3)
1874 // Val 0
1875 // DFS (1, 2)
1876 // Val 50
1877 // We want the second to be less than the first, but if we just go field
1878 // by field, we will get to Val 0 < Val 50 and say the first is less than
1879 // the second. We only want it to be less than if the DFS orders are equal.
1880 //
1881 // Each LLVM instruction only produces one value, and thus the lowest-level
1882 // differentiator that really matters for the stack (and what we use as as a
1883 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001884 // Everything else in the structure is instruction level, and only affects
1885 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001886 //
1887 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1888 // the order of replacement of uses does not matter.
1889 // IE given,
1890 // a = 5
1891 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001892 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1893 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001894 // The .val will be the same as well.
1895 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001896 // You will replace both, and it does not matter what order you replace them
1897 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1898 // operand 2).
1899 // Similarly for the case of same dfsin, dfsout, localnum, but different
1900 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001901 // a = 5
1902 // b = 6
1903 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001904 // in c, we will a valuedfs for a, and one for b,with everything the same
1905 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001906 // It does not matter what order we replace these operands in.
1907 // You will always end up with the same IR, and this is guaranteed.
1908 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1909 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1910 Other.U);
1911 }
1912};
1913
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001914void NewGVN::convertDenseToDFSOrdered(
1915 CongruenceClass::MemberSet &Dense,
1916 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001917 for (auto D : Dense) {
1918 // First add the value.
1919 BasicBlock *BB = getBlockForValue(D);
1920 // Constants are handled prior to ever calling this function, so
1921 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001922 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001923 ValueDFS VD;
1924
Daniel Berlinb66164c2017-01-14 00:24:23 +00001925 DomTreeNode *DomNode = DT->getNode(BB);
1926 VD.DFSIn = DomNode->getDFSNumIn();
1927 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00001928 // If it's a store, use the leader of the value operand.
1929 if (auto *SI = dyn_cast<StoreInst>(D)) {
1930 auto Leader =
1931 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
1932 VD.Val = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
1933 } else {
1934 VD.Val = D;
1935 }
1936
Davide Italiano7e274e02016-12-22 16:03:48 +00001937 // If it's an instruction, use the real local dfs number.
1938 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlinaac56842017-01-15 09:18:41 +00001939 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001940 else
1941 llvm_unreachable("Should have been an instruction");
1942
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001943 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001944
Daniel Berlinb66164c2017-01-14 00:24:23 +00001945 // Now add the uses.
Davide Italiano7e274e02016-12-22 16:03:48 +00001946 for (auto &U : D->uses()) {
1947 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1948 ValueDFS VD;
1949 // Put the phi node uses in the incoming block.
1950 BasicBlock *IBlock;
1951 if (auto *P = dyn_cast<PHINode>(I)) {
1952 IBlock = P->getIncomingBlock(U);
1953 // Make phi node users appear last in the incoming block
1954 // they are from.
1955 VD.LocalNum = InstrDFS.size() + 1;
1956 } else {
1957 IBlock = I->getParent();
Daniel Berlinaac56842017-01-15 09:18:41 +00001958 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001959 }
Davide Italianoccbbc832017-01-26 00:42:42 +00001960
1961 // Skip uses in unreachable blocks, as we're going
1962 // to delete them.
1963 if (ReachableBlocks.count(IBlock) == 0)
1964 continue;
1965
Daniel Berlinb66164c2017-01-14 00:24:23 +00001966 DomTreeNode *DomNode = DT->getNode(IBlock);
1967 VD.DFSIn = DomNode->getDFSNumIn();
1968 VD.DFSOut = DomNode->getDFSNumOut();
Davide Italiano7e274e02016-12-22 16:03:48 +00001969 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001970 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001971 }
1972 }
1973 }
1974}
1975
1976static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1977 // Patch the replacement so that it is not more restrictive than the value
1978 // being replaced.
1979 auto *Op = dyn_cast<BinaryOperator>(I);
1980 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1981
1982 if (Op && ReplOp)
1983 ReplOp->andIRFlags(Op);
1984
1985 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1986 // FIXME: If both the original and replacement value are part of the
1987 // same control-flow region (meaning that the execution of one
1988 // guarentees the executation of the other), then we can combine the
1989 // noalias scopes here and do better than the general conservative
1990 // answer used in combineMetadata().
1991
1992 // In general, GVN unifies expressions over different control-flow
1993 // regions, and so we need a conservative combination of the noalias
1994 // scopes.
1995 unsigned KnownIDs[] = {
1996 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1997 LLVMContext::MD_noalias, LLVMContext::MD_range,
1998 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1999 LLVMContext::MD_invariant_group};
2000 combineMetadata(ReplInst, I, KnownIDs);
2001 }
2002}
2003
2004static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2005 patchReplacementInstruction(I, Repl);
2006 I->replaceAllUsesWith(Repl);
2007}
2008
2009void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2010 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2011 ++NumGVNBlocksDeleted;
2012
Daniel Berlin2b834922017-01-26 18:30:29 +00002013 // Change to unreachable does not handle destroying phi nodes. We just replace
2014 // the users with undef.
2015 if (BB->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00002016 return;
Daniel Berlin2b834922017-01-26 18:30:29 +00002017 auto BBI = BB->begin();
2018 while (auto *Phi = dyn_cast<PHINode>(BBI)) {
2019 Phi->replaceAllUsesWith(UndefValue::get(Phi->getType()));
2020 ++BBI;
Davide Italiano7e274e02016-12-22 16:03:48 +00002021 }
Daniel Berlin2b834922017-01-26 18:30:29 +00002022
2023 Instruction *ToKill = &*BBI;
2024 // Nothing but phi nodes, so nothing left to remove.
2025 if (!ToKill)
2026 return;
2027 NumGVNInstrDeleted += changeToUnreachable(ToKill, false);
Davide Italiano7e274e02016-12-22 16:03:48 +00002028}
2029
2030void NewGVN::markInstructionForDeletion(Instruction *I) {
2031 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2032 InstructionsToErase.insert(I);
2033}
2034
2035void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2036
2037 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2038 patchAndReplaceAllUsesWith(I, V);
2039 // We save the actual erasing to avoid invalidating memory
2040 // dependencies until we are done with everything.
2041 markInstructionForDeletion(I);
2042}
2043
2044namespace {
2045
2046// This is a stack that contains both the value and dfs info of where
2047// that value is valid.
2048class ValueDFSStack {
2049public:
2050 Value *back() const { return ValueStack.back(); }
2051 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2052
2053 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002054 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002055 DFSStack.emplace_back(DFSIn, DFSOut);
2056 }
2057 bool empty() const { return DFSStack.empty(); }
2058 bool isInScope(int DFSIn, int DFSOut) const {
2059 if (empty())
2060 return false;
2061 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2062 }
2063
2064 void popUntilDFSScope(int DFSIn, int DFSOut) {
2065
2066 // These two should always be in sync at this point.
2067 assert(ValueStack.size() == DFSStack.size() &&
2068 "Mismatch between ValueStack and DFSStack");
2069 while (
2070 !DFSStack.empty() &&
2071 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2072 DFSStack.pop_back();
2073 ValueStack.pop_back();
2074 }
2075 }
2076
2077private:
2078 SmallVector<Value *, 8> ValueStack;
2079 SmallVector<std::pair<int, int>, 8> DFSStack;
2080};
2081}
Daniel Berlin04443432017-01-07 03:23:47 +00002082
Davide Italiano7e274e02016-12-22 16:03:48 +00002083bool NewGVN::eliminateInstructions(Function &F) {
2084 // This is a non-standard eliminator. The normal way to eliminate is
2085 // to walk the dominator tree in order, keeping track of available
2086 // values, and eliminating them. However, this is mildly
2087 // pointless. It requires doing lookups on every instruction,
2088 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002089 // instructions part of most singleton congruence classes, we know we
2090 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002091
2092 // Instead, this eliminator looks at the congruence classes directly, sorts
2093 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002094 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002095 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002096 // last member. This is worst case O(E log E) where E = number of
2097 // instructions in a single congruence class. In theory, this is all
2098 // instructions. In practice, it is much faster, as most instructions are
2099 // either in singleton congruence classes or can't possibly be eliminated
2100 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002101 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002102 // for elimination purposes.
2103 // TODO: If we wanted to be faster, We could remove any members with no
2104 // overlapping ranges while sorting, as we will never eliminate anything
2105 // with those members, as they don't dominate anything else in our set.
2106
Davide Italiano7e274e02016-12-22 16:03:48 +00002107 bool AnythingReplaced = false;
2108
2109 // Since we are going to walk the domtree anyway, and we can't guarantee the
2110 // DFS numbers are updated, we compute some ourselves.
2111 DT->updateDFSNumbers();
2112
2113 for (auto &B : F) {
2114 if (!ReachableBlocks.count(&B)) {
2115 for (const auto S : successors(&B)) {
2116 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002117 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002118 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2119 << getBlockName(&B)
2120 << " with undef due to it being unreachable\n");
2121 for (auto &Operand : Phi.incoming_values())
2122 if (Phi.getIncomingBlock(Operand) == &B)
2123 Operand.set(UndefValue::get(Phi.getType()));
2124 }
2125 }
2126 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002127 }
2128
2129 for (CongruenceClass *CC : CongruenceClasses) {
2130 // FIXME: We should eventually be able to replace everything still
2131 // in the initial class with undef, as they should be unreachable.
2132 // Right now, initial still contains some things we skip value
2133 // numbering of (UNREACHABLE's, for example).
2134 if (CC == InitialClass || CC->Dead)
2135 continue;
2136 assert(CC->RepLeader && "We should have had a leader");
2137
2138 // If this is a leader that is always available, and it's a
2139 // constant or has no equivalences, just replace everything with
2140 // it. We then update the congruence class with whatever members
2141 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002142 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2143 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002144 SmallPtrSet<Value *, 4> MembersLeft;
2145 for (auto M : CC->Members) {
2146
2147 Value *Member = M;
2148
2149 // Void things have no uses we can replace.
2150 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2151 MembersLeft.insert(Member);
2152 continue;
2153 }
2154
Daniel Berlin26addef2017-01-20 21:04:30 +00002155 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2156 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002157 // Due to equality propagation, these may not always be
2158 // instructions, they may be real values. We don't really
2159 // care about trying to replace the non-instructions.
2160 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002161 assert(Leader != I && "About to accidentally remove our leader");
2162 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002163 AnythingReplaced = true;
2164
2165 continue;
2166 } else {
2167 MembersLeft.insert(I);
2168 }
2169 }
2170 CC->Members.swap(MembersLeft);
2171
2172 } else {
2173 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2174 // If this is a singleton, we can skip it.
2175 if (CC->Members.size() != 1) {
2176
2177 // This is a stack because equality replacement/etc may place
2178 // constants in the middle of the member list, and we want to use
2179 // those constant values in preference to the current leader, over
2180 // the scope of those constants.
2181 ValueDFSStack EliminationStack;
2182
2183 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002184 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002185 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2186
2187 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002188 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Davide Italiano7e274e02016-12-22 16:03:48 +00002189
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002190 for (auto &VD : DFSOrderedSet) {
2191 int MemberDFSIn = VD.DFSIn;
2192 int MemberDFSOut = VD.DFSOut;
2193 Value *Member = VD.Val;
2194 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002195
Daniel Berlind92e7f92017-01-07 00:01:42 +00002196 if (Member) {
2197 // We ignore void things because we can't get a value from them.
2198 // FIXME: We could actually use this to kill dead stores that are
2199 // dominated by equivalent earlier stores.
2200 if (Member->getType()->isVoidTy())
2201 continue;
2202 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002203
2204 if (EliminationStack.empty()) {
2205 DEBUG(dbgs() << "Elimination Stack is empty\n");
2206 } else {
2207 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2208 << EliminationStack.dfs_back().first << ","
2209 << EliminationStack.dfs_back().second << ")\n");
2210 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002211
2212 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2213 << MemberDFSOut << ")\n");
2214 // First, we see if we are out of scope or empty. If so,
2215 // and there equivalences, we try to replace the top of
2216 // stack with equivalences (if it's on the stack, it must
2217 // not have been eliminated yet).
2218 // Then we synchronize to our current scope, by
2219 // popping until we are back within a DFS scope that
2220 // dominates the current member.
2221 // Then, what happens depends on a few factors
2222 // If the stack is now empty, we need to push
2223 // If we have a constant or a local equivalence we want to
2224 // start using, we also push.
2225 // Otherwise, we walk along, processing members who are
2226 // dominated by this scope, and eliminate them.
2227 bool ShouldPush =
2228 Member && (EliminationStack.empty() || isa<Constant>(Member));
2229 bool OutOfScope =
2230 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2231
2232 if (OutOfScope || ShouldPush) {
2233 // Sync to our current scope.
2234 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2235 ShouldPush |= Member && EliminationStack.empty();
2236 if (ShouldPush) {
2237 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2238 }
2239 }
2240
2241 // If we get to this point, and the stack is empty we must have a use
2242 // with nothing we can use to eliminate it, just skip it.
2243 if (EliminationStack.empty())
2244 continue;
2245
2246 // Skip the Value's, we only want to eliminate on their uses.
2247 if (Member)
2248 continue;
2249 Value *Result = EliminationStack.back();
2250
Daniel Berlind92e7f92017-01-07 00:01:42 +00002251 // Don't replace our existing users with ourselves.
2252 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002253 continue;
2254
2255 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2256 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2257 << "\n");
2258
2259 // If we replaced something in an instruction, handle the patching of
2260 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002261 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002262 patchReplacementInstruction(ReplacedInst, Result);
2263
2264 assert(isa<Instruction>(MemberUse->getUser()));
2265 MemberUse->set(Result);
2266 AnythingReplaced = true;
2267 }
2268 }
2269 }
2270
2271 // Cleanup the congruence class.
2272 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002273 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002274 if (Member->getType()->isVoidTy()) {
2275 MembersLeft.insert(Member);
2276 continue;
2277 }
2278
2279 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2280 if (isInstructionTriviallyDead(MemberInst)) {
2281 // TODO: Don't mark loads of undefs.
2282 markInstructionForDeletion(MemberInst);
2283 continue;
2284 }
2285 }
2286 MembersLeft.insert(Member);
2287 }
2288 CC->Members.swap(MembersLeft);
2289 }
2290
2291 return AnythingReplaced;
2292}