blob: c7afd1d80ed29f4fd2bdcdc8f198939a482b03f4 [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;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000404
405 // These are the only two things the create* functions should have
406 // side-effects on due to allocating memory.
407 mutable BumpPtrAllocator ExpressionAllocator;
408 mutable ArrayRecycler<Value *> ArgRecycler;
409 mutable TarjanSCC SCCFinder;
Daniel Berlinede130d2017-04-26 20:56:14 +0000410 const SimplifyQuery SQ;
Davide Italiano7e274e02016-12-22 16:03:48 +0000411
Daniel Berlin1c087672017-02-11 15:07:01 +0000412 // Number of function arguments, used by ranking
413 unsigned int NumFuncArgs;
414
Daniel Berlin2f72b192017-04-14 02:53:37 +0000415 // RPOOrdering of basic blocks
416 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
417
Davide Italiano7e274e02016-12-22 16:03:48 +0000418 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000419
420 // This class is called INITIAL in the paper. It is the class everything
421 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000422 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000423 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000424 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000425 std::vector<CongruenceClass *> CongruenceClasses;
426 unsigned NextCongruenceNum;
427
428 // Value Mappings.
429 DenseMap<Value *, CongruenceClass *> ValueToClass;
430 DenseMap<Value *, const Expression *> ValueToExpression;
431
Daniel Berlinf7d95802017-02-18 23:06:50 +0000432 // Mapping from predicate info we used to the instructions we used it with.
433 // In order to correctly ensure propagation, we must keep track of what
434 // comparisons we used, so that when the values of the comparisons change, we
435 // propagate the information to the places we used the comparison.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000436 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
437 PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000438 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
439 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000440 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
441 MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000442
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000443 // A table storing which memorydefs/phis represent a memory state provably
444 // equivalent to another memory state.
445 // We could use the congruence class machinery, but the MemoryAccess's are
446 // abstract memory states, so they can only ever be equivalent to each other,
447 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000448 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000449
Daniel Berlin1316a942017-04-06 18:52:50 +0000450 // We could, if we wanted, build MemoryPhiExpressions and
451 // MemoryVariableExpressions, etc, and value number them the same way we value
452 // number phi expressions. For the moment, this seems like overkill. They
453 // can only exist in one of three states: they can be TOP (equal to
454 // everything), Equivalent to something else, or unique. Because we do not
455 // create expressions for them, we need to simulate leader change not just
456 // when they change class, but when they change state. Note: We can do the
457 // same thing for phis, and avoid having phi expressions if we wanted, We
458 // should eventually unify in one direction or the other, so this is a little
459 // bit of an experiment in which turns out easier to maintain.
460 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
461 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
462
Daniel Berlin2f72b192017-04-14 02:53:37 +0000463 enum PhiCycleState { PCS_Unknown, PCS_CycleFree, PCS_Cycle };
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000464 mutable DenseMap<const PHINode *, PhiCycleState> PhiCycleState;
Davide Italiano7e274e02016-12-22 16:03:48 +0000465 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000466 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000467 ExpressionClassMap ExpressionToClass;
468
469 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000470 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000471
472 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000473 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000474 DenseSet<BlockEdge> ReachableEdges;
475 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
476
477 // This is a bitvector because, on larger functions, we may have
478 // thousands of touched instructions at once (entire blocks,
479 // instructions with hundreds of uses, etc). Even with optimization
480 // for when we mark whole blocks as touched, when this was a
481 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
482 // the time in GVN just managing this list. The bitvector, on the
483 // other hand, efficiently supports test/set/clear of both
484 // individual and ranges, as well as "find next element" This
485 // enables us to use it as a worklist with essentially 0 cost.
486 BitVector TouchedInstructions;
487
488 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000489
490#ifndef NDEBUG
491 // Debugging for how many times each block and instruction got processed.
492 DenseMap<const Value *, unsigned> ProcessedCount;
493#endif
494
495 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000496 // This contains a mapping from Instructions to DFS numbers.
497 // The numbering starts at 1. An instruction with DFS number zero
498 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000499 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000500
501 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000502 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000503
504 // Deletion info.
505 SmallPtrSet<Instruction *, 8> InstructionsToErase;
506
507public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000508 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
509 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
510 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000511 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Daniel Berlinede130d2017-04-26 20:56:14 +0000512 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
513 }
Daniel Berlin64e68992017-03-12 04:46:45 +0000514 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000515
516private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000517 // Expression handling.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000518 const Expression *createExpression(Instruction *) const;
519 const Expression *createBinaryExpression(unsigned, Type *, Value *,
520 Value *) const;
521 PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge,
522 bool &AllConstant) const;
523 const VariableExpression *createVariableExpression(Value *) const;
524 const ConstantExpression *createConstantExpression(Constant *) const;
525 const Expression *createVariableOrConstant(Value *V) const;
526 const UnknownExpression *createUnknownExpression(Instruction *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000527 const StoreExpression *createStoreExpression(StoreInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000528 const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000529 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000530 const MemoryAccess *) const;
531 const CallExpression *createCallExpression(CallInst *,
532 const MemoryAccess *) const;
533 const AggregateValueExpression *
534 createAggregateValueExpression(Instruction *) const;
535 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000536
537 // Congruence class handling.
538 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000539 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000540 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000541 return result;
542 }
543
Daniel Berlin1316a942017-04-06 18:52:50 +0000544 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
545 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000546 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000547 return CC;
548 }
549 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
550 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000551 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000552 CC = createMemoryClass(MA);
553 return CC;
554 }
555
Davide Italiano7e274e02016-12-22 16:03:48 +0000556 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000557 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000558 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000559 ValueToClass[Member] = CClass;
560 return CClass;
561 }
562 void initializeCongruenceClasses(Function &F);
563
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000564 // Value number an Instruction or MemoryPhi.
565 void valueNumberMemoryPhi(MemoryPhi *);
566 void valueNumberInstruction(Instruction *);
567
Davide Italiano7e274e02016-12-22 16:03:48 +0000568 // Symbolic evaluation.
569 const Expression *checkSimplificationResults(Expression *, Instruction *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000570 Value *) const;
571 const Expression *performSymbolicEvaluation(Value *) const;
Daniel Berlin07daac82017-04-02 13:23:44 +0000572 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000573 Instruction *,
574 MemoryAccess *) const;
575 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
576 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
577 const Expression *performSymbolicCallEvaluation(Instruction *) const;
578 const Expression *performSymbolicPHIEvaluation(Instruction *) const;
579 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
580 const Expression *performSymbolicCmpEvaluation(Instruction *) const;
581 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000582
583 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000584 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000585 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000586 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000587 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
588 CongruenceClass *, CongruenceClass *);
589 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
590 CongruenceClass *, CongruenceClass *);
591 Value *getNextValueLeader(CongruenceClass *) const;
592 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
593 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
594 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
595 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000596 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000597
Daniel Berlin1c087672017-02-11 15:07:01 +0000598 // Ranking
599 unsigned int getRank(const Value *) const;
600 bool shouldSwapOperands(const Value *, const Value *) const;
601
Davide Italiano7e274e02016-12-22 16:03:48 +0000602 // Reachability handling.
603 void updateReachableEdge(BasicBlock *, BasicBlock *);
604 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000605 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000606
607 // Elimination.
608 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000609 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000610 SmallVectorImpl<ValueDFS> &,
611 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000612 SmallPtrSetImpl<Instruction *> &) const;
613 void convertClassToLoadsAndStores(const CongruenceClass &,
614 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000615
616 bool eliminateInstructions(Function &);
617 void replaceInstruction(Instruction *, Value *);
618 void markInstructionForDeletion(Instruction *);
619 void deleteInstructionsInBlock(BasicBlock *);
620
621 // New instruction creation.
622 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000623
624 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000625 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000626 void markMemoryUsersTouched(const MemoryAccess *);
627 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000628 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000629 void markValueLeaderChangeTouched(CongruenceClass *CC);
630 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000631 void addPredicateUsers(const PredicateBase *, Instruction *) const;
632 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000633
Daniel Berlin06329a92017-03-18 15:41:40 +0000634 // Main loop of value numbering
635 void iterateTouchedInstructions();
636
Davide Italiano7e274e02016-12-22 16:03:48 +0000637 // Utilities.
638 void cleanupTables();
639 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
640 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000641 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000642 void verifyIterationSettled(Function &F);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000643 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000644 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000645 void deleteExpression(const Expression *E) const;
Daniel Berlin21279bd2017-04-06 18:52:58 +0000646 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000647 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
648 return InstrDFS.lookup(V);
649 }
650
Daniel Berlin21279bd2017-04-06 18:52:58 +0000651 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
652 return MemoryToDFSNum(MA);
653 }
654 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
655 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
656 // This deliberately takes a value so it can be used with Use's, which will
657 // auto-convert to Value's but not to MemoryAccess's.
658 unsigned MemoryToDFSNum(const Value *MA) const {
659 assert(isa<MemoryAccess>(MA) &&
660 "This should not be used with instructions");
661 return isa<MemoryUseOrDef>(MA)
662 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
663 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000664 }
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000665 bool isCycleFree(const PHINode *PN) const ;
Daniel Berlin1316a942017-04-06 18:52:50 +0000666 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000667 // Debug counter info. When verifying, we have to reset the value numbering
668 // debug counter to the same state it started in to get the same results.
669 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000670};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000671} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000672
Davide Italianob1114092016-12-28 13:37:17 +0000673template <typename T>
674static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000675 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000676 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000677 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000678}
679
Davide Italianob1114092016-12-28 13:37:17 +0000680bool LoadExpression::equals(const Expression &Other) const {
681 return equalsLoadStoreHelper(*this, Other);
682}
Davide Italiano7e274e02016-12-22 16:03:48 +0000683
Davide Italianob1114092016-12-28 13:37:17 +0000684bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000685 if (!equalsLoadStoreHelper(*this, Other))
686 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000687 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000688 if (const auto *S = dyn_cast<StoreExpression>(&Other))
689 if (getStoredValue() != S->getStoredValue())
690 return false;
691 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000692}
693
694#ifndef NDEBUG
695static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000696 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000697}
698#endif
699
Daniel Berlin06329a92017-03-18 15:41:40 +0000700// Get the basic block from an instruction/memory value.
701BasicBlock *NewGVN::getBlockForValue(Value *V) const {
702 if (auto *I = dyn_cast<Instruction>(V))
703 return I->getParent();
704 else if (auto *MP = dyn_cast<MemoryPhi>(V))
705 return MP->getBlock();
706 llvm_unreachable("Should have been able to figure out a block for our value");
707 return nullptr;
708}
709
Daniel Berlin0e900112017-03-24 06:33:48 +0000710// Delete a definitely dead expression, so it can be reused by the expression
711// allocator. Some of these are not in creation functions, so we have to accept
712// const versions.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000713void NewGVN::deleteExpression(const Expression *E) const {
Daniel Berlin0e900112017-03-24 06:33:48 +0000714 assert(isa<BasicExpression>(E));
715 auto *BE = cast<BasicExpression>(E);
716 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
717 ExpressionAllocator.Deallocate(E);
718}
719
Daniel Berlin2f72b192017-04-14 02:53:37 +0000720PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000721 bool &AllConstant) const {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000722 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000723 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000724 auto *E =
725 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000726
727 E->allocateOperands(ArgRecycler, ExpressionAllocator);
728 E->setType(I->getType());
729 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000730
Daniel Berlin2f72b192017-04-14 02:53:37 +0000731 unsigned PHIRPO = RPOOrdering.lookup(DT->getNode(PHIBlock));
732
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000733 // NewGVN assumes the operands of a PHI node are in a consistent order across
734 // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
735 // this in LLVM at some point we don't want GVN to find wrong congruences.
736 // Therefore, here we sort uses in predecessor order.
737 SmallVector<const Use *, 4> PHIOperands;
738 for (const Use &U : PN->operands())
739 PHIOperands.push_back(&U);
740 std::sort(PHIOperands.begin(), PHIOperands.end(),
741 [&](const Use *U1, const Use *U2) {
742 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
743 });
744
Davide Italianob3886dd2017-01-25 23:37:49 +0000745 // Filter out unreachable phi operands.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000746 auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
747 return ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000748 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000749
750 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000751 [&](const Use *U) -> Value * {
752 auto *BB = PN->getIncomingBlock(*U);
Daniel Berlin2f72b192017-04-14 02:53:37 +0000753 auto *DTN = DT->getNode(BB);
754 if (RPOOrdering.lookup(DTN) >= PHIRPO)
755 HasBackedge = true;
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000756 AllConstant &= isa<UndefValue>(*U) || isa<Constant>(*U);
Daniel Berlin2f72b192017-04-14 02:53:37 +0000757
Daniel Berlind92e7f92017-01-07 00:01:42 +0000758 // Don't try to transform self-defined phis.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000759 if (*U == PN)
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000760 return PN;
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000761 return lookupOperandLeader(*U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000762 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000763 return E;
764}
765
766// Set basic expression info (Arguments, type, opcode) for Expression
767// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000768bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000769 bool AllConstant = true;
770 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
771 E->setType(GEP->getSourceElementType());
772 else
773 E->setType(I->getType());
774 E->setOpcode(I->getOpcode());
775 E->allocateOperands(ArgRecycler, ExpressionAllocator);
776
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000777 // Transform the operand array into an operand leader array, and keep track of
778 // whether all members are constant.
779 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000780 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000781 AllConstant &= isa<Constant>(Operand);
782 return Operand;
783 });
784
Davide Italiano7e274e02016-12-22 16:03:48 +0000785 return AllConstant;
786}
787
788const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000789 Value *Arg1,
790 Value *Arg2) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000791 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000792
793 E->setType(T);
794 E->setOpcode(Opcode);
795 E->allocateOperands(ArgRecycler, ExpressionAllocator);
796 if (Instruction::isCommutative(Opcode)) {
797 // Ensure that commutative instructions that only differ by a permutation
798 // of their operands get the same value number by sorting the operand value
799 // numbers. Since all commutative instructions have two operands it is more
800 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000801 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000802 std::swap(Arg1, Arg2);
803 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000804 E->op_push_back(lookupOperandLeader(Arg1));
805 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000806
Daniel Berlinede130d2017-04-26 20:56:14 +0000807 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000808 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
809 return SimplifiedE;
810 return E;
811}
812
813// Take a Value returned by simplification of Expression E/Instruction
814// I, and see if it resulted in a simpler expression. If so, return
815// that expression.
816// TODO: Once finished, this should not take an Instruction, we only
817// use it for printing.
818const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000819 Instruction *I,
820 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000821 if (!V)
822 return nullptr;
823 if (auto *C = dyn_cast<Constant>(V)) {
824 if (I)
825 DEBUG(dbgs() << "Simplified " << *I << " to "
826 << " constant " << *C << "\n");
827 NumGVNOpsSimplified++;
828 assert(isa<BasicExpression>(E) &&
829 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000830 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000831 return createConstantExpression(C);
832 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
833 if (I)
834 DEBUG(dbgs() << "Simplified " << *I << " to "
835 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000836 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000837 return createVariableExpression(V);
838 }
839
840 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlina8236562017-04-07 18:38:09 +0000841 if (CC && CC->getDefiningExpr()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000842 if (I)
843 DEBUG(dbgs() << "Simplified " << *I << " to "
844 << " expression " << *V << "\n");
845 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000846 deleteExpression(E);
Daniel Berlina8236562017-04-07 18:38:09 +0000847 return CC->getDefiningExpr();
Davide Italiano7e274e02016-12-22 16:03:48 +0000848 }
849 return nullptr;
850}
851
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000852const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000853 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000854
Daniel Berlin97718e62017-01-31 22:32:03 +0000855 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000856
857 if (I->isCommutative()) {
858 // Ensure that commutative instructions that only differ by a permutation
859 // of their operands get the same value number by sorting the operand value
860 // numbers. Since all commutative instructions have two operands it is more
861 // efficient to sort by hand rather than using, say, std::sort.
862 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000863 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000864 E->swapOperands(0, 1);
865 }
866
867 // Perform simplificaiton
868 // TODO: Right now we only check to see if we get a constant result.
869 // We may get a less than constant, but still better, result for
870 // some operations.
871 // IE
872 // add 0, x -> x
873 // and x, x -> x
874 // We should handle this by simply rewriting the expression.
875 if (auto *CI = dyn_cast<CmpInst>(I)) {
876 // Sort the operand value numbers so x<y and y>x get the same value
877 // number.
878 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000879 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000880 E->swapOperands(0, 1);
881 Predicate = CmpInst::getSwappedPredicate(Predicate);
882 }
883 E->setOpcode((CI->getOpcode() << 8) | Predicate);
884 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000885 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
886 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000887 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
888 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +0000889 Value *V =
890 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +0000891 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
892 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000893 } else if (isa<SelectInst>(I)) {
894 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000895 E->getOperand(0) == E->getOperand(1)) {
896 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
897 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000898 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +0000899 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000900 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
901 return SimplifiedE;
902 }
903 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +0000904 Value *V =
905 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000906 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
907 return SimplifiedE;
908 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000909 Value *V =
910 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000911 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
912 return SimplifiedE;
913 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +0000914 Value *V = SimplifyGEPInst(
915 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000916 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
917 return SimplifiedE;
918 } else if (AllConstant) {
919 // We don't bother trying to simplify unless all of the operands
920 // were constant.
921 // TODO: There are a lot of Simplify*'s we could call here, if we
922 // wanted to. The original motivating case for this code was a
923 // zext i1 false to i8, which we don't have an interface to
924 // simplify (IE there is no SimplifyZExt).
925
926 SmallVector<Constant *, 8> C;
927 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000928 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000929
Daniel Berlin64e68992017-03-12 04:46:45 +0000930 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +0000931 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
932 return SimplifiedE;
933 }
934 return E;
935}
936
937const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000938NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000939 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000940 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000941 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000942 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000943 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000944 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000945 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000946 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000947 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000948 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000949 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000950 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000951 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000952 return E;
953 }
954 llvm_unreachable("Unhandled type of aggregate value operation");
955}
956
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000957const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000958 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000959 E->setOpcode(V->getValueID());
960 return E;
961}
962
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000963const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +0000964 if (auto *C = dyn_cast<Constant>(V))
965 return createConstantExpression(C);
966 return createVariableExpression(V);
967}
968
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000969const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000970 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000971 E->setOpcode(C->getValueID());
972 return E;
973}
974
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000975const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +0000976 auto *E = new (ExpressionAllocator) UnknownExpression(I);
977 E->setOpcode(I->getOpcode());
978 return E;
979}
980
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000981const CallExpression *
982NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000983 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000984 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +0000985 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +0000986 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000987 return E;
988}
989
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000990// Return true if some equivalent of instruction Inst dominates instruction U.
991bool NewGVN::someEquivalentDominates(const Instruction *Inst,
992 const Instruction *U) const {
993 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +0000994 // This must be an instruction because we are only called from phi nodes
995 // in the case that the value it needs to check against is an instruction.
996
997 // The most likely candiates for dominance are the leader and the next leader.
998 // The leader or nextleader will dominate in all cases where there is an
999 // equivalent that is higher up in the dom tree.
1000 // We can't *only* check them, however, because the
1001 // dominator tree could have an infinite number of non-dominating siblings
1002 // with instructions that are in the right congruence class.
1003 // A
1004 // B C D E F G
1005 // |
1006 // H
1007 // Instruction U could be in H, with equivalents in every other sibling.
1008 // Depending on the rpo order picked, the leader could be the equivalent in
1009 // any of these siblings.
1010 if (!CC)
1011 return false;
Daniel Berlina8236562017-04-07 18:38:09 +00001012 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001013 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001014 if (CC->getNextLeader().first &&
1015 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001016 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001017 return llvm::any_of(*CC, [&](const Value *Member) {
1018 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001019 DT->dominates(cast<Instruction>(Member), U);
1020 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001021}
1022
Davide Italiano7e274e02016-12-22 16:03:48 +00001023// See if we have a congruence class and leader for this operand, and if so,
1024// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001025Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001026 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001027 if (CC) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001028 // Everything in TOP is represneted by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001029 // We do have to make sure we get the type right though, so we can't set the
1030 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001031 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001032 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001033 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001034 }
1035
Davide Italiano7e274e02016-12-22 16:03:48 +00001036 return V;
1037}
1038
Daniel Berlin1316a942017-04-06 18:52:50 +00001039const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1040 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001041 assert(CC->getMemoryLeader() &&
1042 "Every MemoryAccess should be mapped to a "
1043 "congruence class with a represenative memory "
1044 "access");
1045 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001046}
1047
Daniel Berlinc4796862017-01-27 02:37:11 +00001048// Return true if the MemoryAccess is really equivalent to everything. This is
1049// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001050// state of all MemoryAccesses.
Daniel Berlinc4796862017-01-27 02:37:11 +00001051bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001052 return getMemoryClass(MA) == TOPClass;
1053}
1054
Davide Italiano7e274e02016-12-22 16:03:48 +00001055LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001056 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001057 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001058 auto *E =
1059 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001060 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1061 E->setType(LoadType);
1062
1063 // Give store and loads same opcode so they value number together.
1064 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001065 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001066 if (LI)
1067 E->setAlignment(LI->getAlignment());
1068
1069 // TODO: Value number heap versions. We may be able to discover
1070 // things alias analysis can't on it's own (IE that a store and a
1071 // load have the same value, and thus, it isn't clobbering the load).
1072 return E;
1073}
1074
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001075const StoreExpression *
1076NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001077 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001078 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001079 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001080 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1081 E->setType(SI->getValueOperand()->getType());
1082
1083 // Give store and loads same opcode so they value number together.
1084 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001085 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001086
1087 // TODO: Value number heap versions. We may be able to discover
1088 // things alias analysis can't on it's own (IE that a store and a
1089 // load have the same value, and thus, it isn't clobbering the load).
1090 return E;
1091}
1092
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001093const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001094 // Unlike loads, we never try to eliminate stores, so we do not check if they
1095 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001096 auto *SI = cast<StoreInst>(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00001097 auto *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001098 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001099 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1100 if (EnableStoreRefinement)
1101 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1102 // If we bypassed the use-def chains, make sure we add a use.
1103 if (StoreRHS != StoreAccess->getDefiningAccess())
1104 addMemoryUsers(StoreRHS, StoreAccess);
1105
1106 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001107 // If we are defined by ourselves, use the live on entry def.
1108 if (StoreRHS == StoreAccess)
1109 StoreRHS = MSSA->getLiveOnEntryDef();
1110
Daniel Berlin589cecc2017-01-02 18:00:46 +00001111 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001112 // See if we are defined by a previous store expression, it already has a
1113 // value, and it's the same value as our current store. FIXME: Right now, we
1114 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001115 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1116 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +00001117 // Basically, check if the congruence class the store is in is defined by a
1118 // store that isn't us, and has the same value. MemorySSA takes care of
1119 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +00001120 // The RepStoredValue gets nulled if all the stores disappear in a class, so
1121 // we don't need to check if the class contains a store besides us.
Daniel Berlin1316a942017-04-06 18:52:50 +00001122 if (LastCC &&
Daniel Berlina8236562017-04-07 18:38:09 +00001123 LastCC->getStoredValue() == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin1316a942017-04-06 18:52:50 +00001124 return LastStore;
1125 deleteExpression(LastStore);
Daniel Berlinc4796862017-01-27 02:37:11 +00001126 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001127 // location, and the memory state is the same as it was then (otherwise, it
1128 // could have been overwritten later. See test32 in
1129 // transforms/DeadStoreElimination/simple.ll).
1130 if (auto *LI =
1131 dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001132 if ((lookupOperandLeader(LI->getPointerOperand()) ==
1133 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlin1316a942017-04-06 18:52:50 +00001134 (lookupMemoryLeader(MSSA->getMemoryAccess(LI)->getDefiningAccess()) ==
1135 StoreRHS))
Daniel Berlinc4796862017-01-27 02:37:11 +00001136 return createVariableExpression(LI);
1137 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001138 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001139
1140 // If the store is not equivalent to anything, value number it as a store that
1141 // produces a unique memory state (instead of using it's MemoryUse, we use
1142 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001143 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001144}
1145
Daniel Berlin07daac82017-04-02 13:23:44 +00001146// See if we can extract the value of a loaded pointer from a load, a store, or
1147// a memory instruction.
1148const Expression *
1149NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1150 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001151 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001152 assert((!LI || LI->isSimple()) && "Not a simple load");
1153 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1154 // Can't forward from non-atomic to atomic without violating memory model.
1155 // Also don't need to coerce if they are the same type, we will just
1156 // propogate..
1157 if (LI->isAtomic() > DepSI->isAtomic() ||
1158 LoadType == DepSI->getValueOperand()->getType())
1159 return nullptr;
1160 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1161 if (Offset >= 0) {
1162 if (auto *C = dyn_cast<Constant>(
1163 lookupOperandLeader(DepSI->getValueOperand()))) {
1164 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1165 << *C << "\n");
1166 return createConstantExpression(
1167 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1168 }
1169 }
1170
1171 } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1172 // Can't forward from non-atomic to atomic without violating memory model.
1173 if (LI->isAtomic() > DepLI->isAtomic())
1174 return nullptr;
1175 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1176 if (Offset >= 0) {
1177 // We can coerce a constant load into a load
1178 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1179 if (auto *PossibleConstant =
1180 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1181 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1182 << *PossibleConstant << "\n");
1183 return createConstantExpression(PossibleConstant);
1184 }
1185 }
1186
1187 } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1188 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1189 if (Offset >= 0) {
1190 if (auto *PossibleConstant =
1191 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1192 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1193 << " to constant " << *PossibleConstant << "\n");
1194 return createConstantExpression(PossibleConstant);
1195 }
1196 }
1197 }
1198
1199 // All of the below are only true if the loaded pointer is produced
1200 // by the dependent instruction.
1201 if (LoadPtr != lookupOperandLeader(DepInst) &&
1202 !AA->isMustAlias(LoadPtr, DepInst))
1203 return nullptr;
1204 // If this load really doesn't depend on anything, then we must be loading an
1205 // undef value. This can happen when loading for a fresh allocation with no
1206 // intervening stores, for example. Note that this is only true in the case
1207 // that the result of the allocation is pointer equal to the load ptr.
1208 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1209 return createConstantExpression(UndefValue::get(LoadType));
1210 }
1211 // If this load occurs either right after a lifetime begin,
1212 // then the loaded value is undefined.
1213 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1214 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1215 return createConstantExpression(UndefValue::get(LoadType));
1216 }
1217 // If this load follows a calloc (which zero initializes memory),
1218 // then the loaded value is zero
1219 else if (isCallocLikeFn(DepInst, TLI)) {
1220 return createConstantExpression(Constant::getNullValue(LoadType));
1221 }
1222
1223 return nullptr;
1224}
1225
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001226const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001227 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001228
1229 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001230 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001231 if (!LI->isSimple())
1232 return nullptr;
1233
Daniel Berlin203f47b2017-01-31 22:31:53 +00001234 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001235 // Load of undef is undef.
1236 if (isa<UndefValue>(LoadAddressLeader))
1237 return createConstantExpression(UndefValue::get(LI->getType()));
1238
1239 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
1240
1241 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1242 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1243 Instruction *DefiningInst = MD->getMemoryInst();
1244 // If the defining instruction is not reachable, replace with undef.
1245 if (!ReachableBlocks.count(DefiningInst->getParent()))
1246 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001247 // This will handle stores and memory insts. We only do if it the
1248 // defining access has a different type, or it is a pointer produced by
1249 // certain memory operations that cause the memory to have a fixed value
1250 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001251 if (const auto *CoercionResult =
1252 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1253 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001254 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001255 }
1256 }
1257
Daniel Berlin1316a942017-04-06 18:52:50 +00001258 const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1259 LI, DefiningAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001260 return E;
1261}
1262
Daniel Berlinf7d95802017-02-18 23:06:50 +00001263const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001264NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001265 auto *PI = PredInfo->getPredicateInfoFor(I);
1266 if (!PI)
1267 return nullptr;
1268
1269 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001270
1271 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1272 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001273 return nullptr;
1274
Daniel Berlinfccbda92017-02-22 22:20:58 +00001275 auto *CopyOf = I->getOperand(0);
1276 auto *Cond = PWC->Condition;
1277
Daniel Berlinf7d95802017-02-18 23:06:50 +00001278 // If this a copy of the condition, it must be either true or false depending
1279 // on the predicate info type and edge
1280 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001281 // We should not need to add predicate users because the predicate info is
1282 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001283 if (isa<PredicateAssume>(PI))
1284 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1285 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1286 if (PBranch->TrueEdge)
1287 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1288 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1289 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001290 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1291 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001292 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001293
Daniel Berlinf7d95802017-02-18 23:06:50 +00001294 // Not a copy of the condition, so see what the predicates tell us about this
1295 // value. First, though, we check to make sure the value is actually a copy
1296 // of one of the condition operands. It's possible, in certain cases, for it
1297 // to be a copy of a predicateinfo copy. In particular, if two branch
1298 // operations use the same condition, and one branch dominates the other, we
1299 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001300 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001301 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001302
1303 // Everything below relies on the condition being a comparison.
1304 auto *Cmp = dyn_cast<CmpInst>(Cond);
1305 if (!Cmp)
1306 return nullptr;
1307
1308 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001309 DEBUG(dbgs() << "Copy is not of any condition operands!");
1310 return nullptr;
1311 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001312 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1313 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001314 bool SwappedOps = false;
1315 // Sort the ops
1316 if (shouldSwapOperands(FirstOp, SecondOp)) {
1317 std::swap(FirstOp, SecondOp);
1318 SwappedOps = true;
1319 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001320 CmpInst::Predicate Predicate =
1321 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1322
1323 if (isa<PredicateAssume>(PI)) {
1324 // If the comparison is true when the operands are equal, then we know the
1325 // operands are equal, because assumes must always be true.
1326 if (CmpInst::isTrueWhenEqual(Predicate)) {
1327 addPredicateUsers(PI, I);
1328 return createVariableOrConstant(FirstOp);
1329 }
1330 }
1331 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1332 // If we are *not* a copy of the comparison, we may equal to the other
1333 // operand when the predicate implies something about equality of
1334 // operations. In particular, if the comparison is true/false when the
1335 // operands are equal, and we are on the right edge, we know this operation
1336 // is equal to something.
1337 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1338 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1339 addPredicateUsers(PI, I);
1340 return createVariableOrConstant(FirstOp);
1341 }
1342 // Handle the special case of floating point.
1343 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1344 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1345 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1346 addPredicateUsers(PI, I);
1347 return createConstantExpression(cast<Constant>(FirstOp));
1348 }
1349 }
1350 return nullptr;
1351}
1352
Davide Italiano7e274e02016-12-22 16:03:48 +00001353// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001354const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001355 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001356 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1357 // Instrinsics with the returned attribute are copies of arguments.
1358 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1359 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1360 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1361 return Result;
1362 return createVariableOrConstant(ReturnedValue);
1363 }
1364 }
1365 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001366 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001367 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001368 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001369 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001370 }
1371 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001372}
1373
Daniel Berlin1316a942017-04-06 18:52:50 +00001374// Retrieve the memory class for a given MemoryAccess.
1375CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1376
1377 auto *Result = MemoryAccessToClass.lookup(MA);
1378 assert(Result && "Should have found memory class");
1379 return Result;
1380}
1381
1382// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001383// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001384bool NewGVN::setMemoryClass(const MemoryAccess *From,
1385 CongruenceClass *NewClass) {
1386 assert(NewClass &&
1387 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001388 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001389 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001390 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
1391 DEBUG(dbgs() << *NewClass->getMemoryLeader());
Daniel Berlin9f376b72017-01-29 10:26:03 +00001392 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001393
1394 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001395 bool Changed = false;
1396 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001397 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001398 auto *OldClass = LookupResult->second;
1399 if (OldClass != NewClass) {
1400 // If this is a phi, we have to handle memory member updates.
1401 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001402 OldClass->memory_erase(MP);
1403 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001404 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001405 if (OldClass->getMemoryLeader() == From) {
1406 if (OldClass->memory_empty()) {
1407 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001408 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001409 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001410 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001411 << OldClass->getID() << " to "
1412 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001413 << " due to removal of a memory member " << *From
1414 << "\n");
1415 markMemoryLeaderChangeTouched(OldClass);
1416 }
1417 }
1418 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001419 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001420 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001421 Changed = true;
1422 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001423 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001424
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001425 return Changed;
1426}
Daniel Berlin0e900112017-03-24 06:33:48 +00001427
Daniel Berlin2f72b192017-04-14 02:53:37 +00001428// Determine if a phi is cycle-free. That means the values in the phi don't
1429// depend on any expressions that can change value as a result of the phi.
1430// For example, a non-cycle free phi would be v = phi(0, v+1).
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001431bool NewGVN::isCycleFree(const PHINode *PN) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001432 // In order to compute cycle-freeness, we do SCC finding on the phi, and see
1433 // what kind of SCC it ends up in. If it is a singleton, it is cycle-free.
1434 // If it is not in a singleton, it is only cycle free if the other members are
1435 // all phi nodes (as they do not compute anything, they are copies). TODO:
1436 // There are likely a few other intrinsics or expressions that could be
1437 // included here, but this happens so infrequently already that it is not
1438 // likely to be worth it.
1439 auto PCS = PhiCycleState.lookup(PN);
1440 if (PCS == PCS_Unknown) {
1441 SCCFinder.Start(PN);
1442 auto &SCC = SCCFinder.getComponentFor(PN);
1443 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1444 if (SCC.size() == 1)
1445 PhiCycleState.insert({PN, PCS_CycleFree});
1446 else {
1447 bool AllPhis =
1448 llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
1449 PCS = AllPhis ? PCS_CycleFree : PCS_Cycle;
1450 for (auto *Member : SCC)
1451 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
1452 PhiCycleState.insert({MemberPhi, PCS});
1453 }
1454 }
1455 if (PCS == PCS_Cycle)
1456 return false;
1457 return true;
1458}
1459
Davide Italiano7e274e02016-12-22 16:03:48 +00001460// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001461const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001462 // True if one of the incoming phi edges is a backedge.
1463 bool HasBackedge = false;
1464 // All constant tracks the state of whether all the *original* phi operands
Davide Italiano839c7e62017-05-02 21:11:40 +00001465 // were constant. This is really shorthand for "this phi cannot cycle due
1466 // to forward propagation", as any change in value of the phi is guaranteed
1467 // not to later change the value of the phi.
Daniel Berlin2f72b192017-04-14 02:53:37 +00001468 // IE it can't be v = phi(undef, v+1)
1469 bool AllConstant = true;
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001470 auto *E = cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001471 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001472 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001473 // We track if any were undef because they need special handling.
1474 bool HasUndef = false;
1475 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1476 if (Arg == I)
1477 return false;
1478 if (isa<UndefValue>(Arg)) {
1479 HasUndef = true;
1480 return false;
1481 }
1482 return true;
1483 });
1484 // If we are left with no operands, it's undef
1485 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001486 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1487 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001488 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001489 return createConstantExpression(UndefValue::get(I->getType()));
1490 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001491 unsigned NumOps = 0;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001492 Value *AllSameValue = *(Filtered.begin());
1493 ++Filtered.begin();
1494 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berlin2f72b192017-04-14 02:53:37 +00001495 if (llvm::all_of(Filtered, [AllSameValue, &NumOps](const Value *V) {
1496 ++NumOps;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001497 return V == AllSameValue;
1498 })) {
1499 // In LLVM's non-standard representation of phi nodes, it's possible to have
1500 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1501 // on the original phi node), especially in weird CFG's where some arguments
1502 // are unreachable, or uninitialized along certain paths. This can cause
1503 // infinite loops during evaluation. We work around this by not trying to
1504 // really evaluate them independently, but instead using a variable
1505 // expression to say if one is equivalent to the other.
1506 // We also special case undef, so that if we have an undef, we can't use the
1507 // common value unless it dominates the phi block.
1508 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001509 // If we have undef and at least one other value, this is really a
1510 // multivalued phi, and we need to know if it's cycle free in order to
1511 // evaluate whether we can ignore the undef. The other parts of this are
1512 // just shortcuts. If there is no backedge, or all operands are
1513 // constants, or all operands are ignored but the undef, it also must be
1514 // cycle free.
1515 if (!AllConstant && HasBackedge && NumOps > 0 &&
1516 !isa<UndefValue>(AllSameValue) && !isCycleFree(cast<PHINode>(I)))
1517 return E;
1518
Daniel Berlind92e7f92017-01-07 00:01:42 +00001519 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001520 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001521 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001522 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001523 }
1524
Davide Italiano7e274e02016-12-22 16:03:48 +00001525 NumGVNPhisAllSame++;
1526 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1527 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001528 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001529 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001530 }
1531 return E;
1532}
1533
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001534const Expression *
1535NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001536 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1537 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1538 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1539 unsigned Opcode = 0;
1540 // EI might be an extract from one of our recognised intrinsics. If it
1541 // is we'll synthesize a semantically equivalent expression instead on
1542 // an extract value expression.
1543 switch (II->getIntrinsicID()) {
1544 case Intrinsic::sadd_with_overflow:
1545 case Intrinsic::uadd_with_overflow:
1546 Opcode = Instruction::Add;
1547 break;
1548 case Intrinsic::ssub_with_overflow:
1549 case Intrinsic::usub_with_overflow:
1550 Opcode = Instruction::Sub;
1551 break;
1552 case Intrinsic::smul_with_overflow:
1553 case Intrinsic::umul_with_overflow:
1554 Opcode = Instruction::Mul;
1555 break;
1556 default:
1557 break;
1558 }
1559
1560 if (Opcode != 0) {
1561 // Intrinsic recognized. Grab its args to finish building the
1562 // expression.
1563 assert(II->getNumArgOperands() == 2 &&
1564 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001565 return createBinaryExpression(
1566 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001567 }
1568 }
1569 }
1570
Daniel Berlin97718e62017-01-31 22:32:03 +00001571 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001572}
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001573const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001574 auto *CI = dyn_cast<CmpInst>(I);
1575 // See if our operands are equal to those of a previous predicate, and if so,
1576 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001577 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1578 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001579 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001580 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001581 std::swap(Op0, Op1);
1582 OurPredicate = CI->getSwappedPredicate();
1583 }
1584
1585 // Avoid processing the same info twice
1586 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001587 // See if we know something about the comparison itself, like it is the target
1588 // of an assume.
1589 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1590 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1591 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1592
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001593 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001594 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001595 if (CI->isTrueWhenEqual())
1596 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1597 else if (CI->isFalseWhenEqual())
1598 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1599 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001600
1601 // NOTE: Because we are comparing both operands here and below, and using
1602 // previous comparisons, we rely on fact that predicateinfo knows to mark
1603 // comparisons that use renamed operands as users of the earlier comparisons.
1604 // It is *not* enough to just mark predicateinfo renamed operands as users of
1605 // the earlier comparisons, because the *other* operand may have changed in a
1606 // previous iteration.
1607 // Example:
1608 // icmp slt %a, %b
1609 // %b.0 = ssa.copy(%b)
1610 // false branch:
1611 // icmp slt %c, %b.0
1612
1613 // %c and %a may start out equal, and thus, the code below will say the second
1614 // %icmp is false. c may become equal to something else, and in that case the
1615 // %second icmp *must* be reexamined, but would not if only the renamed
1616 // %operands are considered users of the icmp.
1617
1618 // *Currently* we only check one level of comparisons back, and only mark one
1619 // level back as touched when changes appen . If you modify this code to look
1620 // back farther through comparisons, you *must* mark the appropriate
1621 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1622 // we know something just from the operands themselves
1623
1624 // See if our operands have predicate info, so that we may be able to derive
1625 // something from a previous comparison.
1626 for (const auto &Op : CI->operands()) {
1627 auto *PI = PredInfo->getPredicateInfoFor(Op);
1628 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1629 if (PI == LastPredInfo)
1630 continue;
1631 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001632
Daniel Berlinf7d95802017-02-18 23:06:50 +00001633 // TODO: Along the false edge, we may know more things too, like icmp of
1634 // same operands is false.
1635 // TODO: We only handle actual comparison conditions below, not and/or.
1636 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1637 if (!BranchCond)
1638 continue;
1639 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1640 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1641 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001642 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001643 std::swap(BranchOp0, BranchOp1);
1644 BranchPredicate = BranchCond->getSwappedPredicate();
1645 }
1646 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1647 if (PBranch->TrueEdge) {
1648 // If we know the previous predicate is true and we are in the true
1649 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001650 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1651 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001652 addPredicateUsers(PI, I);
1653 return createConstantExpression(
1654 ConstantInt::getTrue(CI->getType()));
1655 }
1656
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001657 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1658 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001659 addPredicateUsers(PI, I);
1660 return createConstantExpression(
1661 ConstantInt::getFalse(CI->getType()));
1662 }
1663
1664 } else {
1665 // Just handle the ne and eq cases, where if we have the same
1666 // operands, we may know something.
1667 if (BranchPredicate == OurPredicate) {
1668 addPredicateUsers(PI, I);
1669 // Same predicate, same ops,we know it was false, so this is false.
1670 return createConstantExpression(
1671 ConstantInt::getFalse(CI->getType()));
1672 } else if (BranchPredicate ==
1673 CmpInst::getInversePredicate(OurPredicate)) {
1674 addPredicateUsers(PI, I);
1675 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001676 return createConstantExpression(
1677 ConstantInt::getTrue(CI->getType()));
1678 }
1679 }
1680 }
1681 }
1682 }
1683 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001684 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001685}
Davide Italiano7e274e02016-12-22 16:03:48 +00001686
1687// Substitute and symbolize the value before value numbering.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001688const Expression *NewGVN::performSymbolicEvaluation(Value *V) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001689 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001690 if (auto *C = dyn_cast<Constant>(V))
1691 E = createConstantExpression(C);
1692 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1693 E = createVariableExpression(V);
1694 } else {
1695 // TODO: memory intrinsics.
1696 // TODO: Some day, we should do the forward propagation and reassociation
1697 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001698 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001699 switch (I->getOpcode()) {
1700 case Instruction::ExtractValue:
1701 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001702 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001703 break;
1704 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001705 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001706 break;
1707 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001708 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001709 break;
1710 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001711 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001712 break;
1713 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001714 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001715 break;
1716 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001717 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001718 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001719 case Instruction::ICmp:
1720 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001721 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001722 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001723 case Instruction::Add:
1724 case Instruction::FAdd:
1725 case Instruction::Sub:
1726 case Instruction::FSub:
1727 case Instruction::Mul:
1728 case Instruction::FMul:
1729 case Instruction::UDiv:
1730 case Instruction::SDiv:
1731 case Instruction::FDiv:
1732 case Instruction::URem:
1733 case Instruction::SRem:
1734 case Instruction::FRem:
1735 case Instruction::Shl:
1736 case Instruction::LShr:
1737 case Instruction::AShr:
1738 case Instruction::And:
1739 case Instruction::Or:
1740 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001741 case Instruction::Trunc:
1742 case Instruction::ZExt:
1743 case Instruction::SExt:
1744 case Instruction::FPToUI:
1745 case Instruction::FPToSI:
1746 case Instruction::UIToFP:
1747 case Instruction::SIToFP:
1748 case Instruction::FPTrunc:
1749 case Instruction::FPExt:
1750 case Instruction::PtrToInt:
1751 case Instruction::IntToPtr:
1752 case Instruction::Select:
1753 case Instruction::ExtractElement:
1754 case Instruction::InsertElement:
1755 case Instruction::ShuffleVector:
1756 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001757 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001758 break;
1759 default:
1760 return nullptr;
1761 }
1762 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001763 return E;
1764}
1765
Davide Italiano7e274e02016-12-22 16:03:48 +00001766void NewGVN::markUsersTouched(Value *V) {
1767 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001768 for (auto *User : V->users()) {
1769 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001770 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001771 }
1772}
1773
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001774void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001775 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1776 MemoryToUsers[To].insert(U);
1777}
1778
1779void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001780 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00001781}
1782
1783void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1784 if (isa<MemoryUse>(MA))
1785 return;
1786 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00001787 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin1316a942017-04-06 18:52:50 +00001788 const auto Result = MemoryToUsers.find(MA);
1789 if (Result != MemoryToUsers.end()) {
1790 for (auto *User : Result->second)
Daniel Berlin21279bd2017-04-06 18:52:58 +00001791 TouchedInstructions.set(MemoryToDFSNum(User));
Daniel Berlin1316a942017-04-06 18:52:50 +00001792 MemoryToUsers.erase(Result);
Davide Italiano7e274e02016-12-22 16:03:48 +00001793 }
1794}
1795
Daniel Berlinf7d95802017-02-18 23:06:50 +00001796// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001797void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001798 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1799 PredicateToUsers[PBranch->Condition].insert(I);
1800 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1801 PredicateToUsers[PAssume->Condition].insert(I);
1802}
1803
1804// Touch all the predicates that depend on this instruction.
1805void NewGVN::markPredicateUsersTouched(Instruction *I) {
1806 const auto Result = PredicateToUsers.find(I);
Daniel Berlin46b72e62017-03-19 00:07:32 +00001807 if (Result != PredicateToUsers.end()) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001808 for (auto *User : Result->second)
Daniel Berlin21279bd2017-04-06 18:52:58 +00001809 TouchedInstructions.set(InstrToDFSNum(User));
Daniel Berlin46b72e62017-03-19 00:07:32 +00001810 PredicateToUsers.erase(Result);
1811 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001812}
1813
Daniel Berlin1316a942017-04-06 18:52:50 +00001814// Mark users affected by a memory leader change.
1815void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001816 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00001817 markMemoryDefTouched(M);
1818}
1819
Daniel Berlin32f8d562017-01-07 16:55:14 +00001820// Touch the instructions that need to be updated after a congruence class has a
1821// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00001822void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001823 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001824 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00001825 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001826 LeaderChanges.insert(M);
1827 }
1828}
1829
Daniel Berlin1316a942017-04-06 18:52:50 +00001830// Give a range of things that have instruction DFS numbers, this will return
1831// the member of the range with the smallest dfs number.
1832template <class T, class Range>
1833T *NewGVN::getMinDFSOfRange(const Range &R) const {
1834 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
1835 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001836 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00001837 if (DFSNum < MinDFS.second)
1838 MinDFS = {X, DFSNum};
1839 }
1840 return MinDFS.first;
1841}
1842
1843// This function returns the MemoryAccess that should be the next leader of
1844// congruence class CC, under the assumption that the current leader is going to
1845// disappear.
1846const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
1847 // TODO: If this ends up to slow, we can maintain a next memory leader like we
1848 // do for regular leaders.
1849 // Make sure there will be a leader to find
Davide Italianof58a30232017-04-10 23:08:35 +00001850 assert((CC->getStoreCount() > 0 || !CC->memory_empty()) &&
1851 "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00001852 if (CC->getStoreCount() > 0) {
1853 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlin1316a942017-04-06 18:52:50 +00001854 return MSSA->getMemoryAccess(NL);
1855 // Find the store with the minimum DFS number.
1856 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00001857 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlin1316a942017-04-06 18:52:50 +00001858 return MSSA->getMemoryAccess(cast<StoreInst>(V));
1859 }
Daniel Berlina8236562017-04-07 18:38:09 +00001860 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001861
1862 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00001863 // !OldClass->memory_empty()
1864 if (CC->memory_size() == 1)
1865 return *CC->memory_begin();
1866 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00001867}
1868
1869// This function returns the next value leader of a congruence class, under the
1870// assumption that the current leader is going away. This should end up being
1871// the next most dominating member.
1872Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
1873 // We don't need to sort members if there is only 1, and we don't care about
1874 // sorting the TOP class because everything either gets out of it or is
1875 // unreachable.
1876
Daniel Berlina8236562017-04-07 18:38:09 +00001877 if (CC->size() == 1 || CC == TOPClass) {
1878 return *(CC->begin());
1879 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001880 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00001881 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00001882 } else {
1883 ++NumGVNSortedLeaderChanges;
1884 // NOTE: If this ends up to slow, we can maintain a dual structure for
1885 // member testing/insertion, or keep things mostly sorted, and sort only
1886 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00001887 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00001888 }
1889}
1890
1891// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
1892// the memory members, etc for the move.
1893//
1894// The invariants of this function are:
1895//
1896// I must be moving to NewClass from OldClass The StoreCount of OldClass and
1897// NewClass is expected to have been updated for I already if it is is a store.
1898// The OldClass memory leader has not been updated yet if I was the leader.
1899void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
1900 MemoryAccess *InstMA,
1901 CongruenceClass *OldClass,
1902 CongruenceClass *NewClass) {
1903 // If the leader is I, and we had a represenative MemoryAccess, it should
1904 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00001905 assert((!InstMA || !OldClass->getMemoryLeader() ||
1906 OldClass->getLeader() != I ||
1907 OldClass->getMemoryLeader() == InstMA) &&
1908 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00001909 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00001910 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001911 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00001912 assert(NewClass->size() == 1 ||
1913 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
1914 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00001915 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00001916 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00001917 << " due to new memory instruction becoming leader\n");
1918 markMemoryLeaderChangeTouched(NewClass);
1919 }
1920 setMemoryClass(InstMA, NewClass);
1921 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00001922 if (OldClass->getMemoryLeader() == InstMA) {
1923 if (OldClass->getStoreCount() != 0 || !OldClass->memory_empty()) {
1924 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1925 DEBUG(dbgs() << "Memory class leader change for class "
1926 << OldClass->getID() << " to "
1927 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001928 << " due to removal of old leader " << *InstMA << "\n");
1929 markMemoryLeaderChangeTouched(OldClass);
1930 } else
Daniel Berlina8236562017-04-07 18:38:09 +00001931 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001932 }
1933}
1934
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001935// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00001936// Update OldClass and NewClass for the move (including changing leaders, etc).
1937void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001938 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001939 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00001940 if (I == OldClass->getNextLeader().first)
1941 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001942
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001943 // It's possible, though unlikely, for us to discover equivalences such
1944 // that the current leader does not dominate the old one.
1945 // This statistic tracks how often this happens.
1946 // We assert on phi nodes when this happens, currently, for debugging, because
1947 // we want to make sure we name phi node cycles properly.
Daniel Berlina8236562017-04-07 18:38:09 +00001948 if (isa<Instruction>(NewClass->getLeader()) && NewClass->getLeader() &&
1949 I != NewClass->getLeader()) {
Daniel Berlinffc30782017-03-24 06:33:51 +00001950 auto *IBB = I->getParent();
Daniel Berlina8236562017-04-07 18:38:09 +00001951 auto *NCBB = cast<Instruction>(NewClass->getLeader())->getParent();
Daniel Berlin21279bd2017-04-06 18:52:58 +00001952 bool Dominated =
Daniel Berlina8236562017-04-07 18:38:09 +00001953 IBB == NCBB && InstrToDFSNum(I) < InstrToDFSNum(NewClass->getLeader());
Daniel Berlinffc30782017-03-24 06:33:51 +00001954 Dominated = Dominated || DT->properlyDominates(IBB, NCBB);
1955 if (Dominated) {
1956 ++NumGVNNotMostDominatingLeader;
1957 assert(
1958 !isa<PHINode>(I) &&
1959 "New class for instruction should not be dominated by instruction");
1960 }
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001961 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001962
Daniel Berlina8236562017-04-07 18:38:09 +00001963 if (NewClass->getLeader() != I)
1964 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001965
Daniel Berlina8236562017-04-07 18:38:09 +00001966 OldClass->erase(I);
1967 NewClass->insert(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00001968 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001969 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001970 OldClass->decStoreCount();
1971 // Okay, so when do we want to make a store a leader of a class?
1972 // If we have a store defined by an earlier load, we want the earlier load
1973 // to lead the class.
1974 // If we have a store defined by something else, we want the store to lead
1975 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00001976 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00001977 // as the leader
1978 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001979 // If it's a store expression we are using, it means we are not equivalent
1980 // to something earlier.
1981 if (isa<StoreExpression>(E)) {
1982 assert(lookupOperandLeader(SI->getValueOperand()) !=
Daniel Berlina8236562017-04-07 18:38:09 +00001983 NewClass->getLeader());
1984 NewClass->setStoredValue(lookupOperandLeader(SI->getValueOperand()));
Daniel Berlin1316a942017-04-06 18:52:50 +00001985 markValueLeaderChangeTouched(NewClass);
1986 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00001987 DEBUG(dbgs() << "Changing leader of congruence class "
1988 << NewClass->getID() << " from " << *NewClass->getLeader()
1989 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00001990 // If we changed the leader, we have to mark it changed because we don't
1991 // know what it will do to symbolic evlauation.
Daniel Berlina8236562017-04-07 18:38:09 +00001992 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001993 }
1994 // We rely on the code below handling the MemoryAccess change.
1995 }
Daniel Berlina8236562017-04-07 18:38:09 +00001996 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001997 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001998 // True if there is no memory instructions left in a class that had memory
1999 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002000
Daniel Berlin1316a942017-04-06 18:52:50 +00002001 // If it's not a memory use, set the MemoryAccess equivalence
2002 auto *InstMA = dyn_cast_or_null<MemoryDef>(MSSA->getMemoryAccess(I));
Daniel Berlina8236562017-04-07 18:38:09 +00002003 bool InstWasMemoryLeader = InstMA && OldClass->getMemoryLeader() == InstMA;
Daniel Berlin1316a942017-04-06 18:52:50 +00002004 if (InstMA)
2005 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002006 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002007 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002008 if (OldClass->empty() && OldClass != TOPClass) {
2009 if (OldClass->getDefiningExpr()) {
2010 DEBUG(dbgs() << "Erasing expression " << OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002011 << " from table\n");
Daniel Berlina8236562017-04-07 18:38:09 +00002012 ExpressionToClass.erase(OldClass->getDefiningExpr());
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002013 }
Daniel Berlina8236562017-04-07 18:38:09 +00002014 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002015 // When the leader changes, the value numbering of
2016 // everything may change due to symbolization changes, so we need to
2017 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00002018 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002019 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002020 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002021 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002022 // Note that this is basically clean up for the expression removal that
2023 // happens below. If we remove stores from a class, we may leave it as a
2024 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002025 if (OldClass->getStoreCount() == 0) {
2026 if (OldClass->getStoredValue())
2027 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002028 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002029 // If we destroy the old access leader and it's a store, we have to
2030 // effectively destroy the congruence class. When it comes to scalars,
2031 // anything with the same value is as good as any other. That means that
2032 // one leader is as good as another, and as long as you have some leader for
2033 // the value, you are good.. When it comes to *memory states*, only one
2034 // particular thing really represents the definition of a given memory
2035 // state. Once it goes away, we need to re-evaluate which pieces of memory
2036 // are really still equivalent. The best way to do this is to re-value
2037 // number things. The only way to really make that happen is to destroy the
2038 // rest of the class. In order to effectively destroy the class, we reset
2039 // ExpressionToClass for each by using the ValueToExpression mapping. The
2040 // members later get marked as touched due to the leader change. We will
2041 // create new congruence classes, and the pieces that are still equivalent
2042 // will end back together in a new class. If this becomes too expensive, it
2043 // is possible to use a versioning scheme for the congruence classes to
2044 // avoid the expressions finding this old class. Note that the situation is
2045 // different for memory phis, becuase they are evaluated anew each time, and
2046 // they become equal not by hashing, but by seeing if all operands are the
2047 // same (or only one is reachable).
Daniel Berlina8236562017-04-07 18:38:09 +00002048 if (OldClass->getStoreCount() > 0 && InstWasMemoryLeader) {
2049 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002050 << " because MemoryAccess leader changed");
Daniel Berlina8236562017-04-07 18:38:09 +00002051 for (auto Member : *OldClass)
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002052 ExpressionToClass.erase(ValueToExpression.lookup(Member));
2053 }
Daniel Berlina8236562017-04-07 18:38:09 +00002054 OldClass->setLeader(getNextValueLeader(OldClass));
2055 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002056 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002057 }
2058}
2059
Davide Italiano7e274e02016-12-22 16:03:48 +00002060// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002061void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
2062 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002063 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002064 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002065
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002066 CongruenceClass *IClass = ValueToClass[I];
2067 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002068 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002069 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002070
2071 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00002072 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002073 EClass = ValueToClass[VE->getVariableValue()];
2074 } else {
2075 auto lookupResult = ExpressionToClass.insert({E, nullptr});
2076
2077 // If it's not in the value table, create a new congruence class.
2078 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002079 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002080 auto place = lookupResult.first;
2081 place->second = NewClass;
2082
2083 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002084 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002085 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002086 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2087 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002088 NewClass->setLeader(SI);
2089 NewClass->setStoredValue(lookupOperandLeader(SI->getValueOperand()));
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002090 // The RepMemoryAccess field will be filled in properly by the
2091 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002092 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002093 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002094 }
2095 assert(!isa<VariableExpression>(E) &&
2096 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002097
2098 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002099 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002100 << " using expression " << *E << " at " << NewClass->getID()
2101 << " and leader " << *(NewClass->getLeader()));
2102 if (NewClass->getStoredValue())
2103 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002104 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002105 } else {
2106 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002107 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002108 assert((isa<Constant>(EClass->getLeader()) ||
2109 (EClass->getStoredValue() &&
2110 isa<Constant>(EClass->getStoredValue()))) &&
2111 "Any class with a constant expression should have a "
2112 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002113
Davide Italiano7e274e02016-12-22 16:03:48 +00002114 assert(EClass && "Somehow don't have an eclass");
2115
Daniel Berlin1316a942017-04-06 18:52:50 +00002116 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002117 }
2118 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002119 bool ClassChanged = IClass != EClass;
2120 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002121 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002122 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002123 << "\n");
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002124 if (ClassChanged)
Daniel Berlin1316a942017-04-06 18:52:50 +00002125 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002126 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002127 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002128 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002129 if (auto *CI = dyn_cast<CmpInst>(I))
2130 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002131 }
2132}
2133
2134// Process the fact that Edge (from, to) is reachable, including marking
2135// any newly reachable blocks and instructions for processing.
2136void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2137 // Check if the Edge was reachable before.
2138 if (ReachableEdges.insert({From, To}).second) {
2139 // If this block wasn't reachable before, all instructions are touched.
2140 if (ReachableBlocks.insert(To).second) {
2141 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2142 const auto &InstRange = BlockInstRange.lookup(To);
2143 TouchedInstructions.set(InstRange.first, InstRange.second);
2144 } else {
2145 DEBUG(dbgs() << "Block " << getBlockName(To)
2146 << " was reachable, but new edge {" << getBlockName(From)
2147 << "," << getBlockName(To) << "} to it found\n");
2148
2149 // We've made an edge reachable to an existing block, which may
2150 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2151 // they are the only thing that depend on new edges. Anything using their
2152 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00002153 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002154 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002155
Davide Italiano7e274e02016-12-22 16:03:48 +00002156 auto BI = To->begin();
2157 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002158 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002159 ++BI;
2160 }
2161 }
2162 }
2163}
2164
2165// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2166// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002167Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002168 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002169 if (isa<Constant>(Result))
2170 return Result;
2171 return nullptr;
2172}
2173
2174// Process the outgoing edges of a block for reachability.
2175void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2176 // Evaluate reachability of terminator instruction.
2177 BranchInst *BR;
2178 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2179 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002180 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002181 if (!CondEvaluated) {
2182 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002183 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002184 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2185 CondEvaluated = CE->getConstantValue();
2186 }
2187 } else if (isa<ConstantInt>(Cond)) {
2188 CondEvaluated = Cond;
2189 }
2190 }
2191 ConstantInt *CI;
2192 BasicBlock *TrueSucc = BR->getSuccessor(0);
2193 BasicBlock *FalseSucc = BR->getSuccessor(1);
2194 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2195 if (CI->isOne()) {
2196 DEBUG(dbgs() << "Condition for Terminator " << *TI
2197 << " evaluated to true\n");
2198 updateReachableEdge(B, TrueSucc);
2199 } else if (CI->isZero()) {
2200 DEBUG(dbgs() << "Condition for Terminator " << *TI
2201 << " evaluated to false\n");
2202 updateReachableEdge(B, FalseSucc);
2203 }
2204 } else {
2205 updateReachableEdge(B, TrueSucc);
2206 updateReachableEdge(B, FalseSucc);
2207 }
2208 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2209 // For switches, propagate the case values into the case
2210 // destinations.
2211
2212 // Remember how many outgoing edges there are to every successor.
2213 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2214
Davide Italiano7e274e02016-12-22 16:03:48 +00002215 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002216 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002217 // See if we were able to turn this switch statement into a constant.
2218 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002219 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002220 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002221 auto Case = *SI->findCaseValue(CondVal);
2222 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002223 // We proved the value is outside of the range of the case.
2224 // We can't do anything other than mark the default dest as reachable,
2225 // and go home.
2226 updateReachableEdge(B, SI->getDefaultDest());
2227 return;
2228 }
2229 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002230 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002231 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002232 } else {
2233 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2234 BasicBlock *TargetBlock = SI->getSuccessor(i);
2235 ++SwitchEdges[TargetBlock];
2236 updateReachableEdge(B, TargetBlock);
2237 }
2238 }
2239 } else {
2240 // Otherwise this is either unconditional, or a type we have no
2241 // idea about. Just mark successors as reachable.
2242 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2243 BasicBlock *TargetBlock = TI->getSuccessor(i);
2244 updateReachableEdge(B, TargetBlock);
2245 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002246
2247 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002248 // equivalent only to itself.
2249 //
2250 auto *MA = MSSA->getMemoryAccess(TI);
2251 if (MA && !isa<MemoryUse>(MA)) {
2252 auto *CC = ensureLeaderOfMemoryClass(MA);
2253 if (setMemoryClass(MA, CC))
2254 markMemoryUsersTouched(MA);
2255 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002256 }
2257}
2258
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002259// The algorithm initially places the values of the routine in the TOP
2260// congruence class. The leader of TOP is the undetermined value `undef`.
2261// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002262void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002263 NextCongruenceNum = 0;
2264
2265 // Note that even though we use the live on entry def as a representative
2266 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2267 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2268 // should be checking whether the MemoryAccess is top if we want to know if it
2269 // is equivalent to everything. Otherwise, what this really signifies is that
2270 // the access "it reaches all the way back to the beginning of the function"
2271
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002272 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002273 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002274 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002275 // The live on entry def gets put into it's own class
2276 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2277 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002278
Daniel Berlinec9deb72017-04-18 17:06:11 +00002279 for (auto DTN : nodes(DT)) {
2280 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002281 // All MemoryAccesses are equivalent to live on entry to start. They must
2282 // be initialized to something so that initial changes are noticed. For
2283 // the maximal answer, we initialize them all to be the same as
2284 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002285 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002286 if (MemoryBlockDefs)
2287 for (const auto &Def : *MemoryBlockDefs) {
2288 MemoryAccessToClass[&Def] = TOPClass;
2289 auto *MD = dyn_cast<MemoryDef>(&Def);
2290 // Insert the memory phis into the member list.
2291 if (!MD) {
2292 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002293 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002294 MemoryPhiState.insert({MP, MPS_TOP});
2295 }
2296
2297 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002298 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002299 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002300 for (auto &I : *BB) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00002301 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002302 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002303 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2304 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002305 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002306 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002307 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002308 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002309
2310 // Initialize arguments to be in their own unique congruence classes
2311 for (auto &FA : F.args())
2312 createSingletonCongruenceClass(&FA);
2313}
2314
2315void NewGVN::cleanupTables() {
2316 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002317 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2318 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002319 // Make sure we delete the congruence class (probably worth switching to
2320 // a unique_ptr at some point.
2321 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002322 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002323 }
2324
2325 ValueToClass.clear();
2326 ArgRecycler.clear(ExpressionAllocator);
2327 ExpressionAllocator.Reset();
2328 CongruenceClasses.clear();
2329 ExpressionToClass.clear();
2330 ValueToExpression.clear();
2331 ReachableBlocks.clear();
2332 ReachableEdges.clear();
2333#ifndef NDEBUG
2334 ProcessedCount.clear();
2335#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002336 InstrDFS.clear();
2337 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002338 DFSToInstr.clear();
2339 BlockInstRange.clear();
2340 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002341 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002342 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002343 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002344}
2345
2346std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2347 unsigned Start) {
2348 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002349 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
2350 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002351 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002352 }
2353
Davide Italiano7e274e02016-12-22 16:03:48 +00002354 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002355 // There's no need to call isInstructionTriviallyDead more than once on
2356 // an instruction. Therefore, once we know that an instruction is dead
2357 // we change its DFS number so that it doesn't get value numbered.
2358 if (isInstructionTriviallyDead(&I, TLI)) {
2359 InstrDFS[&I] = 0;
2360 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2361 markInstructionForDeletion(&I);
2362 continue;
2363 }
2364
Davide Italiano7e274e02016-12-22 16:03:48 +00002365 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002366 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002367 }
2368
2369 // All of the range functions taken half-open ranges (open on the end side).
2370 // So we do not subtract one from count, because at this point it is one
2371 // greater than the last instruction.
2372 return std::make_pair(Start, End);
2373}
2374
2375void NewGVN::updateProcessedCount(Value *V) {
2376#ifndef NDEBUG
2377 if (ProcessedCount.count(V) == 0) {
2378 ProcessedCount.insert({V, 1});
2379 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002380 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002381 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002382 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002383 }
2384#endif
2385}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002386// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2387void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2388 // If all the arguments are the same, the MemoryPhi has the same value as the
2389 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00002390 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00002391 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002392 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002393 return lookupMemoryLeader(cast<MemoryAccess>(U)) != MP &&
Daniel Berlinc4796862017-01-27 02:37:11 +00002394 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002395 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002396 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002397 // If all that is left is nothing, our memoryphi is undef. We keep it as
2398 // InitialClass. Note: The only case this should happen is if we have at
2399 // least one self-argument.
2400 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002401 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002402 markMemoryUsersTouched(MP);
2403 return;
2404 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002405
2406 // Transform the remaining operands into operand leaders.
2407 // FIXME: mapped_iterator should have a range version.
2408 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002409 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002410 };
2411 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2412 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2413
2414 // and now check if all the elements are equal.
2415 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002416 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002417 ++MappedBegin;
2418 bool AllEqual = std::all_of(
2419 MappedBegin, MappedEnd,
2420 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2421
2422 if (AllEqual)
2423 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2424 else
2425 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002426 // If it's equal to something, it's in that class. Otherwise, it has to be in
2427 // a class where it is the leader (other things may be equivalent to it, but
2428 // it needs to start off in its own class, which means it must have been the
2429 // leader, and it can't have stopped being the leader because it was never
2430 // removed).
2431 CongruenceClass *CC =
2432 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2433 auto OldState = MemoryPhiState.lookup(MP);
2434 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2435 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2436 MemoryPhiState[MP] = NewState;
2437 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002438 markMemoryUsersTouched(MP);
2439}
2440
2441// Value number a single instruction, symbolically evaluating, performing
2442// congruence finding, and updating mappings.
2443void NewGVN::valueNumberInstruction(Instruction *I) {
2444 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002445 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002446 const Expression *Symbolized = nullptr;
2447 if (DebugCounter::shouldExecute(VNCounter)) {
2448 Symbolized = performSymbolicEvaluation(I);
2449 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002450 // Mark the instruction as unused so we don't value number it again.
2451 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002452 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002453 // If we couldn't come up with a symbolic expression, use the unknown
2454 // expression
Daniel Berlin1316a942017-04-06 18:52:50 +00002455 if (Symbolized == nullptr) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002456 Symbolized = createUnknownExpression(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00002457 }
2458
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002459 performCongruenceFinding(I, Symbolized);
2460 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002461 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002462 // don't currently understand. We don't place non-value producing
2463 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002464 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002465 auto *Symbolized = createUnknownExpression(I);
2466 performCongruenceFinding(I, Symbolized);
2467 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002468 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2469 }
2470}
Davide Italiano7e274e02016-12-22 16:03:48 +00002471
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002472// Check if there is a path, using single or equal argument phi nodes, from
2473// First to Second.
2474bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
2475 const MemoryAccess *Second) const {
2476 if (First == Second)
2477 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002478 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002479 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002480
Daniel Berlin871ecd92017-04-01 09:44:24 +00002481 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002482 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002483 if (ChainDef == Second)
2484 return true;
2485 if (MSSA->isLiveOnEntryDef(ChainDef))
2486 return false;
2487 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002488 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002489 auto *MP = cast<MemoryPhi>(EndDef);
2490 auto ReachableOperandPred = [&](const Use &U) {
2491 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2492 };
2493 auto FilteredPhiArgs =
2494 make_filter_range(MP->operands(), ReachableOperandPred);
2495 SmallVector<const Value *, 32> OperandList;
2496 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2497 std::back_inserter(OperandList));
2498 bool Okay = OperandList.size() == 1;
2499 if (!Okay)
2500 Okay =
2501 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2502 if (Okay)
2503 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
2504 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002505}
2506
Daniel Berlin589cecc2017-01-02 18:00:46 +00002507// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002508// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002509// subject to very rare false negatives. It is only useful for
2510// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002511void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002512#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002513 // Verify that the memory table equivalence and memory member set match
2514 for (const auto *CC : CongruenceClasses) {
2515 if (CC == TOPClass || CC->isDead())
2516 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002517 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00002518 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002519 "Any class with a store as a leader should have a "
2520 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00002521 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002522 "Any congruence class with a store should have a "
2523 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00002524 }
2525
Daniel Berlina8236562017-04-07 18:38:09 +00002526 if (CC->getMemoryLeader())
2527 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00002528 "Representative MemoryAccess does not appear to be reverse "
2529 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00002530 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002531 assert(MemoryAccessToClass.lookup(M) == CC &&
2532 "Memory member does not appear to be reverse mapped properly");
2533 }
2534
2535 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002536 // congruence class.
2537
2538 // Filter out the unreachable and trivially dead entries, because they may
2539 // never have been updated if the instructions were not processed.
2540 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002541 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002542 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00002543 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2544 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00002545 return false;
2546 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2547 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
2548 return true;
2549 };
2550
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002551 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002552 for (auto KV : Filtered) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002553 assert(KV.second != TOPClass &&
2554 "Memory not unreachable but ended up in TOP");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002555 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002556 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italiano67ada752017-01-02 19:03:16 +00002557 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00002558 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002559 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2560 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2561 "The instructions for these memory operations should have "
2562 "been in the same congruence class or reachable through"
2563 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002564 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002565 // We can only sanely verify that MemoryDefs in the operand list all have
2566 // the same class.
2567 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002568 return ReachableEdges.count(
2569 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002570 isa<MemoryDef>(U);
2571
2572 };
2573 // All arguments should in the same class, ignoring unreachable arguments
2574 auto FilteredPhiArgs =
2575 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2576 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2577 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2578 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2579 const MemoryDef *MD = cast<MemoryDef>(U);
2580 return ValueToClass.lookup(MD->getMemoryInst());
2581 });
2582 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2583 PhiOpClasses.begin()) &&
2584 "All MemoryPhi arguments should be in the same class");
2585 }
2586 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002587#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002588}
2589
Daniel Berlin06329a92017-03-18 15:41:40 +00002590// Verify that the sparse propagation we did actually found the maximal fixpoint
2591// We do this by storing the value to class mapping, touching all instructions,
2592// and redoing the iteration to see if anything changed.
2593void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002594#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002595 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002596 if (DebugCounter::isCounterSet(VNCounter))
2597 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2598
2599 // Note that we have to store the actual classes, as we may change existing
2600 // classes during iteration. This is because our memory iteration propagation
2601 // is not perfect, and so may waste a little work. But it should generate
2602 // exactly the same congruence classes we have now, with different IDs.
2603 std::map<const Value *, CongruenceClass> BeforeIteration;
2604
2605 for (auto &KV : ValueToClass) {
2606 if (auto *I = dyn_cast<Instruction>(KV.first))
2607 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002608 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002609 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002610 BeforeIteration.insert({KV.first, *KV.second});
2611 }
2612
2613 TouchedInstructions.set();
2614 TouchedInstructions.reset(0);
2615 iterateTouchedInstructions();
2616 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2617 EqualClasses;
2618 for (const auto &KV : ValueToClass) {
2619 if (auto *I = dyn_cast<Instruction>(KV.first))
2620 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002621 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00002622 continue;
2623 // We could sink these uses, but i think this adds a bit of clarity here as
2624 // to what we are comparing.
2625 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2626 auto *AfterCC = KV.second;
2627 // Note that the classes can't change at this point, so we memoize the set
2628 // that are equal.
2629 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00002630 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00002631 "Value number changed after main loop completed!");
2632 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002633 }
2634 }
2635#endif
2636}
2637
Daniel Berlin06329a92017-03-18 15:41:40 +00002638// This is the main value numbering loop, it iterates over the initial touched
2639// instruction set, propagating value numbers, marking things touched, etc,
2640// until the set of touched instructions is completely empty.
2641void NewGVN::iterateTouchedInstructions() {
2642 unsigned int Iterations = 0;
2643 // Figure out where touchedinstructions starts
2644 int FirstInstr = TouchedInstructions.find_first();
2645 // Nothing set, nothing to iterate, just return.
2646 if (FirstInstr == -1)
2647 return;
Daniel Berlin21279bd2017-04-06 18:52:58 +00002648 BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00002649 while (TouchedInstructions.any()) {
2650 ++Iterations;
2651 // Walk through all the instructions in all the blocks in RPO.
2652 // TODO: As we hit a new block, we should push and pop equalities into a
2653 // table lookupOperandLeader can use, to catch things PredicateInfo
2654 // might miss, like edge-only equivalences.
2655 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2656 InstrNum = TouchedInstructions.find_next(InstrNum)) {
2657
2658 // This instruction was found to be dead. We don't bother looking
2659 // at it again.
2660 if (InstrNum == 0) {
2661 TouchedInstructions.reset(InstrNum);
2662 continue;
2663 }
2664
Daniel Berlin21279bd2017-04-06 18:52:58 +00002665 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlin06329a92017-03-18 15:41:40 +00002666 BasicBlock *CurrBlock = getBlockForValue(V);
2667
2668 // If we hit a new block, do reachability processing.
2669 if (CurrBlock != LastBlock) {
2670 LastBlock = CurrBlock;
2671 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2672 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2673
2674 // If it's not reachable, erase any touched instructions and move on.
2675 if (!BlockReachable) {
2676 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2677 DEBUG(dbgs() << "Skipping instructions in block "
2678 << getBlockName(CurrBlock)
2679 << " because it is unreachable\n");
2680 continue;
2681 }
2682 updateProcessedCount(CurrBlock);
2683 }
2684
2685 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2686 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2687 valueNumberMemoryPhi(MP);
2688 } else if (auto *I = dyn_cast<Instruction>(V)) {
2689 valueNumberInstruction(I);
2690 } else {
2691 llvm_unreachable("Should have been a MemoryPhi or Instruction");
2692 }
2693 updateProcessedCount(V);
2694 // Reset after processing (because we may mark ourselves as touched when
2695 // we propagate equalities).
2696 TouchedInstructions.reset(InstrNum);
2697 }
2698 }
2699 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2700}
2701
Daniel Berlin85f91b02016-12-26 20:06:58 +00002702// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00002703bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00002704 if (DebugCounter::isCounterSet(VNCounter))
2705 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00002706 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00002707 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00002708 MSSAWalker = MSSA->getWalker();
2709
2710 // Count number of instructions for sizing of hash tables, and come
2711 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002712 unsigned ICount = 1;
2713 // Add an empty instruction to account for the fact that we start at 1
2714 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002715 // Note: We want ideal RPO traversal of the blocks, which is not quite the
2716 // same as dominator tree order, particularly with regard whether backedges
2717 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00002718 // If we visit in the wrong order, we will end up performing N times as many
2719 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002720 // The dominator tree does guarantee that, for a given dom tree node, it's
2721 // parent must occur before it in the RPO ordering. Thus, we only need to sort
2722 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00002723 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00002724 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002725 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002726 auto *Node = DT->getNode(B);
2727 assert(Node && "RPO and Dominator tree should have same reachability");
2728 RPOOrdering[Node] = ++Counter;
2729 }
2730 // Sort dominator tree children arrays into RPO.
2731 for (auto &B : RPOT) {
2732 auto *Node = DT->getNode(B);
2733 if (Node->getChildren().size() > 1)
2734 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00002735 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002736 return RPOOrdering[A] < RPOOrdering[B];
2737 });
2738 }
2739
2740 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002741 for (auto DTN : depth_first(DT->getRootNode())) {
2742 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00002743 const auto &BlockRange = assignDFSNumbers(B, ICount);
2744 BlockInstRange.insert({B, BlockRange});
2745 ICount += BlockRange.second - BlockRange.first;
2746 }
2747
Daniel Berline0bd37e2016-12-29 22:15:12 +00002748 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002749 // Ensure we don't end up resizing the expressionToClass map, as
2750 // that can be quite expensive. At most, we have one expression per
2751 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002752 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002753
2754 // Initialize the touched instructions to include the entry block.
2755 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2756 TouchedInstructions.set(InstRange.first, InstRange.second);
2757 ReachableBlocks.insert(&F.getEntryBlock());
2758
2759 initializeCongruenceClasses(F);
Daniel Berlin06329a92017-03-18 15:41:40 +00002760 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00002761 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00002762 verifyIterationSettled(F);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002763
Davide Italiano7e274e02016-12-22 16:03:48 +00002764 Changed |= eliminateInstructions(F);
2765
2766 // Delete all instructions marked for deletion.
2767 for (Instruction *ToErase : InstructionsToErase) {
2768 if (!ToErase->use_empty())
2769 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2770
2771 ToErase->eraseFromParent();
2772 }
2773
2774 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002775 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2776 return !ReachableBlocks.count(&BB);
2777 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002778
2779 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2780 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002781 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002782 deleteInstructionsInBlock(&BB);
2783 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002784 }
2785
2786 cleanupTables();
2787 return Changed;
2788}
2789
Davide Italiano7e274e02016-12-22 16:03:48 +00002790// Return true if V is a value that will always be available (IE can
2791// be placed anywhere) in the function. We don't do globals here
2792// because they are often worse to put in place.
2793// TODO: Separate cost from availability
2794static bool alwaysAvailable(Value *V) {
2795 return isa<Constant>(V) || isa<Argument>(V);
2796}
2797
Davide Italiano7e274e02016-12-22 16:03:48 +00002798struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002799 int DFSIn = 0;
2800 int DFSOut = 0;
2801 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002802 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002803 // The bool in the Def tells us whether the Def is the stored value of a
2804 // store.
2805 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002806 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002807 bool operator<(const ValueDFS &Other) const {
2808 // It's not enough that any given field be less than - we have sets
2809 // of fields that need to be evaluated together to give a proper ordering.
2810 // For example, if you have;
2811 // DFS (1, 3)
2812 // Val 0
2813 // DFS (1, 2)
2814 // Val 50
2815 // We want the second to be less than the first, but if we just go field
2816 // by field, we will get to Val 0 < Val 50 and say the first is less than
2817 // the second. We only want it to be less than if the DFS orders are equal.
2818 //
2819 // Each LLVM instruction only produces one value, and thus the lowest-level
2820 // differentiator that really matters for the stack (and what we use as as a
2821 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002822 // Everything else in the structure is instruction level, and only affects
2823 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002824 //
2825 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2826 // the order of replacement of uses does not matter.
2827 // IE given,
2828 // a = 5
2829 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002830 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2831 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002832 // The .val will be the same as well.
2833 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002834 // You will replace both, and it does not matter what order you replace them
2835 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2836 // operand 2).
2837 // Similarly for the case of same dfsin, dfsout, localnum, but different
2838 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002839 // a = 5
2840 // b = 6
2841 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002842 // in c, we will a valuedfs for a, and one for b,with everything the same
2843 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002844 // It does not matter what order we replace these operands in.
2845 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002846 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2847 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002848 Other.U);
2849 }
2850};
2851
Daniel Berlinc4796862017-01-27 02:37:11 +00002852// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002853// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00002854// reachable uses for each value is stored in UseCount, and instructions that
2855// seem
2856// dead (have no non-dead uses) are stored in ProbablyDead.
2857void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00002858 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00002859 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00002860 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00002861 for (auto D : Dense) {
2862 // First add the value.
2863 BasicBlock *BB = getBlockForValue(D);
2864 // Constants are handled prior to ever calling this function, so
2865 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002866 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002867 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002868 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002869 VDDef.DFSIn = DomNode->getDFSNumIn();
2870 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002871 // If it's a store, use the leader of the value operand, if it's always
2872 // available, or the value operand. TODO: We could do dominance checks to
2873 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00002874 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002875 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002876 if (alwaysAvailable(Leader)) {
2877 VDDef.Def.setPointer(Leader);
2878 } else {
2879 VDDef.Def.setPointer(SI->getValueOperand());
2880 VDDef.Def.setInt(true);
2881 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002882 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002883 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00002884 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002885 assert(isa<Instruction>(D) &&
2886 "The dense set member should always be an instruction");
Daniel Berlin21279bd2017-04-06 18:52:58 +00002887 VDDef.LocalNum = InstrToDFSNum(D);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002888 DFSOrderedSet.emplace_back(VDDef);
Daniel Berline3e69e12017-03-10 00:32:33 +00002889 Instruction *Def = cast<Instruction>(D);
2890 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002891 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00002892 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002893 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002894 // Don't try to replace into dead uses
2895 if (InstructionsToErase.count(I))
2896 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002897 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002898 // Put the phi node uses in the incoming block.
2899 BasicBlock *IBlock;
2900 if (auto *P = dyn_cast<PHINode>(I)) {
2901 IBlock = P->getIncomingBlock(U);
2902 // Make phi node users appear last in the incoming block
2903 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002904 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002905 } else {
2906 IBlock = I->getParent();
Daniel Berlin21279bd2017-04-06 18:52:58 +00002907 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002908 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002909
2910 // Skip uses in unreachable blocks, as we're going
2911 // to delete them.
2912 if (ReachableBlocks.count(IBlock) == 0)
2913 continue;
2914
Daniel Berlinb66164c2017-01-14 00:24:23 +00002915 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002916 VDUse.DFSIn = DomNode->getDFSNumIn();
2917 VDUse.DFSOut = DomNode->getDFSNumOut();
2918 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00002919 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002920 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002921 }
2922 }
Daniel Berline3e69e12017-03-10 00:32:33 +00002923
2924 // If there are no uses, it's probably dead (but it may have side-effects,
2925 // so not definitely dead. Otherwise, store the number of uses so we can
2926 // track if it becomes dead later).
2927 if (UseCount == 0)
2928 ProbablyDead.insert(Def);
2929 else
2930 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002931 }
2932}
2933
Daniel Berlinc4796862017-01-27 02:37:11 +00002934// This function converts the set of members for a congruence class from values,
2935// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00002936void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00002937 const CongruenceClass &Dense,
2938 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00002939 for (auto D : Dense) {
2940 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2941 continue;
2942
2943 BasicBlock *BB = getBlockForValue(D);
2944 ValueDFS VD;
2945 DomTreeNode *DomNode = DT->getNode(BB);
2946 VD.DFSIn = DomNode->getDFSNumIn();
2947 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002948 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00002949
2950 // If it's an instruction, use the real local dfs number.
2951 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002952 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00002953 else
2954 llvm_unreachable("Should have been an instruction");
2955
2956 LoadsAndStores.emplace_back(VD);
2957 }
2958}
2959
Davide Italiano7e274e02016-12-22 16:03:48 +00002960static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002961 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002962 if (!ReplInst)
2963 return;
2964
Davide Italiano7e274e02016-12-22 16:03:48 +00002965 // Patch the replacement so that it is not more restrictive than the value
2966 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002967 // Note that if 'I' is a load being replaced by some operation,
2968 // for example, by an arithmetic operation, then andIRFlags()
2969 // would just erase all math flags from the original arithmetic
2970 // operation, which is clearly not wanted and not needed.
2971 if (!isa<LoadInst>(I))
2972 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002973
Daniel Berlin86eab152017-02-12 22:25:20 +00002974 // FIXME: If both the original and replacement value are part of the
2975 // same control-flow region (meaning that the execution of one
2976 // guarantees the execution of the other), then we can combine the
2977 // noalias scopes here and do better than the general conservative
2978 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002979
Daniel Berlin86eab152017-02-12 22:25:20 +00002980 // In general, GVN unifies expressions over different control-flow
2981 // regions, and so we need a conservative combination of the noalias
2982 // scopes.
2983 static const unsigned KnownIDs[] = {
2984 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2985 LLVMContext::MD_noalias, LLVMContext::MD_range,
2986 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2987 LLVMContext::MD_invariant_group};
2988 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002989}
2990
2991static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2992 patchReplacementInstruction(I, Repl);
2993 I->replaceAllUsesWith(Repl);
2994}
2995
2996void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2997 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2998 ++NumGVNBlocksDeleted;
2999
Daniel Berline19f0e02017-01-30 17:06:55 +00003000 // Delete the instructions backwards, as it has a reduced likelihood of having
3001 // to update as many def-use and use-def chains. Start after the terminator.
3002 auto StartPoint = BB->rbegin();
3003 ++StartPoint;
3004 // Note that we explicitly recalculate BB->rend() on each iteration,
3005 // as it may change when we remove the first instruction.
3006 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3007 Instruction &Inst = *I++;
3008 if (!Inst.use_empty())
3009 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3010 if (isa<LandingPadInst>(Inst))
3011 continue;
3012
3013 Inst.eraseFromParent();
3014 ++NumGVNInstrDeleted;
3015 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003016 // Now insert something that simplifycfg will turn into an unreachable.
3017 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3018 new StoreInst(UndefValue::get(Int8Ty),
3019 Constant::getNullValue(Int8Ty->getPointerTo()),
3020 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003021}
3022
3023void NewGVN::markInstructionForDeletion(Instruction *I) {
3024 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3025 InstructionsToErase.insert(I);
3026}
3027
3028void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3029
3030 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3031 patchAndReplaceAllUsesWith(I, V);
3032 // We save the actual erasing to avoid invalidating memory
3033 // dependencies until we are done with everything.
3034 markInstructionForDeletion(I);
3035}
3036
3037namespace {
3038
3039// This is a stack that contains both the value and dfs info of where
3040// that value is valid.
3041class ValueDFSStack {
3042public:
3043 Value *back() const { return ValueStack.back(); }
3044 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3045
3046 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003047 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003048 DFSStack.emplace_back(DFSIn, DFSOut);
3049 }
3050 bool empty() const { return DFSStack.empty(); }
3051 bool isInScope(int DFSIn, int DFSOut) const {
3052 if (empty())
3053 return false;
3054 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3055 }
3056
3057 void popUntilDFSScope(int DFSIn, int DFSOut) {
3058
3059 // These two should always be in sync at this point.
3060 assert(ValueStack.size() == DFSStack.size() &&
3061 "Mismatch between ValueStack and DFSStack");
3062 while (
3063 !DFSStack.empty() &&
3064 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3065 DFSStack.pop_back();
3066 ValueStack.pop_back();
3067 }
3068 }
3069
3070private:
3071 SmallVector<Value *, 8> ValueStack;
3072 SmallVector<std::pair<int, int>, 8> DFSStack;
3073};
3074}
Daniel Berlin04443432017-01-07 03:23:47 +00003075
Davide Italiano7e274e02016-12-22 16:03:48 +00003076bool NewGVN::eliminateInstructions(Function &F) {
3077 // This is a non-standard eliminator. The normal way to eliminate is
3078 // to walk the dominator tree in order, keeping track of available
3079 // values, and eliminating them. However, this is mildly
3080 // pointless. It requires doing lookups on every instruction,
3081 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003082 // instructions part of most singleton congruence classes, we know we
3083 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003084
3085 // Instead, this eliminator looks at the congruence classes directly, sorts
3086 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003087 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003088 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003089 // last member. This is worst case O(E log E) where E = number of
3090 // instructions in a single congruence class. In theory, this is all
3091 // instructions. In practice, it is much faster, as most instructions are
3092 // either in singleton congruence classes or can't possibly be eliminated
3093 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003094 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003095 // for elimination purposes.
3096 // TODO: If we wanted to be faster, We could remove any members with no
3097 // overlapping ranges while sorting, as we will never eliminate anything
3098 // with those members, as they don't dominate anything else in our set.
3099
Davide Italiano7e274e02016-12-22 16:03:48 +00003100 bool AnythingReplaced = false;
3101
3102 // Since we are going to walk the domtree anyway, and we can't guarantee the
3103 // DFS numbers are updated, we compute some ourselves.
3104 DT->updateDFSNumbers();
3105
3106 for (auto &B : F) {
3107 if (!ReachableBlocks.count(&B)) {
3108 for (const auto S : successors(&B)) {
3109 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003110 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00003111 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
3112 << getBlockName(&B)
3113 << " with undef due to it being unreachable\n");
3114 for (auto &Operand : Phi.incoming_values())
3115 if (Phi.getIncomingBlock(Operand) == &B)
3116 Operand.set(UndefValue::get(Phi.getType()));
3117 }
3118 }
3119 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003120 }
3121
Daniel Berline3e69e12017-03-10 00:32:33 +00003122 // Map to store the use counts
3123 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlin4d547962017-02-12 23:24:45 +00003124 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00003125 // Track the equivalent store info so we can decide whether to try
3126 // dead store elimination.
3127 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003128 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003129 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003130 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003131 // Everything still in the TOP class is unreachable or dead.
3132 if (CC == TOPClass) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00003133#ifndef NDEBUG
Daniel Berlina8236562017-04-07 18:38:09 +00003134 for (auto M : *CC)
Daniel Berlinb79f5362017-02-11 12:48:50 +00003135 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3136 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003137 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003138 "point");
3139#endif
3140 continue;
3141 }
3142
Daniel Berlina8236562017-04-07 18:38:09 +00003143 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003144 // If this is a leader that is always available, and it's a
3145 // constant or has no equivalences, just replace everything with
3146 // it. We then update the congruence class with whatever members
3147 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003148 Value *Leader =
3149 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003150 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003151 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003152 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003153 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003154 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003155 if (Member == Leader || !isa<Instruction>(Member) ||
3156 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003157 MembersLeft.insert(Member);
3158 continue;
3159 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003160 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3161 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003162 auto *I = cast<Instruction>(Member);
3163 assert(Leader != I && "About to accidentally remove our leader");
3164 replaceInstruction(I, Leader);
3165 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003166 }
Daniel Berlina8236562017-04-07 18:38:09 +00003167 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003168 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00003169 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
3170 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003171 // If this is a singleton, we can skip it.
Daniel Berlina8236562017-04-07 18:38:09 +00003172 if (CC->size() != 1) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003173 // This is a stack because equality replacement/etc may place
3174 // constants in the middle of the member list, and we want to use
3175 // those constant values in preference to the current leader, over
3176 // the scope of those constants.
3177 ValueDFSStack EliminationStack;
3178
3179 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003180 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003181 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003182
3183 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003184 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003185 for (auto &VD : DFSOrderedSet) {
3186 int MemberDFSIn = VD.DFSIn;
3187 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003188 Value *Def = VD.Def.getPointer();
3189 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003190 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003191 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003192 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003193 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00003194
3195 if (EliminationStack.empty()) {
3196 DEBUG(dbgs() << "Elimination Stack is empty\n");
3197 } else {
3198 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3199 << EliminationStack.dfs_back().first << ","
3200 << EliminationStack.dfs_back().second << ")\n");
3201 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003202
3203 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3204 << MemberDFSOut << ")\n");
3205 // First, we see if we are out of scope or empty. If so,
3206 // and there equivalences, we try to replace the top of
3207 // stack with equivalences (if it's on the stack, it must
3208 // not have been eliminated yet).
3209 // Then we synchronize to our current scope, by
3210 // popping until we are back within a DFS scope that
3211 // dominates the current member.
3212 // Then, what happens depends on a few factors
3213 // If the stack is now empty, we need to push
3214 // If we have a constant or a local equivalence we want to
3215 // start using, we also push.
3216 // Otherwise, we walk along, processing members who are
3217 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003218 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003219 bool OutOfScope =
3220 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3221
3222 if (OutOfScope || ShouldPush) {
3223 // Sync to our current scope.
3224 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003225 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003226 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003227 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003228 }
3229 }
3230
Daniel Berline3e69e12017-03-10 00:32:33 +00003231 // Skip the Def's, we only want to eliminate on their uses. But mark
3232 // dominated defs as dead.
3233 if (Def) {
3234 // For anything in this case, what and how we value number
3235 // guarantees that any side-effets that would have occurred (ie
3236 // throwing, etc) can be proven to either still occur (because it's
3237 // dominated by something that has the same side-effects), or never
3238 // occur. Otherwise, we would not have been able to prove it value
3239 // equivalent to something else. For these things, we can just mark
3240 // it all dead. Note that this is different from the "ProbablyDead"
3241 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003242 // easy to prove dead if they are also side-effect free. Note that
3243 // because stores are put in terms of the stored value, we skip
3244 // stored values here. If the stored value is really dead, it will
3245 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003246 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003247 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003248 markInstructionForDeletion(cast<Instruction>(Def));
3249 continue;
3250 }
3251 // At this point, we know it is a Use we are trying to possibly
3252 // replace.
3253
3254 assert(isa<Instruction>(U->get()) &&
3255 "Current def should have been an instruction");
3256 assert(isa<Instruction>(U->getUser()) &&
3257 "Current user should have been an instruction");
3258
3259 // If the thing we are replacing into is already marked to be dead,
3260 // this use is dead. Note that this is true regardless of whether
3261 // we have anything dominating the use or not. We do this here
3262 // because we are already walking all the uses anyway.
3263 Instruction *InstUse = cast<Instruction>(U->getUser());
3264 if (InstructionsToErase.count(InstUse)) {
3265 auto &UseCount = UseCounts[U->get()];
3266 if (--UseCount == 0) {
3267 ProbablyDead.insert(cast<Instruction>(U->get()));
3268 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003269 }
3270
Davide Italiano7e274e02016-12-22 16:03:48 +00003271 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003272 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003273 if (EliminationStack.empty())
3274 continue;
3275
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003276 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003277
Daniel Berlind92e7f92017-01-07 00:01:42 +00003278 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003279 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003280 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003281 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003282 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003283
3284 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003285 // metadata. Skip this if we are replacing predicateinfo with its
3286 // original operand, as we already know we can just drop it.
3287 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003288 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3289 if (!PI || DominatingLeader != PI->OriginalOp)
3290 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003291 U->set(DominatingLeader);
3292 // This is now a use of the dominating leader, which means if the
3293 // dominating leader was dead, it's now live!
3294 auto &LeaderUseCount = UseCounts[DominatingLeader];
3295 // It's about to be alive again.
3296 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3297 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
3298 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003299 AnythingReplaced = true;
3300 }
3301 }
3302 }
3303
Daniel Berline3e69e12017-03-10 00:32:33 +00003304 // At this point, anything still in the ProbablyDead set is actually dead if
3305 // would be trivially dead.
3306 for (auto *I : ProbablyDead)
3307 if (wouldInstructionBeTriviallyDead(I))
3308 markInstructionForDeletion(I);
3309
Davide Italiano7e274e02016-12-22 16:03:48 +00003310 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003311 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003312 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003313 if (!isa<Instruction>(Member) ||
3314 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003315 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003316 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003317
3318 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003319 if (CC->getStoreCount() > 0) {
3320 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003321 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3322 ValueDFSStack EliminationStack;
3323 for (auto &VD : PossibleDeadStores) {
3324 int MemberDFSIn = VD.DFSIn;
3325 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003326 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003327 if (EliminationStack.empty() ||
3328 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3329 // Sync to our current scope.
3330 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3331 if (EliminationStack.empty()) {
3332 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3333 continue;
3334 }
3335 }
3336 // We already did load elimination, so nothing to do here.
3337 if (isa<LoadInst>(Member))
3338 continue;
3339 assert(!EliminationStack.empty());
3340 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003341 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003342 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3343 // Member is dominater by Leader, and thus dead
3344 DEBUG(dbgs() << "Marking dead store " << *Member
3345 << " that is dominated by " << *Leader << "\n");
3346 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003347 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003348 ++NumGVNDeadStores;
3349 }
3350 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003351 }
3352
3353 return AnythingReplaced;
3354}
Daniel Berlin1c087672017-02-11 15:07:01 +00003355
3356// This function provides global ranking of operations so that we can place them
3357// in a canonical order. Note that rank alone is not necessarily enough for a
3358// complete ordering, as constants all have the same rank. However, generally,
3359// we will simplify an operation with all constants so that it doesn't matter
3360// what order they appear in.
3361unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003362 // Prefer undef to anything else
3363 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00003364 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003365 if (isa<Constant>(V))
3366 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00003367 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003368 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003369
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003370 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003371 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003372 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00003373 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003374 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003375 // Unreachable or something else, just return a really large number.
3376 return ~0;
3377}
3378
3379// This is a function that says whether two commutative operations should
3380// have their order swapped when canonicalizing.
3381bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3382 // Because we only care about a total ordering, and don't rewrite expressions
3383 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003384 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003385 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003386}
Daniel Berlin64e68992017-03-12 04:46:45 +00003387
3388class NewGVNLegacyPass : public FunctionPass {
3389public:
3390 static char ID; // Pass identification, replacement for typeid.
3391 NewGVNLegacyPass() : FunctionPass(ID) {
3392 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3393 }
3394 bool runOnFunction(Function &F) override;
3395
3396private:
3397 void getAnalysisUsage(AnalysisUsage &AU) const override {
3398 AU.addRequired<AssumptionCacheTracker>();
3399 AU.addRequired<DominatorTreeWrapperPass>();
3400 AU.addRequired<TargetLibraryInfoWrapperPass>();
3401 AU.addRequired<MemorySSAWrapperPass>();
3402 AU.addRequired<AAResultsWrapperPass>();
3403 AU.addPreserved<DominatorTreeWrapperPass>();
3404 AU.addPreserved<GlobalsAAWrapperPass>();
3405 }
3406};
3407
3408bool NewGVNLegacyPass::runOnFunction(Function &F) {
3409 if (skipFunction(F))
3410 return false;
3411 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3412 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3413 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3414 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3415 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3416 F.getParent()->getDataLayout())
3417 .runGVN();
3418}
3419
3420INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3421 false, false)
3422INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3423INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3424INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3425INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3426INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3427INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3428INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3429 false)
3430
3431char NewGVNLegacyPass::ID = 0;
3432
3433// createGVNPass - The public interface to this file.
3434FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3435
3436PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3437 // Apparently the order in which we get these results matter for
3438 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3439 // the same order here, just in case.
3440 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3441 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3442 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3443 auto &AA = AM.getResult<AAManager>(F);
3444 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3445 bool Changed =
3446 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3447 .runGVN();
3448 if (!Changed)
3449 return PreservedAnalyses::all();
3450 PreservedAnalyses PA;
3451 PA.preserve<DominatorTreeAnalysis>();
3452 PA.preserve<GlobalsAA>();
3453 return PA;
3454}