blob: 54fe5fd79d7df0c7190d003540c0843b99cd4ce1 [file] [log] [blame]
Eugene Zelenko99241d72017-10-20 21:47:29 +00001//===- NewGVN.cpp - Global Value Numbering Pass ---------------------------===//
Davide Italiano7e274e02016-12-22 16:03:48 +00002//
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//===----------------------------------------------------------------------===//
Eugene Zelenko99241d72017-10-20 21:47:29 +00009//
Davide Italiano7e274e02016-12-22 16:03:48 +000010/// \file
11/// This file implements the new LLVM's Global Value Numbering pass.
12/// GVN partitions values computed by a function into congruence classes.
13/// Values ending up in the same congruence class are guaranteed to be the same
14/// for every execution of the program. In that respect, congruency is a
15/// compile-time approximation of equivalence of values at runtime.
16/// The algorithm implemented here uses a sparse formulation and it's based
17/// on the ideas described in the paper:
18/// "A Sparse Algorithm for Predicated Global Value Numbering" from
19/// Karthik Gargi.
20///
Daniel Berlindb3c7be2017-01-26 21:39:49 +000021/// A brief overview of the algorithm: The algorithm is essentially the same as
22/// the standard RPO value numbering algorithm (a good reference is the paper
23/// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
24/// The RPO algorithm proceeds, on every iteration, to process every reachable
25/// block and every instruction in that block. This is because the standard RPO
26/// algorithm does not track what things have the same value number, it only
27/// tracks what the value number of a given operation is (the mapping is
28/// operation -> value number). Thus, when a value number of an operation
29/// changes, it must reprocess everything to ensure all uses of a value number
30/// get updated properly. In constrast, the sparse algorithm we use *also*
31/// tracks what operations have a given value number (IE it also tracks the
32/// reverse mapping from value number -> operations with that value number), so
33/// that it only needs to reprocess the instructions that are affected when
Daniel Berlinb527b2c2017-05-19 19:01:27 +000034/// something's value number changes. The vast majority of complexity and code
35/// in this file is devoted to tracking what value numbers could change for what
36/// instructions when various things happen. The rest of the algorithm is
37/// devoted to performing symbolic evaluation, forward propagation, and
38/// simplification of operations based on the value numbers deduced so far
39///
40/// In order to make the GVN mostly-complete, we use a technique derived from
41/// "Detection of Redundant Expressions: A Complete and Polynomial-time
42/// Algorithm in SSA" by R.R. Pai. The source of incompleteness in most SSA
43/// based GVN algorithms is related to their inability to detect equivalence
44/// between phi of ops (IE phi(a+b, c+d)) and op of phis (phi(a,c) + phi(b, d)).
45/// We resolve this issue by generating the equivalent "phi of ops" form for
46/// each op of phis we see, in a way that only takes polynomial time to resolve.
Daniel Berlindb3c7be2017-01-26 21:39:49 +000047///
48/// We also do not perform elimination by using any published algorithm. All
49/// published algorithms are O(Instructions). Instead, we use a technique that
50/// is O(number of operations with the same value number), enabling us to skip
51/// trying to eliminate things that have unique value numbers.
Eugene Zelenko99241d72017-10-20 21:47:29 +000052//
Davide Italiano7e274e02016-12-22 16:03:48 +000053//===----------------------------------------------------------------------===//
54
55#include "llvm/Transforms/Scalar/NewGVN.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000056#include "llvm/ADT/ArrayRef.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000057#include "llvm/ADT/BitVector.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000058#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/DenseMapInfo.h"
60#include "llvm/ADT/DenseSet.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000061#include "llvm/ADT/DepthFirstIterator.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000062#include "llvm/ADT/GraphTraits.h"
63#include "llvm/ADT/Hashing.h"
64#include "llvm/ADT/PointerIntPair.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000065#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000066#include "llvm/ADT/SmallPtrSet.h"
67#include "llvm/ADT/SmallVector.h"
Daniel Berlin9b926e92017-09-30 23:51:53 +000068#include "llvm/ADT/SparseBitVector.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000069#include "llvm/ADT/Statistic.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000070#include "llvm/ADT/iterator_range.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000071#include "llvm/Analysis/AliasAnalysis.h"
72#include "llvm/Analysis/AssumptionCache.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000073#include "llvm/Analysis/CFGPrinter.h"
74#include "llvm/Analysis/ConstantFolding.h"
75#include "llvm/Analysis/GlobalsModRef.h"
76#include "llvm/Analysis/InstructionSimplify.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000077#include "llvm/Analysis/MemoryBuiltins.h"
Daniel Berlin2f72b192017-04-14 02:53:37 +000078#include "llvm/Analysis/MemorySSA.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000079#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000080#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000081#include "llvm/IR/Argument.h"
82#include "llvm/IR/BasicBlock.h"
83#include "llvm/IR/Constant.h"
84#include "llvm/IR/Constants.h"
85#include "llvm/IR/Dominators.h"
86#include "llvm/IR/Function.h"
87#include "llvm/IR/InstrTypes.h"
88#include "llvm/IR/Instruction.h"
89#include "llvm/IR/Instructions.h"
90#include "llvm/IR/IntrinsicInst.h"
91#include "llvm/IR/Intrinsics.h"
92#include "llvm/IR/LLVMContext.h"
93#include "llvm/IR/Type.h"
94#include "llvm/IR/Use.h"
95#include "llvm/IR/User.h"
96#include "llvm/IR/Value.h"
97#include "llvm/Pass.h"
98#include "llvm/Support/Allocator.h"
99#include "llvm/Support/ArrayRecycler.h"
100#include "llvm/Support/Casting.h"
101#include "llvm/Support/CommandLine.h"
102#include "llvm/Support/Debug.h"
Daniel Berlin283a6082017-03-01 19:59:26 +0000103#include "llvm/Support/DebugCounter.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +0000104#include "llvm/Support/ErrorHandling.h"
105#include "llvm/Support/PointerLikeTypeTraits.h"
106#include "llvm/Support/raw_ostream.h"
Davide Italiano7e274e02016-12-22 16:03:48 +0000107#include "llvm/Transforms/Scalar.h"
108#include "llvm/Transforms/Scalar/GVNExpression.h"
Daniel Berlinf7d95802017-02-18 23:06:50 +0000109#include "llvm/Transforms/Utils/PredicateInfo.h"
Daniel Berlin07daac82017-04-02 13:23:44 +0000110#include "llvm/Transforms/Utils/VNCoercion.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +0000111#include <algorithm>
112#include <cassert>
113#include <cstdint>
114#include <iterator>
115#include <map>
116#include <memory>
117#include <set>
118#include <string>
119#include <tuple>
120#include <utility>
121#include <vector>
122
Davide Italiano7e274e02016-12-22 16:03:48 +0000123using namespace llvm;
Davide Italiano7e274e02016-12-22 16:03:48 +0000124using namespace llvm::GVNExpression;
Daniel Berlin07daac82017-04-02 13:23:44 +0000125using namespace llvm::VNCoercion;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000126
Davide Italiano7e274e02016-12-22 16:03:48 +0000127#define DEBUG_TYPE "newgvn"
128
129STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
130STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
131STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
132STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +0000133STATISTIC(NumGVNMaxIterations,
134 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000135STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
136STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
137STATISTIC(NumGVNAvoidedSortedLeaderChanges,
138 "Number of avoided sorted leader changes");
Daniel Berlinc4796862017-01-27 02:37:11 +0000139STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000140STATISTIC(NumGVNPHIOfOpsCreated, "Number of PHI of ops created");
141STATISTIC(NumGVNPHIOfOpsEliminations,
142 "Number of things eliminated using PHI of ops");
Daniel Berlin283a6082017-03-01 19:59:26 +0000143DEBUG_COUNTER(VNCounter, "newgvn-vn",
Craig Topper9cd976d2017-08-10 17:48:11 +0000144 "Controls which instructions are value numbered");
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000145DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
Craig Topper9cd976d2017-08-10 17:48:11 +0000146 "Controls which instructions we create phi of ops for");
Daniel Berlin1316a942017-04-06 18:52:50 +0000147// Currently store defining access refinement is too slow due to basicaa being
148// egregiously slow. This flag lets us keep it working while we work on this
149// issue.
150static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
151 cl::init(false), cl::Hidden);
152
Chad Rosiera5508e32017-08-10 14:12:57 +0000153/// Currently, the generation "phi of ops" can result in correctness issues.
Daniel Berlin94090dd2017-09-02 02:18:44 +0000154static cl::opt<bool> EnablePhiOfOps("enable-phi-of-ops", cl::init(true),
Chad Rosiera5508e32017-08-10 14:12:57 +0000155 cl::Hidden);
156
Davide Italiano7e274e02016-12-22 16:03:48 +0000157//===----------------------------------------------------------------------===//
158// GVN Pass
159//===----------------------------------------------------------------------===//
160
161// Anchor methods.
162namespace llvm {
163namespace GVNExpression {
Eugene Zelenko99241d72017-10-20 21:47:29 +0000164
Daniel Berlin85f91b02016-12-26 20:06:58 +0000165Expression::~Expression() = default;
166BasicExpression::~BasicExpression() = default;
167CallExpression::~CallExpression() = default;
168LoadExpression::~LoadExpression() = default;
169StoreExpression::~StoreExpression() = default;
170AggregateValueExpression::~AggregateValueExpression() = default;
171PHIExpression::~PHIExpression() = default;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000172
173} // end namespace GVNExpression
174} // end namespace llvm
Davide Italiano7e274e02016-12-22 16:03:48 +0000175
Benjamin Kramer49a49fe2017-08-20 13:03:48 +0000176namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +0000177
Daniel Berlin2f72b192017-04-14 02:53:37 +0000178// Tarjan's SCC finding algorithm with Nuutila's improvements
179// SCCIterator is actually fairly complex for the simple thing we want.
180// It also wants to hand us SCC's that are unrelated to the phi node we ask
181// about, and have us process them there or risk redoing work.
182// Graph traits over a filter iterator also doesn't work that well here.
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000183// This SCC finder is specialized to walk use-def chains, and only follows
184// instructions,
Daniel Berlin2f72b192017-04-14 02:53:37 +0000185// not generic values (arguments, etc).
186struct TarjanSCC {
Daniel Berlin2f72b192017-04-14 02:53:37 +0000187 TarjanSCC() : Components(1) {}
188
189 void Start(const Instruction *Start) {
190 if (Root.lookup(Start) == 0)
191 FindSCC(Start);
192 }
193
194 const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
195 unsigned ComponentID = ValueToComponent.lookup(V);
196
197 assert(ComponentID > 0 &&
198 "Asking for a component for a value we never processed");
199 return Components[ComponentID];
200 }
201
202private:
203 void FindSCC(const Instruction *I) {
204 Root[I] = ++DFSNum;
205 // Store the DFS Number we had before it possibly gets incremented.
206 unsigned int OurDFS = DFSNum;
207 for (auto &Op : I->operands()) {
208 if (auto *InstOp = dyn_cast<Instruction>(Op)) {
209 if (Root.lookup(Op) == 0)
210 FindSCC(InstOp);
211 if (!InComponent.count(Op))
212 Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
213 }
214 }
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000215 // See if we really were the root of a component, by seeing if we still have
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000216 // our DFSNumber. If we do, we are the root of the component, and we have
217 // completed a component. If we do not, we are not the root of a component,
218 // and belong on the component stack.
Daniel Berlin2f72b192017-04-14 02:53:37 +0000219 if (Root.lookup(I) == OurDFS) {
220 unsigned ComponentID = Components.size();
221 Components.resize(Components.size() + 1);
222 auto &Component = Components.back();
223 Component.insert(I);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000224 LLVM_DEBUG(dbgs() << "Component root is " << *I << "\n");
Daniel Berlin2f72b192017-04-14 02:53:37 +0000225 InComponent.insert(I);
226 ValueToComponent[I] = ComponentID;
227 // Pop a component off the stack and label it.
228 while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
229 auto *Member = Stack.back();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000230 LLVM_DEBUG(dbgs() << "Component member is " << *Member << "\n");
Daniel Berlin2f72b192017-04-14 02:53:37 +0000231 Component.insert(Member);
232 InComponent.insert(Member);
233 ValueToComponent[Member] = ComponentID;
234 Stack.pop_back();
235 }
236 } else {
237 // Part of a component, push to stack
238 Stack.push_back(I);
239 }
240 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000241
Daniel Berlin2f72b192017-04-14 02:53:37 +0000242 unsigned int DFSNum = 1;
243 SmallPtrSet<const Value *, 8> InComponent;
244 DenseMap<const Value *, unsigned int> Root;
245 SmallVector<const Value *, 8> Stack;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000246
Daniel Berlin2f72b192017-04-14 02:53:37 +0000247 // Store the components as vector of ptr sets, because we need the topo order
248 // of SCC's, but not individual member order
249 SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000250
Daniel Berlin2f72b192017-04-14 02:53:37 +0000251 DenseMap<const Value *, unsigned> ValueToComponent;
252};
Eugene Zelenko99241d72017-10-20 21:47:29 +0000253
Davide Italiano7e274e02016-12-22 16:03:48 +0000254// Congruence classes represent the set of expressions/instructions
255// that are all the same *during some scope in the function*.
256// That is, because of the way we perform equality propagation, and
257// because of memory value numbering, it is not correct to assume
258// you can willy-nilly replace any member with any other at any
259// point in the function.
260//
261// For any Value in the Member set, it is valid to replace any dominated member
262// with that Value.
263//
Daniel Berlin1316a942017-04-06 18:52:50 +0000264// Every congruence class has a leader, and the leader is used to symbolize
265// instructions in a canonical way (IE every operand of an instruction that is a
266// member of the same congruence class will always be replaced with leader
267// during symbolization). To simplify symbolization, we keep the leader as a
268// constant if class can be proved to be a constant value. Otherwise, the
269// leader is the member of the value set with the smallest DFS number. Each
270// congruence class also has a defining expression, though the expression may be
271// null. If it exists, it can be used for forward propagation and reassociation
272// of values.
273
274// For memory, we also track a representative MemoryAccess, and a set of memory
275// members for MemoryPhis (which have no real instructions). Note that for
276// memory, it seems tempting to try to split the memory members into a
277// MemoryCongruenceClass or something. Unfortunately, this does not work
278// easily. The value numbering of a given memory expression depends on the
279// leader of the memory congruence class, and the leader of memory congruence
280// class depends on the value numbering of a given memory expression. This
281// leads to wasted propagation, and in some cases, missed optimization. For
282// example: If we had value numbered two stores together before, but now do not,
283// we move them to a new value congruence class. This in turn will move at one
284// of the memorydefs to a new memory congruence class. Which in turn, affects
285// the value numbering of the stores we just value numbered (because the memory
286// congruence class is part of the value number). So while theoretically
287// possible to split them up, it turns out to be *incredibly* complicated to get
288// it to work right, because of the interdependency. While structurally
289// slightly messier, it is algorithmically much simpler and faster to do what we
Daniel Berlina8236562017-04-07 18:38:09 +0000290// do here, and track them both at once in the same class.
291// Note: The default iterators for this class iterate over values
292class CongruenceClass {
293public:
294 using MemberType = Value;
295 using MemberSet = SmallPtrSet<MemberType *, 4>;
296 using MemoryMemberType = MemoryPhi;
297 using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
298
299 explicit CongruenceClass(unsigned ID) : ID(ID) {}
300 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
301 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Eugene Zelenko99241d72017-10-20 21:47:29 +0000302
Daniel Berlina8236562017-04-07 18:38:09 +0000303 unsigned getID() const { return ID; }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000304
Daniel Berlina8236562017-04-07 18:38:09 +0000305 // True if this class has no members left. This is mainly used for assertion
306 // purposes, and for skipping empty classes.
307 bool isDead() const {
308 // If it's both dead from a value perspective, and dead from a memory
309 // perspective, it's really dead.
310 return empty() && memory_empty();
311 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000312
Daniel Berlina8236562017-04-07 18:38:09 +0000313 // Leader functions
314 Value *getLeader() const { return RepLeader; }
315 void setLeader(Value *Leader) { RepLeader = Leader; }
316 const std::pair<Value *, unsigned int> &getNextLeader() const {
317 return NextLeader;
318 }
319 void resetNextLeader() { NextLeader = {nullptr, ~0}; }
Daniel Berlina8236562017-04-07 18:38:09 +0000320 void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
321 if (LeaderPair.second < NextLeader.second)
322 NextLeader = LeaderPair;
323 }
324
325 Value *getStoredValue() const { return RepStoredValue; }
326 void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
327 const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
328 void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
329
330 // Forward propagation info
331 const Expression *getDefiningExpr() const { return DefiningExpr; }
Daniel Berlina8236562017-04-07 18:38:09 +0000332
333 // Value member set
334 bool empty() const { return Members.empty(); }
335 unsigned size() const { return Members.size(); }
336 MemberSet::const_iterator begin() const { return Members.begin(); }
337 MemberSet::const_iterator end() const { return Members.end(); }
338 void insert(MemberType *M) { Members.insert(M); }
339 void erase(MemberType *M) { Members.erase(M); }
340 void swap(MemberSet &Other) { Members.swap(Other); }
341
342 // Memory member set
343 bool memory_empty() const { return MemoryMembers.empty(); }
344 unsigned memory_size() const { return MemoryMembers.size(); }
345 MemoryMemberSet::const_iterator memory_begin() const {
346 return MemoryMembers.begin();
347 }
348 MemoryMemberSet::const_iterator memory_end() const {
349 return MemoryMembers.end();
350 }
351 iterator_range<MemoryMemberSet::const_iterator> memory() const {
352 return make_range(memory_begin(), memory_end());
353 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000354
Daniel Berlina8236562017-04-07 18:38:09 +0000355 void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
356 void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
357
358 // Store count
359 unsigned getStoreCount() const { return StoreCount; }
360 void incStoreCount() { ++StoreCount; }
361 void decStoreCount() {
362 assert(StoreCount != 0 && "Store count went negative");
363 --StoreCount;
364 }
365
Davide Italianodc435322017-05-10 19:57:43 +0000366 // True if this class has no memory members.
367 bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
368
George Burgess IV485762c2018-05-30 22:24:08 +0000369 // Return true if two congruence classes are equivalent to each other. This
370 // means that every field but the ID number and the dead field are equivalent.
Daniel Berlina8236562017-04-07 18:38:09 +0000371 bool isEquivalentTo(const CongruenceClass *Other) const {
372 if (!Other)
373 return false;
374 if (this == Other)
375 return true;
376
377 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
378 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
379 Other->RepMemoryAccess))
380 return false;
381 if (DefiningExpr != Other->DefiningExpr)
382 if (!DefiningExpr || !Other->DefiningExpr ||
383 *DefiningExpr != *Other->DefiningExpr)
384 return false;
George Burgess IV485762c2018-05-30 22:24:08 +0000385
386 if (Members.size() != Other->Members.size())
387 return false;
388
389 return all_of(Members,
390 [&](const Value *V) { return Other->Members.count(V); });
Daniel Berlina8236562017-04-07 18:38:09 +0000391 }
392
393private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000394 unsigned ID;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000395
Davide Italiano7e274e02016-12-22 16:03:48 +0000396 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000397 Value *RepLeader = nullptr;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000398
Daniel Berlina8236562017-04-07 18:38:09 +0000399 // The most dominating leader after our current leader, because the member set
400 // is not sorted and is expensive to keep sorted all the time.
401 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
Eugene Zelenko99241d72017-10-20 21:47:29 +0000402
Daniel Berlin1316a942017-04-06 18:52:50 +0000403 // If this is represented by a store, the value of the store.
Daniel Berlin26addef2017-01-20 21:04:30 +0000404 Value *RepStoredValue = nullptr;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000405
Daniel Berlin1316a942017-04-06 18:52:50 +0000406 // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
407 // access.
408 const MemoryAccess *RepMemoryAccess = nullptr;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000409
Davide Italiano7e274e02016-12-22 16:03:48 +0000410 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000411 const Expression *DefiningExpr = nullptr;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000412
Davide Italiano7e274e02016-12-22 16:03:48 +0000413 // Actual members of this class.
414 MemberSet Members;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000415
Daniel Berlin1316a942017-04-06 18:52:50 +0000416 // This is the set of MemoryPhis that exist in the class. MemoryDefs and
417 // MemoryUses have real instructions representing them, so we only need to
418 // track MemoryPhis here.
419 MemoryMemberSet MemoryMembers;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000420
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000421 // Number of stores in this congruence class.
422 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000423 int StoreCount = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +0000424};
Eugene Zelenko99241d72017-10-20 21:47:29 +0000425
426} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000427
428namespace llvm {
Eugene Zelenko99241d72017-10-20 21:47:29 +0000429
Daniel Berlineafdd862017-06-06 17:15:28 +0000430struct ExactEqualsExpression {
431 const Expression &E;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000432
Daniel Berlineafdd862017-06-06 17:15:28 +0000433 explicit ExactEqualsExpression(const Expression &E) : E(E) {}
Eugene Zelenko99241d72017-10-20 21:47:29 +0000434
Daniel Berlineafdd862017-06-06 17:15:28 +0000435 hash_code getComputedHash() const { return E.getComputedHash(); }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000436
Daniel Berlineafdd862017-06-06 17:15:28 +0000437 bool operator==(const Expression &Other) const {
438 return E.exactlyEquals(Other);
439 }
440};
441
Daniel Berlin85f91b02016-12-26 20:06:58 +0000442template <> struct DenseMapInfo<const Expression *> {
443 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000444 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000445 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
446 return reinterpret_cast<const Expression *>(Val);
447 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000448
Daniel Berlin85f91b02016-12-26 20:06:58 +0000449 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000450 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000451 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
452 return reinterpret_cast<const Expression *>(Val);
453 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000454
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000455 static unsigned getHashValue(const Expression *E) {
Daniel Berlineafdd862017-06-06 17:15:28 +0000456 return E->getComputedHash();
Daniel Berlin85f91b02016-12-26 20:06:58 +0000457 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000458
Daniel Berlineafdd862017-06-06 17:15:28 +0000459 static unsigned getHashValue(const ExactEqualsExpression &E) {
460 return E.getComputedHash();
461 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000462
Daniel Berlineafdd862017-06-06 17:15:28 +0000463 static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS) {
464 if (RHS == getTombstoneKey() || RHS == getEmptyKey())
465 return false;
466 return LHS == *RHS;
467 }
468
Daniel Berlin85f91b02016-12-26 20:06:58 +0000469 static bool isEqual(const Expression *LHS, const Expression *RHS) {
470 if (LHS == RHS)
471 return true;
472 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
473 LHS == getEmptyKey() || RHS == getEmptyKey())
474 return false;
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000475 // Compare hashes before equality. This is *not* what the hashtable does,
476 // since it is computing it modulo the number of buckets, whereas we are
477 // using the full hash keyspace. Since the hashes are precomputed, this
478 // check is *much* faster than equality.
479 if (LHS->getComputedHash() != RHS->getComputedHash())
480 return false;
Daniel Berlin85f91b02016-12-26 20:06:58 +0000481 return *LHS == *RHS;
482 }
483};
Eugene Zelenko99241d72017-10-20 21:47:29 +0000484
Davide Italiano7e274e02016-12-22 16:03:48 +0000485} // end namespace llvm
486
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000487namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +0000488
Daniel Berlin64e68992017-03-12 04:46:45 +0000489class NewGVN {
490 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000491 DominatorTree *DT;
Daniel Berlin64e68992017-03-12 04:46:45 +0000492 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000493 AliasAnalysis *AA;
494 MemorySSA *MSSA;
495 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000496 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000497 std::unique_ptr<PredicateInfo> PredInfo;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000498
499 // These are the only two things the create* functions should have
500 // side-effects on due to allocating memory.
501 mutable BumpPtrAllocator ExpressionAllocator;
502 mutable ArrayRecycler<Value *> ArgRecycler;
503 mutable TarjanSCC SCCFinder;
Daniel Berlinede130d2017-04-26 20:56:14 +0000504 const SimplifyQuery SQ;
Davide Italiano7e274e02016-12-22 16:03:48 +0000505
Daniel Berlin1c087672017-02-11 15:07:01 +0000506 // Number of function arguments, used by ranking
507 unsigned int NumFuncArgs;
508
Daniel Berlin2f72b192017-04-14 02:53:37 +0000509 // RPOOrdering of basic blocks
510 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
511
Davide Italiano7e274e02016-12-22 16:03:48 +0000512 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000513
514 // This class is called INITIAL in the paper. It is the class everything
515 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000516 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000517 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000518 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000519 std::vector<CongruenceClass *> CongruenceClasses;
520 unsigned NextCongruenceNum;
521
522 // Value Mappings.
523 DenseMap<Value *, CongruenceClass *> ValueToClass;
524 DenseMap<Value *, const Expression *> ValueToExpression;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000525
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000526 // Value PHI handling, used to make equivalence between phi(op, op) and
527 // op(phi, phi).
528 // These mappings just store various data that would normally be part of the
529 // IR.
Daniel Berlin9b926e92017-09-30 23:51:53 +0000530 SmallPtrSet<const Instruction *, 8> PHINodeUses;
531
Daniel Berlin94090dd2017-09-02 02:18:44 +0000532 DenseMap<const Value *, bool> OpSafeForPHIOfOps;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000533
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000534 // Map a temporary instruction we created to a parent block.
535 DenseMap<const Value *, BasicBlock *> TempToBlock;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000536
Davide Italiano5974c312017-08-03 21:17:49 +0000537 // Map between the already in-program instructions and the temporary phis we
538 // created that they are known equivalent to.
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000539 DenseMap<const Value *, PHINode *> RealToTemp;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000540
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000541 // In order to know when we should re-process instructions that have
542 // phi-of-ops, we track the set of expressions that they needed as
543 // leaders. When we discover new leaders for those expressions, we process the
544 // associated phi-of-op instructions again in case they have changed. The
545 // other way they may change is if they had leaders, and those leaders
546 // disappear. However, at the point they have leaders, there are uses of the
547 // relevant operands in the created phi node, and so they will get reprocessed
548 // through the normal user marking we perform.
549 mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
550 DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
551 ExpressionToPhiOfOps;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000552
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000553 // Map from temporary operation to MemoryAccess.
554 DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000555
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000556 // Set of all temporary instructions we created.
Davide Italiano5974c312017-08-03 21:17:49 +0000557 // Note: This will include instructions that were just created during value
558 // numbering. The way to test if something is using them is to check
559 // RealToTemp.
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000560 DenseSet<Instruction *> AllTempInstructions;
Davide Italiano7e274e02016-12-22 16:03:48 +0000561
Daniel Berlin9b926e92017-09-30 23:51:53 +0000562 // This is the set of instructions to revisit on a reachability change. At
563 // the end of the main iteration loop it will contain at least all the phi of
564 // ops instructions that will be changed to phis, as well as regular phis.
565 // During the iteration loop, it may contain other things, such as phi of ops
566 // instructions that used edge reachability to reach a result, and so need to
567 // be revisited when the edge changes, independent of whether the phi they
568 // depended on changes.
569 DenseMap<BasicBlock *, SparseBitVector<>> RevisitOnReachabilityChange;
570
Daniel Berlinf7d95802017-02-18 23:06:50 +0000571 // Mapping from predicate info we used to the instructions we used it with.
572 // In order to correctly ensure propagation, we must keep track of what
573 // comparisons we used, so that when the values of the comparisons change, we
574 // propagate the information to the places we used the comparison.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000575 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
576 PredicateToUsers;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000577
Daniel Berlin1316a942017-04-06 18:52:50 +0000578 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
579 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000580 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
581 MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000582
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000583 // A table storing which memorydefs/phis represent a memory state provably
584 // equivalent to another memory state.
585 // We could use the congruence class machinery, but the MemoryAccess's are
586 // abstract memory states, so they can only ever be equivalent to each other,
587 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000588 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000589
Daniel Berlin1316a942017-04-06 18:52:50 +0000590 // We could, if we wanted, build MemoryPhiExpressions and
591 // MemoryVariableExpressions, etc, and value number them the same way we value
592 // number phi expressions. For the moment, this seems like overkill. They
593 // can only exist in one of three states: they can be TOP (equal to
594 // everything), Equivalent to something else, or unique. Because we do not
595 // create expressions for them, we need to simulate leader change not just
596 // when they change class, but when they change state. Note: We can do the
597 // same thing for phis, and avoid having phi expressions if we wanted, We
598 // should eventually unify in one direction or the other, so this is a little
599 // bit of an experiment in which turns out easier to maintain.
600 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
601 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
602
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000603 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
604 mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000605
Davide Italiano7e274e02016-12-22 16:03:48 +0000606 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000607 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000608 ExpressionClassMap ExpressionToClass;
609
Daniel Berline021d2d2017-05-19 20:22:20 +0000610 // We have a single expression that represents currently DeadExpressions.
611 // For dead expressions we can prove will stay dead, we mark them with
612 // DFS number zero. However, it's possible in the case of phi nodes
613 // for us to assume/prove all arguments are dead during fixpointing.
614 // We use DeadExpression for that case.
615 DeadExpression *SingletonDeadExpression = nullptr;
616
Davide Italiano7e274e02016-12-22 16:03:48 +0000617 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000618 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000619
620 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000621 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000622 DenseSet<BlockEdge> ReachableEdges;
623 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
624
625 // This is a bitvector because, on larger functions, we may have
626 // thousands of touched instructions at once (entire blocks,
627 // instructions with hundreds of uses, etc). Even with optimization
628 // for when we mark whole blocks as touched, when this was a
629 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
630 // the time in GVN just managing this list. The bitvector, on the
631 // other hand, efficiently supports test/set/clear of both
632 // individual and ranges, as well as "find next element" This
633 // enables us to use it as a worklist with essentially 0 cost.
634 BitVector TouchedInstructions;
635
636 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000637
638#ifndef NDEBUG
639 // Debugging for how many times each block and instruction got processed.
640 DenseMap<const Value *, unsigned> ProcessedCount;
641#endif
642
643 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000644 // This contains a mapping from Instructions to DFS numbers.
645 // The numbering starts at 1. An instruction with DFS number zero
646 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000647 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000648
649 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000650 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000651
652 // Deletion info.
653 SmallPtrSet<Instruction *, 8> InstructionsToErase;
654
655public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000656 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
657 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
658 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000659 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Florian Hahn19f9e322018-08-17 14:39:04 +0000660 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)),
661 SQ(DL, TLI, DT, AC, /*CtxI=*/nullptr, /*UseInstrInfo=*/false) {}
Eugene Zelenko99241d72017-10-20 21:47:29 +0000662
Daniel Berlin64e68992017-03-12 04:46:45 +0000663 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000664
665private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000666 // Expression handling.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000667 const Expression *createExpression(Instruction *) const;
Daniel Berlin54a92fc2017-09-05 02:17:42 +0000668 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
669 Instruction *) const;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000670
Daniel Berlinc1305af2017-09-30 23:51:54 +0000671 // Our canonical form for phi arguments is a pair of incoming value, incoming
672 // basic block.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000673 using ValPair = std::pair<Value *, BasicBlock *>;
674
Daniel Berlinc1305af2017-09-30 23:51:54 +0000675 PHIExpression *createPHIExpression(ArrayRef<ValPair>, const Instruction *,
676 BasicBlock *, bool &HasBackEdge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000677 bool &OriginalOpsConstant) const;
Daniel Berline021d2d2017-05-19 20:22:20 +0000678 const DeadExpression *createDeadExpression() const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000679 const VariableExpression *createVariableExpression(Value *) const;
680 const ConstantExpression *createConstantExpression(Constant *) const;
681 const Expression *createVariableOrConstant(Value *V) const;
682 const UnknownExpression *createUnknownExpression(Instruction *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000683 const StoreExpression *createStoreExpression(StoreInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000684 const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000685 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000686 const MemoryAccess *) const;
687 const CallExpression *createCallExpression(CallInst *,
688 const MemoryAccess *) const;
689 const AggregateValueExpression *
690 createAggregateValueExpression(Instruction *) const;
691 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000692
693 // Congruence class handling.
694 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000695 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000696 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000697 return result;
698 }
699
Daniel Berlin1316a942017-04-06 18:52:50 +0000700 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
701 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000702 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000703 return CC;
704 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000705
Daniel Berlin1316a942017-04-06 18:52:50 +0000706 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
707 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000708 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000709 CC = createMemoryClass(MA);
710 return CC;
711 }
712
Davide Italiano7e274e02016-12-22 16:03:48 +0000713 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000714 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000715 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000716 ValueToClass[Member] = CClass;
717 return CClass;
718 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000719
Davide Italiano7e274e02016-12-22 16:03:48 +0000720 void initializeCongruenceClasses(Function &F);
Daniel Berlin9b926e92017-09-30 23:51:53 +0000721 const Expression *makePossiblePHIOfOps(Instruction *,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000722 SmallPtrSetImpl<Value *> &);
Daniel Berlin94090dd2017-09-02 02:18:44 +0000723 Value *findLeaderForInst(Instruction *ValueOp,
724 SmallPtrSetImpl<Value *> &Visited,
725 MemoryAccess *MemAccess, Instruction *OrigInst,
726 BasicBlock *PredBB);
Daniel Berlin08dd5822017-10-06 01:33:06 +0000727 bool OpIsSafeForPHIOfOpsHelper(Value *V, const BasicBlock *PHIBlock,
728 SmallPtrSetImpl<const Value *> &Visited,
729 SmallVectorImpl<Instruction *> &Worklist);
730 bool OpIsSafeForPHIOfOps(Value *Op, const BasicBlock *PHIBlock,
Daniel Berlin94090dd2017-09-02 02:18:44 +0000731 SmallPtrSetImpl<const Value *> &);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000732 void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
Davide Italiano5974c312017-08-03 21:17:49 +0000733 void removePhiOfOps(Instruction *I, PHINode *PHITemp);
Davide Italiano7e274e02016-12-22 16:03:48 +0000734
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000735 // Value number an Instruction or MemoryPhi.
736 void valueNumberMemoryPhi(MemoryPhi *);
737 void valueNumberInstruction(Instruction *);
738
Davide Italiano7e274e02016-12-22 16:03:48 +0000739 // Symbolic evaluation.
740 const Expression *checkSimplificationResults(Expression *, Instruction *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000741 Value *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000742 const Expression *performSymbolicEvaluation(Value *,
743 SmallPtrSetImpl<Value *> &) const;
Daniel Berlin07daac82017-04-02 13:23:44 +0000744 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000745 Instruction *,
746 MemoryAccess *) const;
747 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
748 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
749 const Expression *performSymbolicCallEvaluation(Instruction *) const;
Daniel Berlinc1305af2017-09-30 23:51:54 +0000750 void sortPHIOps(MutableArrayRef<ValPair> Ops) const;
751 const Expression *performSymbolicPHIEvaluation(ArrayRef<ValPair>,
752 Instruction *I,
753 BasicBlock *PHIBlock) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000754 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
755 const Expression *performSymbolicCmpEvaluation(Instruction *) const;
756 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000757
758 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000759 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000760 Value *lookupOperandLeader(Value *) const;
Daniel Berlin94090dd2017-09-02 02:18:44 +0000761 CongruenceClass *getClassForExpression(const Expression *E) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000762 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000763 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
764 CongruenceClass *, CongruenceClass *);
765 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
766 CongruenceClass *, CongruenceClass *);
767 Value *getNextValueLeader(CongruenceClass *) const;
768 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
769 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
770 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
771 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000772 bool isMemoryAccessTOP(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000773
Daniel Berlin1c087672017-02-11 15:07:01 +0000774 // Ranking
775 unsigned int getRank(const Value *) const;
776 bool shouldSwapOperands(const Value *, const Value *) const;
777
Davide Italiano7e274e02016-12-22 16:03:48 +0000778 // Reachability handling.
779 void updateReachableEdge(BasicBlock *, BasicBlock *);
780 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000781 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000782
783 // Elimination.
784 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000785 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000786 SmallVectorImpl<ValueDFS> &,
787 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000788 SmallPtrSetImpl<Instruction *> &) const;
789 void convertClassToLoadsAndStores(const CongruenceClass &,
790 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000791
792 bool eliminateInstructions(Function &);
793 void replaceInstruction(Instruction *, Value *);
794 void markInstructionForDeletion(Instruction *);
795 void deleteInstructionsInBlock(BasicBlock *);
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +0000796 Value *findPHIOfOpsLeader(const Expression *, const Instruction *,
797 const BasicBlock *) const;
798
Davide Italiano7e274e02016-12-22 16:03:48 +0000799 // New instruction creation.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000800 void handleNewInstruction(Instruction *) {}
Daniel Berlin32f8d562017-01-07 16:55:14 +0000801
802 // Various instruction touch utilities
Daniel Berlin0207cca2017-05-21 23:41:56 +0000803 template <typename Map, typename KeyType, typename Func>
804 void for_each_found(Map &, const KeyType &, Func);
805 template <typename Map, typename KeyType>
806 void touchAndErase(Map &, const KeyType &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000807 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000808 void markMemoryUsersTouched(const MemoryAccess *);
809 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000810 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000811 void markValueLeaderChangeTouched(CongruenceClass *CC);
812 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000813 void markPhiOfOpsChanged(const Expression *E);
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000814 void addPredicateUsers(const PredicateBase *, Instruction *) const;
815 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000816 void addAdditionalUsers(Value *To, Value *User) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000817
Daniel Berlin06329a92017-03-18 15:41:40 +0000818 // Main loop of value numbering
819 void iterateTouchedInstructions();
820
Davide Italiano7e274e02016-12-22 16:03:48 +0000821 // Utilities.
822 void cleanupTables();
823 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000824 void updateProcessedCount(const Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000825 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000826 void verifyIterationSettled(Function &F);
Daniel Berlin45403572017-05-16 19:58:47 +0000827 void verifyStoreExpressions() const;
Davide Italianoeab0de22017-05-18 23:22:44 +0000828 bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
829 const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000830 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000831 void deleteExpression(const Expression *E) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000832 MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
833 MemoryAccess *getDefiningAccess(const MemoryAccess *) const;
834 MemoryPhi *getMemoryAccess(const BasicBlock *) const;
835 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000836
Daniel Berlin21279bd2017-04-06 18:52:58 +0000837 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000838 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
839 return InstrDFS.lookup(V);
840 }
841
Daniel Berlin21279bd2017-04-06 18:52:58 +0000842 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
843 return MemoryToDFSNum(MA);
844 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000845
Daniel Berlin21279bd2017-04-06 18:52:58 +0000846 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000847
Daniel Berlin21279bd2017-04-06 18:52:58 +0000848 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
849 // This deliberately takes a value so it can be used with Use's, which will
850 // auto-convert to Value's but not to MemoryAccess's.
851 unsigned MemoryToDFSNum(const Value *MA) const {
852 assert(isa<MemoryAccess>(MA) &&
853 "This should not be used with instructions");
854 return isa<MemoryUseOrDef>(MA)
855 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
856 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000857 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000858
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000859 bool isCycleFree(const Instruction *) const;
860 bool isBackedge(BasicBlock *From, BasicBlock *To) const;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000861
Daniel Berlin06329a92017-03-18 15:41:40 +0000862 // Debug counter info. When verifying, we have to reset the value numbering
863 // debug counter to the same state it started in to get the same results.
George Burgess IVb00fb462018-07-23 21:49:36 +0000864 int64_t StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000865};
Eugene Zelenko99241d72017-10-20 21:47:29 +0000866
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000867} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000868
Davide Italianob1114092016-12-28 13:37:17 +0000869template <typename T>
870static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000871 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000872 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000873 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000874}
875
Davide Italianob1114092016-12-28 13:37:17 +0000876bool LoadExpression::equals(const Expression &Other) const {
877 return equalsLoadStoreHelper(*this, Other);
878}
Davide Italiano7e274e02016-12-22 16:03:48 +0000879
Davide Italianob1114092016-12-28 13:37:17 +0000880bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000881 if (!equalsLoadStoreHelper(*this, Other))
882 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000883 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000884 if (const auto *S = dyn_cast<StoreExpression>(&Other))
885 if (getStoredValue() != S->getStoredValue())
886 return false;
887 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000888}
889
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000890// Determine if the edge From->To is a backedge
891bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
Davide Italianoc2f73b72017-08-02 04:05:49 +0000892 return From == To ||
893 RPOOrdering.lookup(DT->getNode(From)) >=
894 RPOOrdering.lookup(DT->getNode(To));
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000895}
896
Davide Italiano7e274e02016-12-22 16:03:48 +0000897#ifndef NDEBUG
898static std::string getBlockName(const BasicBlock *B) {
Sean Fertilecd0d7632018-06-29 17:48:58 +0000899 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000900}
901#endif
902
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000903// Get a MemoryAccess for an instruction, fake or real.
904MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
905 auto *Result = MSSA->getMemoryAccess(I);
906 return Result ? Result : TempToMemory.lookup(I);
907}
908
909// Get a MemoryPhi for a basic block. These are all real.
910MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
911 return MSSA->getMemoryAccess(BB);
912}
913
Daniel Berlin06329a92017-03-18 15:41:40 +0000914// Get the basic block from an instruction/memory value.
915BasicBlock *NewGVN::getBlockForValue(Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000916 if (auto *I = dyn_cast<Instruction>(V)) {
917 auto *Parent = I->getParent();
918 if (Parent)
919 return Parent;
920 Parent = TempToBlock.lookup(V);
921 assert(Parent && "Every fake instruction should have a block");
922 return Parent;
923 }
924
925 auto *MP = dyn_cast<MemoryPhi>(V);
926 assert(MP && "Should have been an instruction or a MemoryPhi");
927 return MP->getBlock();
Daniel Berlin06329a92017-03-18 15:41:40 +0000928}
929
Daniel Berlin0e900112017-03-24 06:33:48 +0000930// Delete a definitely dead expression, so it can be reused by the expression
931// allocator. Some of these are not in creation functions, so we have to accept
932// const versions.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000933void NewGVN::deleteExpression(const Expression *E) const {
Daniel Berlin0e900112017-03-24 06:33:48 +0000934 assert(isa<BasicExpression>(E));
935 auto *BE = cast<BasicExpression>(E);
936 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
937 ExpressionAllocator.Deallocate(E);
938}
Daniel Berlin1a582582017-09-05 02:17:41 +0000939
Daniel Berlinf9c94552017-09-05 02:17:43 +0000940// If V is a predicateinfo copy, get the thing it is a copy of.
941static Value *getCopyOf(const Value *V) {
Daniel Berlin1a582582017-09-05 02:17:41 +0000942 if (auto *II = dyn_cast<IntrinsicInst>(V))
Daniel Berlinf9c94552017-09-05 02:17:43 +0000943 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
944 return II->getOperand(0);
945 return nullptr;
946}
947
948// Return true if V is really PN, even accounting for predicateinfo copies.
949static bool isCopyOfPHI(const Value *V, const PHINode *PN) {
950 return V == PN || getCopyOf(V) == PN;
951}
952
953static bool isCopyOfAPHI(const Value *V) {
954 auto *CO = getCopyOf(V);
955 return CO && isa<PHINode>(CO);
Daniel Berlin1a582582017-09-05 02:17:41 +0000956}
957
Daniel Berlinc1305af2017-09-30 23:51:54 +0000958// Sort PHI Operands into a canonical order. What we use here is an RPO
959// order. The BlockInstRange numbers are generated in an RPO walk of the basic
960// blocks.
961void NewGVN::sortPHIOps(MutableArrayRef<ValPair> Ops) const {
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000962 llvm::sort(Ops.begin(), Ops.end(),
963 [&](const ValPair &P1, const ValPair &P2) {
Daniel Berlinc1305af2017-09-30 23:51:54 +0000964 return BlockInstRange.lookup(P1.second).first <
965 BlockInstRange.lookup(P2.second).first;
966 });
967}
968
Daniel Berlin9b926e92017-09-30 23:51:53 +0000969// Return true if V is a value that will always be available (IE can
970// be placed anywhere) in the function. We don't do globals here
971// because they are often worse to put in place.
972static bool alwaysAvailable(Value *V) {
973 return isa<Constant>(V) || isa<Argument>(V);
974}
975
Daniel Berlinc1305af2017-09-30 23:51:54 +0000976// Create a PHIExpression from an array of {incoming edge, value} pairs. I is
977// the original instruction we are creating a PHIExpression for (but may not be
978// a phi node). We require, as an invariant, that all the PHIOperands in the
979// same block are sorted the same way. sortPHIOps will sort them into a
980// canonical order.
981PHIExpression *NewGVN::createPHIExpression(ArrayRef<ValPair> PHIOperands,
982 const Instruction *I,
983 BasicBlock *PHIBlock,
984 bool &HasBackedge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000985 bool &OriginalOpsConstant) const {
Daniel Berlinc1305af2017-09-30 23:51:54 +0000986 unsigned NumOps = PHIOperands.size();
987 auto *E = new (ExpressionAllocator) PHIExpression(NumOps, PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000988
989 E->allocateOperands(ArgRecycler, ExpressionAllocator);
Daniel Berlinc1305af2017-09-30 23:51:54 +0000990 E->setType(PHIOperands.begin()->first->getType());
991 E->setOpcode(Instruction::PHI);
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000992
Davide Italianob3886dd2017-01-25 23:37:49 +0000993 // Filter out unreachable phi operands.
Daniel Berlinc1305af2017-09-30 23:51:54 +0000994 auto Filtered = make_filter_range(PHIOperands, [&](const ValPair &P) {
995 auto *BB = P.second;
996 if (auto *PHIOp = dyn_cast<PHINode>(I))
997 if (isCopyOfPHI(P.first, PHIOp))
998 return false;
Daniel Berlinf9c94552017-09-05 02:17:43 +0000999 if (!ReachableEdges.count({BB, PHIBlock}))
Daniel Berline67c3222017-05-25 15:44:20 +00001000 return false;
1001 // Things in TOPClass are equivalent to everything.
Daniel Berlinc1305af2017-09-30 23:51:54 +00001002 if (ValueToClass.lookup(P.first) == TOPClass)
Daniel Berline67c3222017-05-25 15:44:20 +00001003 return false;
Daniel Berlinc1305af2017-09-30 23:51:54 +00001004 OriginalOpsConstant = OriginalOpsConstant && isa<Constant>(P.first);
Daniel Berlinf9c94552017-09-05 02:17:43 +00001005 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
Daniel Berlinc1305af2017-09-30 23:51:54 +00001006 return lookupOperandLeader(P.first) != I;
Davide Italianob3886dd2017-01-25 23:37:49 +00001007 });
Daniel Berlinc1305af2017-09-30 23:51:54 +00001008 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
1009 [&](const ValPair &P) -> Value * {
1010 return lookupOperandLeader(P.first);
1011 });
Davide Italiano7e274e02016-12-22 16:03:48 +00001012 return E;
1013}
1014
1015// Set basic expression info (Arguments, type, opcode) for Expression
1016// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001017bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001018 bool AllConstant = true;
1019 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
1020 E->setType(GEP->getSourceElementType());
1021 else
1022 E->setType(I->getType());
1023 E->setOpcode(I->getOpcode());
1024 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1025
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001026 // Transform the operand array into an operand leader array, and keep track of
1027 // whether all members are constant.
1028 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001029 auto Operand = lookupOperandLeader(O);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001030 AllConstant = AllConstant && isa<Constant>(Operand);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001031 return Operand;
1032 });
1033
Davide Italiano7e274e02016-12-22 16:03:48 +00001034 return AllConstant;
1035}
1036
1037const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin54a92fc2017-09-05 02:17:42 +00001038 Value *Arg1, Value *Arg2,
1039 Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001040 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +00001041
1042 E->setType(T);
1043 E->setOpcode(Opcode);
1044 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1045 if (Instruction::isCommutative(Opcode)) {
1046 // Ensure that commutative instructions that only differ by a permutation
1047 // of their operands get the same value number by sorting the operand value
1048 // numbers. Since all commutative instructions have two operands it is more
1049 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +00001050 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +00001051 std::swap(Arg1, Arg2);
1052 }
Daniel Berlin203f47b2017-01-31 22:31:53 +00001053 E->op_push_back(lookupOperandLeader(Arg1));
1054 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +00001055
Daniel Berlinede130d2017-04-26 20:56:14 +00001056 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlin54a92fc2017-09-05 02:17:42 +00001057 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
Davide Italiano7e274e02016-12-22 16:03:48 +00001058 return SimplifiedE;
1059 return E;
1060}
1061
1062// Take a Value returned by simplification of Expression E/Instruction
1063// I, and see if it resulted in a simpler expression. If so, return
1064// that expression.
Davide Italiano7e274e02016-12-22 16:03:48 +00001065const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001066 Instruction *I,
1067 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001068 if (!V)
1069 return nullptr;
1070 if (auto *C = dyn_cast<Constant>(V)) {
1071 if (I)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001072 LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
1073 << " constant " << *C << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001074 NumGVNOpsSimplified++;
1075 assert(isa<BasicExpression>(E) &&
1076 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +00001077 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001078 return createConstantExpression(C);
1079 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1080 if (I)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001081 LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
1082 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001083 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001084 return createVariableExpression(V);
1085 }
1086
1087 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlin7ef26da2017-08-30 19:52:39 +00001088 if (CC) {
1089 if (CC->getLeader() && CC->getLeader() != I) {
Daniel Berlin94090dd2017-09-02 02:18:44 +00001090 // Don't add temporary instructions to the user lists.
1091 if (!AllTempInstructions.count(I))
1092 addAdditionalUsers(V, I);
Daniel Berlin7ef26da2017-08-30 19:52:39 +00001093 return createVariableOrConstant(CC->getLeader());
Daniel Berlinc8ed4042017-05-30 06:42:29 +00001094 }
Daniel Berlin7ef26da2017-08-30 19:52:39 +00001095 if (CC->getDefiningExpr()) {
1096 // If we simplified to something else, we need to communicate
1097 // that we're users of the value we simplified to.
1098 if (I != V) {
1099 // Don't add temporary instructions to the user lists.
1100 if (!AllTempInstructions.count(I))
1101 addAdditionalUsers(V, I);
1102 }
1103
1104 if (I)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001105 LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
1106 << " expression " << *CC->getDefiningExpr() << "\n");
Daniel Berlin7ef26da2017-08-30 19:52:39 +00001107 NumGVNOpsSimplified++;
1108 deleteExpression(E);
1109 return CC->getDefiningExpr();
1110 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001111 }
Daniel Berlin7ef26da2017-08-30 19:52:39 +00001112
Davide Italiano7e274e02016-12-22 16:03:48 +00001113 return nullptr;
1114}
1115
Daniel Berlin94090dd2017-09-02 02:18:44 +00001116// Create a value expression from the instruction I, replacing operands with
1117// their leaders.
1118
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001119const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001120 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +00001121
Daniel Berlin97718e62017-01-31 22:32:03 +00001122 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001123
1124 if (I->isCommutative()) {
1125 // Ensure that commutative instructions that only differ by a permutation
1126 // of their operands get the same value number by sorting the operand value
1127 // numbers. Since all commutative instructions have two operands it is more
1128 // efficient to sort by hand rather than using, say, std::sort.
1129 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +00001130 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +00001131 E->swapOperands(0, 1);
1132 }
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001133 // Perform simplification.
Davide Italiano7e274e02016-12-22 16:03:48 +00001134 if (auto *CI = dyn_cast<CmpInst>(I)) {
1135 // Sort the operand value numbers so x<y and y>x get the same value
1136 // number.
1137 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +00001138 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001139 E->swapOperands(0, 1);
1140 Predicate = CmpInst::getSwappedPredicate(Predicate);
1141 }
1142 E->setOpcode((CI->getOpcode() << 8) | Predicate);
1143 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +00001144 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
1145 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +00001146 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
1147 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +00001148 Value *V =
1149 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +00001150 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1151 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001152 } else if (isa<SelectInst>(I)) {
1153 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlinf9486032017-08-24 02:43:17 +00001154 E->getOperand(1) == E->getOperand(2)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001155 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1156 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +00001157 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +00001158 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001159 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1160 return SimplifiedE;
1161 }
1162 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001163 Value *V =
1164 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001165 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1166 return SimplifiedE;
1167 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001168 Value *V =
1169 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001170 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1171 return SimplifiedE;
1172 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001173 Value *V = SimplifyGEPInst(
1174 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001175 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1176 return SimplifiedE;
1177 } else if (AllConstant) {
1178 // We don't bother trying to simplify unless all of the operands
1179 // were constant.
1180 // TODO: There are a lot of Simplify*'s we could call here, if we
1181 // wanted to. The original motivating case for this code was a
1182 // zext i1 false to i8, which we don't have an interface to
1183 // simplify (IE there is no SimplifyZExt).
1184
1185 SmallVector<Constant *, 8> C;
1186 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001187 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +00001188
Daniel Berlin64e68992017-03-12 04:46:45 +00001189 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +00001190 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1191 return SimplifiedE;
1192 }
1193 return E;
1194}
1195
1196const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001197NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001198 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001199 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001200 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001201 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001202 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001203 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001204 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001205 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001206 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001207 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001208 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001209 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001210 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001211 return E;
1212 }
1213 llvm_unreachable("Unhandled type of aggregate value operation");
1214}
1215
Daniel Berline021d2d2017-05-19 20:22:20 +00001216const DeadExpression *NewGVN::createDeadExpression() const {
1217 // DeadExpression has no arguments and all DeadExpression's are the same,
1218 // so we only need one of them.
1219 return SingletonDeadExpression;
1220}
1221
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001222const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001223 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001224 E->setOpcode(V->getValueID());
1225 return E;
1226}
1227
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001228const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001229 if (auto *C = dyn_cast<Constant>(V))
1230 return createConstantExpression(C);
1231 return createVariableExpression(V);
1232}
1233
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001234const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001235 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +00001236 E->setOpcode(C->getValueID());
1237 return E;
1238}
1239
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001240const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001241 auto *E = new (ExpressionAllocator) UnknownExpression(I);
1242 E->setOpcode(I->getOpcode());
1243 return E;
1244}
1245
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001246const CallExpression *
1247NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001248 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001249 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +00001250 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +00001251 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001252 return E;
1253}
1254
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001255// Return true if some equivalent of instruction Inst dominates instruction U.
1256bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1257 const Instruction *U) const {
1258 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlin9b926e92017-09-30 23:51:53 +00001259 // This must be an instruction because we are only called from phi nodes
Daniel Berlinffc30782017-03-24 06:33:51 +00001260 // in the case that the value it needs to check against is an instruction.
1261
Hiroshi Inouef2096492018-06-14 05:41:49 +00001262 // The most likely candidates for dominance are the leader and the next leader.
Daniel Berlinffc30782017-03-24 06:33:51 +00001263 // The leader or nextleader will dominate in all cases where there is an
1264 // equivalent that is higher up in the dom tree.
1265 // We can't *only* check them, however, because the
1266 // dominator tree could have an infinite number of non-dominating siblings
1267 // with instructions that are in the right congruence class.
1268 // A
1269 // B C D E F G
1270 // |
1271 // H
1272 // Instruction U could be in H, with equivalents in every other sibling.
1273 // Depending on the rpo order picked, the leader could be the equivalent in
1274 // any of these siblings.
1275 if (!CC)
1276 return false;
Daniel Berlin9b926e92017-09-30 23:51:53 +00001277 if (alwaysAvailable(CC->getLeader()))
1278 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001279 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001280 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001281 if (CC->getNextLeader().first &&
1282 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001283 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001284 return llvm::any_of(*CC, [&](const Value *Member) {
1285 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001286 DT->dominates(cast<Instruction>(Member), U);
1287 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001288}
1289
Davide Italiano7e274e02016-12-22 16:03:48 +00001290// See if we have a congruence class and leader for this operand, and if so,
1291// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001292Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001293 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001294 if (CC) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001295 // Everything in TOP is represented by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001296 // We do have to make sure we get the type right though, so we can't set the
1297 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001298 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001299 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001300 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001301 }
1302
Davide Italiano7e274e02016-12-22 16:03:48 +00001303 return V;
1304}
1305
Daniel Berlin1316a942017-04-06 18:52:50 +00001306const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1307 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001308 assert(CC->getMemoryLeader() &&
Davide Italianob60f6e02017-05-12 15:25:56 +00001309 "Every MemoryAccess should be mapped to a congruence class with a "
1310 "representative memory access");
Daniel Berlina8236562017-04-07 18:38:09 +00001311 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001312}
1313
Daniel Berlinc4796862017-01-27 02:37:11 +00001314// Return true if the MemoryAccess is really equivalent to everything. This is
1315// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001316// state of all MemoryAccesses.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001317bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001318 return getMemoryClass(MA) == TOPClass;
1319}
1320
Davide Italiano7e274e02016-12-22 16:03:48 +00001321LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001322 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001323 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001324 auto *E =
1325 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001326 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1327 E->setType(LoadType);
1328
1329 // Give store and loads same opcode so they value number together.
1330 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001331 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001332 if (LI)
1333 E->setAlignment(LI->getAlignment());
1334
1335 // TODO: Value number heap versions. We may be able to discover
1336 // things alias analysis can't on it's own (IE that a store and a
1337 // load have the same value, and thus, it isn't clobbering the load).
1338 return E;
1339}
1340
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001341const StoreExpression *
1342NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001343 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001344 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001345 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001346 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1347 E->setType(SI->getValueOperand()->getType());
1348
1349 // Give store and loads same opcode so they value number together.
1350 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001351 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001352
1353 // TODO: Value number heap versions. We may be able to discover
1354 // things alias analysis can't on it's own (IE that a store and a
1355 // load have the same value, and thus, it isn't clobbering the load).
1356 return E;
1357}
1358
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001359const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001360 // Unlike loads, we never try to eliminate stores, so we do not check if they
1361 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001362 auto *SI = cast<StoreInst>(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001363 auto *StoreAccess = getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001364 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001365 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1366 if (EnableStoreRefinement)
1367 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1368 // If we bypassed the use-def chains, make sure we add a use.
Daniel Berlinde269f42017-08-26 07:37:11 +00001369 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlin1316a942017-04-06 18:52:50 +00001370 if (StoreRHS != StoreAccess->getDefiningAccess())
1371 addMemoryUsers(StoreRHS, StoreAccess);
Daniel Berlinc4796862017-01-27 02:37:11 +00001372 // If we are defined by ourselves, use the live on entry def.
1373 if (StoreRHS == StoreAccess)
1374 StoreRHS = MSSA->getLiveOnEntryDef();
1375
Daniel Berlin589cecc2017-01-02 18:00:46 +00001376 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001377 // See if we are defined by a previous store expression, it already has a
1378 // value, and it's the same value as our current store. FIXME: Right now, we
1379 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001380 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1381 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlin36b08b22017-06-19 00:24:00 +00001382 // We really want to check whether the expression we matched was a store. No
1383 // easy way to do that. However, we can check that the class we found has a
1384 // store, which, assuming the value numbering state is not corrupt, is
1385 // sufficient, because we must also be equivalent to that store's expression
1386 // for it to be in the same class as the load.
1387 if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
Daniel Berlin1316a942017-04-06 18:52:50 +00001388 return LastStore;
Daniel Berlinc4796862017-01-27 02:37:11 +00001389 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001390 // location, and the memory state is the same as it was then (otherwise, it
1391 // could have been overwritten later. See test32 in
1392 // transforms/DeadStoreElimination/simple.ll).
Daniel Berlin36b08b22017-06-19 00:24:00 +00001393 if (auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
Daniel Berlin203f47b2017-01-31 22:31:53 +00001394 if ((lookupOperandLeader(LI->getPointerOperand()) ==
Daniel Berlin36b08b22017-06-19 00:24:00 +00001395 LastStore->getOperand(0)) &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001396 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
Daniel Berlin1316a942017-04-06 18:52:50 +00001397 StoreRHS))
Daniel Berlin36b08b22017-06-19 00:24:00 +00001398 return LastStore;
1399 deleteExpression(LastStore);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001400 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001401
1402 // If the store is not equivalent to anything, value number it as a store that
1403 // produces a unique memory state (instead of using it's MemoryUse, we use
1404 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001405 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001406}
1407
Daniel Berlin07daac82017-04-02 13:23:44 +00001408// See if we can extract the value of a loaded pointer from a load, a store, or
1409// a memory instruction.
1410const Expression *
1411NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1412 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001413 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001414 assert((!LI || LI->isSimple()) && "Not a simple load");
1415 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1416 // Can't forward from non-atomic to atomic without violating memory model.
1417 // Also don't need to coerce if they are the same type, we will just
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001418 // propagate.
Daniel Berlin07daac82017-04-02 13:23:44 +00001419 if (LI->isAtomic() > DepSI->isAtomic() ||
1420 LoadType == DepSI->getValueOperand()->getType())
1421 return nullptr;
1422 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1423 if (Offset >= 0) {
1424 if (auto *C = dyn_cast<Constant>(
1425 lookupOperandLeader(DepSI->getValueOperand()))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001426 LLVM_DEBUG(dbgs() << "Coercing load from store " << *DepSI
1427 << " to constant " << *C << "\n");
Daniel Berlin07daac82017-04-02 13:23:44 +00001428 return createConstantExpression(
1429 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1430 }
1431 }
Davide Italiano9bdccb32017-08-26 22:31:10 +00001432 } else if (auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
Daniel Berlin07daac82017-04-02 13:23:44 +00001433 // Can't forward from non-atomic to atomic without violating memory model.
1434 if (LI->isAtomic() > DepLI->isAtomic())
1435 return nullptr;
1436 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1437 if (Offset >= 0) {
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001438 // We can coerce a constant load into a load.
Daniel Berlin07daac82017-04-02 13:23:44 +00001439 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1440 if (auto *PossibleConstant =
1441 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001442 LLVM_DEBUG(dbgs() << "Coercing load from load " << *LI
1443 << " to constant " << *PossibleConstant << "\n");
Daniel Berlin07daac82017-04-02 13:23:44 +00001444 return createConstantExpression(PossibleConstant);
1445 }
1446 }
Davide Italiano9bdccb32017-08-26 22:31:10 +00001447 } else if (auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
Daniel Berlin07daac82017-04-02 13:23:44 +00001448 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1449 if (Offset >= 0) {
1450 if (auto *PossibleConstant =
1451 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001452 LLVM_DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1453 << " to constant " << *PossibleConstant << "\n");
Daniel Berlin07daac82017-04-02 13:23:44 +00001454 return createConstantExpression(PossibleConstant);
1455 }
1456 }
1457 }
1458
1459 // All of the below are only true if the loaded pointer is produced
1460 // by the dependent instruction.
1461 if (LoadPtr != lookupOperandLeader(DepInst) &&
1462 !AA->isMustAlias(LoadPtr, DepInst))
1463 return nullptr;
1464 // If this load really doesn't depend on anything, then we must be loading an
1465 // undef value. This can happen when loading for a fresh allocation with no
1466 // intervening stores, for example. Note that this is only true in the case
1467 // that the result of the allocation is pointer equal to the load ptr.
1468 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1469 return createConstantExpression(UndefValue::get(LoadType));
1470 }
1471 // If this load occurs either right after a lifetime begin,
1472 // then the loaded value is undefined.
1473 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1474 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1475 return createConstantExpression(UndefValue::get(LoadType));
1476 }
1477 // If this load follows a calloc (which zero initializes memory),
1478 // then the loaded value is zero
1479 else if (isCallocLikeFn(DepInst, TLI)) {
1480 return createConstantExpression(Constant::getNullValue(LoadType));
1481 }
1482
1483 return nullptr;
1484}
1485
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001486const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001487 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001488
1489 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001490 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001491 if (!LI->isSimple())
1492 return nullptr;
1493
Daniel Berlin203f47b2017-01-31 22:31:53 +00001494 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001495 // Load of undef is undef.
1496 if (isa<UndefValue>(LoadAddressLeader))
1497 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001498 MemoryAccess *OriginalAccess = getMemoryAccess(I);
1499 MemoryAccess *DefiningAccess =
1500 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001501
1502 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1503 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1504 Instruction *DefiningInst = MD->getMemoryInst();
1505 // If the defining instruction is not reachable, replace with undef.
1506 if (!ReachableBlocks.count(DefiningInst->getParent()))
1507 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001508 // This will handle stores and memory insts. We only do if it the
1509 // defining access has a different type, or it is a pointer produced by
1510 // certain memory operations that cause the memory to have a fixed value
1511 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001512 if (const auto *CoercionResult =
1513 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1514 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001515 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001516 }
1517 }
1518
Daniel Berlin94090dd2017-09-02 02:18:44 +00001519 const auto *LE = createLoadExpression(LI->getType(), LoadAddressLeader, LI,
1520 DefiningAccess);
Daniel Berlinde269f42017-08-26 07:37:11 +00001521 // If our MemoryLeader is not our defining access, add a use to the
1522 // MemoryLeader, so that we get reprocessed when it changes.
1523 if (LE->getMemoryLeader() != DefiningAccess)
1524 addMemoryUsers(LE->getMemoryLeader(), OriginalAccess);
1525 return LE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001526}
1527
Daniel Berlinf7d95802017-02-18 23:06:50 +00001528const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001529NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001530 auto *PI = PredInfo->getPredicateInfoFor(I);
1531 if (!PI)
1532 return nullptr;
1533
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001534 LLVM_DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001535
1536 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1537 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001538 return nullptr;
1539
Daniel Berlinfccbda92017-02-22 22:20:58 +00001540 auto *CopyOf = I->getOperand(0);
1541 auto *Cond = PWC->Condition;
1542
Daniel Berlinf7d95802017-02-18 23:06:50 +00001543 // If this a copy of the condition, it must be either true or false depending
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001544 // on the predicate info type and edge.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001545 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001546 // We should not need to add predicate users because the predicate info is
1547 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001548 if (isa<PredicateAssume>(PI))
1549 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1550 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1551 if (PBranch->TrueEdge)
1552 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1553 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1554 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001555 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1556 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001557 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001558
Daniel Berlinf7d95802017-02-18 23:06:50 +00001559 // Not a copy of the condition, so see what the predicates tell us about this
1560 // value. First, though, we check to make sure the value is actually a copy
1561 // of one of the condition operands. It's possible, in certain cases, for it
1562 // to be a copy of a predicateinfo copy. In particular, if two branch
1563 // operations use the same condition, and one branch dominates the other, we
1564 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001565 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001566 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001567
1568 // Everything below relies on the condition being a comparison.
1569 auto *Cmp = dyn_cast<CmpInst>(Cond);
1570 if (!Cmp)
1571 return nullptr;
1572
1573 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001574 LLVM_DEBUG(dbgs() << "Copy is not of any condition operands!\n");
Daniel Berlinf7d95802017-02-18 23:06:50 +00001575 return nullptr;
1576 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001577 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1578 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001579 bool SwappedOps = false;
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001580 // Sort the ops.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001581 if (shouldSwapOperands(FirstOp, SecondOp)) {
1582 std::swap(FirstOp, SecondOp);
1583 SwappedOps = true;
1584 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001585 CmpInst::Predicate Predicate =
1586 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1587
1588 if (isa<PredicateAssume>(PI)) {
Florian Hahna6e63f12018-05-22 17:38:22 +00001589 // If we assume the operands are equal, then they are equal.
1590 if (Predicate == CmpInst::ICMP_EQ) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001591 addPredicateUsers(PI, I);
Florian Hahna6e63f12018-05-22 17:38:22 +00001592 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1593 I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001594 return createVariableOrConstant(FirstOp);
1595 }
1596 }
1597 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1598 // If we are *not* a copy of the comparison, we may equal to the other
1599 // operand when the predicate implies something about equality of
1600 // operations. In particular, if the comparison is true/false when the
1601 // operands are equal, and we are on the right edge, we know this operation
1602 // is equal to something.
1603 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1604 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1605 addPredicateUsers(PI, I);
Daniel Berlin23fec572017-08-30 19:53:23 +00001606 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1607 I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001608 return createVariableOrConstant(FirstOp);
1609 }
1610 // Handle the special case of floating point.
1611 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1612 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1613 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1614 addPredicateUsers(PI, I);
Daniel Berlin23fec572017-08-30 19:53:23 +00001615 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1616 I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001617 return createConstantExpression(cast<Constant>(FirstOp));
1618 }
1619 }
1620 return nullptr;
1621}
1622
Davide Italiano7e274e02016-12-22 16:03:48 +00001623// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001624const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001625 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001626 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
Hiroshi Inouef2096492018-06-14 05:41:49 +00001627 // Intrinsics with the returned attribute are copies of arguments.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001628 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1629 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1630 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1631 return Result;
1632 return createVariableOrConstant(ReturnedValue);
1633 }
1634 }
1635 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001636 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001637 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001638 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001639 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001640 }
1641 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001642}
1643
Daniel Berlin1316a942017-04-06 18:52:50 +00001644// Retrieve the memory class for a given MemoryAccess.
1645CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001646 auto *Result = MemoryAccessToClass.lookup(MA);
1647 assert(Result && "Should have found memory class");
1648 return Result;
1649}
1650
1651// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001652// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001653bool NewGVN::setMemoryClass(const MemoryAccess *From,
1654 CongruenceClass *NewClass) {
1655 assert(NewClass &&
1656 "Every MemoryAccess should be getting mapped to a non-null class");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001657 LLVM_DEBUG(dbgs() << "Setting " << *From);
1658 LLVM_DEBUG(dbgs() << " equivalent to congruence class ");
1659 LLVM_DEBUG(dbgs() << NewClass->getID()
1660 << " with current MemoryAccess leader ");
1661 LLVM_DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001662
1663 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001664 bool Changed = false;
1665 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001666 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001667 auto *OldClass = LookupResult->second;
1668 if (OldClass != NewClass) {
1669 // If this is a phi, we have to handle memory member updates.
1670 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001671 OldClass->memory_erase(MP);
1672 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001673 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001674 if (OldClass->getMemoryLeader() == From) {
Davide Italiano41f5c7b2017-05-12 15:22:45 +00001675 if (OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001676 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001677 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001678 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001679 LLVM_DEBUG(dbgs() << "Memory class leader change for class "
1680 << OldClass->getID() << " to "
1681 << *OldClass->getMemoryLeader()
1682 << " due to removal of a memory member " << *From
1683 << "\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00001684 markMemoryLeaderChangeTouched(OldClass);
1685 }
1686 }
1687 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001688 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001689 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001690 Changed = true;
1691 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001692 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001693
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001694 return Changed;
1695}
Daniel Berlin0e900112017-03-24 06:33:48 +00001696
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001697// Determine if a instruction is cycle-free. That means the values in the
1698// instruction don't depend on any expressions that can change value as a result
1699// of the instruction. For example, a non-cycle free instruction would be v =
1700// phi(0, v+1).
1701bool NewGVN::isCycleFree(const Instruction *I) const {
1702 // In order to compute cycle-freeness, we do SCC finding on the instruction,
1703 // and see what kind of SCC it ends up in. If it is a singleton, it is
1704 // cycle-free. If it is not in a singleton, it is only cycle free if the
1705 // other members are all phi nodes (as they do not compute anything, they are
1706 // copies).
1707 auto ICS = InstCycleState.lookup(I);
1708 if (ICS == ICS_Unknown) {
1709 SCCFinder.Start(I);
1710 auto &SCC = SCCFinder.getComponentFor(I);
Hiroshi Inouebcadfee2018-04-12 05:53:20 +00001711 // It's cycle free if it's size 1 or the SCC is *only* phi nodes.
Daniel Berlin2f72b192017-04-14 02:53:37 +00001712 if (SCC.size() == 1)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001713 InstCycleState.insert({I, ICS_CycleFree});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001714 else {
Daniel Berlinf9c94552017-09-05 02:17:43 +00001715 bool AllPhis = llvm::all_of(SCC, [](const Value *V) {
1716 return isa<PHINode>(V) || isCopyOfAPHI(V);
1717 });
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001718 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
Daniel Berlin2f72b192017-04-14 02:53:37 +00001719 for (auto *Member : SCC)
1720 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001721 InstCycleState.insert({MemberPhi, ICS});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001722 }
1723 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001724 if (ICS == ICS_Cycle)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001725 return false;
1726 return true;
1727}
1728
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001729// Evaluate PHI nodes symbolically and create an expression result.
Daniel Berlinc1305af2017-09-30 23:51:54 +00001730const Expression *
1731NewGVN::performSymbolicPHIEvaluation(ArrayRef<ValPair> PHIOps,
1732 Instruction *I,
1733 BasicBlock *PHIBlock) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001734 // True if one of the incoming phi edges is a backedge.
1735 bool HasBackedge = false;
1736 // All constant tracks the state of whether all the *original* phi operands
Daniel Berline021d2d2017-05-19 20:22:20 +00001737 // This is really shorthand for "this phi cannot cycle due to forward
1738 // change in value of the phi is guaranteed not to later change the value of
1739 // the phi. IE it can't be v = phi(undef, v+1)
Daniel Berlinf9c94552017-09-05 02:17:43 +00001740 bool OriginalOpsConstant = true;
Daniel Berlinc1305af2017-09-30 23:51:54 +00001741 auto *E = cast<PHIExpression>(createPHIExpression(
1742 PHIOps, I, PHIBlock, HasBackedge, OriginalOpsConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001743 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001744 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001745 // We track if any were undef because they need special handling.
1746 bool HasUndef = false;
Daniel Berline021d2d2017-05-19 20:22:20 +00001747 auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
Daniel Berlind92e7f92017-01-07 00:01:42 +00001748 if (isa<UndefValue>(Arg)) {
1749 HasUndef = true;
1750 return false;
1751 }
1752 return true;
1753 });
Daniel Berline021d2d2017-05-19 20:22:20 +00001754 // If we are left with no operands, it's dead.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001755 if (Filtered.begin() == Filtered.end()) {
Daniel Berline67c3222017-05-25 15:44:20 +00001756 // If it has undef at this point, it means there are no-non-undef arguments,
1757 // and thus, the value of the phi node must be undef.
1758 if (HasUndef) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001759 LLVM_DEBUG(
1760 dbgs() << "PHI Node " << *I
1761 << " has no non-undef arguments, valuing it as undef\n");
Daniel Berline67c3222017-05-25 15:44:20 +00001762 return createConstantExpression(UndefValue::get(I->getType()));
1763 }
1764
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001765 LLVM_DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001766 deleteExpression(E);
Daniel Berline021d2d2017-05-19 20:22:20 +00001767 return createDeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00001768 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001769 Value *AllSameValue = *(Filtered.begin());
1770 ++Filtered.begin();
1771 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berlinf9c94552017-09-05 02:17:43 +00001772 if (llvm::all_of(Filtered, [&](Value *Arg) { return Arg == AllSameValue; })) {
Daniel Berlind92e7f92017-01-07 00:01:42 +00001773 // In LLVM's non-standard representation of phi nodes, it's possible to have
1774 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1775 // on the original phi node), especially in weird CFG's where some arguments
1776 // are unreachable, or uninitialized along certain paths. This can cause
1777 // infinite loops during evaluation. We work around this by not trying to
1778 // really evaluate them independently, but instead using a variable
1779 // expression to say if one is equivalent to the other.
1780 // We also special case undef, so that if we have an undef, we can't use the
1781 // common value unless it dominates the phi block.
1782 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001783 // If we have undef and at least one other value, this is really a
1784 // multivalued phi, and we need to know if it's cycle free in order to
1785 // evaluate whether we can ignore the undef. The other parts of this are
1786 // just shortcuts. If there is no backedge, or all operands are
Daniel Berlinf9c94552017-09-05 02:17:43 +00001787 // constants, it also must be cycle free.
1788 if (HasBackedge && !OriginalOpsConstant &&
Daniel Berline67c3222017-05-25 15:44:20 +00001789 !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
Daniel Berlin2f72b192017-04-14 02:53:37 +00001790 return E;
1791
Daniel Berlind92e7f92017-01-07 00:01:42 +00001792 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001793 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001794 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001795 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001796 }
Daniel Berlineafdd862017-06-06 17:15:28 +00001797 // Can't simplify to something that comes later in the iteration.
1798 // Otherwise, when and if it changes congruence class, we will never catch
1799 // up. We will always be a class behind it.
1800 if (isa<Instruction>(AllSameValue) &&
1801 InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
1802 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001803 NumGVNPhisAllSame++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001804 LLVM_DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1805 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001806 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001807 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001808 }
1809 return E;
1810}
1811
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001812const Expression *
1813NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001814 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1815 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1816 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1817 unsigned Opcode = 0;
1818 // EI might be an extract from one of our recognised intrinsics. If it
1819 // is we'll synthesize a semantically equivalent expression instead on
1820 // an extract value expression.
1821 switch (II->getIntrinsicID()) {
1822 case Intrinsic::sadd_with_overflow:
1823 case Intrinsic::uadd_with_overflow:
1824 Opcode = Instruction::Add;
1825 break;
1826 case Intrinsic::ssub_with_overflow:
1827 case Intrinsic::usub_with_overflow:
1828 Opcode = Instruction::Sub;
1829 break;
1830 case Intrinsic::smul_with_overflow:
1831 case Intrinsic::umul_with_overflow:
1832 Opcode = Instruction::Mul;
1833 break;
1834 default:
1835 break;
1836 }
1837
1838 if (Opcode != 0) {
1839 // Intrinsic recognized. Grab its args to finish building the
1840 // expression.
1841 assert(II->getNumArgOperands() == 2 &&
1842 "Expect two args for recognised intrinsics.");
Daniel Berlin54a92fc2017-09-05 02:17:42 +00001843 return createBinaryExpression(Opcode, EI->getType(),
1844 II->getArgOperand(0),
1845 II->getArgOperand(1), I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001846 }
1847 }
1848 }
1849
Daniel Berlin97718e62017-01-31 22:32:03 +00001850 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001851}
Eugene Zelenko99241d72017-10-20 21:47:29 +00001852
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001853const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Chad Rosier4d852592017-08-08 18:41:49 +00001854 assert(isa<CmpInst>(I) && "Expected a cmp instruction.");
1855
1856 auto *CI = cast<CmpInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001857 // See if our operands are equal to those of a previous predicate, and if so,
1858 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001859 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1860 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001861 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001862 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001863 std::swap(Op0, Op1);
1864 OurPredicate = CI->getSwappedPredicate();
1865 }
1866
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001867 // Avoid processing the same info twice.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001868 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001869 // See if we know something about the comparison itself, like it is the target
1870 // of an assume.
1871 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1872 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1873 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1874
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001875 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001876 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001877 if (CI->isTrueWhenEqual())
1878 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1879 else if (CI->isFalseWhenEqual())
1880 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1881 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001882
1883 // NOTE: Because we are comparing both operands here and below, and using
1884 // previous comparisons, we rely on fact that predicateinfo knows to mark
1885 // comparisons that use renamed operands as users of the earlier comparisons.
1886 // It is *not* enough to just mark predicateinfo renamed operands as users of
1887 // the earlier comparisons, because the *other* operand may have changed in a
1888 // previous iteration.
1889 // Example:
1890 // icmp slt %a, %b
1891 // %b.0 = ssa.copy(%b)
1892 // false branch:
1893 // icmp slt %c, %b.0
1894
1895 // %c and %a may start out equal, and thus, the code below will say the second
1896 // %icmp is false. c may become equal to something else, and in that case the
1897 // %second icmp *must* be reexamined, but would not if only the renamed
1898 // %operands are considered users of the icmp.
1899
1900 // *Currently* we only check one level of comparisons back, and only mark one
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001901 // level back as touched when changes happen. If you modify this code to look
Daniel Berlinf7d95802017-02-18 23:06:50 +00001902 // back farther through comparisons, you *must* mark the appropriate
1903 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1904 // we know something just from the operands themselves
1905
1906 // See if our operands have predicate info, so that we may be able to derive
1907 // something from a previous comparison.
1908 for (const auto &Op : CI->operands()) {
1909 auto *PI = PredInfo->getPredicateInfoFor(Op);
1910 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1911 if (PI == LastPredInfo)
1912 continue;
1913 LastPredInfo = PI;
Daniel Berlin86932102017-09-01 19:20:18 +00001914 // In phi of ops cases, we may have predicate info that we are evaluating
1915 // in a different context.
1916 if (!DT->dominates(PBranch->To, getBlockForValue(I)))
1917 continue;
1918 // TODO: Along the false edge, we may know more things too, like
1919 // icmp of
Daniel Berlinf7d95802017-02-18 23:06:50 +00001920 // same operands is false.
Daniel Berlin86932102017-09-01 19:20:18 +00001921 // TODO: We only handle actual comparison conditions below, not
1922 // and/or.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001923 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1924 if (!BranchCond)
1925 continue;
1926 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1927 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1928 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001929 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001930 std::swap(BranchOp0, BranchOp1);
1931 BranchPredicate = BranchCond->getSwappedPredicate();
1932 }
1933 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1934 if (PBranch->TrueEdge) {
1935 // If we know the previous predicate is true and we are in the true
1936 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001937 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1938 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001939 addPredicateUsers(PI, I);
1940 return createConstantExpression(
1941 ConstantInt::getTrue(CI->getType()));
1942 }
1943
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001944 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1945 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001946 addPredicateUsers(PI, I);
1947 return createConstantExpression(
1948 ConstantInt::getFalse(CI->getType()));
1949 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001950 } else {
1951 // Just handle the ne and eq cases, where if we have the same
1952 // operands, we may know something.
1953 if (BranchPredicate == OurPredicate) {
1954 addPredicateUsers(PI, I);
1955 // Same predicate, same ops,we know it was false, so this is false.
1956 return createConstantExpression(
1957 ConstantInt::getFalse(CI->getType()));
1958 } else if (BranchPredicate ==
1959 CmpInst::getInversePredicate(OurPredicate)) {
1960 addPredicateUsers(PI, I);
1961 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001962 return createConstantExpression(
1963 ConstantInt::getTrue(CI->getType()));
1964 }
1965 }
1966 }
1967 }
1968 }
1969 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001970 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001971}
Davide Italiano7e274e02016-12-22 16:03:48 +00001972
1973// Substitute and symbolize the value before value numbering.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001974const Expression *
1975NewGVN::performSymbolicEvaluation(Value *V,
1976 SmallPtrSetImpl<Value *> &Visited) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001977 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001978 if (auto *C = dyn_cast<Constant>(V))
1979 E = createConstantExpression(C);
1980 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1981 E = createVariableExpression(V);
1982 } else {
1983 // TODO: memory intrinsics.
1984 // TODO: Some day, we should do the forward propagation and reassociation
1985 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001986 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001987 switch (I->getOpcode()) {
1988 case Instruction::ExtractValue:
1989 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001990 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001991 break;
Daniel Berlinc1305af2017-09-30 23:51:54 +00001992 case Instruction::PHI: {
1993 SmallVector<ValPair, 3> Ops;
1994 auto *PN = cast<PHINode>(I);
1995 for (unsigned i = 0; i < PN->getNumOperands(); ++i)
1996 Ops.push_back({PN->getIncomingValue(i), PN->getIncomingBlock(i)});
1997 // Sort to ensure the invariant createPHIExpression requires is met.
1998 sortPHIOps(Ops);
1999 E = performSymbolicPHIEvaluation(Ops, I, getBlockForValue(I));
2000 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00002001 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00002002 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002003 break;
2004 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00002005 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002006 break;
2007 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00002008 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002009 break;
Fangrui Songf78650a2018-07-30 19:41:25 +00002010 case Instruction::BitCast:
Daniel Berlin97718e62017-01-31 22:32:03 +00002011 E = createExpression(I);
Eugene Zelenko99241d72017-10-20 21:47:29 +00002012 break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00002013 case Instruction::ICmp:
Eugene Zelenko99241d72017-10-20 21:47:29 +00002014 case Instruction::FCmp:
Daniel Berlin97718e62017-01-31 22:32:03 +00002015 E = performSymbolicCmpEvaluation(I);
Eugene Zelenko99241d72017-10-20 21:47:29 +00002016 break;
Davide Italiano7e274e02016-12-22 16:03:48 +00002017 case Instruction::Add:
2018 case Instruction::FAdd:
2019 case Instruction::Sub:
2020 case Instruction::FSub:
2021 case Instruction::Mul:
2022 case Instruction::FMul:
2023 case Instruction::UDiv:
2024 case Instruction::SDiv:
2025 case Instruction::FDiv:
2026 case Instruction::URem:
2027 case Instruction::SRem:
2028 case Instruction::FRem:
2029 case Instruction::Shl:
2030 case Instruction::LShr:
2031 case Instruction::AShr:
2032 case Instruction::And:
2033 case Instruction::Or:
2034 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00002035 case Instruction::Trunc:
2036 case Instruction::ZExt:
2037 case Instruction::SExt:
2038 case Instruction::FPToUI:
2039 case Instruction::FPToSI:
2040 case Instruction::UIToFP:
2041 case Instruction::SIToFP:
2042 case Instruction::FPTrunc:
2043 case Instruction::FPExt:
2044 case Instruction::PtrToInt:
2045 case Instruction::IntToPtr:
2046 case Instruction::Select:
2047 case Instruction::ExtractElement:
2048 case Instruction::InsertElement:
2049 case Instruction::ShuffleVector:
2050 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00002051 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002052 break;
2053 default:
2054 return nullptr;
2055 }
2056 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002057 return E;
2058}
2059
Daniel Berlin0207cca2017-05-21 23:41:56 +00002060// Look up a container in a map, and then call a function for each thing in the
2061// found container.
2062template <typename Map, typename KeyType, typename Func>
2063void NewGVN::for_each_found(Map &M, const KeyType &Key, Func F) {
2064 const auto Result = M.find_as(Key);
2065 if (Result != M.end())
2066 for (typename Map::mapped_type::value_type Mapped : Result->second)
2067 F(Mapped);
2068}
2069
2070// Look up a container of values/instructions in a map, and touch all the
2071// instructions in the container. Then erase value from the map.
2072template <typename Map, typename KeyType>
2073void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
2074 const auto Result = M.find_as(Key);
2075 if (Result != M.end()) {
2076 for (const typename Map::mapped_type::value_type Mapped : Result->second)
2077 TouchedInstructions.set(InstrToDFSNum(Mapped));
2078 M.erase(Result);
2079 }
2080}
2081
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002082void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
Daniel Berlin54a92fc2017-09-05 02:17:42 +00002083 assert(User && To != User);
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002084 if (isa<Instruction>(To))
2085 AdditionalUsers[To].insert(User);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002086}
2087
Davide Italiano7e274e02016-12-22 16:03:48 +00002088void NewGVN::markUsersTouched(Value *V) {
2089 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002090 for (auto *User : V->users()) {
2091 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00002092 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00002093 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00002094 touchAndErase(AdditionalUsers, V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002095}
2096
Daniel Berlin6604a2f2017-05-09 16:40:04 +00002097void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002098 LLVM_DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002099 MemoryToUsers[To].insert(U);
2100}
2101
2102void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002103 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00002104}
2105
2106void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
2107 if (isa<MemoryUse>(MA))
2108 return;
2109 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00002110 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin0207cca2017-05-21 23:41:56 +00002111 touchAndErase(MemoryToUsers, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00002112}
2113
Daniel Berlinf7d95802017-02-18 23:06:50 +00002114// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00002115void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002116 // Don't add temporary instructions to the user lists.
2117 if (AllTempInstructions.count(I))
2118 return;
2119
Daniel Berlinf7d95802017-02-18 23:06:50 +00002120 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
2121 PredicateToUsers[PBranch->Condition].insert(I);
2122 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
2123 PredicateToUsers[PAssume->Condition].insert(I);
2124}
2125
2126// Touch all the predicates that depend on this instruction.
2127void NewGVN::markPredicateUsersTouched(Instruction *I) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00002128 touchAndErase(PredicateToUsers, I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002129}
2130
Daniel Berlin1316a942017-04-06 18:52:50 +00002131// Mark users affected by a memory leader change.
2132void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00002133 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002134 markMemoryDefTouched(M);
2135}
2136
Daniel Berlin32f8d562017-01-07 16:55:14 +00002137// Touch the instructions that need to be updated after a congruence class has a
2138// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00002139void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00002140 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00002141 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002142 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002143 LeaderChanges.insert(M);
2144 }
2145}
2146
Daniel Berlin1316a942017-04-06 18:52:50 +00002147// Give a range of things that have instruction DFS numbers, this will return
2148// the member of the range with the smallest dfs number.
2149template <class T, class Range>
2150T *NewGVN::getMinDFSOfRange(const Range &R) const {
2151 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
2152 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002153 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00002154 if (DFSNum < MinDFS.second)
2155 MinDFS = {X, DFSNum};
2156 }
2157 return MinDFS.first;
2158}
2159
2160// This function returns the MemoryAccess that should be the next leader of
2161// congruence class CC, under the assumption that the current leader is going to
2162// disappear.
2163const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2164 // TODO: If this ends up to slow, we can maintain a next memory leader like we
2165 // do for regular leaders.
Daniel Berlinde269f42017-08-26 07:37:11 +00002166 // Make sure there will be a leader to find.
Davide Italianodc435322017-05-10 19:57:43 +00002167 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00002168 if (CC->getStoreCount() > 0) {
2169 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002170 return getMemoryAccess(NL);
Daniel Berlin1316a942017-04-06 18:52:50 +00002171 // Find the store with the minimum DFS number.
2172 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00002173 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002174 return getMemoryAccess(cast<StoreInst>(V));
Daniel Berlin1316a942017-04-06 18:52:50 +00002175 }
Daniel Berlina8236562017-04-07 18:38:09 +00002176 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00002177
2178 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00002179 // !OldClass->memory_empty()
2180 if (CC->memory_size() == 1)
2181 return *CC->memory_begin();
2182 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00002183}
2184
2185// This function returns the next value leader of a congruence class, under the
2186// assumption that the current leader is going away. This should end up being
2187// the next most dominating member.
2188Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2189 // We don't need to sort members if there is only 1, and we don't care about
2190 // sorting the TOP class because everything either gets out of it or is
2191 // unreachable.
2192
Daniel Berlina8236562017-04-07 18:38:09 +00002193 if (CC->size() == 1 || CC == TOPClass) {
2194 return *(CC->begin());
2195 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002196 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00002197 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00002198 } else {
2199 ++NumGVNSortedLeaderChanges;
2200 // NOTE: If this ends up to slow, we can maintain a dual structure for
2201 // member testing/insertion, or keep things mostly sorted, and sort only
2202 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00002203 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00002204 }
2205}
2206
2207// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2208// the memory members, etc for the move.
2209//
2210// The invariants of this function are:
2211//
Davide Italianofb4544c2017-07-11 19:15:36 +00002212// - I must be moving to NewClass from OldClass
2213// - The StoreCount of OldClass and NewClass is expected to have been updated
Hiroshi Inoue9ff23802018-04-09 04:37:53 +00002214// for I already if it is a store.
Davide Italianofb4544c2017-07-11 19:15:36 +00002215// - The OldClass memory leader has not been updated yet if I was the leader.
Daniel Berlin1316a942017-04-06 18:52:50 +00002216void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2217 MemoryAccess *InstMA,
2218 CongruenceClass *OldClass,
2219 CongruenceClass *NewClass) {
Hiroshi Inouef2096492018-06-14 05:41:49 +00002220 // If the leader is I, and we had a representative MemoryAccess, it should
Daniel Berlin1316a942017-04-06 18:52:50 +00002221 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00002222 assert((!InstMA || !OldClass->getMemoryLeader() ||
2223 OldClass->getLeader() != I ||
Davide Italianoee1c8212017-07-11 19:49:12 +00002224 MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
2225 MemoryAccessToClass.lookup(InstMA)) &&
Davide Italianof58a30232017-04-10 23:08:35 +00002226 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00002227 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00002228 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002229 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00002230 assert(NewClass->size() == 1 ||
2231 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2232 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00002233 // Mark it touched if we didn't just create a singleton
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002234 LLVM_DEBUG(dbgs() << "Memory class leader change for class "
2235 << NewClass->getID()
2236 << " due to new memory instruction becoming leader\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002237 markMemoryLeaderChangeTouched(NewClass);
2238 }
2239 setMemoryClass(InstMA, NewClass);
2240 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00002241 if (OldClass->getMemoryLeader() == InstMA) {
Davide Italianodc435322017-05-10 19:57:43 +00002242 if (!OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00002243 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002244 LLVM_DEBUG(dbgs() << "Memory class leader change for class "
2245 << OldClass->getID() << " to "
2246 << *OldClass->getMemoryLeader()
2247 << " due to removal of old leader " << *InstMA << "\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002248 markMemoryLeaderChangeTouched(OldClass);
2249 } else
Daniel Berlina8236562017-04-07 18:38:09 +00002250 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00002251 }
2252}
2253
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002254// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00002255// Update OldClass and NewClass for the move (including changing leaders, etc).
2256void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002257 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002258 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00002259 if (I == OldClass->getNextLeader().first)
2260 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002261
Daniel Berlinff152002017-05-19 19:01:24 +00002262 OldClass->erase(I);
2263 NewClass->insert(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002264
Daniel Berlina8236562017-04-07 18:38:09 +00002265 if (NewClass->getLeader() != I)
2266 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlin1316a942017-04-06 18:52:50 +00002267 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002268 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002269 OldClass->decStoreCount();
2270 // Okay, so when do we want to make a store a leader of a class?
2271 // If we have a store defined by an earlier load, we want the earlier load
2272 // to lead the class.
2273 // If we have a store defined by something else, we want the store to lead
2274 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00002275 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00002276 // as the leader
2277 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002278 // If it's a store expression we are using, it means we are not equivalent
2279 // to something earlier.
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002280 if (auto *SE = dyn_cast<StoreExpression>(E)) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002281 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1316a942017-04-06 18:52:50 +00002282 markValueLeaderChangeTouched(NewClass);
2283 // Shift the new class leader to be the store
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002284 LLVM_DEBUG(dbgs() << "Changing leader of congruence class "
2285 << NewClass->getID() << " from "
2286 << *NewClass->getLeader() << " to " << *SI
2287 << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002288 // If we changed the leader, we have to mark it changed because we don't
Davide Italiano67b0e532017-07-11 19:19:45 +00002289 // know what it will do to symbolic evaluation.
Daniel Berlina8236562017-04-07 18:38:09 +00002290 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002291 }
2292 // We rely on the code below handling the MemoryAccess change.
2293 }
Daniel Berlina8236562017-04-07 18:38:09 +00002294 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002295 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002296 // True if there is no memory instructions left in a class that had memory
2297 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002298
Daniel Berlin1316a942017-04-06 18:52:50 +00002299 // If it's not a memory use, set the MemoryAccess equivalence
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002300 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
Daniel Berlin1316a942017-04-06 18:52:50 +00002301 if (InstMA)
2302 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002303 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002304 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002305 if (OldClass->empty() && OldClass != TOPClass) {
2306 if (OldClass->getDefiningExpr()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002307 LLVM_DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
2308 << " from table\n");
Daniel Berlineafdd862017-06-06 17:15:28 +00002309 // We erase it as an exact expression to make sure we don't just erase an
2310 // equivalent one.
2311 auto Iter = ExpressionToClass.find_as(
2312 ExactEqualsExpression(*OldClass->getDefiningExpr()));
2313 if (Iter != ExpressionToClass.end())
2314 ExpressionToClass.erase(Iter);
2315#ifdef EXPENSIVE_CHECKS
2316 assert(
2317 (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2318 "We erased the expression we just inserted, which should not happen");
2319#endif
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002320 }
Daniel Berlina8236562017-04-07 18:38:09 +00002321 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002322 // When the leader changes, the value numbering of
2323 // everything may change due to symbolization changes, so we need to
2324 // reprocess.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002325 LLVM_DEBUG(dbgs() << "Value class leader change for class "
2326 << OldClass->getID() << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002327 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002328 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002329 // Note that this is basically clean up for the expression removal that
2330 // happens below. If we remove stores from a class, we may leave it as a
2331 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002332 if (OldClass->getStoreCount() == 0) {
2333 if (OldClass->getStoredValue())
2334 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002335 }
Daniel Berlina8236562017-04-07 18:38:09 +00002336 OldClass->setLeader(getNextValueLeader(OldClass));
2337 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002338 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002339 }
2340}
2341
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002342// For a given expression, mark the phi of ops instructions that could have
2343// changed as a result.
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002344void NewGVN::markPhiOfOpsChanged(const Expression *E) {
Daniel Berlind36c27b2017-09-30 23:51:55 +00002345 touchAndErase(ExpressionToPhiOfOps, E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002346}
Daniel Berlin0207cca2017-05-21 23:41:56 +00002347
Davide Italiano7e274e02016-12-22 16:03:48 +00002348// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002349void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002350 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002351 // TOP.
Daniel Berline021d2d2017-05-19 20:22:20 +00002352
2353 CongruenceClass *IClass = ValueToClass.lookup(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002354 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002355 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002356 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002357
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002358 CongruenceClass *EClass = nullptr;
Daniel Berlin02c6b172017-01-02 18:00:53 +00002359 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002360 EClass = ValueToClass.lookup(VE->getVariableValue());
Daniel Berline021d2d2017-05-19 20:22:20 +00002361 } else if (isa<DeadExpression>(E)) {
2362 EClass = TOPClass;
2363 }
2364 if (!EClass) {
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002365 auto lookupResult = ExpressionToClass.insert({E, nullptr});
Davide Italiano7e274e02016-12-22 16:03:48 +00002366
2367 // If it's not in the value table, create a new congruence class.
2368 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002369 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002370 auto place = lookupResult.first;
2371 place->second = NewClass;
2372
2373 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002374 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002375 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002376 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2377 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002378 NewClass->setLeader(SI);
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002379 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002380 // The RepMemoryAccess field will be filled in properly by the
2381 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002382 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002383 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002384 }
2385 assert(!isa<VariableExpression>(E) &&
2386 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002387
2388 EClass = NewClass;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002389 LLVM_DEBUG(dbgs() << "Created new congruence class for " << *I
2390 << " using expression " << *E << " at "
2391 << NewClass->getID() << " and leader "
2392 << *(NewClass->getLeader()));
Daniel Berlina8236562017-04-07 18:38:09 +00002393 if (NewClass->getStoredValue())
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002394 LLVM_DEBUG(dbgs() << " and stored value "
2395 << *(NewClass->getStoredValue()));
2396 LLVM_DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002397 } else {
2398 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002399 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002400 assert((isa<Constant>(EClass->getLeader()) ||
2401 (EClass->getStoredValue() &&
2402 isa<Constant>(EClass->getStoredValue()))) &&
2403 "Any class with a constant expression should have a "
2404 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002405
Davide Italiano7e274e02016-12-22 16:03:48 +00002406 assert(EClass && "Somehow don't have an eclass");
2407
Daniel Berlin1316a942017-04-06 18:52:50 +00002408 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002409 }
2410 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002411 bool ClassChanged = IClass != EClass;
2412 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002413 if (ClassChanged || LeaderChanged) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002414 LLVM_DEBUG(dbgs() << "New class " << EClass->getID() << " for expression "
2415 << *E << "\n");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002416 if (ClassChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002417 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002418 markPhiOfOpsChanged(E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002419 }
2420
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002421 markUsersTouched(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002422 if (MemoryAccess *MA = getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002423 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002424 if (auto *CI = dyn_cast<CmpInst>(I))
2425 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002426 }
Daniel Berlin45403572017-05-16 19:58:47 +00002427 // If we changed the class of the store, we want to ensure nothing finds the
2428 // old store expression. In particular, loads do not compare against stored
2429 // value, so they will find old store expressions (and associated class
2430 // mappings) if we leave them in the table.
Davide Italianoee49f492017-05-19 04:06:10 +00002431 if (ClassChanged && isa<StoreInst>(I)) {
Daniel Berlin45403572017-05-16 19:58:47 +00002432 auto *OldE = ValueToExpression.lookup(I);
2433 // It could just be that the old class died. We don't want to erase it if we
2434 // just moved classes.
Daniel Berlineafdd862017-06-06 17:15:28 +00002435 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
2436 // Erase this as an exact expression to ensure we don't erase expressions
2437 // equivalent to it.
2438 auto Iter = ExpressionToClass.find_as(ExactEqualsExpression(*OldE));
2439 if (Iter != ExpressionToClass.end())
2440 ExpressionToClass.erase(Iter);
2441 }
Daniel Berlin45403572017-05-16 19:58:47 +00002442 }
2443 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002444}
2445
2446// Process the fact that Edge (from, to) is reachable, including marking
2447// any newly reachable blocks and instructions for processing.
2448void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2449 // Check if the Edge was reachable before.
2450 if (ReachableEdges.insert({From, To}).second) {
2451 // If this block wasn't reachable before, all instructions are touched.
2452 if (ReachableBlocks.insert(To).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002453 LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
2454 << " marked reachable\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002455 const auto &InstRange = BlockInstRange.lookup(To);
2456 TouchedInstructions.set(InstRange.first, InstRange.second);
2457 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002458 LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
2459 << " was reachable, but new edge {"
2460 << getBlockName(From) << "," << getBlockName(To)
2461 << "} to it found\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002462
2463 // We've made an edge reachable to an existing block, which may
2464 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2465 // they are the only thing that depend on new edges. Anything using their
2466 // values will get propagated to if necessary.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002467 if (MemoryAccess *MemPhi = getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002468 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002469
Daniel Berlin9b926e92017-09-30 23:51:53 +00002470 // FIXME: We should just add a union op on a Bitvector and
2471 // SparseBitVector. We can do it word by word faster than we are doing it
2472 // here.
2473 for (auto InstNum : RevisitOnReachabilityChange[To])
2474 TouchedInstructions.set(InstNum);
Davide Italiano7e274e02016-12-22 16:03:48 +00002475 }
2476 }
2477}
2478
2479// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2480// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002481Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002482 auto Result = lookupOperandLeader(Cond);
Davide Italianodaa9c0e2017-06-19 16:46:15 +00002483 return isa<Constant>(Result) ? Result : nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002484}
2485
2486// Process the outgoing edges of a block for reachability.
2487void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2488 // Evaluate reachability of terminator instruction.
2489 BranchInst *BR;
2490 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2491 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002492 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002493 if (!CondEvaluated) {
2494 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002495 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002496 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2497 CondEvaluated = CE->getConstantValue();
2498 }
2499 } else if (isa<ConstantInt>(Cond)) {
2500 CondEvaluated = Cond;
2501 }
2502 }
2503 ConstantInt *CI;
2504 BasicBlock *TrueSucc = BR->getSuccessor(0);
2505 BasicBlock *FalseSucc = BR->getSuccessor(1);
2506 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2507 if (CI->isOne()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002508 LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
2509 << " evaluated to true\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002510 updateReachableEdge(B, TrueSucc);
2511 } else if (CI->isZero()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002512 LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
2513 << " evaluated to false\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002514 updateReachableEdge(B, FalseSucc);
2515 }
2516 } else {
2517 updateReachableEdge(B, TrueSucc);
2518 updateReachableEdge(B, FalseSucc);
2519 }
2520 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2521 // For switches, propagate the case values into the case
2522 // destinations.
2523
2524 // Remember how many outgoing edges there are to every successor.
2525 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2526
Davide Italiano7e274e02016-12-22 16:03:48 +00002527 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002528 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002529 // See if we were able to turn this switch statement into a constant.
2530 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002531 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002532 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002533 auto Case = *SI->findCaseValue(CondVal);
2534 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002535 // We proved the value is outside of the range of the case.
2536 // We can't do anything other than mark the default dest as reachable,
2537 // and go home.
2538 updateReachableEdge(B, SI->getDefaultDest());
2539 return;
2540 }
2541 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002542 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002543 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002544 } else {
2545 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2546 BasicBlock *TargetBlock = SI->getSuccessor(i);
2547 ++SwitchEdges[TargetBlock];
2548 updateReachableEdge(B, TargetBlock);
2549 }
2550 }
2551 } else {
2552 // Otherwise this is either unconditional, or a type we have no
2553 // idea about. Just mark successors as reachable.
2554 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2555 BasicBlock *TargetBlock = TI->getSuccessor(i);
2556 updateReachableEdge(B, TargetBlock);
2557 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002558
2559 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002560 // equivalent only to itself.
2561 //
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002562 auto *MA = getMemoryAccess(TI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002563 if (MA && !isa<MemoryUse>(MA)) {
2564 auto *CC = ensureLeaderOfMemoryClass(MA);
2565 if (setMemoryClass(MA, CC))
2566 markMemoryUsersTouched(MA);
2567 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002568 }
2569}
2570
Davide Italiano5974c312017-08-03 21:17:49 +00002571// Remove the PHI of Ops PHI for I
2572void NewGVN::removePhiOfOps(Instruction *I, PHINode *PHITemp) {
2573 InstrDFS.erase(PHITemp);
2574 // It's still a temp instruction. We keep it in the array so it gets erased.
Daniel Berlin9b926e92017-09-30 23:51:53 +00002575 // However, it's no longer used by I, or in the block
Davide Italiano5974c312017-08-03 21:17:49 +00002576 TempToBlock.erase(PHITemp);
2577 RealToTemp.erase(I);
Daniel Berlin9b926e92017-09-30 23:51:53 +00002578 // We don't remove the users from the phi node uses. This wastes a little
2579 // time, but such is life. We could use two sets to track which were there
2580 // are the start of NewGVN, and which were added, but right nowt he cost of
2581 // tracking is more than the cost of checking for more phi of ops.
Davide Italiano5974c312017-08-03 21:17:49 +00002582}
2583
2584// Add PHI Op in BB as a PHI of operations version of ExistingValue.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002585void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2586 Instruction *ExistingValue) {
2587 InstrDFS[Op] = InstrToDFSNum(ExistingValue);
2588 AllTempInstructions.insert(Op);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002589 TempToBlock[Op] = BB;
Daniel Berlinb779db72017-06-29 17:01:10 +00002590 RealToTemp[ExistingValue] = Op;
Daniel Berlin9b926e92017-09-30 23:51:53 +00002591 // Add all users to phi node use, as they are now uses of the phi of ops phis
2592 // and may themselves be phi of ops.
2593 for (auto *U : ExistingValue->users())
2594 if (auto *UI = dyn_cast<Instruction>(U))
2595 PHINodeUses.insert(UI);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002596}
2597
2598static bool okayForPHIOfOps(const Instruction *I) {
Chad Rosiera5508e32017-08-10 14:12:57 +00002599 if (!EnablePhiOfOps)
2600 return false;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002601 return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
2602 isa<LoadInst>(I);
2603}
2604
Daniel Berlin08dd5822017-10-06 01:33:06 +00002605bool NewGVN::OpIsSafeForPHIOfOpsHelper(
2606 Value *V, const BasicBlock *PHIBlock,
2607 SmallPtrSetImpl<const Value *> &Visited,
2608 SmallVectorImpl<Instruction *> &Worklist) {
2609
Daniel Berlin94090dd2017-09-02 02:18:44 +00002610 if (!isa<Instruction>(V))
2611 return true;
2612 auto OISIt = OpSafeForPHIOfOps.find(V);
2613 if (OISIt != OpSafeForPHIOfOps.end())
2614 return OISIt->second;
Daniel Berlinde6958e2017-09-30 23:51:04 +00002615
Daniel Berlin08dd5822017-10-06 01:33:06 +00002616 // Keep walking until we either dominate the phi block, or hit a phi, or run
2617 // out of things to check.
Daniel Berlin94090dd2017-09-02 02:18:44 +00002618 if (DT->properlyDominates(getBlockForValue(V), PHIBlock)) {
2619 OpSafeForPHIOfOps.insert({V, true});
2620 return true;
2621 }
2622 // PHI in the same block.
2623 if (isa<PHINode>(V) && getBlockForValue(V) == PHIBlock) {
2624 OpSafeForPHIOfOps.insert({V, false});
2625 return false;
2626 }
Daniel Berlinde6958e2017-09-30 23:51:04 +00002627
Daniel Berlinde6958e2017-09-30 23:51:04 +00002628 auto *OrigI = cast<Instruction>(V);
2629 for (auto *Op : OrigI->operand_values()) {
Daniel Berlin94090dd2017-09-02 02:18:44 +00002630 if (!isa<Instruction>(Op))
2631 continue;
Daniel Berlinde6958e2017-09-30 23:51:04 +00002632 // Stop now if we find an unsafe operand.
2633 auto OISIt = OpSafeForPHIOfOps.find(OrigI);
Daniel Berlin94090dd2017-09-02 02:18:44 +00002634 if (OISIt != OpSafeForPHIOfOps.end()) {
2635 if (!OISIt->second) {
2636 OpSafeForPHIOfOps.insert({V, false});
2637 return false;
2638 }
Daniel Berlin94090dd2017-09-02 02:18:44 +00002639 continue;
Daniel Berlinde6958e2017-09-30 23:51:04 +00002640 }
Daniel Berlin08dd5822017-10-06 01:33:06 +00002641 if (!Visited.insert(Op).second)
2642 continue;
Daniel Berlinde6958e2017-09-30 23:51:04 +00002643 Worklist.push_back(cast<Instruction>(Op));
2644 }
Daniel Berlin08dd5822017-10-06 01:33:06 +00002645 return true;
2646}
Daniel Berlinde6958e2017-09-30 23:51:04 +00002647
Daniel Berlin08dd5822017-10-06 01:33:06 +00002648// Return true if this operand will be safe to use for phi of ops.
2649//
2650// The reason some operands are unsafe is that we are not trying to recursively
2651// translate everything back through phi nodes. We actually expect some lookups
2652// of expressions to fail. In particular, a lookup where the expression cannot
2653// exist in the predecessor. This is true even if the expression, as shown, can
2654// be determined to be constant.
2655bool NewGVN::OpIsSafeForPHIOfOps(Value *V, const BasicBlock *PHIBlock,
2656 SmallPtrSetImpl<const Value *> &Visited) {
2657 SmallVector<Instruction *, 4> Worklist;
2658 if (!OpIsSafeForPHIOfOpsHelper(V, PHIBlock, Visited, Worklist))
2659 return false;
Daniel Berlinde6958e2017-09-30 23:51:04 +00002660 while (!Worklist.empty()) {
2661 auto *I = Worklist.pop_back_val();
Daniel Berlin08dd5822017-10-06 01:33:06 +00002662 if (!OpIsSafeForPHIOfOpsHelper(I, PHIBlock, Visited, Worklist))
Daniel Berlin94090dd2017-09-02 02:18:44 +00002663 return false;
Daniel Berlin94090dd2017-09-02 02:18:44 +00002664 }
2665 OpSafeForPHIOfOps.insert({V, true});
2666 return true;
2667}
2668
2669// Try to find a leader for instruction TransInst, which is a phi translated
2670// version of something in our original program. Visited is used to ensure we
2671// don't infinite loop during translations of cycles. OrigInst is the
2672// instruction in the original program, and PredBB is the predecessor we
2673// translated it through.
2674Value *NewGVN::findLeaderForInst(Instruction *TransInst,
2675 SmallPtrSetImpl<Value *> &Visited,
2676 MemoryAccess *MemAccess, Instruction *OrigInst,
2677 BasicBlock *PredBB) {
2678 unsigned IDFSNum = InstrToDFSNum(OrigInst);
2679 // Make sure it's marked as a temporary instruction.
2680 AllTempInstructions.insert(TransInst);
2681 // and make sure anything that tries to add it's DFS number is
2682 // redirected to the instruction we are making a phi of ops
2683 // for.
2684 TempToBlock.insert({TransInst, PredBB});
2685 InstrDFS.insert({TransInst, IDFSNum});
2686
2687 const Expression *E = performSymbolicEvaluation(TransInst, Visited);
2688 InstrDFS.erase(TransInst);
2689 AllTempInstructions.erase(TransInst);
2690 TempToBlock.erase(TransInst);
2691 if (MemAccess)
2692 TempToMemory.erase(TransInst);
2693 if (!E)
2694 return nullptr;
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +00002695 auto *FoundVal = findPHIOfOpsLeader(E, OrigInst, PredBB);
2696 if (!FoundVal) {
Daniel Berlin94090dd2017-09-02 02:18:44 +00002697 ExpressionToPhiOfOps[E].insert(OrigInst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002698 LLVM_DEBUG(dbgs() << "Cannot find phi of ops operand for " << *TransInst
2699 << " in block " << getBlockName(PredBB) << "\n");
Daniel Berlin94090dd2017-09-02 02:18:44 +00002700 return nullptr;
2701 }
2702 if (auto *SI = dyn_cast<StoreInst>(FoundVal))
2703 FoundVal = SI->getValueOperand();
2704 return FoundVal;
2705}
2706
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002707// When we see an instruction that is an op of phis, generate the equivalent phi
2708// of ops form.
2709const Expression *
Daniel Berlin9b926e92017-09-30 23:51:53 +00002710NewGVN::makePossiblePHIOfOps(Instruction *I,
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002711 SmallPtrSetImpl<Value *> &Visited) {
2712 if (!okayForPHIOfOps(I))
2713 return nullptr;
2714
2715 if (!Visited.insert(I).second)
2716 return nullptr;
2717 // For now, we require the instruction be cycle free because we don't
2718 // *always* create a phi of ops for instructions that could be done as phi
2719 // of ops, we only do it if we think it is useful. If we did do it all the
2720 // time, we could remove the cycle free check.
2721 if (!isCycleFree(I))
2722 return nullptr;
2723
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002724 SmallPtrSet<const Value *, 8> ProcessedPHIs;
2725 // TODO: We don't do phi translation on memory accesses because it's
2726 // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2727 // which we don't have a good way of doing ATM.
2728 auto *MemAccess = getMemoryAccess(I);
2729 // If the memory operation is defined by a memory operation this block that
2730 // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2731 // can't help, as it would still be killed by that memory operation.
2732 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2733 MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2734 return nullptr;
2735
2736 // Convert op of phis to phi of ops
Florian Hahn773872f2018-04-20 16:37:13 +00002737 SmallPtrSet<const Value *, 10> VisitedOps;
2738 SmallVector<Value *, 4> Ops(I->operand_values());
2739 BasicBlock *SamePHIBlock = nullptr;
2740 PHINode *OpPHI = nullptr;
2741 if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
2742 return nullptr;
2743 for (auto *Op : Ops) {
Daniel Berlin9b926e92017-09-30 23:51:53 +00002744 if (!isa<PHINode>(Op)) {
2745 auto *ValuePHI = RealToTemp.lookup(Op);
2746 if (!ValuePHI)
2747 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002748 LLVM_DEBUG(dbgs() << "Found possible dependent phi of ops\n");
Daniel Berlin9b926e92017-09-30 23:51:53 +00002749 Op = ValuePHI;
2750 }
Florian Hahn773872f2018-04-20 16:37:13 +00002751 OpPHI = cast<PHINode>(Op);
2752 if (!SamePHIBlock) {
2753 SamePHIBlock = getBlockForValue(OpPHI);
2754 } else if (SamePHIBlock != getBlockForValue(OpPHI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002755 LLVM_DEBUG(
2756 dbgs()
2757 << "PHIs for operands are not all in the same block, aborting\n");
Florian Hahn773872f2018-04-20 16:37:13 +00002758 return nullptr;
Daniel Berlinc1305af2017-09-30 23:51:54 +00002759 }
Florian Hahn773872f2018-04-20 16:37:13 +00002760 // No point in doing this for one-operand phis.
2761 if (OpPHI->getNumOperands() == 1) {
2762 OpPHI = nullptr;
2763 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002764 }
Florian Hahn773872f2018-04-20 16:37:13 +00002765 }
Daniel Berlinc1305af2017-09-30 23:51:54 +00002766
Florian Hahn773872f2018-04-20 16:37:13 +00002767 if (!OpPHI)
2768 return nullptr;
2769
2770 SmallVector<ValPair, 4> PHIOps;
2771 SmallPtrSet<Value *, 4> Deps;
2772 auto *PHIBlock = getBlockForValue(OpPHI);
2773 RevisitOnReachabilityChange[PHIBlock].reset(InstrToDFSNum(I));
2774 for (unsigned PredNum = 0; PredNum < OpPHI->getNumOperands(); ++PredNum) {
2775 auto *PredBB = OpPHI->getIncomingBlock(PredNum);
2776 Value *FoundVal = nullptr;
2777 SmallPtrSet<Value *, 4> CurrentDeps;
2778 // We could just skip unreachable edges entirely but it's tricky to do
2779 // with rewriting existing phi nodes.
2780 if (ReachableEdges.count({PredBB, PHIBlock})) {
2781 // Clone the instruction, create an expression from it that is
2782 // translated back into the predecessor, and see if we have a leader.
2783 Instruction *ValueOp = I->clone();
2784 if (MemAccess)
2785 TempToMemory.insert({ValueOp, MemAccess});
2786 bool SafeForPHIOfOps = true;
2787 VisitedOps.clear();
2788 for (auto &Op : ValueOp->operands()) {
2789 auto *OrigOp = &*Op;
2790 // When these operand changes, it could change whether there is a
2791 // leader for us or not, so we have to add additional users.
2792 if (isa<PHINode>(Op)) {
2793 Op = Op->DoPHITranslation(PHIBlock, PredBB);
2794 if (Op != OrigOp && Op != I)
2795 CurrentDeps.insert(Op);
2796 } else if (auto *ValuePHI = RealToTemp.lookup(Op)) {
2797 if (getBlockForValue(ValuePHI) == PHIBlock)
2798 Op = ValuePHI->getIncomingValueForBlock(PredBB);
2799 }
2800 // If we phi-translated the op, it must be safe.
2801 SafeForPHIOfOps =
2802 SafeForPHIOfOps &&
2803 (Op != OrigOp || OpIsSafeForPHIOfOps(Op, PHIBlock, VisitedOps));
2804 }
2805 // FIXME: For those things that are not safe we could generate
2806 // expressions all the way down, and see if this comes out to a
2807 // constant. For anything where that is true, and unsafe, we should
2808 // have made a phi-of-ops (or value numbered it equivalent to something)
2809 // for the pieces already.
2810 FoundVal = !SafeForPHIOfOps ? nullptr
2811 : findLeaderForInst(ValueOp, Visited,
2812 MemAccess, I, PredBB);
2813 ValueOp->deleteValue();
2814 if (!FoundVal) {
2815 // We failed to find a leader for the current ValueOp, but this might
2816 // change in case of the translated operands change.
2817 if (SafeForPHIOfOps)
2818 for (auto Dep : CurrentDeps)
2819 addAdditionalUsers(Dep, I);
2820
2821 return nullptr;
2822 }
2823 Deps.insert(CurrentDeps.begin(), CurrentDeps.end());
2824 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002825 LLVM_DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2826 << getBlockName(PredBB)
2827 << " because the block is unreachable\n");
Florian Hahn773872f2018-04-20 16:37:13 +00002828 FoundVal = UndefValue::get(I->getType());
2829 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
2830 }
2831
2832 PHIOps.push_back({FoundVal, PredBB});
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002833 LLVM_DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2834 << getBlockName(PredBB) << "\n");
Florian Hahn773872f2018-04-20 16:37:13 +00002835 }
2836 for (auto Dep : Deps)
2837 addAdditionalUsers(Dep, I);
2838 sortPHIOps(PHIOps);
2839 auto *E = performSymbolicPHIEvaluation(PHIOps, I, PHIBlock);
2840 if (isa<ConstantExpression>(E) || isa<VariableExpression>(E)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002841 LLVM_DEBUG(
2842 dbgs()
2843 << "Not creating real PHI of ops because it simplified to existing "
2844 "value or constant\n");
Daniel Berlinc1305af2017-09-30 23:51:54 +00002845 return E;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002846 }
Florian Hahn773872f2018-04-20 16:37:13 +00002847 auto *ValuePHI = RealToTemp.lookup(I);
2848 bool NewPHI = false;
2849 if (!ValuePHI) {
2850 ValuePHI =
2851 PHINode::Create(I->getType(), OpPHI->getNumOperands(), "phiofops");
2852 addPhiOfOps(ValuePHI, PHIBlock, I);
2853 NewPHI = true;
2854 NumGVNPHIOfOpsCreated++;
2855 }
2856 if (NewPHI) {
2857 for (auto PHIOp : PHIOps)
2858 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2859 } else {
2860 TempToBlock[ValuePHI] = PHIBlock;
2861 unsigned int i = 0;
2862 for (auto PHIOp : PHIOps) {
2863 ValuePHI->setIncomingValue(i, PHIOp.first);
2864 ValuePHI->setIncomingBlock(i, PHIOp.second);
2865 ++i;
2866 }
2867 }
2868 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002869 LLVM_DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2870 << "\n");
Florian Hahn773872f2018-04-20 16:37:13 +00002871
2872 return E;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002873}
2874
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002875// The algorithm initially places the values of the routine in the TOP
2876// congruence class. The leader of TOP is the undetermined value `undef`.
2877// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002878void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002879 NextCongruenceNum = 0;
2880
2881 // Note that even though we use the live on entry def as a representative
2882 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2883 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2884 // should be checking whether the MemoryAccess is top if we want to know if it
2885 // is equivalent to everything. Otherwise, what this really signifies is that
2886 // the access "it reaches all the way back to the beginning of the function"
2887
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002888 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002889 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002890 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002891 // The live on entry def gets put into it's own class
2892 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2893 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002894
Daniel Berlinec9deb72017-04-18 17:06:11 +00002895 for (auto DTN : nodes(DT)) {
2896 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002897 // All MemoryAccesses are equivalent to live on entry to start. They must
2898 // be initialized to something so that initial changes are noticed. For
2899 // the maximal answer, we initialize them all to be the same as
2900 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002901 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002902 if (MemoryBlockDefs)
2903 for (const auto &Def : *MemoryBlockDefs) {
2904 MemoryAccessToClass[&Def] = TOPClass;
2905 auto *MD = dyn_cast<MemoryDef>(&Def);
2906 // Insert the memory phis into the member list.
2907 if (!MD) {
2908 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002909 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002910 MemoryPhiState.insert({MP, MPS_TOP});
2911 }
2912
2913 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002914 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002915 }
Daniel Berlin9b926e92017-09-30 23:51:53 +00002916
2917 // FIXME: This is trying to discover which instructions are uses of phi
2918 // nodes. We should move this into one of the myriad of places that walk
2919 // all the operands already.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002920 for (auto &I : *BB) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002921 if (isa<PHINode>(&I))
2922 for (auto *U : I.users())
2923 if (auto *UInst = dyn_cast<Instruction>(U))
2924 if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
2925 PHINodeUses.insert(UInst);
Daniel Berlin22a4a012017-02-11 15:20:15 +00002926 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002927 // them, and they just end up sitting in TOP.
Chandler Carruth9ae926b2018-08-26 09:51:22 +00002928 if (I.isTerminator() && I.getType()->isVoidTy())
Daniel Berlin22a4a012017-02-11 15:20:15 +00002929 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002930 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002931 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002932 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002933 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002934
2935 // Initialize arguments to be in their own unique congruence classes
2936 for (auto &FA : F.args())
2937 createSingletonCongruenceClass(&FA);
2938}
2939
2940void NewGVN::cleanupTables() {
2941 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002942 LLVM_DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2943 << " has " << CongruenceClasses[i]->size()
2944 << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002945 // Make sure we delete the congruence class (probably worth switching to
2946 // a unique_ptr at some point.
2947 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002948 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002949 }
2950
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002951 // Destroy the value expressions
2952 SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2953 AllTempInstructions.end());
2954 AllTempInstructions.clear();
2955
2956 // We have to drop all references for everything first, so there are no uses
2957 // left as we delete them.
2958 for (auto *I : TempInst) {
2959 I->dropAllReferences();
2960 }
2961
2962 while (!TempInst.empty()) {
2963 auto *I = TempInst.back();
2964 TempInst.pop_back();
2965 I->deleteValue();
2966 }
2967
Davide Italiano7e274e02016-12-22 16:03:48 +00002968 ValueToClass.clear();
2969 ArgRecycler.clear(ExpressionAllocator);
2970 ExpressionAllocator.Reset();
2971 CongruenceClasses.clear();
2972 ExpressionToClass.clear();
2973 ValueToExpression.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002974 RealToTemp.clear();
2975 AdditionalUsers.clear();
2976 ExpressionToPhiOfOps.clear();
2977 TempToBlock.clear();
2978 TempToMemory.clear();
Daniel Berlin94090dd2017-09-02 02:18:44 +00002979 PHINodeUses.clear();
2980 OpSafeForPHIOfOps.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002981 ReachableBlocks.clear();
2982 ReachableEdges.clear();
2983#ifndef NDEBUG
2984 ProcessedCount.clear();
2985#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002986 InstrDFS.clear();
2987 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002988 DFSToInstr.clear();
2989 BlockInstRange.clear();
2990 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002991 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002992 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002993 MemoryToUsers.clear();
Daniel Berlin9b926e92017-09-30 23:51:53 +00002994 RevisitOnReachabilityChange.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002995}
2996
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002997// Assign local DFS number mapping to instructions, and leave space for Value
2998// PHI's.
Davide Italiano7e274e02016-12-22 16:03:48 +00002999std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
3000 unsigned Start) {
3001 unsigned End = Start;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003002 if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003003 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003004 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003005 }
3006
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003007 // Then the real block goes next.
Davide Italiano7e274e02016-12-22 16:03:48 +00003008 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00003009 // There's no need to call isInstructionTriviallyDead more than once on
3010 // an instruction. Therefore, once we know that an instruction is dead
3011 // we change its DFS number so that it doesn't get value numbered.
3012 if (isInstructionTriviallyDead(&I, TLI)) {
3013 InstrDFS[&I] = 0;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003014 LLVM_DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
Daniel Berlin856fa142017-03-06 18:42:27 +00003015 markInstructionForDeletion(&I);
3016 continue;
3017 }
Daniel Berlin9b926e92017-09-30 23:51:53 +00003018 if (isa<PHINode>(&I))
3019 RevisitOnReachabilityChange[B].set(End);
Davide Italiano7e274e02016-12-22 16:03:48 +00003020 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003021 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003022 }
3023
3024 // All of the range functions taken half-open ranges (open on the end side).
3025 // So we do not subtract one from count, because at this point it is one
3026 // greater than the last instruction.
3027 return std::make_pair(Start, End);
3028}
3029
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003030void NewGVN::updateProcessedCount(const Value *V) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003031#ifndef NDEBUG
3032 if (ProcessedCount.count(V) == 0) {
3033 ProcessedCount.insert({V, 1});
3034 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00003035 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00003036 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00003037 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00003038 }
3039#endif
3040}
Eugene Zelenko99241d72017-10-20 21:47:29 +00003041
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003042// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
3043void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
3044 // If all the arguments are the same, the MemoryPhi has the same value as the
Daniel Berlind130b6c2017-05-21 23:41:58 +00003045 // argument. Filter out unreachable blocks and self phis from our operands.
3046 // TODO: We could do cycle-checking on the memory phis to allow valueizing for
3047 // self-phi checking.
Daniel Berlin41b39162017-03-18 15:41:36 +00003048 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003049 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlind130b6c2017-05-21 23:41:58 +00003050 return cast<MemoryAccess>(U) != MP &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003051 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00003052 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003053 });
Daniel Berlinc4796862017-01-27 02:37:11 +00003054 // If all that is left is nothing, our memoryphi is undef. We keep it as
3055 // InitialClass. Note: The only case this should happen is if we have at
3056 // least one self-argument.
3057 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00003058 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00003059 markMemoryUsersTouched(MP);
3060 return;
3061 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003062
3063 // Transform the remaining operands into operand leaders.
3064 // FIXME: mapped_iterator should have a range version.
3065 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00003066 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003067 };
3068 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
3069 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
3070
3071 // and now check if all the elements are equal.
3072 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00003073 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003074 ++MappedBegin;
3075 bool AllEqual = std::all_of(
3076 MappedBegin, MappedEnd,
3077 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
3078
3079 if (AllEqual)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003080 LLVM_DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue
3081 << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003082 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003083 LLVM_DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00003084 // If it's equal to something, it's in that class. Otherwise, it has to be in
3085 // a class where it is the leader (other things may be equivalent to it, but
3086 // it needs to start off in its own class, which means it must have been the
3087 // leader, and it can't have stopped being the leader because it was never
3088 // removed).
3089 CongruenceClass *CC =
3090 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
3091 auto OldState = MemoryPhiState.lookup(MP);
3092 assert(OldState != MPS_Invalid && "Invalid memory phi state");
3093 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
3094 MemoryPhiState[MP] = NewState;
3095 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003096 markMemoryUsersTouched(MP);
3097}
3098
3099// Value number a single instruction, symbolically evaluating, performing
3100// congruence finding, and updating mappings.
3101void NewGVN::valueNumberInstruction(Instruction *I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003102 LLVM_DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003103 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00003104 const Expression *Symbolized = nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003105 SmallPtrSet<Value *, 2> Visited;
Daniel Berlin283a6082017-03-01 19:59:26 +00003106 if (DebugCounter::shouldExecute(VNCounter)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003107 Symbolized = performSymbolicEvaluation(I, Visited);
3108 // Make a phi of ops if necessary
3109 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
3110 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
Daniel Berlin9b926e92017-09-30 23:51:53 +00003111 auto *PHIE = makePossiblePHIOfOps(I, Visited);
Davide Italiano5974c312017-08-03 21:17:49 +00003112 // If we created a phi of ops, use it.
3113 // If we couldn't create one, make sure we don't leave one lying around
3114 if (PHIE) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003115 Symbolized = PHIE;
Davide Italiano5974c312017-08-03 21:17:49 +00003116 } else if (auto *Op = RealToTemp.lookup(I)) {
3117 removePhiOfOps(I, Op);
3118 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003119 }
Daniel Berlin283a6082017-03-01 19:59:26 +00003120 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00003121 // Mark the instruction as unused so we don't value number it again.
3122 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00003123 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00003124 // If we couldn't come up with a symbolic expression, use the unknown
3125 // expression
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003126 if (Symbolized == nullptr)
Daniel Berlin02c6b172017-01-02 18:00:53 +00003127 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003128 performCongruenceFinding(I, Symbolized);
3129 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00003130 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00003131 // don't currently understand. We don't place non-value producing
3132 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00003133 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00003134 auto *Symbolized = createUnknownExpression(I);
3135 performCongruenceFinding(I, Symbolized);
3136 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00003137 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
3138 }
3139}
Davide Italiano7e274e02016-12-22 16:03:48 +00003140
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003141// Check if there is a path, using single or equal argument phi nodes, from
3142// First to Second.
Davide Italianoeab0de22017-05-18 23:22:44 +00003143bool NewGVN::singleReachablePHIPath(
3144 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
3145 const MemoryAccess *Second) const {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003146 if (First == Second)
3147 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00003148 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003149 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00003150
Davide Italianoeab0de22017-05-18 23:22:44 +00003151 // This is not perfect, but as we're just verifying here, we can live with
3152 // the loss of precision. The real solution would be that of doing strongly
3153 // connected component finding in this routine, and it's probably not worth
3154 // the complexity for the time being. So, we just keep a set of visited
3155 // MemoryAccess and return true when we hit a cycle.
3156 if (Visited.count(First))
3157 return true;
3158 Visited.insert(First);
3159
Daniel Berlin871ecd92017-04-01 09:44:24 +00003160 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00003161 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00003162 if (ChainDef == Second)
3163 return true;
3164 if (MSSA->isLiveOnEntryDef(ChainDef))
3165 return false;
3166 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003167 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00003168 auto *MP = cast<MemoryPhi>(EndDef);
3169 auto ReachableOperandPred = [&](const Use &U) {
3170 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
3171 };
3172 auto FilteredPhiArgs =
3173 make_filter_range(MP->operands(), ReachableOperandPred);
3174 SmallVector<const Value *, 32> OperandList;
3175 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
3176 std::back_inserter(OperandList));
Chen Zhenge2d47dd2018-08-17 07:51:01 +00003177 bool Okay = is_splat(OperandList);
Daniel Berlin871ecd92017-04-01 09:44:24 +00003178 if (Okay)
Davide Italianoeab0de22017-05-18 23:22:44 +00003179 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
3180 Second);
Daniel Berlin871ecd92017-04-01 09:44:24 +00003181 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003182}
3183
Daniel Berlin589cecc2017-01-02 18:00:46 +00003184// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003185// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00003186// subject to very rare false negatives. It is only useful for
3187// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003188void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00003189#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00003190 // Verify that the memory table equivalence and memory member set match
3191 for (const auto *CC : CongruenceClasses) {
3192 if (CC == TOPClass || CC->isDead())
3193 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00003194 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00003195 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00003196 "Any class with a store as a leader should have a "
3197 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00003198 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00003199 "Any congruence class with a store should have a "
3200 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00003201 }
3202
Daniel Berlina8236562017-04-07 18:38:09 +00003203 if (CC->getMemoryLeader())
3204 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00003205 "Representative MemoryAccess does not appear to be reverse "
3206 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00003207 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00003208 assert(MemoryAccessToClass.lookup(M) == CC &&
3209 "Memory member does not appear to be reverse mapped properly");
3210 }
3211
3212 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00003213 // congruence class.
3214
3215 // Filter out the unreachable and trivially dead entries, because they may
3216 // never have been updated if the instructions were not processed.
3217 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00003218 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00003219 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00003220 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
3221 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00003222 return false;
3223 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
3224 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Davide Italiano6e7a2122017-05-15 18:50:53 +00003225
3226 // We could have phi nodes which operands are all trivially dead,
3227 // so we don't process them.
3228 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
3229 for (auto &U : MemPHI->incoming_values()) {
Daniel Berlinc1305af2017-09-30 23:51:54 +00003230 if (auto *I = dyn_cast<Instruction>(&*U)) {
Davide Italiano6e7a2122017-05-15 18:50:53 +00003231 if (!isInstructionTriviallyDead(I))
3232 return true;
3233 }
3234 }
3235 return false;
3236 }
3237
Daniel Berlin589cecc2017-01-02 18:00:46 +00003238 return true;
3239 };
3240
Daniel Berlin1ea5f322017-01-26 22:21:48 +00003241 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00003242 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00003243 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00003244 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italianoeab0de22017-05-18 23:22:44 +00003245 if (FirstMUD && SecondMUD) {
3246 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
3247 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00003248 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
3249 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
3250 "The instructions for these memory operations should have "
3251 "been in the same congruence class or reachable through"
3252 "a single argument phi");
Davide Italianoeab0de22017-05-18 23:22:44 +00003253 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00003254 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00003255 // We can only sanely verify that MemoryDefs in the operand list all have
3256 // the same class.
3257 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00003258 return ReachableEdges.count(
3259 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00003260 isa<MemoryDef>(U);
3261
3262 };
3263 // All arguments should in the same class, ignoring unreachable arguments
3264 auto FilteredPhiArgs =
3265 make_filter_range(FirstMP->operands(), ReachableOperandPred);
3266 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
3267 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
3268 std::back_inserter(PhiOpClasses), [&](const Use &U) {
3269 const MemoryDef *MD = cast<MemoryDef>(U);
3270 return ValueToClass.lookup(MD->getMemoryInst());
3271 });
Chen Zhenge2d47dd2018-08-17 07:51:01 +00003272 assert(is_splat(PhiOpClasses) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00003273 "All MemoryPhi arguments should be in the same class");
3274 }
3275 }
Davide Italianoe9781e72017-03-25 02:40:02 +00003276#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00003277}
3278
Daniel Berlin06329a92017-03-18 15:41:40 +00003279// Verify that the sparse propagation we did actually found the maximal fixpoint
3280// We do this by storing the value to class mapping, touching all instructions,
3281// and redoing the iteration to see if anything changed.
3282void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00003283#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003284 LLVM_DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00003285 if (DebugCounter::isCounterSet(VNCounter))
3286 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
3287
3288 // Note that we have to store the actual classes, as we may change existing
3289 // classes during iteration. This is because our memory iteration propagation
3290 // is not perfect, and so may waste a little work. But it should generate
3291 // exactly the same congruence classes we have now, with different IDs.
3292 std::map<const Value *, CongruenceClass> BeforeIteration;
3293
3294 for (auto &KV : ValueToClass) {
3295 if (auto *I = dyn_cast<Instruction>(KV.first))
3296 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003297 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00003298 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00003299 BeforeIteration.insert({KV.first, *KV.second});
3300 }
3301
3302 TouchedInstructions.set();
3303 TouchedInstructions.reset(0);
3304 iterateTouchedInstructions();
3305 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
3306 EqualClasses;
3307 for (const auto &KV : ValueToClass) {
3308 if (auto *I = dyn_cast<Instruction>(KV.first))
3309 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003310 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00003311 continue;
3312 // We could sink these uses, but i think this adds a bit of clarity here as
3313 // to what we are comparing.
3314 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
3315 auto *AfterCC = KV.second;
3316 // Note that the classes can't change at this point, so we memoize the set
3317 // that are equal.
3318 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00003319 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00003320 "Value number changed after main loop completed!");
3321 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00003322 }
3323 }
3324#endif
3325}
3326
Daniel Berlin45403572017-05-16 19:58:47 +00003327// Verify that for each store expression in the expression to class mapping,
3328// only the latest appears, and multiple ones do not appear.
3329// Because loads do not use the stored value when doing equality with stores,
3330// if we don't erase the old store expressions from the table, a load can find
3331// a no-longer valid StoreExpression.
3332void NewGVN::verifyStoreExpressions() const {
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003333#ifndef NDEBUG
Daniel Berlin36b08b22017-06-19 00:24:00 +00003334 // This is the only use of this, and it's not worth defining a complicated
3335 // densemapinfo hash/equality function for it.
3336 std::set<
3337 std::pair<const Value *,
3338 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3339 StoreExpressionSet;
Daniel Berlin45403572017-05-16 19:58:47 +00003340 for (const auto &KV : ExpressionToClass) {
3341 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3342 // Make sure a version that will conflict with loads is not already there
Daniel Berlin36b08b22017-06-19 00:24:00 +00003343 auto Res = StoreExpressionSet.insert(
3344 {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3345 SE->getStoredValue())});
3346 bool Okay = Res.second;
3347 // It's okay to have the same expression already in there if it is
3348 // identical in nature.
3349 // This can happen when the leader of the stored value changes over time.
Davide Italiano0ec715b2017-06-20 22:57:40 +00003350 if (!Okay)
3351 Okay = (std::get<1>(Res.first->second) == KV.second) &&
3352 (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3353 lookupOperandLeader(SE->getStoredValue()));
Daniel Berlin36b08b22017-06-19 00:24:00 +00003354 assert(Okay && "Stored expression conflict exists in expression table");
Daniel Berlin45403572017-05-16 19:58:47 +00003355 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3356 assert(ValueExpr && ValueExpr->equals(*SE) &&
3357 "StoreExpression in ExpressionToClass is not latest "
3358 "StoreExpression for value");
3359 }
3360 }
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003361#endif
Daniel Berlin45403572017-05-16 19:58:47 +00003362}
3363
Daniel Berlin06329a92017-03-18 15:41:40 +00003364// This is the main value numbering loop, it iterates over the initial touched
3365// instruction set, propagating value numbers, marking things touched, etc,
3366// until the set of touched instructions is completely empty.
3367void NewGVN::iterateTouchedInstructions() {
3368 unsigned int Iterations = 0;
3369 // Figure out where touchedinstructions starts
3370 int FirstInstr = TouchedInstructions.find_first();
3371 // Nothing set, nothing to iterate, just return.
3372 if (FirstInstr == -1)
3373 return;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003374 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00003375 while (TouchedInstructions.any()) {
3376 ++Iterations;
3377 // Walk through all the instructions in all the blocks in RPO.
3378 // TODO: As we hit a new block, we should push and pop equalities into a
3379 // table lookupOperandLeader can use, to catch things PredicateInfo
3380 // might miss, like edge-only equivalences.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003381 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
Daniel Berlin06329a92017-03-18 15:41:40 +00003382
3383 // This instruction was found to be dead. We don't bother looking
3384 // at it again.
3385 if (InstrNum == 0) {
3386 TouchedInstructions.reset(InstrNum);
3387 continue;
3388 }
3389
Daniel Berlin21279bd2017-04-06 18:52:58 +00003390 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003391 const BasicBlock *CurrBlock = getBlockForValue(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003392
3393 // If we hit a new block, do reachability processing.
3394 if (CurrBlock != LastBlock) {
3395 LastBlock = CurrBlock;
3396 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3397 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3398
3399 // If it's not reachable, erase any touched instructions and move on.
3400 if (!BlockReachable) {
3401 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003402 LLVM_DEBUG(dbgs() << "Skipping instructions in block "
3403 << getBlockName(CurrBlock)
3404 << " because it is unreachable\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00003405 continue;
3406 }
3407 updateProcessedCount(CurrBlock);
3408 }
Daniel Berlineafdd862017-06-06 17:15:28 +00003409 // Reset after processing (because we may mark ourselves as touched when
3410 // we propagate equalities).
3411 TouchedInstructions.reset(InstrNum);
Daniel Berlin06329a92017-03-18 15:41:40 +00003412
3413 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003414 LLVM_DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00003415 valueNumberMemoryPhi(MP);
3416 } else if (auto *I = dyn_cast<Instruction>(V)) {
3417 valueNumberInstruction(I);
3418 } else {
3419 llvm_unreachable("Should have been a MemoryPhi or Instruction");
3420 }
3421 updateProcessedCount(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003422 }
3423 }
3424 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3425}
3426
Daniel Berlin85f91b02016-12-26 20:06:58 +00003427// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00003428bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00003429 if (DebugCounter::isCounterSet(VNCounter))
3430 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00003431 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00003432 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00003433 MSSAWalker = MSSA->getWalker();
Daniel Berline021d2d2017-05-19 20:22:20 +00003434 SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00003435
3436 // Count number of instructions for sizing of hash tables, and come
3437 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003438 unsigned ICount = 1;
3439 // Add an empty instruction to account for the fact that we start at 1
3440 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00003441 // Note: We want ideal RPO traversal of the blocks, which is not quite the
3442 // same as dominator tree order, particularly with regard whether backedges
3443 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00003444 // If we visit in the wrong order, we will end up performing N times as many
3445 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00003446 // The dominator tree does guarantee that, for a given dom tree node, it's
3447 // parent must occur before it in the RPO ordering. Thus, we only need to sort
3448 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00003449 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00003450 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00003451 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003452 auto *Node = DT->getNode(B);
3453 assert(Node && "RPO and Dominator tree should have same reachability");
3454 RPOOrdering[Node] = ++Counter;
3455 }
3456 // Sort dominator tree children arrays into RPO.
3457 for (auto &B : RPOT) {
3458 auto *Node = DT->getNode(B);
3459 if (Node->getChildren().size() > 1)
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +00003460 llvm::sort(Node->begin(), Node->end(),
3461 [&](const DomTreeNode *A, const DomTreeNode *B) {
3462 return RPOOrdering[A] < RPOOrdering[B];
3463 });
Daniel Berlin6658cc92016-12-29 01:12:36 +00003464 }
3465
3466 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00003467 for (auto DTN : depth_first(DT->getRootNode())) {
3468 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00003469 const auto &BlockRange = assignDFSNumbers(B, ICount);
3470 BlockInstRange.insert({B, BlockRange});
3471 ICount += BlockRange.second - BlockRange.first;
3472 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003473 initializeCongruenceClasses(F);
Davide Italiano7e274e02016-12-22 16:03:48 +00003474
Daniel Berline0bd37e2016-12-29 22:15:12 +00003475 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003476 // Ensure we don't end up resizing the expressionToClass map, as
3477 // that can be quite expensive. At most, we have one expression per
3478 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003479 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003480
3481 // Initialize the touched instructions to include the entry block.
3482 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
3483 TouchedInstructions.set(InstRange.first, InstRange.second);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003484 LLVM_DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3485 << " marked reachable\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003486 ReachableBlocks.insert(&F.getEntryBlock());
3487
Daniel Berlin06329a92017-03-18 15:41:40 +00003488 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00003489 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00003490 verifyIterationSettled(F);
Daniel Berlin45403572017-05-16 19:58:47 +00003491 verifyStoreExpressions();
Daniel Berlinf7d95802017-02-18 23:06:50 +00003492
Davide Italiano7e274e02016-12-22 16:03:48 +00003493 Changed |= eliminateInstructions(F);
3494
3495 // Delete all instructions marked for deletion.
3496 for (Instruction *ToErase : InstructionsToErase) {
3497 if (!ToErase->use_empty())
3498 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3499
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003500 if (ToErase->getParent())
3501 ToErase->eraseFromParent();
Davide Italiano7e274e02016-12-22 16:03:48 +00003502 }
3503
3504 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003505 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3506 return !ReachableBlocks.count(&BB);
3507 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003508
3509 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003510 LLVM_DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
3511 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003512 deleteInstructionsInBlock(&BB);
3513 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003514 }
3515
3516 cleanupTables();
3517 return Changed;
3518}
3519
Davide Italiano7e274e02016-12-22 16:03:48 +00003520struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003521 int DFSIn = 0;
3522 int DFSOut = 0;
3523 int LocalNum = 0;
Eugene Zelenko99241d72017-10-20 21:47:29 +00003524
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003525 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003526 // The bool in the Def tells us whether the Def is the stored value of a
3527 // store.
3528 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003529 Use *U = nullptr;
Eugene Zelenko99241d72017-10-20 21:47:29 +00003530
Davide Italiano7e274e02016-12-22 16:03:48 +00003531 bool operator<(const ValueDFS &Other) const {
3532 // It's not enough that any given field be less than - we have sets
3533 // of fields that need to be evaluated together to give a proper ordering.
3534 // For example, if you have;
3535 // DFS (1, 3)
3536 // Val 0
3537 // DFS (1, 2)
3538 // Val 50
3539 // We want the second to be less than the first, but if we just go field
3540 // by field, we will get to Val 0 < Val 50 and say the first is less than
3541 // the second. We only want it to be less than if the DFS orders are equal.
3542 //
3543 // Each LLVM instruction only produces one value, and thus the lowest-level
3544 // differentiator that really matters for the stack (and what we use as as a
3545 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003546 // Everything else in the structure is instruction level, and only affects
3547 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00003548 //
3549 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3550 // the order of replacement of uses does not matter.
3551 // IE given,
3552 // a = 5
3553 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00003554 // When you hit b, you will have two valuedfs with the same dfsin, out, and
3555 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00003556 // The .val will be the same as well.
3557 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003558 // You will replace both, and it does not matter what order you replace them
3559 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3560 // operand 2).
3561 // Similarly for the case of same dfsin, dfsout, localnum, but different
3562 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00003563 // a = 5
3564 // b = 6
3565 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00003566 // in c, we will a valuedfs for a, and one for b,with everything the same
3567 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00003568 // It does not matter what order we replace these operands in.
3569 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003570 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3571 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00003572 Other.U);
3573 }
3574};
3575
Daniel Berlinc4796862017-01-27 02:37:11 +00003576// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003577// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00003578// reachable uses for each value is stored in UseCount, and instructions that
3579// seem
3580// dead (have no non-dead uses) are stored in ProbablyDead.
3581void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00003582 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00003583 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00003584 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00003585 for (auto D : Dense) {
3586 // First add the value.
3587 BasicBlock *BB = getBlockForValue(D);
3588 // Constants are handled prior to ever calling this function, so
3589 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00003590 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003591 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003592 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003593 VDDef.DFSIn = DomNode->getDFSNumIn();
3594 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003595 // If it's a store, use the leader of the value operand, if it's always
3596 // available, or the value operand. TODO: We could do dominance checks to
3597 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00003598 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00003599 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003600 if (alwaysAvailable(Leader)) {
3601 VDDef.Def.setPointer(Leader);
3602 } else {
3603 VDDef.Def.setPointer(SI->getValueOperand());
3604 VDDef.Def.setInt(true);
3605 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003606 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003607 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00003608 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003609 assert(isa<Instruction>(D) &&
3610 "The dense set member should always be an instruction");
Daniel Berline3e69e12017-03-10 00:32:33 +00003611 Instruction *Def = cast<Instruction>(D);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003612 VDDef.LocalNum = InstrToDFSNum(D);
3613 DFSOrderedSet.push_back(VDDef);
3614 // If there is a phi node equivalent, add it
3615 if (auto *PN = RealToTemp.lookup(Def)) {
3616 auto *PHIE =
3617 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3618 if (PHIE) {
3619 VDDef.Def.setInt(false);
3620 VDDef.Def.setPointer(PN);
3621 VDDef.LocalNum = 0;
3622 DFSOrderedSet.push_back(VDDef);
3623 }
3624 }
3625
Daniel Berline3e69e12017-03-10 00:32:33 +00003626 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003627 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00003628 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003629 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003630 // Don't try to replace into dead uses
3631 if (InstructionsToErase.count(I))
3632 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003633 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00003634 // Put the phi node uses in the incoming block.
3635 BasicBlock *IBlock;
3636 if (auto *P = dyn_cast<PHINode>(I)) {
3637 IBlock = P->getIncomingBlock(U);
3638 // Make phi node users appear last in the incoming block
3639 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003640 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00003641 } else {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003642 IBlock = getBlockForValue(I);
Daniel Berlin21279bd2017-04-06 18:52:58 +00003643 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003644 }
Davide Italianoccbbc832017-01-26 00:42:42 +00003645
3646 // Skip uses in unreachable blocks, as we're going
3647 // to delete them.
3648 if (ReachableBlocks.count(IBlock) == 0)
3649 continue;
3650
Daniel Berlinb66164c2017-01-14 00:24:23 +00003651 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003652 VDUse.DFSIn = DomNode->getDFSNumIn();
3653 VDUse.DFSOut = DomNode->getDFSNumOut();
3654 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00003655 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003656 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00003657 }
3658 }
Daniel Berline3e69e12017-03-10 00:32:33 +00003659
3660 // If there are no uses, it's probably dead (but it may have side-effects,
3661 // so not definitely dead. Otherwise, store the number of uses so we can
3662 // track if it becomes dead later).
3663 if (UseCount == 0)
3664 ProbablyDead.insert(Def);
3665 else
3666 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003667 }
3668}
3669
Daniel Berlinc4796862017-01-27 02:37:11 +00003670// This function converts the set of members for a congruence class from values,
3671// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00003672void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00003673 const CongruenceClass &Dense,
3674 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00003675 for (auto D : Dense) {
3676 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
3677 continue;
3678
3679 BasicBlock *BB = getBlockForValue(D);
3680 ValueDFS VD;
3681 DomTreeNode *DomNode = DT->getNode(BB);
3682 VD.DFSIn = DomNode->getDFSNumIn();
3683 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003684 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00003685
3686 // If it's an instruction, use the real local dfs number.
3687 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00003688 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00003689 else
3690 llvm_unreachable("Should have been an instruction");
3691
3692 LoadsAndStores.emplace_back(VD);
3693 }
3694}
3695
Davide Italiano7e274e02016-12-22 16:03:48 +00003696static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3697 patchReplacementInstruction(I, Repl);
3698 I->replaceAllUsesWith(Repl);
3699}
3700
3701void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003702 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Davide Italiano7e274e02016-12-22 16:03:48 +00003703 ++NumGVNBlocksDeleted;
3704
Daniel Berline19f0e02017-01-30 17:06:55 +00003705 // Delete the instructions backwards, as it has a reduced likelihood of having
3706 // to update as many def-use and use-def chains. Start after the terminator.
3707 auto StartPoint = BB->rbegin();
3708 ++StartPoint;
3709 // Note that we explicitly recalculate BB->rend() on each iteration,
3710 // as it may change when we remove the first instruction.
3711 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3712 Instruction &Inst = *I++;
3713 if (!Inst.use_empty())
3714 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3715 if (isa<LandingPadInst>(Inst))
3716 continue;
3717
3718 Inst.eraseFromParent();
3719 ++NumGVNInstrDeleted;
3720 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003721 // Now insert something that simplifycfg will turn into an unreachable.
3722 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3723 new StoreInst(UndefValue::get(Int8Ty),
3724 Constant::getNullValue(Int8Ty->getPointerTo()),
3725 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003726}
3727
3728void NewGVN::markInstructionForDeletion(Instruction *I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003729 LLVM_DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003730 InstructionsToErase.insert(I);
3731}
3732
3733void NewGVN::replaceInstruction(Instruction *I, Value *V) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003734 LLVM_DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003735 patchAndReplaceAllUsesWith(I, V);
3736 // We save the actual erasing to avoid invalidating memory
3737 // dependencies until we are done with everything.
3738 markInstructionForDeletion(I);
3739}
3740
3741namespace {
3742
3743// This is a stack that contains both the value and dfs info of where
3744// that value is valid.
3745class ValueDFSStack {
3746public:
3747 Value *back() const { return ValueStack.back(); }
3748 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3749
3750 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003751 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003752 DFSStack.emplace_back(DFSIn, DFSOut);
3753 }
Eugene Zelenko99241d72017-10-20 21:47:29 +00003754
Davide Italiano7e274e02016-12-22 16:03:48 +00003755 bool empty() const { return DFSStack.empty(); }
Eugene Zelenko99241d72017-10-20 21:47:29 +00003756
Davide Italiano7e274e02016-12-22 16:03:48 +00003757 bool isInScope(int DFSIn, int DFSOut) const {
3758 if (empty())
3759 return false;
3760 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3761 }
3762
3763 void popUntilDFSScope(int DFSIn, int DFSOut) {
3764
3765 // These two should always be in sync at this point.
3766 assert(ValueStack.size() == DFSStack.size() &&
3767 "Mismatch between ValueStack and DFSStack");
3768 while (
3769 !DFSStack.empty() &&
3770 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3771 DFSStack.pop_back();
3772 ValueStack.pop_back();
3773 }
3774 }
3775
3776private:
3777 SmallVector<Value *, 8> ValueStack;
3778 SmallVector<std::pair<int, int>, 8> DFSStack;
3779};
Eugene Zelenko99241d72017-10-20 21:47:29 +00003780
3781} // end anonymous namespace
Daniel Berlin04443432017-01-07 03:23:47 +00003782
Daniel Berlin94090dd2017-09-02 02:18:44 +00003783// Given an expression, get the congruence class for it.
3784CongruenceClass *NewGVN::getClassForExpression(const Expression *E) const {
3785 if (auto *VE = dyn_cast<VariableExpression>(E))
3786 return ValueToClass.lookup(VE->getVariableValue());
3787 else if (isa<DeadExpression>(E))
3788 return TOPClass;
3789 return ExpressionToClass.lookup(E);
3790}
3791
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003792// Given a value and a basic block we are trying to see if it is available in,
3793// see if the value has a leader available in that block.
Daniel Berlin94090dd2017-09-02 02:18:44 +00003794Value *NewGVN::findPHIOfOpsLeader(const Expression *E,
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +00003795 const Instruction *OrigInst,
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003796 const BasicBlock *BB) const {
3797 // It would already be constant if we could make it constant
3798 if (auto *CE = dyn_cast<ConstantExpression>(E))
3799 return CE->getConstantValue();
Daniel Berlin94090dd2017-09-02 02:18:44 +00003800 if (auto *VE = dyn_cast<VariableExpression>(E)) {
3801 auto *V = VE->getVariableValue();
3802 if (alwaysAvailable(V) || DT->dominates(getBlockForValue(V), BB))
3803 return VE->getVariableValue();
3804 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003805
Daniel Berlin94090dd2017-09-02 02:18:44 +00003806 auto *CC = getClassForExpression(E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003807 if (!CC)
3808 return nullptr;
3809 if (alwaysAvailable(CC->getLeader()))
3810 return CC->getLeader();
3811
3812 for (auto Member : *CC) {
3813 auto *MemberInst = dyn_cast<Instruction>(Member);
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +00003814 if (MemberInst == OrigInst)
3815 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003816 // Anything that isn't an instruction is always available.
3817 if (!MemberInst)
3818 return Member;
Daniel Berlin94090dd2017-09-02 02:18:44 +00003819 if (DT->dominates(getBlockForValue(MemberInst), BB))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003820 return Member;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003821 }
3822 return nullptr;
3823}
3824
Davide Italiano7e274e02016-12-22 16:03:48 +00003825bool NewGVN::eliminateInstructions(Function &F) {
3826 // This is a non-standard eliminator. The normal way to eliminate is
3827 // to walk the dominator tree in order, keeping track of available
3828 // values, and eliminating them. However, this is mildly
3829 // pointless. It requires doing lookups on every instruction,
3830 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003831 // instructions part of most singleton congruence classes, we know we
3832 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003833
3834 // Instead, this eliminator looks at the congruence classes directly, sorts
3835 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003836 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003837 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003838 // last member. This is worst case O(E log E) where E = number of
3839 // instructions in a single congruence class. In theory, this is all
3840 // instructions. In practice, it is much faster, as most instructions are
3841 // either in singleton congruence classes or can't possibly be eliminated
3842 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003843 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003844 // for elimination purposes.
3845 // TODO: If we wanted to be faster, We could remove any members with no
3846 // overlapping ranges while sorting, as we will never eliminate anything
3847 // with those members, as they don't dominate anything else in our set.
3848
Davide Italiano7e274e02016-12-22 16:03:48 +00003849 bool AnythingReplaced = false;
3850
3851 // Since we are going to walk the domtree anyway, and we can't guarantee the
3852 // DFS numbers are updated, we compute some ourselves.
3853 DT->updateDFSNumbers();
3854
Daniel Berlin0207cca2017-05-21 23:41:56 +00003855 // Go through all of our phi nodes, and kill the arguments associated with
3856 // unreachable edges.
Daniel Berlin9b926e92017-09-30 23:51:53 +00003857 auto ReplaceUnreachablePHIArgs = [&](PHINode *PHI, BasicBlock *BB) {
3858 for (auto &Operand : PHI->incoming_values())
3859 if (!ReachableEdges.count({PHI->getIncomingBlock(Operand), BB})) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003860 LLVM_DEBUG(dbgs() << "Replacing incoming value of " << PHI
3861 << " for block "
3862 << getBlockName(PHI->getIncomingBlock(Operand))
3863 << " with undef due to it being unreachable\n");
Daniel Berlin9b926e92017-09-30 23:51:53 +00003864 Operand.set(UndefValue::get(PHI->getType()));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003865 }
3866 };
Daniel Berlin9b926e92017-09-30 23:51:53 +00003867 // Replace unreachable phi arguments.
3868 // At this point, RevisitOnReachabilityChange only contains:
3869 //
3870 // 1. PHIs
3871 // 2. Temporaries that will convert to PHIs
3872 // 3. Operations that are affected by an unreachable edge but do not fit into
3873 // 1 or 2 (rare).
3874 // So it is a slight overshoot of what we want. We could make it exact by
3875 // using two SparseBitVectors per block.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003876 DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
Daniel Berlin9b926e92017-09-30 23:51:53 +00003877 for (auto &KV : ReachableEdges)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003878 ReachablePredCount[KV.getEnd()]++;
Daniel Berlin9b926e92017-09-30 23:51:53 +00003879 for (auto &BBPair : RevisitOnReachabilityChange) {
3880 for (auto InstNum : BBPair.second) {
3881 auto *Inst = InstrFromDFSNum(InstNum);
3882 auto *PHI = dyn_cast<PHINode>(Inst);
3883 PHI = PHI ? PHI : dyn_cast_or_null<PHINode>(RealToTemp.lookup(Inst));
3884 if (!PHI)
3885 continue;
3886 auto *BB = BBPair.first;
3887 if (ReachablePredCount.lookup(BB) != PHI->getNumIncomingValues())
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003888 ReplaceUnreachablePHIArgs(PHI, BB);
Davide Italiano7e274e02016-12-22 16:03:48 +00003889 }
Daniel Berlin9b926e92017-09-30 23:51:53 +00003890 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003891
Daniel Berline3e69e12017-03-10 00:32:33 +00003892 // Map to store the use counts
3893 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003894 for (auto *CC : reverse(CongruenceClasses)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003895 LLVM_DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
3896 << "\n");
Daniel Berlinc4796862017-01-27 02:37:11 +00003897 // Track the equivalent store info so we can decide whether to try
3898 // dead store elimination.
3899 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003900 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003901 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003902 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003903 // Everything still in the TOP class is unreachable or dead.
3904 if (CC == TOPClass) {
Daniel Berline021d2d2017-05-19 20:22:20 +00003905 for (auto M : *CC) {
3906 auto *VTE = ValueToExpression.lookup(M);
3907 if (VTE && isa<DeadExpression>(VTE))
3908 markInstructionForDeletion(cast<Instruction>(M));
Daniel Berlinb79f5362017-02-11 12:48:50 +00003909 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3910 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003911 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003912 "point");
Daniel Berline021d2d2017-05-19 20:22:20 +00003913 }
Daniel Berlinb79f5362017-02-11 12:48:50 +00003914 continue;
3915 }
3916
Daniel Berlina8236562017-04-07 18:38:09 +00003917 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003918 // If this is a leader that is always available, and it's a
3919 // constant or has no equivalences, just replace everything with
3920 // it. We then update the congruence class with whatever members
3921 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003922 Value *Leader =
3923 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003924 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003925 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003926 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003927 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003928 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003929 if (Member == Leader || !isa<Instruction>(Member) ||
3930 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003931 MembersLeft.insert(Member);
3932 continue;
3933 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003934 LLVM_DEBUG(dbgs() << "Found replacement " << *(Leader) << " for "
3935 << *Member << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003936 auto *I = cast<Instruction>(Member);
3937 assert(Leader != I && "About to accidentally remove our leader");
3938 replaceInstruction(I, Leader);
3939 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003940 }
Daniel Berlina8236562017-04-07 18:38:09 +00003941 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003942 } else {
Davide Italiano7e274e02016-12-22 16:03:48 +00003943 // If this is a singleton, we can skip it.
Davide Italiano5974c312017-08-03 21:17:49 +00003944 if (CC->size() != 1 || RealToTemp.count(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003945 // This is a stack because equality replacement/etc may place
3946 // constants in the middle of the member list, and we want to use
3947 // those constant values in preference to the current leader, over
3948 // the scope of those constants.
3949 ValueDFSStack EliminationStack;
3950
3951 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003952 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003953 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003954
3955 // Sort the whole thing.
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +00003956 llvm::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003957 for (auto &VD : DFSOrderedSet) {
3958 int MemberDFSIn = VD.DFSIn;
3959 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003960 Value *Def = VD.Def.getPointer();
3961 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003962 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003963 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003964 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003965 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003966 auto *DefInst = dyn_cast_or_null<Instruction>(Def);
3967 if (DefInst && AllTempInstructions.count(DefInst)) {
3968 auto *PN = cast<PHINode>(DefInst);
3969
3970 // If this is a value phi and that's the expression we used, insert
3971 // it into the program
3972 // remove from temp instruction list.
3973 AllTempInstructions.erase(PN);
3974 auto *DefBlock = getBlockForValue(Def);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003975 LLVM_DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3976 << " into block "
3977 << getBlockName(getBlockForValue(Def)) << "\n");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003978 PN->insertBefore(&DefBlock->front());
3979 Def = PN;
3980 NumGVNPHIOfOpsEliminations++;
3981 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003982
3983 if (EliminationStack.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003984 LLVM_DEBUG(dbgs() << "Elimination Stack is empty\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003985 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003986 LLVM_DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3987 << EliminationStack.dfs_back().first << ","
3988 << EliminationStack.dfs_back().second << ")\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003989 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003990
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003991 LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3992 << MemberDFSOut << ")\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003993 // First, we see if we are out of scope or empty. If so,
3994 // and there equivalences, we try to replace the top of
3995 // stack with equivalences (if it's on the stack, it must
3996 // not have been eliminated yet).
3997 // Then we synchronize to our current scope, by
3998 // popping until we are back within a DFS scope that
3999 // dominates the current member.
4000 // Then, what happens depends on a few factors
4001 // If the stack is now empty, we need to push
4002 // If we have a constant or a local equivalence we want to
4003 // start using, we also push.
4004 // Otherwise, we walk along, processing members who are
4005 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00004006 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00004007 bool OutOfScope =
4008 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
4009
4010 if (OutOfScope || ShouldPush) {
4011 // Sync to our current scope.
4012 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00004013 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00004014 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00004015 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00004016 }
4017 }
4018
Daniel Berline3e69e12017-03-10 00:32:33 +00004019 // Skip the Def's, we only want to eliminate on their uses. But mark
4020 // dominated defs as dead.
4021 if (Def) {
4022 // For anything in this case, what and how we value number
4023 // guarantees that any side-effets that would have occurred (ie
4024 // throwing, etc) can be proven to either still occur (because it's
4025 // dominated by something that has the same side-effects), or never
4026 // occur. Otherwise, we would not have been able to prove it value
4027 // equivalent to something else. For these things, we can just mark
4028 // it all dead. Note that this is different from the "ProbablyDead"
4029 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00004030 // easy to prove dead if they are also side-effect free. Note that
4031 // because stores are put in terms of the stored value, we skip
4032 // stored values here. If the stored value is really dead, it will
4033 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00004034 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00004035 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00004036 markInstructionForDeletion(cast<Instruction>(Def));
4037 continue;
4038 }
4039 // At this point, we know it is a Use we are trying to possibly
4040 // replace.
4041
4042 assert(isa<Instruction>(U->get()) &&
4043 "Current def should have been an instruction");
4044 assert(isa<Instruction>(U->getUser()) &&
4045 "Current user should have been an instruction");
4046
4047 // If the thing we are replacing into is already marked to be dead,
4048 // this use is dead. Note that this is true regardless of whether
4049 // we have anything dominating the use or not. We do this here
4050 // because we are already walking all the uses anyway.
4051 Instruction *InstUse = cast<Instruction>(U->getUser());
4052 if (InstructionsToErase.count(InstUse)) {
4053 auto &UseCount = UseCounts[U->get()];
4054 if (--UseCount == 0) {
4055 ProbablyDead.insert(cast<Instruction>(U->get()));
4056 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00004057 }
4058
Davide Italiano7e274e02016-12-22 16:03:48 +00004059 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00004060 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00004061 if (EliminationStack.empty())
4062 continue;
4063
Daniel Berlinc0e008d2017-03-10 00:32:26 +00004064 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00004065
Davide Italianoa76e5fa2017-05-18 21:43:23 +00004066 auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
Daniel Berlin56cca742018-01-09 20:12:42 +00004067 bool isSSACopy = II && II->getIntrinsicID() == Intrinsic::ssa_copy;
4068 if (isSSACopy)
Davide Italianoa76e5fa2017-05-18 21:43:23 +00004069 DominatingLeader = II->getOperand(0);
4070
Daniel Berlind92e7f92017-01-07 00:01:42 +00004071 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00004072 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00004073 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004074 LLVM_DEBUG(dbgs()
4075 << "Found replacement " << *DominatingLeader << " for "
4076 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00004077
4078 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00004079 // metadata. Skip this if we are replacing predicateinfo with its
4080 // original operand, as we already know we can just drop it.
4081 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00004082 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
4083 if (!PI || DominatingLeader != PI->OriginalOp)
4084 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00004085 U->set(DominatingLeader);
4086 // This is now a use of the dominating leader, which means if the
4087 // dominating leader was dead, it's now live!
4088 auto &LeaderUseCount = UseCounts[DominatingLeader];
4089 // It's about to be alive again.
4090 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
4091 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
Hiroshi Inouef2096492018-06-14 05:41:49 +00004092 // Copy instructions, however, are still dead because we use their
Daniel Berlin56cca742018-01-09 20:12:42 +00004093 // operand as the leader.
4094 if (LeaderUseCount == 0 && isSSACopy)
Davide Italianoa76e5fa2017-05-18 21:43:23 +00004095 ProbablyDead.insert(II);
Daniel Berline3e69e12017-03-10 00:32:33 +00004096 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00004097 AnythingReplaced = true;
4098 }
4099 }
4100 }
4101
Daniel Berline3e69e12017-03-10 00:32:33 +00004102 // At this point, anything still in the ProbablyDead set is actually dead if
4103 // would be trivially dead.
4104 for (auto *I : ProbablyDead)
4105 if (wouldInstructionBeTriviallyDead(I))
4106 markInstructionForDeletion(I);
4107
Davide Italiano7e274e02016-12-22 16:03:48 +00004108 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00004109 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00004110 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00004111 if (!isa<Instruction>(Member) ||
4112 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00004113 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00004114 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00004115
4116 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00004117 if (CC->getStoreCount() > 0) {
4118 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +00004119 llvm::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
Daniel Berlinc4796862017-01-27 02:37:11 +00004120 ValueDFSStack EliminationStack;
4121 for (auto &VD : PossibleDeadStores) {
4122 int MemberDFSIn = VD.DFSIn;
4123 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00004124 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00004125 if (EliminationStack.empty() ||
4126 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
4127 // Sync to our current scope.
4128 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
4129 if (EliminationStack.empty()) {
4130 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
4131 continue;
4132 }
4133 }
4134 // We already did load elimination, so nothing to do here.
4135 if (isa<LoadInst>(Member))
4136 continue;
4137 assert(!EliminationStack.empty());
4138 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00004139 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00004140 assert(DT->dominates(Leader->getParent(), Member->getParent()));
4141 // Member is dominater by Leader, and thus dead
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004142 LLVM_DEBUG(dbgs() << "Marking dead store " << *Member
4143 << " that is dominated by " << *Leader << "\n");
Daniel Berlinc4796862017-01-27 02:37:11 +00004144 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00004145 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00004146 ++NumGVNDeadStores;
4147 }
4148 }
Davide Italiano7e274e02016-12-22 16:03:48 +00004149 }
Davide Italiano7e274e02016-12-22 16:03:48 +00004150 return AnythingReplaced;
4151}
Daniel Berlin1c087672017-02-11 15:07:01 +00004152
4153// This function provides global ranking of operations so that we can place them
4154// in a canonical order. Note that rank alone is not necessarily enough for a
4155// complete ordering, as constants all have the same rank. However, generally,
4156// we will simplify an operation with all constants so that it doesn't matter
4157// what order they appear in.
4158unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004159 // Prefer constants to undef to anything else
4160 // Undef is a constant, have to check it first.
4161 // Prefer smaller constants to constantexprs
4162 if (isa<ConstantExpr>(V))
4163 return 2;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004164 if (isa<UndefValue>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004165 return 1;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004166 if (isa<Constant>(V))
4167 return 0;
Daniel Berlin1c087672017-02-11 15:07:01 +00004168 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004169 return 3 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00004170
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004171 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00004172 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00004173 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00004174 if (Result > 0)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004175 return 4 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00004176 // Unreachable or something else, just return a really large number.
4177 return ~0;
4178}
4179
4180// This is a function that says whether two commutative operations should
4181// have their order swapped when canonicalizing.
4182bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
4183 // Because we only care about a total ordering, and don't rewrite expressions
4184 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004185 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00004186 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00004187}
Daniel Berlin64e68992017-03-12 04:46:45 +00004188
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00004189namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +00004190
Daniel Berlin64e68992017-03-12 04:46:45 +00004191class NewGVNLegacyPass : public FunctionPass {
4192public:
Eugene Zelenko99241d72017-10-20 21:47:29 +00004193 // Pass identification, replacement for typeid.
4194 static char ID;
4195
Daniel Berlin64e68992017-03-12 04:46:45 +00004196 NewGVNLegacyPass() : FunctionPass(ID) {
4197 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
4198 }
Eugene Zelenko99241d72017-10-20 21:47:29 +00004199
Daniel Berlin64e68992017-03-12 04:46:45 +00004200 bool runOnFunction(Function &F) override;
4201
4202private:
4203 void getAnalysisUsage(AnalysisUsage &AU) const override {
4204 AU.addRequired<AssumptionCacheTracker>();
4205 AU.addRequired<DominatorTreeWrapperPass>();
4206 AU.addRequired<TargetLibraryInfoWrapperPass>();
4207 AU.addRequired<MemorySSAWrapperPass>();
4208 AU.addRequired<AAResultsWrapperPass>();
4209 AU.addPreserved<DominatorTreeWrapperPass>();
4210 AU.addPreserved<GlobalsAAWrapperPass>();
4211 }
4212};
Eugene Zelenko99241d72017-10-20 21:47:29 +00004213
4214} // end anonymous namespace
Daniel Berlin64e68992017-03-12 04:46:45 +00004215
4216bool NewGVNLegacyPass::runOnFunction(Function &F) {
4217 if (skipFunction(F))
4218 return false;
4219 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4220 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
4221 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
4222 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
4223 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
4224 F.getParent()->getDataLayout())
4225 .runGVN();
4226}
4227
Eugene Zelenko99241d72017-10-20 21:47:29 +00004228char NewGVNLegacyPass::ID = 0;
4229
Daniel Berlin64e68992017-03-12 04:46:45 +00004230INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
4231 false, false)
4232INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4233INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
4234INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4235INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
4236INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
4237INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
4238INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
4239 false)
4240
Daniel Berlin64e68992017-03-12 04:46:45 +00004241// createGVNPass - The public interface to this file.
4242FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
4243
4244PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
4245 // Apparently the order in which we get these results matter for
4246 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
4247 // the same order here, just in case.
4248 auto &AC = AM.getResult<AssumptionAnalysis>(F);
4249 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
4250 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
4251 auto &AA = AM.getResult<AAManager>(F);
4252 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
4253 bool Changed =
4254 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
4255 .runGVN();
4256 if (!Changed)
4257 return PreservedAnalyses::all();
4258 PreservedAnalyses PA;
4259 PA.preserve<DominatorTreeAnalysis>();
4260 PA.preserve<GlobalsAA>();
4261 return PA;
4262}