blob: 4b6a2fd7fda6b49777ac2b7a626a752467f32d95 [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; }
Daniel Berlina8236562017-04-07 18:38:09 +0000286
287 // Value member set
288 bool empty() const { return Members.empty(); }
289 unsigned size() const { return Members.size(); }
290 MemberSet::const_iterator begin() const { return Members.begin(); }
291 MemberSet::const_iterator end() const { return Members.end(); }
292 void insert(MemberType *M) { Members.insert(M); }
293 void erase(MemberType *M) { Members.erase(M); }
294 void swap(MemberSet &Other) { Members.swap(Other); }
295
296 // Memory member set
297 bool memory_empty() const { return MemoryMembers.empty(); }
298 unsigned memory_size() const { return MemoryMembers.size(); }
299 MemoryMemberSet::const_iterator memory_begin() const {
300 return MemoryMembers.begin();
301 }
302 MemoryMemberSet::const_iterator memory_end() const {
303 return MemoryMembers.end();
304 }
305 iterator_range<MemoryMemberSet::const_iterator> memory() const {
306 return make_range(memory_begin(), memory_end());
307 }
308 void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
309 void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
310
311 // Store count
312 unsigned getStoreCount() const { return StoreCount; }
313 void incStoreCount() { ++StoreCount; }
314 void decStoreCount() {
315 assert(StoreCount != 0 && "Store count went negative");
316 --StoreCount;
317 }
318
Davide Italianodc435322017-05-10 19:57:43 +0000319 // True if this class has no memory members.
320 bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
321
Daniel Berlina8236562017-04-07 18:38:09 +0000322 // Return true if two congruence classes are equivalent to each other. This
323 // means
324 // that every field but the ID number and the dead field are equivalent.
325 bool isEquivalentTo(const CongruenceClass *Other) const {
326 if (!Other)
327 return false;
328 if (this == Other)
329 return true;
330
331 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
332 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
333 Other->RepMemoryAccess))
334 return false;
335 if (DefiningExpr != Other->DefiningExpr)
336 if (!DefiningExpr || !Other->DefiningExpr ||
337 *DefiningExpr != *Other->DefiningExpr)
338 return false;
339 // We need some ordered set
340 std::set<Value *> AMembers(Members.begin(), Members.end());
341 std::set<Value *> BMembers(Members.begin(), Members.end());
342 return AMembers == BMembers;
343 }
344
345private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000346 unsigned ID;
347 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000348 Value *RepLeader = nullptr;
Daniel Berlina8236562017-04-07 18:38:09 +0000349 // The most dominating leader after our current leader, because the member set
350 // is not sorted and is expensive to keep sorted all the time.
351 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
Daniel Berlin1316a942017-04-06 18:52:50 +0000352 // If this is represented by a store, the value of the store.
Daniel Berlin26addef2017-01-20 21:04:30 +0000353 Value *RepStoredValue = nullptr;
Daniel Berlin1316a942017-04-06 18:52:50 +0000354 // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
355 // access.
356 const MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000357 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000358 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000359 // Actual members of this class.
360 MemberSet Members;
Daniel Berlin1316a942017-04-06 18:52:50 +0000361 // This is the set of MemoryPhis that exist in the class. MemoryDefs and
362 // MemoryUses have real instructions representing them, so we only need to
363 // track MemoryPhis here.
364 MemoryMemberSet MemoryMembers;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000365 // Number of stores in this congruence class.
366 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000367 int StoreCount = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +0000368};
369
370namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000371template <> struct DenseMapInfo<const Expression *> {
372 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000373 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000374 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
375 return reinterpret_cast<const Expression *>(Val);
376 }
377 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000378 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000379 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
380 return reinterpret_cast<const Expression *>(Val);
381 }
382 static unsigned getHashValue(const Expression *V) {
383 return static_cast<unsigned>(V->getHashValue());
384 }
385 static bool isEqual(const Expression *LHS, const Expression *RHS) {
386 if (LHS == RHS)
387 return true;
388 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
389 LHS == getEmptyKey() || RHS == getEmptyKey())
390 return false;
391 return *LHS == *RHS;
392 }
393};
Davide Italiano7e274e02016-12-22 16:03:48 +0000394} // end namespace llvm
395
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000396namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000397class NewGVN {
398 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000399 DominatorTree *DT;
Daniel Berlin64e68992017-03-12 04:46:45 +0000400 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000401 AliasAnalysis *AA;
402 MemorySSA *MSSA;
403 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000404 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000405 std::unique_ptr<PredicateInfo> PredInfo;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000406
407 // These are the only two things the create* functions should have
408 // side-effects on due to allocating memory.
409 mutable BumpPtrAllocator ExpressionAllocator;
410 mutable ArrayRecycler<Value *> ArgRecycler;
411 mutable TarjanSCC SCCFinder;
Daniel Berlinede130d2017-04-26 20:56:14 +0000412 const SimplifyQuery SQ;
Davide Italiano7e274e02016-12-22 16:03:48 +0000413
Daniel Berlin1c087672017-02-11 15:07:01 +0000414 // Number of function arguments, used by ranking
415 unsigned int NumFuncArgs;
416
Daniel Berlin2f72b192017-04-14 02:53:37 +0000417 // RPOOrdering of basic blocks
418 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
419
Davide Italiano7e274e02016-12-22 16:03:48 +0000420 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000421
422 // This class is called INITIAL in the paper. It is the class everything
423 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000424 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000425 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000426 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000427 std::vector<CongruenceClass *> CongruenceClasses;
428 unsigned NextCongruenceNum;
429
430 // Value Mappings.
431 DenseMap<Value *, CongruenceClass *> ValueToClass;
432 DenseMap<Value *, const Expression *> ValueToExpression;
433
Daniel Berlinf7d95802017-02-18 23:06:50 +0000434 // Mapping from predicate info we used to the instructions we used it with.
435 // In order to correctly ensure propagation, we must keep track of what
436 // comparisons we used, so that when the values of the comparisons change, we
437 // propagate the information to the places we used the comparison.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000438 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
439 PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000440 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
441 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000442 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
443 MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000444
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000445 // A table storing which memorydefs/phis represent a memory state provably
446 // equivalent to another memory state.
447 // We could use the congruence class machinery, but the MemoryAccess's are
448 // abstract memory states, so they can only ever be equivalent to each other,
449 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000450 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000451
Daniel Berlin1316a942017-04-06 18:52:50 +0000452 // We could, if we wanted, build MemoryPhiExpressions and
453 // MemoryVariableExpressions, etc, and value number them the same way we value
454 // number phi expressions. For the moment, this seems like overkill. They
455 // can only exist in one of three states: they can be TOP (equal to
456 // everything), Equivalent to something else, or unique. Because we do not
457 // create expressions for them, we need to simulate leader change not just
458 // when they change class, but when they change state. Note: We can do the
459 // same thing for phis, and avoid having phi expressions if we wanted, We
460 // should eventually unify in one direction or the other, so this is a little
461 // bit of an experiment in which turns out easier to maintain.
462 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
463 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
464
Daniel Berlin2f72b192017-04-14 02:53:37 +0000465 enum PhiCycleState { PCS_Unknown, PCS_CycleFree, PCS_Cycle };
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000466 mutable DenseMap<const PHINode *, PhiCycleState> PhiCycleState;
Davide Italiano7e274e02016-12-22 16:03:48 +0000467 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000468 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000469 ExpressionClassMap ExpressionToClass;
470
471 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000472 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000473
474 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000475 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000476 DenseSet<BlockEdge> ReachableEdges;
477 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
478
479 // This is a bitvector because, on larger functions, we may have
480 // thousands of touched instructions at once (entire blocks,
481 // instructions with hundreds of uses, etc). Even with optimization
482 // for when we mark whole blocks as touched, when this was a
483 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
484 // the time in GVN just managing this list. The bitvector, on the
485 // other hand, efficiently supports test/set/clear of both
486 // individual and ranges, as well as "find next element" This
487 // enables us to use it as a worklist with essentially 0 cost.
488 BitVector TouchedInstructions;
489
490 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000491
492#ifndef NDEBUG
493 // Debugging for how many times each block and instruction got processed.
494 DenseMap<const Value *, unsigned> ProcessedCount;
495#endif
496
497 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000498 // This contains a mapping from Instructions to DFS numbers.
499 // The numbering starts at 1. An instruction with DFS number zero
500 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000501 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000502
503 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000504 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000505
506 // Deletion info.
507 SmallPtrSet<Instruction *, 8> InstructionsToErase;
508
509public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000510 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
511 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
512 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000513 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Daniel Berlinede130d2017-04-26 20:56:14 +0000514 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
515 }
Daniel Berlin64e68992017-03-12 04:46:45 +0000516 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000517
518private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000519 // Expression handling.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000520 const Expression *createExpression(Instruction *) const;
521 const Expression *createBinaryExpression(unsigned, Type *, Value *,
522 Value *) const;
523 PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge,
524 bool &AllConstant) const;
525 const VariableExpression *createVariableExpression(Value *) const;
526 const ConstantExpression *createConstantExpression(Constant *) const;
527 const Expression *createVariableOrConstant(Value *V) const;
528 const UnknownExpression *createUnknownExpression(Instruction *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000529 const StoreExpression *createStoreExpression(StoreInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000530 const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000531 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000532 const MemoryAccess *) const;
533 const CallExpression *createCallExpression(CallInst *,
534 const MemoryAccess *) const;
535 const AggregateValueExpression *
536 createAggregateValueExpression(Instruction *) const;
537 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000538
539 // Congruence class handling.
540 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000541 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000542 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000543 return result;
544 }
545
Daniel Berlin1316a942017-04-06 18:52:50 +0000546 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
547 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000548 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000549 return CC;
550 }
551 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
552 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000553 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000554 CC = createMemoryClass(MA);
555 return CC;
556 }
557
Davide Italiano7e274e02016-12-22 16:03:48 +0000558 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000559 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000560 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000561 ValueToClass[Member] = CClass;
562 return CClass;
563 }
564 void initializeCongruenceClasses(Function &F);
565
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000566 // Value number an Instruction or MemoryPhi.
567 void valueNumberMemoryPhi(MemoryPhi *);
568 void valueNumberInstruction(Instruction *);
569
Davide Italiano7e274e02016-12-22 16:03:48 +0000570 // Symbolic evaluation.
571 const Expression *checkSimplificationResults(Expression *, Instruction *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000572 Value *) const;
573 const Expression *performSymbolicEvaluation(Value *) const;
Daniel Berlin07daac82017-04-02 13:23:44 +0000574 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000575 Instruction *,
576 MemoryAccess *) const;
577 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
578 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
579 const Expression *performSymbolicCallEvaluation(Instruction *) const;
580 const Expression *performSymbolicPHIEvaluation(Instruction *) const;
581 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
582 const Expression *performSymbolicCmpEvaluation(Instruction *) const;
583 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000584
585 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000586 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000587 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000588 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000589 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
590 CongruenceClass *, CongruenceClass *);
591 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
592 CongruenceClass *, CongruenceClass *);
593 Value *getNextValueLeader(CongruenceClass *) const;
594 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
595 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
596 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
597 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000598 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000599
Daniel Berlin1c087672017-02-11 15:07:01 +0000600 // Ranking
601 unsigned int getRank(const Value *) const;
602 bool shouldSwapOperands(const Value *, const Value *) const;
603
Davide Italiano7e274e02016-12-22 16:03:48 +0000604 // Reachability handling.
605 void updateReachableEdge(BasicBlock *, BasicBlock *);
606 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000607 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000608
609 // Elimination.
610 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000611 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000612 SmallVectorImpl<ValueDFS> &,
613 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000614 SmallPtrSetImpl<Instruction *> &) const;
615 void convertClassToLoadsAndStores(const CongruenceClass &,
616 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000617
618 bool eliminateInstructions(Function &);
619 void replaceInstruction(Instruction *, Value *);
620 void markInstructionForDeletion(Instruction *);
621 void deleteInstructionsInBlock(BasicBlock *);
622
623 // New instruction creation.
624 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000625
626 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000627 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000628 void markMemoryUsersTouched(const MemoryAccess *);
629 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000630 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000631 void markValueLeaderChangeTouched(CongruenceClass *CC);
632 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000633 void addPredicateUsers(const PredicateBase *, Instruction *) const;
634 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000635
Daniel Berlin06329a92017-03-18 15:41:40 +0000636 // Main loop of value numbering
637 void iterateTouchedInstructions();
638
Davide Italiano7e274e02016-12-22 16:03:48 +0000639 // Utilities.
640 void cleanupTables();
641 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
642 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000643 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000644 void verifyIterationSettled(Function &F);
Daniel Berlin45403572017-05-16 19:58:47 +0000645 void verifyStoreExpressions() const;
Davide Italianoeab0de22017-05-18 23:22:44 +0000646 bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
647 const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000648 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000649 void deleteExpression(const Expression *E) const;
Daniel Berlin21279bd2017-04-06 18:52:58 +0000650 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000651 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
652 return InstrDFS.lookup(V);
653 }
654
Daniel Berlin21279bd2017-04-06 18:52:58 +0000655 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
656 return MemoryToDFSNum(MA);
657 }
658 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
659 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
660 // This deliberately takes a value so it can be used with Use's, which will
661 // auto-convert to Value's but not to MemoryAccess's.
662 unsigned MemoryToDFSNum(const Value *MA) const {
663 assert(isa<MemoryAccess>(MA) &&
664 "This should not be used with instructions");
665 return isa<MemoryUseOrDef>(MA)
666 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
667 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000668 }
Daniel Berlinabd632d2017-05-16 06:06:12 +0000669 bool isCycleFree(const PHINode *PN) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000670 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000671 // Debug counter info. When verifying, we have to reset the value numbering
672 // debug counter to the same state it started in to get the same results.
673 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000674};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000675} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000676
Davide Italianob1114092016-12-28 13:37:17 +0000677template <typename T>
678static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000679 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000680 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000681 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000682}
683
Davide Italianob1114092016-12-28 13:37:17 +0000684bool LoadExpression::equals(const Expression &Other) const {
685 return equalsLoadStoreHelper(*this, Other);
686}
Davide Italiano7e274e02016-12-22 16:03:48 +0000687
Davide Italianob1114092016-12-28 13:37:17 +0000688bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000689 if (!equalsLoadStoreHelper(*this, Other))
690 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000691 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000692 if (const auto *S = dyn_cast<StoreExpression>(&Other))
693 if (getStoredValue() != S->getStoredValue())
694 return false;
695 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000696}
697
698#ifndef NDEBUG
699static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000700 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000701}
702#endif
703
Daniel Berlin06329a92017-03-18 15:41:40 +0000704// Get the basic block from an instruction/memory value.
705BasicBlock *NewGVN::getBlockForValue(Value *V) const {
706 if (auto *I = dyn_cast<Instruction>(V))
707 return I->getParent();
708 else if (auto *MP = dyn_cast<MemoryPhi>(V))
709 return MP->getBlock();
710 llvm_unreachable("Should have been able to figure out a block for our value");
711 return nullptr;
712}
713
Daniel Berlin0e900112017-03-24 06:33:48 +0000714// Delete a definitely dead expression, so it can be reused by the expression
715// allocator. Some of these are not in creation functions, so we have to accept
716// const versions.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000717void NewGVN::deleteExpression(const Expression *E) const {
Daniel Berlin0e900112017-03-24 06:33:48 +0000718 assert(isa<BasicExpression>(E));
719 auto *BE = cast<BasicExpression>(E);
720 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
721 ExpressionAllocator.Deallocate(E);
722}
723
Daniel Berlin2f72b192017-04-14 02:53:37 +0000724PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000725 bool &AllConstant) const {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000726 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000727 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000728 auto *E =
729 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000730
731 E->allocateOperands(ArgRecycler, ExpressionAllocator);
732 E->setType(I->getType());
733 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000734
Daniel Berlin2f72b192017-04-14 02:53:37 +0000735 unsigned PHIRPO = RPOOrdering.lookup(DT->getNode(PHIBlock));
736
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000737 // NewGVN assumes the operands of a PHI node are in a consistent order across
738 // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
739 // this in LLVM at some point we don't want GVN to find wrong congruences.
740 // Therefore, here we sort uses in predecessor order.
Davide Italiano63998ec2017-05-09 18:29:37 +0000741 // We're sorting the values by pointer. In theory this might be cause of
742 // non-determinism, but here we don't rely on the ordering for anything
743 // significant, e.g. we don't create new instructions based on it so we're
744 // fine.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000745 SmallVector<const Use *, 4> PHIOperands;
746 for (const Use &U : PN->operands())
747 PHIOperands.push_back(&U);
748 std::sort(PHIOperands.begin(), PHIOperands.end(),
749 [&](const Use *U1, const Use *U2) {
750 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
751 });
752
Davide Italianob3886dd2017-01-25 23:37:49 +0000753 // Filter out unreachable phi operands.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000754 auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
755 return ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000756 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000757
758 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000759 [&](const Use *U) -> Value * {
760 auto *BB = PN->getIncomingBlock(*U);
Daniel Berlin2f72b192017-04-14 02:53:37 +0000761 auto *DTN = DT->getNode(BB);
762 if (RPOOrdering.lookup(DTN) >= PHIRPO)
763 HasBackedge = true;
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000764 AllConstant &= isa<UndefValue>(*U) || isa<Constant>(*U);
Daniel Berlin2f72b192017-04-14 02:53:37 +0000765
Daniel Berlind92e7f92017-01-07 00:01:42 +0000766 // Don't try to transform self-defined phis.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000767 if (*U == PN)
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000768 return PN;
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000769 return lookupOperandLeader(*U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000770 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000771 return E;
772}
773
774// Set basic expression info (Arguments, type, opcode) for Expression
775// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000776bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000777 bool AllConstant = true;
778 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
779 E->setType(GEP->getSourceElementType());
780 else
781 E->setType(I->getType());
782 E->setOpcode(I->getOpcode());
783 E->allocateOperands(ArgRecycler, ExpressionAllocator);
784
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000785 // Transform the operand array into an operand leader array, and keep track of
786 // whether all members are constant.
787 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000788 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000789 AllConstant &= isa<Constant>(Operand);
790 return Operand;
791 });
792
Davide Italiano7e274e02016-12-22 16:03:48 +0000793 return AllConstant;
794}
795
796const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000797 Value *Arg1,
798 Value *Arg2) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000799 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000800
801 E->setType(T);
802 E->setOpcode(Opcode);
803 E->allocateOperands(ArgRecycler, ExpressionAllocator);
804 if (Instruction::isCommutative(Opcode)) {
805 // Ensure that commutative instructions that only differ by a permutation
806 // of their operands get the same value number by sorting the operand value
807 // numbers. Since all commutative instructions have two operands it is more
808 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000809 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000810 std::swap(Arg1, Arg2);
811 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000812 E->op_push_back(lookupOperandLeader(Arg1));
813 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000814
Daniel Berlinede130d2017-04-26 20:56:14 +0000815 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000816 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
817 return SimplifiedE;
818 return E;
819}
820
821// Take a Value returned by simplification of Expression E/Instruction
822// I, and see if it resulted in a simpler expression. If so, return
823// that expression.
824// TODO: Once finished, this should not take an Instruction, we only
825// use it for printing.
826const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000827 Instruction *I,
828 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000829 if (!V)
830 return nullptr;
831 if (auto *C = dyn_cast<Constant>(V)) {
832 if (I)
833 DEBUG(dbgs() << "Simplified " << *I << " to "
834 << " constant " << *C << "\n");
835 NumGVNOpsSimplified++;
836 assert(isa<BasicExpression>(E) &&
837 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000838 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000839 return createConstantExpression(C);
840 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
841 if (I)
842 DEBUG(dbgs() << "Simplified " << *I << " to "
843 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000844 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000845 return createVariableExpression(V);
846 }
847
848 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlina8236562017-04-07 18:38:09 +0000849 if (CC && CC->getDefiningExpr()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000850 if (I)
851 DEBUG(dbgs() << "Simplified " << *I << " to "
852 << " expression " << *V << "\n");
853 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000854 deleteExpression(E);
Daniel Berlina8236562017-04-07 18:38:09 +0000855 return CC->getDefiningExpr();
Davide Italiano7e274e02016-12-22 16:03:48 +0000856 }
857 return nullptr;
858}
859
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000860const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000861 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000862
Daniel Berlin97718e62017-01-31 22:32:03 +0000863 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000864
865 if (I->isCommutative()) {
866 // Ensure that commutative instructions that only differ by a permutation
867 // of their operands get the same value number by sorting the operand value
868 // numbers. Since all commutative instructions have two operands it is more
869 // efficient to sort by hand rather than using, say, std::sort.
870 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000871 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000872 E->swapOperands(0, 1);
873 }
874
875 // Perform simplificaiton
876 // TODO: Right now we only check to see if we get a constant result.
877 // We may get a less than constant, but still better, result for
878 // some operations.
879 // IE
880 // add 0, x -> x
881 // and x, x -> x
882 // We should handle this by simply rewriting the expression.
883 if (auto *CI = dyn_cast<CmpInst>(I)) {
884 // Sort the operand value numbers so x<y and y>x get the same value
885 // number.
886 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000887 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000888 E->swapOperands(0, 1);
889 Predicate = CmpInst::getSwappedPredicate(Predicate);
890 }
891 E->setOpcode((CI->getOpcode() << 8) | Predicate);
892 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000893 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
894 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000895 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
896 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +0000897 Value *V =
898 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +0000899 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
900 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000901 } else if (isa<SelectInst>(I)) {
902 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000903 E->getOperand(0) == E->getOperand(1)) {
904 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
905 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000906 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +0000907 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000908 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
909 return SimplifiedE;
910 }
911 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +0000912 Value *V =
913 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000914 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
915 return SimplifiedE;
916 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000917 Value *V =
918 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000919 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
920 return SimplifiedE;
921 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +0000922 Value *V = SimplifyGEPInst(
923 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000924 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
925 return SimplifiedE;
926 } else if (AllConstant) {
927 // We don't bother trying to simplify unless all of the operands
928 // were constant.
929 // TODO: There are a lot of Simplify*'s we could call here, if we
930 // wanted to. The original motivating case for this code was a
931 // zext i1 false to i8, which we don't have an interface to
932 // simplify (IE there is no SimplifyZExt).
933
934 SmallVector<Constant *, 8> C;
935 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000936 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000937
Daniel Berlin64e68992017-03-12 04:46:45 +0000938 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +0000939 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
940 return SimplifiedE;
941 }
942 return E;
943}
944
945const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000946NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000947 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000948 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000949 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000950 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000951 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000952 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000953 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000954 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000955 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000956 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000957 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000958 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000959 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000960 return E;
961 }
962 llvm_unreachable("Unhandled type of aggregate value operation");
963}
964
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000965const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000966 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000967 E->setOpcode(V->getValueID());
968 return E;
969}
970
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000971const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +0000972 if (auto *C = dyn_cast<Constant>(V))
973 return createConstantExpression(C);
974 return createVariableExpression(V);
975}
976
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000977const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000978 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000979 E->setOpcode(C->getValueID());
980 return E;
981}
982
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000983const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +0000984 auto *E = new (ExpressionAllocator) UnknownExpression(I);
985 E->setOpcode(I->getOpcode());
986 return E;
987}
988
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000989const CallExpression *
990NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000991 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000992 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +0000993 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +0000994 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000995 return E;
996}
997
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000998// Return true if some equivalent of instruction Inst dominates instruction U.
999bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1000 const Instruction *U) const {
1001 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +00001002 // This must be an instruction because we are only called from phi nodes
1003 // in the case that the value it needs to check against is an instruction.
1004
1005 // The most likely candiates for dominance are the leader and the next leader.
1006 // The leader or nextleader will dominate in all cases where there is an
1007 // equivalent that is higher up in the dom tree.
1008 // We can't *only* check them, however, because the
1009 // dominator tree could have an infinite number of non-dominating siblings
1010 // with instructions that are in the right congruence class.
1011 // A
1012 // B C D E F G
1013 // |
1014 // H
1015 // Instruction U could be in H, with equivalents in every other sibling.
1016 // Depending on the rpo order picked, the leader could be the equivalent in
1017 // any of these siblings.
1018 if (!CC)
1019 return false;
Daniel Berlina8236562017-04-07 18:38:09 +00001020 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001021 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001022 if (CC->getNextLeader().first &&
1023 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001024 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001025 return llvm::any_of(*CC, [&](const Value *Member) {
1026 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001027 DT->dominates(cast<Instruction>(Member), U);
1028 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001029}
1030
Davide Italiano7e274e02016-12-22 16:03:48 +00001031// See if we have a congruence class and leader for this operand, and if so,
1032// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001033Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001034 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001035 if (CC) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001036 // Everything in TOP is represneted by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001037 // We do have to make sure we get the type right though, so we can't set the
1038 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001039 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001040 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001041 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001042 }
1043
Davide Italiano7e274e02016-12-22 16:03:48 +00001044 return V;
1045}
1046
Daniel Berlin1316a942017-04-06 18:52:50 +00001047const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1048 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001049 assert(CC->getMemoryLeader() &&
Davide Italianob60f6e02017-05-12 15:25:56 +00001050 "Every MemoryAccess should be mapped to a congruence class with a "
1051 "representative memory access");
Daniel Berlina8236562017-04-07 18:38:09 +00001052 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001053}
1054
Daniel Berlinc4796862017-01-27 02:37:11 +00001055// Return true if the MemoryAccess is really equivalent to everything. This is
1056// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001057// state of all MemoryAccesses.
Daniel Berlinc4796862017-01-27 02:37:11 +00001058bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001059 return getMemoryClass(MA) == TOPClass;
1060}
1061
Davide Italiano7e274e02016-12-22 16:03:48 +00001062LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001063 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001064 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001065 auto *E =
1066 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001067 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1068 E->setType(LoadType);
1069
1070 // Give store and loads same opcode so they value number together.
1071 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001072 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001073 if (LI)
1074 E->setAlignment(LI->getAlignment());
1075
1076 // TODO: Value number heap versions. We may be able to discover
1077 // things alias analysis can't on it's own (IE that a store and a
1078 // load have the same value, and thus, it isn't clobbering the load).
1079 return E;
1080}
1081
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001082const StoreExpression *
1083NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001084 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001085 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001086 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001087 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1088 E->setType(SI->getValueOperand()->getType());
1089
1090 // Give store and loads same opcode so they value number together.
1091 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001092 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001093
1094 // TODO: Value number heap versions. We may be able to discover
1095 // things alias analysis can't on it's own (IE that a store and a
1096 // load have the same value, and thus, it isn't clobbering the load).
1097 return E;
1098}
1099
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001100const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001101 // Unlike loads, we never try to eliminate stores, so we do not check if they
1102 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001103 auto *SI = cast<StoreInst>(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00001104 auto *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001105 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001106 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1107 if (EnableStoreRefinement)
1108 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1109 // If we bypassed the use-def chains, make sure we add a use.
1110 if (StoreRHS != StoreAccess->getDefiningAccess())
1111 addMemoryUsers(StoreRHS, StoreAccess);
1112
1113 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001114 // If we are defined by ourselves, use the live on entry def.
1115 if (StoreRHS == StoreAccess)
1116 StoreRHS = MSSA->getLiveOnEntryDef();
1117
Daniel Berlin589cecc2017-01-02 18:00:46 +00001118 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001119 // See if we are defined by a previous store expression, it already has a
1120 // value, and it's the same value as our current store. FIXME: Right now, we
1121 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001122 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1123 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +00001124 // Basically, check if the congruence class the store is in is defined by a
1125 // store that isn't us, and has the same value. MemorySSA takes care of
1126 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +00001127 // The RepStoredValue gets nulled if all the stores disappear in a class, so
1128 // we don't need to check if the class contains a store besides us.
Daniel Berlin1316a942017-04-06 18:52:50 +00001129 if (LastCC &&
Daniel Berlina8236562017-04-07 18:38:09 +00001130 LastCC->getStoredValue() == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin1316a942017-04-06 18:52:50 +00001131 return LastStore;
1132 deleteExpression(LastStore);
Daniel Berlinc4796862017-01-27 02:37:11 +00001133 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001134 // location, and the memory state is the same as it was then (otherwise, it
1135 // could have been overwritten later. See test32 in
1136 // transforms/DeadStoreElimination/simple.ll).
1137 if (auto *LI =
1138 dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001139 if ((lookupOperandLeader(LI->getPointerOperand()) ==
1140 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlin1316a942017-04-06 18:52:50 +00001141 (lookupMemoryLeader(MSSA->getMemoryAccess(LI)->getDefiningAccess()) ==
1142 StoreRHS))
Daniel Berlinc4796862017-01-27 02:37:11 +00001143 return createVariableExpression(LI);
1144 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001145 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001146
1147 // If the store is not equivalent to anything, value number it as a store that
1148 // produces a unique memory state (instead of using it's MemoryUse, we use
1149 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001150 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001151}
1152
Daniel Berlin07daac82017-04-02 13:23:44 +00001153// See if we can extract the value of a loaded pointer from a load, a store, or
1154// a memory instruction.
1155const Expression *
1156NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1157 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001158 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001159 assert((!LI || LI->isSimple()) && "Not a simple load");
1160 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1161 // Can't forward from non-atomic to atomic without violating memory model.
1162 // Also don't need to coerce if they are the same type, we will just
1163 // propogate..
1164 if (LI->isAtomic() > DepSI->isAtomic() ||
1165 LoadType == DepSI->getValueOperand()->getType())
1166 return nullptr;
1167 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1168 if (Offset >= 0) {
1169 if (auto *C = dyn_cast<Constant>(
1170 lookupOperandLeader(DepSI->getValueOperand()))) {
1171 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1172 << *C << "\n");
1173 return createConstantExpression(
1174 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1175 }
1176 }
1177
1178 } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1179 // Can't forward from non-atomic to atomic without violating memory model.
1180 if (LI->isAtomic() > DepLI->isAtomic())
1181 return nullptr;
1182 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1183 if (Offset >= 0) {
1184 // We can coerce a constant load into a load
1185 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1186 if (auto *PossibleConstant =
1187 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1188 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1189 << *PossibleConstant << "\n");
1190 return createConstantExpression(PossibleConstant);
1191 }
1192 }
1193
1194 } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1195 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1196 if (Offset >= 0) {
1197 if (auto *PossibleConstant =
1198 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1199 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1200 << " to constant " << *PossibleConstant << "\n");
1201 return createConstantExpression(PossibleConstant);
1202 }
1203 }
1204 }
1205
1206 // All of the below are only true if the loaded pointer is produced
1207 // by the dependent instruction.
1208 if (LoadPtr != lookupOperandLeader(DepInst) &&
1209 !AA->isMustAlias(LoadPtr, DepInst))
1210 return nullptr;
1211 // If this load really doesn't depend on anything, then we must be loading an
1212 // undef value. This can happen when loading for a fresh allocation with no
1213 // intervening stores, for example. Note that this is only true in the case
1214 // that the result of the allocation is pointer equal to the load ptr.
1215 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1216 return createConstantExpression(UndefValue::get(LoadType));
1217 }
1218 // If this load occurs either right after a lifetime begin,
1219 // then the loaded value is undefined.
1220 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1221 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1222 return createConstantExpression(UndefValue::get(LoadType));
1223 }
1224 // If this load follows a calloc (which zero initializes memory),
1225 // then the loaded value is zero
1226 else if (isCallocLikeFn(DepInst, TLI)) {
1227 return createConstantExpression(Constant::getNullValue(LoadType));
1228 }
1229
1230 return nullptr;
1231}
1232
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001233const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001234 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001235
1236 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001237 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001238 if (!LI->isSimple())
1239 return nullptr;
1240
Daniel Berlin203f47b2017-01-31 22:31:53 +00001241 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001242 // Load of undef is undef.
1243 if (isa<UndefValue>(LoadAddressLeader))
1244 return createConstantExpression(UndefValue::get(LI->getType()));
1245
1246 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
1247
1248 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1249 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1250 Instruction *DefiningInst = MD->getMemoryInst();
1251 // If the defining instruction is not reachable, replace with undef.
1252 if (!ReachableBlocks.count(DefiningInst->getParent()))
1253 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001254 // This will handle stores and memory insts. We only do if it the
1255 // defining access has a different type, or it is a pointer produced by
1256 // certain memory operations that cause the memory to have a fixed value
1257 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001258 if (const auto *CoercionResult =
1259 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1260 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001261 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001262 }
1263 }
1264
Daniel Berlin1316a942017-04-06 18:52:50 +00001265 const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1266 LI, DefiningAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001267 return E;
1268}
1269
Daniel Berlinf7d95802017-02-18 23:06:50 +00001270const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001271NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001272 auto *PI = PredInfo->getPredicateInfoFor(I);
1273 if (!PI)
1274 return nullptr;
1275
1276 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001277
1278 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1279 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001280 return nullptr;
1281
Daniel Berlinfccbda92017-02-22 22:20:58 +00001282 auto *CopyOf = I->getOperand(0);
1283 auto *Cond = PWC->Condition;
1284
Daniel Berlinf7d95802017-02-18 23:06:50 +00001285 // If this a copy of the condition, it must be either true or false depending
1286 // on the predicate info type and edge
1287 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001288 // We should not need to add predicate users because the predicate info is
1289 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001290 if (isa<PredicateAssume>(PI))
1291 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1292 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1293 if (PBranch->TrueEdge)
1294 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1295 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1296 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001297 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1298 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001299 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001300
Daniel Berlinf7d95802017-02-18 23:06:50 +00001301 // Not a copy of the condition, so see what the predicates tell us about this
1302 // value. First, though, we check to make sure the value is actually a copy
1303 // of one of the condition operands. It's possible, in certain cases, for it
1304 // to be a copy of a predicateinfo copy. In particular, if two branch
1305 // operations use the same condition, and one branch dominates the other, we
1306 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001307 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001308 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001309
1310 // Everything below relies on the condition being a comparison.
1311 auto *Cmp = dyn_cast<CmpInst>(Cond);
1312 if (!Cmp)
1313 return nullptr;
1314
1315 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Davide Italianoc43a9f82017-05-12 15:28:12 +00001316 DEBUG(dbgs() << "Copy is not of any condition operands!\n");
Daniel Berlinf7d95802017-02-18 23:06:50 +00001317 return nullptr;
1318 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001319 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1320 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001321 bool SwappedOps = false;
1322 // Sort the ops
1323 if (shouldSwapOperands(FirstOp, SecondOp)) {
1324 std::swap(FirstOp, SecondOp);
1325 SwappedOps = true;
1326 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001327 CmpInst::Predicate Predicate =
1328 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1329
1330 if (isa<PredicateAssume>(PI)) {
1331 // If the comparison is true when the operands are equal, then we know the
1332 // operands are equal, because assumes must always be true.
1333 if (CmpInst::isTrueWhenEqual(Predicate)) {
1334 addPredicateUsers(PI, I);
1335 return createVariableOrConstant(FirstOp);
1336 }
1337 }
1338 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1339 // If we are *not* a copy of the comparison, we may equal to the other
1340 // operand when the predicate implies something about equality of
1341 // operations. In particular, if the comparison is true/false when the
1342 // operands are equal, and we are on the right edge, we know this operation
1343 // is equal to something.
1344 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1345 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1346 addPredicateUsers(PI, I);
1347 return createVariableOrConstant(FirstOp);
1348 }
1349 // Handle the special case of floating point.
1350 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1351 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1352 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1353 addPredicateUsers(PI, I);
1354 return createConstantExpression(cast<Constant>(FirstOp));
1355 }
1356 }
1357 return nullptr;
1358}
1359
Davide Italiano7e274e02016-12-22 16:03:48 +00001360// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001361const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001362 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001363 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1364 // Instrinsics with the returned attribute are copies of arguments.
1365 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1366 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1367 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1368 return Result;
1369 return createVariableOrConstant(ReturnedValue);
1370 }
1371 }
1372 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001373 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001374 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001375 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001376 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001377 }
1378 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001379}
1380
Daniel Berlin1316a942017-04-06 18:52:50 +00001381// Retrieve the memory class for a given MemoryAccess.
1382CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1383
1384 auto *Result = MemoryAccessToClass.lookup(MA);
1385 assert(Result && "Should have found memory class");
1386 return Result;
1387}
1388
1389// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001390// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001391bool NewGVN::setMemoryClass(const MemoryAccess *From,
1392 CongruenceClass *NewClass) {
1393 assert(NewClass &&
1394 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001395 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001396 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001397 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
Davide Italianob7a66982017-05-09 20:02:48 +00001398 DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001399
1400 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001401 bool Changed = false;
1402 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001403 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001404 auto *OldClass = LookupResult->second;
1405 if (OldClass != NewClass) {
1406 // If this is a phi, we have to handle memory member updates.
1407 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001408 OldClass->memory_erase(MP);
1409 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001410 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001411 if (OldClass->getMemoryLeader() == From) {
Davide Italiano41f5c7b2017-05-12 15:22:45 +00001412 if (OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001413 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001414 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001415 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001416 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001417 << OldClass->getID() << " to "
1418 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001419 << " due to removal of a memory member " << *From
1420 << "\n");
1421 markMemoryLeaderChangeTouched(OldClass);
1422 }
1423 }
1424 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001425 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001426 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001427 Changed = true;
1428 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001429 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001430
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001431 return Changed;
1432}
Daniel Berlin0e900112017-03-24 06:33:48 +00001433
Daniel Berlin2f72b192017-04-14 02:53:37 +00001434// Determine if a phi is cycle-free. That means the values in the phi don't
1435// depend on any expressions that can change value as a result of the phi.
1436// For example, a non-cycle free phi would be v = phi(0, v+1).
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001437bool NewGVN::isCycleFree(const PHINode *PN) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001438 // In order to compute cycle-freeness, we do SCC finding on the phi, and see
1439 // what kind of SCC it ends up in. If it is a singleton, it is cycle-free.
1440 // If it is not in a singleton, it is only cycle free if the other members are
1441 // all phi nodes (as they do not compute anything, they are copies). TODO:
1442 // There are likely a few other intrinsics or expressions that could be
1443 // included here, but this happens so infrequently already that it is not
1444 // likely to be worth it.
1445 auto PCS = PhiCycleState.lookup(PN);
1446 if (PCS == PCS_Unknown) {
1447 SCCFinder.Start(PN);
1448 auto &SCC = SCCFinder.getComponentFor(PN);
1449 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1450 if (SCC.size() == 1)
1451 PhiCycleState.insert({PN, PCS_CycleFree});
1452 else {
1453 bool AllPhis =
1454 llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
1455 PCS = AllPhis ? PCS_CycleFree : PCS_Cycle;
1456 for (auto *Member : SCC)
1457 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
1458 PhiCycleState.insert({MemberPhi, PCS});
1459 }
1460 }
1461 if (PCS == PCS_Cycle)
1462 return false;
1463 return true;
1464}
1465
Davide Italiano7e274e02016-12-22 16:03:48 +00001466// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001467const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001468 // True if one of the incoming phi edges is a backedge.
1469 bool HasBackedge = false;
1470 // All constant tracks the state of whether all the *original* phi operands
Davide Italiano839c7e62017-05-02 21:11:40 +00001471 // were constant. This is really shorthand for "this phi cannot cycle due
1472 // to forward propagation", as any change in value of the phi is guaranteed
1473 // not to later change the value of the phi.
Daniel Berlin2f72b192017-04-14 02:53:37 +00001474 // IE it can't be v = phi(undef, v+1)
1475 bool AllConstant = true;
Daniel Berlinabd632d2017-05-16 06:06:12 +00001476 auto *E =
1477 cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001478 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001479 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001480 // We track if any were undef because they need special handling.
1481 bool HasUndef = false;
1482 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1483 if (Arg == I)
1484 return false;
1485 if (isa<UndefValue>(Arg)) {
1486 HasUndef = true;
1487 return false;
1488 }
1489 return true;
1490 });
1491 // If we are left with no operands, it's undef
1492 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001493 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1494 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001495 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001496 return createConstantExpression(UndefValue::get(I->getType()));
1497 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001498 unsigned NumOps = 0;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001499 Value *AllSameValue = *(Filtered.begin());
1500 ++Filtered.begin();
1501 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berlin2f72b192017-04-14 02:53:37 +00001502 if (llvm::all_of(Filtered, [AllSameValue, &NumOps](const Value *V) {
1503 ++NumOps;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001504 return V == AllSameValue;
1505 })) {
1506 // In LLVM's non-standard representation of phi nodes, it's possible to have
1507 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1508 // on the original phi node), especially in weird CFG's where some arguments
1509 // are unreachable, or uninitialized along certain paths. This can cause
1510 // infinite loops during evaluation. We work around this by not trying to
1511 // really evaluate them independently, but instead using a variable
1512 // expression to say if one is equivalent to the other.
1513 // We also special case undef, so that if we have an undef, we can't use the
1514 // common value unless it dominates the phi block.
1515 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001516 // If we have undef and at least one other value, this is really a
1517 // multivalued phi, and we need to know if it's cycle free in order to
1518 // evaluate whether we can ignore the undef. The other parts of this are
1519 // just shortcuts. If there is no backedge, or all operands are
1520 // constants, or all operands are ignored but the undef, it also must be
1521 // cycle free.
1522 if (!AllConstant && HasBackedge && NumOps > 0 &&
1523 !isa<UndefValue>(AllSameValue) && !isCycleFree(cast<PHINode>(I)))
1524 return E;
1525
Daniel Berlind92e7f92017-01-07 00:01:42 +00001526 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001527 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001528 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001529 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001530 }
1531
Davide Italiano7e274e02016-12-22 16:03:48 +00001532 NumGVNPhisAllSame++;
1533 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1534 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001535 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001536 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001537 }
1538 return E;
1539}
1540
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001541const Expression *
1542NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001543 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1544 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1545 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1546 unsigned Opcode = 0;
1547 // EI might be an extract from one of our recognised intrinsics. If it
1548 // is we'll synthesize a semantically equivalent expression instead on
1549 // an extract value expression.
1550 switch (II->getIntrinsicID()) {
1551 case Intrinsic::sadd_with_overflow:
1552 case Intrinsic::uadd_with_overflow:
1553 Opcode = Instruction::Add;
1554 break;
1555 case Intrinsic::ssub_with_overflow:
1556 case Intrinsic::usub_with_overflow:
1557 Opcode = Instruction::Sub;
1558 break;
1559 case Intrinsic::smul_with_overflow:
1560 case Intrinsic::umul_with_overflow:
1561 Opcode = Instruction::Mul;
1562 break;
1563 default:
1564 break;
1565 }
1566
1567 if (Opcode != 0) {
1568 // Intrinsic recognized. Grab its args to finish building the
1569 // expression.
1570 assert(II->getNumArgOperands() == 2 &&
1571 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001572 return createBinaryExpression(
1573 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001574 }
1575 }
1576 }
1577
Daniel Berlin97718e62017-01-31 22:32:03 +00001578 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001579}
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001580const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001581 auto *CI = dyn_cast<CmpInst>(I);
1582 // See if our operands are equal to those of a previous predicate, and if so,
1583 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001584 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1585 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001586 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001587 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001588 std::swap(Op0, Op1);
1589 OurPredicate = CI->getSwappedPredicate();
1590 }
1591
1592 // Avoid processing the same info twice
1593 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001594 // See if we know something about the comparison itself, like it is the target
1595 // of an assume.
1596 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1597 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1598 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1599
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001600 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001601 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001602 if (CI->isTrueWhenEqual())
1603 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1604 else if (CI->isFalseWhenEqual())
1605 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1606 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001607
1608 // NOTE: Because we are comparing both operands here and below, and using
1609 // previous comparisons, we rely on fact that predicateinfo knows to mark
1610 // comparisons that use renamed operands as users of the earlier comparisons.
1611 // It is *not* enough to just mark predicateinfo renamed operands as users of
1612 // the earlier comparisons, because the *other* operand may have changed in a
1613 // previous iteration.
1614 // Example:
1615 // icmp slt %a, %b
1616 // %b.0 = ssa.copy(%b)
1617 // false branch:
1618 // icmp slt %c, %b.0
1619
1620 // %c and %a may start out equal, and thus, the code below will say the second
1621 // %icmp is false. c may become equal to something else, and in that case the
1622 // %second icmp *must* be reexamined, but would not if only the renamed
1623 // %operands are considered users of the icmp.
1624
1625 // *Currently* we only check one level of comparisons back, and only mark one
1626 // level back as touched when changes appen . If you modify this code to look
1627 // back farther through comparisons, you *must* mark the appropriate
1628 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1629 // we know something just from the operands themselves
1630
1631 // See if our operands have predicate info, so that we may be able to derive
1632 // something from a previous comparison.
1633 for (const auto &Op : CI->operands()) {
1634 auto *PI = PredInfo->getPredicateInfoFor(Op);
1635 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1636 if (PI == LastPredInfo)
1637 continue;
1638 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001639
Daniel Berlinf7d95802017-02-18 23:06:50 +00001640 // TODO: Along the false edge, we may know more things too, like icmp of
1641 // same operands is false.
1642 // TODO: We only handle actual comparison conditions below, not and/or.
1643 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1644 if (!BranchCond)
1645 continue;
1646 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1647 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1648 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001649 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001650 std::swap(BranchOp0, BranchOp1);
1651 BranchPredicate = BranchCond->getSwappedPredicate();
1652 }
1653 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1654 if (PBranch->TrueEdge) {
1655 // If we know the previous predicate is true and we are in the true
1656 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001657 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1658 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001659 addPredicateUsers(PI, I);
1660 return createConstantExpression(
1661 ConstantInt::getTrue(CI->getType()));
1662 }
1663
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001664 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1665 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001666 addPredicateUsers(PI, I);
1667 return createConstantExpression(
1668 ConstantInt::getFalse(CI->getType()));
1669 }
1670
1671 } else {
1672 // Just handle the ne and eq cases, where if we have the same
1673 // operands, we may know something.
1674 if (BranchPredicate == OurPredicate) {
1675 addPredicateUsers(PI, I);
1676 // Same predicate, same ops,we know it was false, so this is false.
1677 return createConstantExpression(
1678 ConstantInt::getFalse(CI->getType()));
1679 } else if (BranchPredicate ==
1680 CmpInst::getInversePredicate(OurPredicate)) {
1681 addPredicateUsers(PI, I);
1682 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001683 return createConstantExpression(
1684 ConstantInt::getTrue(CI->getType()));
1685 }
1686 }
1687 }
1688 }
1689 }
1690 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001691 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001692}
Davide Italiano7e274e02016-12-22 16:03:48 +00001693
1694// Substitute and symbolize the value before value numbering.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001695const Expression *NewGVN::performSymbolicEvaluation(Value *V) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001696 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001697 if (auto *C = dyn_cast<Constant>(V))
1698 E = createConstantExpression(C);
1699 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1700 E = createVariableExpression(V);
1701 } else {
1702 // TODO: memory intrinsics.
1703 // TODO: Some day, we should do the forward propagation and reassociation
1704 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001705 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001706 switch (I->getOpcode()) {
1707 case Instruction::ExtractValue:
1708 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001709 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001710 break;
1711 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001712 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001713 break;
1714 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001715 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001716 break;
1717 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001718 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001719 break;
1720 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001721 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001722 break;
1723 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001724 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001725 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001726 case Instruction::ICmp:
1727 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001728 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001729 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001730 case Instruction::Add:
1731 case Instruction::FAdd:
1732 case Instruction::Sub:
1733 case Instruction::FSub:
1734 case Instruction::Mul:
1735 case Instruction::FMul:
1736 case Instruction::UDiv:
1737 case Instruction::SDiv:
1738 case Instruction::FDiv:
1739 case Instruction::URem:
1740 case Instruction::SRem:
1741 case Instruction::FRem:
1742 case Instruction::Shl:
1743 case Instruction::LShr:
1744 case Instruction::AShr:
1745 case Instruction::And:
1746 case Instruction::Or:
1747 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001748 case Instruction::Trunc:
1749 case Instruction::ZExt:
1750 case Instruction::SExt:
1751 case Instruction::FPToUI:
1752 case Instruction::FPToSI:
1753 case Instruction::UIToFP:
1754 case Instruction::SIToFP:
1755 case Instruction::FPTrunc:
1756 case Instruction::FPExt:
1757 case Instruction::PtrToInt:
1758 case Instruction::IntToPtr:
1759 case Instruction::Select:
1760 case Instruction::ExtractElement:
1761 case Instruction::InsertElement:
1762 case Instruction::ShuffleVector:
1763 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001764 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001765 break;
1766 default:
1767 return nullptr;
1768 }
1769 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001770 return E;
1771}
1772
Davide Italiano7e274e02016-12-22 16:03:48 +00001773void NewGVN::markUsersTouched(Value *V) {
1774 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001775 for (auto *User : V->users()) {
1776 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001777 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001778 }
1779}
1780
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001781void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001782 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1783 MemoryToUsers[To].insert(U);
1784}
1785
1786void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001787 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00001788}
1789
1790void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1791 if (isa<MemoryUse>(MA))
1792 return;
1793 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00001794 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin1316a942017-04-06 18:52:50 +00001795 const auto Result = MemoryToUsers.find(MA);
1796 if (Result != MemoryToUsers.end()) {
1797 for (auto *User : Result->second)
Daniel Berlin21279bd2017-04-06 18:52:58 +00001798 TouchedInstructions.set(MemoryToDFSNum(User));
Daniel Berlin1316a942017-04-06 18:52:50 +00001799 MemoryToUsers.erase(Result);
Davide Italiano7e274e02016-12-22 16:03:48 +00001800 }
1801}
1802
Daniel Berlinf7d95802017-02-18 23:06:50 +00001803// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001804void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001805 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1806 PredicateToUsers[PBranch->Condition].insert(I);
1807 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1808 PredicateToUsers[PAssume->Condition].insert(I);
1809}
1810
1811// Touch all the predicates that depend on this instruction.
1812void NewGVN::markPredicateUsersTouched(Instruction *I) {
1813 const auto Result = PredicateToUsers.find(I);
Daniel Berlin46b72e62017-03-19 00:07:32 +00001814 if (Result != PredicateToUsers.end()) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001815 for (auto *User : Result->second)
Daniel Berlin21279bd2017-04-06 18:52:58 +00001816 TouchedInstructions.set(InstrToDFSNum(User));
Daniel Berlin46b72e62017-03-19 00:07:32 +00001817 PredicateToUsers.erase(Result);
1818 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001819}
1820
Daniel Berlin1316a942017-04-06 18:52:50 +00001821// Mark users affected by a memory leader change.
1822void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001823 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00001824 markMemoryDefTouched(M);
1825}
1826
Daniel Berlin32f8d562017-01-07 16:55:14 +00001827// Touch the instructions that need to be updated after a congruence class has a
1828// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00001829void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001830 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001831 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00001832 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001833 LeaderChanges.insert(M);
1834 }
1835}
1836
Daniel Berlin1316a942017-04-06 18:52:50 +00001837// Give a range of things that have instruction DFS numbers, this will return
1838// the member of the range with the smallest dfs number.
1839template <class T, class Range>
1840T *NewGVN::getMinDFSOfRange(const Range &R) const {
1841 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
1842 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001843 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00001844 if (DFSNum < MinDFS.second)
1845 MinDFS = {X, DFSNum};
1846 }
1847 return MinDFS.first;
1848}
1849
1850// This function returns the MemoryAccess that should be the next leader of
1851// congruence class CC, under the assumption that the current leader is going to
1852// disappear.
1853const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
1854 // TODO: If this ends up to slow, we can maintain a next memory leader like we
1855 // do for regular leaders.
1856 // Make sure there will be a leader to find
Davide Italianodc435322017-05-10 19:57:43 +00001857 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00001858 if (CC->getStoreCount() > 0) {
1859 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlin1316a942017-04-06 18:52:50 +00001860 return MSSA->getMemoryAccess(NL);
1861 // Find the store with the minimum DFS number.
1862 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00001863 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlin1316a942017-04-06 18:52:50 +00001864 return MSSA->getMemoryAccess(cast<StoreInst>(V));
1865 }
Daniel Berlina8236562017-04-07 18:38:09 +00001866 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001867
1868 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00001869 // !OldClass->memory_empty()
1870 if (CC->memory_size() == 1)
1871 return *CC->memory_begin();
1872 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00001873}
1874
1875// This function returns the next value leader of a congruence class, under the
1876// assumption that the current leader is going away. This should end up being
1877// the next most dominating member.
1878Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
1879 // We don't need to sort members if there is only 1, and we don't care about
1880 // sorting the TOP class because everything either gets out of it or is
1881 // unreachable.
1882
Daniel Berlina8236562017-04-07 18:38:09 +00001883 if (CC->size() == 1 || CC == TOPClass) {
1884 return *(CC->begin());
1885 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001886 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00001887 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00001888 } else {
1889 ++NumGVNSortedLeaderChanges;
1890 // NOTE: If this ends up to slow, we can maintain a dual structure for
1891 // member testing/insertion, or keep things mostly sorted, and sort only
1892 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00001893 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00001894 }
1895}
1896
1897// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
1898// the memory members, etc for the move.
1899//
1900// The invariants of this function are:
1901//
1902// I must be moving to NewClass from OldClass The StoreCount of OldClass and
1903// NewClass is expected to have been updated for I already if it is is a store.
1904// The OldClass memory leader has not been updated yet if I was the leader.
1905void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
1906 MemoryAccess *InstMA,
1907 CongruenceClass *OldClass,
1908 CongruenceClass *NewClass) {
1909 // If the leader is I, and we had a represenative MemoryAccess, it should
1910 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00001911 assert((!InstMA || !OldClass->getMemoryLeader() ||
1912 OldClass->getLeader() != I ||
1913 OldClass->getMemoryLeader() == InstMA) &&
1914 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00001915 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00001916 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001917 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00001918 assert(NewClass->size() == 1 ||
1919 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
1920 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00001921 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00001922 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00001923 << " due to new memory instruction becoming leader\n");
1924 markMemoryLeaderChangeTouched(NewClass);
1925 }
1926 setMemoryClass(InstMA, NewClass);
1927 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00001928 if (OldClass->getMemoryLeader() == InstMA) {
Davide Italianodc435322017-05-10 19:57:43 +00001929 if (!OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001930 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1931 DEBUG(dbgs() << "Memory class leader change for class "
1932 << OldClass->getID() << " to "
1933 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001934 << " due to removal of old leader " << *InstMA << "\n");
1935 markMemoryLeaderChangeTouched(OldClass);
1936 } else
Daniel Berlina8236562017-04-07 18:38:09 +00001937 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001938 }
1939}
1940
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001941// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00001942// Update OldClass and NewClass for the move (including changing leaders, etc).
1943void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001944 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001945 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00001946 if (I == OldClass->getNextLeader().first)
1947 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001948
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001949 // It's possible, though unlikely, for us to discover equivalences such
1950 // that the current leader does not dominate the old one.
1951 // This statistic tracks how often this happens.
1952 // We assert on phi nodes when this happens, currently, for debugging, because
1953 // we want to make sure we name phi node cycles properly.
Daniel Berlina8236562017-04-07 18:38:09 +00001954 if (isa<Instruction>(NewClass->getLeader()) && NewClass->getLeader() &&
1955 I != NewClass->getLeader()) {
Daniel Berlinffc30782017-03-24 06:33:51 +00001956 auto *IBB = I->getParent();
Daniel Berlina8236562017-04-07 18:38:09 +00001957 auto *NCBB = cast<Instruction>(NewClass->getLeader())->getParent();
Daniel Berlin21279bd2017-04-06 18:52:58 +00001958 bool Dominated =
Daniel Berlina8236562017-04-07 18:38:09 +00001959 IBB == NCBB && InstrToDFSNum(I) < InstrToDFSNum(NewClass->getLeader());
Daniel Berlinffc30782017-03-24 06:33:51 +00001960 Dominated = Dominated || DT->properlyDominates(IBB, NCBB);
1961 if (Dominated) {
1962 ++NumGVNNotMostDominatingLeader;
1963 assert(
1964 !isa<PHINode>(I) &&
1965 "New class for instruction should not be dominated by instruction");
1966 }
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001967 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001968
Daniel Berlina8236562017-04-07 18:38:09 +00001969 if (NewClass->getLeader() != I)
1970 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001971
Daniel Berlina8236562017-04-07 18:38:09 +00001972 OldClass->erase(I);
1973 NewClass->insert(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00001974 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001975 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001976 OldClass->decStoreCount();
1977 // Okay, so when do we want to make a store a leader of a class?
1978 // If we have a store defined by an earlier load, we want the earlier load
1979 // to lead the class.
1980 // If we have a store defined by something else, we want the store to lead
1981 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00001982 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00001983 // as the leader
1984 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001985 // If it's a store expression we are using, it means we are not equivalent
1986 // to something earlier.
Daniel Berlin629e1ff2017-05-16 06:06:15 +00001987 if (auto *SE = dyn_cast<StoreExpression>(E)) {
1988 assert(SE->getStoredValue() != NewClass->getLeader());
1989 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1316a942017-04-06 18:52:50 +00001990 markValueLeaderChangeTouched(NewClass);
1991 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00001992 DEBUG(dbgs() << "Changing leader of congruence class "
1993 << NewClass->getID() << " from " << *NewClass->getLeader()
1994 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00001995 // If we changed the leader, we have to mark it changed because we don't
1996 // know what it will do to symbolic evlauation.
Daniel Berlina8236562017-04-07 18:38:09 +00001997 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001998 }
1999 // We rely on the code below handling the MemoryAccess change.
2000 }
Daniel Berlina8236562017-04-07 18:38:09 +00002001 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002002 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002003 // True if there is no memory instructions left in a class that had memory
2004 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002005
Daniel Berlin1316a942017-04-06 18:52:50 +00002006 // If it's not a memory use, set the MemoryAccess equivalence
2007 auto *InstMA = dyn_cast_or_null<MemoryDef>(MSSA->getMemoryAccess(I));
Daniel Berlin1316a942017-04-06 18:52:50 +00002008 if (InstMA)
2009 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002010 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002011 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002012 if (OldClass->empty() && OldClass != TOPClass) {
2013 if (OldClass->getDefiningExpr()) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002014 DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002015 << " from table\n");
Daniel Berlina8236562017-04-07 18:38:09 +00002016 ExpressionToClass.erase(OldClass->getDefiningExpr());
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002017 }
Daniel Berlina8236562017-04-07 18:38:09 +00002018 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002019 // When the leader changes, the value numbering of
2020 // everything may change due to symbolization changes, so we need to
2021 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00002022 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002023 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002024 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002025 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002026 // Note that this is basically clean up for the expression removal that
2027 // happens below. If we remove stores from a class, we may leave it as a
2028 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002029 if (OldClass->getStoreCount() == 0) {
2030 if (OldClass->getStoredValue())
2031 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002032 }
Daniel Berlina8236562017-04-07 18:38:09 +00002033 OldClass->setLeader(getNextValueLeader(OldClass));
2034 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002035 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002036 }
2037}
2038
Davide Italiano7e274e02016-12-22 16:03:48 +00002039// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002040void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002041 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002042 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002043
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002044 CongruenceClass *IClass = ValueToClass[I];
2045 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002046 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002047 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002048
2049 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00002050 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002051 EClass = ValueToClass[VE->getVariableValue()];
2052 } else {
2053 auto lookupResult = ExpressionToClass.insert({E, nullptr});
2054
2055 // If it's not in the value table, create a new congruence class.
2056 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002057 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002058 auto place = lookupResult.first;
2059 place->second = NewClass;
2060
2061 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002062 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002063 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002064 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2065 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002066 NewClass->setLeader(SI);
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002067 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002068 // The RepMemoryAccess field will be filled in properly by the
2069 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002070 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002071 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002072 }
2073 assert(!isa<VariableExpression>(E) &&
2074 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002075
2076 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002077 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002078 << " using expression " << *E << " at " << NewClass->getID()
2079 << " and leader " << *(NewClass->getLeader()));
2080 if (NewClass->getStoredValue())
2081 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002082 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002083 } else {
2084 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002085 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002086 assert((isa<Constant>(EClass->getLeader()) ||
2087 (EClass->getStoredValue() &&
2088 isa<Constant>(EClass->getStoredValue()))) &&
2089 "Any class with a constant expression should have a "
2090 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002091
Davide Italiano7e274e02016-12-22 16:03:48 +00002092 assert(EClass && "Somehow don't have an eclass");
2093
Daniel Berlin1316a942017-04-06 18:52:50 +00002094 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002095 }
2096 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002097 bool ClassChanged = IClass != EClass;
2098 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002099 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002100 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002101 << "\n");
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002102 if (ClassChanged)
Daniel Berlin1316a942017-04-06 18:52:50 +00002103 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002104 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002105 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002106 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002107 if (auto *CI = dyn_cast<CmpInst>(I))
2108 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002109 }
Daniel Berlin45403572017-05-16 19:58:47 +00002110 // If we changed the class of the store, we want to ensure nothing finds the
2111 // old store expression. In particular, loads do not compare against stored
2112 // value, so they will find old store expressions (and associated class
2113 // mappings) if we leave them in the table.
Davide Italianoee49f492017-05-19 04:06:10 +00002114 if (ClassChanged && isa<StoreInst>(I)) {
Daniel Berlin45403572017-05-16 19:58:47 +00002115 auto *OldE = ValueToExpression.lookup(I);
2116 // It could just be that the old class died. We don't want to erase it if we
2117 // just moved classes.
Davide Italianoee49f492017-05-19 04:06:10 +00002118 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE)
Daniel Berlin45403572017-05-16 19:58:47 +00002119 ExpressionToClass.erase(OldE);
2120 }
2121 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002122}
2123
2124// Process the fact that Edge (from, to) is reachable, including marking
2125// any newly reachable blocks and instructions for processing.
2126void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2127 // Check if the Edge was reachable before.
2128 if (ReachableEdges.insert({From, To}).second) {
2129 // If this block wasn't reachable before, all instructions are touched.
2130 if (ReachableBlocks.insert(To).second) {
2131 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2132 const auto &InstRange = BlockInstRange.lookup(To);
2133 TouchedInstructions.set(InstRange.first, InstRange.second);
2134 } else {
2135 DEBUG(dbgs() << "Block " << getBlockName(To)
2136 << " was reachable, but new edge {" << getBlockName(From)
2137 << "," << getBlockName(To) << "} to it found\n");
2138
2139 // We've made an edge reachable to an existing block, which may
2140 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2141 // they are the only thing that depend on new edges. Anything using their
2142 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00002143 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002144 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002145
Davide Italiano7e274e02016-12-22 16:03:48 +00002146 auto BI = To->begin();
2147 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002148 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002149 ++BI;
2150 }
2151 }
2152 }
2153}
2154
2155// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2156// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002157Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002158 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002159 if (isa<Constant>(Result))
2160 return Result;
2161 return nullptr;
2162}
2163
2164// Process the outgoing edges of a block for reachability.
2165void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2166 // Evaluate reachability of terminator instruction.
2167 BranchInst *BR;
2168 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2169 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002170 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002171 if (!CondEvaluated) {
2172 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002173 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002174 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2175 CondEvaluated = CE->getConstantValue();
2176 }
2177 } else if (isa<ConstantInt>(Cond)) {
2178 CondEvaluated = Cond;
2179 }
2180 }
2181 ConstantInt *CI;
2182 BasicBlock *TrueSucc = BR->getSuccessor(0);
2183 BasicBlock *FalseSucc = BR->getSuccessor(1);
2184 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2185 if (CI->isOne()) {
2186 DEBUG(dbgs() << "Condition for Terminator " << *TI
2187 << " evaluated to true\n");
2188 updateReachableEdge(B, TrueSucc);
2189 } else if (CI->isZero()) {
2190 DEBUG(dbgs() << "Condition for Terminator " << *TI
2191 << " evaluated to false\n");
2192 updateReachableEdge(B, FalseSucc);
2193 }
2194 } else {
2195 updateReachableEdge(B, TrueSucc);
2196 updateReachableEdge(B, FalseSucc);
2197 }
2198 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2199 // For switches, propagate the case values into the case
2200 // destinations.
2201
2202 // Remember how many outgoing edges there are to every successor.
2203 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2204
Davide Italiano7e274e02016-12-22 16:03:48 +00002205 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002206 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002207 // See if we were able to turn this switch statement into a constant.
2208 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002209 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002210 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002211 auto Case = *SI->findCaseValue(CondVal);
2212 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002213 // We proved the value is outside of the range of the case.
2214 // We can't do anything other than mark the default dest as reachable,
2215 // and go home.
2216 updateReachableEdge(B, SI->getDefaultDest());
2217 return;
2218 }
2219 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002220 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002221 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002222 } else {
2223 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2224 BasicBlock *TargetBlock = SI->getSuccessor(i);
2225 ++SwitchEdges[TargetBlock];
2226 updateReachableEdge(B, TargetBlock);
2227 }
2228 }
2229 } else {
2230 // Otherwise this is either unconditional, or a type we have no
2231 // idea about. Just mark successors as reachable.
2232 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2233 BasicBlock *TargetBlock = TI->getSuccessor(i);
2234 updateReachableEdge(B, TargetBlock);
2235 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002236
2237 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002238 // equivalent only to itself.
2239 //
2240 auto *MA = MSSA->getMemoryAccess(TI);
2241 if (MA && !isa<MemoryUse>(MA)) {
2242 auto *CC = ensureLeaderOfMemoryClass(MA);
2243 if (setMemoryClass(MA, CC))
2244 markMemoryUsersTouched(MA);
2245 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002246 }
2247}
2248
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002249// The algorithm initially places the values of the routine in the TOP
2250// congruence class. The leader of TOP is the undetermined value `undef`.
2251// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002252void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002253 NextCongruenceNum = 0;
2254
2255 // Note that even though we use the live on entry def as a representative
2256 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2257 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2258 // should be checking whether the MemoryAccess is top if we want to know if it
2259 // is equivalent to everything. Otherwise, what this really signifies is that
2260 // the access "it reaches all the way back to the beginning of the function"
2261
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002262 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002263 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002264 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002265 // The live on entry def gets put into it's own class
2266 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2267 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002268
Daniel Berlinec9deb72017-04-18 17:06:11 +00002269 for (auto DTN : nodes(DT)) {
2270 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002271 // All MemoryAccesses are equivalent to live on entry to start. They must
2272 // be initialized to something so that initial changes are noticed. For
2273 // the maximal answer, we initialize them all to be the same as
2274 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002275 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002276 if (MemoryBlockDefs)
2277 for (const auto &Def : *MemoryBlockDefs) {
2278 MemoryAccessToClass[&Def] = TOPClass;
2279 auto *MD = dyn_cast<MemoryDef>(&Def);
2280 // Insert the memory phis into the member list.
2281 if (!MD) {
2282 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002283 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002284 MemoryPhiState.insert({MP, MPS_TOP});
2285 }
2286
2287 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002288 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002289 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002290 for (auto &I : *BB) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00002291 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002292 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002293 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2294 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002295 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002296 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002297 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002298 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002299
2300 // Initialize arguments to be in their own unique congruence classes
2301 for (auto &FA : F.args())
2302 createSingletonCongruenceClass(&FA);
2303}
2304
2305void NewGVN::cleanupTables() {
2306 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002307 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2308 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002309 // Make sure we delete the congruence class (probably worth switching to
2310 // a unique_ptr at some point.
2311 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002312 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002313 }
2314
2315 ValueToClass.clear();
2316 ArgRecycler.clear(ExpressionAllocator);
2317 ExpressionAllocator.Reset();
2318 CongruenceClasses.clear();
2319 ExpressionToClass.clear();
2320 ValueToExpression.clear();
2321 ReachableBlocks.clear();
2322 ReachableEdges.clear();
2323#ifndef NDEBUG
2324 ProcessedCount.clear();
2325#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002326 InstrDFS.clear();
2327 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002328 DFSToInstr.clear();
2329 BlockInstRange.clear();
2330 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002331 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002332 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002333 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002334}
2335
2336std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2337 unsigned Start) {
2338 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002339 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
2340 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002341 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002342 }
2343
Davide Italiano7e274e02016-12-22 16:03:48 +00002344 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002345 // There's no need to call isInstructionTriviallyDead more than once on
2346 // an instruction. Therefore, once we know that an instruction is dead
2347 // we change its DFS number so that it doesn't get value numbered.
2348 if (isInstructionTriviallyDead(&I, TLI)) {
2349 InstrDFS[&I] = 0;
2350 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2351 markInstructionForDeletion(&I);
2352 continue;
2353 }
2354
Davide Italiano7e274e02016-12-22 16:03:48 +00002355 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002356 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002357 }
2358
2359 // All of the range functions taken half-open ranges (open on the end side).
2360 // So we do not subtract one from count, because at this point it is one
2361 // greater than the last instruction.
2362 return std::make_pair(Start, End);
2363}
2364
2365void NewGVN::updateProcessedCount(Value *V) {
2366#ifndef NDEBUG
2367 if (ProcessedCount.count(V) == 0) {
2368 ProcessedCount.insert({V, 1});
2369 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002370 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002371 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002372 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002373 }
2374#endif
2375}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002376// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2377void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2378 // If all the arguments are the same, the MemoryPhi has the same value as the
2379 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00002380 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00002381 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002382 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002383 return lookupMemoryLeader(cast<MemoryAccess>(U)) != MP &&
Daniel Berlinc4796862017-01-27 02:37:11 +00002384 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002385 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002386 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002387 // If all that is left is nothing, our memoryphi is undef. We keep it as
2388 // InitialClass. Note: The only case this should happen is if we have at
2389 // least one self-argument.
2390 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002391 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002392 markMemoryUsersTouched(MP);
2393 return;
2394 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002395
2396 // Transform the remaining operands into operand leaders.
2397 // FIXME: mapped_iterator should have a range version.
2398 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002399 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002400 };
2401 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2402 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2403
2404 // and now check if all the elements are equal.
2405 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002406 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002407 ++MappedBegin;
2408 bool AllEqual = std::all_of(
2409 MappedBegin, MappedEnd,
2410 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2411
2412 if (AllEqual)
2413 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2414 else
2415 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002416 // If it's equal to something, it's in that class. Otherwise, it has to be in
2417 // a class where it is the leader (other things may be equivalent to it, but
2418 // it needs to start off in its own class, which means it must have been the
2419 // leader, and it can't have stopped being the leader because it was never
2420 // removed).
2421 CongruenceClass *CC =
2422 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2423 auto OldState = MemoryPhiState.lookup(MP);
2424 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2425 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2426 MemoryPhiState[MP] = NewState;
2427 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002428 markMemoryUsersTouched(MP);
2429}
2430
2431// Value number a single instruction, symbolically evaluating, performing
2432// congruence finding, and updating mappings.
2433void NewGVN::valueNumberInstruction(Instruction *I) {
2434 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002435 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002436 const Expression *Symbolized = nullptr;
2437 if (DebugCounter::shouldExecute(VNCounter)) {
2438 Symbolized = performSymbolicEvaluation(I);
2439 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002440 // Mark the instruction as unused so we don't value number it again.
2441 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002442 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002443 // If we couldn't come up with a symbolic expression, use the unknown
2444 // expression
Daniel Berlin1316a942017-04-06 18:52:50 +00002445 if (Symbolized == nullptr) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002446 Symbolized = createUnknownExpression(I);
Daniel Berlin1316a942017-04-06 18:52:50 +00002447 }
2448
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002449 performCongruenceFinding(I, Symbolized);
2450 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002451 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002452 // don't currently understand. We don't place non-value producing
2453 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002454 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002455 auto *Symbolized = createUnknownExpression(I);
2456 performCongruenceFinding(I, Symbolized);
2457 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002458 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2459 }
2460}
Davide Italiano7e274e02016-12-22 16:03:48 +00002461
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002462// Check if there is a path, using single or equal argument phi nodes, from
2463// First to Second.
Davide Italianoeab0de22017-05-18 23:22:44 +00002464bool NewGVN::singleReachablePHIPath(
2465 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
2466 const MemoryAccess *Second) const {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002467 if (First == Second)
2468 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002469 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002470 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002471
Davide Italianoeab0de22017-05-18 23:22:44 +00002472 // This is not perfect, but as we're just verifying here, we can live with
2473 // the loss of precision. The real solution would be that of doing strongly
2474 // connected component finding in this routine, and it's probably not worth
2475 // the complexity for the time being. So, we just keep a set of visited
2476 // MemoryAccess and return true when we hit a cycle.
2477 if (Visited.count(First))
2478 return true;
2479 Visited.insert(First);
2480
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)
Davide Italianoeab0de22017-05-18 23:22:44 +00002503 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2504 Second);
Daniel Berlin871ecd92017-04-01 09:44:24 +00002505 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002506}
2507
Daniel Berlin589cecc2017-01-02 18:00:46 +00002508// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002509// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002510// subject to very rare false negatives. It is only useful for
2511// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002512void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002513#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002514 // Verify that the memory table equivalence and memory member set match
2515 for (const auto *CC : CongruenceClasses) {
2516 if (CC == TOPClass || CC->isDead())
2517 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002518 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00002519 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002520 "Any class with a store as a leader should have a "
2521 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00002522 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002523 "Any congruence class with a store should have a "
2524 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00002525 }
2526
Daniel Berlina8236562017-04-07 18:38:09 +00002527 if (CC->getMemoryLeader())
2528 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00002529 "Representative MemoryAccess does not appear to be reverse "
2530 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00002531 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002532 assert(MemoryAccessToClass.lookup(M) == CC &&
2533 "Memory member does not appear to be reverse mapped properly");
2534 }
2535
2536 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002537 // congruence class.
2538
2539 // Filter out the unreachable and trivially dead entries, because they may
2540 // never have been updated if the instructions were not processed.
2541 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002542 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002543 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00002544 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2545 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00002546 return false;
2547 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2548 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Davide Italiano6e7a2122017-05-15 18:50:53 +00002549
2550 // We could have phi nodes which operands are all trivially dead,
2551 // so we don't process them.
2552 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
2553 for (auto &U : MemPHI->incoming_values()) {
2554 if (Instruction *I = dyn_cast<Instruction>(U.get())) {
2555 if (!isInstructionTriviallyDead(I))
2556 return true;
2557 }
2558 }
2559 return false;
2560 }
2561
Daniel Berlin589cecc2017-01-02 18:00:46 +00002562 return true;
2563 };
2564
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002565 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002566 for (auto KV : Filtered) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002567 assert(KV.second != TOPClass &&
2568 "Memory not unreachable but ended up in TOP");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002569 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002570 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italianoeab0de22017-05-18 23:22:44 +00002571 if (FirstMUD && SecondMUD) {
2572 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
2573 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002574 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2575 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2576 "The instructions for these memory operations should have "
2577 "been in the same congruence class or reachable through"
2578 "a single argument phi");
Davide Italianoeab0de22017-05-18 23:22:44 +00002579 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002580 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002581 // We can only sanely verify that MemoryDefs in the operand list all have
2582 // the same class.
2583 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002584 return ReachableEdges.count(
2585 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002586 isa<MemoryDef>(U);
2587
2588 };
2589 // All arguments should in the same class, ignoring unreachable arguments
2590 auto FilteredPhiArgs =
2591 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2592 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2593 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2594 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2595 const MemoryDef *MD = cast<MemoryDef>(U);
2596 return ValueToClass.lookup(MD->getMemoryInst());
2597 });
2598 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2599 PhiOpClasses.begin()) &&
2600 "All MemoryPhi arguments should be in the same class");
2601 }
2602 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002603#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002604}
2605
Daniel Berlin06329a92017-03-18 15:41:40 +00002606// Verify that the sparse propagation we did actually found the maximal fixpoint
2607// We do this by storing the value to class mapping, touching all instructions,
2608// and redoing the iteration to see if anything changed.
2609void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002610#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002611 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002612 if (DebugCounter::isCounterSet(VNCounter))
2613 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2614
2615 // Note that we have to store the actual classes, as we may change existing
2616 // classes during iteration. This is because our memory iteration propagation
2617 // is not perfect, and so may waste a little work. But it should generate
2618 // exactly the same congruence classes we have now, with different IDs.
2619 std::map<const Value *, CongruenceClass> BeforeIteration;
2620
2621 for (auto &KV : ValueToClass) {
2622 if (auto *I = dyn_cast<Instruction>(KV.first))
2623 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002624 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002625 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002626 BeforeIteration.insert({KV.first, *KV.second});
2627 }
2628
2629 TouchedInstructions.set();
2630 TouchedInstructions.reset(0);
2631 iterateTouchedInstructions();
2632 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2633 EqualClasses;
2634 for (const auto &KV : ValueToClass) {
2635 if (auto *I = dyn_cast<Instruction>(KV.first))
2636 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002637 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00002638 continue;
2639 // We could sink these uses, but i think this adds a bit of clarity here as
2640 // to what we are comparing.
2641 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2642 auto *AfterCC = KV.second;
2643 // Note that the classes can't change at this point, so we memoize the set
2644 // that are equal.
2645 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00002646 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00002647 "Value number changed after main loop completed!");
2648 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002649 }
2650 }
2651#endif
2652}
2653
Daniel Berlin45403572017-05-16 19:58:47 +00002654// Verify that for each store expression in the expression to class mapping,
2655// only the latest appears, and multiple ones do not appear.
2656// Because loads do not use the stored value when doing equality with stores,
2657// if we don't erase the old store expressions from the table, a load can find
2658// a no-longer valid StoreExpression.
2659void NewGVN::verifyStoreExpressions() const {
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00002660#ifndef NDEBUG
Daniel Berlin45403572017-05-16 19:58:47 +00002661 DenseSet<std::pair<const Value *, const Value *>> StoreExpressionSet;
2662 for (const auto &KV : ExpressionToClass) {
2663 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
2664 // Make sure a version that will conflict with loads is not already there
2665 auto Res =
2666 StoreExpressionSet.insert({SE->getOperand(0), SE->getMemoryLeader()});
2667 assert(Res.second &&
2668 "Stored expression conflict exists in expression table");
2669 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
2670 assert(ValueExpr && ValueExpr->equals(*SE) &&
2671 "StoreExpression in ExpressionToClass is not latest "
2672 "StoreExpression for value");
2673 }
2674 }
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00002675#endif
Daniel Berlin45403572017-05-16 19:58:47 +00002676}
2677
Daniel Berlin06329a92017-03-18 15:41:40 +00002678// This is the main value numbering loop, it iterates over the initial touched
2679// instruction set, propagating value numbers, marking things touched, etc,
2680// until the set of touched instructions is completely empty.
2681void NewGVN::iterateTouchedInstructions() {
2682 unsigned int Iterations = 0;
2683 // Figure out where touchedinstructions starts
2684 int FirstInstr = TouchedInstructions.find_first();
2685 // Nothing set, nothing to iterate, just return.
2686 if (FirstInstr == -1)
2687 return;
Daniel Berlin21279bd2017-04-06 18:52:58 +00002688 BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00002689 while (TouchedInstructions.any()) {
2690 ++Iterations;
2691 // Walk through all the instructions in all the blocks in RPO.
2692 // TODO: As we hit a new block, we should push and pop equalities into a
2693 // table lookupOperandLeader can use, to catch things PredicateInfo
2694 // might miss, like edge-only equivalences.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00002695 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
Daniel Berlin06329a92017-03-18 15:41:40 +00002696
2697 // This instruction was found to be dead. We don't bother looking
2698 // at it again.
2699 if (InstrNum == 0) {
2700 TouchedInstructions.reset(InstrNum);
2701 continue;
2702 }
2703
Daniel Berlin21279bd2017-04-06 18:52:58 +00002704 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlin06329a92017-03-18 15:41:40 +00002705 BasicBlock *CurrBlock = getBlockForValue(V);
2706
2707 // If we hit a new block, do reachability processing.
2708 if (CurrBlock != LastBlock) {
2709 LastBlock = CurrBlock;
2710 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2711 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2712
2713 // If it's not reachable, erase any touched instructions and move on.
2714 if (!BlockReachable) {
2715 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2716 DEBUG(dbgs() << "Skipping instructions in block "
2717 << getBlockName(CurrBlock)
2718 << " because it is unreachable\n");
2719 continue;
2720 }
2721 updateProcessedCount(CurrBlock);
2722 }
2723
2724 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2725 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2726 valueNumberMemoryPhi(MP);
2727 } else if (auto *I = dyn_cast<Instruction>(V)) {
2728 valueNumberInstruction(I);
2729 } else {
2730 llvm_unreachable("Should have been a MemoryPhi or Instruction");
2731 }
2732 updateProcessedCount(V);
2733 // Reset after processing (because we may mark ourselves as touched when
2734 // we propagate equalities).
2735 TouchedInstructions.reset(InstrNum);
2736 }
2737 }
2738 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2739}
2740
Daniel Berlin85f91b02016-12-26 20:06:58 +00002741// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00002742bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00002743 if (DebugCounter::isCounterSet(VNCounter))
2744 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00002745 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00002746 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00002747 MSSAWalker = MSSA->getWalker();
2748
2749 // Count number of instructions for sizing of hash tables, and come
2750 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002751 unsigned ICount = 1;
2752 // Add an empty instruction to account for the fact that we start at 1
2753 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002754 // Note: We want ideal RPO traversal of the blocks, which is not quite the
2755 // same as dominator tree order, particularly with regard whether backedges
2756 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00002757 // If we visit in the wrong order, we will end up performing N times as many
2758 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002759 // The dominator tree does guarantee that, for a given dom tree node, it's
2760 // parent must occur before it in the RPO ordering. Thus, we only need to sort
2761 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00002762 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00002763 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002764 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002765 auto *Node = DT->getNode(B);
2766 assert(Node && "RPO and Dominator tree should have same reachability");
2767 RPOOrdering[Node] = ++Counter;
2768 }
2769 // Sort dominator tree children arrays into RPO.
2770 for (auto &B : RPOT) {
2771 auto *Node = DT->getNode(B);
2772 if (Node->getChildren().size() > 1)
2773 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00002774 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002775 return RPOOrdering[A] < RPOOrdering[B];
2776 });
2777 }
2778
2779 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002780 for (auto DTN : depth_first(DT->getRootNode())) {
2781 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00002782 const auto &BlockRange = assignDFSNumbers(B, ICount);
2783 BlockInstRange.insert({B, BlockRange});
2784 ICount += BlockRange.second - BlockRange.first;
2785 }
2786
Daniel Berline0bd37e2016-12-29 22:15:12 +00002787 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002788 // Ensure we don't end up resizing the expressionToClass map, as
2789 // that can be quite expensive. At most, we have one expression per
2790 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002791 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002792
2793 // Initialize the touched instructions to include the entry block.
2794 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2795 TouchedInstructions.set(InstRange.first, InstRange.second);
2796 ReachableBlocks.insert(&F.getEntryBlock());
2797
2798 initializeCongruenceClasses(F);
Daniel Berlin06329a92017-03-18 15:41:40 +00002799 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00002800 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00002801 verifyIterationSettled(F);
Daniel Berlin45403572017-05-16 19:58:47 +00002802 verifyStoreExpressions();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002803
Davide Italiano7e274e02016-12-22 16:03:48 +00002804 Changed |= eliminateInstructions(F);
2805
2806 // Delete all instructions marked for deletion.
2807 for (Instruction *ToErase : InstructionsToErase) {
2808 if (!ToErase->use_empty())
2809 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2810
2811 ToErase->eraseFromParent();
2812 }
2813
2814 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002815 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2816 return !ReachableBlocks.count(&BB);
2817 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002818
2819 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2820 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002821 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002822 deleteInstructionsInBlock(&BB);
2823 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002824 }
2825
2826 cleanupTables();
2827 return Changed;
2828}
2829
Davide Italiano7e274e02016-12-22 16:03:48 +00002830// Return true if V is a value that will always be available (IE can
2831// be placed anywhere) in the function. We don't do globals here
2832// because they are often worse to put in place.
2833// TODO: Separate cost from availability
2834static bool alwaysAvailable(Value *V) {
2835 return isa<Constant>(V) || isa<Argument>(V);
2836}
2837
Davide Italiano7e274e02016-12-22 16:03:48 +00002838struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002839 int DFSIn = 0;
2840 int DFSOut = 0;
2841 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002842 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002843 // The bool in the Def tells us whether the Def is the stored value of a
2844 // store.
2845 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002846 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002847 bool operator<(const ValueDFS &Other) const {
2848 // It's not enough that any given field be less than - we have sets
2849 // of fields that need to be evaluated together to give a proper ordering.
2850 // For example, if you have;
2851 // DFS (1, 3)
2852 // Val 0
2853 // DFS (1, 2)
2854 // Val 50
2855 // We want the second to be less than the first, but if we just go field
2856 // by field, we will get to Val 0 < Val 50 and say the first is less than
2857 // the second. We only want it to be less than if the DFS orders are equal.
2858 //
2859 // Each LLVM instruction only produces one value, and thus the lowest-level
2860 // differentiator that really matters for the stack (and what we use as as a
2861 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002862 // Everything else in the structure is instruction level, and only affects
2863 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002864 //
2865 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2866 // the order of replacement of uses does not matter.
2867 // IE given,
2868 // a = 5
2869 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002870 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2871 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002872 // The .val will be the same as well.
2873 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002874 // You will replace both, and it does not matter what order you replace them
2875 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2876 // operand 2).
2877 // Similarly for the case of same dfsin, dfsout, localnum, but different
2878 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002879 // a = 5
2880 // b = 6
2881 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002882 // in c, we will a valuedfs for a, and one for b,with everything the same
2883 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002884 // It does not matter what order we replace these operands in.
2885 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002886 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2887 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002888 Other.U);
2889 }
2890};
2891
Daniel Berlinc4796862017-01-27 02:37:11 +00002892// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002893// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00002894// reachable uses for each value is stored in UseCount, and instructions that
2895// seem
2896// dead (have no non-dead uses) are stored in ProbablyDead.
2897void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00002898 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00002899 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00002900 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00002901 for (auto D : Dense) {
2902 // First add the value.
2903 BasicBlock *BB = getBlockForValue(D);
2904 // Constants are handled prior to ever calling this function, so
2905 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002906 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002907 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002908 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002909 VDDef.DFSIn = DomNode->getDFSNumIn();
2910 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002911 // If it's a store, use the leader of the value operand, if it's always
2912 // available, or the value operand. TODO: We could do dominance checks to
2913 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00002914 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002915 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002916 if (alwaysAvailable(Leader)) {
2917 VDDef.Def.setPointer(Leader);
2918 } else {
2919 VDDef.Def.setPointer(SI->getValueOperand());
2920 VDDef.Def.setInt(true);
2921 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002922 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002923 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00002924 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002925 assert(isa<Instruction>(D) &&
2926 "The dense set member should always be an instruction");
Daniel Berlin21279bd2017-04-06 18:52:58 +00002927 VDDef.LocalNum = InstrToDFSNum(D);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002928 DFSOrderedSet.emplace_back(VDDef);
Daniel Berline3e69e12017-03-10 00:32:33 +00002929 Instruction *Def = cast<Instruction>(D);
2930 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002931 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00002932 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002933 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002934 // Don't try to replace into dead uses
2935 if (InstructionsToErase.count(I))
2936 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002937 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002938 // Put the phi node uses in the incoming block.
2939 BasicBlock *IBlock;
2940 if (auto *P = dyn_cast<PHINode>(I)) {
2941 IBlock = P->getIncomingBlock(U);
2942 // Make phi node users appear last in the incoming block
2943 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002944 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002945 } else {
2946 IBlock = I->getParent();
Daniel Berlin21279bd2017-04-06 18:52:58 +00002947 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002948 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002949
2950 // Skip uses in unreachable blocks, as we're going
2951 // to delete them.
2952 if (ReachableBlocks.count(IBlock) == 0)
2953 continue;
2954
Daniel Berlinb66164c2017-01-14 00:24:23 +00002955 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002956 VDUse.DFSIn = DomNode->getDFSNumIn();
2957 VDUse.DFSOut = DomNode->getDFSNumOut();
2958 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00002959 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002960 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002961 }
2962 }
Daniel Berline3e69e12017-03-10 00:32:33 +00002963
2964 // If there are no uses, it's probably dead (but it may have side-effects,
2965 // so not definitely dead. Otherwise, store the number of uses so we can
2966 // track if it becomes dead later).
2967 if (UseCount == 0)
2968 ProbablyDead.insert(Def);
2969 else
2970 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002971 }
2972}
2973
Daniel Berlinc4796862017-01-27 02:37:11 +00002974// This function converts the set of members for a congruence class from values,
2975// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00002976void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00002977 const CongruenceClass &Dense,
2978 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00002979 for (auto D : Dense) {
2980 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2981 continue;
2982
2983 BasicBlock *BB = getBlockForValue(D);
2984 ValueDFS VD;
2985 DomTreeNode *DomNode = DT->getNode(BB);
2986 VD.DFSIn = DomNode->getDFSNumIn();
2987 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002988 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00002989
2990 // If it's an instruction, use the real local dfs number.
2991 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002992 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00002993 else
2994 llvm_unreachable("Should have been an instruction");
2995
2996 LoadsAndStores.emplace_back(VD);
2997 }
2998}
2999
Davide Italiano7e274e02016-12-22 16:03:48 +00003000static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00003001 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00003002 if (!ReplInst)
3003 return;
3004
Davide Italiano7e274e02016-12-22 16:03:48 +00003005 // Patch the replacement so that it is not more restrictive than the value
3006 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00003007 // Note that if 'I' is a load being replaced by some operation,
3008 // for example, by an arithmetic operation, then andIRFlags()
3009 // would just erase all math flags from the original arithmetic
3010 // operation, which is clearly not wanted and not needed.
3011 if (!isa<LoadInst>(I))
3012 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003013
Daniel Berlin86eab152017-02-12 22:25:20 +00003014 // FIXME: If both the original and replacement value are part of the
3015 // same control-flow region (meaning that the execution of one
3016 // guarantees the execution of the other), then we can combine the
3017 // noalias scopes here and do better than the general conservative
3018 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00003019
Daniel Berlin86eab152017-02-12 22:25:20 +00003020 // In general, GVN unifies expressions over different control-flow
3021 // regions, and so we need a conservative combination of the noalias
3022 // scopes.
3023 static const unsigned KnownIDs[] = {
3024 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3025 LLVMContext::MD_noalias, LLVMContext::MD_range,
3026 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
3027 LLVMContext::MD_invariant_group};
3028 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00003029}
3030
3031static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3032 patchReplacementInstruction(I, Repl);
3033 I->replaceAllUsesWith(Repl);
3034}
3035
3036void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3037 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
3038 ++NumGVNBlocksDeleted;
3039
Daniel Berline19f0e02017-01-30 17:06:55 +00003040 // Delete the instructions backwards, as it has a reduced likelihood of having
3041 // to update as many def-use and use-def chains. Start after the terminator.
3042 auto StartPoint = BB->rbegin();
3043 ++StartPoint;
3044 // Note that we explicitly recalculate BB->rend() on each iteration,
3045 // as it may change when we remove the first instruction.
3046 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3047 Instruction &Inst = *I++;
3048 if (!Inst.use_empty())
3049 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3050 if (isa<LandingPadInst>(Inst))
3051 continue;
3052
3053 Inst.eraseFromParent();
3054 ++NumGVNInstrDeleted;
3055 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003056 // Now insert something that simplifycfg will turn into an unreachable.
3057 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3058 new StoreInst(UndefValue::get(Int8Ty),
3059 Constant::getNullValue(Int8Ty->getPointerTo()),
3060 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003061}
3062
3063void NewGVN::markInstructionForDeletion(Instruction *I) {
3064 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3065 InstructionsToErase.insert(I);
3066}
3067
3068void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3069
3070 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3071 patchAndReplaceAllUsesWith(I, V);
3072 // We save the actual erasing to avoid invalidating memory
3073 // dependencies until we are done with everything.
3074 markInstructionForDeletion(I);
3075}
3076
3077namespace {
3078
3079// This is a stack that contains both the value and dfs info of where
3080// that value is valid.
3081class ValueDFSStack {
3082public:
3083 Value *back() const { return ValueStack.back(); }
3084 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3085
3086 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003087 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003088 DFSStack.emplace_back(DFSIn, DFSOut);
3089 }
3090 bool empty() const { return DFSStack.empty(); }
3091 bool isInScope(int DFSIn, int DFSOut) const {
3092 if (empty())
3093 return false;
3094 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3095 }
3096
3097 void popUntilDFSScope(int DFSIn, int DFSOut) {
3098
3099 // These two should always be in sync at this point.
3100 assert(ValueStack.size() == DFSStack.size() &&
3101 "Mismatch between ValueStack and DFSStack");
3102 while (
3103 !DFSStack.empty() &&
3104 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3105 DFSStack.pop_back();
3106 ValueStack.pop_back();
3107 }
3108 }
3109
3110private:
3111 SmallVector<Value *, 8> ValueStack;
3112 SmallVector<std::pair<int, int>, 8> DFSStack;
3113};
3114}
Daniel Berlin04443432017-01-07 03:23:47 +00003115
Davide Italiano7e274e02016-12-22 16:03:48 +00003116bool NewGVN::eliminateInstructions(Function &F) {
3117 // This is a non-standard eliminator. The normal way to eliminate is
3118 // to walk the dominator tree in order, keeping track of available
3119 // values, and eliminating them. However, this is mildly
3120 // pointless. It requires doing lookups on every instruction,
3121 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003122 // instructions part of most singleton congruence classes, we know we
3123 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003124
3125 // Instead, this eliminator looks at the congruence classes directly, sorts
3126 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003127 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003128 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003129 // last member. This is worst case O(E log E) where E = number of
3130 // instructions in a single congruence class. In theory, this is all
3131 // instructions. In practice, it is much faster, as most instructions are
3132 // either in singleton congruence classes or can't possibly be eliminated
3133 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003134 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003135 // for elimination purposes.
3136 // TODO: If we wanted to be faster, We could remove any members with no
3137 // overlapping ranges while sorting, as we will never eliminate anything
3138 // with those members, as they don't dominate anything else in our set.
3139
Davide Italiano7e274e02016-12-22 16:03:48 +00003140 bool AnythingReplaced = false;
3141
3142 // Since we are going to walk the domtree anyway, and we can't guarantee the
3143 // DFS numbers are updated, we compute some ourselves.
3144 DT->updateDFSNumbers();
3145
3146 for (auto &B : F) {
3147 if (!ReachableBlocks.count(&B)) {
3148 for (const auto S : successors(&B)) {
3149 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003150 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00003151 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
3152 << getBlockName(&B)
3153 << " with undef due to it being unreachable\n");
3154 for (auto &Operand : Phi.incoming_values())
3155 if (Phi.getIncomingBlock(Operand) == &B)
3156 Operand.set(UndefValue::get(Phi.getType()));
3157 }
3158 }
3159 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003160 }
3161
Daniel Berline3e69e12017-03-10 00:32:33 +00003162 // Map to store the use counts
3163 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlin4d547962017-02-12 23:24:45 +00003164 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00003165 // Track the equivalent store info so we can decide whether to try
3166 // dead store elimination.
3167 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003168 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003169 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003170 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003171 // Everything still in the TOP class is unreachable or dead.
3172 if (CC == TOPClass) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00003173#ifndef NDEBUG
Daniel Berlina8236562017-04-07 18:38:09 +00003174 for (auto M : *CC)
Daniel Berlinb79f5362017-02-11 12:48:50 +00003175 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3176 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003177 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003178 "point");
3179#endif
3180 continue;
3181 }
3182
Daniel Berlina8236562017-04-07 18:38:09 +00003183 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003184 // If this is a leader that is always available, and it's a
3185 // constant or has no equivalences, just replace everything with
3186 // it. We then update the congruence class with whatever members
3187 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003188 Value *Leader =
3189 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003190 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003191 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003192 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003193 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003194 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003195 if (Member == Leader || !isa<Instruction>(Member) ||
3196 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003197 MembersLeft.insert(Member);
3198 continue;
3199 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003200 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3201 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003202 auto *I = cast<Instruction>(Member);
3203 assert(Leader != I && "About to accidentally remove our leader");
3204 replaceInstruction(I, Leader);
3205 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003206 }
Daniel Berlina8236562017-04-07 18:38:09 +00003207 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003208 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00003209 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
3210 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003211 // If this is a singleton, we can skip it.
Daniel Berlina8236562017-04-07 18:38:09 +00003212 if (CC->size() != 1) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003213 // This is a stack because equality replacement/etc may place
3214 // constants in the middle of the member list, and we want to use
3215 // those constant values in preference to the current leader, over
3216 // the scope of those constants.
3217 ValueDFSStack EliminationStack;
3218
3219 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003220 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003221 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003222
3223 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003224 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003225 for (auto &VD : DFSOrderedSet) {
3226 int MemberDFSIn = VD.DFSIn;
3227 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003228 Value *Def = VD.Def.getPointer();
3229 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003230 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003231 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003232 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003233 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00003234
3235 if (EliminationStack.empty()) {
3236 DEBUG(dbgs() << "Elimination Stack is empty\n");
3237 } else {
3238 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3239 << EliminationStack.dfs_back().first << ","
3240 << EliminationStack.dfs_back().second << ")\n");
3241 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003242
3243 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3244 << MemberDFSOut << ")\n");
3245 // First, we see if we are out of scope or empty. If so,
3246 // and there equivalences, we try to replace the top of
3247 // stack with equivalences (if it's on the stack, it must
3248 // not have been eliminated yet).
3249 // Then we synchronize to our current scope, by
3250 // popping until we are back within a DFS scope that
3251 // dominates the current member.
3252 // Then, what happens depends on a few factors
3253 // If the stack is now empty, we need to push
3254 // If we have a constant or a local equivalence we want to
3255 // start using, we also push.
3256 // Otherwise, we walk along, processing members who are
3257 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003258 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003259 bool OutOfScope =
3260 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3261
3262 if (OutOfScope || ShouldPush) {
3263 // Sync to our current scope.
3264 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003265 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003266 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003267 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003268 }
3269 }
3270
Daniel Berline3e69e12017-03-10 00:32:33 +00003271 // Skip the Def's, we only want to eliminate on their uses. But mark
3272 // dominated defs as dead.
3273 if (Def) {
3274 // For anything in this case, what and how we value number
3275 // guarantees that any side-effets that would have occurred (ie
3276 // throwing, etc) can be proven to either still occur (because it's
3277 // dominated by something that has the same side-effects), or never
3278 // occur. Otherwise, we would not have been able to prove it value
3279 // equivalent to something else. For these things, we can just mark
3280 // it all dead. Note that this is different from the "ProbablyDead"
3281 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003282 // easy to prove dead if they are also side-effect free. Note that
3283 // because stores are put in terms of the stored value, we skip
3284 // stored values here. If the stored value is really dead, it will
3285 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003286 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003287 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003288 markInstructionForDeletion(cast<Instruction>(Def));
3289 continue;
3290 }
3291 // At this point, we know it is a Use we are trying to possibly
3292 // replace.
3293
3294 assert(isa<Instruction>(U->get()) &&
3295 "Current def should have been an instruction");
3296 assert(isa<Instruction>(U->getUser()) &&
3297 "Current user should have been an instruction");
3298
3299 // If the thing we are replacing into is already marked to be dead,
3300 // this use is dead. Note that this is true regardless of whether
3301 // we have anything dominating the use or not. We do this here
3302 // because we are already walking all the uses anyway.
3303 Instruction *InstUse = cast<Instruction>(U->getUser());
3304 if (InstructionsToErase.count(InstUse)) {
3305 auto &UseCount = UseCounts[U->get()];
3306 if (--UseCount == 0) {
3307 ProbablyDead.insert(cast<Instruction>(U->get()));
3308 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003309 }
3310
Davide Italiano7e274e02016-12-22 16:03:48 +00003311 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003312 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003313 if (EliminationStack.empty())
3314 continue;
3315
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003316 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003317
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003318 auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
3319 if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3320 DominatingLeader = II->getOperand(0);
3321
Daniel Berlind92e7f92017-01-07 00:01:42 +00003322 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003323 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003324 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003325 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003326 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003327
3328 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003329 // metadata. Skip this if we are replacing predicateinfo with its
3330 // original operand, as we already know we can just drop it.
3331 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003332 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3333 if (!PI || DominatingLeader != PI->OriginalOp)
3334 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003335 U->set(DominatingLeader);
3336 // This is now a use of the dominating leader, which means if the
3337 // dominating leader was dead, it's now live!
3338 auto &LeaderUseCount = UseCounts[DominatingLeader];
3339 // It's about to be alive again.
3340 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3341 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003342 if (LeaderUseCount == 0 && II)
3343 ProbablyDead.insert(II);
Daniel Berline3e69e12017-03-10 00:32:33 +00003344 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003345 AnythingReplaced = true;
3346 }
3347 }
3348 }
3349
Daniel Berline3e69e12017-03-10 00:32:33 +00003350 // At this point, anything still in the ProbablyDead set is actually dead if
3351 // would be trivially dead.
3352 for (auto *I : ProbablyDead)
3353 if (wouldInstructionBeTriviallyDead(I))
3354 markInstructionForDeletion(I);
3355
Davide Italiano7e274e02016-12-22 16:03:48 +00003356 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003357 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003358 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003359 if (!isa<Instruction>(Member) ||
3360 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003361 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003362 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003363
3364 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003365 if (CC->getStoreCount() > 0) {
3366 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003367 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3368 ValueDFSStack EliminationStack;
3369 for (auto &VD : PossibleDeadStores) {
3370 int MemberDFSIn = VD.DFSIn;
3371 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003372 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003373 if (EliminationStack.empty() ||
3374 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3375 // Sync to our current scope.
3376 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3377 if (EliminationStack.empty()) {
3378 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3379 continue;
3380 }
3381 }
3382 // We already did load elimination, so nothing to do here.
3383 if (isa<LoadInst>(Member))
3384 continue;
3385 assert(!EliminationStack.empty());
3386 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003387 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003388 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3389 // Member is dominater by Leader, and thus dead
3390 DEBUG(dbgs() << "Marking dead store " << *Member
3391 << " that is dominated by " << *Leader << "\n");
3392 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003393 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003394 ++NumGVNDeadStores;
3395 }
3396 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003397 }
3398
3399 return AnythingReplaced;
3400}
Daniel Berlin1c087672017-02-11 15:07:01 +00003401
3402// This function provides global ranking of operations so that we can place them
3403// in a canonical order. Note that rank alone is not necessarily enough for a
3404// complete ordering, as constants all have the same rank. However, generally,
3405// we will simplify an operation with all constants so that it doesn't matter
3406// what order they appear in.
3407unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003408 // Prefer undef to anything else
3409 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00003410 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003411 if (isa<Constant>(V))
3412 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00003413 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003414 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003415
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003416 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003417 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003418 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00003419 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003420 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003421 // Unreachable or something else, just return a really large number.
3422 return ~0;
3423}
3424
3425// This is a function that says whether two commutative operations should
3426// have their order swapped when canonicalizing.
3427bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3428 // Because we only care about a total ordering, and don't rewrite expressions
3429 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003430 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003431 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003432}
Daniel Berlin64e68992017-03-12 04:46:45 +00003433
3434class NewGVNLegacyPass : public FunctionPass {
3435public:
3436 static char ID; // Pass identification, replacement for typeid.
3437 NewGVNLegacyPass() : FunctionPass(ID) {
3438 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3439 }
3440 bool runOnFunction(Function &F) override;
3441
3442private:
3443 void getAnalysisUsage(AnalysisUsage &AU) const override {
3444 AU.addRequired<AssumptionCacheTracker>();
3445 AU.addRequired<DominatorTreeWrapperPass>();
3446 AU.addRequired<TargetLibraryInfoWrapperPass>();
3447 AU.addRequired<MemorySSAWrapperPass>();
3448 AU.addRequired<AAResultsWrapperPass>();
3449 AU.addPreserved<DominatorTreeWrapperPass>();
3450 AU.addPreserved<GlobalsAAWrapperPass>();
3451 }
3452};
3453
3454bool NewGVNLegacyPass::runOnFunction(Function &F) {
3455 if (skipFunction(F))
3456 return false;
3457 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3458 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3459 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3460 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3461 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3462 F.getParent()->getDataLayout())
3463 .runGVN();
3464}
3465
3466INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3467 false, false)
3468INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3469INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3470INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3471INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3472INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3473INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3474INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3475 false)
3476
3477char NewGVNLegacyPass::ID = 0;
3478
3479// createGVNPass - The public interface to this file.
3480FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3481
3482PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3483 // Apparently the order in which we get these results matter for
3484 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3485 // the same order here, just in case.
3486 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3487 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3488 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3489 auto &AA = AM.getResult<AAManager>(F);
3490 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3491 bool Changed =
3492 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3493 .runGVN();
3494 if (!Changed)
3495 return PreservedAnalyses::all();
3496 PreservedAnalyses PA;
3497 PA.preserve<DominatorTreeAnalysis>();
3498 PA.preserve<GlobalsAA>();
3499 return PA;
3500}