blob: 526a4c0f35c5dbb1a9313e167c6356962af7e1a3 [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 Berlin1316a942017-04-06 18:52:50 +0000500 unsigned getInstrNum(const Value *V) const {
501 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
502 return InstrDFS.lookup(V);
503 }
504
505 unsigned getInstrNum(const MemoryAccess *MA) const {
506 return getMemoryInstrNum(MA);
507 }
508
509 unsigned getMemoryInstrNum(const Value *) const;
510 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000511 // Debug counter info. When verifying, we have to reset the value numbering
512 // debug counter to the same state it started in to get the same results.
513 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000514};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000515} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000516
Davide Italianob1114092016-12-28 13:37:17 +0000517template <typename T>
518static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000519 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000520 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000521 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000522}
523
Davide Italianob1114092016-12-28 13:37:17 +0000524bool LoadExpression::equals(const Expression &Other) const {
525 return equalsLoadStoreHelper(*this, Other);
526}
Davide Italiano7e274e02016-12-22 16:03:48 +0000527
Davide Italianob1114092016-12-28 13:37:17 +0000528bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000529 if (!equalsLoadStoreHelper(*this, Other))
530 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000531 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000532 if (const auto *S = dyn_cast<StoreExpression>(&Other))
533 if (getStoredValue() != S->getStoredValue())
534 return false;
535 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000536}
537
538#ifndef NDEBUG
539static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000540 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000541}
542#endif
543
Daniel Berlin06329a92017-03-18 15:41:40 +0000544// Get the basic block from an instruction/memory value.
545BasicBlock *NewGVN::getBlockForValue(Value *V) const {
546 if (auto *I = dyn_cast<Instruction>(V))
547 return I->getParent();
548 else if (auto *MP = dyn_cast<MemoryPhi>(V))
549 return MP->getBlock();
550 llvm_unreachable("Should have been able to figure out a block for our value");
551 return nullptr;
552}
553
Daniel Berlin0e900112017-03-24 06:33:48 +0000554// Delete a definitely dead expression, so it can be reused by the expression
555// allocator. Some of these are not in creation functions, so we have to accept
556// const versions.
557void NewGVN::deleteExpression(const Expression *E) {
558 assert(isa<BasicExpression>(E));
559 auto *BE = cast<BasicExpression>(E);
560 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
561 ExpressionAllocator.Deallocate(E);
562}
563
Davide Italiano7e274e02016-12-22 16:03:48 +0000564PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000565 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000566 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000567 auto *E =
568 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000569
570 E->allocateOperands(ArgRecycler, ExpressionAllocator);
571 E->setType(I->getType());
572 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000573
Davide Italianob3886dd2017-01-25 23:37:49 +0000574 // Filter out unreachable phi operands.
575 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +0000576 return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000577 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000578
579 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
580 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000581 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000582 if (U == PN)
583 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000584 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000585 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000586 return E;
587}
588
589// Set basic expression info (Arguments, type, opcode) for Expression
590// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000591bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000592 bool AllConstant = true;
593 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
594 E->setType(GEP->getSourceElementType());
595 else
596 E->setType(I->getType());
597 E->setOpcode(I->getOpcode());
598 E->allocateOperands(ArgRecycler, ExpressionAllocator);
599
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000600 // Transform the operand array into an operand leader array, and keep track of
601 // whether all members are constant.
602 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000603 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000604 AllConstant &= isa<Constant>(Operand);
605 return Operand;
606 });
607
Davide Italiano7e274e02016-12-22 16:03:48 +0000608 return AllConstant;
609}
610
611const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000612 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000613 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000614
615 E->setType(T);
616 E->setOpcode(Opcode);
617 E->allocateOperands(ArgRecycler, ExpressionAllocator);
618 if (Instruction::isCommutative(Opcode)) {
619 // Ensure that commutative instructions that only differ by a permutation
620 // of their operands get the same value number by sorting the operand value
621 // numbers. Since all commutative instructions have two operands it is more
622 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000623 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000624 std::swap(Arg1, Arg2);
625 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000626 E->op_push_back(lookupOperandLeader(Arg1));
627 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000628
Daniel Berlin64e68992017-03-12 04:46:45 +0000629 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), DL, TLI,
Davide Italiano7e274e02016-12-22 16:03:48 +0000630 DT, AC);
631 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
632 return SimplifiedE;
633 return E;
634}
635
636// Take a Value returned by simplification of Expression E/Instruction
637// I, and see if it resulted in a simpler expression. If so, return
638// that expression.
639// TODO: Once finished, this should not take an Instruction, we only
640// use it for printing.
641const Expression *NewGVN::checkSimplificationResults(Expression *E,
642 Instruction *I, Value *V) {
643 if (!V)
644 return nullptr;
645 if (auto *C = dyn_cast<Constant>(V)) {
646 if (I)
647 DEBUG(dbgs() << "Simplified " << *I << " to "
648 << " constant " << *C << "\n");
649 NumGVNOpsSimplified++;
650 assert(isa<BasicExpression>(E) &&
651 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000652 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000653 return createConstantExpression(C);
654 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
655 if (I)
656 DEBUG(dbgs() << "Simplified " << *I << " to "
657 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000658 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000659 return createVariableExpression(V);
660 }
661
662 CongruenceClass *CC = ValueToClass.lookup(V);
663 if (CC && CC->DefiningExpr) {
664 if (I)
665 DEBUG(dbgs() << "Simplified " << *I << " to "
666 << " expression " << *V << "\n");
667 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000668 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000669 return CC->DefiningExpr;
670 }
671 return nullptr;
672}
673
Daniel Berlin97718e62017-01-31 22:32:03 +0000674const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000675 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000676
Daniel Berlin97718e62017-01-31 22:32:03 +0000677 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000678
679 if (I->isCommutative()) {
680 // Ensure that commutative instructions that only differ by a permutation
681 // of their operands get the same value number by sorting the operand value
682 // numbers. Since all commutative instructions have two operands it is more
683 // efficient to sort by hand rather than using, say, std::sort.
684 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000685 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000686 E->swapOperands(0, 1);
687 }
688
689 // Perform simplificaiton
690 // TODO: Right now we only check to see if we get a constant result.
691 // We may get a less than constant, but still better, result for
692 // some operations.
693 // IE
694 // add 0, x -> x
695 // and x, x -> x
696 // We should handle this by simply rewriting the expression.
697 if (auto *CI = dyn_cast<CmpInst>(I)) {
698 // Sort the operand value numbers so x<y and y>x get the same value
699 // number.
700 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000701 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000702 E->swapOperands(0, 1);
703 Predicate = CmpInst::getSwappedPredicate(Predicate);
704 }
705 E->setOpcode((CI->getOpcode() << 8) | Predicate);
706 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000707 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
708 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000709 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
710 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000711 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000712 DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000713 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
714 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000715 } else if (isa<SelectInst>(I)) {
716 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000717 E->getOperand(0) == E->getOperand(1)) {
718 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
719 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000720 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000721 E->getOperand(2), DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000722 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
723 return SimplifiedE;
724 }
725 } else if (I->isBinaryOp()) {
726 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000727 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000728 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
729 return SimplifiedE;
730 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin64e68992017-03-12 04:46:45 +0000731 Value *V = SimplifyInstruction(BI, DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000732 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
733 return SimplifiedE;
734 } else if (isa<GetElementPtrInst>(I)) {
735 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000736 ArrayRef<Value *>(E->op_begin(), E->op_end()),
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 (AllConstant) {
741 // We don't bother trying to simplify unless all of the operands
742 // were constant.
743 // TODO: There are a lot of Simplify*'s we could call here, if we
744 // wanted to. The original motivating case for this code was a
745 // zext i1 false to i8, which we don't have an interface to
746 // simplify (IE there is no SimplifyZExt).
747
748 SmallVector<Constant *, 8> C;
749 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000750 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000751
Daniel Berlin64e68992017-03-12 04:46:45 +0000752 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +0000753 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
754 return SimplifiedE;
755 }
756 return E;
757}
758
759const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000760NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000761 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000762 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000763 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000764 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000765 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000766 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000767 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000768 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000769 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000770 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000771 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000772 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000773 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000774 return E;
775 }
776 llvm_unreachable("Unhandled type of aggregate value operation");
777}
778
Daniel Berlin85f91b02016-12-26 20:06:58 +0000779const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000780 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000781 E->setOpcode(V->getValueID());
782 return E;
783}
784
Daniel Berlinf7d95802017-02-18 23:06:50 +0000785const Expression *NewGVN::createVariableOrConstant(Value *V) {
786 if (auto *C = dyn_cast<Constant>(V))
787 return createConstantExpression(C);
788 return createVariableExpression(V);
789}
790
Daniel Berlin85f91b02016-12-26 20:06:58 +0000791const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000792 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000793 E->setOpcode(C->getValueID());
794 return E;
795}
796
Daniel Berlin02c6b172017-01-02 18:00:53 +0000797const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
798 auto *E = new (ExpressionAllocator) UnknownExpression(I);
799 E->setOpcode(I->getOpcode());
800 return E;
801}
802
Davide Italiano7e274e02016-12-22 16:03:48 +0000803const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin1316a942017-04-06 18:52:50 +0000804 const MemoryAccess *MA) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000805 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000806 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +0000807 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +0000808 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000809 return E;
810}
811
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000812// Return true if some equivalent of instruction Inst dominates instruction U.
813bool NewGVN::someEquivalentDominates(const Instruction *Inst,
814 const Instruction *U) const {
815 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +0000816 // This must be an instruction because we are only called from phi nodes
817 // in the case that the value it needs to check against is an instruction.
818
819 // The most likely candiates for dominance are the leader and the next leader.
820 // The leader or nextleader will dominate in all cases where there is an
821 // equivalent that is higher up in the dom tree.
822 // We can't *only* check them, however, because the
823 // dominator tree could have an infinite number of non-dominating siblings
824 // with instructions that are in the right congruence class.
825 // A
826 // B C D E F G
827 // |
828 // H
829 // Instruction U could be in H, with equivalents in every other sibling.
830 // Depending on the rpo order picked, the leader could be the equivalent in
831 // any of these siblings.
832 if (!CC)
833 return false;
834 if (DT->dominates(cast<Instruction>(CC->RepLeader), U))
835 return true;
836 if (CC->NextLeader.first &&
837 DT->dominates(cast<Instruction>(CC->NextLeader.first), U))
838 return true;
839 return llvm::any_of(CC->Members, [&](const Value *Member) {
840 return Member != CC->RepLeader &&
841 DT->dominates(cast<Instruction>(Member), U);
842 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000843}
844
Davide Italiano7e274e02016-12-22 16:03:48 +0000845// See if we have a congruence class and leader for this operand, and if so,
846// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000847Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000848 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000849 if (CC) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000850 // Everything in TOP is represneted by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000851 // We do have to make sure we get the type right though, so we can't set the
852 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000853 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +0000854 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000855 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000856 }
857
Davide Italiano7e274e02016-12-22 16:03:48 +0000858 return V;
859}
860
Daniel Berlin1316a942017-04-06 18:52:50 +0000861const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
862 auto *CC = getMemoryClass(MA);
863 assert(CC->RepMemoryAccess && "Every MemoryAccess should be mapped to a "
864 "congruence class with a represenative memory "
865 "access");
866 return CC->RepMemoryAccess;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000867}
868
Daniel Berlinc4796862017-01-27 02:37:11 +0000869// Return true if the MemoryAccess is really equivalent to everything. This is
870// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +0000871// state of all MemoryAccesses.
Daniel Berlinc4796862017-01-27 02:37:11 +0000872bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000873 return getMemoryClass(MA) == TOPClass;
874}
875
876// Given a MemoryAccess, return the relevant instruction DFS number. Note: This
877// deliberately takes a value so it can be used with Use's, which will
878// auto-convert to Value's but not to MemoryAccess's.
879unsigned NewGVN::getMemoryInstrNum(const Value *MA) const {
880 assert(isa<MemoryAccess>(MA) && "This should not be used with instructions");
881 return isa<MemoryUseOrDef>(MA)
882 ? InstrDFS.lookup(cast<MemoryUseOrDef>(MA)->getMemoryInst())
883 : InstrDFS.lookup(MA);
Daniel Berlinc4796862017-01-27 02:37:11 +0000884}
885
Davide Italiano7e274e02016-12-22 16:03:48 +0000886LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +0000887 LoadInst *LI,
888 const MemoryAccess *MA) {
889 auto *E =
890 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +0000891 E->allocateOperands(ArgRecycler, ExpressionAllocator);
892 E->setType(LoadType);
893
894 // Give store and loads same opcode so they value number together.
895 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +0000896 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +0000897 if (LI)
898 E->setAlignment(LI->getAlignment());
899
900 // TODO: Value number heap versions. We may be able to discover
901 // things alias analysis can't on it's own (IE that a store and a
902 // load have the same value, and thus, it isn't clobbering the load).
903 return E;
904}
905
906const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin1316a942017-04-06 18:52:50 +0000907 const MemoryAccess *MA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000908 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000909 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +0000910 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000911 E->allocateOperands(ArgRecycler, ExpressionAllocator);
912 E->setType(SI->getValueOperand()->getType());
913
914 // Give store and loads same opcode so they value number together.
915 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000916 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000917
918 // TODO: Value number heap versions. We may be able to discover
919 // things alias analysis can't on it's own (IE that a store and a
920 // load have the same value, and thus, it isn't clobbering the load).
921 return E;
922}
923
Daniel Berlin97718e62017-01-31 22:32:03 +0000924const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000925 // Unlike loads, we never try to eliminate stores, so we do not check if they
926 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000927 auto *SI = cast<StoreInst>(I);
Daniel Berlin1316a942017-04-06 18:52:50 +0000928 auto *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000929 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +0000930 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
931 if (EnableStoreRefinement)
932 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
933 // If we bypassed the use-def chains, make sure we add a use.
934 if (StoreRHS != StoreAccess->getDefiningAccess())
935 addMemoryUsers(StoreRHS, StoreAccess);
936
937 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +0000938 // If we are defined by ourselves, use the live on entry def.
939 if (StoreRHS == StoreAccess)
940 StoreRHS = MSSA->getLiveOnEntryDef();
941
Daniel Berlin589cecc2017-01-02 18:00:46 +0000942 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000943 // See if we are defined by a previous store expression, it already has a
944 // value, and it's the same value as our current store. FIXME: Right now, we
945 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +0000946 const auto *LastStore = createStoreExpression(SI, StoreRHS);
947 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000948 // Basically, check if the congruence class the store is in is defined by a
949 // store that isn't us, and has the same value. MemorySSA takes care of
950 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000951 // The RepStoredValue gets nulled if all the stores disappear in a class, so
952 // we don't need to check if the class contains a store besides us.
Daniel Berlin1316a942017-04-06 18:52:50 +0000953 if (LastCC &&
954 LastCC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
955 return LastStore;
956 deleteExpression(LastStore);
Daniel Berlinc4796862017-01-27 02:37:11 +0000957 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +0000958 // location, and the memory state is the same as it was then (otherwise, it
959 // could have been overwritten later. See test32 in
960 // transforms/DeadStoreElimination/simple.ll).
961 if (auto *LI =
962 dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000963 if ((lookupOperandLeader(LI->getPointerOperand()) ==
964 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlin1316a942017-04-06 18:52:50 +0000965 (lookupMemoryLeader(MSSA->getMemoryAccess(LI)->getDefiningAccess()) ==
966 StoreRHS))
Daniel Berlinc4796862017-01-27 02:37:11 +0000967 return createVariableExpression(LI);
968 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000969 }
Daniel Berlin1316a942017-04-06 18:52:50 +0000970
971 // If the store is not equivalent to anything, value number it as a store that
972 // produces a unique memory state (instead of using it's MemoryUse, we use
973 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +0000974 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000975}
976
Daniel Berlin07daac82017-04-02 13:23:44 +0000977// See if we can extract the value of a loaded pointer from a load, a store, or
978// a memory instruction.
979const Expression *
980NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
981 LoadInst *LI, Instruction *DepInst,
982 MemoryAccess *DefiningAccess) {
983 assert((!LI || LI->isSimple()) && "Not a simple load");
984 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
985 // Can't forward from non-atomic to atomic without violating memory model.
986 // Also don't need to coerce if they are the same type, we will just
987 // propogate..
988 if (LI->isAtomic() > DepSI->isAtomic() ||
989 LoadType == DepSI->getValueOperand()->getType())
990 return nullptr;
991 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
992 if (Offset >= 0) {
993 if (auto *C = dyn_cast<Constant>(
994 lookupOperandLeader(DepSI->getValueOperand()))) {
995 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
996 << *C << "\n");
997 return createConstantExpression(
998 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
999 }
1000 }
1001
1002 } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1003 // Can't forward from non-atomic to atomic without violating memory model.
1004 if (LI->isAtomic() > DepLI->isAtomic())
1005 return nullptr;
1006 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1007 if (Offset >= 0) {
1008 // We can coerce a constant load into a load
1009 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1010 if (auto *PossibleConstant =
1011 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1012 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1013 << *PossibleConstant << "\n");
1014 return createConstantExpression(PossibleConstant);
1015 }
1016 }
1017
1018 } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1019 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1020 if (Offset >= 0) {
1021 if (auto *PossibleConstant =
1022 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1023 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1024 << " to constant " << *PossibleConstant << "\n");
1025 return createConstantExpression(PossibleConstant);
1026 }
1027 }
1028 }
1029
1030 // All of the below are only true if the loaded pointer is produced
1031 // by the dependent instruction.
1032 if (LoadPtr != lookupOperandLeader(DepInst) &&
1033 !AA->isMustAlias(LoadPtr, DepInst))
1034 return nullptr;
1035 // If this load really doesn't depend on anything, then we must be loading an
1036 // undef value. This can happen when loading for a fresh allocation with no
1037 // intervening stores, for example. Note that this is only true in the case
1038 // that the result of the allocation is pointer equal to the load ptr.
1039 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1040 return createConstantExpression(UndefValue::get(LoadType));
1041 }
1042 // If this load occurs either right after a lifetime begin,
1043 // then the loaded value is undefined.
1044 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1045 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1046 return createConstantExpression(UndefValue::get(LoadType));
1047 }
1048 // If this load follows a calloc (which zero initializes memory),
1049 // then the loaded value is zero
1050 else if (isCallocLikeFn(DepInst, TLI)) {
1051 return createConstantExpression(Constant::getNullValue(LoadType));
1052 }
1053
1054 return nullptr;
1055}
1056
Daniel Berlin97718e62017-01-31 22:32:03 +00001057const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001058 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001059
1060 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001061 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001062 if (!LI->isSimple())
1063 return nullptr;
1064
Daniel Berlin203f47b2017-01-31 22:31:53 +00001065 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001066 // Load of undef is undef.
1067 if (isa<UndefValue>(LoadAddressLeader))
1068 return createConstantExpression(UndefValue::get(LI->getType()));
1069
1070 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
1071
1072 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1073 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1074 Instruction *DefiningInst = MD->getMemoryInst();
1075 // If the defining instruction is not reachable, replace with undef.
1076 if (!ReachableBlocks.count(DefiningInst->getParent()))
1077 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001078 // This will handle stores and memory insts. We only do if it the
1079 // defining access has a different type, or it is a pointer produced by
1080 // certain memory operations that cause the memory to have a fixed value
1081 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001082 if (const auto *CoercionResult =
1083 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1084 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001085 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001086 }
1087 }
1088
Daniel Berlin1316a942017-04-06 18:52:50 +00001089 const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1090 LI, DefiningAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001091 return E;
1092}
1093
Daniel Berlinf7d95802017-02-18 23:06:50 +00001094const Expression *
1095NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
1096 auto *PI = PredInfo->getPredicateInfoFor(I);
1097 if (!PI)
1098 return nullptr;
1099
1100 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001101
1102 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1103 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001104 return nullptr;
1105
Daniel Berlinfccbda92017-02-22 22:20:58 +00001106 auto *CopyOf = I->getOperand(0);
1107 auto *Cond = PWC->Condition;
1108
Daniel Berlinf7d95802017-02-18 23:06:50 +00001109 // If this a copy of the condition, it must be either true or false depending
1110 // on the predicate info type and edge
1111 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001112 // We should not need to add predicate users because the predicate info is
1113 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001114 if (isa<PredicateAssume>(PI))
1115 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1116 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1117 if (PBranch->TrueEdge)
1118 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1119 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1120 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001121 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1122 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001123 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001124
Daniel Berlinf7d95802017-02-18 23:06:50 +00001125 // Not a copy of the condition, so see what the predicates tell us about this
1126 // value. First, though, we check to make sure the value is actually a copy
1127 // of one of the condition operands. It's possible, in certain cases, for it
1128 // to be a copy of a predicateinfo copy. In particular, if two branch
1129 // operations use the same condition, and one branch dominates the other, we
1130 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001131 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001132 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001133
1134 // Everything below relies on the condition being a comparison.
1135 auto *Cmp = dyn_cast<CmpInst>(Cond);
1136 if (!Cmp)
1137 return nullptr;
1138
1139 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001140 DEBUG(dbgs() << "Copy is not of any condition operands!");
1141 return nullptr;
1142 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001143 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1144 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001145 bool SwappedOps = false;
1146 // Sort the ops
1147 if (shouldSwapOperands(FirstOp, SecondOp)) {
1148 std::swap(FirstOp, SecondOp);
1149 SwappedOps = true;
1150 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001151 CmpInst::Predicate Predicate =
1152 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1153
1154 if (isa<PredicateAssume>(PI)) {
1155 // If the comparison is true when the operands are equal, then we know the
1156 // operands are equal, because assumes must always be true.
1157 if (CmpInst::isTrueWhenEqual(Predicate)) {
1158 addPredicateUsers(PI, I);
1159 return createVariableOrConstant(FirstOp);
1160 }
1161 }
1162 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1163 // If we are *not* a copy of the comparison, we may equal to the other
1164 // operand when the predicate implies something about equality of
1165 // operations. In particular, if the comparison is true/false when the
1166 // operands are equal, and we are on the right edge, we know this operation
1167 // is equal to something.
1168 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1169 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1170 addPredicateUsers(PI, I);
1171 return createVariableOrConstant(FirstOp);
1172 }
1173 // Handle the special case of floating point.
1174 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1175 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1176 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1177 addPredicateUsers(PI, I);
1178 return createConstantExpression(cast<Constant>(FirstOp));
1179 }
1180 }
1181 return nullptr;
1182}
1183
Davide Italiano7e274e02016-12-22 16:03:48 +00001184// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001185const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001186 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001187 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1188 // Instrinsics with the returned attribute are copies of arguments.
1189 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1190 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1191 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1192 return Result;
1193 return createVariableOrConstant(ReturnedValue);
1194 }
1195 }
1196 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001197 return createCallExpression(CI, TOPClass->RepMemoryAccess);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001198 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001199 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001200 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001201 }
1202 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001203}
1204
Daniel Berlin1316a942017-04-06 18:52:50 +00001205// Retrieve the memory class for a given MemoryAccess.
1206CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1207
1208 auto *Result = MemoryAccessToClass.lookup(MA);
1209 assert(Result && "Should have found memory class");
1210 return Result;
1211}
1212
1213// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001214// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001215bool NewGVN::setMemoryClass(const MemoryAccess *From,
1216 CongruenceClass *NewClass) {
1217 assert(NewClass &&
1218 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001219 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001220 DEBUG(dbgs() << " equivalent to congruence class ");
1221 DEBUG(dbgs() << NewClass->ID << " with current MemoryAccess leader ");
1222 DEBUG(dbgs() << *NewClass->RepMemoryAccess);
Daniel Berlin9f376b72017-01-29 10:26:03 +00001223 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001224
1225 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001226 bool Changed = false;
1227 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001228 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001229 auto *OldClass = LookupResult->second;
1230 if (OldClass != NewClass) {
1231 // If this is a phi, we have to handle memory member updates.
1232 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
1233 OldClass->MemoryMembers.erase(MP);
1234 NewClass->MemoryMembers.insert(MP);
1235 // This may have killed the class if it had no non-memory members
1236 if (OldClass->RepMemoryAccess == From) {
1237 if (OldClass->MemoryMembers.empty()) {
1238 OldClass->RepMemoryAccess = nullptr;
1239 } else {
1240 // TODO: Verify memory phi leader cycling is not possible
1241 OldClass->RepMemoryAccess = getNextMemoryLeader(OldClass);
1242 DEBUG(dbgs() << "Memory class leader change for class "
1243 << OldClass->ID << " to " << *OldClass->RepMemoryAccess
1244 << " due to removal of a memory member " << *From
1245 << "\n");
1246 markMemoryLeaderChangeTouched(OldClass);
1247 }
1248 }
1249 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001250 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001251 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001252 Changed = true;
1253 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001254 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001255
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001256 return Changed;
1257}
Daniel Berlin0e900112017-03-24 06:33:48 +00001258
Davide Italiano7e274e02016-12-22 16:03:48 +00001259// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001260const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001261 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001262 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1263
1264 // See if all arguaments are the same.
1265 // We track if any were undef because they need special handling.
1266 bool HasUndef = false;
1267 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1268 if (Arg == I)
1269 return false;
1270 if (isa<UndefValue>(Arg)) {
1271 HasUndef = true;
1272 return false;
1273 }
1274 return true;
1275 });
1276 // If we are left with no operands, it's undef
1277 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001278 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1279 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001280 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001281 return createConstantExpression(UndefValue::get(I->getType()));
1282 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001283 Value *AllSameValue = *(Filtered.begin());
1284 ++Filtered.begin();
1285 // Can't use std::equal here, sadly, because filter.begin moves.
1286 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
1287 return V == AllSameValue;
1288 })) {
1289 // In LLVM's non-standard representation of phi nodes, it's possible to have
1290 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1291 // on the original phi node), especially in weird CFG's where some arguments
1292 // are unreachable, or uninitialized along certain paths. This can cause
1293 // infinite loops during evaluation. We work around this by not trying to
1294 // really evaluate them independently, but instead using a variable
1295 // expression to say if one is equivalent to the other.
1296 // We also special case undef, so that if we have an undef, we can't use the
1297 // common value unless it dominates the phi block.
1298 if (HasUndef) {
1299 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001300 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001301 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001302 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001303 }
1304
Davide Italiano7e274e02016-12-22 16:03:48 +00001305 NumGVNPhisAllSame++;
1306 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1307 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001308 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001309 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001310 }
1311 return E;
1312}
1313
Daniel Berlin97718e62017-01-31 22:32:03 +00001314const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001315 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1316 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1317 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1318 unsigned Opcode = 0;
1319 // EI might be an extract from one of our recognised intrinsics. If it
1320 // is we'll synthesize a semantically equivalent expression instead on
1321 // an extract value expression.
1322 switch (II->getIntrinsicID()) {
1323 case Intrinsic::sadd_with_overflow:
1324 case Intrinsic::uadd_with_overflow:
1325 Opcode = Instruction::Add;
1326 break;
1327 case Intrinsic::ssub_with_overflow:
1328 case Intrinsic::usub_with_overflow:
1329 Opcode = Instruction::Sub;
1330 break;
1331 case Intrinsic::smul_with_overflow:
1332 case Intrinsic::umul_with_overflow:
1333 Opcode = Instruction::Mul;
1334 break;
1335 default:
1336 break;
1337 }
1338
1339 if (Opcode != 0) {
1340 // Intrinsic recognized. Grab its args to finish building the
1341 // expression.
1342 assert(II->getNumArgOperands() == 2 &&
1343 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001344 return createBinaryExpression(
1345 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001346 }
1347 }
1348 }
1349
Daniel Berlin97718e62017-01-31 22:32:03 +00001350 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001351}
Daniel Berlin97718e62017-01-31 22:32:03 +00001352const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001353 auto *CI = dyn_cast<CmpInst>(I);
1354 // See if our operands are equal to those of a previous predicate, and if so,
1355 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001356 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1357 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001358 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001359 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001360 std::swap(Op0, Op1);
1361 OurPredicate = CI->getSwappedPredicate();
1362 }
1363
1364 // Avoid processing the same info twice
1365 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001366 // See if we know something about the comparison itself, like it is the target
1367 // of an assume.
1368 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1369 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1370 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1371
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001372 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001373 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001374 if (CI->isTrueWhenEqual())
1375 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1376 else if (CI->isFalseWhenEqual())
1377 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1378 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001379
1380 // NOTE: Because we are comparing both operands here and below, and using
1381 // previous comparisons, we rely on fact that predicateinfo knows to mark
1382 // comparisons that use renamed operands as users of the earlier comparisons.
1383 // It is *not* enough to just mark predicateinfo renamed operands as users of
1384 // the earlier comparisons, because the *other* operand may have changed in a
1385 // previous iteration.
1386 // Example:
1387 // icmp slt %a, %b
1388 // %b.0 = ssa.copy(%b)
1389 // false branch:
1390 // icmp slt %c, %b.0
1391
1392 // %c and %a may start out equal, and thus, the code below will say the second
1393 // %icmp is false. c may become equal to something else, and in that case the
1394 // %second icmp *must* be reexamined, but would not if only the renamed
1395 // %operands are considered users of the icmp.
1396
1397 // *Currently* we only check one level of comparisons back, and only mark one
1398 // level back as touched when changes appen . If you modify this code to look
1399 // back farther through comparisons, you *must* mark the appropriate
1400 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1401 // we know something just from the operands themselves
1402
1403 // See if our operands have predicate info, so that we may be able to derive
1404 // something from a previous comparison.
1405 for (const auto &Op : CI->operands()) {
1406 auto *PI = PredInfo->getPredicateInfoFor(Op);
1407 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1408 if (PI == LastPredInfo)
1409 continue;
1410 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001411
Daniel Berlinf7d95802017-02-18 23:06:50 +00001412 // TODO: Along the false edge, we may know more things too, like icmp of
1413 // same operands is false.
1414 // TODO: We only handle actual comparison conditions below, not and/or.
1415 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1416 if (!BranchCond)
1417 continue;
1418 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1419 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1420 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001421 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001422 std::swap(BranchOp0, BranchOp1);
1423 BranchPredicate = BranchCond->getSwappedPredicate();
1424 }
1425 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1426 if (PBranch->TrueEdge) {
1427 // If we know the previous predicate is true and we are in the true
1428 // edge then we may be implied true or false.
1429 if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate,
1430 BranchPredicate)) {
1431 addPredicateUsers(PI, I);
1432 return createConstantExpression(
1433 ConstantInt::getTrue(CI->getType()));
1434 }
1435
1436 if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate,
1437 BranchPredicate)) {
1438 addPredicateUsers(PI, I);
1439 return createConstantExpression(
1440 ConstantInt::getFalse(CI->getType()));
1441 }
1442
1443 } else {
1444 // Just handle the ne and eq cases, where if we have the same
1445 // operands, we may know something.
1446 if (BranchPredicate == OurPredicate) {
1447 addPredicateUsers(PI, I);
1448 // Same predicate, same ops,we know it was false, so this is false.
1449 return createConstantExpression(
1450 ConstantInt::getFalse(CI->getType()));
1451 } else if (BranchPredicate ==
1452 CmpInst::getInversePredicate(OurPredicate)) {
1453 addPredicateUsers(PI, I);
1454 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001455 return createConstantExpression(
1456 ConstantInt::getTrue(CI->getType()));
1457 }
1458 }
1459 }
1460 }
1461 }
1462 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001463 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001464}
Davide Italiano7e274e02016-12-22 16:03:48 +00001465
1466// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001467const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001468 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001469 if (auto *C = dyn_cast<Constant>(V))
1470 E = createConstantExpression(C);
1471 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1472 E = createVariableExpression(V);
1473 } else {
1474 // TODO: memory intrinsics.
1475 // TODO: Some day, we should do the forward propagation and reassociation
1476 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001477 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001478 switch (I->getOpcode()) {
1479 case Instruction::ExtractValue:
1480 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001481 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001482 break;
1483 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001484 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001485 break;
1486 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001487 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001488 break;
1489 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001490 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001491 break;
1492 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001493 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001494 break;
1495 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001496 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001497 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001498 case Instruction::ICmp:
1499 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001500 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001501 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001502 case Instruction::Add:
1503 case Instruction::FAdd:
1504 case Instruction::Sub:
1505 case Instruction::FSub:
1506 case Instruction::Mul:
1507 case Instruction::FMul:
1508 case Instruction::UDiv:
1509 case Instruction::SDiv:
1510 case Instruction::FDiv:
1511 case Instruction::URem:
1512 case Instruction::SRem:
1513 case Instruction::FRem:
1514 case Instruction::Shl:
1515 case Instruction::LShr:
1516 case Instruction::AShr:
1517 case Instruction::And:
1518 case Instruction::Or:
1519 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001520 case Instruction::Trunc:
1521 case Instruction::ZExt:
1522 case Instruction::SExt:
1523 case Instruction::FPToUI:
1524 case Instruction::FPToSI:
1525 case Instruction::UIToFP:
1526 case Instruction::SIToFP:
1527 case Instruction::FPTrunc:
1528 case Instruction::FPExt:
1529 case Instruction::PtrToInt:
1530 case Instruction::IntToPtr:
1531 case Instruction::Select:
1532 case Instruction::ExtractElement:
1533 case Instruction::InsertElement:
1534 case Instruction::ShuffleVector:
1535 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001536 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001537 break;
1538 default:
1539 return nullptr;
1540 }
1541 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001542 return E;
1543}
1544
Davide Italiano7e274e02016-12-22 16:03:48 +00001545void NewGVN::markUsersTouched(Value *V) {
1546 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001547 for (auto *User : V->users()) {
1548 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001549 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001550 }
1551}
1552
Daniel Berlin1316a942017-04-06 18:52:50 +00001553void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) {
1554 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1555 MemoryToUsers[To].insert(U);
1556}
1557
1558void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
1559 TouchedInstructions.set(getMemoryInstrNum(MA));
1560}
1561
1562void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1563 if (isa<MemoryUse>(MA))
1564 return;
1565 for (auto U : MA->users())
1566 TouchedInstructions.set(getMemoryInstrNum(U));
1567 const auto Result = MemoryToUsers.find(MA);
1568 if (Result != MemoryToUsers.end()) {
1569 for (auto *User : Result->second)
1570 TouchedInstructions.set(getMemoryInstrNum(User));
1571 MemoryToUsers.erase(Result);
Davide Italiano7e274e02016-12-22 16:03:48 +00001572 }
1573}
1574
Daniel Berlinf7d95802017-02-18 23:06:50 +00001575// Add I to the set of users of a given predicate.
1576void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1577 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1578 PredicateToUsers[PBranch->Condition].insert(I);
1579 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1580 PredicateToUsers[PAssume->Condition].insert(I);
1581}
1582
1583// Touch all the predicates that depend on this instruction.
1584void NewGVN::markPredicateUsersTouched(Instruction *I) {
1585 const auto Result = PredicateToUsers.find(I);
Daniel Berlin46b72e62017-03-19 00:07:32 +00001586 if (Result != PredicateToUsers.end()) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001587 for (auto *User : Result->second)
1588 TouchedInstructions.set(InstrDFS.lookup(User));
Daniel Berlin46b72e62017-03-19 00:07:32 +00001589 PredicateToUsers.erase(Result);
1590 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001591}
1592
Daniel Berlin1316a942017-04-06 18:52:50 +00001593// Mark users affected by a memory leader change.
1594void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
1595 for (auto M : CC->MemoryMembers)
1596 markMemoryDefTouched(M);
1597}
1598
Daniel Berlin32f8d562017-01-07 16:55:14 +00001599// Touch the instructions that need to be updated after a congruence class has a
1600// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00001601void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001602 for (auto M : CC->Members) {
1603 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001604 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001605 LeaderChanges.insert(M);
1606 }
1607}
1608
Daniel Berlin1316a942017-04-06 18:52:50 +00001609// Give a range of things that have instruction DFS numbers, this will return
1610// the member of the range with the smallest dfs number.
1611template <class T, class Range>
1612T *NewGVN::getMinDFSOfRange(const Range &R) const {
1613 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
1614 for (const auto X : R) {
1615 auto DFSNum = getInstrNum(X);
1616 if (DFSNum < MinDFS.second)
1617 MinDFS = {X, DFSNum};
1618 }
1619 return MinDFS.first;
1620}
1621
1622// This function returns the MemoryAccess that should be the next leader of
1623// congruence class CC, under the assumption that the current leader is going to
1624// disappear.
1625const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
1626 // TODO: If this ends up to slow, we can maintain a next memory leader like we
1627 // do for regular leaders.
1628 // Make sure there will be a leader to find
1629 assert(CC->StoreCount > 0 ||
1630 !CC->MemoryMembers.empty() &&
1631 "Can't get next leader if there is none");
1632 if (CC->StoreCount > 0) {
1633 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->NextLeader.first))
1634 return MSSA->getMemoryAccess(NL);
1635 // Find the store with the minimum DFS number.
1636 auto *V = getMinDFSOfRange<Value>(make_filter_range(
1637 CC->Members, [&](const Value *V) { return isa<StoreInst>(V); }));
1638 return MSSA->getMemoryAccess(cast<StoreInst>(V));
1639 }
1640 assert(CC->StoreCount == 0);
1641
1642 // Given our assertion, hitting this part must mean
1643 // !OldClass->MemoryMembers.empty()
1644 if (CC->MemoryMembers.size() == 1)
1645 return *CC->MemoryMembers.begin();
1646 return getMinDFSOfRange<const MemoryPhi>(CC->MemoryMembers);
1647}
1648
1649// This function returns the next value leader of a congruence class, under the
1650// assumption that the current leader is going away. This should end up being
1651// the next most dominating member.
1652Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
1653 // We don't need to sort members if there is only 1, and we don't care about
1654 // sorting the TOP class because everything either gets out of it or is
1655 // unreachable.
1656
1657 if (CC->Members.size() == 1 || CC == TOPClass) {
1658 return *(CC->Members.begin());
1659 } else if (CC->NextLeader.first) {
1660 ++NumGVNAvoidedSortedLeaderChanges;
1661 return CC->NextLeader.first;
1662 } else {
1663 ++NumGVNSortedLeaderChanges;
1664 // NOTE: If this ends up to slow, we can maintain a dual structure for
1665 // member testing/insertion, or keep things mostly sorted, and sort only
1666 // here, or use SparseBitVector or ....
1667 return getMinDFSOfRange<Value>(CC->Members);
1668 }
1669}
1670
1671// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
1672// the memory members, etc for the move.
1673//
1674// The invariants of this function are:
1675//
1676// I must be moving to NewClass from OldClass The StoreCount of OldClass and
1677// NewClass is expected to have been updated for I already if it is is a store.
1678// The OldClass memory leader has not been updated yet if I was the leader.
1679void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
1680 MemoryAccess *InstMA,
1681 CongruenceClass *OldClass,
1682 CongruenceClass *NewClass) {
1683 // If the leader is I, and we had a represenative MemoryAccess, it should
1684 // be the MemoryAccess of OldClass.
1685 assert(!InstMA || !OldClass->RepMemoryAccess || OldClass->RepLeader != I ||
1686 OldClass->RepMemoryAccess == InstMA &&
1687 "Representative MemoryAccess mismatch");
1688 // First, see what happens to the new class
1689 if (!NewClass->RepMemoryAccess) {
1690 // Should be a new class, or a store becoming a leader of a new class.
1691 assert(NewClass->Members.size() == 1 ||
1692 (isa<StoreInst>(I) && NewClass->StoreCount == 1));
1693 NewClass->RepMemoryAccess = InstMA;
1694 // Mark it touched if we didn't just create a singleton
1695 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->ID
1696 << " due to new memory instruction becoming leader\n");
1697 markMemoryLeaderChangeTouched(NewClass);
1698 }
1699 setMemoryClass(InstMA, NewClass);
1700 // Now, fixup the old class if necessary
1701 if (OldClass->RepMemoryAccess == InstMA) {
1702 if (OldClass->StoreCount != 0 || !OldClass->MemoryMembers.empty()) {
1703 OldClass->RepMemoryAccess = getNextMemoryLeader(OldClass);
1704 DEBUG(dbgs() << "Memory class leader change for class " << OldClass->ID
1705 << " to " << *OldClass->RepMemoryAccess
1706 << " due to removal of old leader " << *InstMA << "\n");
1707 markMemoryLeaderChangeTouched(OldClass);
1708 } else
1709 OldClass->RepMemoryAccess = nullptr;
1710 }
1711}
1712
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001713// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00001714// Update OldClass and NewClass for the move (including changing leaders, etc).
1715void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001716 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001717 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001718 if (I == OldClass->NextLeader.first)
1719 OldClass->NextLeader = {nullptr, ~0U};
1720
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001721 // It's possible, though unlikely, for us to discover equivalences such
1722 // that the current leader does not dominate the old one.
1723 // This statistic tracks how often this happens.
1724 // We assert on phi nodes when this happens, currently, for debugging, because
1725 // we want to make sure we name phi node cycles properly.
1726 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001727 I != NewClass->RepLeader) {
1728 auto *IBB = I->getParent();
1729 auto *NCBB = cast<Instruction>(NewClass->RepLeader)->getParent();
1730 bool Dominated = IBB == NCBB &&
1731 InstrDFS.lookup(I) < InstrDFS.lookup(NewClass->RepLeader);
1732 Dominated = Dominated || DT->properlyDominates(IBB, NCBB);
1733 if (Dominated) {
1734 ++NumGVNNotMostDominatingLeader;
1735 assert(
1736 !isa<PHINode>(I) &&
1737 "New class for instruction should not be dominated by instruction");
1738 }
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001739 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001740
1741 if (NewClass->RepLeader != I) {
1742 auto DFSNum = InstrDFS.lookup(I);
1743 if (DFSNum < NewClass->NextLeader.second)
1744 NewClass->NextLeader = {I, DFSNum};
1745 }
1746
1747 OldClass->Members.erase(I);
1748 NewClass->Members.insert(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00001749 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001750 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001751 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001752 assert(OldClass->StoreCount >= 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001753 // Okay, so when do we want to make a store a leader of a class? If we have
1754 // a store defined by an earlier load, we want the earlier load to lead the
1755 // class. If we have a store defined by something else, we want the store
1756 // to lead the class so everything else gets the "something else" as a
1757 // value.
1758 // If we have a store as the single member of the class, we want the store
1759 // as the leader.
1760 if (NewClass->StoreCount == 0 && !NewClass->RepStoredValue) {
1761 // If it's a store expression we are using, it means we are not equivalent
1762 // to something earlier.
1763 if (isa<StoreExpression>(E)) {
1764 assert(lookupOperandLeader(SI->getValueOperand()) !=
1765 NewClass->RepLeader);
1766 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
1767 markValueLeaderChangeTouched(NewClass);
1768 // Shift the new class leader to be the store
1769 DEBUG(dbgs() << "Changing leader of congruence class " << NewClass->ID
1770 << " from " << *NewClass->RepLeader << " to " << *SI
1771 << " because store joined class\n");
1772 // If we changed the leader, we have to mark it changed because we don't
1773 // know what it will do to symbolic evlauation.
1774 NewClass->RepLeader = SI;
1775 }
1776 // We rely on the code below handling the MemoryAccess change.
1777 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001778 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001779 assert(NewClass->StoreCount > 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001780 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001781 // True if there is no memory instructions left in a class that had memory
1782 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001783
Daniel Berlin1316a942017-04-06 18:52:50 +00001784 // If it's not a memory use, set the MemoryAccess equivalence
1785 auto *InstMA = dyn_cast_or_null<MemoryDef>(MSSA->getMemoryAccess(I));
1786 bool InstWasMemoryLeader = InstMA && OldClass->RepMemoryAccess == InstMA;
1787 if (InstMA)
1788 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001789 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001790 // See if we destroyed the class or need to swap leaders.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001791 if (OldClass->Members.empty() && OldClass != TOPClass) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001792 if (OldClass->DefiningExpr) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001793 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1794 << " from table\n");
1795 ExpressionToClass.erase(OldClass->DefiningExpr);
1796 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001797 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001798 // When the leader changes, the value numbering of
1799 // everything may change due to symbolization changes, so we need to
1800 // reprocess.
Daniel Berlin1316a942017-04-06 18:52:50 +00001801 DEBUG(dbgs() << "Value class leader change for class " << OldClass->ID
1802 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001803 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001804 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00001805 // Note that this is basically clean up for the expression removal that
1806 // happens below. If we remove stores from a class, we may leave it as a
1807 // class of equivalent memory phis.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001808 if (OldClass->StoreCount == 0) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001809 if (OldClass->RepStoredValue)
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001810 OldClass->RepStoredValue = nullptr;
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001811 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001812 // If we destroy the old access leader and it's a store, we have to
1813 // effectively destroy the congruence class. When it comes to scalars,
1814 // anything with the same value is as good as any other. That means that
1815 // one leader is as good as another, and as long as you have some leader for
1816 // the value, you are good.. When it comes to *memory states*, only one
1817 // particular thing really represents the definition of a given memory
1818 // state. Once it goes away, we need to re-evaluate which pieces of memory
1819 // are really still equivalent. The best way to do this is to re-value
1820 // number things. The only way to really make that happen is to destroy the
1821 // rest of the class. In order to effectively destroy the class, we reset
1822 // ExpressionToClass for each by using the ValueToExpression mapping. The
1823 // members later get marked as touched due to the leader change. We will
1824 // create new congruence classes, and the pieces that are still equivalent
1825 // will end back together in a new class. If this becomes too expensive, it
1826 // is possible to use a versioning scheme for the congruence classes to
1827 // avoid the expressions finding this old class. Note that the situation is
1828 // different for memory phis, becuase they are evaluated anew each time, and
1829 // they become equal not by hashing, but by seeing if all operands are the
1830 // same (or only one is reachable).
1831 if (OldClass->StoreCount > 0 && InstWasMemoryLeader) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001832 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
Daniel Berlin1316a942017-04-06 18:52:50 +00001833 << " because MemoryAccess leader changed");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001834 for (auto Member : OldClass->Members)
1835 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1836 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001837 OldClass->RepLeader = getNextValueLeader(OldClass);
1838 OldClass->NextLeader = {nullptr, ~0U};
1839 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001840 }
1841}
1842
Davide Italiano7e274e02016-12-22 16:03:48 +00001843// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001844void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1845 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001846 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001847 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001848
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001849 CongruenceClass *IClass = ValueToClass[I];
1850 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001851 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00001852 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001853
1854 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001855 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001856 EClass = ValueToClass[VE->getVariableValue()];
1857 } else {
1858 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1859
1860 // If it's not in the value table, create a new congruence class.
1861 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001862 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001863 auto place = lookupResult.first;
1864 place->second = NewClass;
1865
1866 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001867 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001868 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001869 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1870 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001871 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001872 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001873 // The RepMemoryAccess field will be filled in properly by the
1874 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001875 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001876 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001877 }
1878 assert(!isa<VariableExpression>(E) &&
1879 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001880
1881 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001882 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001883 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001884 << " and leader " << *(NewClass->RepLeader));
1885 if (NewClass->RepStoredValue)
1886 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1887 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001888 } else {
1889 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001890 if (isa<ConstantExpression>(E))
Daniel Berlin1316a942017-04-06 18:52:50 +00001891 assert(
1892 isa<Constant>(EClass->RepLeader) ||
1893 (EClass->RepStoredValue && isa<Constant>(EClass->RepStoredValue)) &&
1894 "Any class with a constant expression should have a "
1895 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001896
Davide Italiano7e274e02016-12-22 16:03:48 +00001897 assert(EClass && "Somehow don't have an eclass");
1898
Daniel Berlin1316a942017-04-06 18:52:50 +00001899 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001900 }
1901 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001902 bool ClassChanged = IClass != EClass;
1903 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001904 if (ClassChanged || LeaderChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001905 DEBUG(dbgs() << "New class " << EClass->ID << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00001906 << "\n");
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001907 if (ClassChanged)
Daniel Berlin1316a942017-04-06 18:52:50 +00001908 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001909 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001910 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001911 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001912 if (auto *CI = dyn_cast<CmpInst>(I))
1913 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00001914 }
1915}
1916
1917// Process the fact that Edge (from, to) is reachable, including marking
1918// any newly reachable blocks and instructions for processing.
1919void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1920 // Check if the Edge was reachable before.
1921 if (ReachableEdges.insert({From, To}).second) {
1922 // If this block wasn't reachable before, all instructions are touched.
1923 if (ReachableBlocks.insert(To).second) {
1924 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1925 const auto &InstRange = BlockInstRange.lookup(To);
1926 TouchedInstructions.set(InstRange.first, InstRange.second);
1927 } else {
1928 DEBUG(dbgs() << "Block " << getBlockName(To)
1929 << " was reachable, but new edge {" << getBlockName(From)
1930 << "," << getBlockName(To) << "} to it found\n");
1931
1932 // We've made an edge reachable to an existing block, which may
1933 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1934 // they are the only thing that depend on new edges. Anything using their
1935 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001936 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001937 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001938
Davide Italiano7e274e02016-12-22 16:03:48 +00001939 auto BI = To->begin();
1940 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001941 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001942 ++BI;
1943 }
1944 }
1945 }
1946}
1947
1948// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1949// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001950Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001951 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001952 if (isa<Constant>(Result))
1953 return Result;
1954 return nullptr;
1955}
1956
1957// Process the outgoing edges of a block for reachability.
1958void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1959 // Evaluate reachability of terminator instruction.
1960 BranchInst *BR;
1961 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1962 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001963 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001964 if (!CondEvaluated) {
1965 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001966 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001967 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1968 CondEvaluated = CE->getConstantValue();
1969 }
1970 } else if (isa<ConstantInt>(Cond)) {
1971 CondEvaluated = Cond;
1972 }
1973 }
1974 ConstantInt *CI;
1975 BasicBlock *TrueSucc = BR->getSuccessor(0);
1976 BasicBlock *FalseSucc = BR->getSuccessor(1);
1977 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1978 if (CI->isOne()) {
1979 DEBUG(dbgs() << "Condition for Terminator " << *TI
1980 << " evaluated to true\n");
1981 updateReachableEdge(B, TrueSucc);
1982 } else if (CI->isZero()) {
1983 DEBUG(dbgs() << "Condition for Terminator " << *TI
1984 << " evaluated to false\n");
1985 updateReachableEdge(B, FalseSucc);
1986 }
1987 } else {
1988 updateReachableEdge(B, TrueSucc);
1989 updateReachableEdge(B, FalseSucc);
1990 }
1991 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1992 // For switches, propagate the case values into the case
1993 // destinations.
1994
1995 // Remember how many outgoing edges there are to every successor.
1996 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1997
Davide Italiano7e274e02016-12-22 16:03:48 +00001998 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001999 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002000 // See if we were able to turn this switch statement into a constant.
2001 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002002 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002003 // We should be able to get case value for this.
2004 auto CaseVal = SI->findCaseValue(CondVal);
2005 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
2006 // We proved the value is outside of the range of the case.
2007 // We can't do anything other than mark the default dest as reachable,
2008 // and go home.
2009 updateReachableEdge(B, SI->getDefaultDest());
2010 return;
2011 }
2012 // Now get where it goes and mark it reachable.
2013 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
2014 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002015 } else {
2016 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2017 BasicBlock *TargetBlock = SI->getSuccessor(i);
2018 ++SwitchEdges[TargetBlock];
2019 updateReachableEdge(B, TargetBlock);
2020 }
2021 }
2022 } else {
2023 // Otherwise this is either unconditional, or a type we have no
2024 // idea about. Just mark successors as reachable.
2025 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2026 BasicBlock *TargetBlock = TI->getSuccessor(i);
2027 updateReachableEdge(B, TargetBlock);
2028 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002029
2030 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002031 // equivalent only to itself.
2032 //
2033 auto *MA = MSSA->getMemoryAccess(TI);
2034 if (MA && !isa<MemoryUse>(MA)) {
2035 auto *CC = ensureLeaderOfMemoryClass(MA);
2036 if (setMemoryClass(MA, CC))
2037 markMemoryUsersTouched(MA);
2038 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002039 }
2040}
2041
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002042// The algorithm initially places the values of the routine in the TOP
2043// congruence class. The leader of TOP is the undetermined value `undef`.
2044// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002045void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002046 NextCongruenceNum = 0;
2047
2048 // Note that even though we use the live on entry def as a representative
2049 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2050 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2051 // should be checking whether the MemoryAccess is top if we want to know if it
2052 // is equivalent to everything. Otherwise, what this really signifies is that
2053 // the access "it reaches all the way back to the beginning of the function"
2054
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002055 // Initialize all other instructions to be in TOP class.
Davide Italiano7e274e02016-12-22 16:03:48 +00002056 CongruenceClass::MemberSet InitialValues;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002057 TOPClass = createCongruenceClass(nullptr, nullptr);
2058 TOPClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin1316a942017-04-06 18:52:50 +00002059 // The live on entry def gets put into it's own class
2060 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2061 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002062
Daniel Berlin1316a942017-04-06 18:52:50 +00002063 for (auto &B : F) {
2064 // All MemoryAccesses are equivalent to live on entry to start. They must
2065 // be initialized to something so that initial changes are noticed. For
2066 // the maximal answer, we initialize them all to be the same as
2067 // liveOnEntry.
2068 auto *MemoryBlockDefs = MSSA->getBlockDefs(&B);
2069 if (MemoryBlockDefs)
2070 for (const auto &Def : *MemoryBlockDefs) {
2071 MemoryAccessToClass[&Def] = TOPClass;
2072 auto *MD = dyn_cast<MemoryDef>(&Def);
2073 // Insert the memory phis into the member list.
2074 if (!MD) {
2075 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
2076 TOPClass->MemoryMembers.insert(MP);
2077 MemoryPhiState.insert({MP, MPS_TOP});
2078 }
2079
2080 if (MD && isa<StoreInst>(MD->getMemoryInst()))
2081 ++TOPClass->StoreCount;
2082 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002083 for (auto &I : B) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00002084 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002085 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002086 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2087 continue;
2088 InitialValues.insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002089 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002090 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002091 }
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002092 TOPClass->Members.swap(InitialValues);
Davide Italiano7e274e02016-12-22 16:03:48 +00002093
2094 // Initialize arguments to be in their own unique congruence classes
2095 for (auto &FA : F.args())
2096 createSingletonCongruenceClass(&FA);
2097}
2098
2099void NewGVN::cleanupTables() {
2100 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
2101 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
2102 << CongruenceClasses[i]->Members.size() << " members\n");
2103 // Make sure we delete the congruence class (probably worth switching to
2104 // a unique_ptr at some point.
2105 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002106 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002107 }
2108
2109 ValueToClass.clear();
2110 ArgRecycler.clear(ExpressionAllocator);
2111 ExpressionAllocator.Reset();
2112 CongruenceClasses.clear();
2113 ExpressionToClass.clear();
2114 ValueToExpression.clear();
2115 ReachableBlocks.clear();
2116 ReachableEdges.clear();
2117#ifndef NDEBUG
2118 ProcessedCount.clear();
2119#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002120 InstrDFS.clear();
2121 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002122 DFSToInstr.clear();
2123 BlockInstRange.clear();
2124 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002125 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002126 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002127 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002128}
2129
2130std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2131 unsigned Start) {
2132 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002133 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
2134 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002135 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002136 }
2137
Davide Italiano7e274e02016-12-22 16:03:48 +00002138 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002139 // There's no need to call isInstructionTriviallyDead more than once on
2140 // an instruction. Therefore, once we know that an instruction is dead
2141 // we change its DFS number so that it doesn't get value numbered.
2142 if (isInstructionTriviallyDead(&I, TLI)) {
2143 InstrDFS[&I] = 0;
2144 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2145 markInstructionForDeletion(&I);
2146 continue;
2147 }
2148
Davide Italiano7e274e02016-12-22 16:03:48 +00002149 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002150 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002151 }
2152
2153 // All of the range functions taken half-open ranges (open on the end side).
2154 // So we do not subtract one from count, because at this point it is one
2155 // greater than the last instruction.
2156 return std::make_pair(Start, End);
2157}
2158
2159void NewGVN::updateProcessedCount(Value *V) {
2160#ifndef NDEBUG
2161 if (ProcessedCount.count(V) == 0) {
2162 ProcessedCount.insert({V, 1});
2163 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002164 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002165 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002166 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002167 }
2168#endif
2169}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002170// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2171void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2172 // If all the arguments are the same, the MemoryPhi has the same value as the
2173 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00002174 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00002175 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002176 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002177 return lookupMemoryLeader(cast<MemoryAccess>(U)) != MP &&
Daniel Berlinc4796862017-01-27 02:37:11 +00002178 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002179 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002180 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002181 // If all that is left is nothing, our memoryphi is undef. We keep it as
2182 // InitialClass. Note: The only case this should happen is if we have at
2183 // least one self-argument.
2184 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002185 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002186 markMemoryUsersTouched(MP);
2187 return;
2188 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002189
2190 // Transform the remaining operands into operand leaders.
2191 // FIXME: mapped_iterator should have a range version.
2192 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002193 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002194 };
2195 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2196 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2197
2198 // and now check if all the elements are equal.
2199 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002200 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002201 ++MappedBegin;
2202 bool AllEqual = std::all_of(
2203 MappedBegin, MappedEnd,
2204 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2205
2206 if (AllEqual)
2207 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2208 else
2209 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002210 // If it's equal to something, it's in that class. Otherwise, it has to be in
2211 // a class where it is the leader (other things may be equivalent to it, but
2212 // it needs to start off in its own class, which means it must have been the
2213 // leader, and it can't have stopped being the leader because it was never
2214 // removed).
2215 CongruenceClass *CC =
2216 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2217 auto OldState = MemoryPhiState.lookup(MP);
2218 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2219 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2220 MemoryPhiState[MP] = NewState;
2221 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002222 markMemoryUsersTouched(MP);
2223}
2224
2225// Value number a single instruction, symbolically evaluating, performing
2226// congruence finding, and updating mappings.
2227void NewGVN::valueNumberInstruction(Instruction *I) {
2228 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002229 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002230 const Expression *Symbolized = nullptr;
2231 if (DebugCounter::shouldExecute(VNCounter)) {
2232 Symbolized = performSymbolicEvaluation(I);
2233 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002234 // Mark the instruction as unused so we don't value number it again.
2235 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002236 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002237 // If we couldn't come up with a symbolic expression, use the unknown
2238 // expression
Daniel Berlin1316a942017-04-06 18:52:50 +00002239 if (Symbolized == nullptr) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002240 Symbolized = createUnknownExpression(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00002241 }
2242
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002243 performCongruenceFinding(I, Symbolized);
2244 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002245 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002246 // don't currently understand. We don't place non-value producing
2247 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002248 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002249 auto *Symbolized = createUnknownExpression(I);
2250 performCongruenceFinding(I, Symbolized);
2251 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002252 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2253 }
2254}
Davide Italiano7e274e02016-12-22 16:03:48 +00002255
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002256// Check if there is a path, using single or equal argument phi nodes, from
2257// First to Second.
2258bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
2259 const MemoryAccess *Second) const {
2260 if (First == Second)
2261 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002262 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002263 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002264
Daniel Berlin871ecd92017-04-01 09:44:24 +00002265 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002266 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002267 if (ChainDef == Second)
2268 return true;
2269 if (MSSA->isLiveOnEntryDef(ChainDef))
2270 return false;
2271 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002272 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002273 auto *MP = cast<MemoryPhi>(EndDef);
2274 auto ReachableOperandPred = [&](const Use &U) {
2275 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2276 };
2277 auto FilteredPhiArgs =
2278 make_filter_range(MP->operands(), ReachableOperandPred);
2279 SmallVector<const Value *, 32> OperandList;
2280 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2281 std::back_inserter(OperandList));
2282 bool Okay = OperandList.size() == 1;
2283 if (!Okay)
2284 Okay =
2285 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2286 if (Okay)
2287 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
2288 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002289}
2290
Daniel Berlin589cecc2017-01-02 18:00:46 +00002291// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002292// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002293// subject to very rare false negatives. It is only useful for
2294// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002295void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002296#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002297 // Verify that the memory table equivalence and memory member set match
2298 for (const auto *CC : CongruenceClasses) {
2299 if (CC == TOPClass || CC->isDead())
2300 continue;
2301 if (CC->StoreCount != 0) {
2302 assert(CC->RepStoredValue ||
2303 !isa<StoreInst>(CC->RepLeader) && "Any class with a store as a "
2304 "leader should have a "
2305 "representative stored value\n");
2306 assert(CC->RepMemoryAccess && "Any congruence class with a store should "
2307 "have a representative access\n");
2308 }
2309
2310 if (CC->RepMemoryAccess)
2311 assert(MemoryAccessToClass.lookup(CC->RepMemoryAccess) == CC &&
2312 "Representative MemoryAccess does not appear to be reverse "
2313 "mapped properly");
2314 for (auto M : CC->MemoryMembers)
2315 assert(MemoryAccessToClass.lookup(M) == CC &&
2316 "Memory member does not appear to be reverse mapped properly");
2317 }
2318
2319 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002320 // congruence class.
2321
2322 // Filter out the unreachable and trivially dead entries, because they may
2323 // never have been updated if the instructions were not processed.
2324 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002325 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002326 bool Result = ReachableBlocks.count(Pair.first->getBlock());
2327 if (!Result)
2328 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002329 if (MSSA->isLiveOnEntryDef(Pair.first))
2330 return true;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002331 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2332 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Daniel Berlin1316a942017-04-06 18:52:50 +00002333 if (getMemoryInstrNum(Pair.first) == 0)
2334 return false;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002335 return true;
2336 };
2337
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002338 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002339 for (auto KV : Filtered) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002340 assert(KV.second != TOPClass &&
2341 "Memory not unreachable but ended up in TOP");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002342 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002343 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00002344 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00002345 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002346 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2347 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2348 "The instructions for these memory operations should have "
2349 "been in the same congruence class or reachable through"
2350 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002351 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002352 // We can only sanely verify that MemoryDefs in the operand list all have
2353 // the same class.
2354 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002355 return ReachableEdges.count(
2356 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002357 isa<MemoryDef>(U);
2358
2359 };
2360 // All arguments should in the same class, ignoring unreachable arguments
2361 auto FilteredPhiArgs =
2362 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2363 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2364 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2365 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2366 const MemoryDef *MD = cast<MemoryDef>(U);
2367 return ValueToClass.lookup(MD->getMemoryInst());
2368 });
2369 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2370 PhiOpClasses.begin()) &&
2371 "All MemoryPhi arguments should be in the same class");
2372 }
2373 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002374#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002375}
2376
Daniel Berlin06329a92017-03-18 15:41:40 +00002377// Verify that the sparse propagation we did actually found the maximal fixpoint
2378// We do this by storing the value to class mapping, touching all instructions,
2379// and redoing the iteration to see if anything changed.
2380void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002381#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002382 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002383 if (DebugCounter::isCounterSet(VNCounter))
2384 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2385
2386 // Note that we have to store the actual classes, as we may change existing
2387 // classes during iteration. This is because our memory iteration propagation
2388 // is not perfect, and so may waste a little work. But it should generate
2389 // exactly the same congruence classes we have now, with different IDs.
2390 std::map<const Value *, CongruenceClass> BeforeIteration;
2391
2392 for (auto &KV : ValueToClass) {
2393 if (auto *I = dyn_cast<Instruction>(KV.first))
2394 // Skip unused/dead instructions.
2395 if (InstrDFS.lookup(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002396 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002397 BeforeIteration.insert({KV.first, *KV.second});
2398 }
2399
2400 TouchedInstructions.set();
2401 TouchedInstructions.reset(0);
2402 iterateTouchedInstructions();
2403 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2404 EqualClasses;
2405 for (const auto &KV : ValueToClass) {
2406 if (auto *I = dyn_cast<Instruction>(KV.first))
2407 // Skip unused/dead instructions.
2408 if (InstrDFS.lookup(I) == 0)
2409 continue;
2410 // We could sink these uses, but i think this adds a bit of clarity here as
2411 // to what we are comparing.
2412 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2413 auto *AfterCC = KV.second;
2414 // Note that the classes can't change at this point, so we memoize the set
2415 // that are equal.
2416 if (!EqualClasses.count({BeforeCC, AfterCC})) {
2417 assert(areClassesEquivalent(BeforeCC, AfterCC) &&
2418 "Value number changed after main loop completed!");
2419 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002420 }
2421 }
2422#endif
2423}
2424
Daniel Berlin06329a92017-03-18 15:41:40 +00002425// This is the main value numbering loop, it iterates over the initial touched
2426// instruction set, propagating value numbers, marking things touched, etc,
2427// until the set of touched instructions is completely empty.
2428void NewGVN::iterateTouchedInstructions() {
2429 unsigned int Iterations = 0;
2430 // Figure out where touchedinstructions starts
2431 int FirstInstr = TouchedInstructions.find_first();
2432 // Nothing set, nothing to iterate, just return.
2433 if (FirstInstr == -1)
2434 return;
2435 BasicBlock *LastBlock = getBlockForValue(DFSToInstr[FirstInstr]);
2436 while (TouchedInstructions.any()) {
2437 ++Iterations;
2438 // Walk through all the instructions in all the blocks in RPO.
2439 // TODO: As we hit a new block, we should push and pop equalities into a
2440 // table lookupOperandLeader can use, to catch things PredicateInfo
2441 // might miss, like edge-only equivalences.
2442 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2443 InstrNum = TouchedInstructions.find_next(InstrNum)) {
2444
2445 // This instruction was found to be dead. We don't bother looking
2446 // at it again.
2447 if (InstrNum == 0) {
2448 TouchedInstructions.reset(InstrNum);
2449 continue;
2450 }
2451
2452 Value *V = DFSToInstr[InstrNum];
2453 BasicBlock *CurrBlock = getBlockForValue(V);
2454
2455 // If we hit a new block, do reachability processing.
2456 if (CurrBlock != LastBlock) {
2457 LastBlock = CurrBlock;
2458 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2459 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2460
2461 // If it's not reachable, erase any touched instructions and move on.
2462 if (!BlockReachable) {
2463 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2464 DEBUG(dbgs() << "Skipping instructions in block "
2465 << getBlockName(CurrBlock)
2466 << " because it is unreachable\n");
2467 continue;
2468 }
2469 updateProcessedCount(CurrBlock);
2470 }
2471
2472 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2473 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2474 valueNumberMemoryPhi(MP);
2475 } else if (auto *I = dyn_cast<Instruction>(V)) {
2476 valueNumberInstruction(I);
2477 } else {
2478 llvm_unreachable("Should have been a MemoryPhi or Instruction");
2479 }
2480 updateProcessedCount(V);
2481 // Reset after processing (because we may mark ourselves as touched when
2482 // we propagate equalities).
2483 TouchedInstructions.reset(InstrNum);
2484 }
2485 }
2486 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2487}
2488
Daniel Berlin85f91b02016-12-26 20:06:58 +00002489// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00002490bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00002491 if (DebugCounter::isCounterSet(VNCounter))
2492 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00002493 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00002494 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00002495 MSSAWalker = MSSA->getWalker();
2496
2497 // Count number of instructions for sizing of hash tables, and come
2498 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002499 unsigned ICount = 1;
2500 // Add an empty instruction to account for the fact that we start at 1
2501 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002502 // Note: We want ideal RPO traversal of the blocks, which is not quite the
2503 // same as dominator tree order, particularly with regard whether backedges
2504 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00002505 // If we visit in the wrong order, we will end up performing N times as many
2506 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002507 // The dominator tree does guarantee that, for a given dom tree node, it's
2508 // parent must occur before it in the RPO ordering. Thus, we only need to sort
2509 // the siblings.
2510 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00002511 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00002512 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002513 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002514 auto *Node = DT->getNode(B);
2515 assert(Node && "RPO and Dominator tree should have same reachability");
2516 RPOOrdering[Node] = ++Counter;
2517 }
2518 // Sort dominator tree children arrays into RPO.
2519 for (auto &B : RPOT) {
2520 auto *Node = DT->getNode(B);
2521 if (Node->getChildren().size() > 1)
2522 std::sort(Node->begin(), Node->end(),
2523 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
2524 return RPOOrdering[A] < RPOOrdering[B];
2525 });
2526 }
2527
2528 // Now a standard depth first ordering of the domtree is equivalent to RPO.
2529 auto DFI = df_begin(DT->getRootNode());
2530 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
2531 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00002532 const auto &BlockRange = assignDFSNumbers(B, ICount);
2533 BlockInstRange.insert({B, BlockRange});
2534 ICount += BlockRange.second - BlockRange.first;
2535 }
2536
2537 // Handle forward unreachable blocks and figure out which blocks
2538 // have single preds.
2539 for (auto &B : F) {
2540 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002541 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002542 const auto &BlockRange = assignDFSNumbers(&B, ICount);
2543 BlockInstRange.insert({&B, BlockRange});
2544 ICount += BlockRange.second - BlockRange.first;
2545 }
2546 }
2547
Daniel Berline0bd37e2016-12-29 22:15:12 +00002548 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002549 // Ensure we don't end up resizing the expressionToClass map, as
2550 // that can be quite expensive. At most, we have one expression per
2551 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002552 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002553
2554 // Initialize the touched instructions to include the entry block.
2555 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2556 TouchedInstructions.set(InstRange.first, InstRange.second);
2557 ReachableBlocks.insert(&F.getEntryBlock());
2558
2559 initializeCongruenceClasses(F);
Daniel Berlin06329a92017-03-18 15:41:40 +00002560 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00002561 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00002562 verifyIterationSettled(F);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002563
Davide Italiano7e274e02016-12-22 16:03:48 +00002564 Changed |= eliminateInstructions(F);
2565
2566 // Delete all instructions marked for deletion.
2567 for (Instruction *ToErase : InstructionsToErase) {
2568 if (!ToErase->use_empty())
2569 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2570
2571 ToErase->eraseFromParent();
2572 }
2573
2574 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002575 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2576 return !ReachableBlocks.count(&BB);
2577 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002578
2579 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2580 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002581 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002582 deleteInstructionsInBlock(&BB);
2583 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002584 }
2585
2586 cleanupTables();
2587 return Changed;
2588}
2589
Davide Italiano7e274e02016-12-22 16:03:48 +00002590// Return true if V is a value that will always be available (IE can
2591// be placed anywhere) in the function. We don't do globals here
2592// because they are often worse to put in place.
2593// TODO: Separate cost from availability
2594static bool alwaysAvailable(Value *V) {
2595 return isa<Constant>(V) || isa<Argument>(V);
2596}
2597
Davide Italiano7e274e02016-12-22 16:03:48 +00002598struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002599 int DFSIn = 0;
2600 int DFSOut = 0;
2601 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002602 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002603 // The bool in the Def tells us whether the Def is the stored value of a
2604 // store.
2605 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002606 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002607 bool operator<(const ValueDFS &Other) const {
2608 // It's not enough that any given field be less than - we have sets
2609 // of fields that need to be evaluated together to give a proper ordering.
2610 // For example, if you have;
2611 // DFS (1, 3)
2612 // Val 0
2613 // DFS (1, 2)
2614 // Val 50
2615 // We want the second to be less than the first, but if we just go field
2616 // by field, we will get to Val 0 < Val 50 and say the first is less than
2617 // the second. We only want it to be less than if the DFS orders are equal.
2618 //
2619 // Each LLVM instruction only produces one value, and thus the lowest-level
2620 // differentiator that really matters for the stack (and what we use as as a
2621 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002622 // Everything else in the structure is instruction level, and only affects
2623 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002624 //
2625 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2626 // the order of replacement of uses does not matter.
2627 // IE given,
2628 // a = 5
2629 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002630 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2631 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002632 // The .val will be the same as well.
2633 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002634 // You will replace both, and it does not matter what order you replace them
2635 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2636 // operand 2).
2637 // Similarly for the case of same dfsin, dfsout, localnum, but different
2638 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002639 // a = 5
2640 // b = 6
2641 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002642 // in c, we will a valuedfs for a, and one for b,with everything the same
2643 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002644 // It does not matter what order we replace these operands in.
2645 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002646 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2647 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002648 Other.U);
2649 }
2650};
2651
Daniel Berlinc4796862017-01-27 02:37:11 +00002652// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002653// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00002654// reachable uses for each value is stored in UseCount, and instructions that
2655// seem
2656// dead (have no non-dead uses) are stored in ProbablyDead.
2657void NewGVN::convertClassToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00002658 const CongruenceClass::MemberSet &Dense,
Daniel Berline3e69e12017-03-10 00:32:33 +00002659 SmallVectorImpl<ValueDFS> &DFSOrderedSet,
2660 DenseMap<const Value *, unsigned int> &UseCounts,
2661 SmallPtrSetImpl<Instruction *> &ProbablyDead) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002662 for (auto D : Dense) {
2663 // First add the value.
2664 BasicBlock *BB = getBlockForValue(D);
2665 // Constants are handled prior to ever calling this function, so
2666 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002667 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002668 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002669 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002670 VDDef.DFSIn = DomNode->getDFSNumIn();
2671 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002672 // If it's a store, use the leader of the value operand, if it's always
2673 // available, or the value operand. TODO: We could do dominance checks to
2674 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00002675 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002676 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002677 if (alwaysAvailable(Leader)) {
2678 VDDef.Def.setPointer(Leader);
2679 } else {
2680 VDDef.Def.setPointer(SI->getValueOperand());
2681 VDDef.Def.setInt(true);
2682 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002683 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002684 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00002685 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002686 assert(isa<Instruction>(D) &&
2687 "The dense set member should always be an instruction");
2688 VDDef.LocalNum = InstrDFS.lookup(D);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002689 DFSOrderedSet.emplace_back(VDDef);
Daniel Berline3e69e12017-03-10 00:32:33 +00002690 Instruction *Def = cast<Instruction>(D);
2691 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002692 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00002693 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002694 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002695 // Don't try to replace into dead uses
2696 if (InstructionsToErase.count(I))
2697 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002698 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002699 // Put the phi node uses in the incoming block.
2700 BasicBlock *IBlock;
2701 if (auto *P = dyn_cast<PHINode>(I)) {
2702 IBlock = P->getIncomingBlock(U);
2703 // Make phi node users appear last in the incoming block
2704 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002705 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002706 } else {
2707 IBlock = I->getParent();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002708 VDUse.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002709 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002710
2711 // Skip uses in unreachable blocks, as we're going
2712 // to delete them.
2713 if (ReachableBlocks.count(IBlock) == 0)
2714 continue;
2715
Daniel Berlinb66164c2017-01-14 00:24:23 +00002716 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002717 VDUse.DFSIn = DomNode->getDFSNumIn();
2718 VDUse.DFSOut = DomNode->getDFSNumOut();
2719 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00002720 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002721 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002722 }
2723 }
Daniel Berline3e69e12017-03-10 00:32:33 +00002724
2725 // If there are no uses, it's probably dead (but it may have side-effects,
2726 // so not definitely dead. Otherwise, store the number of uses so we can
2727 // track if it becomes dead later).
2728 if (UseCount == 0)
2729 ProbablyDead.insert(Def);
2730 else
2731 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002732 }
2733}
2734
Daniel Berlinc4796862017-01-27 02:37:11 +00002735// This function converts the set of members for a congruence class from values,
2736// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00002737void NewGVN::convertClassToLoadsAndStores(
Daniel Berlinc4796862017-01-27 02:37:11 +00002738 const CongruenceClass::MemberSet &Dense,
2739 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2740 for (auto D : Dense) {
2741 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2742 continue;
2743
2744 BasicBlock *BB = getBlockForValue(D);
2745 ValueDFS VD;
2746 DomTreeNode *DomNode = DT->getNode(BB);
2747 VD.DFSIn = DomNode->getDFSNumIn();
2748 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002749 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00002750
2751 // If it's an instruction, use the real local dfs number.
2752 if (auto *I = dyn_cast<Instruction>(D))
2753 VD.LocalNum = InstrDFS.lookup(I);
2754 else
2755 llvm_unreachable("Should have been an instruction");
2756
2757 LoadsAndStores.emplace_back(VD);
2758 }
2759}
2760
Davide Italiano7e274e02016-12-22 16:03:48 +00002761static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002762 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002763 if (!ReplInst)
2764 return;
2765
Davide Italiano7e274e02016-12-22 16:03:48 +00002766 // Patch the replacement so that it is not more restrictive than the value
2767 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002768 // Note that if 'I' is a load being replaced by some operation,
2769 // for example, by an arithmetic operation, then andIRFlags()
2770 // would just erase all math flags from the original arithmetic
2771 // operation, which is clearly not wanted and not needed.
2772 if (!isa<LoadInst>(I))
2773 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002774
Daniel Berlin86eab152017-02-12 22:25:20 +00002775 // FIXME: If both the original and replacement value are part of the
2776 // same control-flow region (meaning that the execution of one
2777 // guarantees the execution of the other), then we can combine the
2778 // noalias scopes here and do better than the general conservative
2779 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002780
Daniel Berlin86eab152017-02-12 22:25:20 +00002781 // In general, GVN unifies expressions over different control-flow
2782 // regions, and so we need a conservative combination of the noalias
2783 // scopes.
2784 static const unsigned KnownIDs[] = {
2785 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2786 LLVMContext::MD_noalias, LLVMContext::MD_range,
2787 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2788 LLVMContext::MD_invariant_group};
2789 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002790}
2791
2792static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2793 patchReplacementInstruction(I, Repl);
2794 I->replaceAllUsesWith(Repl);
2795}
2796
2797void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2798 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2799 ++NumGVNBlocksDeleted;
2800
Daniel Berline19f0e02017-01-30 17:06:55 +00002801 // Delete the instructions backwards, as it has a reduced likelihood of having
2802 // to update as many def-use and use-def chains. Start after the terminator.
2803 auto StartPoint = BB->rbegin();
2804 ++StartPoint;
2805 // Note that we explicitly recalculate BB->rend() on each iteration,
2806 // as it may change when we remove the first instruction.
2807 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2808 Instruction &Inst = *I++;
2809 if (!Inst.use_empty())
2810 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2811 if (isa<LandingPadInst>(Inst))
2812 continue;
2813
2814 Inst.eraseFromParent();
2815 ++NumGVNInstrDeleted;
2816 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002817 // Now insert something that simplifycfg will turn into an unreachable.
2818 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2819 new StoreInst(UndefValue::get(Int8Ty),
2820 Constant::getNullValue(Int8Ty->getPointerTo()),
2821 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002822}
2823
2824void NewGVN::markInstructionForDeletion(Instruction *I) {
2825 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2826 InstructionsToErase.insert(I);
2827}
2828
2829void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2830
2831 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2832 patchAndReplaceAllUsesWith(I, V);
2833 // We save the actual erasing to avoid invalidating memory
2834 // dependencies until we are done with everything.
2835 markInstructionForDeletion(I);
2836}
2837
2838namespace {
2839
2840// This is a stack that contains both the value and dfs info of where
2841// that value is valid.
2842class ValueDFSStack {
2843public:
2844 Value *back() const { return ValueStack.back(); }
2845 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2846
2847 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002848 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002849 DFSStack.emplace_back(DFSIn, DFSOut);
2850 }
2851 bool empty() const { return DFSStack.empty(); }
2852 bool isInScope(int DFSIn, int DFSOut) const {
2853 if (empty())
2854 return false;
2855 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2856 }
2857
2858 void popUntilDFSScope(int DFSIn, int DFSOut) {
2859
2860 // These two should always be in sync at this point.
2861 assert(ValueStack.size() == DFSStack.size() &&
2862 "Mismatch between ValueStack and DFSStack");
2863 while (
2864 !DFSStack.empty() &&
2865 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2866 DFSStack.pop_back();
2867 ValueStack.pop_back();
2868 }
2869 }
2870
2871private:
2872 SmallVector<Value *, 8> ValueStack;
2873 SmallVector<std::pair<int, int>, 8> DFSStack;
2874};
2875}
Daniel Berlin04443432017-01-07 03:23:47 +00002876
Davide Italiano7e274e02016-12-22 16:03:48 +00002877bool NewGVN::eliminateInstructions(Function &F) {
2878 // This is a non-standard eliminator. The normal way to eliminate is
2879 // to walk the dominator tree in order, keeping track of available
2880 // values, and eliminating them. However, this is mildly
2881 // pointless. It requires doing lookups on every instruction,
2882 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002883 // instructions part of most singleton congruence classes, we know we
2884 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002885
2886 // Instead, this eliminator looks at the congruence classes directly, sorts
2887 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002888 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002889 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002890 // last member. This is worst case O(E log E) where E = number of
2891 // instructions in a single congruence class. In theory, this is all
2892 // instructions. In practice, it is much faster, as most instructions are
2893 // either in singleton congruence classes or can't possibly be eliminated
2894 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002895 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002896 // for elimination purposes.
2897 // TODO: If we wanted to be faster, We could remove any members with no
2898 // overlapping ranges while sorting, as we will never eliminate anything
2899 // with those members, as they don't dominate anything else in our set.
2900
Davide Italiano7e274e02016-12-22 16:03:48 +00002901 bool AnythingReplaced = false;
2902
2903 // Since we are going to walk the domtree anyway, and we can't guarantee the
2904 // DFS numbers are updated, we compute some ourselves.
2905 DT->updateDFSNumbers();
2906
2907 for (auto &B : F) {
2908 if (!ReachableBlocks.count(&B)) {
2909 for (const auto S : successors(&B)) {
2910 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002911 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002912 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2913 << getBlockName(&B)
2914 << " with undef due to it being unreachable\n");
2915 for (auto &Operand : Phi.incoming_values())
2916 if (Phi.getIncomingBlock(Operand) == &B)
2917 Operand.set(UndefValue::get(Phi.getType()));
2918 }
2919 }
2920 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002921 }
2922
Daniel Berline3e69e12017-03-10 00:32:33 +00002923 // Map to store the use counts
2924 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlin4d547962017-02-12 23:24:45 +00002925 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002926 // Track the equivalent store info so we can decide whether to try
2927 // dead store elimination.
2928 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00002929 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlin1316a942017-04-06 18:52:50 +00002930 if (CC->isDead() || CC->Members.empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00002931 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002932 // Everything still in the TOP class is unreachable or dead.
2933 if (CC == TOPClass) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00002934#ifndef NDEBUG
2935 for (auto M : CC->Members)
2936 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2937 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002938 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00002939 "point");
2940#endif
2941 continue;
2942 }
2943
Davide Italiano7e274e02016-12-22 16:03:48 +00002944 assert(CC->RepLeader && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00002945 // If this is a leader that is always available, and it's a
2946 // constant or has no equivalences, just replace everything with
2947 // it. We then update the congruence class with whatever members
2948 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002949 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2950 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00002951 CongruenceClass::MemberSet MembersLeft;
Davide Italiano7e274e02016-12-22 16:03:48 +00002952 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002953 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002954 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00002955 if (Member == Leader || !isa<Instruction>(Member) ||
2956 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002957 MembersLeft.insert(Member);
2958 continue;
2959 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002960 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2961 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00002962 auto *I = cast<Instruction>(Member);
2963 assert(Leader != I && "About to accidentally remove our leader");
2964 replaceInstruction(I, Leader);
2965 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002966 }
2967 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002968 } else {
2969 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2970 // If this is a singleton, we can skip it.
2971 if (CC->Members.size() != 1) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002972 // This is a stack because equality replacement/etc may place
2973 // constants in the middle of the member list, and we want to use
2974 // those constant values in preference to the current leader, over
2975 // the scope of those constants.
2976 ValueDFSStack EliminationStack;
2977
2978 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002979 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berline3e69e12017-03-10 00:32:33 +00002980 convertClassToDFSOrdered(CC->Members, DFSOrderedSet, UseCounts,
2981 ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00002982
2983 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002984 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002985 for (auto &VD : DFSOrderedSet) {
2986 int MemberDFSIn = VD.DFSIn;
2987 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002988 Value *Def = VD.Def.getPointer();
2989 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00002990 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00002991 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002992 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00002993 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002994
2995 if (EliminationStack.empty()) {
2996 DEBUG(dbgs() << "Elimination Stack is empty\n");
2997 } else {
2998 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2999 << EliminationStack.dfs_back().first << ","
3000 << EliminationStack.dfs_back().second << ")\n");
3001 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003002
3003 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3004 << MemberDFSOut << ")\n");
3005 // First, we see if we are out of scope or empty. If so,
3006 // and there equivalences, we try to replace the top of
3007 // stack with equivalences (if it's on the stack, it must
3008 // not have been eliminated yet).
3009 // Then we synchronize to our current scope, by
3010 // popping until we are back within a DFS scope that
3011 // dominates the current member.
3012 // Then, what happens depends on a few factors
3013 // If the stack is now empty, we need to push
3014 // If we have a constant or a local equivalence we want to
3015 // start using, we also push.
3016 // Otherwise, we walk along, processing members who are
3017 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003018 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003019 bool OutOfScope =
3020 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3021
3022 if (OutOfScope || ShouldPush) {
3023 // Sync to our current scope.
3024 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003025 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003026 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003027 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003028 }
3029 }
3030
Daniel Berline3e69e12017-03-10 00:32:33 +00003031 // Skip the Def's, we only want to eliminate on their uses. But mark
3032 // dominated defs as dead.
3033 if (Def) {
3034 // For anything in this case, what and how we value number
3035 // guarantees that any side-effets that would have occurred (ie
3036 // throwing, etc) can be proven to either still occur (because it's
3037 // dominated by something that has the same side-effects), or never
3038 // occur. Otherwise, we would not have been able to prove it value
3039 // equivalent to something else. For these things, we can just mark
3040 // it all dead. Note that this is different from the "ProbablyDead"
3041 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003042 // easy to prove dead if they are also side-effect free. Note that
3043 // because stores are put in terms of the stored value, we skip
3044 // stored values here. If the stored value is really dead, it will
3045 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003046 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003047 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003048 markInstructionForDeletion(cast<Instruction>(Def));
3049 continue;
3050 }
3051 // At this point, we know it is a Use we are trying to possibly
3052 // replace.
3053
3054 assert(isa<Instruction>(U->get()) &&
3055 "Current def should have been an instruction");
3056 assert(isa<Instruction>(U->getUser()) &&
3057 "Current user should have been an instruction");
3058
3059 // If the thing we are replacing into is already marked to be dead,
3060 // this use is dead. Note that this is true regardless of whether
3061 // we have anything dominating the use or not. We do this here
3062 // because we are already walking all the uses anyway.
3063 Instruction *InstUse = cast<Instruction>(U->getUser());
3064 if (InstructionsToErase.count(InstUse)) {
3065 auto &UseCount = UseCounts[U->get()];
3066 if (--UseCount == 0) {
3067 ProbablyDead.insert(cast<Instruction>(U->get()));
3068 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003069 }
3070
Davide Italiano7e274e02016-12-22 16:03:48 +00003071 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003072 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003073 if (EliminationStack.empty())
3074 continue;
3075
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003076 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003077
Daniel Berlind92e7f92017-01-07 00:01:42 +00003078 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003079 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003080 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003081 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003082 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003083
3084 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003085 // metadata. Skip this if we are replacing predicateinfo with its
3086 // original operand, as we already know we can just drop it.
3087 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003088 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3089 if (!PI || DominatingLeader != PI->OriginalOp)
3090 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003091 U->set(DominatingLeader);
3092 // This is now a use of the dominating leader, which means if the
3093 // dominating leader was dead, it's now live!
3094 auto &LeaderUseCount = UseCounts[DominatingLeader];
3095 // It's about to be alive again.
3096 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3097 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
3098 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003099 AnythingReplaced = true;
3100 }
3101 }
3102 }
3103
Daniel Berline3e69e12017-03-10 00:32:33 +00003104 // At this point, anything still in the ProbablyDead set is actually dead if
3105 // would be trivially dead.
3106 for (auto *I : ProbablyDead)
3107 if (wouldInstructionBeTriviallyDead(I))
3108 markInstructionForDeletion(I);
3109
Davide Italiano7e274e02016-12-22 16:03:48 +00003110 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003111 CongruenceClass::MemberSet MembersLeft;
3112 for (auto *Member : CC->Members)
3113 if (!isa<Instruction>(Member) ||
3114 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003115 MembersLeft.insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +00003116 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003117
3118 // If we have possible dead stores to look at, try to eliminate them.
3119 if (CC->StoreCount > 0) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003120 convertClassToLoadsAndStores(CC->Members, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003121 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3122 ValueDFSStack EliminationStack;
3123 for (auto &VD : PossibleDeadStores) {
3124 int MemberDFSIn = VD.DFSIn;
3125 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003126 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003127 if (EliminationStack.empty() ||
3128 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3129 // Sync to our current scope.
3130 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3131 if (EliminationStack.empty()) {
3132 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3133 continue;
3134 }
3135 }
3136 // We already did load elimination, so nothing to do here.
3137 if (isa<LoadInst>(Member))
3138 continue;
3139 assert(!EliminationStack.empty());
3140 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003141 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003142 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3143 // Member is dominater by Leader, and thus dead
3144 DEBUG(dbgs() << "Marking dead store " << *Member
3145 << " that is dominated by " << *Leader << "\n");
3146 markInstructionForDeletion(Member);
3147 CC->Members.erase(Member);
3148 ++NumGVNDeadStores;
3149 }
3150 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003151 }
3152
3153 return AnythingReplaced;
3154}
Daniel Berlin1c087672017-02-11 15:07:01 +00003155
3156// This function provides global ranking of operations so that we can place them
3157// in a canonical order. Note that rank alone is not necessarily enough for a
3158// complete ordering, as constants all have the same rank. However, generally,
3159// we will simplify an operation with all constants so that it doesn't matter
3160// what order they appear in.
3161unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003162 // Prefer undef to anything else
3163 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00003164 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003165 if (isa<Constant>(V))
3166 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00003167 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003168 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003169
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003170 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003171 // the constant and argument ranking above.
3172 unsigned Result = InstrDFS.lookup(V);
3173 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003174 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003175 // Unreachable or something else, just return a really large number.
3176 return ~0;
3177}
3178
3179// This is a function that says whether two commutative operations should
3180// have their order swapped when canonicalizing.
3181bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3182 // Because we only care about a total ordering, and don't rewrite expressions
3183 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003184 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003185 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003186}
Daniel Berlin64e68992017-03-12 04:46:45 +00003187
3188class NewGVNLegacyPass : public FunctionPass {
3189public:
3190 static char ID; // Pass identification, replacement for typeid.
3191 NewGVNLegacyPass() : FunctionPass(ID) {
3192 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3193 }
3194 bool runOnFunction(Function &F) override;
3195
3196private:
3197 void getAnalysisUsage(AnalysisUsage &AU) const override {
3198 AU.addRequired<AssumptionCacheTracker>();
3199 AU.addRequired<DominatorTreeWrapperPass>();
3200 AU.addRequired<TargetLibraryInfoWrapperPass>();
3201 AU.addRequired<MemorySSAWrapperPass>();
3202 AU.addRequired<AAResultsWrapperPass>();
3203 AU.addPreserved<DominatorTreeWrapperPass>();
3204 AU.addPreserved<GlobalsAAWrapperPass>();
3205 }
3206};
3207
3208bool NewGVNLegacyPass::runOnFunction(Function &F) {
3209 if (skipFunction(F))
3210 return false;
3211 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3212 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3213 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3214 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3215 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3216 F.getParent()->getDataLayout())
3217 .runGVN();
3218}
3219
3220INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3221 false, false)
3222INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3223INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3224INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3225INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3226INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3227INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3228INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3229 false)
3230
3231char NewGVNLegacyPass::ID = 0;
3232
3233// createGVNPass - The public interface to this file.
3234FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3235
3236PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3237 // Apparently the order in which we get these results matter for
3238 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3239 // the same order here, just in case.
3240 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3241 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3242 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3243 auto &AA = AM.getResult<AAManager>(F);
3244 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3245 bool Changed =
3246 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3247 .runGVN();
3248 if (!Changed)
3249 return PreservedAnalyses::all();
3250 PreservedAnalyses PA;
3251 PA.preserve<DominatorTreeAnalysis>();
3252 PA.preserve<GlobalsAA>();
3253 return PA;
3254}