blob: 27809f5b6f6610aa6ca28bc3e424bb3ebf33621b [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
380namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000381template <> struct DenseMapInfo<const Expression *> {
382 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000383 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000384 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
385 return reinterpret_cast<const Expression *>(Val);
386 }
387 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000388 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000389 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
390 return reinterpret_cast<const Expression *>(Val);
391 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000392 static unsigned getHashValue(const Expression *E) {
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000393 return static_cast<unsigned>(E->getComputedHash());
Daniel Berlin85f91b02016-12-26 20:06:58 +0000394 }
395 static bool isEqual(const Expression *LHS, const Expression *RHS) {
396 if (LHS == RHS)
397 return true;
398 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
399 LHS == getEmptyKey() || RHS == getEmptyKey())
400 return false;
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000401 // Compare hashes before equality. This is *not* what the hashtable does,
402 // since it is computing it modulo the number of buckets, whereas we are
403 // using the full hash keyspace. Since the hashes are precomputed, this
404 // check is *much* faster than equality.
405 if (LHS->getComputedHash() != RHS->getComputedHash())
406 return false;
Daniel Berlin85f91b02016-12-26 20:06:58 +0000407 return *LHS == *RHS;
408 }
409};
Davide Italiano7e274e02016-12-22 16:03:48 +0000410} // end namespace llvm
411
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000412namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000413class NewGVN {
414 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000415 DominatorTree *DT;
Daniel Berlin64e68992017-03-12 04:46:45 +0000416 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000417 AliasAnalysis *AA;
418 MemorySSA *MSSA;
419 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000420 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000421 std::unique_ptr<PredicateInfo> PredInfo;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000422
423 // These are the only two things the create* functions should have
424 // side-effects on due to allocating memory.
425 mutable BumpPtrAllocator ExpressionAllocator;
426 mutable ArrayRecycler<Value *> ArgRecycler;
427 mutable TarjanSCC SCCFinder;
Daniel Berlinede130d2017-04-26 20:56:14 +0000428 const SimplifyQuery SQ;
Davide Italiano7e274e02016-12-22 16:03:48 +0000429
Daniel Berlin1c087672017-02-11 15:07:01 +0000430 // Number of function arguments, used by ranking
431 unsigned int NumFuncArgs;
432
Daniel Berlin2f72b192017-04-14 02:53:37 +0000433 // RPOOrdering of basic blocks
434 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
435
Davide Italiano7e274e02016-12-22 16:03:48 +0000436 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000437
438 // This class is called INITIAL in the paper. It is the class everything
439 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000440 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000441 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000442 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000443 std::vector<CongruenceClass *> CongruenceClasses;
444 unsigned NextCongruenceNum;
445
446 // Value Mappings.
447 DenseMap<Value *, CongruenceClass *> ValueToClass;
448 DenseMap<Value *, const Expression *> ValueToExpression;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000449 // Value PHI handling, used to make equivalence between phi(op, op) and
450 // op(phi, phi).
451 // These mappings just store various data that would normally be part of the
452 // IR.
453 DenseSet<const Instruction *> PHINodeUses;
454 // Map a temporary instruction we created to a parent block.
455 DenseMap<const Value *, BasicBlock *> TempToBlock;
456 // Map between the temporary phis we created and the real instructions they
457 // are known equivalent to.
458 DenseMap<const Value *, PHINode *> RealToTemp;
459 // In order to know when we should re-process instructions that have
460 // phi-of-ops, we track the set of expressions that they needed as
461 // leaders. When we discover new leaders for those expressions, we process the
462 // associated phi-of-op instructions again in case they have changed. The
463 // other way they may change is if they had leaders, and those leaders
464 // disappear. However, at the point they have leaders, there are uses of the
465 // relevant operands in the created phi node, and so they will get reprocessed
466 // through the normal user marking we perform.
467 mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
468 DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
469 ExpressionToPhiOfOps;
470 // Map from basic block to the temporary operations we created
Daniel Berlin0207cca2017-05-21 23:41:56 +0000471 DenseMap<const BasicBlock *, SmallVector<PHINode *, 8>> PHIOfOpsPHIs;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000472 // Map from temporary operation to MemoryAccess.
473 DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
474 // Set of all temporary instructions we created.
475 DenseSet<Instruction *> AllTempInstructions;
Davide Italiano7e274e02016-12-22 16:03:48 +0000476
Daniel Berlinf7d95802017-02-18 23:06:50 +0000477 // Mapping from predicate info we used to the instructions we used it with.
478 // In order to correctly ensure propagation, we must keep track of what
479 // comparisons we used, so that when the values of the comparisons change, we
480 // propagate the information to the places we used the comparison.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000481 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
482 PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000483 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
484 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000485 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
486 MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000487
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000488 // A table storing which memorydefs/phis represent a memory state provably
489 // equivalent to another memory state.
490 // We could use the congruence class machinery, but the MemoryAccess's are
491 // abstract memory states, so they can only ever be equivalent to each other,
492 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000493 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000494
Daniel Berlin1316a942017-04-06 18:52:50 +0000495 // We could, if we wanted, build MemoryPhiExpressions and
496 // MemoryVariableExpressions, etc, and value number them the same way we value
497 // number phi expressions. For the moment, this seems like overkill. They
498 // can only exist in one of three states: they can be TOP (equal to
499 // everything), Equivalent to something else, or unique. Because we do not
500 // create expressions for them, we need to simulate leader change not just
501 // when they change class, but when they change state. Note: We can do the
502 // same thing for phis, and avoid having phi expressions if we wanted, We
503 // should eventually unify in one direction or the other, so this is a little
504 // bit of an experiment in which turns out easier to maintain.
505 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
506 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
507
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000508 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
509 mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
Davide Italiano7e274e02016-12-22 16:03:48 +0000510 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000511 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000512 ExpressionClassMap ExpressionToClass;
513
Daniel Berline021d2d2017-05-19 20:22:20 +0000514 // We have a single expression that represents currently DeadExpressions.
515 // For dead expressions we can prove will stay dead, we mark them with
516 // DFS number zero. However, it's possible in the case of phi nodes
517 // for us to assume/prove all arguments are dead during fixpointing.
518 // We use DeadExpression for that case.
519 DeadExpression *SingletonDeadExpression = nullptr;
520
Davide Italiano7e274e02016-12-22 16:03:48 +0000521 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000522 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000523
524 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000525 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000526 DenseSet<BlockEdge> ReachableEdges;
527 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
528
529 // This is a bitvector because, on larger functions, we may have
530 // thousands of touched instructions at once (entire blocks,
531 // instructions with hundreds of uses, etc). Even with optimization
532 // for when we mark whole blocks as touched, when this was a
533 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
534 // the time in GVN just managing this list. The bitvector, on the
535 // other hand, efficiently supports test/set/clear of both
536 // individual and ranges, as well as "find next element" This
537 // enables us to use it as a worklist with essentially 0 cost.
538 BitVector TouchedInstructions;
539
540 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000541
542#ifndef NDEBUG
543 // Debugging for how many times each block and instruction got processed.
544 DenseMap<const Value *, unsigned> ProcessedCount;
545#endif
546
547 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000548 // This contains a mapping from Instructions to DFS numbers.
549 // The numbering starts at 1. An instruction with DFS number zero
550 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000551 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000552
553 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000554 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000555
556 // Deletion info.
557 SmallPtrSet<Instruction *, 8> InstructionsToErase;
558
559public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000560 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
561 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
562 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000563 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Daniel Berlinede130d2017-04-26 20:56:14 +0000564 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
565 }
Daniel Berlin64e68992017-03-12 04:46:45 +0000566 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000567
568private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000569 // Expression handling.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000570 const Expression *createExpression(Instruction *) const;
571 const Expression *createBinaryExpression(unsigned, Type *, Value *,
572 Value *) const;
573 PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000574 bool &OriginalOpsConstant) const;
Daniel Berline021d2d2017-05-19 20:22:20 +0000575 const DeadExpression *createDeadExpression() const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000576 const VariableExpression *createVariableExpression(Value *) const;
577 const ConstantExpression *createConstantExpression(Constant *) const;
578 const Expression *createVariableOrConstant(Value *V) const;
579 const UnknownExpression *createUnknownExpression(Instruction *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000580 const StoreExpression *createStoreExpression(StoreInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000581 const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000582 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000583 const MemoryAccess *) const;
584 const CallExpression *createCallExpression(CallInst *,
585 const MemoryAccess *) const;
586 const AggregateValueExpression *
587 createAggregateValueExpression(Instruction *) const;
588 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000589
590 // Congruence class handling.
591 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000592 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000593 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000594 return result;
595 }
596
Daniel Berlin1316a942017-04-06 18:52:50 +0000597 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
598 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000599 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000600 return CC;
601 }
602 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
603 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000604 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000605 CC = createMemoryClass(MA);
606 return CC;
607 }
608
Davide Italiano7e274e02016-12-22 16:03:48 +0000609 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000610 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000611 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000612 ValueToClass[Member] = CClass;
613 return CClass;
614 }
615 void initializeCongruenceClasses(Function &F);
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +0000616 const Expression *makePossiblePhiOfOps(Instruction *,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000617 SmallPtrSetImpl<Value *> &);
618 void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
Davide Italiano7e274e02016-12-22 16:03:48 +0000619
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000620 // Value number an Instruction or MemoryPhi.
621 void valueNumberMemoryPhi(MemoryPhi *);
622 void valueNumberInstruction(Instruction *);
623
Davide Italiano7e274e02016-12-22 16:03:48 +0000624 // Symbolic evaluation.
625 const Expression *checkSimplificationResults(Expression *, Instruction *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000626 Value *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000627 const Expression *performSymbolicEvaluation(Value *,
628 SmallPtrSetImpl<Value *> &) const;
Daniel Berlin07daac82017-04-02 13:23:44 +0000629 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000630 Instruction *,
631 MemoryAccess *) const;
632 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
633 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
634 const Expression *performSymbolicCallEvaluation(Instruction *) const;
635 const Expression *performSymbolicPHIEvaluation(Instruction *) const;
636 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
637 const Expression *performSymbolicCmpEvaluation(Instruction *) const;
638 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000639
640 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000641 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000642 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000643 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000644 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
645 CongruenceClass *, CongruenceClass *);
646 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
647 CongruenceClass *, CongruenceClass *);
648 Value *getNextValueLeader(CongruenceClass *) const;
649 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
650 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
651 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
652 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000653 bool isMemoryAccessTOP(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000654
Daniel Berlin1c087672017-02-11 15:07:01 +0000655 // Ranking
656 unsigned int getRank(const Value *) const;
657 bool shouldSwapOperands(const Value *, const Value *) const;
658
Davide Italiano7e274e02016-12-22 16:03:48 +0000659 // Reachability handling.
660 void updateReachableEdge(BasicBlock *, BasicBlock *);
661 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000662 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000663
664 // Elimination.
665 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000666 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000667 SmallVectorImpl<ValueDFS> &,
668 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000669 SmallPtrSetImpl<Instruction *> &) const;
670 void convertClassToLoadsAndStores(const CongruenceClass &,
671 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000672
673 bool eliminateInstructions(Function &);
674 void replaceInstruction(Instruction *, Value *);
675 void markInstructionForDeletion(Instruction *);
676 void deleteInstructionsInBlock(BasicBlock *);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000677 Value *findPhiOfOpsLeader(const Expression *E, const BasicBlock *BB) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000678
679 // New instruction creation.
680 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000681
682 // Various instruction touch utilities
Daniel Berlin0207cca2017-05-21 23:41:56 +0000683 template <typename Map, typename KeyType, typename Func>
684 void for_each_found(Map &, const KeyType &, Func);
685 template <typename Map, typename KeyType>
686 void touchAndErase(Map &, const KeyType &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000687 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000688 void markMemoryUsersTouched(const MemoryAccess *);
689 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000690 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000691 void markValueLeaderChangeTouched(CongruenceClass *CC);
692 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000693 void markPhiOfOpsChanged(const Expression *E);
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000694 void addPredicateUsers(const PredicateBase *, Instruction *) const;
695 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000696 void addAdditionalUsers(Value *To, Value *User) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000697
Daniel Berlin06329a92017-03-18 15:41:40 +0000698 // Main loop of value numbering
699 void iterateTouchedInstructions();
700
Davide Italiano7e274e02016-12-22 16:03:48 +0000701 // Utilities.
702 void cleanupTables();
703 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000704 void updateProcessedCount(const Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000705 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000706 void verifyIterationSettled(Function &F);
Daniel Berlin45403572017-05-16 19:58:47 +0000707 void verifyStoreExpressions() const;
Davide Italianoeab0de22017-05-18 23:22:44 +0000708 bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
709 const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000710 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000711 void deleteExpression(const Expression *E) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000712 MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
713 MemoryAccess *getDefiningAccess(const MemoryAccess *) const;
714 MemoryPhi *getMemoryAccess(const BasicBlock *) const;
715 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin21279bd2017-04-06 18:52:58 +0000716 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000717 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
718 return InstrDFS.lookup(V);
719 }
720
Daniel Berlin21279bd2017-04-06 18:52:58 +0000721 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
722 return MemoryToDFSNum(MA);
723 }
724 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
725 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
726 // This deliberately takes a value so it can be used with Use's, which will
727 // auto-convert to Value's but not to MemoryAccess's.
728 unsigned MemoryToDFSNum(const Value *MA) const {
729 assert(isa<MemoryAccess>(MA) &&
730 "This should not be used with instructions");
731 return isa<MemoryUseOrDef>(MA)
732 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
733 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000734 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000735 bool isCycleFree(const Instruction *) const;
736 bool isBackedge(BasicBlock *From, BasicBlock *To) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000737 // Debug counter info. When verifying, we have to reset the value numbering
738 // debug counter to the same state it started in to get the same results.
739 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000740};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000741} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000742
Davide Italianob1114092016-12-28 13:37:17 +0000743template <typename T>
744static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000745 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000746 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000747 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000748}
749
Davide Italianob1114092016-12-28 13:37:17 +0000750bool LoadExpression::equals(const Expression &Other) const {
751 return equalsLoadStoreHelper(*this, Other);
752}
Davide Italiano7e274e02016-12-22 16:03:48 +0000753
Davide Italianob1114092016-12-28 13:37:17 +0000754bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000755 if (!equalsLoadStoreHelper(*this, Other))
756 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000757 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000758 if (const auto *S = dyn_cast<StoreExpression>(&Other))
759 if (getStoredValue() != S->getStoredValue())
760 return false;
761 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000762}
763
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000764// Determine if the edge From->To is a backedge
765bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
766 if (From == To)
767 return true;
768 auto *FromDTN = DT->getNode(From);
769 auto *ToDTN = DT->getNode(To);
770 return RPOOrdering.lookup(FromDTN) >= RPOOrdering.lookup(ToDTN);
771}
772
Davide Italiano7e274e02016-12-22 16:03:48 +0000773#ifndef NDEBUG
774static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000775 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000776}
777#endif
778
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000779// Get a MemoryAccess for an instruction, fake or real.
780MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
781 auto *Result = MSSA->getMemoryAccess(I);
782 return Result ? Result : TempToMemory.lookup(I);
783}
784
785// Get a MemoryPhi for a basic block. These are all real.
786MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
787 return MSSA->getMemoryAccess(BB);
788}
789
Daniel Berlin06329a92017-03-18 15:41:40 +0000790// Get the basic block from an instruction/memory value.
791BasicBlock *NewGVN::getBlockForValue(Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000792 if (auto *I = dyn_cast<Instruction>(V)) {
793 auto *Parent = I->getParent();
794 if (Parent)
795 return Parent;
796 Parent = TempToBlock.lookup(V);
797 assert(Parent && "Every fake instruction should have a block");
798 return Parent;
799 }
800
801 auto *MP = dyn_cast<MemoryPhi>(V);
802 assert(MP && "Should have been an instruction or a MemoryPhi");
803 return MP->getBlock();
Daniel Berlin06329a92017-03-18 15:41:40 +0000804}
805
Daniel Berlin0e900112017-03-24 06:33:48 +0000806// Delete a definitely dead expression, so it can be reused by the expression
807// allocator. Some of these are not in creation functions, so we have to accept
808// const versions.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000809void NewGVN::deleteExpression(const Expression *E) const {
Daniel Berlin0e900112017-03-24 06:33:48 +0000810 assert(isa<BasicExpression>(E));
811 auto *BE = cast<BasicExpression>(E);
812 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
813 ExpressionAllocator.Deallocate(E);
814}
Daniel Berlin2f72b192017-04-14 02:53:37 +0000815PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000816 bool &OriginalOpsConstant) const {
817 BasicBlock *PHIBlock = getBlockForValue(I);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000818 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000819 auto *E =
820 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000821
822 E->allocateOperands(ArgRecycler, ExpressionAllocator);
823 E->setType(I->getType());
824 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000825
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000826 // NewGVN assumes the operands of a PHI node are in a consistent order across
827 // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
828 // this in LLVM at some point we don't want GVN to find wrong congruences.
829 // Therefore, here we sort uses in predecessor order.
Davide Italiano63998ec2017-05-09 18:29:37 +0000830 // We're sorting the values by pointer. In theory this might be cause of
831 // non-determinism, but here we don't rely on the ordering for anything
832 // significant, e.g. we don't create new instructions based on it so we're
833 // fine.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000834 SmallVector<const Use *, 4> PHIOperands;
835 for (const Use &U : PN->operands())
836 PHIOperands.push_back(&U);
837 std::sort(PHIOperands.begin(), PHIOperands.end(),
838 [&](const Use *U1, const Use *U2) {
839 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
840 });
841
Davide Italianob3886dd2017-01-25 23:37:49 +0000842 // Filter out unreachable phi operands.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000843 auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
Daniel Berline67c3222017-05-25 15:44:20 +0000844 if (*U == PN)
845 return false;
846 if (!ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock}))
847 return false;
848 // Things in TOPClass are equivalent to everything.
849 if (ValueToClass.lookup(*U) == TOPClass)
850 return false;
851 return true;
Davide Italianob3886dd2017-01-25 23:37:49 +0000852 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000853 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000854 [&](const Use *U) -> Value * {
855 auto *BB = PN->getIncomingBlock(*U);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000856 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
857 OriginalOpsConstant =
858 OriginalOpsConstant && isa<Constant>(*U);
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000859 return lookupOperandLeader(*U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000860 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000861 return E;
862}
863
864// Set basic expression info (Arguments, type, opcode) for Expression
865// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000866bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000867 bool AllConstant = true;
868 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
869 E->setType(GEP->getSourceElementType());
870 else
871 E->setType(I->getType());
872 E->setOpcode(I->getOpcode());
873 E->allocateOperands(ArgRecycler, ExpressionAllocator);
874
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000875 // Transform the operand array into an operand leader array, and keep track of
876 // whether all members are constant.
877 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000878 auto Operand = lookupOperandLeader(O);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000879 AllConstant = AllConstant && isa<Constant>(Operand);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000880 return Operand;
881 });
882
Davide Italiano7e274e02016-12-22 16:03:48 +0000883 return AllConstant;
884}
885
886const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000887 Value *Arg1,
888 Value *Arg2) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000889 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000890
891 E->setType(T);
892 E->setOpcode(Opcode);
893 E->allocateOperands(ArgRecycler, ExpressionAllocator);
894 if (Instruction::isCommutative(Opcode)) {
895 // Ensure that commutative instructions that only differ by a permutation
896 // of their operands get the same value number by sorting the operand value
897 // numbers. Since all commutative instructions have two operands it is more
898 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000899 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000900 std::swap(Arg1, Arg2);
901 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000902 E->op_push_back(lookupOperandLeader(Arg1));
903 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000904
Daniel Berlinede130d2017-04-26 20:56:14 +0000905 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000906 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
907 return SimplifiedE;
908 return E;
909}
910
911// Take a Value returned by simplification of Expression E/Instruction
912// I, and see if it resulted in a simpler expression. If so, return
913// that expression.
914// TODO: Once finished, this should not take an Instruction, we only
915// use it for printing.
916const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000917 Instruction *I,
918 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000919 if (!V)
920 return nullptr;
921 if (auto *C = dyn_cast<Constant>(V)) {
922 if (I)
923 DEBUG(dbgs() << "Simplified " << *I << " to "
924 << " constant " << *C << "\n");
925 NumGVNOpsSimplified++;
926 assert(isa<BasicExpression>(E) &&
927 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000928 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000929 return createConstantExpression(C);
930 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
931 if (I)
932 DEBUG(dbgs() << "Simplified " << *I << " to "
933 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000934 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000935 return createVariableExpression(V);
936 }
937
938 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlina8236562017-04-07 18:38:09 +0000939 if (CC && CC->getDefiningExpr()) {
Davide Italianofd9100e2017-05-24 02:30:24 +0000940 // If we simplified to something else, we need to communicate
941 // that we're users of the value we simplified to.
Daniel Berlinc8ed4042017-05-30 06:42:29 +0000942 if (I != V) {
943 // Don't add temporary instructions to the user lists.
944 if (!AllTempInstructions.count(I))
945 addAdditionalUsers(V, I);
946 }
947
Davide Italiano7e274e02016-12-22 16:03:48 +0000948 if (I)
949 DEBUG(dbgs() << "Simplified " << *I << " to "
Daniel Berlin01939972017-05-21 23:41:53 +0000950 << " expression " << *CC->getDefiningExpr() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +0000951 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000952 deleteExpression(E);
Daniel Berlina8236562017-04-07 18:38:09 +0000953 return CC->getDefiningExpr();
Davide Italiano7e274e02016-12-22 16:03:48 +0000954 }
955 return nullptr;
956}
957
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000958const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000959 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000960
Daniel Berlin97718e62017-01-31 22:32:03 +0000961 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000962
963 if (I->isCommutative()) {
964 // Ensure that commutative instructions that only differ by a permutation
965 // of their operands get the same value number by sorting the operand value
966 // numbers. Since all commutative instructions have two operands it is more
967 // efficient to sort by hand rather than using, say, std::sort.
968 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000969 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000970 E->swapOperands(0, 1);
971 }
972
973 // Perform simplificaiton
974 // TODO: Right now we only check to see if we get a constant result.
975 // We may get a less than constant, but still better, result for
976 // some operations.
977 // IE
978 // add 0, x -> x
979 // and x, x -> x
980 // We should handle this by simply rewriting the expression.
981 if (auto *CI = dyn_cast<CmpInst>(I)) {
982 // Sort the operand value numbers so x<y and y>x get the same value
983 // number.
984 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000985 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000986 E->swapOperands(0, 1);
987 Predicate = CmpInst::getSwappedPredicate(Predicate);
988 }
989 E->setOpcode((CI->getOpcode() << 8) | Predicate);
990 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000991 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
992 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000993 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
994 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +0000995 Value *V =
996 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +0000997 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
998 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000999 } else if (isa<SelectInst>(I)) {
1000 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +00001001 E->getOperand(0) == E->getOperand(1)) {
1002 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1003 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +00001004 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +00001005 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001006 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1007 return SimplifiedE;
1008 }
1009 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001010 Value *V =
1011 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001012 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1013 return SimplifiedE;
1014 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001015 Value *V =
1016 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001017 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1018 return SimplifiedE;
1019 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001020 Value *V = SimplifyGEPInst(
1021 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001022 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1023 return SimplifiedE;
1024 } else if (AllConstant) {
1025 // We don't bother trying to simplify unless all of the operands
1026 // were constant.
1027 // TODO: There are a lot of Simplify*'s we could call here, if we
1028 // wanted to. The original motivating case for this code was a
1029 // zext i1 false to i8, which we don't have an interface to
1030 // simplify (IE there is no SimplifyZExt).
1031
1032 SmallVector<Constant *, 8> C;
1033 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001034 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +00001035
Daniel Berlin64e68992017-03-12 04:46:45 +00001036 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +00001037 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1038 return SimplifiedE;
1039 }
1040 return E;
1041}
1042
1043const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001044NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001045 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001046 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001047 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001048 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001049 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001050 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001051 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001052 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001053 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001054 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001055 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001056 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001057 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001058 return E;
1059 }
1060 llvm_unreachable("Unhandled type of aggregate value operation");
1061}
1062
Daniel Berline021d2d2017-05-19 20:22:20 +00001063const DeadExpression *NewGVN::createDeadExpression() const {
1064 // DeadExpression has no arguments and all DeadExpression's are the same,
1065 // so we only need one of them.
1066 return SingletonDeadExpression;
1067}
1068
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001069const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001070 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001071 E->setOpcode(V->getValueID());
1072 return E;
1073}
1074
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001075const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001076 if (auto *C = dyn_cast<Constant>(V))
1077 return createConstantExpression(C);
1078 return createVariableExpression(V);
1079}
1080
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001081const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001082 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +00001083 E->setOpcode(C->getValueID());
1084 return E;
1085}
1086
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001087const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001088 auto *E = new (ExpressionAllocator) UnknownExpression(I);
1089 E->setOpcode(I->getOpcode());
1090 return E;
1091}
1092
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001093const CallExpression *
1094NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001095 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001096 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +00001097 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +00001098 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001099 return E;
1100}
1101
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001102// Return true if some equivalent of instruction Inst dominates instruction U.
1103bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1104 const Instruction *U) const {
1105 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +00001106 // This must be an instruction because we are only called from phi nodes
1107 // in the case that the value it needs to check against is an instruction.
1108
1109 // The most likely candiates for dominance are the leader and the next leader.
1110 // The leader or nextleader will dominate in all cases where there is an
1111 // equivalent that is higher up in the dom tree.
1112 // We can't *only* check them, however, because the
1113 // dominator tree could have an infinite number of non-dominating siblings
1114 // with instructions that are in the right congruence class.
1115 // A
1116 // B C D E F G
1117 // |
1118 // H
1119 // Instruction U could be in H, with equivalents in every other sibling.
1120 // Depending on the rpo order picked, the leader could be the equivalent in
1121 // any of these siblings.
1122 if (!CC)
1123 return false;
Daniel Berlina8236562017-04-07 18:38:09 +00001124 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001125 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001126 if (CC->getNextLeader().first &&
1127 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001128 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001129 return llvm::any_of(*CC, [&](const Value *Member) {
1130 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001131 DT->dominates(cast<Instruction>(Member), U);
1132 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001133}
1134
Davide Italiano7e274e02016-12-22 16:03:48 +00001135// See if we have a congruence class and leader for this operand, and if so,
1136// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001137Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001138 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001139 if (CC) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001140 // Everything in TOP is represented by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001141 // We do have to make sure we get the type right though, so we can't set the
1142 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001143 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001144 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001145 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001146 }
1147
Davide Italiano7e274e02016-12-22 16:03:48 +00001148 return V;
1149}
1150
Daniel Berlin1316a942017-04-06 18:52:50 +00001151const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1152 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001153 assert(CC->getMemoryLeader() &&
Davide Italianob60f6e02017-05-12 15:25:56 +00001154 "Every MemoryAccess should be mapped to a congruence class with a "
1155 "representative memory access");
Daniel Berlina8236562017-04-07 18:38:09 +00001156 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001157}
1158
Daniel Berlinc4796862017-01-27 02:37:11 +00001159// Return true if the MemoryAccess is really equivalent to everything. This is
1160// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001161// state of all MemoryAccesses.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001162bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001163 return getMemoryClass(MA) == TOPClass;
1164}
1165
Davide Italiano7e274e02016-12-22 16:03:48 +00001166LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001167 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001168 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001169 auto *E =
1170 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001171 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1172 E->setType(LoadType);
1173
1174 // Give store and loads same opcode so they value number together.
1175 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001176 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001177 if (LI)
1178 E->setAlignment(LI->getAlignment());
1179
1180 // TODO: Value number heap versions. We may be able to discover
1181 // things alias analysis can't on it's own (IE that a store and a
1182 // load have the same value, and thus, it isn't clobbering the load).
1183 return E;
1184}
1185
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001186const StoreExpression *
1187NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001188 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001189 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001190 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001191 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1192 E->setType(SI->getValueOperand()->getType());
1193
1194 // Give store and loads same opcode so they value number together.
1195 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001196 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001197
1198 // TODO: Value number heap versions. We may be able to discover
1199 // things alias analysis can't on it's own (IE that a store and a
1200 // load have the same value, and thus, it isn't clobbering the load).
1201 return E;
1202}
1203
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001204const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001205 // Unlike loads, we never try to eliminate stores, so we do not check if they
1206 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001207 auto *SI = cast<StoreInst>(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001208 auto *StoreAccess = getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001209 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001210 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1211 if (EnableStoreRefinement)
1212 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1213 // If we bypassed the use-def chains, make sure we add a use.
1214 if (StoreRHS != StoreAccess->getDefiningAccess())
1215 addMemoryUsers(StoreRHS, StoreAccess);
Daniel Berlin1316a942017-04-06 18:52:50 +00001216 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001217 // If we are defined by ourselves, use the live on entry def.
1218 if (StoreRHS == StoreAccess)
1219 StoreRHS = MSSA->getLiveOnEntryDef();
1220
Daniel Berlin589cecc2017-01-02 18:00:46 +00001221 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001222 // See if we are defined by a previous store expression, it already has a
1223 // value, and it's the same value as our current store. FIXME: Right now, we
1224 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001225 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1226 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +00001227 // Basically, check if the congruence class the store is in is defined by a
1228 // store that isn't us, and has the same value. MemorySSA takes care of
1229 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +00001230 // The RepStoredValue gets nulled if all the stores disappear in a class, so
1231 // we don't need to check if the class contains a store besides us.
Daniel Berlin1316a942017-04-06 18:52:50 +00001232 if (LastCC &&
Daniel Berlina8236562017-04-07 18:38:09 +00001233 LastCC->getStoredValue() == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin1316a942017-04-06 18:52:50 +00001234 return LastStore;
1235 deleteExpression(LastStore);
Daniel Berlinc4796862017-01-27 02:37:11 +00001236 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001237 // location, and the memory state is the same as it was then (otherwise, it
1238 // could have been overwritten later. See test32 in
1239 // transforms/DeadStoreElimination/simple.ll).
1240 if (auto *LI =
1241 dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001242 if ((lookupOperandLeader(LI->getPointerOperand()) ==
1243 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001244 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
Daniel Berlin1316a942017-04-06 18:52:50 +00001245 StoreRHS))
Davide Italiano9a0f5422017-05-20 00:46:54 +00001246 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001247 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001248 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001249
1250 // If the store is not equivalent to anything, value number it as a store that
1251 // produces a unique memory state (instead of using it's MemoryUse, we use
1252 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001253 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001254}
1255
Daniel Berlin07daac82017-04-02 13:23:44 +00001256// See if we can extract the value of a loaded pointer from a load, a store, or
1257// a memory instruction.
1258const Expression *
1259NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1260 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001261 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001262 assert((!LI || LI->isSimple()) && "Not a simple load");
1263 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1264 // Can't forward from non-atomic to atomic without violating memory model.
1265 // Also don't need to coerce if they are the same type, we will just
1266 // propogate..
1267 if (LI->isAtomic() > DepSI->isAtomic() ||
1268 LoadType == DepSI->getValueOperand()->getType())
1269 return nullptr;
1270 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1271 if (Offset >= 0) {
1272 if (auto *C = dyn_cast<Constant>(
1273 lookupOperandLeader(DepSI->getValueOperand()))) {
1274 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1275 << *C << "\n");
1276 return createConstantExpression(
1277 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1278 }
1279 }
1280
1281 } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1282 // Can't forward from non-atomic to atomic without violating memory model.
1283 if (LI->isAtomic() > DepLI->isAtomic())
1284 return nullptr;
1285 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1286 if (Offset >= 0) {
1287 // We can coerce a constant load into a load
1288 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1289 if (auto *PossibleConstant =
1290 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1291 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1292 << *PossibleConstant << "\n");
1293 return createConstantExpression(PossibleConstant);
1294 }
1295 }
1296
1297 } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1298 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1299 if (Offset >= 0) {
1300 if (auto *PossibleConstant =
1301 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1302 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1303 << " to constant " << *PossibleConstant << "\n");
1304 return createConstantExpression(PossibleConstant);
1305 }
1306 }
1307 }
1308
1309 // All of the below are only true if the loaded pointer is produced
1310 // by the dependent instruction.
1311 if (LoadPtr != lookupOperandLeader(DepInst) &&
1312 !AA->isMustAlias(LoadPtr, DepInst))
1313 return nullptr;
1314 // If this load really doesn't depend on anything, then we must be loading an
1315 // undef value. This can happen when loading for a fresh allocation with no
1316 // intervening stores, for example. Note that this is only true in the case
1317 // that the result of the allocation is pointer equal to the load ptr.
1318 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1319 return createConstantExpression(UndefValue::get(LoadType));
1320 }
1321 // If this load occurs either right after a lifetime begin,
1322 // then the loaded value is undefined.
1323 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1324 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1325 return createConstantExpression(UndefValue::get(LoadType));
1326 }
1327 // If this load follows a calloc (which zero initializes memory),
1328 // then the loaded value is zero
1329 else if (isCallocLikeFn(DepInst, TLI)) {
1330 return createConstantExpression(Constant::getNullValue(LoadType));
1331 }
1332
1333 return nullptr;
1334}
1335
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001336const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001337 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001338
1339 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001340 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001341 if (!LI->isSimple())
1342 return nullptr;
1343
Daniel Berlin203f47b2017-01-31 22:31:53 +00001344 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001345 // Load of undef is undef.
1346 if (isa<UndefValue>(LoadAddressLeader))
1347 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001348 MemoryAccess *OriginalAccess = getMemoryAccess(I);
1349 MemoryAccess *DefiningAccess =
1350 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001351
1352 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1353 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1354 Instruction *DefiningInst = MD->getMemoryInst();
1355 // If the defining instruction is not reachable, replace with undef.
1356 if (!ReachableBlocks.count(DefiningInst->getParent()))
1357 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001358 // This will handle stores and memory insts. We only do if it the
1359 // defining access has a different type, or it is a pointer produced by
1360 // certain memory operations that cause the memory to have a fixed value
1361 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001362 if (const auto *CoercionResult =
1363 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1364 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001365 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001366 }
1367 }
1368
Daniel Berlin1316a942017-04-06 18:52:50 +00001369 const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1370 LI, DefiningAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001371 return E;
1372}
1373
Daniel Berlinf7d95802017-02-18 23:06:50 +00001374const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001375NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001376 auto *PI = PredInfo->getPredicateInfoFor(I);
1377 if (!PI)
1378 return nullptr;
1379
1380 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001381
1382 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1383 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001384 return nullptr;
1385
Daniel Berlinfccbda92017-02-22 22:20:58 +00001386 auto *CopyOf = I->getOperand(0);
1387 auto *Cond = PWC->Condition;
1388
Daniel Berlinf7d95802017-02-18 23:06:50 +00001389 // If this a copy of the condition, it must be either true or false depending
1390 // on the predicate info type and edge
1391 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001392 // We should not need to add predicate users because the predicate info is
1393 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001394 if (isa<PredicateAssume>(PI))
1395 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1396 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1397 if (PBranch->TrueEdge)
1398 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1399 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1400 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001401 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1402 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001403 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001404
Daniel Berlinf7d95802017-02-18 23:06:50 +00001405 // Not a copy of the condition, so see what the predicates tell us about this
1406 // value. First, though, we check to make sure the value is actually a copy
1407 // of one of the condition operands. It's possible, in certain cases, for it
1408 // to be a copy of a predicateinfo copy. In particular, if two branch
1409 // operations use the same condition, and one branch dominates the other, we
1410 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001411 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001412 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001413
1414 // Everything below relies on the condition being a comparison.
1415 auto *Cmp = dyn_cast<CmpInst>(Cond);
1416 if (!Cmp)
1417 return nullptr;
1418
1419 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Davide Italianoc43a9f82017-05-12 15:28:12 +00001420 DEBUG(dbgs() << "Copy is not of any condition operands!\n");
Daniel Berlinf7d95802017-02-18 23:06:50 +00001421 return nullptr;
1422 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001423 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1424 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001425 bool SwappedOps = false;
1426 // Sort the ops
1427 if (shouldSwapOperands(FirstOp, SecondOp)) {
1428 std::swap(FirstOp, SecondOp);
1429 SwappedOps = true;
1430 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001431 CmpInst::Predicate Predicate =
1432 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1433
1434 if (isa<PredicateAssume>(PI)) {
1435 // If the comparison is true when the operands are equal, then we know the
1436 // operands are equal, because assumes must always be true.
1437 if (CmpInst::isTrueWhenEqual(Predicate)) {
1438 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001439 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001440 return createVariableOrConstant(FirstOp);
1441 }
1442 }
1443 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1444 // If we are *not* a copy of the comparison, we may equal to the other
1445 // operand when the predicate implies something about equality of
1446 // operations. In particular, if the comparison is true/false when the
1447 // operands are equal, and we are on the right edge, we know this operation
1448 // is equal to something.
1449 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1450 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1451 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001452 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001453 return createVariableOrConstant(FirstOp);
1454 }
1455 // Handle the special case of floating point.
1456 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1457 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1458 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1459 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001460 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001461 return createConstantExpression(cast<Constant>(FirstOp));
1462 }
1463 }
1464 return nullptr;
1465}
1466
Davide Italiano7e274e02016-12-22 16:03:48 +00001467// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001468const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001469 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001470 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1471 // Instrinsics with the returned attribute are copies of arguments.
1472 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1473 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1474 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1475 return Result;
1476 return createVariableOrConstant(ReturnedValue);
1477 }
1478 }
1479 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001480 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001481 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001482 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001483 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001484 }
1485 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001486}
1487
Daniel Berlin1316a942017-04-06 18:52:50 +00001488// Retrieve the memory class for a given MemoryAccess.
1489CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1490
1491 auto *Result = MemoryAccessToClass.lookup(MA);
1492 assert(Result && "Should have found memory class");
1493 return Result;
1494}
1495
1496// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001497// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001498bool NewGVN::setMemoryClass(const MemoryAccess *From,
1499 CongruenceClass *NewClass) {
1500 assert(NewClass &&
1501 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001502 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001503 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001504 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
Davide Italianob7a66982017-05-09 20:02:48 +00001505 DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001506
1507 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001508 bool Changed = false;
1509 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001510 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001511 auto *OldClass = LookupResult->second;
1512 if (OldClass != NewClass) {
1513 // If this is a phi, we have to handle memory member updates.
1514 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001515 OldClass->memory_erase(MP);
1516 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001517 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001518 if (OldClass->getMemoryLeader() == From) {
Davide Italiano41f5c7b2017-05-12 15:22:45 +00001519 if (OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001520 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001521 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001522 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001523 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001524 << OldClass->getID() << " to "
1525 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001526 << " due to removal of a memory member " << *From
1527 << "\n");
1528 markMemoryLeaderChangeTouched(OldClass);
1529 }
1530 }
1531 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001532 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001533 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001534 Changed = true;
1535 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001536 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001537
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001538 return Changed;
1539}
Daniel Berlin0e900112017-03-24 06:33:48 +00001540
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001541// Determine if a instruction is cycle-free. That means the values in the
1542// instruction don't depend on any expressions that can change value as a result
1543// of the instruction. For example, a non-cycle free instruction would be v =
1544// phi(0, v+1).
1545bool NewGVN::isCycleFree(const Instruction *I) const {
1546 // In order to compute cycle-freeness, we do SCC finding on the instruction,
1547 // and see what kind of SCC it ends up in. If it is a singleton, it is
1548 // cycle-free. If it is not in a singleton, it is only cycle free if the
1549 // other members are all phi nodes (as they do not compute anything, they are
1550 // copies).
1551 auto ICS = InstCycleState.lookup(I);
1552 if (ICS == ICS_Unknown) {
1553 SCCFinder.Start(I);
1554 auto &SCC = SCCFinder.getComponentFor(I);
Daniel Berlin2f72b192017-04-14 02:53:37 +00001555 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1556 if (SCC.size() == 1)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001557 InstCycleState.insert({I, ICS_CycleFree});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001558 else {
1559 bool AllPhis =
1560 llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001561 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
Daniel Berlin2f72b192017-04-14 02:53:37 +00001562 for (auto *Member : SCC)
1563 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001564 InstCycleState.insert({MemberPhi, ICS});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001565 }
1566 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001567 if (ICS == ICS_Cycle)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001568 return false;
1569 return true;
1570}
1571
Davide Italiano7e274e02016-12-22 16:03:48 +00001572// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001573const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
Daniel Berline67c3222017-05-25 15:44:20 +00001574 // Resolve irreducible and reducible phi cycles.
1575 // FIXME: This is hopefully a temporary solution while we resolve the issues
1576 // with fixpointing self-cycles. It currently should be "guaranteed" to be
1577 // correct, but non-optimal. The SCCFinder does not, for example, take
1578 // reachability of arguments into account, etc.
1579 SCCFinder.Start(I);
1580 bool CanOptimize = true;
1581 SmallPtrSet<Value *, 8> OuterOps;
1582
1583 auto &Component = SCCFinder.getComponentFor(I);
1584 for (auto *Member : Component) {
1585 if (!isa<PHINode>(Member)) {
1586 CanOptimize = false;
1587 break;
1588 }
1589 for (auto &PHIOp : cast<PHINode>(Member)->operands())
1590 if (!isa<PHINode>(PHIOp) || !Component.count(cast<PHINode>(PHIOp)))
1591 OuterOps.insert(PHIOp);
1592 }
1593 if (CanOptimize && OuterOps.size() == 1) {
1594 DEBUG(dbgs() << "Resolving cyclic phi to value " << *(*OuterOps.begin())
1595 << "\n");
1596 return createVariableOrConstant(*OuterOps.begin());
1597 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001598 // True if one of the incoming phi edges is a backedge.
1599 bool HasBackedge = false;
1600 // All constant tracks the state of whether all the *original* phi operands
Daniel Berline021d2d2017-05-19 20:22:20 +00001601 // This is really shorthand for "this phi cannot cycle due to forward
1602 // change in value of the phi is guaranteed not to later change the value of
1603 // the phi. IE it can't be v = phi(undef, v+1)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001604 bool AllConstant = true;
Daniel Berlinabd632d2017-05-16 06:06:12 +00001605 auto *E =
1606 cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001607 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001608 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001609 // We track if any were undef because they need special handling.
1610 bool HasUndef = false;
Daniel Berline021d2d2017-05-19 20:22:20 +00001611 auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
Daniel Berlind92e7f92017-01-07 00:01:42 +00001612 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 Berline67c3222017-05-25 15:44:20 +00001620 // If it has undef at this point, it means there are no-non-undef arguments,
1621 // and thus, the value of the phi node must be undef.
1622 if (HasUndef) {
1623 DEBUG(dbgs() << "PHI Node " << *I
1624 << " has no non-undef arguments, valuing it as undef\n");
1625 return createConstantExpression(UndefValue::get(I->getType()));
1626 }
1627
Daniel Berline021d2d2017-05-19 20:22:20 +00001628 DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001629 deleteExpression(E);
Daniel Berline021d2d2017-05-19 20:22:20 +00001630 return createDeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00001631 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001632 unsigned NumOps = 0;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001633 Value *AllSameValue = *(Filtered.begin());
1634 ++Filtered.begin();
1635 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berline021d2d2017-05-19 20:22:20 +00001636 if (llvm::all_of(Filtered, [&](Value *Arg) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001637 ++NumOps;
Daniel Berline021d2d2017-05-19 20:22:20 +00001638 return Arg == AllSameValue;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001639 })) {
1640 // In LLVM's non-standard representation of phi nodes, it's possible to have
1641 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1642 // on the original phi node), especially in weird CFG's where some arguments
1643 // are unreachable, or uninitialized along certain paths. This can cause
1644 // infinite loops during evaluation. We work around this by not trying to
1645 // really evaluate them independently, but instead using a variable
1646 // expression to say if one is equivalent to the other.
1647 // We also special case undef, so that if we have an undef, we can't use the
1648 // common value unless it dominates the phi block.
1649 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001650 // If we have undef and at least one other value, this is really a
1651 // multivalued phi, and we need to know if it's cycle free in order to
1652 // evaluate whether we can ignore the undef. The other parts of this are
1653 // just shortcuts. If there is no backedge, or all operands are
1654 // constants, or all operands are ignored but the undef, it also must be
1655 // cycle free.
1656 if (!AllConstant && HasBackedge && NumOps > 0 &&
Daniel Berline67c3222017-05-25 15:44:20 +00001657 !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
Daniel Berlin2f72b192017-04-14 02:53:37 +00001658 return E;
1659
Daniel Berlind92e7f92017-01-07 00:01:42 +00001660 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001661 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001662 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001663 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001664 }
1665
Davide Italiano7e274e02016-12-22 16:03:48 +00001666 NumGVNPhisAllSame++;
1667 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1668 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001669 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001670 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001671 }
1672 return E;
1673}
1674
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001675const Expression *
1676NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001677 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1678 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1679 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1680 unsigned Opcode = 0;
1681 // EI might be an extract from one of our recognised intrinsics. If it
1682 // is we'll synthesize a semantically equivalent expression instead on
1683 // an extract value expression.
1684 switch (II->getIntrinsicID()) {
1685 case Intrinsic::sadd_with_overflow:
1686 case Intrinsic::uadd_with_overflow:
1687 Opcode = Instruction::Add;
1688 break;
1689 case Intrinsic::ssub_with_overflow:
1690 case Intrinsic::usub_with_overflow:
1691 Opcode = Instruction::Sub;
1692 break;
1693 case Intrinsic::smul_with_overflow:
1694 case Intrinsic::umul_with_overflow:
1695 Opcode = Instruction::Mul;
1696 break;
1697 default:
1698 break;
1699 }
1700
1701 if (Opcode != 0) {
1702 // Intrinsic recognized. Grab its args to finish building the
1703 // expression.
1704 assert(II->getNumArgOperands() == 2 &&
1705 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001706 return createBinaryExpression(
1707 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001708 }
1709 }
1710 }
1711
Daniel Berlin97718e62017-01-31 22:32:03 +00001712 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001713}
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001714const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001715 auto *CI = dyn_cast<CmpInst>(I);
1716 // See if our operands are equal to those of a previous predicate, and if so,
1717 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001718 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1719 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001720 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001721 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001722 std::swap(Op0, Op1);
1723 OurPredicate = CI->getSwappedPredicate();
1724 }
1725
1726 // Avoid processing the same info twice
1727 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001728 // See if we know something about the comparison itself, like it is the target
1729 // of an assume.
1730 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1731 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1732 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1733
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001734 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001735 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001736 if (CI->isTrueWhenEqual())
1737 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1738 else if (CI->isFalseWhenEqual())
1739 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1740 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001741
1742 // NOTE: Because we are comparing both operands here and below, and using
1743 // previous comparisons, we rely on fact that predicateinfo knows to mark
1744 // comparisons that use renamed operands as users of the earlier comparisons.
1745 // It is *not* enough to just mark predicateinfo renamed operands as users of
1746 // the earlier comparisons, because the *other* operand may have changed in a
1747 // previous iteration.
1748 // Example:
1749 // icmp slt %a, %b
1750 // %b.0 = ssa.copy(%b)
1751 // false branch:
1752 // icmp slt %c, %b.0
1753
1754 // %c and %a may start out equal, and thus, the code below will say the second
1755 // %icmp is false. c may become equal to something else, and in that case the
1756 // %second icmp *must* be reexamined, but would not if only the renamed
1757 // %operands are considered users of the icmp.
1758
1759 // *Currently* we only check one level of comparisons back, and only mark one
1760 // level back as touched when changes appen . If you modify this code to look
1761 // back farther through comparisons, you *must* mark the appropriate
1762 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1763 // we know something just from the operands themselves
1764
1765 // See if our operands have predicate info, so that we may be able to derive
1766 // something from a previous comparison.
1767 for (const auto &Op : CI->operands()) {
1768 auto *PI = PredInfo->getPredicateInfoFor(Op);
1769 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1770 if (PI == LastPredInfo)
1771 continue;
1772 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001773
Daniel Berlinf7d95802017-02-18 23:06:50 +00001774 // TODO: Along the false edge, we may know more things too, like icmp of
1775 // same operands is false.
1776 // TODO: We only handle actual comparison conditions below, not and/or.
1777 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1778 if (!BranchCond)
1779 continue;
1780 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1781 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1782 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001783 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001784 std::swap(BranchOp0, BranchOp1);
1785 BranchPredicate = BranchCond->getSwappedPredicate();
1786 }
1787 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1788 if (PBranch->TrueEdge) {
1789 // If we know the previous predicate is true and we are in the true
1790 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001791 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1792 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001793 addPredicateUsers(PI, I);
1794 return createConstantExpression(
1795 ConstantInt::getTrue(CI->getType()));
1796 }
1797
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001798 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1799 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001800 addPredicateUsers(PI, I);
1801 return createConstantExpression(
1802 ConstantInt::getFalse(CI->getType()));
1803 }
1804
1805 } else {
1806 // Just handle the ne and eq cases, where if we have the same
1807 // operands, we may know something.
1808 if (BranchPredicate == OurPredicate) {
1809 addPredicateUsers(PI, I);
1810 // Same predicate, same ops,we know it was false, so this is false.
1811 return createConstantExpression(
1812 ConstantInt::getFalse(CI->getType()));
1813 } else if (BranchPredicate ==
1814 CmpInst::getInversePredicate(OurPredicate)) {
1815 addPredicateUsers(PI, I);
1816 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001817 return createConstantExpression(
1818 ConstantInt::getTrue(CI->getType()));
1819 }
1820 }
1821 }
1822 }
1823 }
1824 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001825 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001826}
Davide Italiano7e274e02016-12-22 16:03:48 +00001827
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001828// Return true if V is a value that will always be available (IE can
1829// be placed anywhere) in the function. We don't do globals here
1830// because they are often worse to put in place.
1831// TODO: Separate cost from availability
1832static bool alwaysAvailable(Value *V) {
1833 return isa<Constant>(V) || isa<Argument>(V);
1834}
1835
Davide Italiano7e274e02016-12-22 16:03:48 +00001836// Substitute and symbolize the value before value numbering.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001837const Expression *
1838NewGVN::performSymbolicEvaluation(Value *V,
1839 SmallPtrSetImpl<Value *> &Visited) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001840 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001841 if (auto *C = dyn_cast<Constant>(V))
1842 E = createConstantExpression(C);
1843 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1844 E = createVariableExpression(V);
1845 } else {
1846 // TODO: memory intrinsics.
1847 // TODO: Some day, we should do the forward propagation and reassociation
1848 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001849 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001850 switch (I->getOpcode()) {
1851 case Instruction::ExtractValue:
1852 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001853 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001854 break;
1855 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001856 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001857 break;
1858 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001859 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001860 break;
1861 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001862 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001863 break;
1864 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001865 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001866 break;
1867 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001868 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001869 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001870 case Instruction::ICmp:
1871 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001872 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001873 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001874 case Instruction::Add:
1875 case Instruction::FAdd:
1876 case Instruction::Sub:
1877 case Instruction::FSub:
1878 case Instruction::Mul:
1879 case Instruction::FMul:
1880 case Instruction::UDiv:
1881 case Instruction::SDiv:
1882 case Instruction::FDiv:
1883 case Instruction::URem:
1884 case Instruction::SRem:
1885 case Instruction::FRem:
1886 case Instruction::Shl:
1887 case Instruction::LShr:
1888 case Instruction::AShr:
1889 case Instruction::And:
1890 case Instruction::Or:
1891 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001892 case Instruction::Trunc:
1893 case Instruction::ZExt:
1894 case Instruction::SExt:
1895 case Instruction::FPToUI:
1896 case Instruction::FPToSI:
1897 case Instruction::UIToFP:
1898 case Instruction::SIToFP:
1899 case Instruction::FPTrunc:
1900 case Instruction::FPExt:
1901 case Instruction::PtrToInt:
1902 case Instruction::IntToPtr:
1903 case Instruction::Select:
1904 case Instruction::ExtractElement:
1905 case Instruction::InsertElement:
1906 case Instruction::ShuffleVector:
1907 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001908 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001909 break;
1910 default:
1911 return nullptr;
1912 }
1913 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001914 return E;
1915}
1916
Daniel Berlin0207cca2017-05-21 23:41:56 +00001917// Look up a container in a map, and then call a function for each thing in the
1918// found container.
1919template <typename Map, typename KeyType, typename Func>
1920void NewGVN::for_each_found(Map &M, const KeyType &Key, Func F) {
1921 const auto Result = M.find_as(Key);
1922 if (Result != M.end())
1923 for (typename Map::mapped_type::value_type Mapped : Result->second)
1924 F(Mapped);
1925}
1926
1927// Look up a container of values/instructions in a map, and touch all the
1928// instructions in the container. Then erase value from the map.
1929template <typename Map, typename KeyType>
1930void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
1931 const auto Result = M.find_as(Key);
1932 if (Result != M.end()) {
1933 for (const typename Map::mapped_type::value_type Mapped : Result->second)
1934 TouchedInstructions.set(InstrToDFSNum(Mapped));
1935 M.erase(Result);
1936 }
1937}
1938
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001939void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00001940 if (isa<Instruction>(To))
1941 AdditionalUsers[To].insert(User);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001942}
1943
Davide Italiano7e274e02016-12-22 16:03:48 +00001944void NewGVN::markUsersTouched(Value *V) {
1945 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001946 for (auto *User : V->users()) {
1947 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001948 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001949 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00001950 touchAndErase(AdditionalUsers, V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001951}
1952
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001953void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001954 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1955 MemoryToUsers[To].insert(U);
1956}
1957
1958void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001959 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00001960}
1961
1962void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1963 if (isa<MemoryUse>(MA))
1964 return;
1965 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00001966 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin0207cca2017-05-21 23:41:56 +00001967 touchAndErase(MemoryToUsers, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001968}
1969
Daniel Berlinf7d95802017-02-18 23:06:50 +00001970// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001971void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001972 // Don't add temporary instructions to the user lists.
1973 if (AllTempInstructions.count(I))
1974 return;
1975
Daniel Berlinf7d95802017-02-18 23:06:50 +00001976 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1977 PredicateToUsers[PBranch->Condition].insert(I);
1978 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1979 PredicateToUsers[PAssume->Condition].insert(I);
1980}
1981
1982// Touch all the predicates that depend on this instruction.
1983void NewGVN::markPredicateUsersTouched(Instruction *I) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00001984 touchAndErase(PredicateToUsers, I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001985}
1986
Daniel Berlin1316a942017-04-06 18:52:50 +00001987// Mark users affected by a memory leader change.
1988void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001989 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00001990 markMemoryDefTouched(M);
1991}
1992
Daniel Berlin32f8d562017-01-07 16:55:14 +00001993// Touch the instructions that need to be updated after a congruence class has a
1994// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00001995void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001996 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001997 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00001998 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001999 LeaderChanges.insert(M);
2000 }
2001}
2002
Daniel Berlin1316a942017-04-06 18:52:50 +00002003// Give a range of things that have instruction DFS numbers, this will return
2004// the member of the range with the smallest dfs number.
2005template <class T, class Range>
2006T *NewGVN::getMinDFSOfRange(const Range &R) const {
2007 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
2008 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002009 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00002010 if (DFSNum < MinDFS.second)
2011 MinDFS = {X, DFSNum};
2012 }
2013 return MinDFS.first;
2014}
2015
2016// This function returns the MemoryAccess that should be the next leader of
2017// congruence class CC, under the assumption that the current leader is going to
2018// disappear.
2019const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2020 // TODO: If this ends up to slow, we can maintain a next memory leader like we
2021 // do for regular leaders.
2022 // Make sure there will be a leader to find
Davide Italianodc435322017-05-10 19:57:43 +00002023 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00002024 if (CC->getStoreCount() > 0) {
2025 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002026 return getMemoryAccess(NL);
Daniel Berlin1316a942017-04-06 18:52:50 +00002027 // Find the store with the minimum DFS number.
2028 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00002029 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002030 return getMemoryAccess(cast<StoreInst>(V));
Daniel Berlin1316a942017-04-06 18:52:50 +00002031 }
Daniel Berlina8236562017-04-07 18:38:09 +00002032 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00002033
2034 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00002035 // !OldClass->memory_empty()
2036 if (CC->memory_size() == 1)
2037 return *CC->memory_begin();
2038 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00002039}
2040
2041// This function returns the next value leader of a congruence class, under the
2042// assumption that the current leader is going away. This should end up being
2043// the next most dominating member.
2044Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2045 // We don't need to sort members if there is only 1, and we don't care about
2046 // sorting the TOP class because everything either gets out of it or is
2047 // unreachable.
2048
Daniel Berlina8236562017-04-07 18:38:09 +00002049 if (CC->size() == 1 || CC == TOPClass) {
2050 return *(CC->begin());
2051 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002052 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00002053 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00002054 } else {
2055 ++NumGVNSortedLeaderChanges;
2056 // NOTE: If this ends up to slow, we can maintain a dual structure for
2057 // member testing/insertion, or keep things mostly sorted, and sort only
2058 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00002059 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00002060 }
2061}
2062
2063// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2064// the memory members, etc for the move.
2065//
2066// The invariants of this function are:
2067//
2068// I must be moving to NewClass from OldClass The StoreCount of OldClass and
2069// NewClass is expected to have been updated for I already if it is is a store.
2070// The OldClass memory leader has not been updated yet if I was the leader.
2071void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2072 MemoryAccess *InstMA,
2073 CongruenceClass *OldClass,
2074 CongruenceClass *NewClass) {
2075 // If the leader is I, and we had a represenative MemoryAccess, it should
2076 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00002077 assert((!InstMA || !OldClass->getMemoryLeader() ||
2078 OldClass->getLeader() != I ||
2079 OldClass->getMemoryLeader() == InstMA) &&
2080 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00002081 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00002082 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002083 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00002084 assert(NewClass->size() == 1 ||
2085 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2086 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00002087 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00002088 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002089 << " due to new memory instruction becoming leader\n");
2090 markMemoryLeaderChangeTouched(NewClass);
2091 }
2092 setMemoryClass(InstMA, NewClass);
2093 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00002094 if (OldClass->getMemoryLeader() == InstMA) {
Davide Italianodc435322017-05-10 19:57:43 +00002095 if (!OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00002096 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2097 DEBUG(dbgs() << "Memory class leader change for class "
2098 << OldClass->getID() << " to "
2099 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00002100 << " due to removal of old leader " << *InstMA << "\n");
2101 markMemoryLeaderChangeTouched(OldClass);
2102 } else
Daniel Berlina8236562017-04-07 18:38:09 +00002103 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00002104 }
2105}
2106
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002107// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00002108// Update OldClass and NewClass for the move (including changing leaders, etc).
2109void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002110 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002111 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00002112 if (I == OldClass->getNextLeader().first)
2113 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002114
Daniel Berlinff152002017-05-19 19:01:24 +00002115 OldClass->erase(I);
2116 NewClass->insert(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002117
Daniel Berlina8236562017-04-07 18:38:09 +00002118 if (NewClass->getLeader() != I)
2119 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlin1316a942017-04-06 18:52:50 +00002120 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002121 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002122 OldClass->decStoreCount();
2123 // Okay, so when do we want to make a store a leader of a class?
2124 // If we have a store defined by an earlier load, we want the earlier load
2125 // to lead the class.
2126 // If we have a store defined by something else, we want the store to lead
2127 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00002128 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00002129 // as the leader
2130 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002131 // If it's a store expression we are using, it means we are not equivalent
2132 // to something earlier.
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002133 if (auto *SE = dyn_cast<StoreExpression>(E)) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002134 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1316a942017-04-06 18:52:50 +00002135 markValueLeaderChangeTouched(NewClass);
2136 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00002137 DEBUG(dbgs() << "Changing leader of congruence class "
2138 << NewClass->getID() << " from " << *NewClass->getLeader()
2139 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002140 // If we changed the leader, we have to mark it changed because we don't
2141 // know what it will do to symbolic evlauation.
Daniel Berlina8236562017-04-07 18:38:09 +00002142 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002143 }
2144 // We rely on the code below handling the MemoryAccess change.
2145 }
Daniel Berlina8236562017-04-07 18:38:09 +00002146 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002147 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002148 // True if there is no memory instructions left in a class that had memory
2149 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002150
Daniel Berlin1316a942017-04-06 18:52:50 +00002151 // If it's not a memory use, set the MemoryAccess equivalence
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002152 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
Daniel Berlin1316a942017-04-06 18:52:50 +00002153 if (InstMA)
2154 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002155 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002156 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002157 if (OldClass->empty() && OldClass != TOPClass) {
2158 if (OldClass->getDefiningExpr()) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002159 DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002160 << " from table\n");
Daniel Berlina8236562017-04-07 18:38:09 +00002161 ExpressionToClass.erase(OldClass->getDefiningExpr());
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002162 }
Daniel Berlina8236562017-04-07 18:38:09 +00002163 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002164 // When the leader changes, the value numbering of
2165 // everything may change due to symbolization changes, so we need to
2166 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00002167 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002168 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002169 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002170 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002171 // Note that this is basically clean up for the expression removal that
2172 // happens below. If we remove stores from a class, we may leave it as a
2173 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002174 if (OldClass->getStoreCount() == 0) {
2175 if (OldClass->getStoredValue())
2176 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002177 }
Daniel Berlina8236562017-04-07 18:38:09 +00002178 OldClass->setLeader(getNextValueLeader(OldClass));
2179 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002180 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002181 }
2182}
2183
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002184// For a given expression, mark the phi of ops instructions that could have
2185// changed as a result.
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002186void NewGVN::markPhiOfOpsChanged(const Expression *E) {
2187 touchAndErase(ExpressionToPhiOfOps, E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002188}
Daniel Berlin0207cca2017-05-21 23:41:56 +00002189
Davide Italiano7e274e02016-12-22 16:03:48 +00002190// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002191void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002192 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002193 // TOP.
Daniel Berline021d2d2017-05-19 20:22:20 +00002194
2195 CongruenceClass *IClass = ValueToClass.lookup(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002196 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002197 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002198 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002199
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002200 CongruenceClass *EClass = nullptr;
Daniel Berlin02c6b172017-01-02 18:00:53 +00002201 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002202 EClass = ValueToClass.lookup(VE->getVariableValue());
Daniel Berline021d2d2017-05-19 20:22:20 +00002203 } else if (isa<DeadExpression>(E)) {
2204 EClass = TOPClass;
2205 }
2206 if (!EClass) {
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002207 auto lookupResult = ExpressionToClass.insert({E, nullptr});
Davide Italiano7e274e02016-12-22 16:03:48 +00002208
2209 // If it's not in the value table, create a new congruence class.
2210 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002211 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002212 auto place = lookupResult.first;
2213 place->second = NewClass;
2214
2215 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002216 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002217 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002218 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2219 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002220 NewClass->setLeader(SI);
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002221 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002222 // The RepMemoryAccess field will be filled in properly by the
2223 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002224 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002225 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002226 }
2227 assert(!isa<VariableExpression>(E) &&
2228 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002229
2230 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002231 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002232 << " using expression " << *E << " at " << NewClass->getID()
2233 << " and leader " << *(NewClass->getLeader()));
2234 if (NewClass->getStoredValue())
2235 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002236 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002237 } else {
2238 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002239 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002240 assert((isa<Constant>(EClass->getLeader()) ||
2241 (EClass->getStoredValue() &&
2242 isa<Constant>(EClass->getStoredValue()))) &&
2243 "Any class with a constant expression should have a "
2244 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002245
Davide Italiano7e274e02016-12-22 16:03:48 +00002246 assert(EClass && "Somehow don't have an eclass");
2247
Daniel Berlin1316a942017-04-06 18:52:50 +00002248 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002249 }
2250 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002251 bool ClassChanged = IClass != EClass;
2252 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002253 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002254 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002255 << "\n");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002256 if (ClassChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002257 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002258 markPhiOfOpsChanged(E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002259 }
2260
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002261 markUsersTouched(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002262 if (MemoryAccess *MA = getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002263 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002264 if (auto *CI = dyn_cast<CmpInst>(I))
2265 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002266 }
Daniel Berlin45403572017-05-16 19:58:47 +00002267 // If we changed the class of the store, we want to ensure nothing finds the
2268 // old store expression. In particular, loads do not compare against stored
2269 // value, so they will find old store expressions (and associated class
2270 // mappings) if we leave them in the table.
Davide Italianoee49f492017-05-19 04:06:10 +00002271 if (ClassChanged && isa<StoreInst>(I)) {
Daniel Berlin45403572017-05-16 19:58:47 +00002272 auto *OldE = ValueToExpression.lookup(I);
2273 // It could just be that the old class died. We don't want to erase it if we
2274 // just moved classes.
Davide Italianoee49f492017-05-19 04:06:10 +00002275 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE)
Daniel Berlin45403572017-05-16 19:58:47 +00002276 ExpressionToClass.erase(OldE);
2277 }
2278 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002279}
2280
2281// Process the fact that Edge (from, to) is reachable, including marking
2282// any newly reachable blocks and instructions for processing.
2283void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2284 // Check if the Edge was reachable before.
2285 if (ReachableEdges.insert({From, To}).second) {
2286 // If this block wasn't reachable before, all instructions are touched.
2287 if (ReachableBlocks.insert(To).second) {
2288 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2289 const auto &InstRange = BlockInstRange.lookup(To);
2290 TouchedInstructions.set(InstRange.first, InstRange.second);
2291 } else {
2292 DEBUG(dbgs() << "Block " << getBlockName(To)
2293 << " was reachable, but new edge {" << getBlockName(From)
2294 << "," << getBlockName(To) << "} to it found\n");
2295
2296 // We've made an edge reachable to an existing block, which may
2297 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2298 // they are the only thing that depend on new edges. Anything using their
2299 // values will get propagated to if necessary.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002300 if (MemoryAccess *MemPhi = getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002301 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002302
Davide Italiano7e274e02016-12-22 16:03:48 +00002303 auto BI = To->begin();
2304 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002305 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002306 ++BI;
2307 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00002308 for_each_found(PHIOfOpsPHIs, To, [&](const PHINode *I) {
2309 TouchedInstructions.set(InstrToDFSNum(I));
2310 });
Davide Italiano7e274e02016-12-22 16:03:48 +00002311 }
2312 }
2313}
2314
2315// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2316// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002317Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002318 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002319 if (isa<Constant>(Result))
2320 return Result;
2321 return nullptr;
2322}
2323
2324// Process the outgoing edges of a block for reachability.
2325void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2326 // Evaluate reachability of terminator instruction.
2327 BranchInst *BR;
2328 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2329 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002330 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002331 if (!CondEvaluated) {
2332 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002333 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002334 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2335 CondEvaluated = CE->getConstantValue();
2336 }
2337 } else if (isa<ConstantInt>(Cond)) {
2338 CondEvaluated = Cond;
2339 }
2340 }
2341 ConstantInt *CI;
2342 BasicBlock *TrueSucc = BR->getSuccessor(0);
2343 BasicBlock *FalseSucc = BR->getSuccessor(1);
2344 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2345 if (CI->isOne()) {
2346 DEBUG(dbgs() << "Condition for Terminator " << *TI
2347 << " evaluated to true\n");
2348 updateReachableEdge(B, TrueSucc);
2349 } else if (CI->isZero()) {
2350 DEBUG(dbgs() << "Condition for Terminator " << *TI
2351 << " evaluated to false\n");
2352 updateReachableEdge(B, FalseSucc);
2353 }
2354 } else {
2355 updateReachableEdge(B, TrueSucc);
2356 updateReachableEdge(B, FalseSucc);
2357 }
2358 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2359 // For switches, propagate the case values into the case
2360 // destinations.
2361
2362 // Remember how many outgoing edges there are to every successor.
2363 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2364
Davide Italiano7e274e02016-12-22 16:03:48 +00002365 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002366 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002367 // See if we were able to turn this switch statement into a constant.
2368 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002369 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002370 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002371 auto Case = *SI->findCaseValue(CondVal);
2372 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002373 // We proved the value is outside of the range of the case.
2374 // We can't do anything other than mark the default dest as reachable,
2375 // and go home.
2376 updateReachableEdge(B, SI->getDefaultDest());
2377 return;
2378 }
2379 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002380 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002381 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002382 } else {
2383 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2384 BasicBlock *TargetBlock = SI->getSuccessor(i);
2385 ++SwitchEdges[TargetBlock];
2386 updateReachableEdge(B, TargetBlock);
2387 }
2388 }
2389 } else {
2390 // Otherwise this is either unconditional, or a type we have no
2391 // idea about. Just mark successors as reachable.
2392 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2393 BasicBlock *TargetBlock = TI->getSuccessor(i);
2394 updateReachableEdge(B, TargetBlock);
2395 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002396
2397 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002398 // equivalent only to itself.
2399 //
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002400 auto *MA = getMemoryAccess(TI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002401 if (MA && !isa<MemoryUse>(MA)) {
2402 auto *CC = ensureLeaderOfMemoryClass(MA);
2403 if (setMemoryClass(MA, CC))
2404 markMemoryUsersTouched(MA);
2405 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002406 }
2407}
2408
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002409void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2410 Instruction *ExistingValue) {
2411 InstrDFS[Op] = InstrToDFSNum(ExistingValue);
2412 AllTempInstructions.insert(Op);
2413 PHIOfOpsPHIs[BB].push_back(Op);
2414 TempToBlock[Op] = BB;
2415 if (ExistingValue)
2416 RealToTemp[ExistingValue] = Op;
2417}
2418
2419static bool okayForPHIOfOps(const Instruction *I) {
2420 return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
2421 isa<LoadInst>(I);
2422}
2423
2424// When we see an instruction that is an op of phis, generate the equivalent phi
2425// of ops form.
2426const Expression *
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002427NewGVN::makePossiblePhiOfOps(Instruction *I,
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002428 SmallPtrSetImpl<Value *> &Visited) {
2429 if (!okayForPHIOfOps(I))
2430 return nullptr;
2431
2432 if (!Visited.insert(I).second)
2433 return nullptr;
2434 // For now, we require the instruction be cycle free because we don't
2435 // *always* create a phi of ops for instructions that could be done as phi
2436 // of ops, we only do it if we think it is useful. If we did do it all the
2437 // time, we could remove the cycle free check.
2438 if (!isCycleFree(I))
2439 return nullptr;
2440
2441 unsigned IDFSNum = InstrToDFSNum(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002442 SmallPtrSet<const Value *, 8> ProcessedPHIs;
2443 // TODO: We don't do phi translation on memory accesses because it's
2444 // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2445 // which we don't have a good way of doing ATM.
2446 auto *MemAccess = getMemoryAccess(I);
2447 // If the memory operation is defined by a memory operation this block that
2448 // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2449 // can't help, as it would still be killed by that memory operation.
2450 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2451 MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2452 return nullptr;
2453
2454 // Convert op of phis to phi of ops
2455 for (auto &Op : I->operands()) {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002456 // TODO: We can't handle expressions that must be recursively translated
2457 // IE
2458 // a = phi (b, c)
2459 // f = use a
2460 // g = f + phi of something
2461 // To properly make a phi of ops for g, we'd have to properly translate and
2462 // use the instruction for f. We should add this by splitting out the
2463 // instruction creation we do below.
2464 if (isa<Instruction>(Op) && PHINodeUses.count(cast<Instruction>(Op)))
2465 return nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002466 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();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002484 if (MemAccess)
Daniel Berlinc8ed4042017-05-30 06:42:29 +00002485 TempToMemory.insert({ValueOp, MemAccess});
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002486
2487 for (auto &Op : ValueOp->operands()) {
2488 Op = Op->DoPHITranslation(PHIBlock, PredBB);
2489 // When this operand changes, it could change whether there is a
2490 // leader for us or not.
2491 addAdditionalUsers(Op, I);
2492 }
2493 // Make sure it's marked as a temporary instruction.
2494 AllTempInstructions.insert(ValueOp);
2495 // and make sure anything that tries to add it's DFS number is
2496 // redirected to the instruction we are making a phi of ops
2497 // for.
2498 InstrDFS.insert({ValueOp, IDFSNum});
2499 const Expression *E = performSymbolicEvaluation(ValueOp, Visited);
2500 InstrDFS.erase(ValueOp);
2501 AllTempInstructions.erase(ValueOp);
2502 ValueOp->deleteValue();
2503 if (MemAccess)
Daniel Berlinc8ed4042017-05-30 06:42:29 +00002504 TempToMemory.erase(ValueOp);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002505 if (!E)
2506 return nullptr;
2507 FoundVal = findPhiOfOpsLeader(E, PredBB);
2508 if (!FoundVal) {
2509 ExpressionToPhiOfOps[E].insert(I);
2510 return nullptr;
2511 }
2512 if (auto *SI = dyn_cast<StoreInst>(FoundVal))
2513 FoundVal = SI->getValueOperand();
2514 } else {
2515 DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2516 << getBlockName(PredBB)
2517 << " because the block is unreachable\n");
2518 FoundVal = UndefValue::get(I->getType());
2519 }
2520
2521 Ops.push_back({FoundVal, PredBB});
2522 DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2523 << getBlockName(PredBB) << "\n");
2524 }
2525 auto *ValuePHI = RealToTemp.lookup(I);
2526 bool NewPHI = false;
2527 if (!ValuePHI) {
2528 ValuePHI = PHINode::Create(I->getType(), OpPHI->getNumOperands());
2529 addPhiOfOps(ValuePHI, PHIBlock, I);
2530 NewPHI = true;
2531 NumGVNPHIOfOpsCreated++;
2532 }
2533 if (NewPHI) {
2534 for (auto PHIOp : Ops)
2535 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2536 } else {
2537 unsigned int i = 0;
2538 for (auto PHIOp : Ops) {
2539 ValuePHI->setIncomingValue(i, PHIOp.first);
2540 ValuePHI->setIncomingBlock(i, PHIOp.second);
2541 ++i;
2542 }
2543 }
2544
2545 DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2546 << "\n");
2547 return performSymbolicEvaluation(ValuePHI, Visited);
2548 }
2549 return nullptr;
2550}
2551
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002552// The algorithm initially places the values of the routine in the TOP
2553// congruence class. The leader of TOP is the undetermined value `undef`.
2554// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002555void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002556 NextCongruenceNum = 0;
2557
2558 // Note that even though we use the live on entry def as a representative
2559 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2560 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2561 // should be checking whether the MemoryAccess is top if we want to know if it
2562 // is equivalent to everything. Otherwise, what this really signifies is that
2563 // the access "it reaches all the way back to the beginning of the function"
2564
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002565 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002566 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002567 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002568 // The live on entry def gets put into it's own class
2569 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2570 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002571
Daniel Berlinec9deb72017-04-18 17:06:11 +00002572 for (auto DTN : nodes(DT)) {
2573 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002574 // All MemoryAccesses are equivalent to live on entry to start. They must
2575 // be initialized to something so that initial changes are noticed. For
2576 // the maximal answer, we initialize them all to be the same as
2577 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002578 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002579 if (MemoryBlockDefs)
2580 for (const auto &Def : *MemoryBlockDefs) {
2581 MemoryAccessToClass[&Def] = TOPClass;
2582 auto *MD = dyn_cast<MemoryDef>(&Def);
2583 // Insert the memory phis into the member list.
2584 if (!MD) {
2585 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002586 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002587 MemoryPhiState.insert({MP, MPS_TOP});
2588 }
2589
2590 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002591 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002592 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002593 for (auto &I : *BB) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002594 // TODO: Move to helper
2595 if (isa<PHINode>(&I))
2596 for (auto *U : I.users())
2597 if (auto *UInst = dyn_cast<Instruction>(U))
2598 if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
2599 PHINodeUses.insert(UInst);
Daniel Berlin22a4a012017-02-11 15:20:15 +00002600 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002601 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002602 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2603 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002604 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002605 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002606 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002607 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002608
2609 // Initialize arguments to be in their own unique congruence classes
2610 for (auto &FA : F.args())
2611 createSingletonCongruenceClass(&FA);
2612}
2613
2614void NewGVN::cleanupTables() {
2615 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002616 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2617 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002618 // Make sure we delete the congruence class (probably worth switching to
2619 // a unique_ptr at some point.
2620 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002621 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002622 }
2623
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002624 // Destroy the value expressions
2625 SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2626 AllTempInstructions.end());
2627 AllTempInstructions.clear();
2628
2629 // We have to drop all references for everything first, so there are no uses
2630 // left as we delete them.
2631 for (auto *I : TempInst) {
2632 I->dropAllReferences();
2633 }
2634
2635 while (!TempInst.empty()) {
2636 auto *I = TempInst.back();
2637 TempInst.pop_back();
2638 I->deleteValue();
2639 }
2640
Davide Italiano7e274e02016-12-22 16:03:48 +00002641 ValueToClass.clear();
2642 ArgRecycler.clear(ExpressionAllocator);
2643 ExpressionAllocator.Reset();
2644 CongruenceClasses.clear();
2645 ExpressionToClass.clear();
2646 ValueToExpression.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002647 RealToTemp.clear();
2648 AdditionalUsers.clear();
2649 ExpressionToPhiOfOps.clear();
2650 TempToBlock.clear();
2651 TempToMemory.clear();
2652 PHIOfOpsPHIs.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002653 ReachableBlocks.clear();
2654 ReachableEdges.clear();
2655#ifndef NDEBUG
2656 ProcessedCount.clear();
2657#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002658 InstrDFS.clear();
2659 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002660 DFSToInstr.clear();
2661 BlockInstRange.clear();
2662 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002663 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002664 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002665 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002666}
2667
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002668// Assign local DFS number mapping to instructions, and leave space for Value
2669// PHI's.
Davide Italiano7e274e02016-12-22 16:03:48 +00002670std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2671 unsigned Start) {
2672 unsigned End = Start;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002673 if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002674 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002675 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002676 }
2677
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002678 // Then the real block goes next.
Davide Italiano7e274e02016-12-22 16:03:48 +00002679 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002680 // There's no need to call isInstructionTriviallyDead more than once on
2681 // an instruction. Therefore, once we know that an instruction is dead
2682 // we change its DFS number so that it doesn't get value numbered.
2683 if (isInstructionTriviallyDead(&I, TLI)) {
2684 InstrDFS[&I] = 0;
2685 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2686 markInstructionForDeletion(&I);
2687 continue;
2688 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002689 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002690 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002691 }
2692
2693 // All of the range functions taken half-open ranges (open on the end side).
2694 // So we do not subtract one from count, because at this point it is one
2695 // greater than the last instruction.
2696 return std::make_pair(Start, End);
2697}
2698
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002699void NewGVN::updateProcessedCount(const Value *V) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002700#ifndef NDEBUG
2701 if (ProcessedCount.count(V) == 0) {
2702 ProcessedCount.insert({V, 1});
2703 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002704 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002705 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002706 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002707 }
2708#endif
2709}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002710// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2711void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2712 // If all the arguments are the same, the MemoryPhi has the same value as the
Daniel Berlind130b6c2017-05-21 23:41:58 +00002713 // argument. Filter out unreachable blocks and self phis from our operands.
2714 // TODO: We could do cycle-checking on the memory phis to allow valueizing for
2715 // self-phi checking.
Daniel Berlin41b39162017-03-18 15:41:36 +00002716 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002717 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlind130b6c2017-05-21 23:41:58 +00002718 return cast<MemoryAccess>(U) != MP &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002719 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002720 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002721 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002722 // If all that is left is nothing, our memoryphi is undef. We keep it as
2723 // InitialClass. Note: The only case this should happen is if we have at
2724 // least one self-argument.
2725 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002726 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002727 markMemoryUsersTouched(MP);
2728 return;
2729 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002730
2731 // Transform the remaining operands into operand leaders.
2732 // FIXME: mapped_iterator should have a range version.
2733 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002734 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002735 };
2736 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2737 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2738
2739 // and now check if all the elements are equal.
2740 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002741 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002742 ++MappedBegin;
2743 bool AllEqual = std::all_of(
2744 MappedBegin, MappedEnd,
2745 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2746
2747 if (AllEqual)
2748 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2749 else
2750 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002751 // If it's equal to something, it's in that class. Otherwise, it has to be in
2752 // a class where it is the leader (other things may be equivalent to it, but
2753 // it needs to start off in its own class, which means it must have been the
2754 // leader, and it can't have stopped being the leader because it was never
2755 // removed).
2756 CongruenceClass *CC =
2757 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2758 auto OldState = MemoryPhiState.lookup(MP);
2759 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2760 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2761 MemoryPhiState[MP] = NewState;
2762 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002763 markMemoryUsersTouched(MP);
2764}
2765
2766// Value number a single instruction, symbolically evaluating, performing
2767// congruence finding, and updating mappings.
2768void NewGVN::valueNumberInstruction(Instruction *I) {
2769 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002770 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002771 const Expression *Symbolized = nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002772 SmallPtrSet<Value *, 2> Visited;
Daniel Berlin283a6082017-03-01 19:59:26 +00002773 if (DebugCounter::shouldExecute(VNCounter)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002774 Symbolized = performSymbolicEvaluation(I, Visited);
2775 // Make a phi of ops if necessary
2776 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
2777 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002778 auto *PHIE = makePossiblePhiOfOps(I, Visited);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002779 if (PHIE)
2780 Symbolized = PHIE;
2781 }
2782
Daniel Berlin283a6082017-03-01 19:59:26 +00002783 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002784 // Mark the instruction as unused so we don't value number it again.
2785 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002786 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002787 // If we couldn't come up with a symbolic expression, use the unknown
2788 // expression
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002789 if (Symbolized == nullptr)
Daniel Berlin02c6b172017-01-02 18:00:53 +00002790 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002791 performCongruenceFinding(I, Symbolized);
2792 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002793 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002794 // don't currently understand. We don't place non-value producing
2795 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002796 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002797 auto *Symbolized = createUnknownExpression(I);
2798 performCongruenceFinding(I, Symbolized);
2799 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002800 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2801 }
2802}
Davide Italiano7e274e02016-12-22 16:03:48 +00002803
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002804// Check if there is a path, using single or equal argument phi nodes, from
2805// First to Second.
Davide Italianoeab0de22017-05-18 23:22:44 +00002806bool NewGVN::singleReachablePHIPath(
2807 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
2808 const MemoryAccess *Second) const {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002809 if (First == Second)
2810 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002811 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002812 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002813
Davide Italianoeab0de22017-05-18 23:22:44 +00002814 // This is not perfect, but as we're just verifying here, we can live with
2815 // the loss of precision. The real solution would be that of doing strongly
2816 // connected component finding in this routine, and it's probably not worth
2817 // the complexity for the time being. So, we just keep a set of visited
2818 // MemoryAccess and return true when we hit a cycle.
2819 if (Visited.count(First))
2820 return true;
2821 Visited.insert(First);
2822
Daniel Berlin871ecd92017-04-01 09:44:24 +00002823 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002824 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002825 if (ChainDef == Second)
2826 return true;
2827 if (MSSA->isLiveOnEntryDef(ChainDef))
2828 return false;
2829 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002830 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002831 auto *MP = cast<MemoryPhi>(EndDef);
2832 auto ReachableOperandPred = [&](const Use &U) {
2833 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2834 };
2835 auto FilteredPhiArgs =
2836 make_filter_range(MP->operands(), ReachableOperandPred);
2837 SmallVector<const Value *, 32> OperandList;
2838 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2839 std::back_inserter(OperandList));
2840 bool Okay = OperandList.size() == 1;
2841 if (!Okay)
2842 Okay =
2843 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2844 if (Okay)
Davide Italianoeab0de22017-05-18 23:22:44 +00002845 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2846 Second);
Daniel Berlin871ecd92017-04-01 09:44:24 +00002847 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002848}
2849
Daniel Berlin589cecc2017-01-02 18:00:46 +00002850// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002851// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002852// subject to very rare false negatives. It is only useful for
2853// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002854void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002855#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002856 // Verify that the memory table equivalence and memory member set match
2857 for (const auto *CC : CongruenceClasses) {
2858 if (CC == TOPClass || CC->isDead())
2859 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002860 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00002861 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002862 "Any class with a store as a leader should have a "
2863 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00002864 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002865 "Any congruence class with a store should have a "
2866 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00002867 }
2868
Daniel Berlina8236562017-04-07 18:38:09 +00002869 if (CC->getMemoryLeader())
2870 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00002871 "Representative MemoryAccess does not appear to be reverse "
2872 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00002873 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002874 assert(MemoryAccessToClass.lookup(M) == CC &&
2875 "Memory member does not appear to be reverse mapped properly");
2876 }
2877
2878 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002879 // congruence class.
2880
2881 // Filter out the unreachable and trivially dead entries, because they may
2882 // never have been updated if the instructions were not processed.
2883 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002884 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002885 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00002886 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2887 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00002888 return false;
2889 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2890 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Davide Italiano6e7a2122017-05-15 18:50:53 +00002891
2892 // We could have phi nodes which operands are all trivially dead,
2893 // so we don't process them.
2894 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
2895 for (auto &U : MemPHI->incoming_values()) {
2896 if (Instruction *I = dyn_cast<Instruction>(U.get())) {
2897 if (!isInstructionTriviallyDead(I))
2898 return true;
2899 }
2900 }
2901 return false;
2902 }
2903
Daniel Berlin589cecc2017-01-02 18:00:46 +00002904 return true;
2905 };
2906
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002907 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002908 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002909 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002910 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italianoeab0de22017-05-18 23:22:44 +00002911 if (FirstMUD && SecondMUD) {
2912 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
2913 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002914 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2915 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2916 "The instructions for these memory operations should have "
2917 "been in the same congruence class or reachable through"
2918 "a single argument phi");
Davide Italianoeab0de22017-05-18 23:22:44 +00002919 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002920 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002921 // We can only sanely verify that MemoryDefs in the operand list all have
2922 // the same class.
2923 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002924 return ReachableEdges.count(
2925 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002926 isa<MemoryDef>(U);
2927
2928 };
2929 // All arguments should in the same class, ignoring unreachable arguments
2930 auto FilteredPhiArgs =
2931 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2932 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2933 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2934 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2935 const MemoryDef *MD = cast<MemoryDef>(U);
2936 return ValueToClass.lookup(MD->getMemoryInst());
2937 });
2938 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2939 PhiOpClasses.begin()) &&
2940 "All MemoryPhi arguments should be in the same class");
2941 }
2942 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002943#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002944}
2945
Daniel Berlin06329a92017-03-18 15:41:40 +00002946// Verify that the sparse propagation we did actually found the maximal fixpoint
2947// We do this by storing the value to class mapping, touching all instructions,
2948// and redoing the iteration to see if anything changed.
2949void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002950#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002951 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002952 if (DebugCounter::isCounterSet(VNCounter))
2953 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2954
2955 // Note that we have to store the actual classes, as we may change existing
2956 // classes during iteration. This is because our memory iteration propagation
2957 // is not perfect, and so may waste a little work. But it should generate
2958 // exactly the same congruence classes we have now, with different IDs.
2959 std::map<const Value *, CongruenceClass> BeforeIteration;
2960
2961 for (auto &KV : ValueToClass) {
2962 if (auto *I = dyn_cast<Instruction>(KV.first))
2963 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002964 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002965 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002966 BeforeIteration.insert({KV.first, *KV.second});
2967 }
2968
2969 TouchedInstructions.set();
2970 TouchedInstructions.reset(0);
2971 iterateTouchedInstructions();
2972 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2973 EqualClasses;
2974 for (const auto &KV : ValueToClass) {
2975 if (auto *I = dyn_cast<Instruction>(KV.first))
2976 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002977 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00002978 continue;
2979 // We could sink these uses, but i think this adds a bit of clarity here as
2980 // to what we are comparing.
2981 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2982 auto *AfterCC = KV.second;
2983 // Note that the classes can't change at this point, so we memoize the set
2984 // that are equal.
2985 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00002986 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00002987 "Value number changed after main loop completed!");
2988 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002989 }
2990 }
2991#endif
2992}
2993
Daniel Berlin45403572017-05-16 19:58:47 +00002994// Verify that for each store expression in the expression to class mapping,
2995// only the latest appears, and multiple ones do not appear.
2996// Because loads do not use the stored value when doing equality with stores,
2997// if we don't erase the old store expressions from the table, a load can find
2998// a no-longer valid StoreExpression.
2999void NewGVN::verifyStoreExpressions() const {
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003000#ifndef NDEBUG
Daniel Berlin45403572017-05-16 19:58:47 +00003001 DenseSet<std::pair<const Value *, const Value *>> StoreExpressionSet;
3002 for (const auto &KV : ExpressionToClass) {
3003 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3004 // Make sure a version that will conflict with loads is not already there
3005 auto Res =
3006 StoreExpressionSet.insert({SE->getOperand(0), SE->getMemoryLeader()});
3007 assert(Res.second &&
3008 "Stored expression conflict exists in expression table");
3009 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3010 assert(ValueExpr && ValueExpr->equals(*SE) &&
3011 "StoreExpression in ExpressionToClass is not latest "
3012 "StoreExpression for value");
3013 }
3014 }
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003015#endif
Daniel Berlin45403572017-05-16 19:58:47 +00003016}
3017
Daniel Berlin06329a92017-03-18 15:41:40 +00003018// This is the main value numbering loop, it iterates over the initial touched
3019// instruction set, propagating value numbers, marking things touched, etc,
3020// until the set of touched instructions is completely empty.
3021void NewGVN::iterateTouchedInstructions() {
3022 unsigned int Iterations = 0;
3023 // Figure out where touchedinstructions starts
3024 int FirstInstr = TouchedInstructions.find_first();
3025 // Nothing set, nothing to iterate, just return.
3026 if (FirstInstr == -1)
3027 return;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003028 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00003029 while (TouchedInstructions.any()) {
3030 ++Iterations;
3031 // Walk through all the instructions in all the blocks in RPO.
3032 // TODO: As we hit a new block, we should push and pop equalities into a
3033 // table lookupOperandLeader can use, to catch things PredicateInfo
3034 // might miss, like edge-only equivalences.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003035 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
Daniel Berlin06329a92017-03-18 15:41:40 +00003036
3037 // This instruction was found to be dead. We don't bother looking
3038 // at it again.
3039 if (InstrNum == 0) {
3040 TouchedInstructions.reset(InstrNum);
3041 continue;
3042 }
3043
Daniel Berlin21279bd2017-04-06 18:52:58 +00003044 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003045 const BasicBlock *CurrBlock = getBlockForValue(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003046
3047 // If we hit a new block, do reachability processing.
3048 if (CurrBlock != LastBlock) {
3049 LastBlock = CurrBlock;
3050 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3051 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3052
3053 // If it's not reachable, erase any touched instructions and move on.
3054 if (!BlockReachable) {
3055 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3056 DEBUG(dbgs() << "Skipping instructions in block "
3057 << getBlockName(CurrBlock)
3058 << " because it is unreachable\n");
3059 continue;
3060 }
3061 updateProcessedCount(CurrBlock);
3062 }
3063
3064 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
3065 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
3066 valueNumberMemoryPhi(MP);
3067 } else if (auto *I = dyn_cast<Instruction>(V)) {
3068 valueNumberInstruction(I);
3069 } else {
3070 llvm_unreachable("Should have been a MemoryPhi or Instruction");
3071 }
3072 updateProcessedCount(V);
3073 // Reset after processing (because we may mark ourselves as touched when
3074 // we propagate equalities).
3075 TouchedInstructions.reset(InstrNum);
3076 }
3077 }
3078 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3079}
3080
Daniel Berlin85f91b02016-12-26 20:06:58 +00003081// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00003082bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00003083 if (DebugCounter::isCounterSet(VNCounter))
3084 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00003085 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00003086 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00003087 MSSAWalker = MSSA->getWalker();
Daniel Berline021d2d2017-05-19 20:22:20 +00003088 SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00003089
3090 // Count number of instructions for sizing of hash tables, and come
3091 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003092 unsigned ICount = 1;
3093 // Add an empty instruction to account for the fact that we start at 1
3094 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00003095 // Note: We want ideal RPO traversal of the blocks, which is not quite the
3096 // same as dominator tree order, particularly with regard whether backedges
3097 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00003098 // If we visit in the wrong order, we will end up performing N times as many
3099 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00003100 // The dominator tree does guarantee that, for a given dom tree node, it's
3101 // parent must occur before it in the RPO ordering. Thus, we only need to sort
3102 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00003103 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00003104 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00003105 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003106 auto *Node = DT->getNode(B);
3107 assert(Node && "RPO and Dominator tree should have same reachability");
3108 RPOOrdering[Node] = ++Counter;
3109 }
3110 // Sort dominator tree children arrays into RPO.
3111 for (auto &B : RPOT) {
3112 auto *Node = DT->getNode(B);
3113 if (Node->getChildren().size() > 1)
3114 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00003115 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003116 return RPOOrdering[A] < RPOOrdering[B];
3117 });
3118 }
3119
3120 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00003121 for (auto DTN : depth_first(DT->getRootNode())) {
3122 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00003123 const auto &BlockRange = assignDFSNumbers(B, ICount);
3124 BlockInstRange.insert({B, BlockRange});
3125 ICount += BlockRange.second - BlockRange.first;
3126 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003127 initializeCongruenceClasses(F);
Davide Italiano7e274e02016-12-22 16:03:48 +00003128
Daniel Berline0bd37e2016-12-29 22:15:12 +00003129 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003130 // Ensure we don't end up resizing the expressionToClass map, as
3131 // that can be quite expensive. At most, we have one expression per
3132 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003133 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003134
3135 // Initialize the touched instructions to include the entry block.
3136 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
3137 TouchedInstructions.set(InstRange.first, InstRange.second);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003138 DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3139 << " marked reachable\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003140 ReachableBlocks.insert(&F.getEntryBlock());
3141
Daniel Berlin06329a92017-03-18 15:41:40 +00003142 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00003143 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00003144 verifyIterationSettled(F);
Daniel Berlin45403572017-05-16 19:58:47 +00003145 verifyStoreExpressions();
Daniel Berlinf7d95802017-02-18 23:06:50 +00003146
Davide Italiano7e274e02016-12-22 16:03:48 +00003147 Changed |= eliminateInstructions(F);
3148
3149 // Delete all instructions marked for deletion.
3150 for (Instruction *ToErase : InstructionsToErase) {
3151 if (!ToErase->use_empty())
3152 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3153
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003154 if (ToErase->getParent())
3155 ToErase->eraseFromParent();
Davide Italiano7e274e02016-12-22 16:03:48 +00003156 }
3157
3158 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003159 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3160 return !ReachableBlocks.count(&BB);
3161 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003162
3163 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
3164 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00003165 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003166 deleteInstructionsInBlock(&BB);
3167 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003168 }
3169
3170 cleanupTables();
3171 return Changed;
3172}
3173
Davide Italiano7e274e02016-12-22 16:03:48 +00003174struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003175 int DFSIn = 0;
3176 int DFSOut = 0;
3177 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003178 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003179 // The bool in the Def tells us whether the Def is the stored value of a
3180 // store.
3181 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003182 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00003183 bool operator<(const ValueDFS &Other) const {
3184 // It's not enough that any given field be less than - we have sets
3185 // of fields that need to be evaluated together to give a proper ordering.
3186 // For example, if you have;
3187 // DFS (1, 3)
3188 // Val 0
3189 // DFS (1, 2)
3190 // Val 50
3191 // We want the second to be less than the first, but if we just go field
3192 // by field, we will get to Val 0 < Val 50 and say the first is less than
3193 // the second. We only want it to be less than if the DFS orders are equal.
3194 //
3195 // Each LLVM instruction only produces one value, and thus the lowest-level
3196 // differentiator that really matters for the stack (and what we use as as a
3197 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003198 // Everything else in the structure is instruction level, and only affects
3199 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00003200 //
3201 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3202 // the order of replacement of uses does not matter.
3203 // IE given,
3204 // a = 5
3205 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00003206 // When you hit b, you will have two valuedfs with the same dfsin, out, and
3207 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00003208 // The .val will be the same as well.
3209 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003210 // You will replace both, and it does not matter what order you replace them
3211 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3212 // operand 2).
3213 // Similarly for the case of same dfsin, dfsout, localnum, but different
3214 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00003215 // a = 5
3216 // b = 6
3217 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00003218 // in c, we will a valuedfs for a, and one for b,with everything the same
3219 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00003220 // It does not matter what order we replace these operands in.
3221 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003222 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3223 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00003224 Other.U);
3225 }
3226};
3227
Daniel Berlinc4796862017-01-27 02:37:11 +00003228// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003229// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00003230// reachable uses for each value is stored in UseCount, and instructions that
3231// seem
3232// dead (have no non-dead uses) are stored in ProbablyDead.
3233void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00003234 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00003235 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00003236 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00003237 for (auto D : Dense) {
3238 // First add the value.
3239 BasicBlock *BB = getBlockForValue(D);
3240 // Constants are handled prior to ever calling this function, so
3241 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00003242 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003243 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003244 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003245 VDDef.DFSIn = DomNode->getDFSNumIn();
3246 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003247 // If it's a store, use the leader of the value operand, if it's always
3248 // available, or the value operand. TODO: We could do dominance checks to
3249 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00003250 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00003251 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003252 if (alwaysAvailable(Leader)) {
3253 VDDef.Def.setPointer(Leader);
3254 } else {
3255 VDDef.Def.setPointer(SI->getValueOperand());
3256 VDDef.Def.setInt(true);
3257 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003258 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003259 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00003260 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003261 assert(isa<Instruction>(D) &&
3262 "The dense set member should always be an instruction");
Daniel Berline3e69e12017-03-10 00:32:33 +00003263 Instruction *Def = cast<Instruction>(D);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003264 VDDef.LocalNum = InstrToDFSNum(D);
3265 DFSOrderedSet.push_back(VDDef);
3266 // If there is a phi node equivalent, add it
3267 if (auto *PN = RealToTemp.lookup(Def)) {
3268 auto *PHIE =
3269 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3270 if (PHIE) {
3271 VDDef.Def.setInt(false);
3272 VDDef.Def.setPointer(PN);
3273 VDDef.LocalNum = 0;
3274 DFSOrderedSet.push_back(VDDef);
3275 }
3276 }
3277
Daniel Berline3e69e12017-03-10 00:32:33 +00003278 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003279 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00003280 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003281 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003282 // Don't try to replace into dead uses
3283 if (InstructionsToErase.count(I))
3284 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003285 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00003286 // Put the phi node uses in the incoming block.
3287 BasicBlock *IBlock;
3288 if (auto *P = dyn_cast<PHINode>(I)) {
3289 IBlock = P->getIncomingBlock(U);
3290 // Make phi node users appear last in the incoming block
3291 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003292 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00003293 } else {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003294 IBlock = getBlockForValue(I);
Daniel Berlin21279bd2017-04-06 18:52:58 +00003295 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003296 }
Davide Italianoccbbc832017-01-26 00:42:42 +00003297
3298 // Skip uses in unreachable blocks, as we're going
3299 // to delete them.
3300 if (ReachableBlocks.count(IBlock) == 0)
3301 continue;
3302
Daniel Berlinb66164c2017-01-14 00:24:23 +00003303 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003304 VDUse.DFSIn = DomNode->getDFSNumIn();
3305 VDUse.DFSOut = DomNode->getDFSNumOut();
3306 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00003307 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003308 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00003309 }
3310 }
Daniel Berline3e69e12017-03-10 00:32:33 +00003311
3312 // If there are no uses, it's probably dead (but it may have side-effects,
3313 // so not definitely dead. Otherwise, store the number of uses so we can
3314 // track if it becomes dead later).
3315 if (UseCount == 0)
3316 ProbablyDead.insert(Def);
3317 else
3318 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003319 }
3320}
3321
Daniel Berlinc4796862017-01-27 02:37:11 +00003322// This function converts the set of members for a congruence class from values,
3323// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00003324void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00003325 const CongruenceClass &Dense,
3326 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00003327 for (auto D : Dense) {
3328 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
3329 continue;
3330
3331 BasicBlock *BB = getBlockForValue(D);
3332 ValueDFS VD;
3333 DomTreeNode *DomNode = DT->getNode(BB);
3334 VD.DFSIn = DomNode->getDFSNumIn();
3335 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003336 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00003337
3338 // If it's an instruction, use the real local dfs number.
3339 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00003340 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00003341 else
3342 llvm_unreachable("Should have been an instruction");
3343
3344 LoadsAndStores.emplace_back(VD);
3345 }
3346}
3347
Davide Italiano7e274e02016-12-22 16:03:48 +00003348static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00003349 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00003350 if (!ReplInst)
3351 return;
3352
Davide Italiano7e274e02016-12-22 16:03:48 +00003353 // Patch the replacement so that it is not more restrictive than the value
3354 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00003355 // Note that if 'I' is a load being replaced by some operation,
3356 // for example, by an arithmetic operation, then andIRFlags()
3357 // would just erase all math flags from the original arithmetic
3358 // operation, which is clearly not wanted and not needed.
3359 if (!isa<LoadInst>(I))
3360 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003361
Daniel Berlin86eab152017-02-12 22:25:20 +00003362 // FIXME: If both the original and replacement value are part of the
3363 // same control-flow region (meaning that the execution of one
3364 // guarantees the execution of the other), then we can combine the
3365 // noalias scopes here and do better than the general conservative
3366 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00003367
Daniel Berlin86eab152017-02-12 22:25:20 +00003368 // In general, GVN unifies expressions over different control-flow
3369 // regions, and so we need a conservative combination of the noalias
3370 // scopes.
3371 static const unsigned KnownIDs[] = {
3372 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3373 LLVMContext::MD_noalias, LLVMContext::MD_range,
3374 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
3375 LLVMContext::MD_invariant_group};
3376 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00003377}
3378
3379static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3380 patchReplacementInstruction(I, Repl);
3381 I->replaceAllUsesWith(Repl);
3382}
3383
3384void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3385 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
3386 ++NumGVNBlocksDeleted;
3387
Daniel Berline19f0e02017-01-30 17:06:55 +00003388 // Delete the instructions backwards, as it has a reduced likelihood of having
3389 // to update as many def-use and use-def chains. Start after the terminator.
3390 auto StartPoint = BB->rbegin();
3391 ++StartPoint;
3392 // Note that we explicitly recalculate BB->rend() on each iteration,
3393 // as it may change when we remove the first instruction.
3394 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3395 Instruction &Inst = *I++;
3396 if (!Inst.use_empty())
3397 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3398 if (isa<LandingPadInst>(Inst))
3399 continue;
3400
3401 Inst.eraseFromParent();
3402 ++NumGVNInstrDeleted;
3403 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003404 // Now insert something that simplifycfg will turn into an unreachable.
3405 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3406 new StoreInst(UndefValue::get(Int8Ty),
3407 Constant::getNullValue(Int8Ty->getPointerTo()),
3408 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003409}
3410
3411void NewGVN::markInstructionForDeletion(Instruction *I) {
3412 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3413 InstructionsToErase.insert(I);
3414}
3415
3416void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3417
3418 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3419 patchAndReplaceAllUsesWith(I, V);
3420 // We save the actual erasing to avoid invalidating memory
3421 // dependencies until we are done with everything.
3422 markInstructionForDeletion(I);
3423}
3424
3425namespace {
3426
3427// This is a stack that contains both the value and dfs info of where
3428// that value is valid.
3429class ValueDFSStack {
3430public:
3431 Value *back() const { return ValueStack.back(); }
3432 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3433
3434 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003435 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003436 DFSStack.emplace_back(DFSIn, DFSOut);
3437 }
3438 bool empty() const { return DFSStack.empty(); }
3439 bool isInScope(int DFSIn, int DFSOut) const {
3440 if (empty())
3441 return false;
3442 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3443 }
3444
3445 void popUntilDFSScope(int DFSIn, int DFSOut) {
3446
3447 // These two should always be in sync at this point.
3448 assert(ValueStack.size() == DFSStack.size() &&
3449 "Mismatch between ValueStack and DFSStack");
3450 while (
3451 !DFSStack.empty() &&
3452 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3453 DFSStack.pop_back();
3454 ValueStack.pop_back();
3455 }
3456 }
3457
3458private:
3459 SmallVector<Value *, 8> ValueStack;
3460 SmallVector<std::pair<int, int>, 8> DFSStack;
3461};
3462}
Daniel Berlin04443432017-01-07 03:23:47 +00003463
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003464// Given a value and a basic block we are trying to see if it is available in,
3465// see if the value has a leader available in that block.
3466Value *NewGVN::findPhiOfOpsLeader(const Expression *E,
3467 const BasicBlock *BB) const {
3468 // It would already be constant if we could make it constant
3469 if (auto *CE = dyn_cast<ConstantExpression>(E))
3470 return CE->getConstantValue();
3471 if (auto *VE = dyn_cast<VariableExpression>(E))
3472 return VE->getVariableValue();
3473
3474 auto *CC = ExpressionToClass.lookup(E);
3475 if (!CC)
3476 return nullptr;
3477 if (alwaysAvailable(CC->getLeader()))
3478 return CC->getLeader();
3479
3480 for (auto Member : *CC) {
3481 auto *MemberInst = dyn_cast<Instruction>(Member);
3482 // Anything that isn't an instruction is always available.
3483 if (!MemberInst)
3484 return Member;
3485 // If we are looking for something in the same block as the member, it must
3486 // be a leader because this function is looking for operands for a phi node.
3487 if (MemberInst->getParent() == BB ||
3488 DT->dominates(MemberInst->getParent(), BB)) {
3489 return Member;
3490 }
3491 }
3492 return nullptr;
3493}
3494
Davide Italiano7e274e02016-12-22 16:03:48 +00003495bool NewGVN::eliminateInstructions(Function &F) {
3496 // This is a non-standard eliminator. The normal way to eliminate is
3497 // to walk the dominator tree in order, keeping track of available
3498 // values, and eliminating them. However, this is mildly
3499 // pointless. It requires doing lookups on every instruction,
3500 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003501 // instructions part of most singleton congruence classes, we know we
3502 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003503
3504 // Instead, this eliminator looks at the congruence classes directly, sorts
3505 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003506 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003507 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003508 // last member. This is worst case O(E log E) where E = number of
3509 // instructions in a single congruence class. In theory, this is all
3510 // instructions. In practice, it is much faster, as most instructions are
3511 // either in singleton congruence classes or can't possibly be eliminated
3512 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003513 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003514 // for elimination purposes.
3515 // TODO: If we wanted to be faster, We could remove any members with no
3516 // overlapping ranges while sorting, as we will never eliminate anything
3517 // with those members, as they don't dominate anything else in our set.
3518
Davide Italiano7e274e02016-12-22 16:03:48 +00003519 bool AnythingReplaced = false;
3520
3521 // Since we are going to walk the domtree anyway, and we can't guarantee the
3522 // DFS numbers are updated, we compute some ourselves.
3523 DT->updateDFSNumbers();
3524
Daniel Berlin0207cca2017-05-21 23:41:56 +00003525 // Go through all of our phi nodes, and kill the arguments associated with
3526 // unreachable edges.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003527 auto ReplaceUnreachablePHIArgs = [&](PHINode &PHI, BasicBlock *BB) {
3528 for (auto &Operand : PHI.incoming_values())
3529 if (!ReachableEdges.count({PHI.getIncomingBlock(Operand), BB})) {
3530 DEBUG(dbgs() << "Replacing incoming value of " << PHI << " for block "
3531 << getBlockName(PHI.getIncomingBlock(Operand))
3532 << " with undef due to it being unreachable\n");
3533 Operand.set(UndefValue::get(PHI.getType()));
3534 }
3535 };
3536 SmallPtrSet<BasicBlock *, 8> BlocksWithPhis;
3537 for (auto &B : F)
3538 if ((!B.empty() && isa<PHINode>(*B.begin())) ||
3539 (PHIOfOpsPHIs.find(&B) != PHIOfOpsPHIs.end()))
3540 BlocksWithPhis.insert(&B);
3541 DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
3542 for (auto KV : ReachableEdges)
3543 ReachablePredCount[KV.getEnd()]++;
3544 for (auto *BB : BlocksWithPhis)
3545 // TODO: It would be faster to use getNumIncomingBlocks() on a phi node in
3546 // the block and subtract the pred count, but it's more complicated.
3547 if (ReachablePredCount.lookup(BB) !=
3548 std::distance(pred_begin(BB), pred_end(BB))) {
3549 for (auto II = BB->begin(); isa<PHINode>(II); ++II) {
3550 auto &PHI = cast<PHINode>(*II);
3551 ReplaceUnreachablePHIArgs(PHI, BB);
3552 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00003553 for_each_found(PHIOfOpsPHIs, BB, [&](PHINode *PHI) {
3554 ReplaceUnreachablePHIArgs(*PHI, BB);
3555 });
Davide Italiano7e274e02016-12-22 16:03:48 +00003556 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003557
Daniel Berline3e69e12017-03-10 00:32:33 +00003558 // Map to store the use counts
3559 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003560 for (auto *CC : reverse(CongruenceClasses)) {
Daniel Berline67c3222017-05-25 15:44:20 +00003561 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID() << "\n");
Daniel Berlinc4796862017-01-27 02:37:11 +00003562 // Track the equivalent store info so we can decide whether to try
3563 // dead store elimination.
3564 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003565 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003566 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003567 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003568 // Everything still in the TOP class is unreachable or dead.
3569 if (CC == TOPClass) {
Daniel Berline021d2d2017-05-19 20:22:20 +00003570 for (auto M : *CC) {
3571 auto *VTE = ValueToExpression.lookup(M);
3572 if (VTE && isa<DeadExpression>(VTE))
3573 markInstructionForDeletion(cast<Instruction>(M));
Daniel Berlinb79f5362017-02-11 12:48:50 +00003574 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3575 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003576 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003577 "point");
Daniel Berline021d2d2017-05-19 20:22:20 +00003578 }
Daniel Berlinb79f5362017-02-11 12:48:50 +00003579 continue;
3580 }
3581
Daniel Berlina8236562017-04-07 18:38:09 +00003582 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003583 // If this is a leader that is always available, and it's a
3584 // constant or has no equivalences, just replace everything with
3585 // it. We then update the congruence class with whatever members
3586 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003587 Value *Leader =
3588 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003589 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003590 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003591 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003592 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003593 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003594 if (Member == Leader || !isa<Instruction>(Member) ||
3595 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003596 MembersLeft.insert(Member);
3597 continue;
3598 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003599 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3600 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003601 auto *I = cast<Instruction>(Member);
3602 assert(Leader != I && "About to accidentally remove our leader");
3603 replaceInstruction(I, Leader);
3604 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003605 }
Daniel Berlina8236562017-04-07 18:38:09 +00003606 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003607 } else {
Davide Italiano7e274e02016-12-22 16:03:48 +00003608 // If this is a singleton, we can skip it.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003609 if (CC->size() != 1 || RealToTemp.lookup(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003610 // This is a stack because equality replacement/etc may place
3611 // constants in the middle of the member list, and we want to use
3612 // those constant values in preference to the current leader, over
3613 // the scope of those constants.
3614 ValueDFSStack EliminationStack;
3615
3616 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003617 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003618 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003619
3620 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003621 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003622 for (auto &VD : DFSOrderedSet) {
3623 int MemberDFSIn = VD.DFSIn;
3624 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003625 Value *Def = VD.Def.getPointer();
3626 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003627 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003628 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003629 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003630 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003631 auto *DefInst = dyn_cast_or_null<Instruction>(Def);
3632 if (DefInst && AllTempInstructions.count(DefInst)) {
3633 auto *PN = cast<PHINode>(DefInst);
3634
3635 // If this is a value phi and that's the expression we used, insert
3636 // it into the program
3637 // remove from temp instruction list.
3638 AllTempInstructions.erase(PN);
3639 auto *DefBlock = getBlockForValue(Def);
3640 DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3641 << " into block "
3642 << getBlockName(getBlockForValue(Def)) << "\n");
3643 PN->insertBefore(&DefBlock->front());
3644 Def = PN;
3645 NumGVNPHIOfOpsEliminations++;
3646 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003647
3648 if (EliminationStack.empty()) {
3649 DEBUG(dbgs() << "Elimination Stack is empty\n");
3650 } else {
3651 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3652 << EliminationStack.dfs_back().first << ","
3653 << EliminationStack.dfs_back().second << ")\n");
3654 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003655
3656 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3657 << MemberDFSOut << ")\n");
3658 // First, we see if we are out of scope or empty. If so,
3659 // and there equivalences, we try to replace the top of
3660 // stack with equivalences (if it's on the stack, it must
3661 // not have been eliminated yet).
3662 // Then we synchronize to our current scope, by
3663 // popping until we are back within a DFS scope that
3664 // dominates the current member.
3665 // Then, what happens depends on a few factors
3666 // If the stack is now empty, we need to push
3667 // If we have a constant or a local equivalence we want to
3668 // start using, we also push.
3669 // Otherwise, we walk along, processing members who are
3670 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003671 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003672 bool OutOfScope =
3673 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3674
3675 if (OutOfScope || ShouldPush) {
3676 // Sync to our current scope.
3677 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003678 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003679 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003680 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003681 }
3682 }
3683
Daniel Berline3e69e12017-03-10 00:32:33 +00003684 // Skip the Def's, we only want to eliminate on their uses. But mark
3685 // dominated defs as dead.
3686 if (Def) {
3687 // For anything in this case, what and how we value number
3688 // guarantees that any side-effets that would have occurred (ie
3689 // throwing, etc) can be proven to either still occur (because it's
3690 // dominated by something that has the same side-effects), or never
3691 // occur. Otherwise, we would not have been able to prove it value
3692 // equivalent to something else. For these things, we can just mark
3693 // it all dead. Note that this is different from the "ProbablyDead"
3694 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003695 // easy to prove dead if they are also side-effect free. Note that
3696 // because stores are put in terms of the stored value, we skip
3697 // stored values here. If the stored value is really dead, it will
3698 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003699 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003700 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003701 markInstructionForDeletion(cast<Instruction>(Def));
3702 continue;
3703 }
3704 // At this point, we know it is a Use we are trying to possibly
3705 // replace.
3706
3707 assert(isa<Instruction>(U->get()) &&
3708 "Current def should have been an instruction");
3709 assert(isa<Instruction>(U->getUser()) &&
3710 "Current user should have been an instruction");
3711
3712 // If the thing we are replacing into is already marked to be dead,
3713 // this use is dead. Note that this is true regardless of whether
3714 // we have anything dominating the use or not. We do this here
3715 // because we are already walking all the uses anyway.
3716 Instruction *InstUse = cast<Instruction>(U->getUser());
3717 if (InstructionsToErase.count(InstUse)) {
3718 auto &UseCount = UseCounts[U->get()];
3719 if (--UseCount == 0) {
3720 ProbablyDead.insert(cast<Instruction>(U->get()));
3721 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003722 }
3723
Davide Italiano7e274e02016-12-22 16:03:48 +00003724 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003725 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003726 if (EliminationStack.empty())
3727 continue;
3728
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003729 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003730
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003731 auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
3732 if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3733 DominatingLeader = II->getOperand(0);
3734
Daniel Berlind92e7f92017-01-07 00:01:42 +00003735 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003736 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003737 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003738 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003739 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003740
3741 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003742 // metadata. Skip this if we are replacing predicateinfo with its
3743 // original operand, as we already know we can just drop it.
3744 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003745 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3746 if (!PI || DominatingLeader != PI->OriginalOp)
3747 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003748 U->set(DominatingLeader);
3749 // This is now a use of the dominating leader, which means if the
3750 // dominating leader was dead, it's now live!
3751 auto &LeaderUseCount = UseCounts[DominatingLeader];
3752 // It's about to be alive again.
3753 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3754 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003755 if (LeaderUseCount == 0 && II)
3756 ProbablyDead.insert(II);
Daniel Berline3e69e12017-03-10 00:32:33 +00003757 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003758 AnythingReplaced = true;
3759 }
3760 }
3761 }
3762
Daniel Berline3e69e12017-03-10 00:32:33 +00003763 // At this point, anything still in the ProbablyDead set is actually dead if
3764 // would be trivially dead.
3765 for (auto *I : ProbablyDead)
3766 if (wouldInstructionBeTriviallyDead(I))
3767 markInstructionForDeletion(I);
3768
Davide Italiano7e274e02016-12-22 16:03:48 +00003769 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003770 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003771 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003772 if (!isa<Instruction>(Member) ||
3773 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003774 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003775 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003776
3777 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003778 if (CC->getStoreCount() > 0) {
3779 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003780 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3781 ValueDFSStack EliminationStack;
3782 for (auto &VD : PossibleDeadStores) {
3783 int MemberDFSIn = VD.DFSIn;
3784 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003785 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003786 if (EliminationStack.empty() ||
3787 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3788 // Sync to our current scope.
3789 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3790 if (EliminationStack.empty()) {
3791 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3792 continue;
3793 }
3794 }
3795 // We already did load elimination, so nothing to do here.
3796 if (isa<LoadInst>(Member))
3797 continue;
3798 assert(!EliminationStack.empty());
3799 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003800 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003801 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3802 // Member is dominater by Leader, and thus dead
3803 DEBUG(dbgs() << "Marking dead store " << *Member
3804 << " that is dominated by " << *Leader << "\n");
3805 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003806 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003807 ++NumGVNDeadStores;
3808 }
3809 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003810 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003811 return AnythingReplaced;
3812}
Daniel Berlin1c087672017-02-11 15:07:01 +00003813
3814// This function provides global ranking of operations so that we can place them
3815// in a canonical order. Note that rank alone is not necessarily enough for a
3816// complete ordering, as constants all have the same rank. However, generally,
3817// we will simplify an operation with all constants so that it doesn't matter
3818// what order they appear in.
3819unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003820 // Prefer constants to undef to anything else
3821 // Undef is a constant, have to check it first.
3822 // Prefer smaller constants to constantexprs
3823 if (isa<ConstantExpr>(V))
3824 return 2;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003825 if (isa<UndefValue>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003826 return 1;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003827 if (isa<Constant>(V))
3828 return 0;
Daniel Berlin1c087672017-02-11 15:07:01 +00003829 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003830 return 3 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003831
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003832 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003833 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003834 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00003835 if (Result > 0)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003836 return 4 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003837 // Unreachable or something else, just return a really large number.
3838 return ~0;
3839}
3840
3841// This is a function that says whether two commutative operations should
3842// have their order swapped when canonicalizing.
3843bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3844 // Because we only care about a total ordering, and don't rewrite expressions
3845 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003846 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003847 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003848}
Daniel Berlin64e68992017-03-12 04:46:45 +00003849
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00003850namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +00003851class NewGVNLegacyPass : public FunctionPass {
3852public:
3853 static char ID; // Pass identification, replacement for typeid.
3854 NewGVNLegacyPass() : FunctionPass(ID) {
3855 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3856 }
3857 bool runOnFunction(Function &F) override;
3858
3859private:
3860 void getAnalysisUsage(AnalysisUsage &AU) const override {
3861 AU.addRequired<AssumptionCacheTracker>();
3862 AU.addRequired<DominatorTreeWrapperPass>();
3863 AU.addRequired<TargetLibraryInfoWrapperPass>();
3864 AU.addRequired<MemorySSAWrapperPass>();
3865 AU.addRequired<AAResultsWrapperPass>();
3866 AU.addPreserved<DominatorTreeWrapperPass>();
3867 AU.addPreserved<GlobalsAAWrapperPass>();
3868 }
3869};
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00003870} // namespace
Daniel Berlin64e68992017-03-12 04:46:45 +00003871
3872bool NewGVNLegacyPass::runOnFunction(Function &F) {
3873 if (skipFunction(F))
3874 return false;
3875 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3876 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3877 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3878 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3879 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3880 F.getParent()->getDataLayout())
3881 .runGVN();
3882}
3883
3884INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3885 false, false)
3886INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3887INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3888INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3889INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3890INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3891INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3892INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3893 false)
3894
3895char NewGVNLegacyPass::ID = 0;
3896
3897// createGVNPass - The public interface to this file.
3898FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3899
3900PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3901 // Apparently the order in which we get these results matter for
3902 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3903 // the same order here, just in case.
3904 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3905 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3906 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3907 auto &AA = AM.getResult<AAManager>(F);
3908 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3909 bool Changed =
3910 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3911 .runGVN();
3912 if (!Changed)
3913 return PreservedAnalyses::all();
3914 PreservedAnalyses PA;
3915 PA.preserve<DominatorTreeAnalysis>();
3916 PA.preserve<GlobalsAA>();
3917 return PA;
3918}