blob: 453a308cb2c0da741b705726140a6ef65afb40aa [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"
Davide Italiano7e274e02016-12-22 16:03:48 +000064#include "llvm/Analysis/MemoryBuiltins.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000065#include "llvm/Analysis/MemoryLocation.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000066#include "llvm/Analysis/TargetLibraryInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000067#include "llvm/IR/DataLayout.h"
68#include "llvm/IR/Dominators.h"
69#include "llvm/IR/GlobalVariable.h"
70#include "llvm/IR/IRBuilder.h"
71#include "llvm/IR/IntrinsicInst.h"
72#include "llvm/IR/LLVMContext.h"
73#include "llvm/IR/Metadata.h"
74#include "llvm/IR/PatternMatch.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000075#include "llvm/IR/Type.h"
76#include "llvm/Support/Allocator.h"
77#include "llvm/Support/CommandLine.h"
78#include "llvm/Support/Debug.h"
Daniel Berlin283a6082017-03-01 19:59:26 +000079#include "llvm/Support/DebugCounter.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000080#include "llvm/Transforms/Scalar.h"
81#include "llvm/Transforms/Scalar/GVNExpression.h"
82#include "llvm/Transforms/Utils/BasicBlockUtils.h"
83#include "llvm/Transforms/Utils/Local.h"
84#include "llvm/Transforms/Utils/MemorySSA.h"
Daniel Berlinf7d95802017-02-18 23:06:50 +000085#include "llvm/Transforms/Utils/PredicateInfo.h"
Daniel Berlin07daac82017-04-02 13:23:44 +000086#include "llvm/Transforms/Utils/VNCoercion.h"
Daniel Berlin1316a942017-04-06 18:52:50 +000087#include <numeric>
Davide Italiano7e274e02016-12-22 16:03:48 +000088#include <unordered_map>
89#include <utility>
90#include <vector>
91using namespace llvm;
92using namespace PatternMatch;
93using namespace llvm::GVNExpression;
Daniel Berlin07daac82017-04-02 13:23:44 +000094using namespace llvm::VNCoercion;
Davide Italiano7e274e02016-12-22 16:03:48 +000095#define DEBUG_TYPE "newgvn"
96
97STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
98STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
99STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
100STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +0000101STATISTIC(NumGVNMaxIterations,
102 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000103STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
104STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
105STATISTIC(NumGVNAvoidedSortedLeaderChanges,
106 "Number of avoided sorted leader changes");
Daniel Berlin89fea6f2017-01-20 06:38:41 +0000107STATISTIC(NumGVNNotMostDominatingLeader,
108 "Number of times a member dominated it's new classes' leader");
Daniel Berlinc4796862017-01-27 02:37:11 +0000109STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Daniel Berlin283a6082017-03-01 19:59:26 +0000110DEBUG_COUNTER(VNCounter, "newgvn-vn",
111 "Controls which instructions are value numbered")
Daniel Berlin1316a942017-04-06 18:52:50 +0000112
113// Currently store defining access refinement is too slow due to basicaa being
114// egregiously slow. This flag lets us keep it working while we work on this
115// issue.
116static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
117 cl::init(false), cl::Hidden);
118
Davide Italiano7e274e02016-12-22 16:03:48 +0000119//===----------------------------------------------------------------------===//
120// GVN Pass
121//===----------------------------------------------------------------------===//
122
123// Anchor methods.
124namespace llvm {
125namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000126Expression::~Expression() = default;
127BasicExpression::~BasicExpression() = default;
128CallExpression::~CallExpression() = default;
129LoadExpression::~LoadExpression() = default;
130StoreExpression::~StoreExpression() = default;
131AggregateValueExpression::~AggregateValueExpression() = default;
132PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000133}
134}
135
136// Congruence classes represent the set of expressions/instructions
137// that are all the same *during some scope in the function*.
138// That is, because of the way we perform equality propagation, and
139// because of memory value numbering, it is not correct to assume
140// you can willy-nilly replace any member with any other at any
141// point in the function.
142//
143// For any Value in the Member set, it is valid to replace any dominated member
144// with that Value.
145//
Daniel Berlin1316a942017-04-06 18:52:50 +0000146// Every congruence class has a leader, and the leader is used to symbolize
147// instructions in a canonical way (IE every operand of an instruction that is a
148// member of the same congruence class will always be replaced with leader
149// during symbolization). To simplify symbolization, we keep the leader as a
150// constant if class can be proved to be a constant value. Otherwise, the
151// leader is the member of the value set with the smallest DFS number. Each
152// congruence class also has a defining expression, though the expression may be
153// null. If it exists, it can be used for forward propagation and reassociation
154// of values.
155
156// For memory, we also track a representative MemoryAccess, and a set of memory
157// members for MemoryPhis (which have no real instructions). Note that for
158// memory, it seems tempting to try to split the memory members into a
159// MemoryCongruenceClass or something. Unfortunately, this does not work
160// easily. The value numbering of a given memory expression depends on the
161// leader of the memory congruence class, and the leader of memory congruence
162// class depends on the value numbering of a given memory expression. This
163// leads to wasted propagation, and in some cases, missed optimization. For
164// example: If we had value numbered two stores together before, but now do not,
165// we move them to a new value congruence class. This in turn will move at one
166// of the memorydefs to a new memory congruence class. Which in turn, affects
167// the value numbering of the stores we just value numbered (because the memory
168// congruence class is part of the value number). So while theoretically
169// possible to split them up, it turns out to be *incredibly* complicated to get
170// it to work right, because of the interdependency. While structurally
171// slightly messier, it is algorithmically much simpler and faster to do what we
172// do here,
173// and track them both at once in the same class.
Davide Italiano7e274e02016-12-22 16:03:48 +0000174struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000175 using MemberSet = SmallPtrSet<Value *, 4>;
Daniel Berlin1316a942017-04-06 18:52:50 +0000176 using MemoryMemberSet = SmallPtrSet<const MemoryPhi *, 2>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000177 unsigned ID;
178 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000179 Value *RepLeader = nullptr;
Daniel Berlin1316a942017-04-06 18:52:50 +0000180 // If this is represented by a store, the value of the store.
Daniel Berlin26addef2017-01-20 21:04:30 +0000181 Value *RepStoredValue = nullptr;
Daniel Berlin1316a942017-04-06 18:52:50 +0000182 // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
183 // access.
184 const MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000185 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000186 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000187 // Actual members of this class.
188 MemberSet Members;
Daniel Berlin1316a942017-04-06 18:52:50 +0000189 // This is the set of MemoryPhis that exist in the class. MemoryDefs and
190 // MemoryUses have real instructions representing them, so we only need to
191 // track MemoryPhis here.
192 MemoryMemberSet MemoryMembers;
Davide Italiano7e274e02016-12-22 16:03:48 +0000193
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000194 // Number of stores in this congruence class.
195 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000196 int StoreCount = 0;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000197
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000198 // The most dominating leader after our current leader, because the member set
199 // is not sorted and is expensive to keep sorted all the time.
200 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
201
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000202 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000203 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000204 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Daniel Berlin1316a942017-04-06 18:52:50 +0000205 // True if this class has no members left. This is mainly used for assertion
206 // purposes, and for skipping empty classes.
207 bool isDead() const {
208 // If it's both dead from a value perspective, and dead from a memory
209 // perspective, it's really dead.
210 return Members.empty() && MemoryMembers.empty();
211 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000212};
213
Daniel Berlin06329a92017-03-18 15:41:40 +0000214// Return true if two congruence classes are equivalent to each other. This
215// means
216// that every field but the ID number and the dead field are equivalent.
217bool areClassesEquivalent(const CongruenceClass *A, const CongruenceClass *B) {
218 if (A == B)
219 return true;
220 if ((A && !B) || (B && !A))
221 return false;
222
223 if (std::tie(A->StoreCount, A->RepLeader, A->RepStoredValue,
224 A->RepMemoryAccess) != std::tie(B->StoreCount, B->RepLeader,
225 B->RepStoredValue,
226 B->RepMemoryAccess))
227 return false;
228 if (A->DefiningExpr != B->DefiningExpr)
229 if (!A->DefiningExpr || !B->DefiningExpr ||
230 *A->DefiningExpr != *B->DefiningExpr)
231 return false;
232 // We need some ordered set
233 std::set<Value *> AMembers(A->Members.begin(), A->Members.end());
234 std::set<Value *> BMembers(B->Members.begin(), B->Members.end());
235 return AMembers == BMembers;
236}
237
Davide Italiano7e274e02016-12-22 16:03:48 +0000238namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000239template <> struct DenseMapInfo<const Expression *> {
240 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000241 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000242 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
243 return reinterpret_cast<const Expression *>(Val);
244 }
245 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000246 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000247 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
248 return reinterpret_cast<const Expression *>(Val);
249 }
250 static unsigned getHashValue(const Expression *V) {
251 return static_cast<unsigned>(V->getHashValue());
252 }
253 static bool isEqual(const Expression *LHS, const Expression *RHS) {
254 if (LHS == RHS)
255 return true;
256 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
257 LHS == getEmptyKey() || RHS == getEmptyKey())
258 return false;
259 return *LHS == *RHS;
260 }
261};
Davide Italiano7e274e02016-12-22 16:03:48 +0000262} // end namespace llvm
263
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000264namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000265class NewGVN {
266 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000267 DominatorTree *DT;
Davide Italiano7e274e02016-12-22 16:03:48 +0000268 AssumptionCache *AC;
Daniel Berlin64e68992017-03-12 04:46:45 +0000269 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000270 AliasAnalysis *AA;
271 MemorySSA *MSSA;
272 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000273 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000274 std::unique_ptr<PredicateInfo> PredInfo;
Davide Italiano7e274e02016-12-22 16:03:48 +0000275 BumpPtrAllocator ExpressionAllocator;
276 ArrayRecycler<Value *> ArgRecycler;
277
Daniel Berlin1c087672017-02-11 15:07:01 +0000278 // Number of function arguments, used by ranking
279 unsigned int NumFuncArgs;
280
Davide Italiano7e274e02016-12-22 16:03:48 +0000281 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000282
283 // This class is called INITIAL in the paper. It is the class everything
284 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000285 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000286 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000287 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000288 std::vector<CongruenceClass *> CongruenceClasses;
289 unsigned NextCongruenceNum;
290
291 // Value Mappings.
292 DenseMap<Value *, CongruenceClass *> ValueToClass;
293 DenseMap<Value *, const Expression *> ValueToExpression;
294
Daniel Berlinf7d95802017-02-18 23:06:50 +0000295 // Mapping from predicate info we used to the instructions we used it with.
296 // In order to correctly ensure propagation, we must keep track of what
297 // comparisons we used, so that when the values of the comparisons change, we
298 // propagate the information to the places we used the comparison.
299 DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000300 // Mapping from MemoryAccess we used to the MemoryAccess we used it with. Has
301 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
302 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
303 DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>> MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000304
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000305 // A table storing which memorydefs/phis represent a memory state provably
306 // equivalent to another memory state.
307 // We could use the congruence class machinery, but the MemoryAccess's are
308 // abstract memory states, so they can only ever be equivalent to each other,
309 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000310 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000311
Daniel Berlin1316a942017-04-06 18:52:50 +0000312 // We could, if we wanted, build MemoryPhiExpressions and
313 // MemoryVariableExpressions, etc, and value number them the same way we value
314 // number phi expressions. For the moment, this seems like overkill. They
315 // can only exist in one of three states: they can be TOP (equal to
316 // everything), Equivalent to something else, or unique. Because we do not
317 // create expressions for them, we need to simulate leader change not just
318 // when they change class, but when they change state. Note: We can do the
319 // same thing for phis, and avoid having phi expressions if we wanted, We
320 // should eventually unify in one direction or the other, so this is a little
321 // bit of an experiment in which turns out easier to maintain.
322 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
323 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
324
Davide Italiano7e274e02016-12-22 16:03:48 +0000325 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000326 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000327 ExpressionClassMap ExpressionToClass;
328
329 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000330 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000331
332 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000333 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000334 DenseSet<BlockEdge> ReachableEdges;
335 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
336
337 // This is a bitvector because, on larger functions, we may have
338 // thousands of touched instructions at once (entire blocks,
339 // instructions with hundreds of uses, etc). Even with optimization
340 // for when we mark whole blocks as touched, when this was a
341 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
342 // the time in GVN just managing this list. The bitvector, on the
343 // other hand, efficiently supports test/set/clear of both
344 // individual and ranges, as well as "find next element" This
345 // enables us to use it as a worklist with essentially 0 cost.
346 BitVector TouchedInstructions;
347
348 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000349
350#ifndef NDEBUG
351 // Debugging for how many times each block and instruction got processed.
352 DenseMap<const Value *, unsigned> ProcessedCount;
353#endif
354
355 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000356 // This contains a mapping from Instructions to DFS numbers.
357 // The numbering starts at 1. An instruction with DFS number zero
358 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000359 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000360
361 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000362 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000363
364 // Deletion info.
365 SmallPtrSet<Instruction *, 8> InstructionsToErase;
366
367public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000368 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
369 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
370 const DataLayout &DL)
371 : F(F), DT(DT), AC(AC), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
372 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)) {}
373 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000374
375private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000376 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000377 const Expression *createExpression(Instruction *);
378 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000379 PHIExpression *createPHIExpression(Instruction *);
380 const VariableExpression *createVariableExpression(Value *);
381 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000382 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000383 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000384 const StoreExpression *createStoreExpression(StoreInst *,
385 const MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000386 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin1316a942017-04-06 18:52:50 +0000387 const MemoryAccess *);
388 const CallExpression *createCallExpression(CallInst *, const MemoryAccess *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000389 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
390 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000391
392 // Congruence class handling.
393 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000394 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000395 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000396 return result;
397 }
398
Daniel Berlin1316a942017-04-06 18:52:50 +0000399 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
400 auto *CC = createCongruenceClass(nullptr, nullptr);
401 CC->RepMemoryAccess = MA;
402 return CC;
403 }
404 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
405 auto *CC = getMemoryClass(MA);
406 if (CC->RepMemoryAccess != MA)
407 CC = createMemoryClass(MA);
408 return CC;
409 }
410
Davide Italiano7e274e02016-12-22 16:03:48 +0000411 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000412 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000413 CClass->Members.insert(Member);
414 ValueToClass[Member] = CClass;
415 return CClass;
416 }
417 void initializeCongruenceClasses(Function &F);
418
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000419 // Value number an Instruction or MemoryPhi.
420 void valueNumberMemoryPhi(MemoryPhi *);
421 void valueNumberInstruction(Instruction *);
422
Davide Italiano7e274e02016-12-22 16:03:48 +0000423 // Symbolic evaluation.
424 const Expression *checkSimplificationResults(Expression *, Instruction *,
425 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000426 const Expression *performSymbolicEvaluation(Value *);
Daniel Berlin07daac82017-04-02 13:23:44 +0000427 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
428 Instruction *, MemoryAccess *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000429 const Expression *performSymbolicLoadEvaluation(Instruction *);
430 const Expression *performSymbolicStoreEvaluation(Instruction *);
431 const Expression *performSymbolicCallEvaluation(Instruction *);
432 const Expression *performSymbolicPHIEvaluation(Instruction *);
433 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
434 const Expression *performSymbolicCmpEvaluation(Instruction *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000435 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000436
437 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000438 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000439 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000440 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000441 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
442 CongruenceClass *, CongruenceClass *);
443 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
444 CongruenceClass *, CongruenceClass *);
445 Value *getNextValueLeader(CongruenceClass *) const;
446 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
447 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
448 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
449 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000450 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000451
Daniel Berlin1c087672017-02-11 15:07:01 +0000452 // Ranking
453 unsigned int getRank(const Value *) const;
454 bool shouldSwapOperands(const Value *, const Value *) const;
455
Davide Italiano7e274e02016-12-22 16:03:48 +0000456 // Reachability handling.
457 void updateReachableEdge(BasicBlock *, BasicBlock *);
458 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000459 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000460
461 // Elimination.
462 struct ValueDFS;
Daniel Berline3e69e12017-03-10 00:32:33 +0000463 void convertClassToDFSOrdered(const CongruenceClass::MemberSet &,
464 SmallVectorImpl<ValueDFS> &,
465 DenseMap<const Value *, unsigned int> &,
466 SmallPtrSetImpl<Instruction *> &);
467 void convertClassToLoadsAndStores(const CongruenceClass::MemberSet &,
Daniel Berlinc4796862017-01-27 02:37:11 +0000468 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000469
470 bool eliminateInstructions(Function &);
471 void replaceInstruction(Instruction *, Value *);
472 void markInstructionForDeletion(Instruction *);
473 void deleteInstructionsInBlock(BasicBlock *);
474
475 // New instruction creation.
476 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000477
478 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000479 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000480 void markMemoryUsersTouched(const MemoryAccess *);
481 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000482 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000483 void markValueLeaderChangeTouched(CongruenceClass *CC);
484 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000485 void addPredicateUsers(const PredicateBase *, Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000486 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U);
Davide Italiano7e274e02016-12-22 16:03:48 +0000487
Daniel Berlin06329a92017-03-18 15:41:40 +0000488 // Main loop of value numbering
489 void iterateTouchedInstructions();
490
Davide Italiano7e274e02016-12-22 16:03:48 +0000491 // Utilities.
492 void cleanupTables();
493 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
494 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000495 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000496 void verifyIterationSettled(Function &F);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000497 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000498 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin0e900112017-03-24 06:33:48 +0000499 void deleteExpression(const Expression *E);
Daniel Berlin21279bd2017-04-06 18:52:58 +0000500 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000501 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
502 return InstrDFS.lookup(V);
503 }
504
Daniel Berlin21279bd2017-04-06 18:52:58 +0000505 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
506 return MemoryToDFSNum(MA);
507 }
508 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
509 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
510 // This deliberately takes a value so it can be used with Use's, which will
511 // auto-convert to Value's but not to MemoryAccess's.
512 unsigned MemoryToDFSNum(const Value *MA) const {
513 assert(isa<MemoryAccess>(MA) &&
514 "This should not be used with instructions");
515 return isa<MemoryUseOrDef>(MA)
516 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
517 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000518 }
519
Daniel Berlin1316a942017-04-06 18:52:50 +0000520 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000521 // Debug counter info. When verifying, we have to reset the value numbering
522 // debug counter to the same state it started in to get the same results.
523 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000524};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000525} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000526
Davide Italianob1114092016-12-28 13:37:17 +0000527template <typename T>
528static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000529 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000530 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000531 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000532}
533
Davide Italianob1114092016-12-28 13:37:17 +0000534bool LoadExpression::equals(const Expression &Other) const {
535 return equalsLoadStoreHelper(*this, Other);
536}
Davide Italiano7e274e02016-12-22 16:03:48 +0000537
Davide Italianob1114092016-12-28 13:37:17 +0000538bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000539 if (!equalsLoadStoreHelper(*this, Other))
540 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000541 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000542 if (const auto *S = dyn_cast<StoreExpression>(&Other))
543 if (getStoredValue() != S->getStoredValue())
544 return false;
545 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000546}
547
548#ifndef NDEBUG
549static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000550 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000551}
552#endif
553
Daniel Berlin06329a92017-03-18 15:41:40 +0000554// Get the basic block from an instruction/memory value.
555BasicBlock *NewGVN::getBlockForValue(Value *V) const {
556 if (auto *I = dyn_cast<Instruction>(V))
557 return I->getParent();
558 else if (auto *MP = dyn_cast<MemoryPhi>(V))
559 return MP->getBlock();
560 llvm_unreachable("Should have been able to figure out a block for our value");
561 return nullptr;
562}
563
Daniel Berlin0e900112017-03-24 06:33:48 +0000564// Delete a definitely dead expression, so it can be reused by the expression
565// allocator. Some of these are not in creation functions, so we have to accept
566// const versions.
567void NewGVN::deleteExpression(const Expression *E) {
568 assert(isa<BasicExpression>(E));
569 auto *BE = cast<BasicExpression>(E);
570 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
571 ExpressionAllocator.Deallocate(E);
572}
573
Davide Italiano7e274e02016-12-22 16:03:48 +0000574PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000575 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000576 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000577 auto *E =
578 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000579
580 E->allocateOperands(ArgRecycler, ExpressionAllocator);
581 E->setType(I->getType());
582 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000583
Davide Italianob3886dd2017-01-25 23:37:49 +0000584 // Filter out unreachable phi operands.
585 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +0000586 return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000587 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000588
589 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
590 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000591 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000592 if (U == PN)
593 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000594 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000595 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000596 return E;
597}
598
599// Set basic expression info (Arguments, type, opcode) for Expression
600// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000601bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000602 bool AllConstant = true;
603 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
604 E->setType(GEP->getSourceElementType());
605 else
606 E->setType(I->getType());
607 E->setOpcode(I->getOpcode());
608 E->allocateOperands(ArgRecycler, ExpressionAllocator);
609
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000610 // Transform the operand array into an operand leader array, and keep track of
611 // whether all members are constant.
612 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000613 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000614 AllConstant &= isa<Constant>(Operand);
615 return Operand;
616 });
617
Davide Italiano7e274e02016-12-22 16:03:48 +0000618 return AllConstant;
619}
620
621const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000622 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000623 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000624
625 E->setType(T);
626 E->setOpcode(Opcode);
627 E->allocateOperands(ArgRecycler, ExpressionAllocator);
628 if (Instruction::isCommutative(Opcode)) {
629 // Ensure that commutative instructions that only differ by a permutation
630 // of their operands get the same value number by sorting the operand value
631 // numbers. Since all commutative instructions have two operands it is more
632 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000633 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000634 std::swap(Arg1, Arg2);
635 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000636 E->op_push_back(lookupOperandLeader(Arg1));
637 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000638
Daniel Berlin64e68992017-03-12 04:46:45 +0000639 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), DL, TLI,
Davide Italiano7e274e02016-12-22 16:03:48 +0000640 DT, AC);
641 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
642 return SimplifiedE;
643 return E;
644}
645
646// Take a Value returned by simplification of Expression E/Instruction
647// I, and see if it resulted in a simpler expression. If so, return
648// that expression.
649// TODO: Once finished, this should not take an Instruction, we only
650// use it for printing.
651const Expression *NewGVN::checkSimplificationResults(Expression *E,
652 Instruction *I, Value *V) {
653 if (!V)
654 return nullptr;
655 if (auto *C = dyn_cast<Constant>(V)) {
656 if (I)
657 DEBUG(dbgs() << "Simplified " << *I << " to "
658 << " constant " << *C << "\n");
659 NumGVNOpsSimplified++;
660 assert(isa<BasicExpression>(E) &&
661 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000662 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000663 return createConstantExpression(C);
664 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
665 if (I)
666 DEBUG(dbgs() << "Simplified " << *I << " to "
667 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000668 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000669 return createVariableExpression(V);
670 }
671
672 CongruenceClass *CC = ValueToClass.lookup(V);
673 if (CC && CC->DefiningExpr) {
674 if (I)
675 DEBUG(dbgs() << "Simplified " << *I << " to "
676 << " expression " << *V << "\n");
677 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000678 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000679 return CC->DefiningExpr;
680 }
681 return nullptr;
682}
683
Daniel Berlin97718e62017-01-31 22:32:03 +0000684const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000685 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000686
Daniel Berlin97718e62017-01-31 22:32:03 +0000687 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000688
689 if (I->isCommutative()) {
690 // Ensure that commutative instructions that only differ by a permutation
691 // of their operands get the same value number by sorting the operand value
692 // numbers. Since all commutative instructions have two operands it is more
693 // efficient to sort by hand rather than using, say, std::sort.
694 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000695 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000696 E->swapOperands(0, 1);
697 }
698
699 // Perform simplificaiton
700 // TODO: Right now we only check to see if we get a constant result.
701 // We may get a less than constant, but still better, result for
702 // some operations.
703 // IE
704 // add 0, x -> x
705 // and x, x -> x
706 // We should handle this by simply rewriting the expression.
707 if (auto *CI = dyn_cast<CmpInst>(I)) {
708 // Sort the operand value numbers so x<y and y>x get the same value
709 // number.
710 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000711 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000712 E->swapOperands(0, 1);
713 Predicate = CmpInst::getSwappedPredicate(Predicate);
714 }
715 E->setOpcode((CI->getOpcode() << 8) | Predicate);
716 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000717 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
718 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000719 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
720 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000721 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000722 DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000723 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
724 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000725 } else if (isa<SelectInst>(I)) {
726 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000727 E->getOperand(0) == E->getOperand(1)) {
728 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
729 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000730 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000731 E->getOperand(2), DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000732 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
733 return SimplifiedE;
734 }
735 } else if (I->isBinaryOp()) {
736 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000737 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000738 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
739 return SimplifiedE;
740 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin64e68992017-03-12 04:46:45 +0000741 Value *V = SimplifyInstruction(BI, DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000742 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
743 return SimplifiedE;
744 } else if (isa<GetElementPtrInst>(I)) {
745 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000746 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Daniel Berlin64e68992017-03-12 04:46:45 +0000747 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000748 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
749 return SimplifiedE;
750 } else if (AllConstant) {
751 // We don't bother trying to simplify unless all of the operands
752 // were constant.
753 // TODO: There are a lot of Simplify*'s we could call here, if we
754 // wanted to. The original motivating case for this code was a
755 // zext i1 false to i8, which we don't have an interface to
756 // simplify (IE there is no SimplifyZExt).
757
758 SmallVector<Constant *, 8> C;
759 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000760 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000761
Daniel Berlin64e68992017-03-12 04:46:45 +0000762 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +0000763 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
764 return SimplifiedE;
765 }
766 return E;
767}
768
769const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000770NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000771 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000772 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000773 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000774 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000775 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000776 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000777 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000778 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000779 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000780 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000781 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000782 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000783 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000784 return E;
785 }
786 llvm_unreachable("Unhandled type of aggregate value operation");
787}
788
Daniel Berlin85f91b02016-12-26 20:06:58 +0000789const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000790 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000791 E->setOpcode(V->getValueID());
792 return E;
793}
794
Daniel Berlinf7d95802017-02-18 23:06:50 +0000795const Expression *NewGVN::createVariableOrConstant(Value *V) {
796 if (auto *C = dyn_cast<Constant>(V))
797 return createConstantExpression(C);
798 return createVariableExpression(V);
799}
800
Daniel Berlin85f91b02016-12-26 20:06:58 +0000801const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000802 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000803 E->setOpcode(C->getValueID());
804 return E;
805}
806
Daniel Berlin02c6b172017-01-02 18:00:53 +0000807const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
808 auto *E = new (ExpressionAllocator) UnknownExpression(I);
809 E->setOpcode(I->getOpcode());
810 return E;
811}
812
Davide Italiano7e274e02016-12-22 16:03:48 +0000813const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin1316a942017-04-06 18:52:50 +0000814 const MemoryAccess *MA) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000815 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000816 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +0000817 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +0000818 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000819 return E;
820}
821
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000822// Return true if some equivalent of instruction Inst dominates instruction U.
823bool NewGVN::someEquivalentDominates(const Instruction *Inst,
824 const Instruction *U) const {
825 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +0000826 // This must be an instruction because we are only called from phi nodes
827 // in the case that the value it needs to check against is an instruction.
828
829 // The most likely candiates for dominance are the leader and the next leader.
830 // The leader or nextleader will dominate in all cases where there is an
831 // equivalent that is higher up in the dom tree.
832 // We can't *only* check them, however, because the
833 // dominator tree could have an infinite number of non-dominating siblings
834 // with instructions that are in the right congruence class.
835 // A
836 // B C D E F G
837 // |
838 // H
839 // Instruction U could be in H, with equivalents in every other sibling.
840 // Depending on the rpo order picked, the leader could be the equivalent in
841 // any of these siblings.
842 if (!CC)
843 return false;
844 if (DT->dominates(cast<Instruction>(CC->RepLeader), U))
845 return true;
846 if (CC->NextLeader.first &&
847 DT->dominates(cast<Instruction>(CC->NextLeader.first), U))
848 return true;
849 return llvm::any_of(CC->Members, [&](const Value *Member) {
850 return Member != CC->RepLeader &&
851 DT->dominates(cast<Instruction>(Member), U);
852 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000853}
854
Davide Italiano7e274e02016-12-22 16:03:48 +0000855// See if we have a congruence class and leader for this operand, and if so,
856// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000857Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000858 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000859 if (CC) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000860 // Everything in TOP is represneted by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000861 // We do have to make sure we get the type right though, so we can't set the
862 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000863 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +0000864 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000865 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000866 }
867
Davide Italiano7e274e02016-12-22 16:03:48 +0000868 return V;
869}
870
Daniel Berlin1316a942017-04-06 18:52:50 +0000871const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
872 auto *CC = getMemoryClass(MA);
873 assert(CC->RepMemoryAccess && "Every MemoryAccess should be mapped to a "
874 "congruence class with a represenative memory "
875 "access");
876 return CC->RepMemoryAccess;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000877}
878
Daniel Berlinc4796862017-01-27 02:37:11 +0000879// Return true if the MemoryAccess is really equivalent to everything. This is
880// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +0000881// state of all MemoryAccesses.
Daniel Berlinc4796862017-01-27 02:37:11 +0000882bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000883 return getMemoryClass(MA) == TOPClass;
884}
885
Daniel Berlinc4796862017-01-27 02:37:11 +0000886
Davide Italiano7e274e02016-12-22 16:03:48 +0000887LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +0000888 LoadInst *LI,
889 const MemoryAccess *MA) {
890 auto *E =
891 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +0000892 E->allocateOperands(ArgRecycler, ExpressionAllocator);
893 E->setType(LoadType);
894
895 // Give store and loads same opcode so they value number together.
896 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +0000897 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +0000898 if (LI)
899 E->setAlignment(LI->getAlignment());
900
901 // TODO: Value number heap versions. We may be able to discover
902 // things alias analysis can't on it's own (IE that a store and a
903 // load have the same value, and thus, it isn't clobbering the load).
904 return E;
905}
906
907const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin1316a942017-04-06 18:52:50 +0000908 const MemoryAccess *MA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000909 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000910 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +0000911 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000912 E->allocateOperands(ArgRecycler, ExpressionAllocator);
913 E->setType(SI->getValueOperand()->getType());
914
915 // Give store and loads same opcode so they value number together.
916 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000917 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000918
919 // TODO: Value number heap versions. We may be able to discover
920 // things alias analysis can't on it's own (IE that a store and a
921 // load have the same value, and thus, it isn't clobbering the load).
922 return E;
923}
924
Daniel Berlin97718e62017-01-31 22:32:03 +0000925const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000926 // Unlike loads, we never try to eliminate stores, so we do not check if they
927 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000928 auto *SI = cast<StoreInst>(I);
Daniel Berlin1316a942017-04-06 18:52:50 +0000929 auto *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000930 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +0000931 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
932 if (EnableStoreRefinement)
933 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
934 // If we bypassed the use-def chains, make sure we add a use.
935 if (StoreRHS != StoreAccess->getDefiningAccess())
936 addMemoryUsers(StoreRHS, StoreAccess);
937
938 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +0000939 // If we are defined by ourselves, use the live on entry def.
940 if (StoreRHS == StoreAccess)
941 StoreRHS = MSSA->getLiveOnEntryDef();
942
Daniel Berlin589cecc2017-01-02 18:00:46 +0000943 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000944 // See if we are defined by a previous store expression, it already has a
945 // value, and it's the same value as our current store. FIXME: Right now, we
946 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +0000947 const auto *LastStore = createStoreExpression(SI, StoreRHS);
948 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000949 // Basically, check if the congruence class the store is in is defined by a
950 // store that isn't us, and has the same value. MemorySSA takes care of
951 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000952 // The RepStoredValue gets nulled if all the stores disappear in a class, so
953 // we don't need to check if the class contains a store besides us.
Daniel Berlin1316a942017-04-06 18:52:50 +0000954 if (LastCC &&
955 LastCC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
956 return LastStore;
957 deleteExpression(LastStore);
Daniel Berlinc4796862017-01-27 02:37:11 +0000958 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +0000959 // location, and the memory state is the same as it was then (otherwise, it
960 // could have been overwritten later. See test32 in
961 // transforms/DeadStoreElimination/simple.ll).
962 if (auto *LI =
963 dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000964 if ((lookupOperandLeader(LI->getPointerOperand()) ==
965 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlin1316a942017-04-06 18:52:50 +0000966 (lookupMemoryLeader(MSSA->getMemoryAccess(LI)->getDefiningAccess()) ==
967 StoreRHS))
Daniel Berlinc4796862017-01-27 02:37:11 +0000968 return createVariableExpression(LI);
969 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000970 }
Daniel Berlin1316a942017-04-06 18:52:50 +0000971
972 // If the store is not equivalent to anything, value number it as a store that
973 // produces a unique memory state (instead of using it's MemoryUse, we use
974 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +0000975 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000976}
977
Daniel Berlin07daac82017-04-02 13:23:44 +0000978// See if we can extract the value of a loaded pointer from a load, a store, or
979// a memory instruction.
980const Expression *
981NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
982 LoadInst *LI, Instruction *DepInst,
983 MemoryAccess *DefiningAccess) {
984 assert((!LI || LI->isSimple()) && "Not a simple load");
985 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
986 // Can't forward from non-atomic to atomic without violating memory model.
987 // Also don't need to coerce if they are the same type, we will just
988 // propogate..
989 if (LI->isAtomic() > DepSI->isAtomic() ||
990 LoadType == DepSI->getValueOperand()->getType())
991 return nullptr;
992 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
993 if (Offset >= 0) {
994 if (auto *C = dyn_cast<Constant>(
995 lookupOperandLeader(DepSI->getValueOperand()))) {
996 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
997 << *C << "\n");
998 return createConstantExpression(
999 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1000 }
1001 }
1002
1003 } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1004 // Can't forward from non-atomic to atomic without violating memory model.
1005 if (LI->isAtomic() > DepLI->isAtomic())
1006 return nullptr;
1007 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1008 if (Offset >= 0) {
1009 // We can coerce a constant load into a load
1010 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1011 if (auto *PossibleConstant =
1012 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1013 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1014 << *PossibleConstant << "\n");
1015 return createConstantExpression(PossibleConstant);
1016 }
1017 }
1018
1019 } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1020 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1021 if (Offset >= 0) {
1022 if (auto *PossibleConstant =
1023 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1024 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1025 << " to constant " << *PossibleConstant << "\n");
1026 return createConstantExpression(PossibleConstant);
1027 }
1028 }
1029 }
1030
1031 // All of the below are only true if the loaded pointer is produced
1032 // by the dependent instruction.
1033 if (LoadPtr != lookupOperandLeader(DepInst) &&
1034 !AA->isMustAlias(LoadPtr, DepInst))
1035 return nullptr;
1036 // If this load really doesn't depend on anything, then we must be loading an
1037 // undef value. This can happen when loading for a fresh allocation with no
1038 // intervening stores, for example. Note that this is only true in the case
1039 // that the result of the allocation is pointer equal to the load ptr.
1040 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1041 return createConstantExpression(UndefValue::get(LoadType));
1042 }
1043 // If this load occurs either right after a lifetime begin,
1044 // then the loaded value is undefined.
1045 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1046 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1047 return createConstantExpression(UndefValue::get(LoadType));
1048 }
1049 // If this load follows a calloc (which zero initializes memory),
1050 // then the loaded value is zero
1051 else if (isCallocLikeFn(DepInst, TLI)) {
1052 return createConstantExpression(Constant::getNullValue(LoadType));
1053 }
1054
1055 return nullptr;
1056}
1057
Daniel Berlin97718e62017-01-31 22:32:03 +00001058const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001059 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001060
1061 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001062 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001063 if (!LI->isSimple())
1064 return nullptr;
1065
Daniel Berlin203f47b2017-01-31 22:31:53 +00001066 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001067 // Load of undef is undef.
1068 if (isa<UndefValue>(LoadAddressLeader))
1069 return createConstantExpression(UndefValue::get(LI->getType()));
1070
1071 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
1072
1073 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1074 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1075 Instruction *DefiningInst = MD->getMemoryInst();
1076 // If the defining instruction is not reachable, replace with undef.
1077 if (!ReachableBlocks.count(DefiningInst->getParent()))
1078 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001079 // This will handle stores and memory insts. We only do if it the
1080 // defining access has a different type, or it is a pointer produced by
1081 // certain memory operations that cause the memory to have a fixed value
1082 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001083 if (const auto *CoercionResult =
1084 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1085 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001086 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001087 }
1088 }
1089
Daniel Berlin1316a942017-04-06 18:52:50 +00001090 const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1091 LI, DefiningAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001092 return E;
1093}
1094
Daniel Berlinf7d95802017-02-18 23:06:50 +00001095const Expression *
1096NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
1097 auto *PI = PredInfo->getPredicateInfoFor(I);
1098 if (!PI)
1099 return nullptr;
1100
1101 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001102
1103 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1104 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001105 return nullptr;
1106
Daniel Berlinfccbda92017-02-22 22:20:58 +00001107 auto *CopyOf = I->getOperand(0);
1108 auto *Cond = PWC->Condition;
1109
Daniel Berlinf7d95802017-02-18 23:06:50 +00001110 // If this a copy of the condition, it must be either true or false depending
1111 // on the predicate info type and edge
1112 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001113 // We should not need to add predicate users because the predicate info is
1114 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001115 if (isa<PredicateAssume>(PI))
1116 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1117 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1118 if (PBranch->TrueEdge)
1119 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1120 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1121 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001122 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1123 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001124 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001125
Daniel Berlinf7d95802017-02-18 23:06:50 +00001126 // Not a copy of the condition, so see what the predicates tell us about this
1127 // value. First, though, we check to make sure the value is actually a copy
1128 // of one of the condition operands. It's possible, in certain cases, for it
1129 // to be a copy of a predicateinfo copy. In particular, if two branch
1130 // operations use the same condition, and one branch dominates the other, we
1131 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001132 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001133 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001134
1135 // Everything below relies on the condition being a comparison.
1136 auto *Cmp = dyn_cast<CmpInst>(Cond);
1137 if (!Cmp)
1138 return nullptr;
1139
1140 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001141 DEBUG(dbgs() << "Copy is not of any condition operands!");
1142 return nullptr;
1143 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001144 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1145 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001146 bool SwappedOps = false;
1147 // Sort the ops
1148 if (shouldSwapOperands(FirstOp, SecondOp)) {
1149 std::swap(FirstOp, SecondOp);
1150 SwappedOps = true;
1151 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001152 CmpInst::Predicate Predicate =
1153 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1154
1155 if (isa<PredicateAssume>(PI)) {
1156 // If the comparison is true when the operands are equal, then we know the
1157 // operands are equal, because assumes must always be true.
1158 if (CmpInst::isTrueWhenEqual(Predicate)) {
1159 addPredicateUsers(PI, I);
1160 return createVariableOrConstant(FirstOp);
1161 }
1162 }
1163 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1164 // If we are *not* a copy of the comparison, we may equal to the other
1165 // operand when the predicate implies something about equality of
1166 // operations. In particular, if the comparison is true/false when the
1167 // operands are equal, and we are on the right edge, we know this operation
1168 // is equal to something.
1169 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1170 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1171 addPredicateUsers(PI, I);
1172 return createVariableOrConstant(FirstOp);
1173 }
1174 // Handle the special case of floating point.
1175 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1176 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1177 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1178 addPredicateUsers(PI, I);
1179 return createConstantExpression(cast<Constant>(FirstOp));
1180 }
1181 }
1182 return nullptr;
1183}
1184
Davide Italiano7e274e02016-12-22 16:03:48 +00001185// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001186const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001187 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001188 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1189 // Instrinsics with the returned attribute are copies of arguments.
1190 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1191 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1192 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1193 return Result;
1194 return createVariableOrConstant(ReturnedValue);
1195 }
1196 }
1197 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001198 return createCallExpression(CI, TOPClass->RepMemoryAccess);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001199 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001200 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001201 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001202 }
1203 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001204}
1205
Daniel Berlin1316a942017-04-06 18:52:50 +00001206// Retrieve the memory class for a given MemoryAccess.
1207CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1208
1209 auto *Result = MemoryAccessToClass.lookup(MA);
1210 assert(Result && "Should have found memory class");
1211 return Result;
1212}
1213
1214// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001215// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001216bool NewGVN::setMemoryClass(const MemoryAccess *From,
1217 CongruenceClass *NewClass) {
1218 assert(NewClass &&
1219 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001220 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001221 DEBUG(dbgs() << " equivalent to congruence class ");
1222 DEBUG(dbgs() << NewClass->ID << " with current MemoryAccess leader ");
1223 DEBUG(dbgs() << *NewClass->RepMemoryAccess);
Daniel Berlin9f376b72017-01-29 10:26:03 +00001224 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001225
1226 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001227 bool Changed = false;
1228 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001229 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001230 auto *OldClass = LookupResult->second;
1231 if (OldClass != NewClass) {
1232 // If this is a phi, we have to handle memory member updates.
1233 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
1234 OldClass->MemoryMembers.erase(MP);
1235 NewClass->MemoryMembers.insert(MP);
1236 // This may have killed the class if it had no non-memory members
1237 if (OldClass->RepMemoryAccess == From) {
1238 if (OldClass->MemoryMembers.empty()) {
1239 OldClass->RepMemoryAccess = nullptr;
1240 } else {
1241 // TODO: Verify memory phi leader cycling is not possible
1242 OldClass->RepMemoryAccess = getNextMemoryLeader(OldClass);
1243 DEBUG(dbgs() << "Memory class leader change for class "
1244 << OldClass->ID << " to " << *OldClass->RepMemoryAccess
1245 << " due to removal of a memory member " << *From
1246 << "\n");
1247 markMemoryLeaderChangeTouched(OldClass);
1248 }
1249 }
1250 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001251 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001252 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001253 Changed = true;
1254 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001255 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001256
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001257 return Changed;
1258}
Daniel Berlin0e900112017-03-24 06:33:48 +00001259
Davide Italiano7e274e02016-12-22 16:03:48 +00001260// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001261const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001262 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001263 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1264
1265 // See if all arguaments are the same.
1266 // We track if any were undef because they need special handling.
1267 bool HasUndef = false;
1268 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1269 if (Arg == I)
1270 return false;
1271 if (isa<UndefValue>(Arg)) {
1272 HasUndef = true;
1273 return false;
1274 }
1275 return true;
1276 });
1277 // If we are left with no operands, it's undef
1278 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001279 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1280 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001281 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001282 return createConstantExpression(UndefValue::get(I->getType()));
1283 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001284 Value *AllSameValue = *(Filtered.begin());
1285 ++Filtered.begin();
1286 // Can't use std::equal here, sadly, because filter.begin moves.
1287 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
1288 return V == AllSameValue;
1289 })) {
1290 // In LLVM's non-standard representation of phi nodes, it's possible to have
1291 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1292 // on the original phi node), especially in weird CFG's where some arguments
1293 // are unreachable, or uninitialized along certain paths. This can cause
1294 // infinite loops during evaluation. We work around this by not trying to
1295 // really evaluate them independently, but instead using a variable
1296 // expression to say if one is equivalent to the other.
1297 // We also special case undef, so that if we have an undef, we can't use the
1298 // common value unless it dominates the phi block.
1299 if (HasUndef) {
1300 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001301 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001302 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001303 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001304 }
1305
Davide Italiano7e274e02016-12-22 16:03:48 +00001306 NumGVNPhisAllSame++;
1307 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1308 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001309 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001310 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001311 }
1312 return E;
1313}
1314
Daniel Berlin97718e62017-01-31 22:32:03 +00001315const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001316 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1317 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1318 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1319 unsigned Opcode = 0;
1320 // EI might be an extract from one of our recognised intrinsics. If it
1321 // is we'll synthesize a semantically equivalent expression instead on
1322 // an extract value expression.
1323 switch (II->getIntrinsicID()) {
1324 case Intrinsic::sadd_with_overflow:
1325 case Intrinsic::uadd_with_overflow:
1326 Opcode = Instruction::Add;
1327 break;
1328 case Intrinsic::ssub_with_overflow:
1329 case Intrinsic::usub_with_overflow:
1330 Opcode = Instruction::Sub;
1331 break;
1332 case Intrinsic::smul_with_overflow:
1333 case Intrinsic::umul_with_overflow:
1334 Opcode = Instruction::Mul;
1335 break;
1336 default:
1337 break;
1338 }
1339
1340 if (Opcode != 0) {
1341 // Intrinsic recognized. Grab its args to finish building the
1342 // expression.
1343 assert(II->getNumArgOperands() == 2 &&
1344 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001345 return createBinaryExpression(
1346 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001347 }
1348 }
1349 }
1350
Daniel Berlin97718e62017-01-31 22:32:03 +00001351 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001352}
Daniel Berlin97718e62017-01-31 22:32:03 +00001353const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001354 auto *CI = dyn_cast<CmpInst>(I);
1355 // See if our operands are equal to those of a previous predicate, and if so,
1356 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001357 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1358 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001359 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001360 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001361 std::swap(Op0, Op1);
1362 OurPredicate = CI->getSwappedPredicate();
1363 }
1364
1365 // Avoid processing the same info twice
1366 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001367 // See if we know something about the comparison itself, like it is the target
1368 // of an assume.
1369 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1370 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1371 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1372
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001373 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001374 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001375 if (CI->isTrueWhenEqual())
1376 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1377 else if (CI->isFalseWhenEqual())
1378 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1379 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001380
1381 // NOTE: Because we are comparing both operands here and below, and using
1382 // previous comparisons, we rely on fact that predicateinfo knows to mark
1383 // comparisons that use renamed operands as users of the earlier comparisons.
1384 // It is *not* enough to just mark predicateinfo renamed operands as users of
1385 // the earlier comparisons, because the *other* operand may have changed in a
1386 // previous iteration.
1387 // Example:
1388 // icmp slt %a, %b
1389 // %b.0 = ssa.copy(%b)
1390 // false branch:
1391 // icmp slt %c, %b.0
1392
1393 // %c and %a may start out equal, and thus, the code below will say the second
1394 // %icmp is false. c may become equal to something else, and in that case the
1395 // %second icmp *must* be reexamined, but would not if only the renamed
1396 // %operands are considered users of the icmp.
1397
1398 // *Currently* we only check one level of comparisons back, and only mark one
1399 // level back as touched when changes appen . If you modify this code to look
1400 // back farther through comparisons, you *must* mark the appropriate
1401 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1402 // we know something just from the operands themselves
1403
1404 // See if our operands have predicate info, so that we may be able to derive
1405 // something from a previous comparison.
1406 for (const auto &Op : CI->operands()) {
1407 auto *PI = PredInfo->getPredicateInfoFor(Op);
1408 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1409 if (PI == LastPredInfo)
1410 continue;
1411 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001412
Daniel Berlinf7d95802017-02-18 23:06:50 +00001413 // TODO: Along the false edge, we may know more things too, like icmp of
1414 // same operands is false.
1415 // TODO: We only handle actual comparison conditions below, not and/or.
1416 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1417 if (!BranchCond)
1418 continue;
1419 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1420 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1421 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001422 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001423 std::swap(BranchOp0, BranchOp1);
1424 BranchPredicate = BranchCond->getSwappedPredicate();
1425 }
1426 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1427 if (PBranch->TrueEdge) {
1428 // If we know the previous predicate is true and we are in the true
1429 // edge then we may be implied true or false.
1430 if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate,
1431 BranchPredicate)) {
1432 addPredicateUsers(PI, I);
1433 return createConstantExpression(
1434 ConstantInt::getTrue(CI->getType()));
1435 }
1436
1437 if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate,
1438 BranchPredicate)) {
1439 addPredicateUsers(PI, I);
1440 return createConstantExpression(
1441 ConstantInt::getFalse(CI->getType()));
1442 }
1443
1444 } else {
1445 // Just handle the ne and eq cases, where if we have the same
1446 // operands, we may know something.
1447 if (BranchPredicate == OurPredicate) {
1448 addPredicateUsers(PI, I);
1449 // Same predicate, same ops,we know it was false, so this is false.
1450 return createConstantExpression(
1451 ConstantInt::getFalse(CI->getType()));
1452 } else if (BranchPredicate ==
1453 CmpInst::getInversePredicate(OurPredicate)) {
1454 addPredicateUsers(PI, I);
1455 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001456 return createConstantExpression(
1457 ConstantInt::getTrue(CI->getType()));
1458 }
1459 }
1460 }
1461 }
1462 }
1463 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001464 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001465}
Davide Italiano7e274e02016-12-22 16:03:48 +00001466
1467// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001468const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001469 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001470 if (auto *C = dyn_cast<Constant>(V))
1471 E = createConstantExpression(C);
1472 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1473 E = createVariableExpression(V);
1474 } else {
1475 // TODO: memory intrinsics.
1476 // TODO: Some day, we should do the forward propagation and reassociation
1477 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001478 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001479 switch (I->getOpcode()) {
1480 case Instruction::ExtractValue:
1481 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001482 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001483 break;
1484 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001485 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001486 break;
1487 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001488 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001489 break;
1490 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001491 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001492 break;
1493 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001494 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001495 break;
1496 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001497 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001498 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001499 case Instruction::ICmp:
1500 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001501 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001502 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001503 case Instruction::Add:
1504 case Instruction::FAdd:
1505 case Instruction::Sub:
1506 case Instruction::FSub:
1507 case Instruction::Mul:
1508 case Instruction::FMul:
1509 case Instruction::UDiv:
1510 case Instruction::SDiv:
1511 case Instruction::FDiv:
1512 case Instruction::URem:
1513 case Instruction::SRem:
1514 case Instruction::FRem:
1515 case Instruction::Shl:
1516 case Instruction::LShr:
1517 case Instruction::AShr:
1518 case Instruction::And:
1519 case Instruction::Or:
1520 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001521 case Instruction::Trunc:
1522 case Instruction::ZExt:
1523 case Instruction::SExt:
1524 case Instruction::FPToUI:
1525 case Instruction::FPToSI:
1526 case Instruction::UIToFP:
1527 case Instruction::SIToFP:
1528 case Instruction::FPTrunc:
1529 case Instruction::FPExt:
1530 case Instruction::PtrToInt:
1531 case Instruction::IntToPtr:
1532 case Instruction::Select:
1533 case Instruction::ExtractElement:
1534 case Instruction::InsertElement:
1535 case Instruction::ShuffleVector:
1536 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001537 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001538 break;
1539 default:
1540 return nullptr;
1541 }
1542 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001543 return E;
1544}
1545
Davide Italiano7e274e02016-12-22 16:03:48 +00001546void NewGVN::markUsersTouched(Value *V) {
1547 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001548 for (auto *User : V->users()) {
1549 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001550 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001551 }
1552}
1553
Daniel Berlin1316a942017-04-06 18:52:50 +00001554void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) {
1555 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1556 MemoryToUsers[To].insert(U);
1557}
1558
1559void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001560 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00001561}
1562
1563void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1564 if (isa<MemoryUse>(MA))
1565 return;
1566 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00001567 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin1316a942017-04-06 18:52:50 +00001568 const auto Result = MemoryToUsers.find(MA);
1569 if (Result != MemoryToUsers.end()) {
1570 for (auto *User : Result->second)
Daniel Berlin21279bd2017-04-06 18:52:58 +00001571 TouchedInstructions.set(MemoryToDFSNum(User));
Daniel Berlin1316a942017-04-06 18:52:50 +00001572 MemoryToUsers.erase(Result);
Davide Italiano7e274e02016-12-22 16:03:48 +00001573 }
1574}
1575
Daniel Berlinf7d95802017-02-18 23:06:50 +00001576// Add I to the set of users of a given predicate.
1577void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1578 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1579 PredicateToUsers[PBranch->Condition].insert(I);
1580 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1581 PredicateToUsers[PAssume->Condition].insert(I);
1582}
1583
1584// Touch all the predicates that depend on this instruction.
1585void NewGVN::markPredicateUsersTouched(Instruction *I) {
1586 const auto Result = PredicateToUsers.find(I);
Daniel Berlin46b72e62017-03-19 00:07:32 +00001587 if (Result != PredicateToUsers.end()) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001588 for (auto *User : Result->second)
Daniel Berlin21279bd2017-04-06 18:52:58 +00001589 TouchedInstructions.set(InstrToDFSNum(User));
Daniel Berlin46b72e62017-03-19 00:07:32 +00001590 PredicateToUsers.erase(Result);
1591 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001592}
1593
Daniel Berlin1316a942017-04-06 18:52:50 +00001594// Mark users affected by a memory leader change.
1595void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
1596 for (auto M : CC->MemoryMembers)
1597 markMemoryDefTouched(M);
1598}
1599
Daniel Berlin32f8d562017-01-07 16:55:14 +00001600// Touch the instructions that need to be updated after a congruence class has a
1601// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00001602void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001603 for (auto M : CC->Members) {
1604 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00001605 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001606 LeaderChanges.insert(M);
1607 }
1608}
1609
Daniel Berlin1316a942017-04-06 18:52:50 +00001610// Give a range of things that have instruction DFS numbers, this will return
1611// the member of the range with the smallest dfs number.
1612template <class T, class Range>
1613T *NewGVN::getMinDFSOfRange(const Range &R) const {
1614 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
1615 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001616 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00001617 if (DFSNum < MinDFS.second)
1618 MinDFS = {X, DFSNum};
1619 }
1620 return MinDFS.first;
1621}
1622
1623// This function returns the MemoryAccess that should be the next leader of
1624// congruence class CC, under the assumption that the current leader is going to
1625// disappear.
1626const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
1627 // TODO: If this ends up to slow, we can maintain a next memory leader like we
1628 // do for regular leaders.
1629 // Make sure there will be a leader to find
1630 assert(CC->StoreCount > 0 ||
1631 !CC->MemoryMembers.empty() &&
1632 "Can't get next leader if there is none");
1633 if (CC->StoreCount > 0) {
1634 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->NextLeader.first))
1635 return MSSA->getMemoryAccess(NL);
1636 // Find the store with the minimum DFS number.
1637 auto *V = getMinDFSOfRange<Value>(make_filter_range(
1638 CC->Members, [&](const Value *V) { return isa<StoreInst>(V); }));
1639 return MSSA->getMemoryAccess(cast<StoreInst>(V));
1640 }
1641 assert(CC->StoreCount == 0);
1642
1643 // Given our assertion, hitting this part must mean
1644 // !OldClass->MemoryMembers.empty()
1645 if (CC->MemoryMembers.size() == 1)
1646 return *CC->MemoryMembers.begin();
1647 return getMinDFSOfRange<const MemoryPhi>(CC->MemoryMembers);
1648}
1649
1650// This function returns the next value leader of a congruence class, under the
1651// assumption that the current leader is going away. This should end up being
1652// the next most dominating member.
1653Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
1654 // We don't need to sort members if there is only 1, and we don't care about
1655 // sorting the TOP class because everything either gets out of it or is
1656 // unreachable.
1657
1658 if (CC->Members.size() == 1 || CC == TOPClass) {
1659 return *(CC->Members.begin());
1660 } else if (CC->NextLeader.first) {
1661 ++NumGVNAvoidedSortedLeaderChanges;
1662 return CC->NextLeader.first;
1663 } else {
1664 ++NumGVNSortedLeaderChanges;
1665 // NOTE: If this ends up to slow, we can maintain a dual structure for
1666 // member testing/insertion, or keep things mostly sorted, and sort only
1667 // here, or use SparseBitVector or ....
1668 return getMinDFSOfRange<Value>(CC->Members);
1669 }
1670}
1671
1672// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
1673// the memory members, etc for the move.
1674//
1675// The invariants of this function are:
1676//
1677// I must be moving to NewClass from OldClass The StoreCount of OldClass and
1678// NewClass is expected to have been updated for I already if it is is a store.
1679// The OldClass memory leader has not been updated yet if I was the leader.
1680void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
1681 MemoryAccess *InstMA,
1682 CongruenceClass *OldClass,
1683 CongruenceClass *NewClass) {
1684 // If the leader is I, and we had a represenative MemoryAccess, it should
1685 // be the MemoryAccess of OldClass.
1686 assert(!InstMA || !OldClass->RepMemoryAccess || OldClass->RepLeader != I ||
1687 OldClass->RepMemoryAccess == InstMA &&
1688 "Representative MemoryAccess mismatch");
1689 // First, see what happens to the new class
1690 if (!NewClass->RepMemoryAccess) {
1691 // Should be a new class, or a store becoming a leader of a new class.
1692 assert(NewClass->Members.size() == 1 ||
1693 (isa<StoreInst>(I) && NewClass->StoreCount == 1));
1694 NewClass->RepMemoryAccess = InstMA;
1695 // Mark it touched if we didn't just create a singleton
1696 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->ID
1697 << " due to new memory instruction becoming leader\n");
1698 markMemoryLeaderChangeTouched(NewClass);
1699 }
1700 setMemoryClass(InstMA, NewClass);
1701 // Now, fixup the old class if necessary
1702 if (OldClass->RepMemoryAccess == InstMA) {
1703 if (OldClass->StoreCount != 0 || !OldClass->MemoryMembers.empty()) {
1704 OldClass->RepMemoryAccess = getNextMemoryLeader(OldClass);
1705 DEBUG(dbgs() << "Memory class leader change for class " << OldClass->ID
1706 << " to " << *OldClass->RepMemoryAccess
1707 << " due to removal of old leader " << *InstMA << "\n");
1708 markMemoryLeaderChangeTouched(OldClass);
1709 } else
1710 OldClass->RepMemoryAccess = nullptr;
1711 }
1712}
1713
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001714// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00001715// Update OldClass and NewClass for the move (including changing leaders, etc).
1716void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001717 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001718 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001719 if (I == OldClass->NextLeader.first)
1720 OldClass->NextLeader = {nullptr, ~0U};
1721
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001722 // It's possible, though unlikely, for us to discover equivalences such
1723 // that the current leader does not dominate the old one.
1724 // This statistic tracks how often this happens.
1725 // We assert on phi nodes when this happens, currently, for debugging, because
1726 // we want to make sure we name phi node cycles properly.
1727 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001728 I != NewClass->RepLeader) {
1729 auto *IBB = I->getParent();
1730 auto *NCBB = cast<Instruction>(NewClass->RepLeader)->getParent();
Daniel Berlin21279bd2017-04-06 18:52:58 +00001731 bool Dominated =
1732 IBB == NCBB && InstrToDFSNum(I) < InstrToDFSNum(NewClass->RepLeader);
Daniel Berlinffc30782017-03-24 06:33:51 +00001733 Dominated = Dominated || DT->properlyDominates(IBB, NCBB);
1734 if (Dominated) {
1735 ++NumGVNNotMostDominatingLeader;
1736 assert(
1737 !isa<PHINode>(I) &&
1738 "New class for instruction should not be dominated by instruction");
1739 }
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001740 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001741
1742 if (NewClass->RepLeader != I) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001743 auto DFSNum = InstrToDFSNum(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001744 if (DFSNum < NewClass->NextLeader.second)
1745 NewClass->NextLeader = {I, DFSNum};
1746 }
1747
1748 OldClass->Members.erase(I);
1749 NewClass->Members.insert(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00001750 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001751 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001752 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001753 assert(OldClass->StoreCount >= 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001754 // Okay, so when do we want to make a store a leader of a class? If we have
1755 // a store defined by an earlier load, we want the earlier load to lead the
1756 // class. If we have a store defined by something else, we want the store
1757 // to lead the class so everything else gets the "something else" as a
1758 // value.
1759 // If we have a store as the single member of the class, we want the store
1760 // as the leader.
1761 if (NewClass->StoreCount == 0 && !NewClass->RepStoredValue) {
1762 // If it's a store expression we are using, it means we are not equivalent
1763 // to something earlier.
1764 if (isa<StoreExpression>(E)) {
1765 assert(lookupOperandLeader(SI->getValueOperand()) !=
1766 NewClass->RepLeader);
1767 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
1768 markValueLeaderChangeTouched(NewClass);
1769 // Shift the new class leader to be the store
1770 DEBUG(dbgs() << "Changing leader of congruence class " << NewClass->ID
1771 << " from " << *NewClass->RepLeader << " to " << *SI
1772 << " because store joined class\n");
1773 // If we changed the leader, we have to mark it changed because we don't
1774 // know what it will do to symbolic evlauation.
1775 NewClass->RepLeader = SI;
1776 }
1777 // We rely on the code below handling the MemoryAccess change.
1778 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001779 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001780 assert(NewClass->StoreCount > 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001781 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001782 // True if there is no memory instructions left in a class that had memory
1783 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001784
Daniel Berlin1316a942017-04-06 18:52:50 +00001785 // If it's not a memory use, set the MemoryAccess equivalence
1786 auto *InstMA = dyn_cast_or_null<MemoryDef>(MSSA->getMemoryAccess(I));
1787 bool InstWasMemoryLeader = InstMA && OldClass->RepMemoryAccess == InstMA;
1788 if (InstMA)
1789 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001790 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001791 // See if we destroyed the class or need to swap leaders.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001792 if (OldClass->Members.empty() && OldClass != TOPClass) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001793 if (OldClass->DefiningExpr) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001794 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1795 << " from table\n");
1796 ExpressionToClass.erase(OldClass->DefiningExpr);
1797 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001798 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001799 // When the leader changes, the value numbering of
1800 // everything may change due to symbolization changes, so we need to
1801 // reprocess.
Daniel Berlin1316a942017-04-06 18:52:50 +00001802 DEBUG(dbgs() << "Value class leader change for class " << OldClass->ID
1803 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001804 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001805 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00001806 // Note that this is basically clean up for the expression removal that
1807 // happens below. If we remove stores from a class, we may leave it as a
1808 // class of equivalent memory phis.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001809 if (OldClass->StoreCount == 0) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001810 if (OldClass->RepStoredValue)
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001811 OldClass->RepStoredValue = nullptr;
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001812 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001813 // If we destroy the old access leader and it's a store, we have to
1814 // effectively destroy the congruence class. When it comes to scalars,
1815 // anything with the same value is as good as any other. That means that
1816 // one leader is as good as another, and as long as you have some leader for
1817 // the value, you are good.. When it comes to *memory states*, only one
1818 // particular thing really represents the definition of a given memory
1819 // state. Once it goes away, we need to re-evaluate which pieces of memory
1820 // are really still equivalent. The best way to do this is to re-value
1821 // number things. The only way to really make that happen is to destroy the
1822 // rest of the class. In order to effectively destroy the class, we reset
1823 // ExpressionToClass for each by using the ValueToExpression mapping. The
1824 // members later get marked as touched due to the leader change. We will
1825 // create new congruence classes, and the pieces that are still equivalent
1826 // will end back together in a new class. If this becomes too expensive, it
1827 // is possible to use a versioning scheme for the congruence classes to
1828 // avoid the expressions finding this old class. Note that the situation is
1829 // different for memory phis, becuase they are evaluated anew each time, and
1830 // they become equal not by hashing, but by seeing if all operands are the
1831 // same (or only one is reachable).
1832 if (OldClass->StoreCount > 0 && InstWasMemoryLeader) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001833 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
Daniel Berlin1316a942017-04-06 18:52:50 +00001834 << " because MemoryAccess leader changed");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001835 for (auto Member : OldClass->Members)
1836 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1837 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001838 OldClass->RepLeader = getNextValueLeader(OldClass);
1839 OldClass->NextLeader = {nullptr, ~0U};
1840 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001841 }
1842}
1843
Davide Italiano7e274e02016-12-22 16:03:48 +00001844// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001845void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1846 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001847 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001848 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001849
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001850 CongruenceClass *IClass = ValueToClass[I];
1851 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001852 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00001853 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001854
1855 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001856 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001857 EClass = ValueToClass[VE->getVariableValue()];
1858 } else {
1859 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1860
1861 // If it's not in the value table, create a new congruence class.
1862 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001863 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001864 auto place = lookupResult.first;
1865 place->second = NewClass;
1866
1867 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001868 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001869 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001870 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1871 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001872 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001873 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001874 // The RepMemoryAccess field will be filled in properly by the
1875 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001876 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001877 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001878 }
1879 assert(!isa<VariableExpression>(E) &&
1880 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001881
1882 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001883 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001884 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001885 << " and leader " << *(NewClass->RepLeader));
1886 if (NewClass->RepStoredValue)
1887 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1888 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001889 } else {
1890 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001891 if (isa<ConstantExpression>(E))
Daniel Berlin1316a942017-04-06 18:52:50 +00001892 assert(
1893 isa<Constant>(EClass->RepLeader) ||
1894 (EClass->RepStoredValue && isa<Constant>(EClass->RepStoredValue)) &&
1895 "Any class with a constant expression should have a "
1896 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001897
Davide Italiano7e274e02016-12-22 16:03:48 +00001898 assert(EClass && "Somehow don't have an eclass");
1899
Daniel Berlin1316a942017-04-06 18:52:50 +00001900 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001901 }
1902 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001903 bool ClassChanged = IClass != EClass;
1904 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001905 if (ClassChanged || LeaderChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001906 DEBUG(dbgs() << "New class " << EClass->ID << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00001907 << "\n");
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001908 if (ClassChanged)
Daniel Berlin1316a942017-04-06 18:52:50 +00001909 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001910 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001911 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001912 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001913 if (auto *CI = dyn_cast<CmpInst>(I))
1914 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00001915 }
1916}
1917
1918// Process the fact that Edge (from, to) is reachable, including marking
1919// any newly reachable blocks and instructions for processing.
1920void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1921 // Check if the Edge was reachable before.
1922 if (ReachableEdges.insert({From, To}).second) {
1923 // If this block wasn't reachable before, all instructions are touched.
1924 if (ReachableBlocks.insert(To).second) {
1925 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1926 const auto &InstRange = BlockInstRange.lookup(To);
1927 TouchedInstructions.set(InstRange.first, InstRange.second);
1928 } else {
1929 DEBUG(dbgs() << "Block " << getBlockName(To)
1930 << " was reachable, but new edge {" << getBlockName(From)
1931 << "," << getBlockName(To) << "} to it found\n");
1932
1933 // We've made an edge reachable to an existing block, which may
1934 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1935 // they are the only thing that depend on new edges. Anything using their
1936 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001937 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00001938 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001939
Davide Italiano7e274e02016-12-22 16:03:48 +00001940 auto BI = To->begin();
1941 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001942 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001943 ++BI;
1944 }
1945 }
1946 }
1947}
1948
1949// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1950// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001951Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001952 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001953 if (isa<Constant>(Result))
1954 return Result;
1955 return nullptr;
1956}
1957
1958// Process the outgoing edges of a block for reachability.
1959void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1960 // Evaluate reachability of terminator instruction.
1961 BranchInst *BR;
1962 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1963 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001964 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001965 if (!CondEvaluated) {
1966 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001967 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001968 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1969 CondEvaluated = CE->getConstantValue();
1970 }
1971 } else if (isa<ConstantInt>(Cond)) {
1972 CondEvaluated = Cond;
1973 }
1974 }
1975 ConstantInt *CI;
1976 BasicBlock *TrueSucc = BR->getSuccessor(0);
1977 BasicBlock *FalseSucc = BR->getSuccessor(1);
1978 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1979 if (CI->isOne()) {
1980 DEBUG(dbgs() << "Condition for Terminator " << *TI
1981 << " evaluated to true\n");
1982 updateReachableEdge(B, TrueSucc);
1983 } else if (CI->isZero()) {
1984 DEBUG(dbgs() << "Condition for Terminator " << *TI
1985 << " evaluated to false\n");
1986 updateReachableEdge(B, FalseSucc);
1987 }
1988 } else {
1989 updateReachableEdge(B, TrueSucc);
1990 updateReachableEdge(B, FalseSucc);
1991 }
1992 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1993 // For switches, propagate the case values into the case
1994 // destinations.
1995
1996 // Remember how many outgoing edges there are to every successor.
1997 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1998
Davide Italiano7e274e02016-12-22 16:03:48 +00001999 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002000 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002001 // See if we were able to turn this switch statement into a constant.
2002 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002003 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002004 // We should be able to get case value for this.
2005 auto CaseVal = SI->findCaseValue(CondVal);
2006 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
2007 // We proved the value is outside of the range of the case.
2008 // We can't do anything other than mark the default dest as reachable,
2009 // and go home.
2010 updateReachableEdge(B, SI->getDefaultDest());
2011 return;
2012 }
2013 // Now get where it goes and mark it reachable.
2014 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
2015 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002016 } else {
2017 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2018 BasicBlock *TargetBlock = SI->getSuccessor(i);
2019 ++SwitchEdges[TargetBlock];
2020 updateReachableEdge(B, TargetBlock);
2021 }
2022 }
2023 } else {
2024 // Otherwise this is either unconditional, or a type we have no
2025 // idea about. Just mark successors as reachable.
2026 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2027 BasicBlock *TargetBlock = TI->getSuccessor(i);
2028 updateReachableEdge(B, TargetBlock);
2029 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002030
2031 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002032 // equivalent only to itself.
2033 //
2034 auto *MA = MSSA->getMemoryAccess(TI);
2035 if (MA && !isa<MemoryUse>(MA)) {
2036 auto *CC = ensureLeaderOfMemoryClass(MA);
2037 if (setMemoryClass(MA, CC))
2038 markMemoryUsersTouched(MA);
2039 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002040 }
2041}
2042
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002043// The algorithm initially places the values of the routine in the TOP
2044// congruence class. The leader of TOP is the undetermined value `undef`.
2045// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002046void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002047 NextCongruenceNum = 0;
2048
2049 // Note that even though we use the live on entry def as a representative
2050 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2051 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2052 // should be checking whether the MemoryAccess is top if we want to know if it
2053 // is equivalent to everything. Otherwise, what this really signifies is that
2054 // the access "it reaches all the way back to the beginning of the function"
2055
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002056 // Initialize all other instructions to be in TOP class.
Davide Italiano7e274e02016-12-22 16:03:48 +00002057 CongruenceClass::MemberSet InitialValues;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002058 TOPClass = createCongruenceClass(nullptr, nullptr);
2059 TOPClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin1316a942017-04-06 18:52:50 +00002060 // The live on entry def gets put into it's own class
2061 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2062 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002063
Daniel Berlin1316a942017-04-06 18:52:50 +00002064 for (auto &B : F) {
2065 // All MemoryAccesses are equivalent to live on entry to start. They must
2066 // be initialized to something so that initial changes are noticed. For
2067 // the maximal answer, we initialize them all to be the same as
2068 // liveOnEntry.
2069 auto *MemoryBlockDefs = MSSA->getBlockDefs(&B);
2070 if (MemoryBlockDefs)
2071 for (const auto &Def : *MemoryBlockDefs) {
2072 MemoryAccessToClass[&Def] = TOPClass;
2073 auto *MD = dyn_cast<MemoryDef>(&Def);
2074 // Insert the memory phis into the member list.
2075 if (!MD) {
2076 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
2077 TOPClass->MemoryMembers.insert(MP);
2078 MemoryPhiState.insert({MP, MPS_TOP});
2079 }
2080
2081 if (MD && isa<StoreInst>(MD->getMemoryInst()))
2082 ++TOPClass->StoreCount;
2083 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002084 for (auto &I : B) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00002085 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002086 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002087 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2088 continue;
2089 InitialValues.insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002090 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002091 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002092 }
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002093 TOPClass->Members.swap(InitialValues);
Davide Italiano7e274e02016-12-22 16:03:48 +00002094
2095 // Initialize arguments to be in their own unique congruence classes
2096 for (auto &FA : F.args())
2097 createSingletonCongruenceClass(&FA);
2098}
2099
2100void NewGVN::cleanupTables() {
2101 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
2102 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
2103 << CongruenceClasses[i]->Members.size() << " members\n");
2104 // Make sure we delete the congruence class (probably worth switching to
2105 // a unique_ptr at some point.
2106 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002107 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002108 }
2109
2110 ValueToClass.clear();
2111 ArgRecycler.clear(ExpressionAllocator);
2112 ExpressionAllocator.Reset();
2113 CongruenceClasses.clear();
2114 ExpressionToClass.clear();
2115 ValueToExpression.clear();
2116 ReachableBlocks.clear();
2117 ReachableEdges.clear();
2118#ifndef NDEBUG
2119 ProcessedCount.clear();
2120#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002121 InstrDFS.clear();
2122 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002123 DFSToInstr.clear();
2124 BlockInstRange.clear();
2125 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002126 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002127 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002128 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002129}
2130
2131std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2132 unsigned Start) {
2133 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002134 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
2135 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002136 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002137 }
2138
Davide Italiano7e274e02016-12-22 16:03:48 +00002139 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002140 // There's no need to call isInstructionTriviallyDead more than once on
2141 // an instruction. Therefore, once we know that an instruction is dead
2142 // we change its DFS number so that it doesn't get value numbered.
2143 if (isInstructionTriviallyDead(&I, TLI)) {
2144 InstrDFS[&I] = 0;
2145 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2146 markInstructionForDeletion(&I);
2147 continue;
2148 }
2149
Davide Italiano7e274e02016-12-22 16:03:48 +00002150 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002151 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002152 }
2153
2154 // All of the range functions taken half-open ranges (open on the end side).
2155 // So we do not subtract one from count, because at this point it is one
2156 // greater than the last instruction.
2157 return std::make_pair(Start, End);
2158}
2159
2160void NewGVN::updateProcessedCount(Value *V) {
2161#ifndef NDEBUG
2162 if (ProcessedCount.count(V) == 0) {
2163 ProcessedCount.insert({V, 1});
2164 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002165 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002166 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002167 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002168 }
2169#endif
2170}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002171// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2172void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2173 // If all the arguments are the same, the MemoryPhi has the same value as the
2174 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00002175 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00002176 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002177 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002178 return lookupMemoryLeader(cast<MemoryAccess>(U)) != MP &&
Daniel Berlinc4796862017-01-27 02:37:11 +00002179 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002180 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002181 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002182 // If all that is left is nothing, our memoryphi is undef. We keep it as
2183 // InitialClass. Note: The only case this should happen is if we have at
2184 // least one self-argument.
2185 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002186 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002187 markMemoryUsersTouched(MP);
2188 return;
2189 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002190
2191 // Transform the remaining operands into operand leaders.
2192 // FIXME: mapped_iterator should have a range version.
2193 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002194 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002195 };
2196 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2197 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2198
2199 // and now check if all the elements are equal.
2200 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002201 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002202 ++MappedBegin;
2203 bool AllEqual = std::all_of(
2204 MappedBegin, MappedEnd,
2205 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2206
2207 if (AllEqual)
2208 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2209 else
2210 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002211 // If it's equal to something, it's in that class. Otherwise, it has to be in
2212 // a class where it is the leader (other things may be equivalent to it, but
2213 // it needs to start off in its own class, which means it must have been the
2214 // leader, and it can't have stopped being the leader because it was never
2215 // removed).
2216 CongruenceClass *CC =
2217 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2218 auto OldState = MemoryPhiState.lookup(MP);
2219 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2220 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2221 MemoryPhiState[MP] = NewState;
2222 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002223 markMemoryUsersTouched(MP);
2224}
2225
2226// Value number a single instruction, symbolically evaluating, performing
2227// congruence finding, and updating mappings.
2228void NewGVN::valueNumberInstruction(Instruction *I) {
2229 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002230 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002231 const Expression *Symbolized = nullptr;
2232 if (DebugCounter::shouldExecute(VNCounter)) {
2233 Symbolized = performSymbolicEvaluation(I);
2234 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002235 // Mark the instruction as unused so we don't value number it again.
2236 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002237 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002238 // If we couldn't come up with a symbolic expression, use the unknown
2239 // expression
Daniel Berlin1316a942017-04-06 18:52:50 +00002240 if (Symbolized == nullptr) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002241 Symbolized = createUnknownExpression(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00002242 }
2243
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002244 performCongruenceFinding(I, Symbolized);
2245 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002246 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002247 // don't currently understand. We don't place non-value producing
2248 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002249 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002250 auto *Symbolized = createUnknownExpression(I);
2251 performCongruenceFinding(I, Symbolized);
2252 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002253 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2254 }
2255}
Davide Italiano7e274e02016-12-22 16:03:48 +00002256
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002257// Check if there is a path, using single or equal argument phi nodes, from
2258// First to Second.
2259bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
2260 const MemoryAccess *Second) const {
2261 if (First == Second)
2262 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002263 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002264 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002265
Daniel Berlin871ecd92017-04-01 09:44:24 +00002266 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002267 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002268 if (ChainDef == Second)
2269 return true;
2270 if (MSSA->isLiveOnEntryDef(ChainDef))
2271 return false;
2272 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002273 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002274 auto *MP = cast<MemoryPhi>(EndDef);
2275 auto ReachableOperandPred = [&](const Use &U) {
2276 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2277 };
2278 auto FilteredPhiArgs =
2279 make_filter_range(MP->operands(), ReachableOperandPred);
2280 SmallVector<const Value *, 32> OperandList;
2281 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2282 std::back_inserter(OperandList));
2283 bool Okay = OperandList.size() == 1;
2284 if (!Okay)
2285 Okay =
2286 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2287 if (Okay)
2288 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
2289 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002290}
2291
Daniel Berlin589cecc2017-01-02 18:00:46 +00002292// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002293// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002294// subject to very rare false negatives. It is only useful for
2295// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002296void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002297#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002298 // Verify that the memory table equivalence and memory member set match
2299 for (const auto *CC : CongruenceClasses) {
2300 if (CC == TOPClass || CC->isDead())
2301 continue;
2302 if (CC->StoreCount != 0) {
2303 assert(CC->RepStoredValue ||
2304 !isa<StoreInst>(CC->RepLeader) && "Any class with a store as a "
2305 "leader should have a "
2306 "representative stored value\n");
2307 assert(CC->RepMemoryAccess && "Any congruence class with a store should "
2308 "have a representative access\n");
2309 }
2310
2311 if (CC->RepMemoryAccess)
2312 assert(MemoryAccessToClass.lookup(CC->RepMemoryAccess) == CC &&
2313 "Representative MemoryAccess does not appear to be reverse "
2314 "mapped properly");
2315 for (auto M : CC->MemoryMembers)
2316 assert(MemoryAccessToClass.lookup(M) == CC &&
2317 "Memory member does not appear to be reverse mapped properly");
2318 }
2319
2320 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002321 // congruence class.
2322
2323 // Filter out the unreachable and trivially dead entries, because they may
2324 // never have been updated if the instructions were not processed.
2325 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002326 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002327 bool Result = ReachableBlocks.count(Pair.first->getBlock());
2328 if (!Result)
2329 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002330 if (MSSA->isLiveOnEntryDef(Pair.first))
2331 return true;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002332 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2333 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Daniel Berlin21279bd2017-04-06 18:52:58 +00002334 if (MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin1316a942017-04-06 18:52:50 +00002335 return false;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002336 return true;
2337 };
2338
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002339 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002340 for (auto KV : Filtered) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002341 assert(KV.second != TOPClass &&
2342 "Memory not unreachable but ended up in TOP");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002343 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002344 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00002345 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00002346 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002347 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2348 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2349 "The instructions for these memory operations should have "
2350 "been in the same congruence class or reachable through"
2351 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002352 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002353 // We can only sanely verify that MemoryDefs in the operand list all have
2354 // the same class.
2355 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002356 return ReachableEdges.count(
2357 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002358 isa<MemoryDef>(U);
2359
2360 };
2361 // All arguments should in the same class, ignoring unreachable arguments
2362 auto FilteredPhiArgs =
2363 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2364 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2365 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2366 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2367 const MemoryDef *MD = cast<MemoryDef>(U);
2368 return ValueToClass.lookup(MD->getMemoryInst());
2369 });
2370 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2371 PhiOpClasses.begin()) &&
2372 "All MemoryPhi arguments should be in the same class");
2373 }
2374 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002375#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002376}
2377
Daniel Berlin06329a92017-03-18 15:41:40 +00002378// Verify that the sparse propagation we did actually found the maximal fixpoint
2379// We do this by storing the value to class mapping, touching all instructions,
2380// and redoing the iteration to see if anything changed.
2381void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002382#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002383 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002384 if (DebugCounter::isCounterSet(VNCounter))
2385 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2386
2387 // Note that we have to store the actual classes, as we may change existing
2388 // classes during iteration. This is because our memory iteration propagation
2389 // is not perfect, and so may waste a little work. But it should generate
2390 // exactly the same congruence classes we have now, with different IDs.
2391 std::map<const Value *, CongruenceClass> BeforeIteration;
2392
2393 for (auto &KV : ValueToClass) {
2394 if (auto *I = dyn_cast<Instruction>(KV.first))
2395 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002396 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002397 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002398 BeforeIteration.insert({KV.first, *KV.second});
2399 }
2400
2401 TouchedInstructions.set();
2402 TouchedInstructions.reset(0);
2403 iterateTouchedInstructions();
2404 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2405 EqualClasses;
2406 for (const auto &KV : ValueToClass) {
2407 if (auto *I = dyn_cast<Instruction>(KV.first))
2408 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002409 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00002410 continue;
2411 // We could sink these uses, but i think this adds a bit of clarity here as
2412 // to what we are comparing.
2413 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2414 auto *AfterCC = KV.second;
2415 // Note that the classes can't change at this point, so we memoize the set
2416 // that are equal.
2417 if (!EqualClasses.count({BeforeCC, AfterCC})) {
2418 assert(areClassesEquivalent(BeforeCC, AfterCC) &&
2419 "Value number changed after main loop completed!");
2420 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002421 }
2422 }
2423#endif
2424}
2425
Daniel Berlin06329a92017-03-18 15:41:40 +00002426// This is the main value numbering loop, it iterates over the initial touched
2427// instruction set, propagating value numbers, marking things touched, etc,
2428// until the set of touched instructions is completely empty.
2429void NewGVN::iterateTouchedInstructions() {
2430 unsigned int Iterations = 0;
2431 // Figure out where touchedinstructions starts
2432 int FirstInstr = TouchedInstructions.find_first();
2433 // Nothing set, nothing to iterate, just return.
2434 if (FirstInstr == -1)
2435 return;
Daniel Berlin21279bd2017-04-06 18:52:58 +00002436 BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00002437 while (TouchedInstructions.any()) {
2438 ++Iterations;
2439 // Walk through all the instructions in all the blocks in RPO.
2440 // TODO: As we hit a new block, we should push and pop equalities into a
2441 // table lookupOperandLeader can use, to catch things PredicateInfo
2442 // might miss, like edge-only equivalences.
2443 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2444 InstrNum = TouchedInstructions.find_next(InstrNum)) {
2445
2446 // This instruction was found to be dead. We don't bother looking
2447 // at it again.
2448 if (InstrNum == 0) {
2449 TouchedInstructions.reset(InstrNum);
2450 continue;
2451 }
2452
Daniel Berlin21279bd2017-04-06 18:52:58 +00002453 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlin06329a92017-03-18 15:41:40 +00002454 BasicBlock *CurrBlock = getBlockForValue(V);
2455
2456 // If we hit a new block, do reachability processing.
2457 if (CurrBlock != LastBlock) {
2458 LastBlock = CurrBlock;
2459 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2460 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2461
2462 // If it's not reachable, erase any touched instructions and move on.
2463 if (!BlockReachable) {
2464 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2465 DEBUG(dbgs() << "Skipping instructions in block "
2466 << getBlockName(CurrBlock)
2467 << " because it is unreachable\n");
2468 continue;
2469 }
2470 updateProcessedCount(CurrBlock);
2471 }
2472
2473 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2474 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2475 valueNumberMemoryPhi(MP);
2476 } else if (auto *I = dyn_cast<Instruction>(V)) {
2477 valueNumberInstruction(I);
2478 } else {
2479 llvm_unreachable("Should have been a MemoryPhi or Instruction");
2480 }
2481 updateProcessedCount(V);
2482 // Reset after processing (because we may mark ourselves as touched when
2483 // we propagate equalities).
2484 TouchedInstructions.reset(InstrNum);
2485 }
2486 }
2487 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2488}
2489
Daniel Berlin85f91b02016-12-26 20:06:58 +00002490// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00002491bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00002492 if (DebugCounter::isCounterSet(VNCounter))
2493 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00002494 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00002495 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00002496 MSSAWalker = MSSA->getWalker();
2497
2498 // Count number of instructions for sizing of hash tables, and come
2499 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002500 unsigned ICount = 1;
2501 // Add an empty instruction to account for the fact that we start at 1
2502 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002503 // Note: We want ideal RPO traversal of the blocks, which is not quite the
2504 // same as dominator tree order, particularly with regard whether backedges
2505 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00002506 // If we visit in the wrong order, we will end up performing N times as many
2507 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002508 // The dominator tree does guarantee that, for a given dom tree node, it's
2509 // parent must occur before it in the RPO ordering. Thus, we only need to sort
2510 // the siblings.
2511 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00002512 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00002513 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002514 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002515 auto *Node = DT->getNode(B);
2516 assert(Node && "RPO and Dominator tree should have same reachability");
2517 RPOOrdering[Node] = ++Counter;
2518 }
2519 // Sort dominator tree children arrays into RPO.
2520 for (auto &B : RPOT) {
2521 auto *Node = DT->getNode(B);
2522 if (Node->getChildren().size() > 1)
2523 std::sort(Node->begin(), Node->end(),
2524 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
2525 return RPOOrdering[A] < RPOOrdering[B];
2526 });
2527 }
2528
2529 // Now a standard depth first ordering of the domtree is equivalent to RPO.
2530 auto DFI = df_begin(DT->getRootNode());
2531 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
2532 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00002533 const auto &BlockRange = assignDFSNumbers(B, ICount);
2534 BlockInstRange.insert({B, BlockRange});
2535 ICount += BlockRange.second - BlockRange.first;
2536 }
2537
2538 // Handle forward unreachable blocks and figure out which blocks
2539 // have single preds.
2540 for (auto &B : F) {
2541 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002542 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002543 const auto &BlockRange = assignDFSNumbers(&B, ICount);
2544 BlockInstRange.insert({&B, BlockRange});
2545 ICount += BlockRange.second - BlockRange.first;
2546 }
2547 }
2548
Daniel Berline0bd37e2016-12-29 22:15:12 +00002549 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002550 // Ensure we don't end up resizing the expressionToClass map, as
2551 // that can be quite expensive. At most, we have one expression per
2552 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002553 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002554
2555 // Initialize the touched instructions to include the entry block.
2556 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2557 TouchedInstructions.set(InstRange.first, InstRange.second);
2558 ReachableBlocks.insert(&F.getEntryBlock());
2559
2560 initializeCongruenceClasses(F);
Daniel Berlin06329a92017-03-18 15:41:40 +00002561 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00002562 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00002563 verifyIterationSettled(F);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002564
Davide Italiano7e274e02016-12-22 16:03:48 +00002565 Changed |= eliminateInstructions(F);
2566
2567 // Delete all instructions marked for deletion.
2568 for (Instruction *ToErase : InstructionsToErase) {
2569 if (!ToErase->use_empty())
2570 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2571
2572 ToErase->eraseFromParent();
2573 }
2574
2575 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002576 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2577 return !ReachableBlocks.count(&BB);
2578 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002579
2580 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2581 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002582 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002583 deleteInstructionsInBlock(&BB);
2584 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002585 }
2586
2587 cleanupTables();
2588 return Changed;
2589}
2590
Davide Italiano7e274e02016-12-22 16:03:48 +00002591// Return true if V is a value that will always be available (IE can
2592// be placed anywhere) in the function. We don't do globals here
2593// because they are often worse to put in place.
2594// TODO: Separate cost from availability
2595static bool alwaysAvailable(Value *V) {
2596 return isa<Constant>(V) || isa<Argument>(V);
2597}
2598
Davide Italiano7e274e02016-12-22 16:03:48 +00002599struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002600 int DFSIn = 0;
2601 int DFSOut = 0;
2602 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002603 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002604 // The bool in the Def tells us whether the Def is the stored value of a
2605 // store.
2606 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002607 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002608 bool operator<(const ValueDFS &Other) const {
2609 // It's not enough that any given field be less than - we have sets
2610 // of fields that need to be evaluated together to give a proper ordering.
2611 // For example, if you have;
2612 // DFS (1, 3)
2613 // Val 0
2614 // DFS (1, 2)
2615 // Val 50
2616 // We want the second to be less than the first, but if we just go field
2617 // by field, we will get to Val 0 < Val 50 and say the first is less than
2618 // the second. We only want it to be less than if the DFS orders are equal.
2619 //
2620 // Each LLVM instruction only produces one value, and thus the lowest-level
2621 // differentiator that really matters for the stack (and what we use as as a
2622 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002623 // Everything else in the structure is instruction level, and only affects
2624 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002625 //
2626 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2627 // the order of replacement of uses does not matter.
2628 // IE given,
2629 // a = 5
2630 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002631 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2632 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002633 // The .val will be the same as well.
2634 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002635 // You will replace both, and it does not matter what order you replace them
2636 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2637 // operand 2).
2638 // Similarly for the case of same dfsin, dfsout, localnum, but different
2639 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002640 // a = 5
2641 // b = 6
2642 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002643 // in c, we will a valuedfs for a, and one for b,with everything the same
2644 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002645 // It does not matter what order we replace these operands in.
2646 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002647 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2648 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002649 Other.U);
2650 }
2651};
2652
Daniel Berlinc4796862017-01-27 02:37:11 +00002653// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002654// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00002655// reachable uses for each value is stored in UseCount, and instructions that
2656// seem
2657// dead (have no non-dead uses) are stored in ProbablyDead.
2658void NewGVN::convertClassToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00002659 const CongruenceClass::MemberSet &Dense,
Daniel Berline3e69e12017-03-10 00:32:33 +00002660 SmallVectorImpl<ValueDFS> &DFSOrderedSet,
2661 DenseMap<const Value *, unsigned int> &UseCounts,
2662 SmallPtrSetImpl<Instruction *> &ProbablyDead) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002663 for (auto D : Dense) {
2664 // First add the value.
2665 BasicBlock *BB = getBlockForValue(D);
2666 // Constants are handled prior to ever calling this function, so
2667 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002668 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002669 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002670 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002671 VDDef.DFSIn = DomNode->getDFSNumIn();
2672 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002673 // If it's a store, use the leader of the value operand, if it's always
2674 // available, or the value operand. TODO: We could do dominance checks to
2675 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00002676 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002677 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002678 if (alwaysAvailable(Leader)) {
2679 VDDef.Def.setPointer(Leader);
2680 } else {
2681 VDDef.Def.setPointer(SI->getValueOperand());
2682 VDDef.Def.setInt(true);
2683 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002684 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002685 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00002686 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002687 assert(isa<Instruction>(D) &&
2688 "The dense set member should always be an instruction");
Daniel Berlin21279bd2017-04-06 18:52:58 +00002689 VDDef.LocalNum = InstrToDFSNum(D);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002690 DFSOrderedSet.emplace_back(VDDef);
Daniel Berline3e69e12017-03-10 00:32:33 +00002691 Instruction *Def = cast<Instruction>(D);
2692 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002693 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00002694 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002695 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002696 // Don't try to replace into dead uses
2697 if (InstructionsToErase.count(I))
2698 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002699 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002700 // Put the phi node uses in the incoming block.
2701 BasicBlock *IBlock;
2702 if (auto *P = dyn_cast<PHINode>(I)) {
2703 IBlock = P->getIncomingBlock(U);
2704 // Make phi node users appear last in the incoming block
2705 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002706 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002707 } else {
2708 IBlock = I->getParent();
Daniel Berlin21279bd2017-04-06 18:52:58 +00002709 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002710 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002711
2712 // Skip uses in unreachable blocks, as we're going
2713 // to delete them.
2714 if (ReachableBlocks.count(IBlock) == 0)
2715 continue;
2716
Daniel Berlinb66164c2017-01-14 00:24:23 +00002717 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002718 VDUse.DFSIn = DomNode->getDFSNumIn();
2719 VDUse.DFSOut = DomNode->getDFSNumOut();
2720 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00002721 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002722 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002723 }
2724 }
Daniel Berline3e69e12017-03-10 00:32:33 +00002725
2726 // If there are no uses, it's probably dead (but it may have side-effects,
2727 // so not definitely dead. Otherwise, store the number of uses so we can
2728 // track if it becomes dead later).
2729 if (UseCount == 0)
2730 ProbablyDead.insert(Def);
2731 else
2732 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002733 }
2734}
2735
Daniel Berlinc4796862017-01-27 02:37:11 +00002736// This function converts the set of members for a congruence class from values,
2737// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00002738void NewGVN::convertClassToLoadsAndStores(
Daniel Berlinc4796862017-01-27 02:37:11 +00002739 const CongruenceClass::MemberSet &Dense,
2740 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2741 for (auto D : Dense) {
2742 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2743 continue;
2744
2745 BasicBlock *BB = getBlockForValue(D);
2746 ValueDFS VD;
2747 DomTreeNode *DomNode = DT->getNode(BB);
2748 VD.DFSIn = DomNode->getDFSNumIn();
2749 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002750 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00002751
2752 // If it's an instruction, use the real local dfs number.
2753 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002754 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00002755 else
2756 llvm_unreachable("Should have been an instruction");
2757
2758 LoadsAndStores.emplace_back(VD);
2759 }
2760}
2761
Davide Italiano7e274e02016-12-22 16:03:48 +00002762static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002763 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002764 if (!ReplInst)
2765 return;
2766
Davide Italiano7e274e02016-12-22 16:03:48 +00002767 // Patch the replacement so that it is not more restrictive than the value
2768 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002769 // Note that if 'I' is a load being replaced by some operation,
2770 // for example, by an arithmetic operation, then andIRFlags()
2771 // would just erase all math flags from the original arithmetic
2772 // operation, which is clearly not wanted and not needed.
2773 if (!isa<LoadInst>(I))
2774 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002775
Daniel Berlin86eab152017-02-12 22:25:20 +00002776 // FIXME: If both the original and replacement value are part of the
2777 // same control-flow region (meaning that the execution of one
2778 // guarantees the execution of the other), then we can combine the
2779 // noalias scopes here and do better than the general conservative
2780 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002781
Daniel Berlin86eab152017-02-12 22:25:20 +00002782 // In general, GVN unifies expressions over different control-flow
2783 // regions, and so we need a conservative combination of the noalias
2784 // scopes.
2785 static const unsigned KnownIDs[] = {
2786 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2787 LLVMContext::MD_noalias, LLVMContext::MD_range,
2788 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2789 LLVMContext::MD_invariant_group};
2790 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002791}
2792
2793static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2794 patchReplacementInstruction(I, Repl);
2795 I->replaceAllUsesWith(Repl);
2796}
2797
2798void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2799 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2800 ++NumGVNBlocksDeleted;
2801
Daniel Berline19f0e02017-01-30 17:06:55 +00002802 // Delete the instructions backwards, as it has a reduced likelihood of having
2803 // to update as many def-use and use-def chains. Start after the terminator.
2804 auto StartPoint = BB->rbegin();
2805 ++StartPoint;
2806 // Note that we explicitly recalculate BB->rend() on each iteration,
2807 // as it may change when we remove the first instruction.
2808 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2809 Instruction &Inst = *I++;
2810 if (!Inst.use_empty())
2811 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2812 if (isa<LandingPadInst>(Inst))
2813 continue;
2814
2815 Inst.eraseFromParent();
2816 ++NumGVNInstrDeleted;
2817 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002818 // Now insert something that simplifycfg will turn into an unreachable.
2819 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2820 new StoreInst(UndefValue::get(Int8Ty),
2821 Constant::getNullValue(Int8Ty->getPointerTo()),
2822 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002823}
2824
2825void NewGVN::markInstructionForDeletion(Instruction *I) {
2826 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2827 InstructionsToErase.insert(I);
2828}
2829
2830void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2831
2832 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2833 patchAndReplaceAllUsesWith(I, V);
2834 // We save the actual erasing to avoid invalidating memory
2835 // dependencies until we are done with everything.
2836 markInstructionForDeletion(I);
2837}
2838
2839namespace {
2840
2841// This is a stack that contains both the value and dfs info of where
2842// that value is valid.
2843class ValueDFSStack {
2844public:
2845 Value *back() const { return ValueStack.back(); }
2846 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2847
2848 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002849 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002850 DFSStack.emplace_back(DFSIn, DFSOut);
2851 }
2852 bool empty() const { return DFSStack.empty(); }
2853 bool isInScope(int DFSIn, int DFSOut) const {
2854 if (empty())
2855 return false;
2856 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2857 }
2858
2859 void popUntilDFSScope(int DFSIn, int DFSOut) {
2860
2861 // These two should always be in sync at this point.
2862 assert(ValueStack.size() == DFSStack.size() &&
2863 "Mismatch between ValueStack and DFSStack");
2864 while (
2865 !DFSStack.empty() &&
2866 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2867 DFSStack.pop_back();
2868 ValueStack.pop_back();
2869 }
2870 }
2871
2872private:
2873 SmallVector<Value *, 8> ValueStack;
2874 SmallVector<std::pair<int, int>, 8> DFSStack;
2875};
2876}
Daniel Berlin04443432017-01-07 03:23:47 +00002877
Davide Italiano7e274e02016-12-22 16:03:48 +00002878bool NewGVN::eliminateInstructions(Function &F) {
2879 // This is a non-standard eliminator. The normal way to eliminate is
2880 // to walk the dominator tree in order, keeping track of available
2881 // values, and eliminating them. However, this is mildly
2882 // pointless. It requires doing lookups on every instruction,
2883 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002884 // instructions part of most singleton congruence classes, we know we
2885 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002886
2887 // Instead, this eliminator looks at the congruence classes directly, sorts
2888 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002889 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002890 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002891 // last member. This is worst case O(E log E) where E = number of
2892 // instructions in a single congruence class. In theory, this is all
2893 // instructions. In practice, it is much faster, as most instructions are
2894 // either in singleton congruence classes or can't possibly be eliminated
2895 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002896 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002897 // for elimination purposes.
2898 // TODO: If we wanted to be faster, We could remove any members with no
2899 // overlapping ranges while sorting, as we will never eliminate anything
2900 // with those members, as they don't dominate anything else in our set.
2901
Davide Italiano7e274e02016-12-22 16:03:48 +00002902 bool AnythingReplaced = false;
2903
2904 // Since we are going to walk the domtree anyway, and we can't guarantee the
2905 // DFS numbers are updated, we compute some ourselves.
2906 DT->updateDFSNumbers();
2907
2908 for (auto &B : F) {
2909 if (!ReachableBlocks.count(&B)) {
2910 for (const auto S : successors(&B)) {
2911 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002912 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002913 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2914 << getBlockName(&B)
2915 << " with undef due to it being unreachable\n");
2916 for (auto &Operand : Phi.incoming_values())
2917 if (Phi.getIncomingBlock(Operand) == &B)
2918 Operand.set(UndefValue::get(Phi.getType()));
2919 }
2920 }
2921 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002922 }
2923
Daniel Berline3e69e12017-03-10 00:32:33 +00002924 // Map to store the use counts
2925 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlin4d547962017-02-12 23:24:45 +00002926 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002927 // Track the equivalent store info so we can decide whether to try
2928 // dead store elimination.
2929 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00002930 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlin1316a942017-04-06 18:52:50 +00002931 if (CC->isDead() || CC->Members.empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00002932 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002933 // Everything still in the TOP class is unreachable or dead.
2934 if (CC == TOPClass) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00002935#ifndef NDEBUG
2936 for (auto M : CC->Members)
2937 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2938 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002939 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00002940 "point");
2941#endif
2942 continue;
2943 }
2944
Davide Italiano7e274e02016-12-22 16:03:48 +00002945 assert(CC->RepLeader && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00002946 // If this is a leader that is always available, and it's a
2947 // constant or has no equivalences, just replace everything with
2948 // it. We then update the congruence class with whatever members
2949 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002950 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2951 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00002952 CongruenceClass::MemberSet MembersLeft;
Davide Italiano7e274e02016-12-22 16:03:48 +00002953 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002954 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002955 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00002956 if (Member == Leader || !isa<Instruction>(Member) ||
2957 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002958 MembersLeft.insert(Member);
2959 continue;
2960 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002961 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2962 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00002963 auto *I = cast<Instruction>(Member);
2964 assert(Leader != I && "About to accidentally remove our leader");
2965 replaceInstruction(I, Leader);
2966 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002967 }
2968 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002969 } else {
2970 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2971 // If this is a singleton, we can skip it.
2972 if (CC->Members.size() != 1) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002973 // This is a stack because equality replacement/etc may place
2974 // constants in the middle of the member list, and we want to use
2975 // those constant values in preference to the current leader, over
2976 // the scope of those constants.
2977 ValueDFSStack EliminationStack;
2978
2979 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002980 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berline3e69e12017-03-10 00:32:33 +00002981 convertClassToDFSOrdered(CC->Members, DFSOrderedSet, UseCounts,
2982 ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00002983
2984 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002985 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002986 for (auto &VD : DFSOrderedSet) {
2987 int MemberDFSIn = VD.DFSIn;
2988 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002989 Value *Def = VD.Def.getPointer();
2990 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00002991 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00002992 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002993 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00002994 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002995
2996 if (EliminationStack.empty()) {
2997 DEBUG(dbgs() << "Elimination Stack is empty\n");
2998 } else {
2999 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3000 << EliminationStack.dfs_back().first << ","
3001 << EliminationStack.dfs_back().second << ")\n");
3002 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003003
3004 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3005 << MemberDFSOut << ")\n");
3006 // First, we see if we are out of scope or empty. If so,
3007 // and there equivalences, we try to replace the top of
3008 // stack with equivalences (if it's on the stack, it must
3009 // not have been eliminated yet).
3010 // Then we synchronize to our current scope, by
3011 // popping until we are back within a DFS scope that
3012 // dominates the current member.
3013 // Then, what happens depends on a few factors
3014 // If the stack is now empty, we need to push
3015 // If we have a constant or a local equivalence we want to
3016 // start using, we also push.
3017 // Otherwise, we walk along, processing members who are
3018 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003019 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003020 bool OutOfScope =
3021 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3022
3023 if (OutOfScope || ShouldPush) {
3024 // Sync to our current scope.
3025 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003026 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003027 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003028 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003029 }
3030 }
3031
Daniel Berline3e69e12017-03-10 00:32:33 +00003032 // Skip the Def's, we only want to eliminate on their uses. But mark
3033 // dominated defs as dead.
3034 if (Def) {
3035 // For anything in this case, what and how we value number
3036 // guarantees that any side-effets that would have occurred (ie
3037 // throwing, etc) can be proven to either still occur (because it's
3038 // dominated by something that has the same side-effects), or never
3039 // occur. Otherwise, we would not have been able to prove it value
3040 // equivalent to something else. For these things, we can just mark
3041 // it all dead. Note that this is different from the "ProbablyDead"
3042 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003043 // easy to prove dead if they are also side-effect free. Note that
3044 // because stores are put in terms of the stored value, we skip
3045 // stored values here. If the stored value is really dead, it will
3046 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003047 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003048 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003049 markInstructionForDeletion(cast<Instruction>(Def));
3050 continue;
3051 }
3052 // At this point, we know it is a Use we are trying to possibly
3053 // replace.
3054
3055 assert(isa<Instruction>(U->get()) &&
3056 "Current def should have been an instruction");
3057 assert(isa<Instruction>(U->getUser()) &&
3058 "Current user should have been an instruction");
3059
3060 // If the thing we are replacing into is already marked to be dead,
3061 // this use is dead. Note that this is true regardless of whether
3062 // we have anything dominating the use or not. We do this here
3063 // because we are already walking all the uses anyway.
3064 Instruction *InstUse = cast<Instruction>(U->getUser());
3065 if (InstructionsToErase.count(InstUse)) {
3066 auto &UseCount = UseCounts[U->get()];
3067 if (--UseCount == 0) {
3068 ProbablyDead.insert(cast<Instruction>(U->get()));
3069 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003070 }
3071
Davide Italiano7e274e02016-12-22 16:03:48 +00003072 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003073 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003074 if (EliminationStack.empty())
3075 continue;
3076
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003077 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003078
Daniel Berlind92e7f92017-01-07 00:01:42 +00003079 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003080 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003081 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003082 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003083 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003084
3085 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003086 // metadata. Skip this if we are replacing predicateinfo with its
3087 // original operand, as we already know we can just drop it.
3088 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003089 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3090 if (!PI || DominatingLeader != PI->OriginalOp)
3091 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003092 U->set(DominatingLeader);
3093 // This is now a use of the dominating leader, which means if the
3094 // dominating leader was dead, it's now live!
3095 auto &LeaderUseCount = UseCounts[DominatingLeader];
3096 // It's about to be alive again.
3097 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3098 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
3099 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003100 AnythingReplaced = true;
3101 }
3102 }
3103 }
3104
Daniel Berline3e69e12017-03-10 00:32:33 +00003105 // At this point, anything still in the ProbablyDead set is actually dead if
3106 // would be trivially dead.
3107 for (auto *I : ProbablyDead)
3108 if (wouldInstructionBeTriviallyDead(I))
3109 markInstructionForDeletion(I);
3110
Davide Italiano7e274e02016-12-22 16:03:48 +00003111 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003112 CongruenceClass::MemberSet MembersLeft;
3113 for (auto *Member : CC->Members)
3114 if (!isa<Instruction>(Member) ||
3115 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003116 MembersLeft.insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +00003117 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003118
3119 // If we have possible dead stores to look at, try to eliminate them.
3120 if (CC->StoreCount > 0) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003121 convertClassToLoadsAndStores(CC->Members, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003122 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3123 ValueDFSStack EliminationStack;
3124 for (auto &VD : PossibleDeadStores) {
3125 int MemberDFSIn = VD.DFSIn;
3126 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003127 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003128 if (EliminationStack.empty() ||
3129 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3130 // Sync to our current scope.
3131 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3132 if (EliminationStack.empty()) {
3133 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3134 continue;
3135 }
3136 }
3137 // We already did load elimination, so nothing to do here.
3138 if (isa<LoadInst>(Member))
3139 continue;
3140 assert(!EliminationStack.empty());
3141 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003142 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003143 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3144 // Member is dominater by Leader, and thus dead
3145 DEBUG(dbgs() << "Marking dead store " << *Member
3146 << " that is dominated by " << *Leader << "\n");
3147 markInstructionForDeletion(Member);
3148 CC->Members.erase(Member);
3149 ++NumGVNDeadStores;
3150 }
3151 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003152 }
3153
3154 return AnythingReplaced;
3155}
Daniel Berlin1c087672017-02-11 15:07:01 +00003156
3157// This function provides global ranking of operations so that we can place them
3158// in a canonical order. Note that rank alone is not necessarily enough for a
3159// complete ordering, as constants all have the same rank. However, generally,
3160// we will simplify an operation with all constants so that it doesn't matter
3161// what order they appear in.
3162unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003163 // Prefer undef to anything else
3164 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00003165 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003166 if (isa<Constant>(V))
3167 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00003168 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003169 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003170
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003171 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003172 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003173 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00003174 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003175 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003176 // Unreachable or something else, just return a really large number.
3177 return ~0;
3178}
3179
3180// This is a function that says whether two commutative operations should
3181// have their order swapped when canonicalizing.
3182bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3183 // Because we only care about a total ordering, and don't rewrite expressions
3184 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003185 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003186 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003187}
Daniel Berlin64e68992017-03-12 04:46:45 +00003188
3189class NewGVNLegacyPass : public FunctionPass {
3190public:
3191 static char ID; // Pass identification, replacement for typeid.
3192 NewGVNLegacyPass() : FunctionPass(ID) {
3193 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3194 }
3195 bool runOnFunction(Function &F) override;
3196
3197private:
3198 void getAnalysisUsage(AnalysisUsage &AU) const override {
3199 AU.addRequired<AssumptionCacheTracker>();
3200 AU.addRequired<DominatorTreeWrapperPass>();
3201 AU.addRequired<TargetLibraryInfoWrapperPass>();
3202 AU.addRequired<MemorySSAWrapperPass>();
3203 AU.addRequired<AAResultsWrapperPass>();
3204 AU.addPreserved<DominatorTreeWrapperPass>();
3205 AU.addPreserved<GlobalsAAWrapperPass>();
3206 }
3207};
3208
3209bool NewGVNLegacyPass::runOnFunction(Function &F) {
3210 if (skipFunction(F))
3211 return false;
3212 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3213 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3214 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3215 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3216 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3217 F.getParent()->getDataLayout())
3218 .runGVN();
3219}
3220
3221INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3222 false, false)
3223INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3224INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3225INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3226INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3227INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3228INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3229INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3230 false)
3231
3232char NewGVNLegacyPass::ID = 0;
3233
3234// createGVNPass - The public interface to this file.
3235FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3236
3237PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3238 // Apparently the order in which we get these results matter for
3239 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3240 // the same order here, just in case.
3241 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3242 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3243 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3244 auto &AA = AM.getResult<AAManager>(F);
3245 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3246 bool Changed =
3247 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3248 .runGVN();
3249 if (!Changed)
3250 return PreservedAnalyses::all();
3251 PreservedAnalyses PA;
3252 PA.preserve<DominatorTreeAnalysis>();
3253 PA.preserve<GlobalsAA>();
3254 return PA;
3255}