blob: 3245940a0dd51f18ae68f206d8948b9a5e8eff7c [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
Daniel Berlinb527b2c2017-05-19 19:01:27 +000033/// something's value number changes. The vast majority of complexity and code
34/// in this file is devoted to tracking what value numbers could change for what
35/// instructions when various things happen. The rest of the algorithm is
36/// devoted to performing symbolic evaluation, forward propagation, and
37/// simplification of operations based on the value numbers deduced so far
38///
39/// In order to make the GVN mostly-complete, we use a technique derived from
40/// "Detection of Redundant Expressions: A Complete and Polynomial-time
41/// Algorithm in SSA" by R.R. Pai. The source of incompleteness in most SSA
42/// based GVN algorithms is related to their inability to detect equivalence
43/// between phi of ops (IE phi(a+b, c+d)) and op of phis (phi(a,c) + phi(b, d)).
44/// We resolve this issue by generating the equivalent "phi of ops" form for
45/// each op of phis we see, in a way that only takes polynomial time to resolve.
Daniel Berlindb3c7be2017-01-26 21:39:49 +000046///
47/// We also do not perform elimination by using any published algorithm. All
48/// published algorithms are O(Instructions). Instead, we use a technique that
49/// is O(number of operations with the same value number), enabling us to skip
50/// trying to eliminate things that have unique value numbers.
Davide Italiano7e274e02016-12-22 16:03:48 +000051//===----------------------------------------------------------------------===//
52
53#include "llvm/Transforms/Scalar/NewGVN.h"
54#include "llvm/ADT/BitVector.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/DenseSet.h"
57#include "llvm/ADT/DepthFirstIterator.h"
58#include "llvm/ADT/Hashing.h"
59#include "llvm/ADT/MapVector.h"
60#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000061#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000062#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallSet.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000064#include "llvm/ADT/Statistic.h"
65#include "llvm/ADT/TinyPtrVector.h"
66#include "llvm/Analysis/AliasAnalysis.h"
67#include "llvm/Analysis/AssumptionCache.h"
68#include "llvm/Analysis/CFG.h"
69#include "llvm/Analysis/CFGPrinter.h"
70#include "llvm/Analysis/ConstantFolding.h"
71#include "llvm/Analysis/GlobalsModRef.h"
72#include "llvm/Analysis/InstructionSimplify.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000073#include "llvm/Analysis/MemoryBuiltins.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000074#include "llvm/Analysis/MemoryLocation.h"
Daniel Berlin2f72b192017-04-14 02:53:37 +000075#include "llvm/Analysis/MemorySSA.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000076#include "llvm/Analysis/TargetLibraryInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000077#include "llvm/IR/DataLayout.h"
78#include "llvm/IR/Dominators.h"
79#include "llvm/IR/GlobalVariable.h"
80#include "llvm/IR/IRBuilder.h"
81#include "llvm/IR/IntrinsicInst.h"
82#include "llvm/IR/LLVMContext.h"
83#include "llvm/IR/Metadata.h"
84#include "llvm/IR/PatternMatch.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000085#include "llvm/IR/Type.h"
86#include "llvm/Support/Allocator.h"
87#include "llvm/Support/CommandLine.h"
88#include "llvm/Support/Debug.h"
Daniel Berlin283a6082017-03-01 19:59:26 +000089#include "llvm/Support/DebugCounter.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000090#include "llvm/Transforms/Scalar.h"
91#include "llvm/Transforms/Scalar/GVNExpression.h"
92#include "llvm/Transforms/Utils/BasicBlockUtils.h"
93#include "llvm/Transforms/Utils/Local.h"
Daniel Berlinf7d95802017-02-18 23:06:50 +000094#include "llvm/Transforms/Utils/PredicateInfo.h"
Daniel Berlin07daac82017-04-02 13:23:44 +000095#include "llvm/Transforms/Utils/VNCoercion.h"
Daniel Berlin1316a942017-04-06 18:52:50 +000096#include <numeric>
Davide Italiano7e274e02016-12-22 16:03:48 +000097#include <unordered_map>
98#include <utility>
99#include <vector>
100using namespace llvm;
101using namespace PatternMatch;
102using namespace llvm::GVNExpression;
Daniel Berlin07daac82017-04-02 13:23:44 +0000103using namespace llvm::VNCoercion;
Davide Italiano7e274e02016-12-22 16:03:48 +0000104#define DEBUG_TYPE "newgvn"
105
106STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
107STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
108STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
109STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +0000110STATISTIC(NumGVNMaxIterations,
111 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000112STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
113STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
114STATISTIC(NumGVNAvoidedSortedLeaderChanges,
115 "Number of avoided sorted leader changes");
Daniel Berlinc4796862017-01-27 02:37:11 +0000116STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000117STATISTIC(NumGVNPHIOfOpsCreated, "Number of PHI of ops created");
118STATISTIC(NumGVNPHIOfOpsEliminations,
119 "Number of things eliminated using PHI of ops");
Daniel Berlin283a6082017-03-01 19:59:26 +0000120DEBUG_COUNTER(VNCounter, "newgvn-vn",
121 "Controls which instructions are value numbered")
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000122DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
123 "Controls which instructions we create phi of ops for")
Daniel Berlin1316a942017-04-06 18:52:50 +0000124// Currently store defining access refinement is too slow due to basicaa being
125// egregiously slow. This flag lets us keep it working while we work on this
126// issue.
127static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
128 cl::init(false), cl::Hidden);
129
Davide Italiano7e274e02016-12-22 16:03:48 +0000130//===----------------------------------------------------------------------===//
131// GVN Pass
132//===----------------------------------------------------------------------===//
133
134// Anchor methods.
135namespace llvm {
136namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000137Expression::~Expression() = default;
138BasicExpression::~BasicExpression() = default;
139CallExpression::~CallExpression() = default;
140LoadExpression::~LoadExpression() = default;
141StoreExpression::~StoreExpression() = default;
142AggregateValueExpression::~AggregateValueExpression() = default;
143PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000144}
145}
146
Daniel Berlin2f72b192017-04-14 02:53:37 +0000147// Tarjan's SCC finding algorithm with Nuutila's improvements
148// SCCIterator is actually fairly complex for the simple thing we want.
149// It also wants to hand us SCC's that are unrelated to the phi node we ask
150// about, and have us process them there or risk redoing work.
151// Graph traits over a filter iterator also doesn't work that well here.
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000152// This SCC finder is specialized to walk use-def chains, and only follows
153// instructions,
Daniel Berlin2f72b192017-04-14 02:53:37 +0000154// not generic values (arguments, etc).
155struct TarjanSCC {
156
157 TarjanSCC() : Components(1) {}
158
159 void Start(const Instruction *Start) {
160 if (Root.lookup(Start) == 0)
161 FindSCC(Start);
162 }
163
164 const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
165 unsigned ComponentID = ValueToComponent.lookup(V);
166
167 assert(ComponentID > 0 &&
168 "Asking for a component for a value we never processed");
169 return Components[ComponentID];
170 }
171
172private:
173 void FindSCC(const Instruction *I) {
174 Root[I] = ++DFSNum;
175 // Store the DFS Number we had before it possibly gets incremented.
176 unsigned int OurDFS = DFSNum;
177 for (auto &Op : I->operands()) {
178 if (auto *InstOp = dyn_cast<Instruction>(Op)) {
179 if (Root.lookup(Op) == 0)
180 FindSCC(InstOp);
181 if (!InComponent.count(Op))
182 Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
183 }
184 }
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000185 // See if we really were the root of a component, by seeing if we still have
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000186 // our DFSNumber. If we do, we are the root of the component, and we have
187 // completed a component. If we do not, we are not the root of a component,
188 // and belong on the component stack.
Daniel Berlin2f72b192017-04-14 02:53:37 +0000189 if (Root.lookup(I) == OurDFS) {
190 unsigned ComponentID = Components.size();
191 Components.resize(Components.size() + 1);
192 auto &Component = Components.back();
193 Component.insert(I);
194 DEBUG(dbgs() << "Component root is " << *I << "\n");
195 InComponent.insert(I);
196 ValueToComponent[I] = ComponentID;
197 // Pop a component off the stack and label it.
198 while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
199 auto *Member = Stack.back();
200 DEBUG(dbgs() << "Component member is " << *Member << "\n");
201 Component.insert(Member);
202 InComponent.insert(Member);
203 ValueToComponent[Member] = ComponentID;
204 Stack.pop_back();
205 }
206 } else {
207 // Part of a component, push to stack
208 Stack.push_back(I);
209 }
210 }
211 unsigned int DFSNum = 1;
212 SmallPtrSet<const Value *, 8> InComponent;
213 DenseMap<const Value *, unsigned int> Root;
214 SmallVector<const Value *, 8> Stack;
215 // Store the components as vector of ptr sets, because we need the topo order
216 // of SCC's, but not individual member order
217 SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
218 DenseMap<const Value *, unsigned> ValueToComponent;
219};
Davide Italiano7e274e02016-12-22 16:03:48 +0000220// Congruence classes represent the set of expressions/instructions
221// that are all the same *during some scope in the function*.
222// That is, because of the way we perform equality propagation, and
223// because of memory value numbering, it is not correct to assume
224// you can willy-nilly replace any member with any other at any
225// point in the function.
226//
227// For any Value in the Member set, it is valid to replace any dominated member
228// with that Value.
229//
Daniel Berlin1316a942017-04-06 18:52:50 +0000230// Every congruence class has a leader, and the leader is used to symbolize
231// instructions in a canonical way (IE every operand of an instruction that is a
232// member of the same congruence class will always be replaced with leader
233// during symbolization). To simplify symbolization, we keep the leader as a
234// constant if class can be proved to be a constant value. Otherwise, the
235// leader is the member of the value set with the smallest DFS number. Each
236// congruence class also has a defining expression, though the expression may be
237// null. If it exists, it can be used for forward propagation and reassociation
238// of values.
239
240// For memory, we also track a representative MemoryAccess, and a set of memory
241// members for MemoryPhis (which have no real instructions). Note that for
242// memory, it seems tempting to try to split the memory members into a
243// MemoryCongruenceClass or something. Unfortunately, this does not work
244// easily. The value numbering of a given memory expression depends on the
245// leader of the memory congruence class, and the leader of memory congruence
246// class depends on the value numbering of a given memory expression. This
247// leads to wasted propagation, and in some cases, missed optimization. For
248// example: If we had value numbered two stores together before, but now do not,
249// we move them to a new value congruence class. This in turn will move at one
250// of the memorydefs to a new memory congruence class. Which in turn, affects
251// the value numbering of the stores we just value numbered (because the memory
252// congruence class is part of the value number). So while theoretically
253// possible to split them up, it turns out to be *incredibly* complicated to get
254// it to work right, because of the interdependency. While structurally
255// slightly messier, it is algorithmically much simpler and faster to do what we
Daniel Berlina8236562017-04-07 18:38:09 +0000256// do here, and track them both at once in the same class.
257// Note: The default iterators for this class iterate over values
258class CongruenceClass {
259public:
260 using MemberType = Value;
261 using MemberSet = SmallPtrSet<MemberType *, 4>;
262 using MemoryMemberType = MemoryPhi;
263 using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
264
265 explicit CongruenceClass(unsigned ID) : ID(ID) {}
266 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
267 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
268 unsigned getID() const { return ID; }
269 // True if this class has no members left. This is mainly used for assertion
270 // purposes, and for skipping empty classes.
271 bool isDead() const {
272 // If it's both dead from a value perspective, and dead from a memory
273 // perspective, it's really dead.
274 return empty() && memory_empty();
275 }
276 // Leader functions
277 Value *getLeader() const { return RepLeader; }
278 void setLeader(Value *Leader) { RepLeader = Leader; }
279 const std::pair<Value *, unsigned int> &getNextLeader() const {
280 return NextLeader;
281 }
282 void resetNextLeader() { NextLeader = {nullptr, ~0}; }
283
284 void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
285 if (LeaderPair.second < NextLeader.second)
286 NextLeader = LeaderPair;
287 }
288
289 Value *getStoredValue() const { return RepStoredValue; }
290 void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
291 const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
292 void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
293
294 // Forward propagation info
295 const Expression *getDefiningExpr() const { return DefiningExpr; }
Daniel Berlina8236562017-04-07 18:38:09 +0000296
297 // Value member set
298 bool empty() const { return Members.empty(); }
299 unsigned size() const { return Members.size(); }
300 MemberSet::const_iterator begin() const { return Members.begin(); }
301 MemberSet::const_iterator end() const { return Members.end(); }
302 void insert(MemberType *M) { Members.insert(M); }
303 void erase(MemberType *M) { Members.erase(M); }
304 void swap(MemberSet &Other) { Members.swap(Other); }
305
306 // Memory member set
307 bool memory_empty() const { return MemoryMembers.empty(); }
308 unsigned memory_size() const { return MemoryMembers.size(); }
309 MemoryMemberSet::const_iterator memory_begin() const {
310 return MemoryMembers.begin();
311 }
312 MemoryMemberSet::const_iterator memory_end() const {
313 return MemoryMembers.end();
314 }
315 iterator_range<MemoryMemberSet::const_iterator> memory() const {
316 return make_range(memory_begin(), memory_end());
317 }
318 void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
319 void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
320
321 // Store count
322 unsigned getStoreCount() const { return StoreCount; }
323 void incStoreCount() { ++StoreCount; }
324 void decStoreCount() {
325 assert(StoreCount != 0 && "Store count went negative");
326 --StoreCount;
327 }
328
Davide Italianodc435322017-05-10 19:57:43 +0000329 // True if this class has no memory members.
330 bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
331
Daniel Berlina8236562017-04-07 18:38:09 +0000332 // Return true if two congruence classes are equivalent to each other. This
333 // means
334 // that every field but the ID number and the dead field are equivalent.
335 bool isEquivalentTo(const CongruenceClass *Other) const {
336 if (!Other)
337 return false;
338 if (this == Other)
339 return true;
340
341 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
342 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
343 Other->RepMemoryAccess))
344 return false;
345 if (DefiningExpr != Other->DefiningExpr)
346 if (!DefiningExpr || !Other->DefiningExpr ||
347 *DefiningExpr != *Other->DefiningExpr)
348 return false;
349 // We need some ordered set
350 std::set<Value *> AMembers(Members.begin(), Members.end());
351 std::set<Value *> BMembers(Members.begin(), Members.end());
352 return AMembers == BMembers;
353 }
354
355private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000356 unsigned ID;
357 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000358 Value *RepLeader = nullptr;
Daniel Berlina8236562017-04-07 18:38:09 +0000359 // The most dominating leader after our current leader, because the member set
360 // is not sorted and is expensive to keep sorted all the time.
361 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
Daniel Berlin1316a942017-04-06 18:52:50 +0000362 // If this is represented by a store, the value of the store.
Daniel Berlin26addef2017-01-20 21:04:30 +0000363 Value *RepStoredValue = nullptr;
Daniel Berlin1316a942017-04-06 18:52:50 +0000364 // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
365 // access.
366 const MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000367 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000368 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000369 // Actual members of this class.
370 MemberSet Members;
Daniel Berlin1316a942017-04-06 18:52:50 +0000371 // This is the set of MemoryPhis that exist in the class. MemoryDefs and
372 // MemoryUses have real instructions representing them, so we only need to
373 // track MemoryPhis here.
374 MemoryMemberSet MemoryMembers;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000375 // Number of stores in this congruence class.
376 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000377 int StoreCount = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +0000378};
379
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000380struct HashedExpression;
Davide Italiano7e274e02016-12-22 16:03:48 +0000381namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000382template <> struct DenseMapInfo<const Expression *> {
383 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000384 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000385 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
386 return reinterpret_cast<const Expression *>(Val);
387 }
388 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000389 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000390 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
391 return reinterpret_cast<const Expression *>(Val);
392 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000393 static unsigned getHashValue(const Expression *E) {
394 return static_cast<unsigned>(E->getHashValue());
Daniel Berlin85f91b02016-12-26 20:06:58 +0000395 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000396 static unsigned getHashValue(const HashedExpression &HE);
397 static bool isEqual(const HashedExpression &LHS, const Expression *RHS);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000398 static bool isEqual(const Expression *LHS, const Expression *RHS) {
399 if (LHS == RHS)
400 return true;
401 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
402 LHS == getEmptyKey() || RHS == getEmptyKey())
403 return false;
404 return *LHS == *RHS;
405 }
406};
Davide Italiano7e274e02016-12-22 16:03:48 +0000407} // end namespace llvm
408
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000409// This is just a wrapper around Expression that computes the hash value once at
410// creation time. Hash values for an Expression can't change once they are
411// inserted into the DenseMap (it breaks DenseMap), so they must be immutable at
412// that point anyway.
413struct HashedExpression {
414 const Expression *E;
415 unsigned HashVal;
416 HashedExpression(const Expression *E)
417 : E(E), HashVal(DenseMapInfo<const Expression *>::getHashValue(E)) {}
418};
419
420unsigned
421DenseMapInfo<const Expression *>::getHashValue(const HashedExpression &HE) {
422 return HE.HashVal;
423}
424bool DenseMapInfo<const Expression *>::isEqual(const HashedExpression &LHS,
425 const Expression *RHS) {
426 return isEqual(LHS.E, RHS);
427}
428
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000429namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000430class NewGVN {
431 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000432 DominatorTree *DT;
Daniel Berlin64e68992017-03-12 04:46:45 +0000433 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000434 AliasAnalysis *AA;
435 MemorySSA *MSSA;
436 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000437 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000438 std::unique_ptr<PredicateInfo> PredInfo;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000439
440 // These are the only two things the create* functions should have
441 // side-effects on due to allocating memory.
442 mutable BumpPtrAllocator ExpressionAllocator;
443 mutable ArrayRecycler<Value *> ArgRecycler;
444 mutable TarjanSCC SCCFinder;
Daniel Berlinede130d2017-04-26 20:56:14 +0000445 const SimplifyQuery SQ;
Davide Italiano7e274e02016-12-22 16:03:48 +0000446
Daniel Berlin1c087672017-02-11 15:07:01 +0000447 // Number of function arguments, used by ranking
448 unsigned int NumFuncArgs;
449
Daniel Berlin2f72b192017-04-14 02:53:37 +0000450 // RPOOrdering of basic blocks
451 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
452
Davide Italiano7e274e02016-12-22 16:03:48 +0000453 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000454
455 // This class is called INITIAL in the paper. It is the class everything
456 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000457 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000458 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000459 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000460 std::vector<CongruenceClass *> CongruenceClasses;
461 unsigned NextCongruenceNum;
462
463 // Value Mappings.
464 DenseMap<Value *, CongruenceClass *> ValueToClass;
465 DenseMap<Value *, const Expression *> ValueToExpression;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000466 // Value PHI handling, used to make equivalence between phi(op, op) and
467 // op(phi, phi).
468 // These mappings just store various data that would normally be part of the
469 // IR.
470 DenseSet<const Instruction *> PHINodeUses;
471 // Map a temporary instruction we created to a parent block.
472 DenseMap<const Value *, BasicBlock *> TempToBlock;
473 // Map between the temporary phis we created and the real instructions they
474 // are known equivalent to.
475 DenseMap<const Value *, PHINode *> RealToTemp;
476 // In order to know when we should re-process instructions that have
477 // phi-of-ops, we track the set of expressions that they needed as
478 // leaders. When we discover new leaders for those expressions, we process the
479 // associated phi-of-op instructions again in case they have changed. The
480 // other way they may change is if they had leaders, and those leaders
481 // disappear. However, at the point they have leaders, there are uses of the
482 // relevant operands in the created phi node, and so they will get reprocessed
483 // through the normal user marking we perform.
484 mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
485 DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
486 ExpressionToPhiOfOps;
487 // Map from basic block to the temporary operations we created
Daniel Berlin0207cca2017-05-21 23:41:56 +0000488 DenseMap<const BasicBlock *, SmallVector<PHINode *, 8>> PHIOfOpsPHIs;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000489 // Map from temporary operation to MemoryAccess.
490 DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
491 // Set of all temporary instructions we created.
492 DenseSet<Instruction *> AllTempInstructions;
Davide Italiano7e274e02016-12-22 16:03:48 +0000493
Daniel Berlinf7d95802017-02-18 23:06:50 +0000494 // Mapping from predicate info we used to the instructions we used it with.
495 // In order to correctly ensure propagation, we must keep track of what
496 // comparisons we used, so that when the values of the comparisons change, we
497 // propagate the information to the places we used the comparison.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000498 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
499 PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000500 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
501 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000502 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
503 MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000504
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000505 // A table storing which memorydefs/phis represent a memory state provably
506 // equivalent to another memory state.
507 // We could use the congruence class machinery, but the MemoryAccess's are
508 // abstract memory states, so they can only ever be equivalent to each other,
509 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000510 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000511
Daniel Berlin1316a942017-04-06 18:52:50 +0000512 // We could, if we wanted, build MemoryPhiExpressions and
513 // MemoryVariableExpressions, etc, and value number them the same way we value
514 // number phi expressions. For the moment, this seems like overkill. They
515 // can only exist in one of three states: they can be TOP (equal to
516 // everything), Equivalent to something else, or unique. Because we do not
517 // create expressions for them, we need to simulate leader change not just
518 // when they change class, but when they change state. Note: We can do the
519 // same thing for phis, and avoid having phi expressions if we wanted, We
520 // should eventually unify in one direction or the other, so this is a little
521 // bit of an experiment in which turns out easier to maintain.
522 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
523 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
524
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000525 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
526 mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
Davide Italiano7e274e02016-12-22 16:03:48 +0000527 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000528 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000529 ExpressionClassMap ExpressionToClass;
530
Daniel Berline021d2d2017-05-19 20:22:20 +0000531 // We have a single expression that represents currently DeadExpressions.
532 // For dead expressions we can prove will stay dead, we mark them with
533 // DFS number zero. However, it's possible in the case of phi nodes
534 // for us to assume/prove all arguments are dead during fixpointing.
535 // We use DeadExpression for that case.
536 DeadExpression *SingletonDeadExpression = nullptr;
537
Davide Italiano7e274e02016-12-22 16:03:48 +0000538 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000539 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000540
541 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000542 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000543 DenseSet<BlockEdge> ReachableEdges;
544 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
545
546 // This is a bitvector because, on larger functions, we may have
547 // thousands of touched instructions at once (entire blocks,
548 // instructions with hundreds of uses, etc). Even with optimization
549 // for when we mark whole blocks as touched, when this was a
550 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
551 // the time in GVN just managing this list. The bitvector, on the
552 // other hand, efficiently supports test/set/clear of both
553 // individual and ranges, as well as "find next element" This
554 // enables us to use it as a worklist with essentially 0 cost.
555 BitVector TouchedInstructions;
556
557 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000558
559#ifndef NDEBUG
560 // Debugging for how many times each block and instruction got processed.
561 DenseMap<const Value *, unsigned> ProcessedCount;
562#endif
563
564 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000565 // This contains a mapping from Instructions to DFS numbers.
566 // The numbering starts at 1. An instruction with DFS number zero
567 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000568 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000569
570 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000571 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000572
573 // Deletion info.
574 SmallPtrSet<Instruction *, 8> InstructionsToErase;
575
576public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000577 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
578 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
579 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000580 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Daniel Berlinede130d2017-04-26 20:56:14 +0000581 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
582 }
Daniel Berlin64e68992017-03-12 04:46:45 +0000583 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000584
585private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000586 // Expression handling.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000587 const Expression *createExpression(Instruction *) const;
588 const Expression *createBinaryExpression(unsigned, Type *, Value *,
589 Value *) const;
590 PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000591 bool &OriginalOpsConstant) const;
Daniel Berline021d2d2017-05-19 20:22:20 +0000592 const DeadExpression *createDeadExpression() const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000593 const VariableExpression *createVariableExpression(Value *) const;
594 const ConstantExpression *createConstantExpression(Constant *) const;
595 const Expression *createVariableOrConstant(Value *V) const;
596 const UnknownExpression *createUnknownExpression(Instruction *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000597 const StoreExpression *createStoreExpression(StoreInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000598 const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000599 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000600 const MemoryAccess *) const;
601 const CallExpression *createCallExpression(CallInst *,
602 const MemoryAccess *) const;
603 const AggregateValueExpression *
604 createAggregateValueExpression(Instruction *) const;
605 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000606
607 // Congruence class handling.
608 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000609 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000610 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000611 return result;
612 }
613
Daniel Berlin1316a942017-04-06 18:52:50 +0000614 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
615 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000616 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000617 return CC;
618 }
619 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
620 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000621 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000622 CC = createMemoryClass(MA);
623 return CC;
624 }
625
Davide Italiano7e274e02016-12-22 16:03:48 +0000626 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000627 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000628 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000629 ValueToClass[Member] = CClass;
630 return CClass;
631 }
632 void initializeCongruenceClasses(Function &F);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000633 const Expression *makePossiblePhiOfOps(Instruction *, bool,
634 SmallPtrSetImpl<Value *> &);
635 void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
Davide Italiano7e274e02016-12-22 16:03:48 +0000636
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000637 // Value number an Instruction or MemoryPhi.
638 void valueNumberMemoryPhi(MemoryPhi *);
639 void valueNumberInstruction(Instruction *);
640
Davide Italiano7e274e02016-12-22 16:03:48 +0000641 // Symbolic evaluation.
642 const Expression *checkSimplificationResults(Expression *, Instruction *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000643 Value *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000644 const Expression *performSymbolicEvaluation(Value *,
645 SmallPtrSetImpl<Value *> &) const;
Daniel Berlin07daac82017-04-02 13:23:44 +0000646 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000647 Instruction *,
648 MemoryAccess *) const;
649 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
650 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
651 const Expression *performSymbolicCallEvaluation(Instruction *) const;
652 const Expression *performSymbolicPHIEvaluation(Instruction *) const;
653 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
654 const Expression *performSymbolicCmpEvaluation(Instruction *) const;
655 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000656
657 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000658 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000659 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000660 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000661 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
662 CongruenceClass *, CongruenceClass *);
663 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
664 CongruenceClass *, CongruenceClass *);
665 Value *getNextValueLeader(CongruenceClass *) const;
666 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
667 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
668 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
669 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000670 bool isMemoryAccessTOP(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000671
Daniel Berlin1c087672017-02-11 15:07:01 +0000672 // Ranking
673 unsigned int getRank(const Value *) const;
674 bool shouldSwapOperands(const Value *, const Value *) const;
675
Davide Italiano7e274e02016-12-22 16:03:48 +0000676 // Reachability handling.
677 void updateReachableEdge(BasicBlock *, BasicBlock *);
678 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000679 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000680
681 // Elimination.
682 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000683 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000684 SmallVectorImpl<ValueDFS> &,
685 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000686 SmallPtrSetImpl<Instruction *> &) const;
687 void convertClassToLoadsAndStores(const CongruenceClass &,
688 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000689
690 bool eliminateInstructions(Function &);
691 void replaceInstruction(Instruction *, Value *);
692 void markInstructionForDeletion(Instruction *);
693 void deleteInstructionsInBlock(BasicBlock *);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000694 Value *findPhiOfOpsLeader(const Expression *E, const BasicBlock *BB) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000695
696 // New instruction creation.
697 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000698
699 // Various instruction touch utilities
Daniel Berlin0207cca2017-05-21 23:41:56 +0000700 template <typename Map, typename KeyType, typename Func>
701 void for_each_found(Map &, const KeyType &, Func);
702 template <typename Map, typename KeyType>
703 void touchAndErase(Map &, const KeyType &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000704 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000705 void markMemoryUsersTouched(const MemoryAccess *);
706 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000707 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000708 void markValueLeaderChangeTouched(CongruenceClass *CC);
709 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000710 void markPhiOfOpsChanged(const HashedExpression &HE);
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000711 void addPredicateUsers(const PredicateBase *, Instruction *) const;
712 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000713 void addAdditionalUsers(Value *To, Value *User) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000714
Daniel Berlin06329a92017-03-18 15:41:40 +0000715 // Main loop of value numbering
716 void iterateTouchedInstructions();
717
Davide Italiano7e274e02016-12-22 16:03:48 +0000718 // Utilities.
719 void cleanupTables();
720 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000721 void updateProcessedCount(const Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000722 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000723 void verifyIterationSettled(Function &F);
Daniel Berlin45403572017-05-16 19:58:47 +0000724 void verifyStoreExpressions() const;
Davide Italianoeab0de22017-05-18 23:22:44 +0000725 bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
726 const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000727 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000728 void deleteExpression(const Expression *E) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000729 MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
730 MemoryAccess *getDefiningAccess(const MemoryAccess *) const;
731 MemoryPhi *getMemoryAccess(const BasicBlock *) const;
732 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin21279bd2017-04-06 18:52:58 +0000733 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000734 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
735 return InstrDFS.lookup(V);
736 }
737
Daniel Berlin21279bd2017-04-06 18:52:58 +0000738 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
739 return MemoryToDFSNum(MA);
740 }
741 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
742 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
743 // This deliberately takes a value so it can be used with Use's, which will
744 // auto-convert to Value's but not to MemoryAccess's.
745 unsigned MemoryToDFSNum(const Value *MA) const {
746 assert(isa<MemoryAccess>(MA) &&
747 "This should not be used with instructions");
748 return isa<MemoryUseOrDef>(MA)
749 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
750 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000751 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000752 bool isCycleFree(const Instruction *) const;
753 bool isBackedge(BasicBlock *From, BasicBlock *To) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000754 // Debug counter info. When verifying, we have to reset the value numbering
755 // debug counter to the same state it started in to get the same results.
756 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000757};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000758} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000759
Davide Italianob1114092016-12-28 13:37:17 +0000760template <typename T>
761static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000762 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000763 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000764 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000765}
766
Davide Italianob1114092016-12-28 13:37:17 +0000767bool LoadExpression::equals(const Expression &Other) const {
768 return equalsLoadStoreHelper(*this, Other);
769}
Davide Italiano7e274e02016-12-22 16:03:48 +0000770
Davide Italianob1114092016-12-28 13:37:17 +0000771bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000772 if (!equalsLoadStoreHelper(*this, Other))
773 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000774 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000775 if (const auto *S = dyn_cast<StoreExpression>(&Other))
776 if (getStoredValue() != S->getStoredValue())
777 return false;
778 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000779}
780
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000781// Determine if the edge From->To is a backedge
782bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
783 if (From == To)
784 return true;
785 auto *FromDTN = DT->getNode(From);
786 auto *ToDTN = DT->getNode(To);
787 return RPOOrdering.lookup(FromDTN) >= RPOOrdering.lookup(ToDTN);
788}
789
Davide Italiano7e274e02016-12-22 16:03:48 +0000790#ifndef NDEBUG
791static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000792 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000793}
794#endif
795
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000796// Get a MemoryAccess for an instruction, fake or real.
797MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
798 auto *Result = MSSA->getMemoryAccess(I);
799 return Result ? Result : TempToMemory.lookup(I);
800}
801
802// Get a MemoryPhi for a basic block. These are all real.
803MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
804 return MSSA->getMemoryAccess(BB);
805}
806
Daniel Berlin06329a92017-03-18 15:41:40 +0000807// Get the basic block from an instruction/memory value.
808BasicBlock *NewGVN::getBlockForValue(Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000809 if (auto *I = dyn_cast<Instruction>(V)) {
810 auto *Parent = I->getParent();
811 if (Parent)
812 return Parent;
813 Parent = TempToBlock.lookup(V);
814 assert(Parent && "Every fake instruction should have a block");
815 return Parent;
816 }
817
818 auto *MP = dyn_cast<MemoryPhi>(V);
819 assert(MP && "Should have been an instruction or a MemoryPhi");
820 return MP->getBlock();
Daniel Berlin06329a92017-03-18 15:41:40 +0000821}
822
Daniel Berlin0e900112017-03-24 06:33:48 +0000823// Delete a definitely dead expression, so it can be reused by the expression
824// allocator. Some of these are not in creation functions, so we have to accept
825// const versions.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000826void NewGVN::deleteExpression(const Expression *E) const {
Daniel Berlin0e900112017-03-24 06:33:48 +0000827 assert(isa<BasicExpression>(E));
828 auto *BE = cast<BasicExpression>(E);
829 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
830 ExpressionAllocator.Deallocate(E);
831}
Daniel Berlin2f72b192017-04-14 02:53:37 +0000832PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000833 bool &OriginalOpsConstant) const {
834 BasicBlock *PHIBlock = getBlockForValue(I);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000835 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000836 auto *E =
837 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000838
839 E->allocateOperands(ArgRecycler, ExpressionAllocator);
840 E->setType(I->getType());
841 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000842
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000843 // NewGVN assumes the operands of a PHI node are in a consistent order across
844 // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
845 // this in LLVM at some point we don't want GVN to find wrong congruences.
846 // Therefore, here we sort uses in predecessor order.
Davide Italiano63998ec2017-05-09 18:29:37 +0000847 // We're sorting the values by pointer. In theory this might be cause of
848 // non-determinism, but here we don't rely on the ordering for anything
849 // significant, e.g. we don't create new instructions based on it so we're
850 // fine.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000851 SmallVector<const Use *, 4> PHIOperands;
852 for (const Use &U : PN->operands())
853 PHIOperands.push_back(&U);
854 std::sort(PHIOperands.begin(), PHIOperands.end(),
855 [&](const Use *U1, const Use *U2) {
856 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
857 });
858
Davide Italianob3886dd2017-01-25 23:37:49 +0000859 // Filter out unreachable phi operands.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000860 auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
861 return ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000862 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000863 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000864 [&](const Use *U) -> Value * {
865 auto *BB = PN->getIncomingBlock(*U);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000866 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
867 OriginalOpsConstant =
868 OriginalOpsConstant && isa<Constant>(*U);
Daniel Berline021d2d2017-05-19 20:22:20 +0000869 // Use nullptr to distinguish between things that were
870 // originally self-defined and those that have an operand
871 // leader that is self-defined.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000872 if (*U == PN)
Daniel Berline021d2d2017-05-19 20:22:20 +0000873 return nullptr;
874 // Things in TOPClass are equivalent to everything.
875 if (ValueToClass.lookup(*U) == TOPClass)
876 return nullptr;
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000877 return lookupOperandLeader(*U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000878 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000879 return E;
880}
881
882// Set basic expression info (Arguments, type, opcode) for Expression
883// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000884bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000885 bool AllConstant = true;
886 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
887 E->setType(GEP->getSourceElementType());
888 else
889 E->setType(I->getType());
890 E->setOpcode(I->getOpcode());
891 E->allocateOperands(ArgRecycler, ExpressionAllocator);
892
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000893 // Transform the operand array into an operand leader array, and keep track of
894 // whether all members are constant.
895 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000896 auto Operand = lookupOperandLeader(O);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000897 AllConstant = AllConstant && isa<Constant>(Operand);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000898 return Operand;
899 });
900
Davide Italiano7e274e02016-12-22 16:03:48 +0000901 return AllConstant;
902}
903
904const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000905 Value *Arg1,
906 Value *Arg2) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000907 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000908
909 E->setType(T);
910 E->setOpcode(Opcode);
911 E->allocateOperands(ArgRecycler, ExpressionAllocator);
912 if (Instruction::isCommutative(Opcode)) {
913 // Ensure that commutative instructions that only differ by a permutation
914 // of their operands get the same value number by sorting the operand value
915 // numbers. Since all commutative instructions have two operands it is more
916 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000917 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000918 std::swap(Arg1, Arg2);
919 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000920 E->op_push_back(lookupOperandLeader(Arg1));
921 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000922
Daniel Berlinede130d2017-04-26 20:56:14 +0000923 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000924 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
925 return SimplifiedE;
926 return E;
927}
928
929// Take a Value returned by simplification of Expression E/Instruction
930// I, and see if it resulted in a simpler expression. If so, return
931// that expression.
932// TODO: Once finished, this should not take an Instruction, we only
933// use it for printing.
934const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000935 Instruction *I,
936 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000937 if (!V)
938 return nullptr;
939 if (auto *C = dyn_cast<Constant>(V)) {
940 if (I)
941 DEBUG(dbgs() << "Simplified " << *I << " to "
942 << " constant " << *C << "\n");
943 NumGVNOpsSimplified++;
944 assert(isa<BasicExpression>(E) &&
945 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000946 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000947 return createConstantExpression(C);
948 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
949 if (I)
950 DEBUG(dbgs() << "Simplified " << *I << " to "
951 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000952 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000953 return createVariableExpression(V);
954 }
955
956 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlina8236562017-04-07 18:38:09 +0000957 if (CC && CC->getDefiningExpr()) {
Davide Italianofd9100e2017-05-24 02:30:24 +0000958 // If we simplified to something else, we need to communicate
959 // that we're users of the value we simplified to.
960 if (I != V)
961 addAdditionalUsers(V, I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000962 if (I)
963 DEBUG(dbgs() << "Simplified " << *I << " to "
Daniel Berlin01939972017-05-21 23:41:53 +0000964 << " expression " << *CC->getDefiningExpr() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +0000965 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000966 deleteExpression(E);
Daniel Berlina8236562017-04-07 18:38:09 +0000967 return CC->getDefiningExpr();
Davide Italiano7e274e02016-12-22 16:03:48 +0000968 }
969 return nullptr;
970}
971
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000972const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000973 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000974
Daniel Berlin97718e62017-01-31 22:32:03 +0000975 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000976
977 if (I->isCommutative()) {
978 // Ensure that commutative instructions that only differ by a permutation
979 // of their operands get the same value number by sorting the operand value
980 // numbers. Since all commutative instructions have two operands it is more
981 // efficient to sort by hand rather than using, say, std::sort.
982 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000983 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000984 E->swapOperands(0, 1);
985 }
986
987 // Perform simplificaiton
988 // TODO: Right now we only check to see if we get a constant result.
989 // We may get a less than constant, but still better, result for
990 // some operations.
991 // IE
992 // add 0, x -> x
993 // and x, x -> x
994 // We should handle this by simply rewriting the expression.
995 if (auto *CI = dyn_cast<CmpInst>(I)) {
996 // Sort the operand value numbers so x<y and y>x get the same value
997 // number.
998 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000999 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001000 E->swapOperands(0, 1);
1001 Predicate = CmpInst::getSwappedPredicate(Predicate);
1002 }
1003 E->setOpcode((CI->getOpcode() << 8) | Predicate);
1004 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +00001005 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
1006 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +00001007 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
1008 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +00001009 Value *V =
1010 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +00001011 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1012 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001013 } else if (isa<SelectInst>(I)) {
1014 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +00001015 E->getOperand(0) == E->getOperand(1)) {
1016 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1017 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +00001018 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +00001019 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001020 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1021 return SimplifiedE;
1022 }
1023 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001024 Value *V =
1025 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001026 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1027 return SimplifiedE;
1028 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001029 Value *V =
1030 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001031 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1032 return SimplifiedE;
1033 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001034 Value *V = SimplifyGEPInst(
1035 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001036 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1037 return SimplifiedE;
1038 } else if (AllConstant) {
1039 // We don't bother trying to simplify unless all of the operands
1040 // were constant.
1041 // TODO: There are a lot of Simplify*'s we could call here, if we
1042 // wanted to. The original motivating case for this code was a
1043 // zext i1 false to i8, which we don't have an interface to
1044 // simplify (IE there is no SimplifyZExt).
1045
1046 SmallVector<Constant *, 8> C;
1047 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001048 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +00001049
Daniel Berlin64e68992017-03-12 04:46:45 +00001050 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +00001051 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1052 return SimplifiedE;
1053 }
1054 return E;
1055}
1056
1057const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001058NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001059 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001060 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001061 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001062 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001063 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001064 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001065 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001066 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001067 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001068 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001069 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001070 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001071 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001072 return E;
1073 }
1074 llvm_unreachable("Unhandled type of aggregate value operation");
1075}
1076
Daniel Berline021d2d2017-05-19 20:22:20 +00001077const DeadExpression *NewGVN::createDeadExpression() const {
1078 // DeadExpression has no arguments and all DeadExpression's are the same,
1079 // so we only need one of them.
1080 return SingletonDeadExpression;
1081}
1082
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001083const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001084 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001085 E->setOpcode(V->getValueID());
1086 return E;
1087}
1088
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001089const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001090 if (auto *C = dyn_cast<Constant>(V))
1091 return createConstantExpression(C);
1092 return createVariableExpression(V);
1093}
1094
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001095const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001096 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +00001097 E->setOpcode(C->getValueID());
1098 return E;
1099}
1100
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001101const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001102 auto *E = new (ExpressionAllocator) UnknownExpression(I);
1103 E->setOpcode(I->getOpcode());
1104 return E;
1105}
1106
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001107const CallExpression *
1108NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001109 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001110 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +00001111 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +00001112 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001113 return E;
1114}
1115
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001116// Return true if some equivalent of instruction Inst dominates instruction U.
1117bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1118 const Instruction *U) const {
1119 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +00001120 // This must be an instruction because we are only called from phi nodes
1121 // in the case that the value it needs to check against is an instruction.
1122
1123 // The most likely candiates for dominance are the leader and the next leader.
1124 // The leader or nextleader will dominate in all cases where there is an
1125 // equivalent that is higher up in the dom tree.
1126 // We can't *only* check them, however, because the
1127 // dominator tree could have an infinite number of non-dominating siblings
1128 // with instructions that are in the right congruence class.
1129 // A
1130 // B C D E F G
1131 // |
1132 // H
1133 // Instruction U could be in H, with equivalents in every other sibling.
1134 // Depending on the rpo order picked, the leader could be the equivalent in
1135 // any of these siblings.
1136 if (!CC)
1137 return false;
Daniel Berlina8236562017-04-07 18:38:09 +00001138 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001139 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001140 if (CC->getNextLeader().first &&
1141 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001142 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001143 return llvm::any_of(*CC, [&](const Value *Member) {
1144 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001145 DT->dominates(cast<Instruction>(Member), U);
1146 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001147}
1148
Davide Italiano7e274e02016-12-22 16:03:48 +00001149// See if we have a congruence class and leader for this operand, and if so,
1150// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001151Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001152 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001153 if (CC) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001154 // Everything in TOP is represented by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001155 // We do have to make sure we get the type right though, so we can't set the
1156 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001157 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001158 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001159 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001160 }
1161
Davide Italiano7e274e02016-12-22 16:03:48 +00001162 return V;
1163}
1164
Daniel Berlin1316a942017-04-06 18:52:50 +00001165const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1166 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001167 assert(CC->getMemoryLeader() &&
Davide Italianob60f6e02017-05-12 15:25:56 +00001168 "Every MemoryAccess should be mapped to a congruence class with a "
1169 "representative memory access");
Daniel Berlina8236562017-04-07 18:38:09 +00001170 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001171}
1172
Daniel Berlinc4796862017-01-27 02:37:11 +00001173// Return true if the MemoryAccess is really equivalent to everything. This is
1174// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001175// state of all MemoryAccesses.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001176bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001177 return getMemoryClass(MA) == TOPClass;
1178}
1179
Davide Italiano7e274e02016-12-22 16:03:48 +00001180LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001181 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001182 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001183 auto *E =
1184 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001185 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1186 E->setType(LoadType);
1187
1188 // Give store and loads same opcode so they value number together.
1189 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001190 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001191 if (LI)
1192 E->setAlignment(LI->getAlignment());
1193
1194 // TODO: Value number heap versions. We may be able to discover
1195 // things alias analysis can't on it's own (IE that a store and a
1196 // load have the same value, and thus, it isn't clobbering the load).
1197 return E;
1198}
1199
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001200const StoreExpression *
1201NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001202 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001203 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001204 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001205 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1206 E->setType(SI->getValueOperand()->getType());
1207
1208 // Give store and loads same opcode so they value number together.
1209 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001210 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001211
1212 // TODO: Value number heap versions. We may be able to discover
1213 // things alias analysis can't on it's own (IE that a store and a
1214 // load have the same value, and thus, it isn't clobbering the load).
1215 return E;
1216}
1217
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001218const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001219 // Unlike loads, we never try to eliminate stores, so we do not check if they
1220 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001221 auto *SI = cast<StoreInst>(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001222 auto *StoreAccess = getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001223 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001224 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1225 if (EnableStoreRefinement)
1226 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1227 // If we bypassed the use-def chains, make sure we add a use.
1228 if (StoreRHS != StoreAccess->getDefiningAccess())
1229 addMemoryUsers(StoreRHS, StoreAccess);
Daniel Berlin1316a942017-04-06 18:52:50 +00001230 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001231 // If we are defined by ourselves, use the live on entry def.
1232 if (StoreRHS == StoreAccess)
1233 StoreRHS = MSSA->getLiveOnEntryDef();
1234
Daniel Berlin589cecc2017-01-02 18:00:46 +00001235 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001236 // See if we are defined by a previous store expression, it already has a
1237 // value, and it's the same value as our current store. FIXME: Right now, we
1238 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001239 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1240 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +00001241 // Basically, check if the congruence class the store is in is defined by a
1242 // store that isn't us, and has the same value. MemorySSA takes care of
1243 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +00001244 // The RepStoredValue gets nulled if all the stores disappear in a class, so
1245 // we don't need to check if the class contains a store besides us.
Daniel Berlin1316a942017-04-06 18:52:50 +00001246 if (LastCC &&
Daniel Berlina8236562017-04-07 18:38:09 +00001247 LastCC->getStoredValue() == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin1316a942017-04-06 18:52:50 +00001248 return LastStore;
1249 deleteExpression(LastStore);
Daniel Berlinc4796862017-01-27 02:37:11 +00001250 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001251 // location, and the memory state is the same as it was then (otherwise, it
1252 // could have been overwritten later. See test32 in
1253 // transforms/DeadStoreElimination/simple.ll).
1254 if (auto *LI =
1255 dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001256 if ((lookupOperandLeader(LI->getPointerOperand()) ==
1257 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001258 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
Daniel Berlin1316a942017-04-06 18:52:50 +00001259 StoreRHS))
Davide Italiano9a0f5422017-05-20 00:46:54 +00001260 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001261 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001262 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001263
1264 // If the store is not equivalent to anything, value number it as a store that
1265 // produces a unique memory state (instead of using it's MemoryUse, we use
1266 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001267 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001268}
1269
Daniel Berlin07daac82017-04-02 13:23:44 +00001270// See if we can extract the value of a loaded pointer from a load, a store, or
1271// a memory instruction.
1272const Expression *
1273NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1274 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001275 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001276 assert((!LI || LI->isSimple()) && "Not a simple load");
1277 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1278 // Can't forward from non-atomic to atomic without violating memory model.
1279 // Also don't need to coerce if they are the same type, we will just
1280 // propogate..
1281 if (LI->isAtomic() > DepSI->isAtomic() ||
1282 LoadType == DepSI->getValueOperand()->getType())
1283 return nullptr;
1284 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1285 if (Offset >= 0) {
1286 if (auto *C = dyn_cast<Constant>(
1287 lookupOperandLeader(DepSI->getValueOperand()))) {
1288 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1289 << *C << "\n");
1290 return createConstantExpression(
1291 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1292 }
1293 }
1294
1295 } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1296 // Can't forward from non-atomic to atomic without violating memory model.
1297 if (LI->isAtomic() > DepLI->isAtomic())
1298 return nullptr;
1299 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1300 if (Offset >= 0) {
1301 // We can coerce a constant load into a load
1302 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1303 if (auto *PossibleConstant =
1304 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1305 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1306 << *PossibleConstant << "\n");
1307 return createConstantExpression(PossibleConstant);
1308 }
1309 }
1310
1311 } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1312 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1313 if (Offset >= 0) {
1314 if (auto *PossibleConstant =
1315 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1316 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1317 << " to constant " << *PossibleConstant << "\n");
1318 return createConstantExpression(PossibleConstant);
1319 }
1320 }
1321 }
1322
1323 // All of the below are only true if the loaded pointer is produced
1324 // by the dependent instruction.
1325 if (LoadPtr != lookupOperandLeader(DepInst) &&
1326 !AA->isMustAlias(LoadPtr, DepInst))
1327 return nullptr;
1328 // If this load really doesn't depend on anything, then we must be loading an
1329 // undef value. This can happen when loading for a fresh allocation with no
1330 // intervening stores, for example. Note that this is only true in the case
1331 // that the result of the allocation is pointer equal to the load ptr.
1332 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1333 return createConstantExpression(UndefValue::get(LoadType));
1334 }
1335 // If this load occurs either right after a lifetime begin,
1336 // then the loaded value is undefined.
1337 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1338 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1339 return createConstantExpression(UndefValue::get(LoadType));
1340 }
1341 // If this load follows a calloc (which zero initializes memory),
1342 // then the loaded value is zero
1343 else if (isCallocLikeFn(DepInst, TLI)) {
1344 return createConstantExpression(Constant::getNullValue(LoadType));
1345 }
1346
1347 return nullptr;
1348}
1349
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001350const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001351 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001352
1353 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001354 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001355 if (!LI->isSimple())
1356 return nullptr;
1357
Daniel Berlin203f47b2017-01-31 22:31:53 +00001358 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001359 // Load of undef is undef.
1360 if (isa<UndefValue>(LoadAddressLeader))
1361 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001362 MemoryAccess *OriginalAccess = getMemoryAccess(I);
1363 MemoryAccess *DefiningAccess =
1364 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001365
1366 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1367 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1368 Instruction *DefiningInst = MD->getMemoryInst();
1369 // If the defining instruction is not reachable, replace with undef.
1370 if (!ReachableBlocks.count(DefiningInst->getParent()))
1371 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001372 // This will handle stores and memory insts. We only do if it the
1373 // defining access has a different type, or it is a pointer produced by
1374 // certain memory operations that cause the memory to have a fixed value
1375 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001376 if (const auto *CoercionResult =
1377 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1378 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001379 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001380 }
1381 }
1382
Daniel Berlin1316a942017-04-06 18:52:50 +00001383 const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1384 LI, DefiningAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001385 return E;
1386}
1387
Daniel Berlinf7d95802017-02-18 23:06:50 +00001388const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001389NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001390 auto *PI = PredInfo->getPredicateInfoFor(I);
1391 if (!PI)
1392 return nullptr;
1393
1394 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001395
1396 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1397 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001398 return nullptr;
1399
Daniel Berlinfccbda92017-02-22 22:20:58 +00001400 auto *CopyOf = I->getOperand(0);
1401 auto *Cond = PWC->Condition;
1402
Daniel Berlinf7d95802017-02-18 23:06:50 +00001403 // If this a copy of the condition, it must be either true or false depending
1404 // on the predicate info type and edge
1405 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001406 // We should not need to add predicate users because the predicate info is
1407 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001408 if (isa<PredicateAssume>(PI))
1409 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1410 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1411 if (PBranch->TrueEdge)
1412 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1413 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1414 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001415 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1416 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001417 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001418
Daniel Berlinf7d95802017-02-18 23:06:50 +00001419 // Not a copy of the condition, so see what the predicates tell us about this
1420 // value. First, though, we check to make sure the value is actually a copy
1421 // of one of the condition operands. It's possible, in certain cases, for it
1422 // to be a copy of a predicateinfo copy. In particular, if two branch
1423 // operations use the same condition, and one branch dominates the other, we
1424 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001425 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001426 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001427
1428 // Everything below relies on the condition being a comparison.
1429 auto *Cmp = dyn_cast<CmpInst>(Cond);
1430 if (!Cmp)
1431 return nullptr;
1432
1433 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Davide Italianoc43a9f82017-05-12 15:28:12 +00001434 DEBUG(dbgs() << "Copy is not of any condition operands!\n");
Daniel Berlinf7d95802017-02-18 23:06:50 +00001435 return nullptr;
1436 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001437 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1438 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001439 bool SwappedOps = false;
1440 // Sort the ops
1441 if (shouldSwapOperands(FirstOp, SecondOp)) {
1442 std::swap(FirstOp, SecondOp);
1443 SwappedOps = true;
1444 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001445 CmpInst::Predicate Predicate =
1446 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1447
1448 if (isa<PredicateAssume>(PI)) {
1449 // If the comparison is true when the operands are equal, then we know the
1450 // operands are equal, because assumes must always be true.
1451 if (CmpInst::isTrueWhenEqual(Predicate)) {
1452 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001453 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001454 return createVariableOrConstant(FirstOp);
1455 }
1456 }
1457 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1458 // If we are *not* a copy of the comparison, we may equal to the other
1459 // operand when the predicate implies something about equality of
1460 // operations. In particular, if the comparison is true/false when the
1461 // operands are equal, and we are on the right edge, we know this operation
1462 // is equal to something.
1463 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1464 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1465 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001466 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001467 return createVariableOrConstant(FirstOp);
1468 }
1469 // Handle the special case of floating point.
1470 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1471 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1472 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1473 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001474 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001475 return createConstantExpression(cast<Constant>(FirstOp));
1476 }
1477 }
1478 return nullptr;
1479}
1480
Davide Italiano7e274e02016-12-22 16:03:48 +00001481// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001482const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001483 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001484 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1485 // Instrinsics with the returned attribute are copies of arguments.
1486 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1487 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1488 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1489 return Result;
1490 return createVariableOrConstant(ReturnedValue);
1491 }
1492 }
1493 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001494 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001495 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001496 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001497 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001498 }
1499 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001500}
1501
Daniel Berlin1316a942017-04-06 18:52:50 +00001502// Retrieve the memory class for a given MemoryAccess.
1503CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1504
1505 auto *Result = MemoryAccessToClass.lookup(MA);
1506 assert(Result && "Should have found memory class");
1507 return Result;
1508}
1509
1510// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001511// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001512bool NewGVN::setMemoryClass(const MemoryAccess *From,
1513 CongruenceClass *NewClass) {
1514 assert(NewClass &&
1515 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001516 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001517 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001518 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
Davide Italianob7a66982017-05-09 20:02:48 +00001519 DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001520
1521 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001522 bool Changed = false;
1523 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001524 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001525 auto *OldClass = LookupResult->second;
1526 if (OldClass != NewClass) {
1527 // If this is a phi, we have to handle memory member updates.
1528 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001529 OldClass->memory_erase(MP);
1530 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001531 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001532 if (OldClass->getMemoryLeader() == From) {
Davide Italiano41f5c7b2017-05-12 15:22:45 +00001533 if (OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001534 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001535 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001536 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001537 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001538 << OldClass->getID() << " to "
1539 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001540 << " due to removal of a memory member " << *From
1541 << "\n");
1542 markMemoryLeaderChangeTouched(OldClass);
1543 }
1544 }
1545 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001546 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001547 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001548 Changed = true;
1549 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001550 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001551
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001552 return Changed;
1553}
Daniel Berlin0e900112017-03-24 06:33:48 +00001554
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001555// Determine if a instruction is cycle-free. That means the values in the
1556// instruction don't depend on any expressions that can change value as a result
1557// of the instruction. For example, a non-cycle free instruction would be v =
1558// phi(0, v+1).
1559bool NewGVN::isCycleFree(const Instruction *I) const {
1560 // In order to compute cycle-freeness, we do SCC finding on the instruction,
1561 // and see what kind of SCC it ends up in. If it is a singleton, it is
1562 // cycle-free. If it is not in a singleton, it is only cycle free if the
1563 // other members are all phi nodes (as they do not compute anything, they are
1564 // copies).
1565 auto ICS = InstCycleState.lookup(I);
1566 if (ICS == ICS_Unknown) {
1567 SCCFinder.Start(I);
1568 auto &SCC = SCCFinder.getComponentFor(I);
Daniel Berlin2f72b192017-04-14 02:53:37 +00001569 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1570 if (SCC.size() == 1)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001571 InstCycleState.insert({I, ICS_CycleFree});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001572 else {
1573 bool AllPhis =
1574 llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001575 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
Daniel Berlin2f72b192017-04-14 02:53:37 +00001576 for (auto *Member : SCC)
1577 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001578 InstCycleState.insert({MemberPhi, ICS});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001579 }
1580 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001581 if (ICS == ICS_Cycle)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001582 return false;
1583 return true;
1584}
1585
Davide Italiano7e274e02016-12-22 16:03:48 +00001586// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001587const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001588 // True if one of the incoming phi edges is a backedge.
1589 bool HasBackedge = false;
1590 // All constant tracks the state of whether all the *original* phi operands
Daniel Berline021d2d2017-05-19 20:22:20 +00001591 // This is really shorthand for "this phi cannot cycle due to forward
1592 // change in value of the phi is guaranteed not to later change the value of
1593 // the phi. IE it can't be v = phi(undef, v+1)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001594 bool AllConstant = true;
Daniel Berlinabd632d2017-05-16 06:06:12 +00001595 auto *E =
1596 cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001597 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001598 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001599 // We track if any were undef because they need special handling.
1600 bool HasUndef = false;
Daniel Berlind130b6c2017-05-21 23:41:58 +00001601 bool CycleFree = isCycleFree(I);
Daniel Berline021d2d2017-05-19 20:22:20 +00001602 auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
1603 if (Arg == nullptr)
1604 return false;
1605 // Original self-operands are already eliminated during expression creation.
1606 // We can only eliminate value-wise self-operands if it's cycle
1607 // free. Otherwise, eliminating the operand can cause our value to change,
1608 // which can cause us to not eliminate the operand, which changes the value
1609 // back to what it was before, cycling forever.
1610 if (CycleFree && Arg == I)
Daniel Berlind92e7f92017-01-07 00:01:42 +00001611 return false;
1612 if (isa<UndefValue>(Arg)) {
1613 HasUndef = true;
1614 return false;
1615 }
1616 return true;
1617 });
Daniel Berline021d2d2017-05-19 20:22:20 +00001618 // If we are left with no operands, it's dead.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001619 if (Filtered.begin() == Filtered.end()) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001620 DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001621 deleteExpression(E);
Daniel Berline021d2d2017-05-19 20:22:20 +00001622 return createDeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00001623 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001624 unsigned NumOps = 0;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001625 Value *AllSameValue = *(Filtered.begin());
1626 ++Filtered.begin();
1627 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berline021d2d2017-05-19 20:22:20 +00001628 if (llvm::all_of(Filtered, [&](Value *Arg) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001629 ++NumOps;
Daniel Berline021d2d2017-05-19 20:22:20 +00001630 return Arg == AllSameValue;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001631 })) {
1632 // In LLVM's non-standard representation of phi nodes, it's possible to have
1633 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1634 // on the original phi node), especially in weird CFG's where some arguments
1635 // are unreachable, or uninitialized along certain paths. This can cause
1636 // infinite loops during evaluation. We work around this by not trying to
1637 // really evaluate them independently, but instead using a variable
1638 // expression to say if one is equivalent to the other.
1639 // We also special case undef, so that if we have an undef, we can't use the
1640 // common value unless it dominates the phi block.
1641 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001642 // If we have undef and at least one other value, this is really a
1643 // multivalued phi, and we need to know if it's cycle free in order to
1644 // evaluate whether we can ignore the undef. The other parts of this are
1645 // just shortcuts. If there is no backedge, or all operands are
1646 // constants, or all operands are ignored but the undef, it also must be
1647 // cycle free.
1648 if (!AllConstant && HasBackedge && NumOps > 0 &&
Daniel Berline021d2d2017-05-19 20:22:20 +00001649 !isa<UndefValue>(AllSameValue) && !CycleFree)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001650 return E;
1651
Daniel Berlind92e7f92017-01-07 00:01:42 +00001652 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001653 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001654 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001655 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001656 }
1657
Davide Italiano7e274e02016-12-22 16:03:48 +00001658 NumGVNPhisAllSame++;
1659 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1660 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001661 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001662 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001663 }
1664 return E;
1665}
1666
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001667const Expression *
1668NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001669 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1670 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1671 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1672 unsigned Opcode = 0;
1673 // EI might be an extract from one of our recognised intrinsics. If it
1674 // is we'll synthesize a semantically equivalent expression instead on
1675 // an extract value expression.
1676 switch (II->getIntrinsicID()) {
1677 case Intrinsic::sadd_with_overflow:
1678 case Intrinsic::uadd_with_overflow:
1679 Opcode = Instruction::Add;
1680 break;
1681 case Intrinsic::ssub_with_overflow:
1682 case Intrinsic::usub_with_overflow:
1683 Opcode = Instruction::Sub;
1684 break;
1685 case Intrinsic::smul_with_overflow:
1686 case Intrinsic::umul_with_overflow:
1687 Opcode = Instruction::Mul;
1688 break;
1689 default:
1690 break;
1691 }
1692
1693 if (Opcode != 0) {
1694 // Intrinsic recognized. Grab its args to finish building the
1695 // expression.
1696 assert(II->getNumArgOperands() == 2 &&
1697 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001698 return createBinaryExpression(
1699 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001700 }
1701 }
1702 }
1703
Daniel Berlin97718e62017-01-31 22:32:03 +00001704 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001705}
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001706const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001707 auto *CI = dyn_cast<CmpInst>(I);
1708 // See if our operands are equal to those of a previous predicate, and if so,
1709 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001710 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1711 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001712 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001713 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001714 std::swap(Op0, Op1);
1715 OurPredicate = CI->getSwappedPredicate();
1716 }
1717
1718 // Avoid processing the same info twice
1719 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001720 // See if we know something about the comparison itself, like it is the target
1721 // of an assume.
1722 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1723 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1724 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1725
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001726 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001727 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001728 if (CI->isTrueWhenEqual())
1729 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1730 else if (CI->isFalseWhenEqual())
1731 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1732 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001733
1734 // NOTE: Because we are comparing both operands here and below, and using
1735 // previous comparisons, we rely on fact that predicateinfo knows to mark
1736 // comparisons that use renamed operands as users of the earlier comparisons.
1737 // It is *not* enough to just mark predicateinfo renamed operands as users of
1738 // the earlier comparisons, because the *other* operand may have changed in a
1739 // previous iteration.
1740 // Example:
1741 // icmp slt %a, %b
1742 // %b.0 = ssa.copy(%b)
1743 // false branch:
1744 // icmp slt %c, %b.0
1745
1746 // %c and %a may start out equal, and thus, the code below will say the second
1747 // %icmp is false. c may become equal to something else, and in that case the
1748 // %second icmp *must* be reexamined, but would not if only the renamed
1749 // %operands are considered users of the icmp.
1750
1751 // *Currently* we only check one level of comparisons back, and only mark one
1752 // level back as touched when changes appen . If you modify this code to look
1753 // back farther through comparisons, you *must* mark the appropriate
1754 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1755 // we know something just from the operands themselves
1756
1757 // See if our operands have predicate info, so that we may be able to derive
1758 // something from a previous comparison.
1759 for (const auto &Op : CI->operands()) {
1760 auto *PI = PredInfo->getPredicateInfoFor(Op);
1761 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1762 if (PI == LastPredInfo)
1763 continue;
1764 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001765
Daniel Berlinf7d95802017-02-18 23:06:50 +00001766 // TODO: Along the false edge, we may know more things too, like icmp of
1767 // same operands is false.
1768 // TODO: We only handle actual comparison conditions below, not and/or.
1769 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1770 if (!BranchCond)
1771 continue;
1772 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1773 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1774 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001775 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001776 std::swap(BranchOp0, BranchOp1);
1777 BranchPredicate = BranchCond->getSwappedPredicate();
1778 }
1779 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1780 if (PBranch->TrueEdge) {
1781 // If we know the previous predicate is true and we are in the true
1782 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001783 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1784 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001785 addPredicateUsers(PI, I);
1786 return createConstantExpression(
1787 ConstantInt::getTrue(CI->getType()));
1788 }
1789
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001790 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1791 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001792 addPredicateUsers(PI, I);
1793 return createConstantExpression(
1794 ConstantInt::getFalse(CI->getType()));
1795 }
1796
1797 } else {
1798 // Just handle the ne and eq cases, where if we have the same
1799 // operands, we may know something.
1800 if (BranchPredicate == OurPredicate) {
1801 addPredicateUsers(PI, I);
1802 // Same predicate, same ops,we know it was false, so this is false.
1803 return createConstantExpression(
1804 ConstantInt::getFalse(CI->getType()));
1805 } else if (BranchPredicate ==
1806 CmpInst::getInversePredicate(OurPredicate)) {
1807 addPredicateUsers(PI, I);
1808 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001809 return createConstantExpression(
1810 ConstantInt::getTrue(CI->getType()));
1811 }
1812 }
1813 }
1814 }
1815 }
1816 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001817 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001818}
Davide Italiano7e274e02016-12-22 16:03:48 +00001819
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001820// Return true if V is a value that will always be available (IE can
1821// be placed anywhere) in the function. We don't do globals here
1822// because they are often worse to put in place.
1823// TODO: Separate cost from availability
1824static bool alwaysAvailable(Value *V) {
1825 return isa<Constant>(V) || isa<Argument>(V);
1826}
1827
Davide Italiano7e274e02016-12-22 16:03:48 +00001828// Substitute and symbolize the value before value numbering.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001829const Expression *
1830NewGVN::performSymbolicEvaluation(Value *V,
1831 SmallPtrSetImpl<Value *> &Visited) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001832 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001833 if (auto *C = dyn_cast<Constant>(V))
1834 E = createConstantExpression(C);
1835 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1836 E = createVariableExpression(V);
1837 } else {
1838 // TODO: memory intrinsics.
1839 // TODO: Some day, we should do the forward propagation and reassociation
1840 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001841 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001842 switch (I->getOpcode()) {
1843 case Instruction::ExtractValue:
1844 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001845 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001846 break;
1847 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001848 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001849 break;
1850 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001851 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001852 break;
1853 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001854 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001855 break;
1856 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001857 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001858 break;
1859 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001860 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001861 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001862 case Instruction::ICmp:
1863 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001864 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001865 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001866 case Instruction::Add:
1867 case Instruction::FAdd:
1868 case Instruction::Sub:
1869 case Instruction::FSub:
1870 case Instruction::Mul:
1871 case Instruction::FMul:
1872 case Instruction::UDiv:
1873 case Instruction::SDiv:
1874 case Instruction::FDiv:
1875 case Instruction::URem:
1876 case Instruction::SRem:
1877 case Instruction::FRem:
1878 case Instruction::Shl:
1879 case Instruction::LShr:
1880 case Instruction::AShr:
1881 case Instruction::And:
1882 case Instruction::Or:
1883 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001884 case Instruction::Trunc:
1885 case Instruction::ZExt:
1886 case Instruction::SExt:
1887 case Instruction::FPToUI:
1888 case Instruction::FPToSI:
1889 case Instruction::UIToFP:
1890 case Instruction::SIToFP:
1891 case Instruction::FPTrunc:
1892 case Instruction::FPExt:
1893 case Instruction::PtrToInt:
1894 case Instruction::IntToPtr:
1895 case Instruction::Select:
1896 case Instruction::ExtractElement:
1897 case Instruction::InsertElement:
1898 case Instruction::ShuffleVector:
1899 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001900 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001901 break;
1902 default:
1903 return nullptr;
1904 }
1905 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001906 return E;
1907}
1908
Daniel Berlin0207cca2017-05-21 23:41:56 +00001909// Look up a container in a map, and then call a function for each thing in the
1910// found container.
1911template <typename Map, typename KeyType, typename Func>
1912void NewGVN::for_each_found(Map &M, const KeyType &Key, Func F) {
1913 const auto Result = M.find_as(Key);
1914 if (Result != M.end())
1915 for (typename Map::mapped_type::value_type Mapped : Result->second)
1916 F(Mapped);
1917}
1918
1919// Look up a container of values/instructions in a map, and touch all the
1920// instructions in the container. Then erase value from the map.
1921template <typename Map, typename KeyType>
1922void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
1923 const auto Result = M.find_as(Key);
1924 if (Result != M.end()) {
1925 for (const typename Map::mapped_type::value_type Mapped : Result->second)
1926 TouchedInstructions.set(InstrToDFSNum(Mapped));
1927 M.erase(Result);
1928 }
1929}
1930
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001931void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
1932 AdditionalUsers[To].insert(User);
1933}
1934
Davide Italiano7e274e02016-12-22 16:03:48 +00001935void NewGVN::markUsersTouched(Value *V) {
1936 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001937 for (auto *User : V->users()) {
1938 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001939 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001940 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00001941 touchAndErase(AdditionalUsers, V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001942}
1943
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001944void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001945 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1946 MemoryToUsers[To].insert(U);
1947}
1948
1949void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001950 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00001951}
1952
1953void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1954 if (isa<MemoryUse>(MA))
1955 return;
1956 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00001957 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin0207cca2017-05-21 23:41:56 +00001958 touchAndErase(MemoryToUsers, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001959}
1960
Daniel Berlinf7d95802017-02-18 23:06:50 +00001961// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001962void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001963 // Don't add temporary instructions to the user lists.
1964 if (AllTempInstructions.count(I))
1965 return;
1966
Daniel Berlinf7d95802017-02-18 23:06:50 +00001967 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1968 PredicateToUsers[PBranch->Condition].insert(I);
1969 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1970 PredicateToUsers[PAssume->Condition].insert(I);
1971}
1972
1973// Touch all the predicates that depend on this instruction.
1974void NewGVN::markPredicateUsersTouched(Instruction *I) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00001975 touchAndErase(PredicateToUsers, I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001976}
1977
Daniel Berlin1316a942017-04-06 18:52:50 +00001978// Mark users affected by a memory leader change.
1979void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001980 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00001981 markMemoryDefTouched(M);
1982}
1983
Daniel Berlin32f8d562017-01-07 16:55:14 +00001984// Touch the instructions that need to be updated after a congruence class has a
1985// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00001986void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001987 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001988 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00001989 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001990 LeaderChanges.insert(M);
1991 }
1992}
1993
Daniel Berlin1316a942017-04-06 18:52:50 +00001994// Give a range of things that have instruction DFS numbers, this will return
1995// the member of the range with the smallest dfs number.
1996template <class T, class Range>
1997T *NewGVN::getMinDFSOfRange(const Range &R) const {
1998 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
1999 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002000 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00002001 if (DFSNum < MinDFS.second)
2002 MinDFS = {X, DFSNum};
2003 }
2004 return MinDFS.first;
2005}
2006
2007// This function returns the MemoryAccess that should be the next leader of
2008// congruence class CC, under the assumption that the current leader is going to
2009// disappear.
2010const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2011 // TODO: If this ends up to slow, we can maintain a next memory leader like we
2012 // do for regular leaders.
2013 // Make sure there will be a leader to find
Davide Italianodc435322017-05-10 19:57:43 +00002014 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00002015 if (CC->getStoreCount() > 0) {
2016 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002017 return getMemoryAccess(NL);
Daniel Berlin1316a942017-04-06 18:52:50 +00002018 // Find the store with the minimum DFS number.
2019 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00002020 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002021 return getMemoryAccess(cast<StoreInst>(V));
Daniel Berlin1316a942017-04-06 18:52:50 +00002022 }
Daniel Berlina8236562017-04-07 18:38:09 +00002023 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00002024
2025 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00002026 // !OldClass->memory_empty()
2027 if (CC->memory_size() == 1)
2028 return *CC->memory_begin();
2029 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00002030}
2031
2032// This function returns the next value leader of a congruence class, under the
2033// assumption that the current leader is going away. This should end up being
2034// the next most dominating member.
2035Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2036 // We don't need to sort members if there is only 1, and we don't care about
2037 // sorting the TOP class because everything either gets out of it or is
2038 // unreachable.
2039
Daniel Berlina8236562017-04-07 18:38:09 +00002040 if (CC->size() == 1 || CC == TOPClass) {
2041 return *(CC->begin());
2042 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002043 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00002044 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00002045 } else {
2046 ++NumGVNSortedLeaderChanges;
2047 // NOTE: If this ends up to slow, we can maintain a dual structure for
2048 // member testing/insertion, or keep things mostly sorted, and sort only
2049 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00002050 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00002051 }
2052}
2053
2054// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2055// the memory members, etc for the move.
2056//
2057// The invariants of this function are:
2058//
2059// I must be moving to NewClass from OldClass The StoreCount of OldClass and
2060// NewClass is expected to have been updated for I already if it is is a store.
2061// The OldClass memory leader has not been updated yet if I was the leader.
2062void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2063 MemoryAccess *InstMA,
2064 CongruenceClass *OldClass,
2065 CongruenceClass *NewClass) {
2066 // If the leader is I, and we had a represenative MemoryAccess, it should
2067 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00002068 assert((!InstMA || !OldClass->getMemoryLeader() ||
2069 OldClass->getLeader() != I ||
2070 OldClass->getMemoryLeader() == InstMA) &&
2071 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00002072 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00002073 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002074 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00002075 assert(NewClass->size() == 1 ||
2076 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2077 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00002078 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00002079 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002080 << " due to new memory instruction becoming leader\n");
2081 markMemoryLeaderChangeTouched(NewClass);
2082 }
2083 setMemoryClass(InstMA, NewClass);
2084 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00002085 if (OldClass->getMemoryLeader() == InstMA) {
Davide Italianodc435322017-05-10 19:57:43 +00002086 if (!OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00002087 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2088 DEBUG(dbgs() << "Memory class leader change for class "
2089 << OldClass->getID() << " to "
2090 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00002091 << " due to removal of old leader " << *InstMA << "\n");
2092 markMemoryLeaderChangeTouched(OldClass);
2093 } else
Daniel Berlina8236562017-04-07 18:38:09 +00002094 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00002095 }
2096}
2097
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002098// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00002099// Update OldClass and NewClass for the move (including changing leaders, etc).
2100void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002101 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002102 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00002103 if (I == OldClass->getNextLeader().first)
2104 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002105
Daniel Berlinff152002017-05-19 19:01:24 +00002106 OldClass->erase(I);
2107 NewClass->insert(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002108
Daniel Berlina8236562017-04-07 18:38:09 +00002109 if (NewClass->getLeader() != I)
2110 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlin1316a942017-04-06 18:52:50 +00002111 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002112 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002113 OldClass->decStoreCount();
2114 // Okay, so when do we want to make a store a leader of a class?
2115 // If we have a store defined by an earlier load, we want the earlier load
2116 // to lead the class.
2117 // If we have a store defined by something else, we want the store to lead
2118 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00002119 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00002120 // as the leader
2121 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002122 // If it's a store expression we are using, it means we are not equivalent
2123 // to something earlier.
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002124 if (auto *SE = dyn_cast<StoreExpression>(E)) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002125 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1316a942017-04-06 18:52:50 +00002126 markValueLeaderChangeTouched(NewClass);
2127 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00002128 DEBUG(dbgs() << "Changing leader of congruence class "
2129 << NewClass->getID() << " from " << *NewClass->getLeader()
2130 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002131 // If we changed the leader, we have to mark it changed because we don't
2132 // know what it will do to symbolic evlauation.
Daniel Berlina8236562017-04-07 18:38:09 +00002133 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002134 }
2135 // We rely on the code below handling the MemoryAccess change.
2136 }
Daniel Berlina8236562017-04-07 18:38:09 +00002137 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002138 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002139 // True if there is no memory instructions left in a class that had memory
2140 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002141
Daniel Berlin1316a942017-04-06 18:52:50 +00002142 // If it's not a memory use, set the MemoryAccess equivalence
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002143 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
Daniel Berlin1316a942017-04-06 18:52:50 +00002144 if (InstMA)
2145 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002146 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002147 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002148 if (OldClass->empty() && OldClass != TOPClass) {
2149 if (OldClass->getDefiningExpr()) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002150 DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002151 << " from table\n");
Daniel Berlina8236562017-04-07 18:38:09 +00002152 ExpressionToClass.erase(OldClass->getDefiningExpr());
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002153 }
Daniel Berlina8236562017-04-07 18:38:09 +00002154 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002155 // When the leader changes, the value numbering of
2156 // everything may change due to symbolization changes, so we need to
2157 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00002158 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002159 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002160 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002161 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002162 // Note that this is basically clean up for the expression removal that
2163 // happens below. If we remove stores from a class, we may leave it as a
2164 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002165 if (OldClass->getStoreCount() == 0) {
2166 if (OldClass->getStoredValue())
2167 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002168 }
Daniel Berlina8236562017-04-07 18:38:09 +00002169 OldClass->setLeader(getNextValueLeader(OldClass));
2170 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002171 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002172 }
2173}
2174
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002175// For a given expression, mark the phi of ops instructions that could have
2176// changed as a result.
2177void NewGVN::markPhiOfOpsChanged(const HashedExpression &HE) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00002178 touchAndErase(ExpressionToPhiOfOps, HE);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002179}
Daniel Berlin0207cca2017-05-21 23:41:56 +00002180
Davide Italiano7e274e02016-12-22 16:03:48 +00002181// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002182void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002183 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002184 // TOP.
Daniel Berline021d2d2017-05-19 20:22:20 +00002185
2186 CongruenceClass *IClass = ValueToClass.lookup(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002187 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002188 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002189 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002190
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002191 CongruenceClass *EClass = nullptr;
2192 HashedExpression HE(E);
Daniel Berlin02c6b172017-01-02 18:00:53 +00002193 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002194 EClass = ValueToClass.lookup(VE->getVariableValue());
Daniel Berline021d2d2017-05-19 20:22:20 +00002195 } else if (isa<DeadExpression>(E)) {
2196 EClass = TOPClass;
2197 }
2198 if (!EClass) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002199 auto lookupResult = ExpressionToClass.insert_as({E, nullptr}, HE);
Davide Italiano7e274e02016-12-22 16:03:48 +00002200
2201 // If it's not in the value table, create a new congruence class.
2202 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002203 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002204 auto place = lookupResult.first;
2205 place->second = NewClass;
2206
2207 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002208 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002209 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002210 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2211 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002212 NewClass->setLeader(SI);
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002213 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002214 // The RepMemoryAccess field will be filled in properly by the
2215 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002216 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002217 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002218 }
2219 assert(!isa<VariableExpression>(E) &&
2220 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002221
2222 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002223 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002224 << " using expression " << *E << " at " << NewClass->getID()
2225 << " and leader " << *(NewClass->getLeader()));
2226 if (NewClass->getStoredValue())
2227 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002228 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002229 } else {
2230 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002231 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002232 assert((isa<Constant>(EClass->getLeader()) ||
2233 (EClass->getStoredValue() &&
2234 isa<Constant>(EClass->getStoredValue()))) &&
2235 "Any class with a constant expression should have a "
2236 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002237
Davide Italiano7e274e02016-12-22 16:03:48 +00002238 assert(EClass && "Somehow don't have an eclass");
2239
Daniel Berlin1316a942017-04-06 18:52:50 +00002240 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002241 }
2242 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002243 bool ClassChanged = IClass != EClass;
2244 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002245 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002246 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002247 << "\n");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002248 if (ClassChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002249 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002250 markPhiOfOpsChanged(HE);
2251 }
2252
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002253 markUsersTouched(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002254 if (MemoryAccess *MA = getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002255 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002256 if (auto *CI = dyn_cast<CmpInst>(I))
2257 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002258 }
Daniel Berlin45403572017-05-16 19:58:47 +00002259 // If we changed the class of the store, we want to ensure nothing finds the
2260 // old store expression. In particular, loads do not compare against stored
2261 // value, so they will find old store expressions (and associated class
2262 // mappings) if we leave them in the table.
Davide Italianoee49f492017-05-19 04:06:10 +00002263 if (ClassChanged && isa<StoreInst>(I)) {
Daniel Berlin45403572017-05-16 19:58:47 +00002264 auto *OldE = ValueToExpression.lookup(I);
2265 // It could just be that the old class died. We don't want to erase it if we
2266 // just moved classes.
Davide Italianoee49f492017-05-19 04:06:10 +00002267 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE)
Daniel Berlin45403572017-05-16 19:58:47 +00002268 ExpressionToClass.erase(OldE);
2269 }
2270 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002271}
2272
2273// Process the fact that Edge (from, to) is reachable, including marking
2274// any newly reachable blocks and instructions for processing.
2275void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2276 // Check if the Edge was reachable before.
2277 if (ReachableEdges.insert({From, To}).second) {
2278 // If this block wasn't reachable before, all instructions are touched.
2279 if (ReachableBlocks.insert(To).second) {
2280 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2281 const auto &InstRange = BlockInstRange.lookup(To);
2282 TouchedInstructions.set(InstRange.first, InstRange.second);
2283 } else {
2284 DEBUG(dbgs() << "Block " << getBlockName(To)
2285 << " was reachable, but new edge {" << getBlockName(From)
2286 << "," << getBlockName(To) << "} to it found\n");
2287
2288 // We've made an edge reachable to an existing block, which may
2289 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2290 // they are the only thing that depend on new edges. Anything using their
2291 // values will get propagated to if necessary.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002292 if (MemoryAccess *MemPhi = getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002293 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002294
Davide Italiano7e274e02016-12-22 16:03:48 +00002295 auto BI = To->begin();
2296 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002297 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002298 ++BI;
2299 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00002300 for_each_found(PHIOfOpsPHIs, To, [&](const PHINode *I) {
2301 TouchedInstructions.set(InstrToDFSNum(I));
2302 });
Davide Italiano7e274e02016-12-22 16:03:48 +00002303 }
2304 }
2305}
2306
2307// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2308// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002309Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002310 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002311 if (isa<Constant>(Result))
2312 return Result;
2313 return nullptr;
2314}
2315
2316// Process the outgoing edges of a block for reachability.
2317void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2318 // Evaluate reachability of terminator instruction.
2319 BranchInst *BR;
2320 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2321 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002322 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002323 if (!CondEvaluated) {
2324 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002325 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002326 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2327 CondEvaluated = CE->getConstantValue();
2328 }
2329 } else if (isa<ConstantInt>(Cond)) {
2330 CondEvaluated = Cond;
2331 }
2332 }
2333 ConstantInt *CI;
2334 BasicBlock *TrueSucc = BR->getSuccessor(0);
2335 BasicBlock *FalseSucc = BR->getSuccessor(1);
2336 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2337 if (CI->isOne()) {
2338 DEBUG(dbgs() << "Condition for Terminator " << *TI
2339 << " evaluated to true\n");
2340 updateReachableEdge(B, TrueSucc);
2341 } else if (CI->isZero()) {
2342 DEBUG(dbgs() << "Condition for Terminator " << *TI
2343 << " evaluated to false\n");
2344 updateReachableEdge(B, FalseSucc);
2345 }
2346 } else {
2347 updateReachableEdge(B, TrueSucc);
2348 updateReachableEdge(B, FalseSucc);
2349 }
2350 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2351 // For switches, propagate the case values into the case
2352 // destinations.
2353
2354 // Remember how many outgoing edges there are to every successor.
2355 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2356
Davide Italiano7e274e02016-12-22 16:03:48 +00002357 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002358 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002359 // See if we were able to turn this switch statement into a constant.
2360 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002361 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002362 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002363 auto Case = *SI->findCaseValue(CondVal);
2364 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002365 // We proved the value is outside of the range of the case.
2366 // We can't do anything other than mark the default dest as reachable,
2367 // and go home.
2368 updateReachableEdge(B, SI->getDefaultDest());
2369 return;
2370 }
2371 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002372 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002373 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002374 } else {
2375 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2376 BasicBlock *TargetBlock = SI->getSuccessor(i);
2377 ++SwitchEdges[TargetBlock];
2378 updateReachableEdge(B, TargetBlock);
2379 }
2380 }
2381 } else {
2382 // Otherwise this is either unconditional, or a type we have no
2383 // idea about. Just mark successors as reachable.
2384 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2385 BasicBlock *TargetBlock = TI->getSuccessor(i);
2386 updateReachableEdge(B, TargetBlock);
2387 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002388
2389 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002390 // equivalent only to itself.
2391 //
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002392 auto *MA = getMemoryAccess(TI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002393 if (MA && !isa<MemoryUse>(MA)) {
2394 auto *CC = ensureLeaderOfMemoryClass(MA);
2395 if (setMemoryClass(MA, CC))
2396 markMemoryUsersTouched(MA);
2397 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002398 }
2399}
2400
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002401void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2402 Instruction *ExistingValue) {
2403 InstrDFS[Op] = InstrToDFSNum(ExistingValue);
2404 AllTempInstructions.insert(Op);
2405 PHIOfOpsPHIs[BB].push_back(Op);
2406 TempToBlock[Op] = BB;
2407 if (ExistingValue)
2408 RealToTemp[ExistingValue] = Op;
2409}
2410
2411static bool okayForPHIOfOps(const Instruction *I) {
2412 return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
2413 isa<LoadInst>(I);
2414}
2415
2416// When we see an instruction that is an op of phis, generate the equivalent phi
2417// of ops form.
2418const Expression *
2419NewGVN::makePossiblePhiOfOps(Instruction *I, bool HasBackedge,
2420 SmallPtrSetImpl<Value *> &Visited) {
2421 if (!okayForPHIOfOps(I))
2422 return nullptr;
2423
2424 if (!Visited.insert(I).second)
2425 return nullptr;
2426 // For now, we require the instruction be cycle free because we don't
2427 // *always* create a phi of ops for instructions that could be done as phi
2428 // of ops, we only do it if we think it is useful. If we did do it all the
2429 // time, we could remove the cycle free check.
2430 if (!isCycleFree(I))
2431 return nullptr;
2432
2433 unsigned IDFSNum = InstrToDFSNum(I);
2434 // Pretty much all of the instructions we can convert to phi of ops over a
2435 // backedge that are adds, are really induction variables, and those are
2436 // pretty much pointless to convert. This is very coarse-grained for a
2437 // test, so if we do find some value, we can change it later.
2438 // But otherwise, what can happen is we convert the induction variable from
2439 //
2440 // i = phi (0, tmp)
2441 // tmp = i + 1
2442 //
2443 // to
2444 // i = phi (0, tmpphi)
2445 // tmpphi = phi(1, tmpphi+1)
2446 //
2447 // Which we don't want to happen. We could just avoid this for all non-cycle
2448 // free phis, and we made go that route.
2449 if (HasBackedge && I->getOpcode() == Instruction::Add)
2450 return nullptr;
2451
2452 SmallPtrSet<const Value *, 8> ProcessedPHIs;
2453 // TODO: We don't do phi translation on memory accesses because it's
2454 // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2455 // which we don't have a good way of doing ATM.
2456 auto *MemAccess = getMemoryAccess(I);
2457 // If the memory operation is defined by a memory operation this block that
2458 // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2459 // can't help, as it would still be killed by that memory operation.
2460 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2461 MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2462 return nullptr;
2463
2464 // Convert op of phis to phi of ops
2465 for (auto &Op : I->operands()) {
2466 if (!isa<PHINode>(Op))
2467 continue;
2468 auto *OpPHI = cast<PHINode>(Op);
2469 // No point in doing this for one-operand phis.
2470 if (OpPHI->getNumOperands() == 1)
2471 continue;
2472 if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
2473 return nullptr;
2474 SmallVector<std::pair<Value *, BasicBlock *>, 4> Ops;
2475 auto *PHIBlock = getBlockForValue(OpPHI);
2476 for (auto PredBB : OpPHI->blocks()) {
2477 Value *FoundVal = nullptr;
2478 // We could just skip unreachable edges entirely but it's tricky to do
2479 // with rewriting existing phi nodes.
2480 if (ReachableEdges.count({PredBB, PHIBlock})) {
2481 // Clone the instruction, create an expression from it, and see if we
2482 // have a leader.
2483 Instruction *ValueOp = I->clone();
2484 auto Iter = TempToMemory.end();
2485 if (MemAccess)
2486 Iter = TempToMemory.insert({ValueOp, MemAccess}).first;
2487
2488 for (auto &Op : ValueOp->operands()) {
2489 Op = Op->DoPHITranslation(PHIBlock, PredBB);
2490 // When this operand changes, it could change whether there is a
2491 // leader for us or not.
2492 addAdditionalUsers(Op, I);
2493 }
2494 // Make sure it's marked as a temporary instruction.
2495 AllTempInstructions.insert(ValueOp);
2496 // and make sure anything that tries to add it's DFS number is
2497 // redirected to the instruction we are making a phi of ops
2498 // for.
2499 InstrDFS.insert({ValueOp, IDFSNum});
2500 const Expression *E = performSymbolicEvaluation(ValueOp, Visited);
2501 InstrDFS.erase(ValueOp);
2502 AllTempInstructions.erase(ValueOp);
2503 ValueOp->deleteValue();
2504 if (MemAccess)
2505 TempToMemory.erase(Iter);
2506 if (!E)
2507 return nullptr;
2508 FoundVal = findPhiOfOpsLeader(E, PredBB);
2509 if (!FoundVal) {
2510 ExpressionToPhiOfOps[E].insert(I);
2511 return nullptr;
2512 }
2513 if (auto *SI = dyn_cast<StoreInst>(FoundVal))
2514 FoundVal = SI->getValueOperand();
2515 } else {
2516 DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2517 << getBlockName(PredBB)
2518 << " because the block is unreachable\n");
2519 FoundVal = UndefValue::get(I->getType());
2520 }
2521
2522 Ops.push_back({FoundVal, PredBB});
2523 DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2524 << getBlockName(PredBB) << "\n");
2525 }
2526 auto *ValuePHI = RealToTemp.lookup(I);
2527 bool NewPHI = false;
2528 if (!ValuePHI) {
2529 ValuePHI = PHINode::Create(I->getType(), OpPHI->getNumOperands());
2530 addPhiOfOps(ValuePHI, PHIBlock, I);
2531 NewPHI = true;
2532 NumGVNPHIOfOpsCreated++;
2533 }
2534 if (NewPHI) {
2535 for (auto PHIOp : Ops)
2536 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2537 } else {
2538 unsigned int i = 0;
2539 for (auto PHIOp : Ops) {
2540 ValuePHI->setIncomingValue(i, PHIOp.first);
2541 ValuePHI->setIncomingBlock(i, PHIOp.second);
2542 ++i;
2543 }
2544 }
2545
2546 DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2547 << "\n");
2548 return performSymbolicEvaluation(ValuePHI, Visited);
2549 }
2550 return nullptr;
2551}
2552
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002553// The algorithm initially places the values of the routine in the TOP
2554// congruence class. The leader of TOP is the undetermined value `undef`.
2555// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002556void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002557 NextCongruenceNum = 0;
2558
2559 // Note that even though we use the live on entry def as a representative
2560 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2561 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2562 // should be checking whether the MemoryAccess is top if we want to know if it
2563 // is equivalent to everything. Otherwise, what this really signifies is that
2564 // the access "it reaches all the way back to the beginning of the function"
2565
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002566 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002567 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002568 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002569 // The live on entry def gets put into it's own class
2570 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2571 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002572
Daniel Berlinec9deb72017-04-18 17:06:11 +00002573 for (auto DTN : nodes(DT)) {
2574 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002575 // All MemoryAccesses are equivalent to live on entry to start. They must
2576 // be initialized to something so that initial changes are noticed. For
2577 // the maximal answer, we initialize them all to be the same as
2578 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002579 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002580 if (MemoryBlockDefs)
2581 for (const auto &Def : *MemoryBlockDefs) {
2582 MemoryAccessToClass[&Def] = TOPClass;
2583 auto *MD = dyn_cast<MemoryDef>(&Def);
2584 // Insert the memory phis into the member list.
2585 if (!MD) {
2586 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002587 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002588 MemoryPhiState.insert({MP, MPS_TOP});
2589 }
2590
2591 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002592 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002593 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002594 for (auto &I : *BB) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002595 // TODO: Move to helper
2596 if (isa<PHINode>(&I))
2597 for (auto *U : I.users())
2598 if (auto *UInst = dyn_cast<Instruction>(U))
2599 if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
2600 PHINodeUses.insert(UInst);
Daniel Berlin22a4a012017-02-11 15:20:15 +00002601 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002602 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002603 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2604 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002605 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002606 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002607 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002608 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002609
2610 // Initialize arguments to be in their own unique congruence classes
2611 for (auto &FA : F.args())
2612 createSingletonCongruenceClass(&FA);
2613}
2614
2615void NewGVN::cleanupTables() {
2616 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002617 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2618 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002619 // Make sure we delete the congruence class (probably worth switching to
2620 // a unique_ptr at some point.
2621 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002622 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002623 }
2624
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002625 // Destroy the value expressions
2626 SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2627 AllTempInstructions.end());
2628 AllTempInstructions.clear();
2629
2630 // We have to drop all references for everything first, so there are no uses
2631 // left as we delete them.
2632 for (auto *I : TempInst) {
2633 I->dropAllReferences();
2634 }
2635
2636 while (!TempInst.empty()) {
2637 auto *I = TempInst.back();
2638 TempInst.pop_back();
2639 I->deleteValue();
2640 }
2641
Davide Italiano7e274e02016-12-22 16:03:48 +00002642 ValueToClass.clear();
2643 ArgRecycler.clear(ExpressionAllocator);
2644 ExpressionAllocator.Reset();
2645 CongruenceClasses.clear();
2646 ExpressionToClass.clear();
2647 ValueToExpression.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002648 RealToTemp.clear();
2649 AdditionalUsers.clear();
2650 ExpressionToPhiOfOps.clear();
2651 TempToBlock.clear();
2652 TempToMemory.clear();
2653 PHIOfOpsPHIs.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002654 ReachableBlocks.clear();
2655 ReachableEdges.clear();
2656#ifndef NDEBUG
2657 ProcessedCount.clear();
2658#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002659 InstrDFS.clear();
2660 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002661 DFSToInstr.clear();
2662 BlockInstRange.clear();
2663 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002664 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002665 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002666 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002667}
2668
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002669// Assign local DFS number mapping to instructions, and leave space for Value
2670// PHI's.
Davide Italiano7e274e02016-12-22 16:03:48 +00002671std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2672 unsigned Start) {
2673 unsigned End = Start;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002674 if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002675 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002676 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002677 }
2678
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002679 // Then the real block goes next.
Davide Italiano7e274e02016-12-22 16:03:48 +00002680 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002681 // There's no need to call isInstructionTriviallyDead more than once on
2682 // an instruction. Therefore, once we know that an instruction is dead
2683 // we change its DFS number so that it doesn't get value numbered.
2684 if (isInstructionTriviallyDead(&I, TLI)) {
2685 InstrDFS[&I] = 0;
2686 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2687 markInstructionForDeletion(&I);
2688 continue;
2689 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002690 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002691 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002692 }
2693
2694 // All of the range functions taken half-open ranges (open on the end side).
2695 // So we do not subtract one from count, because at this point it is one
2696 // greater than the last instruction.
2697 return std::make_pair(Start, End);
2698}
2699
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002700void NewGVN::updateProcessedCount(const Value *V) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002701#ifndef NDEBUG
2702 if (ProcessedCount.count(V) == 0) {
2703 ProcessedCount.insert({V, 1});
2704 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002705 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002706 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002707 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002708 }
2709#endif
2710}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002711// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2712void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2713 // If all the arguments are the same, the MemoryPhi has the same value as the
Daniel Berlind130b6c2017-05-21 23:41:58 +00002714 // argument. Filter out unreachable blocks and self phis from our operands.
2715 // TODO: We could do cycle-checking on the memory phis to allow valueizing for
2716 // self-phi checking.
Daniel Berlin41b39162017-03-18 15:41:36 +00002717 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002718 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlind130b6c2017-05-21 23:41:58 +00002719 return cast<MemoryAccess>(U) != MP &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002720 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002721 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002722 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002723 // If all that is left is nothing, our memoryphi is undef. We keep it as
2724 // InitialClass. Note: The only case this should happen is if we have at
2725 // least one self-argument.
2726 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002727 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002728 markMemoryUsersTouched(MP);
2729 return;
2730 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002731
2732 // Transform the remaining operands into operand leaders.
2733 // FIXME: mapped_iterator should have a range version.
2734 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002735 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002736 };
2737 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2738 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2739
2740 // and now check if all the elements are equal.
2741 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002742 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002743 ++MappedBegin;
2744 bool AllEqual = std::all_of(
2745 MappedBegin, MappedEnd,
2746 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2747
2748 if (AllEqual)
2749 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2750 else
2751 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002752 // If it's equal to something, it's in that class. Otherwise, it has to be in
2753 // a class where it is the leader (other things may be equivalent to it, but
2754 // it needs to start off in its own class, which means it must have been the
2755 // leader, and it can't have stopped being the leader because it was never
2756 // removed).
2757 CongruenceClass *CC =
2758 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2759 auto OldState = MemoryPhiState.lookup(MP);
2760 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2761 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2762 MemoryPhiState[MP] = NewState;
2763 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002764 markMemoryUsersTouched(MP);
2765}
2766
2767// Value number a single instruction, symbolically evaluating, performing
2768// congruence finding, and updating mappings.
2769void NewGVN::valueNumberInstruction(Instruction *I) {
2770 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002771 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002772 const Expression *Symbolized = nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002773 SmallPtrSet<Value *, 2> Visited;
Daniel Berlin283a6082017-03-01 19:59:26 +00002774 if (DebugCounter::shouldExecute(VNCounter)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002775 Symbolized = performSymbolicEvaluation(I, Visited);
2776 // Make a phi of ops if necessary
2777 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
2778 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
2779 // FIXME: Backedge argument
2780 auto *PHIE = makePossiblePhiOfOps(I, false, Visited);
2781 if (PHIE)
2782 Symbolized = PHIE;
2783 }
2784
Daniel Berlin283a6082017-03-01 19:59:26 +00002785 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002786 // Mark the instruction as unused so we don't value number it again.
2787 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002788 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002789 // If we couldn't come up with a symbolic expression, use the unknown
2790 // expression
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002791 if (Symbolized == nullptr)
Daniel Berlin02c6b172017-01-02 18:00:53 +00002792 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002793 performCongruenceFinding(I, Symbolized);
2794 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002795 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002796 // don't currently understand. We don't place non-value producing
2797 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002798 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002799 auto *Symbolized = createUnknownExpression(I);
2800 performCongruenceFinding(I, Symbolized);
2801 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002802 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2803 }
2804}
Davide Italiano7e274e02016-12-22 16:03:48 +00002805
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002806// Check if there is a path, using single or equal argument phi nodes, from
2807// First to Second.
Davide Italianoeab0de22017-05-18 23:22:44 +00002808bool NewGVN::singleReachablePHIPath(
2809 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
2810 const MemoryAccess *Second) const {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002811 if (First == Second)
2812 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002813 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002814 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002815
Davide Italianoeab0de22017-05-18 23:22:44 +00002816 // This is not perfect, but as we're just verifying here, we can live with
2817 // the loss of precision. The real solution would be that of doing strongly
2818 // connected component finding in this routine, and it's probably not worth
2819 // the complexity for the time being. So, we just keep a set of visited
2820 // MemoryAccess and return true when we hit a cycle.
2821 if (Visited.count(First))
2822 return true;
2823 Visited.insert(First);
2824
Daniel Berlin871ecd92017-04-01 09:44:24 +00002825 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002826 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002827 if (ChainDef == Second)
2828 return true;
2829 if (MSSA->isLiveOnEntryDef(ChainDef))
2830 return false;
2831 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002832 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002833 auto *MP = cast<MemoryPhi>(EndDef);
2834 auto ReachableOperandPred = [&](const Use &U) {
2835 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2836 };
2837 auto FilteredPhiArgs =
2838 make_filter_range(MP->operands(), ReachableOperandPred);
2839 SmallVector<const Value *, 32> OperandList;
2840 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2841 std::back_inserter(OperandList));
2842 bool Okay = OperandList.size() == 1;
2843 if (!Okay)
2844 Okay =
2845 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2846 if (Okay)
Davide Italianoeab0de22017-05-18 23:22:44 +00002847 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2848 Second);
Daniel Berlin871ecd92017-04-01 09:44:24 +00002849 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002850}
2851
Daniel Berlin589cecc2017-01-02 18:00:46 +00002852// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002853// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002854// subject to very rare false negatives. It is only useful for
2855// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002856void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002857#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002858 // Verify that the memory table equivalence and memory member set match
2859 for (const auto *CC : CongruenceClasses) {
2860 if (CC == TOPClass || CC->isDead())
2861 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002862 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00002863 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002864 "Any class with a store as a leader should have a "
2865 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00002866 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002867 "Any congruence class with a store should have a "
2868 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00002869 }
2870
Daniel Berlina8236562017-04-07 18:38:09 +00002871 if (CC->getMemoryLeader())
2872 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00002873 "Representative MemoryAccess does not appear to be reverse "
2874 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00002875 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002876 assert(MemoryAccessToClass.lookup(M) == CC &&
2877 "Memory member does not appear to be reverse mapped properly");
2878 }
2879
2880 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002881 // congruence class.
2882
2883 // Filter out the unreachable and trivially dead entries, because they may
2884 // never have been updated if the instructions were not processed.
2885 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002886 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002887 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00002888 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2889 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00002890 return false;
2891 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2892 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Davide Italiano6e7a2122017-05-15 18:50:53 +00002893
2894 // We could have phi nodes which operands are all trivially dead,
2895 // so we don't process them.
2896 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
2897 for (auto &U : MemPHI->incoming_values()) {
2898 if (Instruction *I = dyn_cast<Instruction>(U.get())) {
2899 if (!isInstructionTriviallyDead(I))
2900 return true;
2901 }
2902 }
2903 return false;
2904 }
2905
Daniel Berlin589cecc2017-01-02 18:00:46 +00002906 return true;
2907 };
2908
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002909 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002910 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002911 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002912 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italianoeab0de22017-05-18 23:22:44 +00002913 if (FirstMUD && SecondMUD) {
2914 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
2915 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002916 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2917 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2918 "The instructions for these memory operations should have "
2919 "been in the same congruence class or reachable through"
2920 "a single argument phi");
Davide Italianoeab0de22017-05-18 23:22:44 +00002921 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002922 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002923 // We can only sanely verify that MemoryDefs in the operand list all have
2924 // the same class.
2925 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002926 return ReachableEdges.count(
2927 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002928 isa<MemoryDef>(U);
2929
2930 };
2931 // All arguments should in the same class, ignoring unreachable arguments
2932 auto FilteredPhiArgs =
2933 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2934 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2935 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2936 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2937 const MemoryDef *MD = cast<MemoryDef>(U);
2938 return ValueToClass.lookup(MD->getMemoryInst());
2939 });
2940 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2941 PhiOpClasses.begin()) &&
2942 "All MemoryPhi arguments should be in the same class");
2943 }
2944 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002945#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002946}
2947
Daniel Berlin06329a92017-03-18 15:41:40 +00002948// Verify that the sparse propagation we did actually found the maximal fixpoint
2949// We do this by storing the value to class mapping, touching all instructions,
2950// and redoing the iteration to see if anything changed.
2951void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002952#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002953 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002954 if (DebugCounter::isCounterSet(VNCounter))
2955 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2956
2957 // Note that we have to store the actual classes, as we may change existing
2958 // classes during iteration. This is because our memory iteration propagation
2959 // is not perfect, and so may waste a little work. But it should generate
2960 // exactly the same congruence classes we have now, with different IDs.
2961 std::map<const Value *, CongruenceClass> BeforeIteration;
2962
2963 for (auto &KV : ValueToClass) {
2964 if (auto *I = dyn_cast<Instruction>(KV.first))
2965 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002966 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002967 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002968 BeforeIteration.insert({KV.first, *KV.second});
2969 }
2970
2971 TouchedInstructions.set();
2972 TouchedInstructions.reset(0);
2973 iterateTouchedInstructions();
2974 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2975 EqualClasses;
2976 for (const auto &KV : ValueToClass) {
2977 if (auto *I = dyn_cast<Instruction>(KV.first))
2978 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002979 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00002980 continue;
2981 // We could sink these uses, but i think this adds a bit of clarity here as
2982 // to what we are comparing.
2983 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2984 auto *AfterCC = KV.second;
2985 // Note that the classes can't change at this point, so we memoize the set
2986 // that are equal.
2987 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00002988 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00002989 "Value number changed after main loop completed!");
2990 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002991 }
2992 }
2993#endif
2994}
2995
Daniel Berlin45403572017-05-16 19:58:47 +00002996// Verify that for each store expression in the expression to class mapping,
2997// only the latest appears, and multiple ones do not appear.
2998// Because loads do not use the stored value when doing equality with stores,
2999// if we don't erase the old store expressions from the table, a load can find
3000// a no-longer valid StoreExpression.
3001void NewGVN::verifyStoreExpressions() const {
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003002#ifndef NDEBUG
Daniel Berlin45403572017-05-16 19:58:47 +00003003 DenseSet<std::pair<const Value *, const Value *>> StoreExpressionSet;
3004 for (const auto &KV : ExpressionToClass) {
3005 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3006 // Make sure a version that will conflict with loads is not already there
3007 auto Res =
3008 StoreExpressionSet.insert({SE->getOperand(0), SE->getMemoryLeader()});
3009 assert(Res.second &&
3010 "Stored expression conflict exists in expression table");
3011 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3012 assert(ValueExpr && ValueExpr->equals(*SE) &&
3013 "StoreExpression in ExpressionToClass is not latest "
3014 "StoreExpression for value");
3015 }
3016 }
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003017#endif
Daniel Berlin45403572017-05-16 19:58:47 +00003018}
3019
Daniel Berlin06329a92017-03-18 15:41:40 +00003020// This is the main value numbering loop, it iterates over the initial touched
3021// instruction set, propagating value numbers, marking things touched, etc,
3022// until the set of touched instructions is completely empty.
3023void NewGVN::iterateTouchedInstructions() {
3024 unsigned int Iterations = 0;
3025 // Figure out where touchedinstructions starts
3026 int FirstInstr = TouchedInstructions.find_first();
3027 // Nothing set, nothing to iterate, just return.
3028 if (FirstInstr == -1)
3029 return;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003030 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00003031 while (TouchedInstructions.any()) {
3032 ++Iterations;
3033 // Walk through all the instructions in all the blocks in RPO.
3034 // TODO: As we hit a new block, we should push and pop equalities into a
3035 // table lookupOperandLeader can use, to catch things PredicateInfo
3036 // might miss, like edge-only equivalences.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003037 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
Daniel Berlin06329a92017-03-18 15:41:40 +00003038
3039 // This instruction was found to be dead. We don't bother looking
3040 // at it again.
3041 if (InstrNum == 0) {
3042 TouchedInstructions.reset(InstrNum);
3043 continue;
3044 }
3045
Daniel Berlin21279bd2017-04-06 18:52:58 +00003046 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003047 const BasicBlock *CurrBlock = getBlockForValue(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003048
3049 // If we hit a new block, do reachability processing.
3050 if (CurrBlock != LastBlock) {
3051 LastBlock = CurrBlock;
3052 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3053 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3054
3055 // If it's not reachable, erase any touched instructions and move on.
3056 if (!BlockReachable) {
3057 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3058 DEBUG(dbgs() << "Skipping instructions in block "
3059 << getBlockName(CurrBlock)
3060 << " because it is unreachable\n");
3061 continue;
3062 }
3063 updateProcessedCount(CurrBlock);
3064 }
3065
3066 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
3067 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
3068 valueNumberMemoryPhi(MP);
3069 } else if (auto *I = dyn_cast<Instruction>(V)) {
3070 valueNumberInstruction(I);
3071 } else {
3072 llvm_unreachable("Should have been a MemoryPhi or Instruction");
3073 }
3074 updateProcessedCount(V);
3075 // Reset after processing (because we may mark ourselves as touched when
3076 // we propagate equalities).
3077 TouchedInstructions.reset(InstrNum);
3078 }
3079 }
3080 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3081}
3082
Daniel Berlin85f91b02016-12-26 20:06:58 +00003083// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00003084bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00003085 if (DebugCounter::isCounterSet(VNCounter))
3086 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00003087 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00003088 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00003089 MSSAWalker = MSSA->getWalker();
Daniel Berline021d2d2017-05-19 20:22:20 +00003090 SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00003091
3092 // Count number of instructions for sizing of hash tables, and come
3093 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003094 unsigned ICount = 1;
3095 // Add an empty instruction to account for the fact that we start at 1
3096 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00003097 // Note: We want ideal RPO traversal of the blocks, which is not quite the
3098 // same as dominator tree order, particularly with regard whether backedges
3099 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00003100 // If we visit in the wrong order, we will end up performing N times as many
3101 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00003102 // The dominator tree does guarantee that, for a given dom tree node, it's
3103 // parent must occur before it in the RPO ordering. Thus, we only need to sort
3104 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00003105 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00003106 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00003107 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003108 auto *Node = DT->getNode(B);
3109 assert(Node && "RPO and Dominator tree should have same reachability");
3110 RPOOrdering[Node] = ++Counter;
3111 }
3112 // Sort dominator tree children arrays into RPO.
3113 for (auto &B : RPOT) {
3114 auto *Node = DT->getNode(B);
3115 if (Node->getChildren().size() > 1)
3116 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00003117 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003118 return RPOOrdering[A] < RPOOrdering[B];
3119 });
3120 }
3121
3122 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00003123 for (auto DTN : depth_first(DT->getRootNode())) {
3124 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00003125 const auto &BlockRange = assignDFSNumbers(B, ICount);
3126 BlockInstRange.insert({B, BlockRange});
3127 ICount += BlockRange.second - BlockRange.first;
3128 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003129 initializeCongruenceClasses(F);
Davide Italiano7e274e02016-12-22 16:03:48 +00003130
Daniel Berline0bd37e2016-12-29 22:15:12 +00003131 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003132 // Ensure we don't end up resizing the expressionToClass map, as
3133 // that can be quite expensive. At most, we have one expression per
3134 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003135 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003136
3137 // Initialize the touched instructions to include the entry block.
3138 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
3139 TouchedInstructions.set(InstRange.first, InstRange.second);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003140 DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3141 << " marked reachable\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003142 ReachableBlocks.insert(&F.getEntryBlock());
3143
Daniel Berlin06329a92017-03-18 15:41:40 +00003144 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00003145 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00003146 verifyIterationSettled(F);
Daniel Berlin45403572017-05-16 19:58:47 +00003147 verifyStoreExpressions();
Daniel Berlinf7d95802017-02-18 23:06:50 +00003148
Davide Italiano7e274e02016-12-22 16:03:48 +00003149 Changed |= eliminateInstructions(F);
3150
3151 // Delete all instructions marked for deletion.
3152 for (Instruction *ToErase : InstructionsToErase) {
3153 if (!ToErase->use_empty())
3154 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3155
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003156 if (ToErase->getParent())
3157 ToErase->eraseFromParent();
Davide Italiano7e274e02016-12-22 16:03:48 +00003158 }
3159
3160 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003161 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3162 return !ReachableBlocks.count(&BB);
3163 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003164
3165 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
3166 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00003167 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003168 deleteInstructionsInBlock(&BB);
3169 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003170 }
3171
3172 cleanupTables();
3173 return Changed;
3174}
3175
Davide Italiano7e274e02016-12-22 16:03:48 +00003176struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003177 int DFSIn = 0;
3178 int DFSOut = 0;
3179 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003180 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003181 // The bool in the Def tells us whether the Def is the stored value of a
3182 // store.
3183 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003184 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00003185 bool operator<(const ValueDFS &Other) const {
3186 // It's not enough that any given field be less than - we have sets
3187 // of fields that need to be evaluated together to give a proper ordering.
3188 // For example, if you have;
3189 // DFS (1, 3)
3190 // Val 0
3191 // DFS (1, 2)
3192 // Val 50
3193 // We want the second to be less than the first, but if we just go field
3194 // by field, we will get to Val 0 < Val 50 and say the first is less than
3195 // the second. We only want it to be less than if the DFS orders are equal.
3196 //
3197 // Each LLVM instruction only produces one value, and thus the lowest-level
3198 // differentiator that really matters for the stack (and what we use as as a
3199 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003200 // Everything else in the structure is instruction level, and only affects
3201 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00003202 //
3203 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3204 // the order of replacement of uses does not matter.
3205 // IE given,
3206 // a = 5
3207 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00003208 // When you hit b, you will have two valuedfs with the same dfsin, out, and
3209 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00003210 // The .val will be the same as well.
3211 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003212 // You will replace both, and it does not matter what order you replace them
3213 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3214 // operand 2).
3215 // Similarly for the case of same dfsin, dfsout, localnum, but different
3216 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00003217 // a = 5
3218 // b = 6
3219 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00003220 // in c, we will a valuedfs for a, and one for b,with everything the same
3221 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00003222 // It does not matter what order we replace these operands in.
3223 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003224 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3225 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00003226 Other.U);
3227 }
3228};
3229
Daniel Berlinc4796862017-01-27 02:37:11 +00003230// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003231// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00003232// reachable uses for each value is stored in UseCount, and instructions that
3233// seem
3234// dead (have no non-dead uses) are stored in ProbablyDead.
3235void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00003236 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00003237 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00003238 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00003239 for (auto D : Dense) {
3240 // First add the value.
3241 BasicBlock *BB = getBlockForValue(D);
3242 // Constants are handled prior to ever calling this function, so
3243 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00003244 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003245 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003246 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003247 VDDef.DFSIn = DomNode->getDFSNumIn();
3248 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003249 // If it's a store, use the leader of the value operand, if it's always
3250 // available, or the value operand. TODO: We could do dominance checks to
3251 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00003252 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00003253 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003254 if (alwaysAvailable(Leader)) {
3255 VDDef.Def.setPointer(Leader);
3256 } else {
3257 VDDef.Def.setPointer(SI->getValueOperand());
3258 VDDef.Def.setInt(true);
3259 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003260 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003261 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00003262 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003263 assert(isa<Instruction>(D) &&
3264 "The dense set member should always be an instruction");
Daniel Berline3e69e12017-03-10 00:32:33 +00003265 Instruction *Def = cast<Instruction>(D);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003266 VDDef.LocalNum = InstrToDFSNum(D);
3267 DFSOrderedSet.push_back(VDDef);
3268 // If there is a phi node equivalent, add it
3269 if (auto *PN = RealToTemp.lookup(Def)) {
3270 auto *PHIE =
3271 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3272 if (PHIE) {
3273 VDDef.Def.setInt(false);
3274 VDDef.Def.setPointer(PN);
3275 VDDef.LocalNum = 0;
3276 DFSOrderedSet.push_back(VDDef);
3277 }
3278 }
3279
Daniel Berline3e69e12017-03-10 00:32:33 +00003280 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003281 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00003282 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003283 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003284 // Don't try to replace into dead uses
3285 if (InstructionsToErase.count(I))
3286 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003287 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00003288 // Put the phi node uses in the incoming block.
3289 BasicBlock *IBlock;
3290 if (auto *P = dyn_cast<PHINode>(I)) {
3291 IBlock = P->getIncomingBlock(U);
3292 // Make phi node users appear last in the incoming block
3293 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003294 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00003295 } else {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003296 IBlock = getBlockForValue(I);
Daniel Berlin21279bd2017-04-06 18:52:58 +00003297 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003298 }
Davide Italianoccbbc832017-01-26 00:42:42 +00003299
3300 // Skip uses in unreachable blocks, as we're going
3301 // to delete them.
3302 if (ReachableBlocks.count(IBlock) == 0)
3303 continue;
3304
Daniel Berlinb66164c2017-01-14 00:24:23 +00003305 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003306 VDUse.DFSIn = DomNode->getDFSNumIn();
3307 VDUse.DFSOut = DomNode->getDFSNumOut();
3308 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00003309 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003310 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00003311 }
3312 }
Daniel Berline3e69e12017-03-10 00:32:33 +00003313
3314 // If there are no uses, it's probably dead (but it may have side-effects,
3315 // so not definitely dead. Otherwise, store the number of uses so we can
3316 // track if it becomes dead later).
3317 if (UseCount == 0)
3318 ProbablyDead.insert(Def);
3319 else
3320 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003321 }
3322}
3323
Daniel Berlinc4796862017-01-27 02:37:11 +00003324// This function converts the set of members for a congruence class from values,
3325// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00003326void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00003327 const CongruenceClass &Dense,
3328 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00003329 for (auto D : Dense) {
3330 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
3331 continue;
3332
3333 BasicBlock *BB = getBlockForValue(D);
3334 ValueDFS VD;
3335 DomTreeNode *DomNode = DT->getNode(BB);
3336 VD.DFSIn = DomNode->getDFSNumIn();
3337 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003338 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00003339
3340 // If it's an instruction, use the real local dfs number.
3341 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00003342 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00003343 else
3344 llvm_unreachable("Should have been an instruction");
3345
3346 LoadsAndStores.emplace_back(VD);
3347 }
3348}
3349
Davide Italiano7e274e02016-12-22 16:03:48 +00003350static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00003351 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00003352 if (!ReplInst)
3353 return;
3354
Davide Italiano7e274e02016-12-22 16:03:48 +00003355 // Patch the replacement so that it is not more restrictive than the value
3356 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00003357 // Note that if 'I' is a load being replaced by some operation,
3358 // for example, by an arithmetic operation, then andIRFlags()
3359 // would just erase all math flags from the original arithmetic
3360 // operation, which is clearly not wanted and not needed.
3361 if (!isa<LoadInst>(I))
3362 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003363
Daniel Berlin86eab152017-02-12 22:25:20 +00003364 // FIXME: If both the original and replacement value are part of the
3365 // same control-flow region (meaning that the execution of one
3366 // guarantees the execution of the other), then we can combine the
3367 // noalias scopes here and do better than the general conservative
3368 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00003369
Daniel Berlin86eab152017-02-12 22:25:20 +00003370 // In general, GVN unifies expressions over different control-flow
3371 // regions, and so we need a conservative combination of the noalias
3372 // scopes.
3373 static const unsigned KnownIDs[] = {
3374 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3375 LLVMContext::MD_noalias, LLVMContext::MD_range,
3376 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
3377 LLVMContext::MD_invariant_group};
3378 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00003379}
3380
3381static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3382 patchReplacementInstruction(I, Repl);
3383 I->replaceAllUsesWith(Repl);
3384}
3385
3386void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3387 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
3388 ++NumGVNBlocksDeleted;
3389
Daniel Berline19f0e02017-01-30 17:06:55 +00003390 // Delete the instructions backwards, as it has a reduced likelihood of having
3391 // to update as many def-use and use-def chains. Start after the terminator.
3392 auto StartPoint = BB->rbegin();
3393 ++StartPoint;
3394 // Note that we explicitly recalculate BB->rend() on each iteration,
3395 // as it may change when we remove the first instruction.
3396 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3397 Instruction &Inst = *I++;
3398 if (!Inst.use_empty())
3399 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3400 if (isa<LandingPadInst>(Inst))
3401 continue;
3402
3403 Inst.eraseFromParent();
3404 ++NumGVNInstrDeleted;
3405 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003406 // Now insert something that simplifycfg will turn into an unreachable.
3407 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3408 new StoreInst(UndefValue::get(Int8Ty),
3409 Constant::getNullValue(Int8Ty->getPointerTo()),
3410 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003411}
3412
3413void NewGVN::markInstructionForDeletion(Instruction *I) {
3414 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3415 InstructionsToErase.insert(I);
3416}
3417
3418void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3419
3420 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3421 patchAndReplaceAllUsesWith(I, V);
3422 // We save the actual erasing to avoid invalidating memory
3423 // dependencies until we are done with everything.
3424 markInstructionForDeletion(I);
3425}
3426
3427namespace {
3428
3429// This is a stack that contains both the value and dfs info of where
3430// that value is valid.
3431class ValueDFSStack {
3432public:
3433 Value *back() const { return ValueStack.back(); }
3434 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3435
3436 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003437 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003438 DFSStack.emplace_back(DFSIn, DFSOut);
3439 }
3440 bool empty() const { return DFSStack.empty(); }
3441 bool isInScope(int DFSIn, int DFSOut) const {
3442 if (empty())
3443 return false;
3444 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3445 }
3446
3447 void popUntilDFSScope(int DFSIn, int DFSOut) {
3448
3449 // These two should always be in sync at this point.
3450 assert(ValueStack.size() == DFSStack.size() &&
3451 "Mismatch between ValueStack and DFSStack");
3452 while (
3453 !DFSStack.empty() &&
3454 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3455 DFSStack.pop_back();
3456 ValueStack.pop_back();
3457 }
3458 }
3459
3460private:
3461 SmallVector<Value *, 8> ValueStack;
3462 SmallVector<std::pair<int, int>, 8> DFSStack;
3463};
3464}
Daniel Berlin04443432017-01-07 03:23:47 +00003465
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003466// Given a value and a basic block we are trying to see if it is available in,
3467// see if the value has a leader available in that block.
3468Value *NewGVN::findPhiOfOpsLeader(const Expression *E,
3469 const BasicBlock *BB) const {
3470 // It would already be constant if we could make it constant
3471 if (auto *CE = dyn_cast<ConstantExpression>(E))
3472 return CE->getConstantValue();
3473 if (auto *VE = dyn_cast<VariableExpression>(E))
3474 return VE->getVariableValue();
3475
3476 auto *CC = ExpressionToClass.lookup(E);
3477 if (!CC)
3478 return nullptr;
3479 if (alwaysAvailable(CC->getLeader()))
3480 return CC->getLeader();
3481
3482 for (auto Member : *CC) {
3483 auto *MemberInst = dyn_cast<Instruction>(Member);
3484 // Anything that isn't an instruction is always available.
3485 if (!MemberInst)
3486 return Member;
3487 // If we are looking for something in the same block as the member, it must
3488 // be a leader because this function is looking for operands for a phi node.
3489 if (MemberInst->getParent() == BB ||
3490 DT->dominates(MemberInst->getParent(), BB)) {
3491 return Member;
3492 }
3493 }
3494 return nullptr;
3495}
3496
Davide Italiano7e274e02016-12-22 16:03:48 +00003497bool NewGVN::eliminateInstructions(Function &F) {
3498 // This is a non-standard eliminator. The normal way to eliminate is
3499 // to walk the dominator tree in order, keeping track of available
3500 // values, and eliminating them. However, this is mildly
3501 // pointless. It requires doing lookups on every instruction,
3502 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003503 // instructions part of most singleton congruence classes, we know we
3504 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003505
3506 // Instead, this eliminator looks at the congruence classes directly, sorts
3507 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003508 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003509 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003510 // last member. This is worst case O(E log E) where E = number of
3511 // instructions in a single congruence class. In theory, this is all
3512 // instructions. In practice, it is much faster, as most instructions are
3513 // either in singleton congruence classes or can't possibly be eliminated
3514 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003515 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003516 // for elimination purposes.
3517 // TODO: If we wanted to be faster, We could remove any members with no
3518 // overlapping ranges while sorting, as we will never eliminate anything
3519 // with those members, as they don't dominate anything else in our set.
3520
Davide Italiano7e274e02016-12-22 16:03:48 +00003521 bool AnythingReplaced = false;
3522
3523 // Since we are going to walk the domtree anyway, and we can't guarantee the
3524 // DFS numbers are updated, we compute some ourselves.
3525 DT->updateDFSNumbers();
3526
Daniel Berlin0207cca2017-05-21 23:41:56 +00003527 // Go through all of our phi nodes, and kill the arguments associated with
3528 // unreachable edges.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003529 auto ReplaceUnreachablePHIArgs = [&](PHINode &PHI, BasicBlock *BB) {
3530 for (auto &Operand : PHI.incoming_values())
3531 if (!ReachableEdges.count({PHI.getIncomingBlock(Operand), BB})) {
3532 DEBUG(dbgs() << "Replacing incoming value of " << PHI << " for block "
3533 << getBlockName(PHI.getIncomingBlock(Operand))
3534 << " with undef due to it being unreachable\n");
3535 Operand.set(UndefValue::get(PHI.getType()));
3536 }
3537 };
3538 SmallPtrSet<BasicBlock *, 8> BlocksWithPhis;
3539 for (auto &B : F)
3540 if ((!B.empty() && isa<PHINode>(*B.begin())) ||
3541 (PHIOfOpsPHIs.find(&B) != PHIOfOpsPHIs.end()))
3542 BlocksWithPhis.insert(&B);
3543 DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
3544 for (auto KV : ReachableEdges)
3545 ReachablePredCount[KV.getEnd()]++;
3546 for (auto *BB : BlocksWithPhis)
3547 // TODO: It would be faster to use getNumIncomingBlocks() on a phi node in
3548 // the block and subtract the pred count, but it's more complicated.
3549 if (ReachablePredCount.lookup(BB) !=
3550 std::distance(pred_begin(BB), pred_end(BB))) {
3551 for (auto II = BB->begin(); isa<PHINode>(II); ++II) {
3552 auto &PHI = cast<PHINode>(*II);
3553 ReplaceUnreachablePHIArgs(PHI, BB);
3554 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00003555 for_each_found(PHIOfOpsPHIs, BB, [&](PHINode *PHI) {
3556 ReplaceUnreachablePHIArgs(*PHI, BB);
3557 });
Davide Italiano7e274e02016-12-22 16:03:48 +00003558 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003559
Daniel Berline3e69e12017-03-10 00:32:33 +00003560 // Map to store the use counts
3561 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003562 for (auto *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00003563 // Track the equivalent store info so we can decide whether to try
3564 // dead store elimination.
3565 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003566 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003567 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003568 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003569 // Everything still in the TOP class is unreachable or dead.
3570 if (CC == TOPClass) {
Daniel Berline021d2d2017-05-19 20:22:20 +00003571 for (auto M : *CC) {
3572 auto *VTE = ValueToExpression.lookup(M);
3573 if (VTE && isa<DeadExpression>(VTE))
3574 markInstructionForDeletion(cast<Instruction>(M));
Daniel Berlinb79f5362017-02-11 12:48:50 +00003575 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3576 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003577 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003578 "point");
Daniel Berline021d2d2017-05-19 20:22:20 +00003579 }
Daniel Berlinb79f5362017-02-11 12:48:50 +00003580 continue;
3581 }
3582
Daniel Berlina8236562017-04-07 18:38:09 +00003583 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003584 // If this is a leader that is always available, and it's a
3585 // constant or has no equivalences, just replace everything with
3586 // it. We then update the congruence class with whatever members
3587 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003588 Value *Leader =
3589 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003590 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003591 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003592 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003593 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003594 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003595 if (Member == Leader || !isa<Instruction>(Member) ||
3596 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003597 MembersLeft.insert(Member);
3598 continue;
3599 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003600 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3601 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003602 auto *I = cast<Instruction>(Member);
3603 assert(Leader != I && "About to accidentally remove our leader");
3604 replaceInstruction(I, Leader);
3605 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003606 }
Daniel Berlina8236562017-04-07 18:38:09 +00003607 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003608 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00003609 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
3610 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003611 // If this is a singleton, we can skip it.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003612 if (CC->size() != 1 || RealToTemp.lookup(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003613 // This is a stack because equality replacement/etc may place
3614 // constants in the middle of the member list, and we want to use
3615 // those constant values in preference to the current leader, over
3616 // the scope of those constants.
3617 ValueDFSStack EliminationStack;
3618
3619 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003620 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003621 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003622
3623 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003624 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003625 for (auto &VD : DFSOrderedSet) {
3626 int MemberDFSIn = VD.DFSIn;
3627 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003628 Value *Def = VD.Def.getPointer();
3629 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003630 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003631 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003632 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003633 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003634 auto *DefInst = dyn_cast_or_null<Instruction>(Def);
3635 if (DefInst && AllTempInstructions.count(DefInst)) {
3636 auto *PN = cast<PHINode>(DefInst);
3637
3638 // If this is a value phi and that's the expression we used, insert
3639 // it into the program
3640 // remove from temp instruction list.
3641 AllTempInstructions.erase(PN);
3642 auto *DefBlock = getBlockForValue(Def);
3643 DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3644 << " into block "
3645 << getBlockName(getBlockForValue(Def)) << "\n");
3646 PN->insertBefore(&DefBlock->front());
3647 Def = PN;
3648 NumGVNPHIOfOpsEliminations++;
3649 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003650
3651 if (EliminationStack.empty()) {
3652 DEBUG(dbgs() << "Elimination Stack is empty\n");
3653 } else {
3654 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3655 << EliminationStack.dfs_back().first << ","
3656 << EliminationStack.dfs_back().second << ")\n");
3657 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003658
3659 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3660 << MemberDFSOut << ")\n");
3661 // First, we see if we are out of scope or empty. If so,
3662 // and there equivalences, we try to replace the top of
3663 // stack with equivalences (if it's on the stack, it must
3664 // not have been eliminated yet).
3665 // Then we synchronize to our current scope, by
3666 // popping until we are back within a DFS scope that
3667 // dominates the current member.
3668 // Then, what happens depends on a few factors
3669 // If the stack is now empty, we need to push
3670 // If we have a constant or a local equivalence we want to
3671 // start using, we also push.
3672 // Otherwise, we walk along, processing members who are
3673 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003674 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003675 bool OutOfScope =
3676 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3677
3678 if (OutOfScope || ShouldPush) {
3679 // Sync to our current scope.
3680 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003681 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003682 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003683 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003684 }
3685 }
3686
Daniel Berline3e69e12017-03-10 00:32:33 +00003687 // Skip the Def's, we only want to eliminate on their uses. But mark
3688 // dominated defs as dead.
3689 if (Def) {
3690 // For anything in this case, what and how we value number
3691 // guarantees that any side-effets that would have occurred (ie
3692 // throwing, etc) can be proven to either still occur (because it's
3693 // dominated by something that has the same side-effects), or never
3694 // occur. Otherwise, we would not have been able to prove it value
3695 // equivalent to something else. For these things, we can just mark
3696 // it all dead. Note that this is different from the "ProbablyDead"
3697 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003698 // easy to prove dead if they are also side-effect free. Note that
3699 // because stores are put in terms of the stored value, we skip
3700 // stored values here. If the stored value is really dead, it will
3701 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003702 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003703 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003704 markInstructionForDeletion(cast<Instruction>(Def));
3705 continue;
3706 }
3707 // At this point, we know it is a Use we are trying to possibly
3708 // replace.
3709
3710 assert(isa<Instruction>(U->get()) &&
3711 "Current def should have been an instruction");
3712 assert(isa<Instruction>(U->getUser()) &&
3713 "Current user should have been an instruction");
3714
3715 // If the thing we are replacing into is already marked to be dead,
3716 // this use is dead. Note that this is true regardless of whether
3717 // we have anything dominating the use or not. We do this here
3718 // because we are already walking all the uses anyway.
3719 Instruction *InstUse = cast<Instruction>(U->getUser());
3720 if (InstructionsToErase.count(InstUse)) {
3721 auto &UseCount = UseCounts[U->get()];
3722 if (--UseCount == 0) {
3723 ProbablyDead.insert(cast<Instruction>(U->get()));
3724 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003725 }
3726
Davide Italiano7e274e02016-12-22 16:03:48 +00003727 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003728 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003729 if (EliminationStack.empty())
3730 continue;
3731
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003732 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003733
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003734 auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
3735 if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3736 DominatingLeader = II->getOperand(0);
3737
Daniel Berlind92e7f92017-01-07 00:01:42 +00003738 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003739 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003740 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003741 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003742 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003743
3744 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003745 // metadata. Skip this if we are replacing predicateinfo with its
3746 // original operand, as we already know we can just drop it.
3747 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003748 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3749 if (!PI || DominatingLeader != PI->OriginalOp)
3750 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003751 U->set(DominatingLeader);
3752 // This is now a use of the dominating leader, which means if the
3753 // dominating leader was dead, it's now live!
3754 auto &LeaderUseCount = UseCounts[DominatingLeader];
3755 // It's about to be alive again.
3756 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3757 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003758 if (LeaderUseCount == 0 && II)
3759 ProbablyDead.insert(II);
Daniel Berline3e69e12017-03-10 00:32:33 +00003760 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003761 AnythingReplaced = true;
3762 }
3763 }
3764 }
3765
Daniel Berline3e69e12017-03-10 00:32:33 +00003766 // At this point, anything still in the ProbablyDead set is actually dead if
3767 // would be trivially dead.
3768 for (auto *I : ProbablyDead)
3769 if (wouldInstructionBeTriviallyDead(I))
3770 markInstructionForDeletion(I);
3771
Davide Italiano7e274e02016-12-22 16:03:48 +00003772 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003773 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003774 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003775 if (!isa<Instruction>(Member) ||
3776 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003777 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003778 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003779
3780 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003781 if (CC->getStoreCount() > 0) {
3782 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003783 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3784 ValueDFSStack EliminationStack;
3785 for (auto &VD : PossibleDeadStores) {
3786 int MemberDFSIn = VD.DFSIn;
3787 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003788 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003789 if (EliminationStack.empty() ||
3790 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3791 // Sync to our current scope.
3792 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3793 if (EliminationStack.empty()) {
3794 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3795 continue;
3796 }
3797 }
3798 // We already did load elimination, so nothing to do here.
3799 if (isa<LoadInst>(Member))
3800 continue;
3801 assert(!EliminationStack.empty());
3802 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003803 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003804 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3805 // Member is dominater by Leader, and thus dead
3806 DEBUG(dbgs() << "Marking dead store " << *Member
3807 << " that is dominated by " << *Leader << "\n");
3808 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003809 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003810 ++NumGVNDeadStores;
3811 }
3812 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003813 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003814 return AnythingReplaced;
3815}
Daniel Berlin1c087672017-02-11 15:07:01 +00003816
3817// This function provides global ranking of operations so that we can place them
3818// in a canonical order. Note that rank alone is not necessarily enough for a
3819// complete ordering, as constants all have the same rank. However, generally,
3820// we will simplify an operation with all constants so that it doesn't matter
3821// what order they appear in.
3822unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003823 // Prefer constants to undef to anything else
3824 // Undef is a constant, have to check it first.
3825 // Prefer smaller constants to constantexprs
3826 if (isa<ConstantExpr>(V))
3827 return 2;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003828 if (isa<UndefValue>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003829 return 1;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003830 if (isa<Constant>(V))
3831 return 0;
Daniel Berlin1c087672017-02-11 15:07:01 +00003832 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003833 return 3 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003834
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003835 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003836 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003837 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00003838 if (Result > 0)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003839 return 4 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003840 // Unreachable or something else, just return a really large number.
3841 return ~0;
3842}
3843
3844// This is a function that says whether two commutative operations should
3845// have their order swapped when canonicalizing.
3846bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3847 // Because we only care about a total ordering, and don't rewrite expressions
3848 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003849 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003850 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003851}
Daniel Berlin64e68992017-03-12 04:46:45 +00003852
3853class NewGVNLegacyPass : public FunctionPass {
3854public:
3855 static char ID; // Pass identification, replacement for typeid.
3856 NewGVNLegacyPass() : FunctionPass(ID) {
3857 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3858 }
3859 bool runOnFunction(Function &F) override;
3860
3861private:
3862 void getAnalysisUsage(AnalysisUsage &AU) const override {
3863 AU.addRequired<AssumptionCacheTracker>();
3864 AU.addRequired<DominatorTreeWrapperPass>();
3865 AU.addRequired<TargetLibraryInfoWrapperPass>();
3866 AU.addRequired<MemorySSAWrapperPass>();
3867 AU.addRequired<AAResultsWrapperPass>();
3868 AU.addPreserved<DominatorTreeWrapperPass>();
3869 AU.addPreserved<GlobalsAAWrapperPass>();
3870 }
3871};
3872
3873bool NewGVNLegacyPass::runOnFunction(Function &F) {
3874 if (skipFunction(F))
3875 return false;
3876 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3877 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3878 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3879 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3880 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3881 F.getParent()->getDataLayout())
3882 .runGVN();
3883}
3884
3885INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3886 false, false)
3887INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3888INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3889INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3890INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3891INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3892INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3893INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3894 false)
3895
3896char NewGVNLegacyPass::ID = 0;
3897
3898// createGVNPass - The public interface to this file.
3899FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3900
3901PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3902 // Apparently the order in which we get these results matter for
3903 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3904 // the same order here, just in case.
3905 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3906 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3907 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3908 auto &AA = AM.getResult<AAManager>(F);
3909 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3910 bool Changed =
3911 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3912 .runGVN();
3913 if (!Changed)
3914 return PreservedAnalyses::all();
3915 PreservedAnalyses PA;
3916 PA.preserve<DominatorTreeAnalysis>();
3917 PA.preserve<GlobalsAA>();
3918 return PA;
3919}