blob: 3c9850b156ac13fe1d5d926b475c98b80079011b [file] [log] [blame]
Davide Italiano7e274e02016-12-22 16:03:48 +00001//===---- NewGVN.cpp - Global Value Numbering Pass --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file implements the new LLVM's Global Value Numbering pass.
11/// GVN partitions values computed by a function into congruence classes.
12/// Values ending up in the same congruence class are guaranteed to be the same
13/// for every execution of the program. In that respect, congruency is a
14/// compile-time approximation of equivalence of values at runtime.
15/// The algorithm implemented here uses a sparse formulation and it's based
16/// on the ideas described in the paper:
17/// "A Sparse Algorithm for Predicated Global Value Numbering" from
18/// Karthik Gargi.
19///
Daniel Berlindb3c7be2017-01-26 21:39:49 +000020/// A brief overview of the algorithm: The algorithm is essentially the same as
21/// the standard RPO value numbering algorithm (a good reference is the paper
22/// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
23/// The RPO algorithm proceeds, on every iteration, to process every reachable
24/// block and every instruction in that block. This is because the standard RPO
25/// algorithm does not track what things have the same value number, it only
26/// tracks what the value number of a given operation is (the mapping is
27/// operation -> value number). Thus, when a value number of an operation
28/// changes, it must reprocess everything to ensure all uses of a value number
29/// get updated properly. In constrast, the sparse algorithm we use *also*
30/// tracks what operations have a given value number (IE it also tracks the
31/// reverse mapping from value number -> operations with that value number), so
32/// that it only needs to reprocess the instructions that are affected when
33/// something's value number changes. The rest of the algorithm is devoted to
34/// performing symbolic evaluation, forward propagation, and simplification of
35/// operations based on the value numbers deduced so far.
36///
37/// We also do not perform elimination by using any published algorithm. All
38/// published algorithms are O(Instructions). Instead, we use a technique that
39/// is O(number of operations with the same value number), enabling us to skip
40/// trying to eliminate things that have unique value numbers.
Davide Italiano7e274e02016-12-22 16:03:48 +000041//===----------------------------------------------------------------------===//
42
43#include "llvm/Transforms/Scalar/NewGVN.h"
44#include "llvm/ADT/BitVector.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/DenseSet.h"
47#include "llvm/ADT/DepthFirstIterator.h"
48#include "llvm/ADT/Hashing.h"
49#include "llvm/ADT/MapVector.h"
50#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000051#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000052#include "llvm/ADT/SmallPtrSet.h"
53#include "llvm/ADT/SmallSet.h"
54#include "llvm/ADT/SparseBitVector.h"
55#include "llvm/ADT/Statistic.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include "llvm/Analysis/AliasAnalysis.h"
58#include "llvm/Analysis/AssumptionCache.h"
59#include "llvm/Analysis/CFG.h"
60#include "llvm/Analysis/CFGPrinter.h"
61#include "llvm/Analysis/ConstantFolding.h"
62#include "llvm/Analysis/GlobalsModRef.h"
63#include "llvm/Analysis/InstructionSimplify.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000064#include "llvm/Analysis/MemoryBuiltins.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000065#include "llvm/Analysis/MemoryLocation.h"
Daniel Berlin2f72b192017-04-14 02:53:37 +000066#include "llvm/Analysis/MemorySSA.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000067#include "llvm/Analysis/TargetLibraryInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000068#include "llvm/IR/DataLayout.h"
69#include "llvm/IR/Dominators.h"
70#include "llvm/IR/GlobalVariable.h"
71#include "llvm/IR/IRBuilder.h"
72#include "llvm/IR/IntrinsicInst.h"
73#include "llvm/IR/LLVMContext.h"
74#include "llvm/IR/Metadata.h"
75#include "llvm/IR/PatternMatch.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000076#include "llvm/IR/Type.h"
77#include "llvm/Support/Allocator.h"
78#include "llvm/Support/CommandLine.h"
79#include "llvm/Support/Debug.h"
Daniel Berlin283a6082017-03-01 19:59:26 +000080#include "llvm/Support/DebugCounter.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000081#include "llvm/Transforms/Scalar.h"
82#include "llvm/Transforms/Scalar/GVNExpression.h"
83#include "llvm/Transforms/Utils/BasicBlockUtils.h"
84#include "llvm/Transforms/Utils/Local.h"
Daniel Berlinf7d95802017-02-18 23:06:50 +000085#include "llvm/Transforms/Utils/PredicateInfo.h"
Daniel Berlin07daac82017-04-02 13:23:44 +000086#include "llvm/Transforms/Utils/VNCoercion.h"
Daniel Berlin1316a942017-04-06 18:52:50 +000087#include <numeric>
Davide Italiano7e274e02016-12-22 16:03:48 +000088#include <unordered_map>
89#include <utility>
90#include <vector>
91using namespace llvm;
92using namespace PatternMatch;
93using namespace llvm::GVNExpression;
Daniel Berlin07daac82017-04-02 13:23:44 +000094using namespace llvm::VNCoercion;
Davide Italiano7e274e02016-12-22 16:03:48 +000095#define DEBUG_TYPE "newgvn"
96
97STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
98STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
99STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
100STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +0000101STATISTIC(NumGVNMaxIterations,
102 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000103STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
104STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
105STATISTIC(NumGVNAvoidedSortedLeaderChanges,
106 "Number of avoided sorted leader changes");
Daniel Berlin89fea6f2017-01-20 06:38:41 +0000107STATISTIC(NumGVNNotMostDominatingLeader,
108 "Number of times a member dominated it's new classes' leader");
Daniel Berlinc4796862017-01-27 02:37:11 +0000109STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Daniel Berlin283a6082017-03-01 19:59:26 +0000110DEBUG_COUNTER(VNCounter, "newgvn-vn",
111 "Controls which instructions are value numbered")
Daniel Berlin1316a942017-04-06 18:52:50 +0000112
113// Currently store defining access refinement is too slow due to basicaa being
114// egregiously slow. This flag lets us keep it working while we work on this
115// issue.
116static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
117 cl::init(false), cl::Hidden);
118
Davide Italiano7e274e02016-12-22 16:03:48 +0000119//===----------------------------------------------------------------------===//
120// GVN Pass
121//===----------------------------------------------------------------------===//
122
123// Anchor methods.
124namespace llvm {
125namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000126Expression::~Expression() = default;
127BasicExpression::~BasicExpression() = default;
128CallExpression::~CallExpression() = default;
129LoadExpression::~LoadExpression() = default;
130StoreExpression::~StoreExpression() = default;
131AggregateValueExpression::~AggregateValueExpression() = default;
132PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000133}
134}
135
Daniel Berlin2f72b192017-04-14 02:53:37 +0000136// Tarjan's SCC finding algorithm with Nuutila's improvements
137// SCCIterator is actually fairly complex for the simple thing we want.
138// It also wants to hand us SCC's that are unrelated to the phi node we ask
139// about, and have us process them there or risk redoing work.
140// Graph traits over a filter iterator also doesn't work that well here.
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000141// This SCC finder is specialized to walk use-def chains, and only follows
142// instructions,
Daniel Berlin2f72b192017-04-14 02:53:37 +0000143// not generic values (arguments, etc).
144struct TarjanSCC {
145
146 TarjanSCC() : Components(1) {}
147
148 void Start(const Instruction *Start) {
149 if (Root.lookup(Start) == 0)
150 FindSCC(Start);
151 }
152
153 const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
154 unsigned ComponentID = ValueToComponent.lookup(V);
155
156 assert(ComponentID > 0 &&
157 "Asking for a component for a value we never processed");
158 return Components[ComponentID];
159 }
160
161private:
162 void FindSCC(const Instruction *I) {
163 Root[I] = ++DFSNum;
164 // Store the DFS Number we had before it possibly gets incremented.
165 unsigned int OurDFS = DFSNum;
166 for (auto &Op : I->operands()) {
167 if (auto *InstOp = dyn_cast<Instruction>(Op)) {
168 if (Root.lookup(Op) == 0)
169 FindSCC(InstOp);
170 if (!InComponent.count(Op))
171 Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
172 }
173 }
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000174 // See if we really were the root of a component, by seeing if we still have
175 // our DFSNumber.
176 // If we do, we are the root of the component, and we have completed a
177 // component. If we do not,
Daniel Berlin2f72b192017-04-14 02:53:37 +0000178 // we are not the root of a component, and belong on the component stack.
179 if (Root.lookup(I) == OurDFS) {
180 unsigned ComponentID = Components.size();
181 Components.resize(Components.size() + 1);
182 auto &Component = Components.back();
183 Component.insert(I);
184 DEBUG(dbgs() << "Component root is " << *I << "\n");
185 InComponent.insert(I);
186 ValueToComponent[I] = ComponentID;
187 // Pop a component off the stack and label it.
188 while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
189 auto *Member = Stack.back();
190 DEBUG(dbgs() << "Component member is " << *Member << "\n");
191 Component.insert(Member);
192 InComponent.insert(Member);
193 ValueToComponent[Member] = ComponentID;
194 Stack.pop_back();
195 }
196 } else {
197 // Part of a component, push to stack
198 Stack.push_back(I);
199 }
200 }
201 unsigned int DFSNum = 1;
202 SmallPtrSet<const Value *, 8> InComponent;
203 DenseMap<const Value *, unsigned int> Root;
204 SmallVector<const Value *, 8> Stack;
205 // Store the components as vector of ptr sets, because we need the topo order
206 // of SCC's, but not individual member order
207 SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
208 DenseMap<const Value *, unsigned> ValueToComponent;
209};
Davide Italiano7e274e02016-12-22 16:03:48 +0000210// Congruence classes represent the set of expressions/instructions
211// that are all the same *during some scope in the function*.
212// That is, because of the way we perform equality propagation, and
213// because of memory value numbering, it is not correct to assume
214// you can willy-nilly replace any member with any other at any
215// point in the function.
216//
217// For any Value in the Member set, it is valid to replace any dominated member
218// with that Value.
219//
Daniel Berlin1316a942017-04-06 18:52:50 +0000220// Every congruence class has a leader, and the leader is used to symbolize
221// instructions in a canonical way (IE every operand of an instruction that is a
222// member of the same congruence class will always be replaced with leader
223// during symbolization). To simplify symbolization, we keep the leader as a
224// constant if class can be proved to be a constant value. Otherwise, the
225// leader is the member of the value set with the smallest DFS number. Each
226// congruence class also has a defining expression, though the expression may be
227// null. If it exists, it can be used for forward propagation and reassociation
228// of values.
229
230// For memory, we also track a representative MemoryAccess, and a set of memory
231// members for MemoryPhis (which have no real instructions). Note that for
232// memory, it seems tempting to try to split the memory members into a
233// MemoryCongruenceClass or something. Unfortunately, this does not work
234// easily. The value numbering of a given memory expression depends on the
235// leader of the memory congruence class, and the leader of memory congruence
236// class depends on the value numbering of a given memory expression. This
237// leads to wasted propagation, and in some cases, missed optimization. For
238// example: If we had value numbered two stores together before, but now do not,
239// we move them to a new value congruence class. This in turn will move at one
240// of the memorydefs to a new memory congruence class. Which in turn, affects
241// the value numbering of the stores we just value numbered (because the memory
242// congruence class is part of the value number). So while theoretically
243// possible to split them up, it turns out to be *incredibly* complicated to get
244// it to work right, because of the interdependency. While structurally
245// slightly messier, it is algorithmically much simpler and faster to do what we
Daniel Berlina8236562017-04-07 18:38:09 +0000246// do here, and track them both at once in the same class.
247// Note: The default iterators for this class iterate over values
248class CongruenceClass {
249public:
250 using MemberType = Value;
251 using MemberSet = SmallPtrSet<MemberType *, 4>;
252 using MemoryMemberType = MemoryPhi;
253 using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
254
255 explicit CongruenceClass(unsigned ID) : ID(ID) {}
256 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
257 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
258 unsigned getID() const { return ID; }
259 // True if this class has no members left. This is mainly used for assertion
260 // purposes, and for skipping empty classes.
261 bool isDead() const {
262 // If it's both dead from a value perspective, and dead from a memory
263 // perspective, it's really dead.
264 return empty() && memory_empty();
265 }
266 // Leader functions
267 Value *getLeader() const { return RepLeader; }
268 void setLeader(Value *Leader) { RepLeader = Leader; }
269 const std::pair<Value *, unsigned int> &getNextLeader() const {
270 return NextLeader;
271 }
272 void resetNextLeader() { NextLeader = {nullptr, ~0}; }
273
274 void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
275 if (LeaderPair.second < NextLeader.second)
276 NextLeader = LeaderPair;
277 }
278
279 Value *getStoredValue() const { return RepStoredValue; }
280 void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
281 const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
282 void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
283
284 // Forward propagation info
285 const Expression *getDefiningExpr() const { return DefiningExpr; }
286 void setDefiningExpr(const Expression *E) { DefiningExpr = E; }
287
288 // Value member set
289 bool empty() const { return Members.empty(); }
290 unsigned size() const { return Members.size(); }
291 MemberSet::const_iterator begin() const { return Members.begin(); }
292 MemberSet::const_iterator end() const { return Members.end(); }
293 void insert(MemberType *M) { Members.insert(M); }
294 void erase(MemberType *M) { Members.erase(M); }
295 void swap(MemberSet &Other) { Members.swap(Other); }
296
297 // Memory member set
298 bool memory_empty() const { return MemoryMembers.empty(); }
299 unsigned memory_size() const { return MemoryMembers.size(); }
300 MemoryMemberSet::const_iterator memory_begin() const {
301 return MemoryMembers.begin();
302 }
303 MemoryMemberSet::const_iterator memory_end() const {
304 return MemoryMembers.end();
305 }
306 iterator_range<MemoryMemberSet::const_iterator> memory() const {
307 return make_range(memory_begin(), memory_end());
308 }
309 void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
310 void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
311
312 // Store count
313 unsigned getStoreCount() const { return StoreCount; }
314 void incStoreCount() { ++StoreCount; }
315 void decStoreCount() {
316 assert(StoreCount != 0 && "Store count went negative");
317 --StoreCount;
318 }
319
320 // Return true if two congruence classes are equivalent to each other. This
321 // means
322 // that every field but the ID number and the dead field are equivalent.
323 bool isEquivalentTo(const CongruenceClass *Other) const {
324 if (!Other)
325 return false;
326 if (this == Other)
327 return true;
328
329 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
330 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
331 Other->RepMemoryAccess))
332 return false;
333 if (DefiningExpr != Other->DefiningExpr)
334 if (!DefiningExpr || !Other->DefiningExpr ||
335 *DefiningExpr != *Other->DefiningExpr)
336 return false;
337 // We need some ordered set
338 std::set<Value *> AMembers(Members.begin(), Members.end());
339 std::set<Value *> BMembers(Members.begin(), Members.end());
340 return AMembers == BMembers;
341 }
342
343private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000344 unsigned ID;
345 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000346 Value *RepLeader = nullptr;
Daniel Berlina8236562017-04-07 18:38:09 +0000347 // The most dominating leader after our current leader, because the member set
348 // is not sorted and is expensive to keep sorted all the time.
349 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
Daniel Berlin1316a942017-04-06 18:52:50 +0000350 // If this is represented by a store, the value of the store.
Daniel Berlin26addef2017-01-20 21:04:30 +0000351 Value *RepStoredValue = nullptr;
Daniel Berlin1316a942017-04-06 18:52:50 +0000352 // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
353 // access.
354 const MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000355 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000356 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000357 // Actual members of this class.
358 MemberSet Members;
Daniel Berlin1316a942017-04-06 18:52:50 +0000359 // This is the set of MemoryPhis that exist in the class. MemoryDefs and
360 // MemoryUses have real instructions representing them, so we only need to
361 // track MemoryPhis here.
362 MemoryMemberSet MemoryMembers;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000363 // Number of stores in this congruence class.
364 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000365 int StoreCount = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +0000366};
367
368namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000369template <> struct DenseMapInfo<const Expression *> {
370 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000371 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000372 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
373 return reinterpret_cast<const Expression *>(Val);
374 }
375 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000376 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000377 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
378 return reinterpret_cast<const Expression *>(Val);
379 }
380 static unsigned getHashValue(const Expression *V) {
381 return static_cast<unsigned>(V->getHashValue());
382 }
383 static bool isEqual(const Expression *LHS, const Expression *RHS) {
384 if (LHS == RHS)
385 return true;
386 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
387 LHS == getEmptyKey() || RHS == getEmptyKey())
388 return false;
389 return *LHS == *RHS;
390 }
391};
Davide Italiano7e274e02016-12-22 16:03:48 +0000392} // end namespace llvm
393
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000394namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000395class NewGVN {
396 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000397 DominatorTree *DT;
Daniel Berlin64e68992017-03-12 04:46:45 +0000398 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000399 AliasAnalysis *AA;
400 MemorySSA *MSSA;
401 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000402 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000403 std::unique_ptr<PredicateInfo> PredInfo;
Davide Italiano7e274e02016-12-22 16:03:48 +0000404 BumpPtrAllocator ExpressionAllocator;
405 ArrayRecycler<Value *> ArgRecycler;
Daniel Berlin2f72b192017-04-14 02:53:37 +0000406 TarjanSCC SCCFinder;
Daniel Berlinede130d2017-04-26 20:56:14 +0000407 const SimplifyQuery SQ;
Davide Italiano7e274e02016-12-22 16:03:48 +0000408
Daniel Berlin1c087672017-02-11 15:07:01 +0000409 // Number of function arguments, used by ranking
410 unsigned int NumFuncArgs;
411
Daniel Berlin2f72b192017-04-14 02:53:37 +0000412 // RPOOrdering of basic blocks
413 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
414
Davide Italiano7e274e02016-12-22 16:03:48 +0000415 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000416
417 // This class is called INITIAL in the paper. It is the class everything
418 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000419 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000420 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000421 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000422 std::vector<CongruenceClass *> CongruenceClasses;
423 unsigned NextCongruenceNum;
424
425 // Value Mappings.
426 DenseMap<Value *, CongruenceClass *> ValueToClass;
427 DenseMap<Value *, const Expression *> ValueToExpression;
428
Daniel Berlinf7d95802017-02-18 23:06:50 +0000429 // Mapping from predicate info we used to the instructions we used it with.
430 // In order to correctly ensure propagation, we must keep track of what
431 // comparisons we used, so that when the values of the comparisons change, we
432 // propagate the information to the places we used the comparison.
433 DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000434 // Mapping from MemoryAccess we used to the MemoryAccess we used it with. Has
435 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
436 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
437 DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>> MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000438
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000439 // A table storing which memorydefs/phis represent a memory state provably
440 // equivalent to another memory state.
441 // We could use the congruence class machinery, but the MemoryAccess's are
442 // abstract memory states, so they can only ever be equivalent to each other,
443 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000444 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000445
Daniel Berlin1316a942017-04-06 18:52:50 +0000446 // We could, if we wanted, build MemoryPhiExpressions and
447 // MemoryVariableExpressions, etc, and value number them the same way we value
448 // number phi expressions. For the moment, this seems like overkill. They
449 // can only exist in one of three states: they can be TOP (equal to
450 // everything), Equivalent to something else, or unique. Because we do not
451 // create expressions for them, we need to simulate leader change not just
452 // when they change class, but when they change state. Note: We can do the
453 // same thing for phis, and avoid having phi expressions if we wanted, We
454 // should eventually unify in one direction or the other, so this is a little
455 // bit of an experiment in which turns out easier to maintain.
456 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
457 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
458
Daniel Berlin2f72b192017-04-14 02:53:37 +0000459 enum PhiCycleState { PCS_Unknown, PCS_CycleFree, PCS_Cycle };
460 DenseMap<const PHINode *, PhiCycleState> PhiCycleState;
Davide Italiano7e274e02016-12-22 16:03:48 +0000461 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000462 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000463 ExpressionClassMap ExpressionToClass;
464
465 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000466 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000467
468 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000469 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000470 DenseSet<BlockEdge> ReachableEdges;
471 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
472
473 // This is a bitvector because, on larger functions, we may have
474 // thousands of touched instructions at once (entire blocks,
475 // instructions with hundreds of uses, etc). Even with optimization
476 // for when we mark whole blocks as touched, when this was a
477 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
478 // the time in GVN just managing this list. The bitvector, on the
479 // other hand, efficiently supports test/set/clear of both
480 // individual and ranges, as well as "find next element" This
481 // enables us to use it as a worklist with essentially 0 cost.
482 BitVector TouchedInstructions;
483
484 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000485
486#ifndef NDEBUG
487 // Debugging for how many times each block and instruction got processed.
488 DenseMap<const Value *, unsigned> ProcessedCount;
489#endif
490
491 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000492 // This contains a mapping from Instructions to DFS numbers.
493 // The numbering starts at 1. An instruction with DFS number zero
494 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000495 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000496
497 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000498 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000499
500 // Deletion info.
501 SmallPtrSet<Instruction *, 8> InstructionsToErase;
502
503public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000504 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
505 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
506 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000507 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Daniel Berlinede130d2017-04-26 20:56:14 +0000508 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
509 }
Daniel Berlin64e68992017-03-12 04:46:45 +0000510 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000511
512private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000513 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000514 const Expression *createExpression(Instruction *);
515 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Daniel Berlin2f72b192017-04-14 02:53:37 +0000516 PHIExpression *createPHIExpression(Instruction *, bool &HasBackedge,
517 bool &AllConstant);
Davide Italiano7e274e02016-12-22 16:03:48 +0000518 const VariableExpression *createVariableExpression(Value *);
519 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000520 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000521 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000522 const StoreExpression *createStoreExpression(StoreInst *,
523 const MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000524 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin1316a942017-04-06 18:52:50 +0000525 const MemoryAccess *);
526 const CallExpression *createCallExpression(CallInst *, const MemoryAccess *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000527 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
528 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000529
530 // Congruence class handling.
531 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000532 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000533 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000534 return result;
535 }
536
Daniel Berlin1316a942017-04-06 18:52:50 +0000537 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
538 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000539 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000540 return CC;
541 }
542 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
543 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000544 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000545 CC = createMemoryClass(MA);
546 return CC;
547 }
548
Davide Italiano7e274e02016-12-22 16:03:48 +0000549 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000550 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000551 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000552 ValueToClass[Member] = CClass;
553 return CClass;
554 }
555 void initializeCongruenceClasses(Function &F);
556
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000557 // Value number an Instruction or MemoryPhi.
558 void valueNumberMemoryPhi(MemoryPhi *);
559 void valueNumberInstruction(Instruction *);
560
Davide Italiano7e274e02016-12-22 16:03:48 +0000561 // Symbolic evaluation.
562 const Expression *checkSimplificationResults(Expression *, Instruction *,
563 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000564 const Expression *performSymbolicEvaluation(Value *);
Daniel Berlin07daac82017-04-02 13:23:44 +0000565 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
566 Instruction *, MemoryAccess *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000567 const Expression *performSymbolicLoadEvaluation(Instruction *);
568 const Expression *performSymbolicStoreEvaluation(Instruction *);
569 const Expression *performSymbolicCallEvaluation(Instruction *);
570 const Expression *performSymbolicPHIEvaluation(Instruction *);
571 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
572 const Expression *performSymbolicCmpEvaluation(Instruction *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000573 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000574
575 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000576 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000577 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000578 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000579 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
580 CongruenceClass *, CongruenceClass *);
581 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
582 CongruenceClass *, CongruenceClass *);
583 Value *getNextValueLeader(CongruenceClass *) const;
584 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
585 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
586 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
587 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000588 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000589
Daniel Berlin1c087672017-02-11 15:07:01 +0000590 // Ranking
591 unsigned int getRank(const Value *) const;
592 bool shouldSwapOperands(const Value *, const Value *) const;
593
Davide Italiano7e274e02016-12-22 16:03:48 +0000594 // Reachability handling.
595 void updateReachableEdge(BasicBlock *, BasicBlock *);
596 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000597 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000598
599 // Elimination.
600 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000601 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000602 SmallVectorImpl<ValueDFS> &,
603 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000604 SmallPtrSetImpl<Instruction *> &) const;
605 void convertClassToLoadsAndStores(const CongruenceClass &,
606 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000607
608 bool eliminateInstructions(Function &);
609 void replaceInstruction(Instruction *, Value *);
610 void markInstructionForDeletion(Instruction *);
611 void deleteInstructionsInBlock(BasicBlock *);
612
613 // New instruction creation.
614 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000615
616 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000617 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000618 void markMemoryUsersTouched(const MemoryAccess *);
619 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000620 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000621 void markValueLeaderChangeTouched(CongruenceClass *CC);
622 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000623 void addPredicateUsers(const PredicateBase *, Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000624 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U);
Davide Italiano7e274e02016-12-22 16:03:48 +0000625
Daniel Berlin06329a92017-03-18 15:41:40 +0000626 // Main loop of value numbering
627 void iterateTouchedInstructions();
628
Davide Italiano7e274e02016-12-22 16:03:48 +0000629 // Utilities.
630 void cleanupTables();
631 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
632 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000633 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000634 void verifyIterationSettled(Function &F);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000635 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000636 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin0e900112017-03-24 06:33:48 +0000637 void deleteExpression(const Expression *E);
Daniel Berlin21279bd2017-04-06 18:52:58 +0000638 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000639 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
640 return InstrDFS.lookup(V);
641 }
642
Daniel Berlin21279bd2017-04-06 18:52:58 +0000643 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
644 return MemoryToDFSNum(MA);
645 }
646 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
647 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
648 // This deliberately takes a value so it can be used with Use's, which will
649 // auto-convert to Value's but not to MemoryAccess's.
650 unsigned MemoryToDFSNum(const Value *MA) const {
651 assert(isa<MemoryAccess>(MA) &&
652 "This should not be used with instructions");
653 return isa<MemoryUseOrDef>(MA)
654 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
655 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000656 }
Daniel Berlin2f72b192017-04-14 02:53:37 +0000657 bool isCycleFree(const PHINode *PN);
Daniel Berlin1316a942017-04-06 18:52:50 +0000658 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000659 // Debug counter info. When verifying, we have to reset the value numbering
660 // debug counter to the same state it started in to get the same results.
661 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000662};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000663} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000664
Davide Italianob1114092016-12-28 13:37:17 +0000665template <typename T>
666static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000667 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000668 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000669 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000670}
671
Davide Italianob1114092016-12-28 13:37:17 +0000672bool LoadExpression::equals(const Expression &Other) const {
673 return equalsLoadStoreHelper(*this, Other);
674}
Davide Italiano7e274e02016-12-22 16:03:48 +0000675
Davide Italianob1114092016-12-28 13:37:17 +0000676bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000677 if (!equalsLoadStoreHelper(*this, Other))
678 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000679 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000680 if (const auto *S = dyn_cast<StoreExpression>(&Other))
681 if (getStoredValue() != S->getStoredValue())
682 return false;
683 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000684}
685
686#ifndef NDEBUG
687static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000688 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000689}
690#endif
691
Daniel Berlin06329a92017-03-18 15:41:40 +0000692// Get the basic block from an instruction/memory value.
693BasicBlock *NewGVN::getBlockForValue(Value *V) const {
694 if (auto *I = dyn_cast<Instruction>(V))
695 return I->getParent();
696 else if (auto *MP = dyn_cast<MemoryPhi>(V))
697 return MP->getBlock();
698 llvm_unreachable("Should have been able to figure out a block for our value");
699 return nullptr;
700}
701
Daniel Berlin0e900112017-03-24 06:33:48 +0000702// Delete a definitely dead expression, so it can be reused by the expression
703// allocator. Some of these are not in creation functions, so we have to accept
704// const versions.
705void NewGVN::deleteExpression(const Expression *E) {
706 assert(isa<BasicExpression>(E));
707 auto *BE = cast<BasicExpression>(E);
708 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
709 ExpressionAllocator.Deallocate(E);
710}
711
Daniel Berlin2f72b192017-04-14 02:53:37 +0000712PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
713 bool &AllConstant) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000714 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000715 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000716 auto *E =
717 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000718
719 E->allocateOperands(ArgRecycler, ExpressionAllocator);
720 E->setType(I->getType());
721 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000722
Daniel Berlin2f72b192017-04-14 02:53:37 +0000723 unsigned PHIRPO = RPOOrdering.lookup(DT->getNode(PHIBlock));
724
Davide Italianob3886dd2017-01-25 23:37:49 +0000725 // Filter out unreachable phi operands.
726 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +0000727 return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000728 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000729
730 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
731 [&](const Use &U) -> Value * {
Daniel Berlin2f72b192017-04-14 02:53:37 +0000732 auto *BB = PN->getIncomingBlock(U);
733 auto *DTN = DT->getNode(BB);
734 if (RPOOrdering.lookup(DTN) >= PHIRPO)
735 HasBackedge = true;
736 AllConstant &= isa<UndefValue>(U) || isa<Constant>(U);
737
Daniel Berlind92e7f92017-01-07 00:01:42 +0000738 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000739 if (U == PN)
740 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000741 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000742 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000743 return E;
744}
745
746// Set basic expression info (Arguments, type, opcode) for Expression
747// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000748bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000749 bool AllConstant = true;
750 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
751 E->setType(GEP->getSourceElementType());
752 else
753 E->setType(I->getType());
754 E->setOpcode(I->getOpcode());
755 E->allocateOperands(ArgRecycler, ExpressionAllocator);
756
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000757 // Transform the operand array into an operand leader array, and keep track of
758 // whether all members are constant.
759 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000760 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000761 AllConstant &= isa<Constant>(Operand);
762 return Operand;
763 });
764
Davide Italiano7e274e02016-12-22 16:03:48 +0000765 return AllConstant;
766}
767
768const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000769 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000770 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000771
772 E->setType(T);
773 E->setOpcode(Opcode);
774 E->allocateOperands(ArgRecycler, ExpressionAllocator);
775 if (Instruction::isCommutative(Opcode)) {
776 // Ensure that commutative instructions that only differ by a permutation
777 // of their operands get the same value number by sorting the operand value
778 // numbers. Since all commutative instructions have two operands it is more
779 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000780 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000781 std::swap(Arg1, Arg2);
782 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000783 E->op_push_back(lookupOperandLeader(Arg1));
784 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000785
Daniel Berlinede130d2017-04-26 20:56:14 +0000786 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000787 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
788 return SimplifiedE;
789 return E;
790}
791
792// Take a Value returned by simplification of Expression E/Instruction
793// I, and see if it resulted in a simpler expression. If so, return
794// that expression.
795// TODO: Once finished, this should not take an Instruction, we only
796// use it for printing.
797const Expression *NewGVN::checkSimplificationResults(Expression *E,
798 Instruction *I, Value *V) {
799 if (!V)
800 return nullptr;
801 if (auto *C = dyn_cast<Constant>(V)) {
802 if (I)
803 DEBUG(dbgs() << "Simplified " << *I << " to "
804 << " constant " << *C << "\n");
805 NumGVNOpsSimplified++;
806 assert(isa<BasicExpression>(E) &&
807 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000808 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000809 return createConstantExpression(C);
810 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
811 if (I)
812 DEBUG(dbgs() << "Simplified " << *I << " to "
813 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000814 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000815 return createVariableExpression(V);
816 }
817
818 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlina8236562017-04-07 18:38:09 +0000819 if (CC && CC->getDefiningExpr()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000820 if (I)
821 DEBUG(dbgs() << "Simplified " << *I << " to "
822 << " expression " << *V << "\n");
823 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000824 deleteExpression(E);
Daniel Berlina8236562017-04-07 18:38:09 +0000825 return CC->getDefiningExpr();
Davide Italiano7e274e02016-12-22 16:03:48 +0000826 }
827 return nullptr;
828}
829
Daniel Berlin97718e62017-01-31 22:32:03 +0000830const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000831 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000832
Daniel Berlin97718e62017-01-31 22:32:03 +0000833 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000834
835 if (I->isCommutative()) {
836 // Ensure that commutative instructions that only differ by a permutation
837 // of their operands get the same value number by sorting the operand value
838 // numbers. Since all commutative instructions have two operands it is more
839 // efficient to sort by hand rather than using, say, std::sort.
840 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000841 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000842 E->swapOperands(0, 1);
843 }
844
845 // Perform simplificaiton
846 // TODO: Right now we only check to see if we get a constant result.
847 // We may get a less than constant, but still better, result for
848 // some operations.
849 // IE
850 // add 0, x -> x
851 // and x, x -> x
852 // We should handle this by simply rewriting the expression.
853 if (auto *CI = dyn_cast<CmpInst>(I)) {
854 // Sort the operand value numbers so x<y and y>x get the same value
855 // number.
856 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000857 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000858 E->swapOperands(0, 1);
859 Predicate = CmpInst::getSwappedPredicate(Predicate);
860 }
861 E->setOpcode((CI->getOpcode() << 8) | Predicate);
862 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000863 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
864 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000865 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
866 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +0000867 Value *V =
868 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +0000869 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
870 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000871 } else if (isa<SelectInst>(I)) {
872 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000873 E->getOperand(0) == E->getOperand(1)) {
874 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
875 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000876 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +0000877 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000878 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
879 return SimplifiedE;
880 }
881 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +0000882 Value *V =
883 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000884 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
885 return SimplifiedE;
886 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000887 Value *V =
888 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000889 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
890 return SimplifiedE;
891 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +0000892 Value *V = SimplifyGEPInst(
893 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000894 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
895 return SimplifiedE;
896 } else if (AllConstant) {
897 // We don't bother trying to simplify unless all of the operands
898 // were constant.
899 // TODO: There are a lot of Simplify*'s we could call here, if we
900 // wanted to. The original motivating case for this code was a
901 // zext i1 false to i8, which we don't have an interface to
902 // simplify (IE there is no SimplifyZExt).
903
904 SmallVector<Constant *, 8> C;
905 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000906 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000907
Daniel Berlin64e68992017-03-12 04:46:45 +0000908 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +0000909 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
910 return SimplifiedE;
911 }
912 return E;
913}
914
915const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000916NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000917 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000918 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000919 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000920 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000921 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000922 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000923 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000924 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000925 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000926 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000927 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000928 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000929 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000930 return E;
931 }
932 llvm_unreachable("Unhandled type of aggregate value operation");
933}
934
Daniel Berlin85f91b02016-12-26 20:06:58 +0000935const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000936 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000937 E->setOpcode(V->getValueID());
938 return E;
939}
940
Daniel Berlinf7d95802017-02-18 23:06:50 +0000941const Expression *NewGVN::createVariableOrConstant(Value *V) {
942 if (auto *C = dyn_cast<Constant>(V))
943 return createConstantExpression(C);
944 return createVariableExpression(V);
945}
946
Daniel Berlin85f91b02016-12-26 20:06:58 +0000947const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000948 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000949 E->setOpcode(C->getValueID());
950 return E;
951}
952
Daniel Berlin02c6b172017-01-02 18:00:53 +0000953const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
954 auto *E = new (ExpressionAllocator) UnknownExpression(I);
955 E->setOpcode(I->getOpcode());
956 return E;
957}
958
Davide Italiano7e274e02016-12-22 16:03:48 +0000959const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin1316a942017-04-06 18:52:50 +0000960 const MemoryAccess *MA) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000961 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000962 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +0000963 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +0000964 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000965 return E;
966}
967
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000968// Return true if some equivalent of instruction Inst dominates instruction U.
969bool NewGVN::someEquivalentDominates(const Instruction *Inst,
970 const Instruction *U) const {
971 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +0000972 // This must be an instruction because we are only called from phi nodes
973 // in the case that the value it needs to check against is an instruction.
974
975 // The most likely candiates for dominance are the leader and the next leader.
976 // The leader or nextleader will dominate in all cases where there is an
977 // equivalent that is higher up in the dom tree.
978 // We can't *only* check them, however, because the
979 // dominator tree could have an infinite number of non-dominating siblings
980 // with instructions that are in the right congruence class.
981 // A
982 // B C D E F G
983 // |
984 // H
985 // Instruction U could be in H, with equivalents in every other sibling.
986 // Depending on the rpo order picked, the leader could be the equivalent in
987 // any of these siblings.
988 if (!CC)
989 return false;
Daniel Berlina8236562017-04-07 18:38:09 +0000990 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +0000991 return true;
Daniel Berlina8236562017-04-07 18:38:09 +0000992 if (CC->getNextLeader().first &&
993 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +0000994 return true;
Daniel Berlina8236562017-04-07 18:38:09 +0000995 return llvm::any_of(*CC, [&](const Value *Member) {
996 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +0000997 DT->dominates(cast<Instruction>(Member), U);
998 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000999}
1000
Davide Italiano7e274e02016-12-22 16:03:48 +00001001// See if we have a congruence class and leader for this operand, and if so,
1002// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001003Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001004 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001005 if (CC) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001006 // Everything in TOP is represneted by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001007 // We do have to make sure we get the type right though, so we can't set the
1008 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001009 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001010 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001011 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001012 }
1013
Davide Italiano7e274e02016-12-22 16:03:48 +00001014 return V;
1015}
1016
Daniel Berlin1316a942017-04-06 18:52:50 +00001017const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1018 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001019 assert(CC->getMemoryLeader() &&
1020 "Every MemoryAccess should be mapped to a "
1021 "congruence class with a represenative memory "
1022 "access");
1023 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001024}
1025
Daniel Berlinc4796862017-01-27 02:37:11 +00001026// Return true if the MemoryAccess is really equivalent to everything. This is
1027// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001028// state of all MemoryAccesses.
Daniel Berlinc4796862017-01-27 02:37:11 +00001029bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001030 return getMemoryClass(MA) == TOPClass;
1031}
1032
Davide Italiano7e274e02016-12-22 16:03:48 +00001033LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001034 LoadInst *LI,
1035 const MemoryAccess *MA) {
1036 auto *E =
1037 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001038 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1039 E->setType(LoadType);
1040
1041 // Give store and loads same opcode so they value number together.
1042 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001043 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001044 if (LI)
1045 E->setAlignment(LI->getAlignment());
1046
1047 // TODO: Value number heap versions. We may be able to discover
1048 // things alias analysis can't on it's own (IE that a store and a
1049 // load have the same value, and thus, it isn't clobbering the load).
1050 return E;
1051}
1052
1053const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin1316a942017-04-06 18:52:50 +00001054 const MemoryAccess *MA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001055 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001056 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001057 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001058 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1059 E->setType(SI->getValueOperand()->getType());
1060
1061 // Give store and loads same opcode so they value number together.
1062 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001063 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001064
1065 // TODO: Value number heap versions. We may be able to discover
1066 // things alias analysis can't on it's own (IE that a store and a
1067 // load have the same value, and thus, it isn't clobbering the load).
1068 return E;
1069}
1070
Daniel Berlin97718e62017-01-31 22:32:03 +00001071const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001072 // Unlike loads, we never try to eliminate stores, so we do not check if they
1073 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001074 auto *SI = cast<StoreInst>(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00001075 auto *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001076 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001077 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1078 if (EnableStoreRefinement)
1079 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1080 // If we bypassed the use-def chains, make sure we add a use.
1081 if (StoreRHS != StoreAccess->getDefiningAccess())
1082 addMemoryUsers(StoreRHS, StoreAccess);
1083
1084 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001085 // If we are defined by ourselves, use the live on entry def.
1086 if (StoreRHS == StoreAccess)
1087 StoreRHS = MSSA->getLiveOnEntryDef();
1088
Daniel Berlin589cecc2017-01-02 18:00:46 +00001089 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001090 // See if we are defined by a previous store expression, it already has a
1091 // value, and it's the same value as our current store. FIXME: Right now, we
1092 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001093 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1094 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +00001095 // Basically, check if the congruence class the store is in is defined by a
1096 // store that isn't us, and has the same value. MemorySSA takes care of
1097 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +00001098 // The RepStoredValue gets nulled if all the stores disappear in a class, so
1099 // we don't need to check if the class contains a store besides us.
Daniel Berlin1316a942017-04-06 18:52:50 +00001100 if (LastCC &&
Daniel Berlina8236562017-04-07 18:38:09 +00001101 LastCC->getStoredValue() == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin1316a942017-04-06 18:52:50 +00001102 return LastStore;
1103 deleteExpression(LastStore);
Daniel Berlinc4796862017-01-27 02:37:11 +00001104 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001105 // location, and the memory state is the same as it was then (otherwise, it
1106 // could have been overwritten later. See test32 in
1107 // transforms/DeadStoreElimination/simple.ll).
1108 if (auto *LI =
1109 dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001110 if ((lookupOperandLeader(LI->getPointerOperand()) ==
1111 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlin1316a942017-04-06 18:52:50 +00001112 (lookupMemoryLeader(MSSA->getMemoryAccess(LI)->getDefiningAccess()) ==
1113 StoreRHS))
Daniel Berlinc4796862017-01-27 02:37:11 +00001114 return createVariableExpression(LI);
1115 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001116 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001117
1118 // If the store is not equivalent to anything, value number it as a store that
1119 // produces a unique memory state (instead of using it's MemoryUse, we use
1120 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001121 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001122}
1123
Daniel Berlin07daac82017-04-02 13:23:44 +00001124// See if we can extract the value of a loaded pointer from a load, a store, or
1125// a memory instruction.
1126const Expression *
1127NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1128 LoadInst *LI, Instruction *DepInst,
1129 MemoryAccess *DefiningAccess) {
1130 assert((!LI || LI->isSimple()) && "Not a simple load");
1131 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1132 // Can't forward from non-atomic to atomic without violating memory model.
1133 // Also don't need to coerce if they are the same type, we will just
1134 // propogate..
1135 if (LI->isAtomic() > DepSI->isAtomic() ||
1136 LoadType == DepSI->getValueOperand()->getType())
1137 return nullptr;
1138 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1139 if (Offset >= 0) {
1140 if (auto *C = dyn_cast<Constant>(
1141 lookupOperandLeader(DepSI->getValueOperand()))) {
1142 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1143 << *C << "\n");
1144 return createConstantExpression(
1145 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1146 }
1147 }
1148
1149 } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1150 // Can't forward from non-atomic to atomic without violating memory model.
1151 if (LI->isAtomic() > DepLI->isAtomic())
1152 return nullptr;
1153 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1154 if (Offset >= 0) {
1155 // We can coerce a constant load into a load
1156 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1157 if (auto *PossibleConstant =
1158 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1159 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1160 << *PossibleConstant << "\n");
1161 return createConstantExpression(PossibleConstant);
1162 }
1163 }
1164
1165 } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1166 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1167 if (Offset >= 0) {
1168 if (auto *PossibleConstant =
1169 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1170 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1171 << " to constant " << *PossibleConstant << "\n");
1172 return createConstantExpression(PossibleConstant);
1173 }
1174 }
1175 }
1176
1177 // All of the below are only true if the loaded pointer is produced
1178 // by the dependent instruction.
1179 if (LoadPtr != lookupOperandLeader(DepInst) &&
1180 !AA->isMustAlias(LoadPtr, DepInst))
1181 return nullptr;
1182 // If this load really doesn't depend on anything, then we must be loading an
1183 // undef value. This can happen when loading for a fresh allocation with no
1184 // intervening stores, for example. Note that this is only true in the case
1185 // that the result of the allocation is pointer equal to the load ptr.
1186 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1187 return createConstantExpression(UndefValue::get(LoadType));
1188 }
1189 // If this load occurs either right after a lifetime begin,
1190 // then the loaded value is undefined.
1191 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1192 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1193 return createConstantExpression(UndefValue::get(LoadType));
1194 }
1195 // If this load follows a calloc (which zero initializes memory),
1196 // then the loaded value is zero
1197 else if (isCallocLikeFn(DepInst, TLI)) {
1198 return createConstantExpression(Constant::getNullValue(LoadType));
1199 }
1200
1201 return nullptr;
1202}
1203
Daniel Berlin97718e62017-01-31 22:32:03 +00001204const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001205 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001206
1207 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001208 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001209 if (!LI->isSimple())
1210 return nullptr;
1211
Daniel Berlin203f47b2017-01-31 22:31:53 +00001212 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001213 // Load of undef is undef.
1214 if (isa<UndefValue>(LoadAddressLeader))
1215 return createConstantExpression(UndefValue::get(LI->getType()));
1216
1217 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
1218
1219 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1220 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1221 Instruction *DefiningInst = MD->getMemoryInst();
1222 // If the defining instruction is not reachable, replace with undef.
1223 if (!ReachableBlocks.count(DefiningInst->getParent()))
1224 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001225 // This will handle stores and memory insts. We only do if it the
1226 // defining access has a different type, or it is a pointer produced by
1227 // certain memory operations that cause the memory to have a fixed value
1228 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001229 if (const auto *CoercionResult =
1230 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1231 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001232 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001233 }
1234 }
1235
Daniel Berlin1316a942017-04-06 18:52:50 +00001236 const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1237 LI, DefiningAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001238 return E;
1239}
1240
Daniel Berlinf7d95802017-02-18 23:06:50 +00001241const Expression *
1242NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
1243 auto *PI = PredInfo->getPredicateInfoFor(I);
1244 if (!PI)
1245 return nullptr;
1246
1247 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001248
1249 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1250 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001251 return nullptr;
1252
Daniel Berlinfccbda92017-02-22 22:20:58 +00001253 auto *CopyOf = I->getOperand(0);
1254 auto *Cond = PWC->Condition;
1255
Daniel Berlinf7d95802017-02-18 23:06:50 +00001256 // If this a copy of the condition, it must be either true or false depending
1257 // on the predicate info type and edge
1258 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001259 // We should not need to add predicate users because the predicate info is
1260 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001261 if (isa<PredicateAssume>(PI))
1262 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1263 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1264 if (PBranch->TrueEdge)
1265 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1266 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1267 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001268 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1269 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001270 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001271
Daniel Berlinf7d95802017-02-18 23:06:50 +00001272 // Not a copy of the condition, so see what the predicates tell us about this
1273 // value. First, though, we check to make sure the value is actually a copy
1274 // of one of the condition operands. It's possible, in certain cases, for it
1275 // to be a copy of a predicateinfo copy. In particular, if two branch
1276 // operations use the same condition, and one branch dominates the other, we
1277 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001278 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001279 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001280
1281 // Everything below relies on the condition being a comparison.
1282 auto *Cmp = dyn_cast<CmpInst>(Cond);
1283 if (!Cmp)
1284 return nullptr;
1285
1286 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001287 DEBUG(dbgs() << "Copy is not of any condition operands!");
1288 return nullptr;
1289 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001290 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1291 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001292 bool SwappedOps = false;
1293 // Sort the ops
1294 if (shouldSwapOperands(FirstOp, SecondOp)) {
1295 std::swap(FirstOp, SecondOp);
1296 SwappedOps = true;
1297 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001298 CmpInst::Predicate Predicate =
1299 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1300
1301 if (isa<PredicateAssume>(PI)) {
1302 // If the comparison is true when the operands are equal, then we know the
1303 // operands are equal, because assumes must always be true.
1304 if (CmpInst::isTrueWhenEqual(Predicate)) {
1305 addPredicateUsers(PI, I);
1306 return createVariableOrConstant(FirstOp);
1307 }
1308 }
1309 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1310 // If we are *not* a copy of the comparison, we may equal to the other
1311 // operand when the predicate implies something about equality of
1312 // operations. In particular, if the comparison is true/false when the
1313 // operands are equal, and we are on the right edge, we know this operation
1314 // is equal to something.
1315 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1316 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1317 addPredicateUsers(PI, I);
1318 return createVariableOrConstant(FirstOp);
1319 }
1320 // Handle the special case of floating point.
1321 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1322 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1323 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1324 addPredicateUsers(PI, I);
1325 return createConstantExpression(cast<Constant>(FirstOp));
1326 }
1327 }
1328 return nullptr;
1329}
1330
Davide Italiano7e274e02016-12-22 16:03:48 +00001331// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001332const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001333 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001334 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1335 // Instrinsics with the returned attribute are copies of arguments.
1336 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1337 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1338 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1339 return Result;
1340 return createVariableOrConstant(ReturnedValue);
1341 }
1342 }
1343 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001344 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001345 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001346 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001347 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001348 }
1349 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001350}
1351
Daniel Berlin1316a942017-04-06 18:52:50 +00001352// Retrieve the memory class for a given MemoryAccess.
1353CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1354
1355 auto *Result = MemoryAccessToClass.lookup(MA);
1356 assert(Result && "Should have found memory class");
1357 return Result;
1358}
1359
1360// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001361// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001362bool NewGVN::setMemoryClass(const MemoryAccess *From,
1363 CongruenceClass *NewClass) {
1364 assert(NewClass &&
1365 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001366 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001367 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001368 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
1369 DEBUG(dbgs() << *NewClass->getMemoryLeader());
Daniel Berlin9f376b72017-01-29 10:26:03 +00001370 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001371
1372 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001373 bool Changed = false;
1374 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001375 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001376 auto *OldClass = LookupResult->second;
1377 if (OldClass != NewClass) {
1378 // If this is a phi, we have to handle memory member updates.
1379 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001380 OldClass->memory_erase(MP);
1381 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001382 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001383 if (OldClass->getMemoryLeader() == From) {
1384 if (OldClass->memory_empty()) {
1385 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001386 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001387 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001388 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001389 << OldClass->getID() << " to "
1390 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001391 << " due to removal of a memory member " << *From
1392 << "\n");
1393 markMemoryLeaderChangeTouched(OldClass);
1394 }
1395 }
1396 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001397 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001398 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001399 Changed = true;
1400 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001401 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001402
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001403 return Changed;
1404}
Daniel Berlin0e900112017-03-24 06:33:48 +00001405
Daniel Berlin2f72b192017-04-14 02:53:37 +00001406// Determine if a phi is cycle-free. That means the values in the phi don't
1407// depend on any expressions that can change value as a result of the phi.
1408// For example, a non-cycle free phi would be v = phi(0, v+1).
1409bool NewGVN::isCycleFree(const PHINode *PN) {
1410 // In order to compute cycle-freeness, we do SCC finding on the phi, and see
1411 // what kind of SCC it ends up in. If it is a singleton, it is cycle-free.
1412 // If it is not in a singleton, it is only cycle free if the other members are
1413 // all phi nodes (as they do not compute anything, they are copies). TODO:
1414 // There are likely a few other intrinsics or expressions that could be
1415 // included here, but this happens so infrequently already that it is not
1416 // likely to be worth it.
1417 auto PCS = PhiCycleState.lookup(PN);
1418 if (PCS == PCS_Unknown) {
1419 SCCFinder.Start(PN);
1420 auto &SCC = SCCFinder.getComponentFor(PN);
1421 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1422 if (SCC.size() == 1)
1423 PhiCycleState.insert({PN, PCS_CycleFree});
1424 else {
1425 bool AllPhis =
1426 llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
1427 PCS = AllPhis ? PCS_CycleFree : PCS_Cycle;
1428 for (auto *Member : SCC)
1429 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
1430 PhiCycleState.insert({MemberPhi, PCS});
1431 }
1432 }
1433 if (PCS == PCS_Cycle)
1434 return false;
1435 return true;
1436}
1437
Davide Italiano7e274e02016-12-22 16:03:48 +00001438// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001439const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001440 // True if one of the incoming phi edges is a backedge.
1441 bool HasBackedge = false;
1442 // All constant tracks the state of whether all the *original* phi operands
Davide Italiano839c7e62017-05-02 21:11:40 +00001443 // were constant. This is really shorthand for "this phi cannot cycle due
1444 // to forward propagation", as any change in value of the phi is guaranteed
1445 // not to later change the value of the phi.
Daniel Berlin2f72b192017-04-14 02:53:37 +00001446 // IE it can't be v = phi(undef, v+1)
1447 bool AllConstant = true;
1448 auto *E =
1449 cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001450 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001451 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001452 // We track if any were undef because they need special handling.
1453 bool HasUndef = false;
1454 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1455 if (Arg == I)
1456 return false;
1457 if (isa<UndefValue>(Arg)) {
1458 HasUndef = true;
1459 return false;
1460 }
1461 return true;
1462 });
1463 // If we are left with no operands, it's undef
1464 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001465 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1466 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001467 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001468 return createConstantExpression(UndefValue::get(I->getType()));
1469 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001470 unsigned NumOps = 0;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001471 Value *AllSameValue = *(Filtered.begin());
1472 ++Filtered.begin();
1473 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berlin2f72b192017-04-14 02:53:37 +00001474 if (llvm::all_of(Filtered, [AllSameValue, &NumOps](const Value *V) {
1475 ++NumOps;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001476 return V == AllSameValue;
1477 })) {
1478 // In LLVM's non-standard representation of phi nodes, it's possible to have
1479 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1480 // on the original phi node), especially in weird CFG's where some arguments
1481 // are unreachable, or uninitialized along certain paths. This can cause
1482 // infinite loops during evaluation. We work around this by not trying to
1483 // really evaluate them independently, but instead using a variable
1484 // expression to say if one is equivalent to the other.
1485 // We also special case undef, so that if we have an undef, we can't use the
1486 // common value unless it dominates the phi block.
1487 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001488 // If we have undef and at least one other value, this is really a
1489 // multivalued phi, and we need to know if it's cycle free in order to
1490 // evaluate whether we can ignore the undef. The other parts of this are
1491 // just shortcuts. If there is no backedge, or all operands are
1492 // constants, or all operands are ignored but the undef, it also must be
1493 // cycle free.
1494 if (!AllConstant && HasBackedge && NumOps > 0 &&
1495 !isa<UndefValue>(AllSameValue) && !isCycleFree(cast<PHINode>(I)))
1496 return E;
1497
Daniel Berlind92e7f92017-01-07 00:01:42 +00001498 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001499 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001500 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001501 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001502 }
1503
Davide Italiano7e274e02016-12-22 16:03:48 +00001504 NumGVNPhisAllSame++;
1505 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1506 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001507 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001508 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001509 }
1510 return E;
1511}
1512
Daniel Berlin97718e62017-01-31 22:32:03 +00001513const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001514 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1515 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1516 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1517 unsigned Opcode = 0;
1518 // EI might be an extract from one of our recognised intrinsics. If it
1519 // is we'll synthesize a semantically equivalent expression instead on
1520 // an extract value expression.
1521 switch (II->getIntrinsicID()) {
1522 case Intrinsic::sadd_with_overflow:
1523 case Intrinsic::uadd_with_overflow:
1524 Opcode = Instruction::Add;
1525 break;
1526 case Intrinsic::ssub_with_overflow:
1527 case Intrinsic::usub_with_overflow:
1528 Opcode = Instruction::Sub;
1529 break;
1530 case Intrinsic::smul_with_overflow:
1531 case Intrinsic::umul_with_overflow:
1532 Opcode = Instruction::Mul;
1533 break;
1534 default:
1535 break;
1536 }
1537
1538 if (Opcode != 0) {
1539 // Intrinsic recognized. Grab its args to finish building the
1540 // expression.
1541 assert(II->getNumArgOperands() == 2 &&
1542 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001543 return createBinaryExpression(
1544 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001545 }
1546 }
1547 }
1548
Daniel Berlin97718e62017-01-31 22:32:03 +00001549 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001550}
Daniel Berlin97718e62017-01-31 22:32:03 +00001551const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001552 auto *CI = dyn_cast<CmpInst>(I);
1553 // See if our operands are equal to those of a previous predicate, and if so,
1554 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001555 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1556 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001557 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001558 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001559 std::swap(Op0, Op1);
1560 OurPredicate = CI->getSwappedPredicate();
1561 }
1562
1563 // Avoid processing the same info twice
1564 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001565 // See if we know something about the comparison itself, like it is the target
1566 // of an assume.
1567 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1568 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1569 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1570
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001571 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001572 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001573 if (CI->isTrueWhenEqual())
1574 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1575 else if (CI->isFalseWhenEqual())
1576 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1577 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001578
1579 // NOTE: Because we are comparing both operands here and below, and using
1580 // previous comparisons, we rely on fact that predicateinfo knows to mark
1581 // comparisons that use renamed operands as users of the earlier comparisons.
1582 // It is *not* enough to just mark predicateinfo renamed operands as users of
1583 // the earlier comparisons, because the *other* operand may have changed in a
1584 // previous iteration.
1585 // Example:
1586 // icmp slt %a, %b
1587 // %b.0 = ssa.copy(%b)
1588 // false branch:
1589 // icmp slt %c, %b.0
1590
1591 // %c and %a may start out equal, and thus, the code below will say the second
1592 // %icmp is false. c may become equal to something else, and in that case the
1593 // %second icmp *must* be reexamined, but would not if only the renamed
1594 // %operands are considered users of the icmp.
1595
1596 // *Currently* we only check one level of comparisons back, and only mark one
1597 // level back as touched when changes appen . If you modify this code to look
1598 // back farther through comparisons, you *must* mark the appropriate
1599 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1600 // we know something just from the operands themselves
1601
1602 // See if our operands have predicate info, so that we may be able to derive
1603 // something from a previous comparison.
1604 for (const auto &Op : CI->operands()) {
1605 auto *PI = PredInfo->getPredicateInfoFor(Op);
1606 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1607 if (PI == LastPredInfo)
1608 continue;
1609 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001610
Daniel Berlinf7d95802017-02-18 23:06:50 +00001611 // TODO: Along the false edge, we may know more things too, like icmp of
1612 // same operands is false.
1613 // TODO: We only handle actual comparison conditions below, not and/or.
1614 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1615 if (!BranchCond)
1616 continue;
1617 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1618 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1619 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001620 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001621 std::swap(BranchOp0, BranchOp1);
1622 BranchPredicate = BranchCond->getSwappedPredicate();
1623 }
1624 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1625 if (PBranch->TrueEdge) {
1626 // If we know the previous predicate is true and we are in the true
1627 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001628 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1629 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001630 addPredicateUsers(PI, I);
1631 return createConstantExpression(
1632 ConstantInt::getTrue(CI->getType()));
1633 }
1634
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001635 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1636 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001637 addPredicateUsers(PI, I);
1638 return createConstantExpression(
1639 ConstantInt::getFalse(CI->getType()));
1640 }
1641
1642 } else {
1643 // Just handle the ne and eq cases, where if we have the same
1644 // operands, we may know something.
1645 if (BranchPredicate == OurPredicate) {
1646 addPredicateUsers(PI, I);
1647 // Same predicate, same ops,we know it was false, so this is false.
1648 return createConstantExpression(
1649 ConstantInt::getFalse(CI->getType()));
1650 } else if (BranchPredicate ==
1651 CmpInst::getInversePredicate(OurPredicate)) {
1652 addPredicateUsers(PI, I);
1653 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001654 return createConstantExpression(
1655 ConstantInt::getTrue(CI->getType()));
1656 }
1657 }
1658 }
1659 }
1660 }
1661 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001662 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001663}
Davide Italiano7e274e02016-12-22 16:03:48 +00001664
1665// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001666const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001667 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001668 if (auto *C = dyn_cast<Constant>(V))
1669 E = createConstantExpression(C);
1670 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1671 E = createVariableExpression(V);
1672 } else {
1673 // TODO: memory intrinsics.
1674 // TODO: Some day, we should do the forward propagation and reassociation
1675 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001676 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001677 switch (I->getOpcode()) {
1678 case Instruction::ExtractValue:
1679 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001680 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001681 break;
1682 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001683 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001684 break;
1685 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001686 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001687 break;
1688 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001689 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001690 break;
1691 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001692 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001693 break;
1694 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001695 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001696 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001697 case Instruction::ICmp:
1698 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001699 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001700 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001701 case Instruction::Add:
1702 case Instruction::FAdd:
1703 case Instruction::Sub:
1704 case Instruction::FSub:
1705 case Instruction::Mul:
1706 case Instruction::FMul:
1707 case Instruction::UDiv:
1708 case Instruction::SDiv:
1709 case Instruction::FDiv:
1710 case Instruction::URem:
1711 case Instruction::SRem:
1712 case Instruction::FRem:
1713 case Instruction::Shl:
1714 case Instruction::LShr:
1715 case Instruction::AShr:
1716 case Instruction::And:
1717 case Instruction::Or:
1718 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001719 case Instruction::Trunc:
1720 case Instruction::ZExt:
1721 case Instruction::SExt:
1722 case Instruction::FPToUI:
1723 case Instruction::FPToSI:
1724 case Instruction::UIToFP:
1725 case Instruction::SIToFP:
1726 case Instruction::FPTrunc:
1727 case Instruction::FPExt:
1728 case Instruction::PtrToInt:
1729 case Instruction::IntToPtr:
1730 case Instruction::Select:
1731 case Instruction::ExtractElement:
1732 case Instruction::InsertElement:
1733 case Instruction::ShuffleVector:
1734 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001735 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001736 break;
1737 default:
1738 return nullptr;
1739 }
1740 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001741 return E;
1742}
1743
Davide Italiano7e274e02016-12-22 16:03:48 +00001744void NewGVN::markUsersTouched(Value *V) {
1745 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001746 for (auto *User : V->users()) {
1747 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001748 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001749 }
1750}
1751
Daniel Berlin1316a942017-04-06 18:52:50 +00001752void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) {
1753 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1754 MemoryToUsers[To].insert(U);
1755}
1756
1757void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001758 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00001759}
1760
1761void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1762 if (isa<MemoryUse>(MA))
1763 return;
1764 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00001765 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin1316a942017-04-06 18:52:50 +00001766 const auto Result = MemoryToUsers.find(MA);
1767 if (Result != MemoryToUsers.end()) {
1768 for (auto *User : Result->second)
Daniel Berlin21279bd2017-04-06 18:52:58 +00001769 TouchedInstructions.set(MemoryToDFSNum(User));
Daniel Berlin1316a942017-04-06 18:52:50 +00001770 MemoryToUsers.erase(Result);
Davide Italiano7e274e02016-12-22 16:03:48 +00001771 }
1772}
1773
Daniel Berlinf7d95802017-02-18 23:06:50 +00001774// Add I to the set of users of a given predicate.
1775void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1776 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1777 PredicateToUsers[PBranch->Condition].insert(I);
1778 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1779 PredicateToUsers[PAssume->Condition].insert(I);
1780}
1781
1782// Touch all the predicates that depend on this instruction.
1783void NewGVN::markPredicateUsersTouched(Instruction *I) {
1784 const auto Result = PredicateToUsers.find(I);
Daniel Berlin46b72e62017-03-19 00:07:32 +00001785 if (Result != PredicateToUsers.end()) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001786 for (auto *User : Result->second)
Daniel Berlin21279bd2017-04-06 18:52:58 +00001787 TouchedInstructions.set(InstrToDFSNum(User));
Daniel Berlin46b72e62017-03-19 00:07:32 +00001788 PredicateToUsers.erase(Result);
1789 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001790}
1791
Daniel Berlin1316a942017-04-06 18:52:50 +00001792// Mark users affected by a memory leader change.
1793void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001794 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00001795 markMemoryDefTouched(M);
1796}
1797
Daniel Berlin32f8d562017-01-07 16:55:14 +00001798// Touch the instructions that need to be updated after a congruence class has a
1799// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00001800void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001801 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001802 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00001803 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001804 LeaderChanges.insert(M);
1805 }
1806}
1807
Daniel Berlin1316a942017-04-06 18:52:50 +00001808// Give a range of things that have instruction DFS numbers, this will return
1809// the member of the range with the smallest dfs number.
1810template <class T, class Range>
1811T *NewGVN::getMinDFSOfRange(const Range &R) const {
1812 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
1813 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001814 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00001815 if (DFSNum < MinDFS.second)
1816 MinDFS = {X, DFSNum};
1817 }
1818 return MinDFS.first;
1819}
1820
1821// This function returns the MemoryAccess that should be the next leader of
1822// congruence class CC, under the assumption that the current leader is going to
1823// disappear.
1824const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
1825 // TODO: If this ends up to slow, we can maintain a next memory leader like we
1826 // do for regular leaders.
1827 // Make sure there will be a leader to find
Davide Italianof58a30232017-04-10 23:08:35 +00001828 assert((CC->getStoreCount() > 0 || !CC->memory_empty()) &&
1829 "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00001830 if (CC->getStoreCount() > 0) {
1831 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlin1316a942017-04-06 18:52:50 +00001832 return MSSA->getMemoryAccess(NL);
1833 // Find the store with the minimum DFS number.
1834 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00001835 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlin1316a942017-04-06 18:52:50 +00001836 return MSSA->getMemoryAccess(cast<StoreInst>(V));
1837 }
Daniel Berlina8236562017-04-07 18:38:09 +00001838 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001839
1840 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00001841 // !OldClass->memory_empty()
1842 if (CC->memory_size() == 1)
1843 return *CC->memory_begin();
1844 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00001845}
1846
1847// This function returns the next value leader of a congruence class, under the
1848// assumption that the current leader is going away. This should end up being
1849// the next most dominating member.
1850Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
1851 // We don't need to sort members if there is only 1, and we don't care about
1852 // sorting the TOP class because everything either gets out of it or is
1853 // unreachable.
1854
Daniel Berlina8236562017-04-07 18:38:09 +00001855 if (CC->size() == 1 || CC == TOPClass) {
1856 return *(CC->begin());
1857 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001858 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00001859 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00001860 } else {
1861 ++NumGVNSortedLeaderChanges;
1862 // NOTE: If this ends up to slow, we can maintain a dual structure for
1863 // member testing/insertion, or keep things mostly sorted, and sort only
1864 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00001865 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00001866 }
1867}
1868
1869// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
1870// the memory members, etc for the move.
1871//
1872// The invariants of this function are:
1873//
1874// I must be moving to NewClass from OldClass The StoreCount of OldClass and
1875// NewClass is expected to have been updated for I already if it is is a store.
1876// The OldClass memory leader has not been updated yet if I was the leader.
1877void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
1878 MemoryAccess *InstMA,
1879 CongruenceClass *OldClass,
1880 CongruenceClass *NewClass) {
1881 // If the leader is I, and we had a represenative MemoryAccess, it should
1882 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00001883 assert((!InstMA || !OldClass->getMemoryLeader() ||
1884 OldClass->getLeader() != I ||
1885 OldClass->getMemoryLeader() == InstMA) &&
1886 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00001887 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00001888 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001889 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00001890 assert(NewClass->size() == 1 ||
1891 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
1892 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00001893 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00001894 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00001895 << " due to new memory instruction becoming leader\n");
1896 markMemoryLeaderChangeTouched(NewClass);
1897 }
1898 setMemoryClass(InstMA, NewClass);
1899 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00001900 if (OldClass->getMemoryLeader() == InstMA) {
1901 if (OldClass->getStoreCount() != 0 || !OldClass->memory_empty()) {
1902 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1903 DEBUG(dbgs() << "Memory class leader change for class "
1904 << OldClass->getID() << " to "
1905 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001906 << " due to removal of old leader " << *InstMA << "\n");
1907 markMemoryLeaderChangeTouched(OldClass);
1908 } else
Daniel Berlina8236562017-04-07 18:38:09 +00001909 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001910 }
1911}
1912
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001913// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00001914// Update OldClass and NewClass for the move (including changing leaders, etc).
1915void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001916 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001917 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00001918 if (I == OldClass->getNextLeader().first)
1919 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001920
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001921 // It's possible, though unlikely, for us to discover equivalences such
1922 // that the current leader does not dominate the old one.
1923 // This statistic tracks how often this happens.
1924 // We assert on phi nodes when this happens, currently, for debugging, because
1925 // we want to make sure we name phi node cycles properly.
Daniel Berlina8236562017-04-07 18:38:09 +00001926 if (isa<Instruction>(NewClass->getLeader()) && NewClass->getLeader() &&
1927 I != NewClass->getLeader()) {
Daniel Berlinffc30782017-03-24 06:33:51 +00001928 auto *IBB = I->getParent();
Daniel Berlina8236562017-04-07 18:38:09 +00001929 auto *NCBB = cast<Instruction>(NewClass->getLeader())->getParent();
Daniel Berlin21279bd2017-04-06 18:52:58 +00001930 bool Dominated =
Daniel Berlina8236562017-04-07 18:38:09 +00001931 IBB == NCBB && InstrToDFSNum(I) < InstrToDFSNum(NewClass->getLeader());
Daniel Berlinffc30782017-03-24 06:33:51 +00001932 Dominated = Dominated || DT->properlyDominates(IBB, NCBB);
1933 if (Dominated) {
1934 ++NumGVNNotMostDominatingLeader;
1935 assert(
1936 !isa<PHINode>(I) &&
1937 "New class for instruction should not be dominated by instruction");
1938 }
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001939 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001940
Daniel Berlina8236562017-04-07 18:38:09 +00001941 if (NewClass->getLeader() != I)
1942 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001943
Daniel Berlina8236562017-04-07 18:38:09 +00001944 OldClass->erase(I);
1945 NewClass->insert(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00001946 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001947 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001948 OldClass->decStoreCount();
1949 // Okay, so when do we want to make a store a leader of a class?
1950 // If we have a store defined by an earlier load, we want the earlier load
1951 // to lead the class.
1952 // If we have a store defined by something else, we want the store to lead
1953 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00001954 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00001955 // as the leader
1956 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001957 // If it's a store expression we are using, it means we are not equivalent
1958 // to something earlier.
1959 if (isa<StoreExpression>(E)) {
1960 assert(lookupOperandLeader(SI->getValueOperand()) !=
Daniel Berlina8236562017-04-07 18:38:09 +00001961 NewClass->getLeader());
1962 NewClass->setStoredValue(lookupOperandLeader(SI->getValueOperand()));
Daniel Berlin1316a942017-04-06 18:52:50 +00001963 markValueLeaderChangeTouched(NewClass);
1964 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00001965 DEBUG(dbgs() << "Changing leader of congruence class "
1966 << NewClass->getID() << " from " << *NewClass->getLeader()
1967 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00001968 // If we changed the leader, we have to mark it changed because we don't
1969 // know what it will do to symbolic evlauation.
Daniel Berlina8236562017-04-07 18:38:09 +00001970 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001971 }
1972 // We rely on the code below handling the MemoryAccess change.
1973 }
Daniel Berlina8236562017-04-07 18:38:09 +00001974 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001975 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001976 // True if there is no memory instructions left in a class that had memory
1977 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001978
Daniel Berlin1316a942017-04-06 18:52:50 +00001979 // If it's not a memory use, set the MemoryAccess equivalence
1980 auto *InstMA = dyn_cast_or_null<MemoryDef>(MSSA->getMemoryAccess(I));
Daniel Berlina8236562017-04-07 18:38:09 +00001981 bool InstWasMemoryLeader = InstMA && OldClass->getMemoryLeader() == InstMA;
Daniel Berlin1316a942017-04-06 18:52:50 +00001982 if (InstMA)
1983 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001984 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001985 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00001986 if (OldClass->empty() && OldClass != TOPClass) {
1987 if (OldClass->getDefiningExpr()) {
1988 DEBUG(dbgs() << "Erasing expression " << OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001989 << " from table\n");
Daniel Berlina8236562017-04-07 18:38:09 +00001990 ExpressionToClass.erase(OldClass->getDefiningExpr());
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001991 }
Daniel Berlina8236562017-04-07 18:38:09 +00001992 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001993 // When the leader changes, the value numbering of
1994 // everything may change due to symbolization changes, so we need to
1995 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00001996 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00001997 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001998 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001999 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002000 // Note that this is basically clean up for the expression removal that
2001 // happens below. If we remove stores from a class, we may leave it as a
2002 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002003 if (OldClass->getStoreCount() == 0) {
2004 if (OldClass->getStoredValue())
2005 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002006 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002007 // If we destroy the old access leader and it's a store, we have to
2008 // effectively destroy the congruence class. When it comes to scalars,
2009 // anything with the same value is as good as any other. That means that
2010 // one leader is as good as another, and as long as you have some leader for
2011 // the value, you are good.. When it comes to *memory states*, only one
2012 // particular thing really represents the definition of a given memory
2013 // state. Once it goes away, we need to re-evaluate which pieces of memory
2014 // are really still equivalent. The best way to do this is to re-value
2015 // number things. The only way to really make that happen is to destroy the
2016 // rest of the class. In order to effectively destroy the class, we reset
2017 // ExpressionToClass for each by using the ValueToExpression mapping. The
2018 // members later get marked as touched due to the leader change. We will
2019 // create new congruence classes, and the pieces that are still equivalent
2020 // will end back together in a new class. If this becomes too expensive, it
2021 // is possible to use a versioning scheme for the congruence classes to
2022 // avoid the expressions finding this old class. Note that the situation is
2023 // different for memory phis, becuase they are evaluated anew each time, and
2024 // they become equal not by hashing, but by seeing if all operands are the
2025 // same (or only one is reachable).
Daniel Berlina8236562017-04-07 18:38:09 +00002026 if (OldClass->getStoreCount() > 0 && InstWasMemoryLeader) {
2027 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002028 << " because MemoryAccess leader changed");
Daniel Berlina8236562017-04-07 18:38:09 +00002029 for (auto Member : *OldClass)
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002030 ExpressionToClass.erase(ValueToExpression.lookup(Member));
2031 }
Daniel Berlina8236562017-04-07 18:38:09 +00002032 OldClass->setLeader(getNextValueLeader(OldClass));
2033 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002034 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002035 }
2036}
2037
Davide Italiano7e274e02016-12-22 16:03:48 +00002038// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002039void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
2040 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002041 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002042 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002043
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002044 CongruenceClass *IClass = ValueToClass[I];
2045 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002046 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002047 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002048
2049 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00002050 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002051 EClass = ValueToClass[VE->getVariableValue()];
2052 } else {
2053 auto lookupResult = ExpressionToClass.insert({E, nullptr});
2054
2055 // If it's not in the value table, create a new congruence class.
2056 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002057 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002058 auto place = lookupResult.first;
2059 place->second = NewClass;
2060
2061 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002062 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002063 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002064 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2065 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002066 NewClass->setLeader(SI);
2067 NewClass->setStoredValue(lookupOperandLeader(SI->getValueOperand()));
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002068 // The RepMemoryAccess field will be filled in properly by the
2069 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002070 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002071 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002072 }
2073 assert(!isa<VariableExpression>(E) &&
2074 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002075
2076 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002077 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002078 << " using expression " << *E << " at " << NewClass->getID()
2079 << " and leader " << *(NewClass->getLeader()));
2080 if (NewClass->getStoredValue())
2081 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002082 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002083 } else {
2084 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002085 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002086 assert((isa<Constant>(EClass->getLeader()) ||
2087 (EClass->getStoredValue() &&
2088 isa<Constant>(EClass->getStoredValue()))) &&
2089 "Any class with a constant expression should have a "
2090 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002091
Davide Italiano7e274e02016-12-22 16:03:48 +00002092 assert(EClass && "Somehow don't have an eclass");
2093
Daniel Berlin1316a942017-04-06 18:52:50 +00002094 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002095 }
2096 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002097 bool ClassChanged = IClass != EClass;
2098 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002099 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002100 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002101 << "\n");
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002102 if (ClassChanged)
Daniel Berlin1316a942017-04-06 18:52:50 +00002103 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002104 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002105 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002106 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002107 if (auto *CI = dyn_cast<CmpInst>(I))
2108 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002109 }
2110}
2111
2112// Process the fact that Edge (from, to) is reachable, including marking
2113// any newly reachable blocks and instructions for processing.
2114void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2115 // Check if the Edge was reachable before.
2116 if (ReachableEdges.insert({From, To}).second) {
2117 // If this block wasn't reachable before, all instructions are touched.
2118 if (ReachableBlocks.insert(To).second) {
2119 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2120 const auto &InstRange = BlockInstRange.lookup(To);
2121 TouchedInstructions.set(InstRange.first, InstRange.second);
2122 } else {
2123 DEBUG(dbgs() << "Block " << getBlockName(To)
2124 << " was reachable, but new edge {" << getBlockName(From)
2125 << "," << getBlockName(To) << "} to it found\n");
2126
2127 // We've made an edge reachable to an existing block, which may
2128 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2129 // they are the only thing that depend on new edges. Anything using their
2130 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00002131 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002132 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002133
Davide Italiano7e274e02016-12-22 16:03:48 +00002134 auto BI = To->begin();
2135 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002136 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002137 ++BI;
2138 }
2139 }
2140 }
2141}
2142
2143// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2144// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002145Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002146 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002147 if (isa<Constant>(Result))
2148 return Result;
2149 return nullptr;
2150}
2151
2152// Process the outgoing edges of a block for reachability.
2153void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2154 // Evaluate reachability of terminator instruction.
2155 BranchInst *BR;
2156 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2157 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002158 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002159 if (!CondEvaluated) {
2160 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002161 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002162 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2163 CondEvaluated = CE->getConstantValue();
2164 }
2165 } else if (isa<ConstantInt>(Cond)) {
2166 CondEvaluated = Cond;
2167 }
2168 }
2169 ConstantInt *CI;
2170 BasicBlock *TrueSucc = BR->getSuccessor(0);
2171 BasicBlock *FalseSucc = BR->getSuccessor(1);
2172 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2173 if (CI->isOne()) {
2174 DEBUG(dbgs() << "Condition for Terminator " << *TI
2175 << " evaluated to true\n");
2176 updateReachableEdge(B, TrueSucc);
2177 } else if (CI->isZero()) {
2178 DEBUG(dbgs() << "Condition for Terminator " << *TI
2179 << " evaluated to false\n");
2180 updateReachableEdge(B, FalseSucc);
2181 }
2182 } else {
2183 updateReachableEdge(B, TrueSucc);
2184 updateReachableEdge(B, FalseSucc);
2185 }
2186 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2187 // For switches, propagate the case values into the case
2188 // destinations.
2189
2190 // Remember how many outgoing edges there are to every successor.
2191 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2192
Davide Italiano7e274e02016-12-22 16:03:48 +00002193 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002194 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002195 // See if we were able to turn this switch statement into a constant.
2196 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002197 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002198 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002199 auto Case = *SI->findCaseValue(CondVal);
2200 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002201 // We proved the value is outside of the range of the case.
2202 // We can't do anything other than mark the default dest as reachable,
2203 // and go home.
2204 updateReachableEdge(B, SI->getDefaultDest());
2205 return;
2206 }
2207 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002208 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002209 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002210 } else {
2211 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2212 BasicBlock *TargetBlock = SI->getSuccessor(i);
2213 ++SwitchEdges[TargetBlock];
2214 updateReachableEdge(B, TargetBlock);
2215 }
2216 }
2217 } else {
2218 // Otherwise this is either unconditional, or a type we have no
2219 // idea about. Just mark successors as reachable.
2220 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2221 BasicBlock *TargetBlock = TI->getSuccessor(i);
2222 updateReachableEdge(B, TargetBlock);
2223 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002224
2225 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002226 // equivalent only to itself.
2227 //
2228 auto *MA = MSSA->getMemoryAccess(TI);
2229 if (MA && !isa<MemoryUse>(MA)) {
2230 auto *CC = ensureLeaderOfMemoryClass(MA);
2231 if (setMemoryClass(MA, CC))
2232 markMemoryUsersTouched(MA);
2233 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002234 }
2235}
2236
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002237// The algorithm initially places the values of the routine in the TOP
2238// congruence class. The leader of TOP is the undetermined value `undef`.
2239// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002240void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002241 NextCongruenceNum = 0;
2242
2243 // Note that even though we use the live on entry def as a representative
2244 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2245 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2246 // should be checking whether the MemoryAccess is top if we want to know if it
2247 // is equivalent to everything. Otherwise, what this really signifies is that
2248 // the access "it reaches all the way back to the beginning of the function"
2249
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002250 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002251 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002252 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002253 // The live on entry def gets put into it's own class
2254 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2255 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002256
Daniel Berlinec9deb72017-04-18 17:06:11 +00002257 for (auto DTN : nodes(DT)) {
2258 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002259 // All MemoryAccesses are equivalent to live on entry to start. They must
2260 // be initialized to something so that initial changes are noticed. For
2261 // the maximal answer, we initialize them all to be the same as
2262 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002263 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002264 if (MemoryBlockDefs)
2265 for (const auto &Def : *MemoryBlockDefs) {
2266 MemoryAccessToClass[&Def] = TOPClass;
2267 auto *MD = dyn_cast<MemoryDef>(&Def);
2268 // Insert the memory phis into the member list.
2269 if (!MD) {
2270 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002271 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002272 MemoryPhiState.insert({MP, MPS_TOP});
2273 }
2274
2275 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002276 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002277 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002278 for (auto &I : *BB) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00002279 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002280 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002281 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2282 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002283 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002284 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002285 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002286 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002287
2288 // Initialize arguments to be in their own unique congruence classes
2289 for (auto &FA : F.args())
2290 createSingletonCongruenceClass(&FA);
2291}
2292
2293void NewGVN::cleanupTables() {
2294 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002295 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2296 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002297 // Make sure we delete the congruence class (probably worth switching to
2298 // a unique_ptr at some point.
2299 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002300 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002301 }
2302
2303 ValueToClass.clear();
2304 ArgRecycler.clear(ExpressionAllocator);
2305 ExpressionAllocator.Reset();
2306 CongruenceClasses.clear();
2307 ExpressionToClass.clear();
2308 ValueToExpression.clear();
2309 ReachableBlocks.clear();
2310 ReachableEdges.clear();
2311#ifndef NDEBUG
2312 ProcessedCount.clear();
2313#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002314 InstrDFS.clear();
2315 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002316 DFSToInstr.clear();
2317 BlockInstRange.clear();
2318 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002319 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002320 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002321 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002322}
2323
2324std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2325 unsigned Start) {
2326 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002327 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
2328 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002329 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002330 }
2331
Davide Italiano7e274e02016-12-22 16:03:48 +00002332 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002333 // There's no need to call isInstructionTriviallyDead more than once on
2334 // an instruction. Therefore, once we know that an instruction is dead
2335 // we change its DFS number so that it doesn't get value numbered.
2336 if (isInstructionTriviallyDead(&I, TLI)) {
2337 InstrDFS[&I] = 0;
2338 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2339 markInstructionForDeletion(&I);
2340 continue;
2341 }
2342
Davide Italiano7e274e02016-12-22 16:03:48 +00002343 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002344 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002345 }
2346
2347 // All of the range functions taken half-open ranges (open on the end side).
2348 // So we do not subtract one from count, because at this point it is one
2349 // greater than the last instruction.
2350 return std::make_pair(Start, End);
2351}
2352
2353void NewGVN::updateProcessedCount(Value *V) {
2354#ifndef NDEBUG
2355 if (ProcessedCount.count(V) == 0) {
2356 ProcessedCount.insert({V, 1});
2357 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002358 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002359 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002360 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002361 }
2362#endif
2363}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002364// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2365void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2366 // If all the arguments are the same, the MemoryPhi has the same value as the
2367 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00002368 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00002369 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002370 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002371 return lookupMemoryLeader(cast<MemoryAccess>(U)) != MP &&
Daniel Berlinc4796862017-01-27 02:37:11 +00002372 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002373 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002374 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002375 // If all that is left is nothing, our memoryphi is undef. We keep it as
2376 // InitialClass. Note: The only case this should happen is if we have at
2377 // least one self-argument.
2378 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002379 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002380 markMemoryUsersTouched(MP);
2381 return;
2382 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002383
2384 // Transform the remaining operands into operand leaders.
2385 // FIXME: mapped_iterator should have a range version.
2386 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002387 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002388 };
2389 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2390 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2391
2392 // and now check if all the elements are equal.
2393 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002394 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002395 ++MappedBegin;
2396 bool AllEqual = std::all_of(
2397 MappedBegin, MappedEnd,
2398 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2399
2400 if (AllEqual)
2401 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2402 else
2403 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002404 // If it's equal to something, it's in that class. Otherwise, it has to be in
2405 // a class where it is the leader (other things may be equivalent to it, but
2406 // it needs to start off in its own class, which means it must have been the
2407 // leader, and it can't have stopped being the leader because it was never
2408 // removed).
2409 CongruenceClass *CC =
2410 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2411 auto OldState = MemoryPhiState.lookup(MP);
2412 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2413 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2414 MemoryPhiState[MP] = NewState;
2415 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002416 markMemoryUsersTouched(MP);
2417}
2418
2419// Value number a single instruction, symbolically evaluating, performing
2420// congruence finding, and updating mappings.
2421void NewGVN::valueNumberInstruction(Instruction *I) {
2422 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002423 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002424 const Expression *Symbolized = nullptr;
2425 if (DebugCounter::shouldExecute(VNCounter)) {
2426 Symbolized = performSymbolicEvaluation(I);
2427 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002428 // Mark the instruction as unused so we don't value number it again.
2429 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002430 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002431 // If we couldn't come up with a symbolic expression, use the unknown
2432 // expression
Daniel Berlin1316a942017-04-06 18:52:50 +00002433 if (Symbolized == nullptr) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002434 Symbolized = createUnknownExpression(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00002435 }
2436
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002437 performCongruenceFinding(I, Symbolized);
2438 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002439 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002440 // don't currently understand. We don't place non-value producing
2441 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002442 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002443 auto *Symbolized = createUnknownExpression(I);
2444 performCongruenceFinding(I, Symbolized);
2445 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002446 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2447 }
2448}
Davide Italiano7e274e02016-12-22 16:03:48 +00002449
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002450// Check if there is a path, using single or equal argument phi nodes, from
2451// First to Second.
2452bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
2453 const MemoryAccess *Second) const {
2454 if (First == Second)
2455 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002456 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002457 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002458
Daniel Berlin871ecd92017-04-01 09:44:24 +00002459 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002460 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002461 if (ChainDef == Second)
2462 return true;
2463 if (MSSA->isLiveOnEntryDef(ChainDef))
2464 return false;
2465 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002466 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002467 auto *MP = cast<MemoryPhi>(EndDef);
2468 auto ReachableOperandPred = [&](const Use &U) {
2469 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2470 };
2471 auto FilteredPhiArgs =
2472 make_filter_range(MP->operands(), ReachableOperandPred);
2473 SmallVector<const Value *, 32> OperandList;
2474 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2475 std::back_inserter(OperandList));
2476 bool Okay = OperandList.size() == 1;
2477 if (!Okay)
2478 Okay =
2479 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2480 if (Okay)
2481 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
2482 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002483}
2484
Daniel Berlin589cecc2017-01-02 18:00:46 +00002485// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002486// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002487// subject to very rare false negatives. It is only useful for
2488// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002489void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002490#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002491 // Verify that the memory table equivalence and memory member set match
2492 for (const auto *CC : CongruenceClasses) {
2493 if (CC == TOPClass || CC->isDead())
2494 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002495 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00002496 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002497 "Any class with a store as a leader should have a "
2498 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00002499 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002500 "Any congruence class with a store should have a "
2501 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00002502 }
2503
Daniel Berlina8236562017-04-07 18:38:09 +00002504 if (CC->getMemoryLeader())
2505 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00002506 "Representative MemoryAccess does not appear to be reverse "
2507 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00002508 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002509 assert(MemoryAccessToClass.lookup(M) == CC &&
2510 "Memory member does not appear to be reverse mapped properly");
2511 }
2512
2513 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002514 // congruence class.
2515
2516 // Filter out the unreachable and trivially dead entries, because they may
2517 // never have been updated if the instructions were not processed.
2518 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002519 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002520 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00002521 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2522 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00002523 return false;
2524 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2525 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
2526 return true;
2527 };
2528
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002529 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002530 for (auto KV : Filtered) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002531 assert(KV.second != TOPClass &&
2532 "Memory not unreachable but ended up in TOP");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002533 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002534 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italiano67ada752017-01-02 19:03:16 +00002535 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00002536 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002537 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2538 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2539 "The instructions for these memory operations should have "
2540 "been in the same congruence class or reachable through"
2541 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002542 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002543 // We can only sanely verify that MemoryDefs in the operand list all have
2544 // the same class.
2545 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002546 return ReachableEdges.count(
2547 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002548 isa<MemoryDef>(U);
2549
2550 };
2551 // All arguments should in the same class, ignoring unreachable arguments
2552 auto FilteredPhiArgs =
2553 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2554 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2555 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2556 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2557 const MemoryDef *MD = cast<MemoryDef>(U);
2558 return ValueToClass.lookup(MD->getMemoryInst());
2559 });
2560 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2561 PhiOpClasses.begin()) &&
2562 "All MemoryPhi arguments should be in the same class");
2563 }
2564 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002565#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002566}
2567
Daniel Berlin06329a92017-03-18 15:41:40 +00002568// Verify that the sparse propagation we did actually found the maximal fixpoint
2569// We do this by storing the value to class mapping, touching all instructions,
2570// and redoing the iteration to see if anything changed.
2571void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002572#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002573 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002574 if (DebugCounter::isCounterSet(VNCounter))
2575 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2576
2577 // Note that we have to store the actual classes, as we may change existing
2578 // classes during iteration. This is because our memory iteration propagation
2579 // is not perfect, and so may waste a little work. But it should generate
2580 // exactly the same congruence classes we have now, with different IDs.
2581 std::map<const Value *, CongruenceClass> BeforeIteration;
2582
2583 for (auto &KV : ValueToClass) {
2584 if (auto *I = dyn_cast<Instruction>(KV.first))
2585 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002586 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002587 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002588 BeforeIteration.insert({KV.first, *KV.second});
2589 }
2590
2591 TouchedInstructions.set();
2592 TouchedInstructions.reset(0);
2593 iterateTouchedInstructions();
2594 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2595 EqualClasses;
2596 for (const auto &KV : ValueToClass) {
2597 if (auto *I = dyn_cast<Instruction>(KV.first))
2598 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002599 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00002600 continue;
2601 // We could sink these uses, but i think this adds a bit of clarity here as
2602 // to what we are comparing.
2603 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2604 auto *AfterCC = KV.second;
2605 // Note that the classes can't change at this point, so we memoize the set
2606 // that are equal.
2607 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00002608 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00002609 "Value number changed after main loop completed!");
2610 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002611 }
2612 }
2613#endif
2614}
2615
Daniel Berlin06329a92017-03-18 15:41:40 +00002616// This is the main value numbering loop, it iterates over the initial touched
2617// instruction set, propagating value numbers, marking things touched, etc,
2618// until the set of touched instructions is completely empty.
2619void NewGVN::iterateTouchedInstructions() {
2620 unsigned int Iterations = 0;
2621 // Figure out where touchedinstructions starts
2622 int FirstInstr = TouchedInstructions.find_first();
2623 // Nothing set, nothing to iterate, just return.
2624 if (FirstInstr == -1)
2625 return;
Daniel Berlin21279bd2017-04-06 18:52:58 +00002626 BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00002627 while (TouchedInstructions.any()) {
2628 ++Iterations;
2629 // Walk through all the instructions in all the blocks in RPO.
2630 // TODO: As we hit a new block, we should push and pop equalities into a
2631 // table lookupOperandLeader can use, to catch things PredicateInfo
2632 // might miss, like edge-only equivalences.
2633 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2634 InstrNum = TouchedInstructions.find_next(InstrNum)) {
2635
2636 // This instruction was found to be dead. We don't bother looking
2637 // at it again.
2638 if (InstrNum == 0) {
2639 TouchedInstructions.reset(InstrNum);
2640 continue;
2641 }
2642
Daniel Berlin21279bd2017-04-06 18:52:58 +00002643 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlin06329a92017-03-18 15:41:40 +00002644 BasicBlock *CurrBlock = getBlockForValue(V);
2645
2646 // If we hit a new block, do reachability processing.
2647 if (CurrBlock != LastBlock) {
2648 LastBlock = CurrBlock;
2649 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2650 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2651
2652 // If it's not reachable, erase any touched instructions and move on.
2653 if (!BlockReachable) {
2654 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2655 DEBUG(dbgs() << "Skipping instructions in block "
2656 << getBlockName(CurrBlock)
2657 << " because it is unreachable\n");
2658 continue;
2659 }
2660 updateProcessedCount(CurrBlock);
2661 }
2662
2663 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2664 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2665 valueNumberMemoryPhi(MP);
2666 } else if (auto *I = dyn_cast<Instruction>(V)) {
2667 valueNumberInstruction(I);
2668 } else {
2669 llvm_unreachable("Should have been a MemoryPhi or Instruction");
2670 }
2671 updateProcessedCount(V);
2672 // Reset after processing (because we may mark ourselves as touched when
2673 // we propagate equalities).
2674 TouchedInstructions.reset(InstrNum);
2675 }
2676 }
2677 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2678}
2679
Daniel Berlin85f91b02016-12-26 20:06:58 +00002680// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00002681bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00002682 if (DebugCounter::isCounterSet(VNCounter))
2683 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00002684 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00002685 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00002686 MSSAWalker = MSSA->getWalker();
2687
2688 // Count number of instructions for sizing of hash tables, and come
2689 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002690 unsigned ICount = 1;
2691 // Add an empty instruction to account for the fact that we start at 1
2692 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002693 // Note: We want ideal RPO traversal of the blocks, which is not quite the
2694 // same as dominator tree order, particularly with regard whether backedges
2695 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00002696 // If we visit in the wrong order, we will end up performing N times as many
2697 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002698 // The dominator tree does guarantee that, for a given dom tree node, it's
2699 // parent must occur before it in the RPO ordering. Thus, we only need to sort
2700 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00002701 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00002702 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002703 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002704 auto *Node = DT->getNode(B);
2705 assert(Node && "RPO and Dominator tree should have same reachability");
2706 RPOOrdering[Node] = ++Counter;
2707 }
2708 // Sort dominator tree children arrays into RPO.
2709 for (auto &B : RPOT) {
2710 auto *Node = DT->getNode(B);
2711 if (Node->getChildren().size() > 1)
2712 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00002713 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002714 return RPOOrdering[A] < RPOOrdering[B];
2715 });
2716 }
2717
2718 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002719 for (auto DTN : depth_first(DT->getRootNode())) {
2720 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00002721 const auto &BlockRange = assignDFSNumbers(B, ICount);
2722 BlockInstRange.insert({B, BlockRange});
2723 ICount += BlockRange.second - BlockRange.first;
2724 }
2725
Daniel Berline0bd37e2016-12-29 22:15:12 +00002726 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002727 // Ensure we don't end up resizing the expressionToClass map, as
2728 // that can be quite expensive. At most, we have one expression per
2729 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002730 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002731
2732 // Initialize the touched instructions to include the entry block.
2733 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2734 TouchedInstructions.set(InstRange.first, InstRange.second);
2735 ReachableBlocks.insert(&F.getEntryBlock());
2736
2737 initializeCongruenceClasses(F);
Daniel Berlin06329a92017-03-18 15:41:40 +00002738 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00002739 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00002740 verifyIterationSettled(F);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002741
Davide Italiano7e274e02016-12-22 16:03:48 +00002742 Changed |= eliminateInstructions(F);
2743
2744 // Delete all instructions marked for deletion.
2745 for (Instruction *ToErase : InstructionsToErase) {
2746 if (!ToErase->use_empty())
2747 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2748
2749 ToErase->eraseFromParent();
2750 }
2751
2752 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002753 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2754 return !ReachableBlocks.count(&BB);
2755 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002756
2757 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2758 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002759 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002760 deleteInstructionsInBlock(&BB);
2761 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002762 }
2763
2764 cleanupTables();
2765 return Changed;
2766}
2767
Davide Italiano7e274e02016-12-22 16:03:48 +00002768// Return true if V is a value that will always be available (IE can
2769// be placed anywhere) in the function. We don't do globals here
2770// because they are often worse to put in place.
2771// TODO: Separate cost from availability
2772static bool alwaysAvailable(Value *V) {
2773 return isa<Constant>(V) || isa<Argument>(V);
2774}
2775
Davide Italiano7e274e02016-12-22 16:03:48 +00002776struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002777 int DFSIn = 0;
2778 int DFSOut = 0;
2779 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002780 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002781 // The bool in the Def tells us whether the Def is the stored value of a
2782 // store.
2783 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002784 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002785 bool operator<(const ValueDFS &Other) const {
2786 // It's not enough that any given field be less than - we have sets
2787 // of fields that need to be evaluated together to give a proper ordering.
2788 // For example, if you have;
2789 // DFS (1, 3)
2790 // Val 0
2791 // DFS (1, 2)
2792 // Val 50
2793 // We want the second to be less than the first, but if we just go field
2794 // by field, we will get to Val 0 < Val 50 and say the first is less than
2795 // the second. We only want it to be less than if the DFS orders are equal.
2796 //
2797 // Each LLVM instruction only produces one value, and thus the lowest-level
2798 // differentiator that really matters for the stack (and what we use as as a
2799 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002800 // Everything else in the structure is instruction level, and only affects
2801 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002802 //
2803 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2804 // the order of replacement of uses does not matter.
2805 // IE given,
2806 // a = 5
2807 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002808 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2809 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002810 // The .val will be the same as well.
2811 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002812 // You will replace both, and it does not matter what order you replace them
2813 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2814 // operand 2).
2815 // Similarly for the case of same dfsin, dfsout, localnum, but different
2816 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002817 // a = 5
2818 // b = 6
2819 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002820 // in c, we will a valuedfs for a, and one for b,with everything the same
2821 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002822 // It does not matter what order we replace these operands in.
2823 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002824 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2825 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002826 Other.U);
2827 }
2828};
2829
Daniel Berlinc4796862017-01-27 02:37:11 +00002830// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002831// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00002832// reachable uses for each value is stored in UseCount, and instructions that
2833// seem
2834// dead (have no non-dead uses) are stored in ProbablyDead.
2835void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00002836 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00002837 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00002838 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00002839 for (auto D : Dense) {
2840 // First add the value.
2841 BasicBlock *BB = getBlockForValue(D);
2842 // Constants are handled prior to ever calling this function, so
2843 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002844 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002845 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002846 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002847 VDDef.DFSIn = DomNode->getDFSNumIn();
2848 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002849 // If it's a store, use the leader of the value operand, if it's always
2850 // available, or the value operand. TODO: We could do dominance checks to
2851 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00002852 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002853 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002854 if (alwaysAvailable(Leader)) {
2855 VDDef.Def.setPointer(Leader);
2856 } else {
2857 VDDef.Def.setPointer(SI->getValueOperand());
2858 VDDef.Def.setInt(true);
2859 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002860 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002861 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00002862 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002863 assert(isa<Instruction>(D) &&
2864 "The dense set member should always be an instruction");
Daniel Berlin21279bd2017-04-06 18:52:58 +00002865 VDDef.LocalNum = InstrToDFSNum(D);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002866 DFSOrderedSet.emplace_back(VDDef);
Daniel Berline3e69e12017-03-10 00:32:33 +00002867 Instruction *Def = cast<Instruction>(D);
2868 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002869 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00002870 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002871 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002872 // Don't try to replace into dead uses
2873 if (InstructionsToErase.count(I))
2874 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002875 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002876 // Put the phi node uses in the incoming block.
2877 BasicBlock *IBlock;
2878 if (auto *P = dyn_cast<PHINode>(I)) {
2879 IBlock = P->getIncomingBlock(U);
2880 // Make phi node users appear last in the incoming block
2881 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002882 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002883 } else {
2884 IBlock = I->getParent();
Daniel Berlin21279bd2017-04-06 18:52:58 +00002885 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002886 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002887
2888 // Skip uses in unreachable blocks, as we're going
2889 // to delete them.
2890 if (ReachableBlocks.count(IBlock) == 0)
2891 continue;
2892
Daniel Berlinb66164c2017-01-14 00:24:23 +00002893 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002894 VDUse.DFSIn = DomNode->getDFSNumIn();
2895 VDUse.DFSOut = DomNode->getDFSNumOut();
2896 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00002897 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002898 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002899 }
2900 }
Daniel Berline3e69e12017-03-10 00:32:33 +00002901
2902 // If there are no uses, it's probably dead (but it may have side-effects,
2903 // so not definitely dead. Otherwise, store the number of uses so we can
2904 // track if it becomes dead later).
2905 if (UseCount == 0)
2906 ProbablyDead.insert(Def);
2907 else
2908 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002909 }
2910}
2911
Daniel Berlinc4796862017-01-27 02:37:11 +00002912// This function converts the set of members for a congruence class from values,
2913// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00002914void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00002915 const CongruenceClass &Dense,
2916 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00002917 for (auto D : Dense) {
2918 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2919 continue;
2920
2921 BasicBlock *BB = getBlockForValue(D);
2922 ValueDFS VD;
2923 DomTreeNode *DomNode = DT->getNode(BB);
2924 VD.DFSIn = DomNode->getDFSNumIn();
2925 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002926 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00002927
2928 // If it's an instruction, use the real local dfs number.
2929 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002930 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00002931 else
2932 llvm_unreachable("Should have been an instruction");
2933
2934 LoadsAndStores.emplace_back(VD);
2935 }
2936}
2937
Davide Italiano7e274e02016-12-22 16:03:48 +00002938static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002939 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002940 if (!ReplInst)
2941 return;
2942
Davide Italiano7e274e02016-12-22 16:03:48 +00002943 // Patch the replacement so that it is not more restrictive than the value
2944 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002945 // Note that if 'I' is a load being replaced by some operation,
2946 // for example, by an arithmetic operation, then andIRFlags()
2947 // would just erase all math flags from the original arithmetic
2948 // operation, which is clearly not wanted and not needed.
2949 if (!isa<LoadInst>(I))
2950 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002951
Daniel Berlin86eab152017-02-12 22:25:20 +00002952 // FIXME: If both the original and replacement value are part of the
2953 // same control-flow region (meaning that the execution of one
2954 // guarantees the execution of the other), then we can combine the
2955 // noalias scopes here and do better than the general conservative
2956 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002957
Daniel Berlin86eab152017-02-12 22:25:20 +00002958 // In general, GVN unifies expressions over different control-flow
2959 // regions, and so we need a conservative combination of the noalias
2960 // scopes.
2961 static const unsigned KnownIDs[] = {
2962 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2963 LLVMContext::MD_noalias, LLVMContext::MD_range,
2964 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2965 LLVMContext::MD_invariant_group};
2966 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002967}
2968
2969static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2970 patchReplacementInstruction(I, Repl);
2971 I->replaceAllUsesWith(Repl);
2972}
2973
2974void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2975 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2976 ++NumGVNBlocksDeleted;
2977
Daniel Berline19f0e02017-01-30 17:06:55 +00002978 // Delete the instructions backwards, as it has a reduced likelihood of having
2979 // to update as many def-use and use-def chains. Start after the terminator.
2980 auto StartPoint = BB->rbegin();
2981 ++StartPoint;
2982 // Note that we explicitly recalculate BB->rend() on each iteration,
2983 // as it may change when we remove the first instruction.
2984 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2985 Instruction &Inst = *I++;
2986 if (!Inst.use_empty())
2987 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2988 if (isa<LandingPadInst>(Inst))
2989 continue;
2990
2991 Inst.eraseFromParent();
2992 ++NumGVNInstrDeleted;
2993 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002994 // Now insert something that simplifycfg will turn into an unreachable.
2995 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2996 new StoreInst(UndefValue::get(Int8Ty),
2997 Constant::getNullValue(Int8Ty->getPointerTo()),
2998 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002999}
3000
3001void NewGVN::markInstructionForDeletion(Instruction *I) {
3002 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3003 InstructionsToErase.insert(I);
3004}
3005
3006void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3007
3008 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3009 patchAndReplaceAllUsesWith(I, V);
3010 // We save the actual erasing to avoid invalidating memory
3011 // dependencies until we are done with everything.
3012 markInstructionForDeletion(I);
3013}
3014
3015namespace {
3016
3017// This is a stack that contains both the value and dfs info of where
3018// that value is valid.
3019class ValueDFSStack {
3020public:
3021 Value *back() const { return ValueStack.back(); }
3022 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3023
3024 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003025 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003026 DFSStack.emplace_back(DFSIn, DFSOut);
3027 }
3028 bool empty() const { return DFSStack.empty(); }
3029 bool isInScope(int DFSIn, int DFSOut) const {
3030 if (empty())
3031 return false;
3032 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3033 }
3034
3035 void popUntilDFSScope(int DFSIn, int DFSOut) {
3036
3037 // These two should always be in sync at this point.
3038 assert(ValueStack.size() == DFSStack.size() &&
3039 "Mismatch between ValueStack and DFSStack");
3040 while (
3041 !DFSStack.empty() &&
3042 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3043 DFSStack.pop_back();
3044 ValueStack.pop_back();
3045 }
3046 }
3047
3048private:
3049 SmallVector<Value *, 8> ValueStack;
3050 SmallVector<std::pair<int, int>, 8> DFSStack;
3051};
3052}
Daniel Berlin04443432017-01-07 03:23:47 +00003053
Davide Italiano7e274e02016-12-22 16:03:48 +00003054bool NewGVN::eliminateInstructions(Function &F) {
3055 // This is a non-standard eliminator. The normal way to eliminate is
3056 // to walk the dominator tree in order, keeping track of available
3057 // values, and eliminating them. However, this is mildly
3058 // pointless. It requires doing lookups on every instruction,
3059 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003060 // instructions part of most singleton congruence classes, we know we
3061 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003062
3063 // Instead, this eliminator looks at the congruence classes directly, sorts
3064 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003065 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003066 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003067 // last member. This is worst case O(E log E) where E = number of
3068 // instructions in a single congruence class. In theory, this is all
3069 // instructions. In practice, it is much faster, as most instructions are
3070 // either in singleton congruence classes or can't possibly be eliminated
3071 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003072 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003073 // for elimination purposes.
3074 // TODO: If we wanted to be faster, We could remove any members with no
3075 // overlapping ranges while sorting, as we will never eliminate anything
3076 // with those members, as they don't dominate anything else in our set.
3077
Davide Italiano7e274e02016-12-22 16:03:48 +00003078 bool AnythingReplaced = false;
3079
3080 // Since we are going to walk the domtree anyway, and we can't guarantee the
3081 // DFS numbers are updated, we compute some ourselves.
3082 DT->updateDFSNumbers();
3083
3084 for (auto &B : F) {
3085 if (!ReachableBlocks.count(&B)) {
3086 for (const auto S : successors(&B)) {
3087 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003088 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00003089 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
3090 << getBlockName(&B)
3091 << " with undef due to it being unreachable\n");
3092 for (auto &Operand : Phi.incoming_values())
3093 if (Phi.getIncomingBlock(Operand) == &B)
3094 Operand.set(UndefValue::get(Phi.getType()));
3095 }
3096 }
3097 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003098 }
3099
Daniel Berline3e69e12017-03-10 00:32:33 +00003100 // Map to store the use counts
3101 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlin4d547962017-02-12 23:24:45 +00003102 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00003103 // Track the equivalent store info so we can decide whether to try
3104 // dead store elimination.
3105 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003106 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003107 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003108 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003109 // Everything still in the TOP class is unreachable or dead.
3110 if (CC == TOPClass) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00003111#ifndef NDEBUG
Daniel Berlina8236562017-04-07 18:38:09 +00003112 for (auto M : *CC)
Daniel Berlinb79f5362017-02-11 12:48:50 +00003113 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3114 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003115 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003116 "point");
3117#endif
3118 continue;
3119 }
3120
Daniel Berlina8236562017-04-07 18:38:09 +00003121 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003122 // If this is a leader that is always available, and it's a
3123 // constant or has no equivalences, just replace everything with
3124 // it. We then update the congruence class with whatever members
3125 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003126 Value *Leader =
3127 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003128 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003129 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003130 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003131 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003132 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003133 if (Member == Leader || !isa<Instruction>(Member) ||
3134 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003135 MembersLeft.insert(Member);
3136 continue;
3137 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003138 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3139 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003140 auto *I = cast<Instruction>(Member);
3141 assert(Leader != I && "About to accidentally remove our leader");
3142 replaceInstruction(I, Leader);
3143 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003144 }
Daniel Berlina8236562017-04-07 18:38:09 +00003145 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003146 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00003147 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
3148 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003149 // If this is a singleton, we can skip it.
Daniel Berlina8236562017-04-07 18:38:09 +00003150 if (CC->size() != 1) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003151 // This is a stack because equality replacement/etc may place
3152 // constants in the middle of the member list, and we want to use
3153 // those constant values in preference to the current leader, over
3154 // the scope of those constants.
3155 ValueDFSStack EliminationStack;
3156
3157 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003158 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003159 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003160
3161 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003162 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003163 for (auto &VD : DFSOrderedSet) {
3164 int MemberDFSIn = VD.DFSIn;
3165 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003166 Value *Def = VD.Def.getPointer();
3167 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003168 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003169 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003170 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003171 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00003172
3173 if (EliminationStack.empty()) {
3174 DEBUG(dbgs() << "Elimination Stack is empty\n");
3175 } else {
3176 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3177 << EliminationStack.dfs_back().first << ","
3178 << EliminationStack.dfs_back().second << ")\n");
3179 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003180
3181 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3182 << MemberDFSOut << ")\n");
3183 // First, we see if we are out of scope or empty. If so,
3184 // and there equivalences, we try to replace the top of
3185 // stack with equivalences (if it's on the stack, it must
3186 // not have been eliminated yet).
3187 // Then we synchronize to our current scope, by
3188 // popping until we are back within a DFS scope that
3189 // dominates the current member.
3190 // Then, what happens depends on a few factors
3191 // If the stack is now empty, we need to push
3192 // If we have a constant or a local equivalence we want to
3193 // start using, we also push.
3194 // Otherwise, we walk along, processing members who are
3195 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003196 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003197 bool OutOfScope =
3198 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3199
3200 if (OutOfScope || ShouldPush) {
3201 // Sync to our current scope.
3202 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003203 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003204 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003205 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003206 }
3207 }
3208
Daniel Berline3e69e12017-03-10 00:32:33 +00003209 // Skip the Def's, we only want to eliminate on their uses. But mark
3210 // dominated defs as dead.
3211 if (Def) {
3212 // For anything in this case, what and how we value number
3213 // guarantees that any side-effets that would have occurred (ie
3214 // throwing, etc) can be proven to either still occur (because it's
3215 // dominated by something that has the same side-effects), or never
3216 // occur. Otherwise, we would not have been able to prove it value
3217 // equivalent to something else. For these things, we can just mark
3218 // it all dead. Note that this is different from the "ProbablyDead"
3219 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003220 // easy to prove dead if they are also side-effect free. Note that
3221 // because stores are put in terms of the stored value, we skip
3222 // stored values here. If the stored value is really dead, it will
3223 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003224 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003225 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003226 markInstructionForDeletion(cast<Instruction>(Def));
3227 continue;
3228 }
3229 // At this point, we know it is a Use we are trying to possibly
3230 // replace.
3231
3232 assert(isa<Instruction>(U->get()) &&
3233 "Current def should have been an instruction");
3234 assert(isa<Instruction>(U->getUser()) &&
3235 "Current user should have been an instruction");
3236
3237 // If the thing we are replacing into is already marked to be dead,
3238 // this use is dead. Note that this is true regardless of whether
3239 // we have anything dominating the use or not. We do this here
3240 // because we are already walking all the uses anyway.
3241 Instruction *InstUse = cast<Instruction>(U->getUser());
3242 if (InstructionsToErase.count(InstUse)) {
3243 auto &UseCount = UseCounts[U->get()];
3244 if (--UseCount == 0) {
3245 ProbablyDead.insert(cast<Instruction>(U->get()));
3246 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003247 }
3248
Davide Italiano7e274e02016-12-22 16:03:48 +00003249 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003250 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003251 if (EliminationStack.empty())
3252 continue;
3253
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003254 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003255
Daniel Berlind92e7f92017-01-07 00:01:42 +00003256 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003257 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003258 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003259 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003260 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003261
3262 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003263 // metadata. Skip this if we are replacing predicateinfo with its
3264 // original operand, as we already know we can just drop it.
3265 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003266 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3267 if (!PI || DominatingLeader != PI->OriginalOp)
3268 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003269 U->set(DominatingLeader);
3270 // This is now a use of the dominating leader, which means if the
3271 // dominating leader was dead, it's now live!
3272 auto &LeaderUseCount = UseCounts[DominatingLeader];
3273 // It's about to be alive again.
3274 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3275 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
3276 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003277 AnythingReplaced = true;
3278 }
3279 }
3280 }
3281
Daniel Berline3e69e12017-03-10 00:32:33 +00003282 // At this point, anything still in the ProbablyDead set is actually dead if
3283 // would be trivially dead.
3284 for (auto *I : ProbablyDead)
3285 if (wouldInstructionBeTriviallyDead(I))
3286 markInstructionForDeletion(I);
3287
Davide Italiano7e274e02016-12-22 16:03:48 +00003288 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003289 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003290 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003291 if (!isa<Instruction>(Member) ||
3292 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003293 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003294 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003295
3296 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003297 if (CC->getStoreCount() > 0) {
3298 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003299 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3300 ValueDFSStack EliminationStack;
3301 for (auto &VD : PossibleDeadStores) {
3302 int MemberDFSIn = VD.DFSIn;
3303 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003304 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003305 if (EliminationStack.empty() ||
3306 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3307 // Sync to our current scope.
3308 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3309 if (EliminationStack.empty()) {
3310 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3311 continue;
3312 }
3313 }
3314 // We already did load elimination, so nothing to do here.
3315 if (isa<LoadInst>(Member))
3316 continue;
3317 assert(!EliminationStack.empty());
3318 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003319 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003320 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3321 // Member is dominater by Leader, and thus dead
3322 DEBUG(dbgs() << "Marking dead store " << *Member
3323 << " that is dominated by " << *Leader << "\n");
3324 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003325 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003326 ++NumGVNDeadStores;
3327 }
3328 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003329 }
3330
3331 return AnythingReplaced;
3332}
Daniel Berlin1c087672017-02-11 15:07:01 +00003333
3334// This function provides global ranking of operations so that we can place them
3335// in a canonical order. Note that rank alone is not necessarily enough for a
3336// complete ordering, as constants all have the same rank. However, generally,
3337// we will simplify an operation with all constants so that it doesn't matter
3338// what order they appear in.
3339unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003340 // Prefer undef to anything else
3341 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00003342 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003343 if (isa<Constant>(V))
3344 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00003345 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003346 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003347
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003348 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003349 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003350 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00003351 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003352 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003353 // Unreachable or something else, just return a really large number.
3354 return ~0;
3355}
3356
3357// This is a function that says whether two commutative operations should
3358// have their order swapped when canonicalizing.
3359bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3360 // Because we only care about a total ordering, and don't rewrite expressions
3361 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003362 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003363 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003364}
Daniel Berlin64e68992017-03-12 04:46:45 +00003365
3366class NewGVNLegacyPass : public FunctionPass {
3367public:
3368 static char ID; // Pass identification, replacement for typeid.
3369 NewGVNLegacyPass() : FunctionPass(ID) {
3370 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3371 }
3372 bool runOnFunction(Function &F) override;
3373
3374private:
3375 void getAnalysisUsage(AnalysisUsage &AU) const override {
3376 AU.addRequired<AssumptionCacheTracker>();
3377 AU.addRequired<DominatorTreeWrapperPass>();
3378 AU.addRequired<TargetLibraryInfoWrapperPass>();
3379 AU.addRequired<MemorySSAWrapperPass>();
3380 AU.addRequired<AAResultsWrapperPass>();
3381 AU.addPreserved<DominatorTreeWrapperPass>();
3382 AU.addPreserved<GlobalsAAWrapperPass>();
3383 }
3384};
3385
3386bool NewGVNLegacyPass::runOnFunction(Function &F) {
3387 if (skipFunction(F))
3388 return false;
3389 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3390 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3391 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3392 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3393 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3394 F.getParent()->getDataLayout())
3395 .runGVN();
3396}
3397
3398INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3399 false, false)
3400INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3401INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3402INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3403INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3404INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3405INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3406INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3407 false)
3408
3409char NewGVNLegacyPass::ID = 0;
3410
3411// createGVNPass - The public interface to this file.
3412FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3413
3414PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3415 // Apparently the order in which we get these results matter for
3416 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3417 // the same order here, just in case.
3418 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3419 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3420 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3421 auto &AA = AM.getResult<AAManager>(F);
3422 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3423 bool Changed =
3424 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3425 .runGVN();
3426 if (!Changed)
3427 return PreservedAnalyses::all();
3428 PreservedAnalyses PA;
3429 PA.preserve<DominatorTreeAnalysis>();
3430 PA.preserve<GlobalsAA>();
3431 return PA;
3432}