blob: cefbbc92f8275235388a236f2218d0487b2a72a6 [file] [log] [blame]
Davide Italiano7e274e02016-12-22 16:03:48 +00001//===---- NewGVN.cpp - Global Value Numbering Pass --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file implements the new LLVM's Global Value Numbering pass.
11/// GVN partitions values computed by a function into congruence classes.
12/// Values ending up in the same congruence class are guaranteed to be the same
13/// for every execution of the program. In that respect, congruency is a
14/// compile-time approximation of equivalence of values at runtime.
15/// The algorithm implemented here uses a sparse formulation and it's based
16/// on the ideas described in the paper:
17/// "A Sparse Algorithm for Predicated Global Value Numbering" from
18/// Karthik Gargi.
19///
Daniel Berlindb3c7be2017-01-26 21:39:49 +000020/// A brief overview of the algorithm: The algorithm is essentially the same as
21/// the standard RPO value numbering algorithm (a good reference is the paper
22/// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
23/// The RPO algorithm proceeds, on every iteration, to process every reachable
24/// block and every instruction in that block. This is because the standard RPO
25/// algorithm does not track what things have the same value number, it only
26/// tracks what the value number of a given operation is (the mapping is
27/// operation -> value number). Thus, when a value number of an operation
28/// changes, it must reprocess everything to ensure all uses of a value number
29/// get updated properly. In constrast, the sparse algorithm we use *also*
30/// tracks what operations have a given value number (IE it also tracks the
31/// reverse mapping from value number -> operations with that value number), so
32/// that it only needs to reprocess the instructions that are affected when
33/// something's value number changes. The rest of the algorithm is devoted to
34/// performing symbolic evaluation, forward propagation, and simplification of
35/// operations based on the value numbers deduced so far.
36///
37/// We also do not perform elimination by using any published algorithm. All
38/// published algorithms are O(Instructions). Instead, we use a technique that
39/// is O(number of operations with the same value number), enabling us to skip
40/// trying to eliminate things that have unique value numbers.
Davide Italiano7e274e02016-12-22 16:03:48 +000041//===----------------------------------------------------------------------===//
42
43#include "llvm/Transforms/Scalar/NewGVN.h"
44#include "llvm/ADT/BitVector.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/DenseSet.h"
47#include "llvm/ADT/DepthFirstIterator.h"
48#include "llvm/ADT/Hashing.h"
49#include "llvm/ADT/MapVector.h"
50#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000051#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000052#include "llvm/ADT/SmallPtrSet.h"
53#include "llvm/ADT/SmallSet.h"
54#include "llvm/ADT/SparseBitVector.h"
55#include "llvm/ADT/Statistic.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include "llvm/Analysis/AliasAnalysis.h"
58#include "llvm/Analysis/AssumptionCache.h"
59#include "llvm/Analysis/CFG.h"
60#include "llvm/Analysis/CFGPrinter.h"
61#include "llvm/Analysis/ConstantFolding.h"
62#include "llvm/Analysis/GlobalsModRef.h"
63#include "llvm/Analysis/InstructionSimplify.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000064#include "llvm/Analysis/MemoryBuiltins.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000065#include "llvm/Analysis/MemoryLocation.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000066#include "llvm/Analysis/TargetLibraryInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000067#include "llvm/IR/DataLayout.h"
68#include "llvm/IR/Dominators.h"
69#include "llvm/IR/GlobalVariable.h"
70#include "llvm/IR/IRBuilder.h"
71#include "llvm/IR/IntrinsicInst.h"
72#include "llvm/IR/LLVMContext.h"
73#include "llvm/IR/Metadata.h"
74#include "llvm/IR/PatternMatch.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000075#include "llvm/IR/Type.h"
76#include "llvm/Support/Allocator.h"
77#include "llvm/Support/CommandLine.h"
78#include "llvm/Support/Debug.h"
Daniel Berlin283a6082017-03-01 19:59:26 +000079#include "llvm/Support/DebugCounter.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000080#include "llvm/Transforms/Scalar.h"
81#include "llvm/Transforms/Scalar/GVNExpression.h"
82#include "llvm/Transforms/Utils/BasicBlockUtils.h"
83#include "llvm/Transforms/Utils/Local.h"
84#include "llvm/Transforms/Utils/MemorySSA.h"
Daniel Berlinf7d95802017-02-18 23:06:50 +000085#include "llvm/Transforms/Utils/PredicateInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000086#include <unordered_map>
87#include <utility>
88#include <vector>
89using namespace llvm;
90using namespace PatternMatch;
91using namespace llvm::GVNExpression;
Davide Italiano7e274e02016-12-22 16:03:48 +000092#define DEBUG_TYPE "newgvn"
93
94STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
95STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
96STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
97STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +000098STATISTIC(NumGVNMaxIterations,
99 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000100STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
101STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
102STATISTIC(NumGVNAvoidedSortedLeaderChanges,
103 "Number of avoided sorted leader changes");
Daniel Berlin89fea6f2017-01-20 06:38:41 +0000104STATISTIC(NumGVNNotMostDominatingLeader,
105 "Number of times a member dominated it's new classes' leader");
Daniel Berlinc4796862017-01-27 02:37:11 +0000106STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Daniel Berlin283a6082017-03-01 19:59:26 +0000107DEBUG_COUNTER(VNCounter, "newgvn-vn",
108 "Controls which instructions are value numbered")
Davide Italiano7e274e02016-12-22 16:03:48 +0000109//===----------------------------------------------------------------------===//
110// GVN Pass
111//===----------------------------------------------------------------------===//
112
113// Anchor methods.
114namespace llvm {
115namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000116Expression::~Expression() = default;
117BasicExpression::~BasicExpression() = default;
118CallExpression::~CallExpression() = default;
119LoadExpression::~LoadExpression() = default;
120StoreExpression::~StoreExpression() = default;
121AggregateValueExpression::~AggregateValueExpression() = default;
122PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000123}
124}
125
126// Congruence classes represent the set of expressions/instructions
127// that are all the same *during some scope in the function*.
128// That is, because of the way we perform equality propagation, and
129// because of memory value numbering, it is not correct to assume
130// you can willy-nilly replace any member with any other at any
131// point in the function.
132//
133// For any Value in the Member set, it is valid to replace any dominated member
134// with that Value.
135//
136// Every congruence class has a leader, and the leader is used to
137// symbolize instructions in a canonical way (IE every operand of an
138// instruction that is a member of the same congruence class will
139// always be replaced with leader during symbolization).
140// To simplify symbolization, we keep the leader as a constant if class can be
141// proved to be a constant value.
142// Otherwise, the leader is a randomly chosen member of the value set, it does
143// not matter which one is chosen.
144// Each congruence class also has a defining expression,
145// though the expression may be null. If it exists, it can be used for forward
146// propagation and reassociation of values.
147//
148struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000149 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000150 unsigned ID;
151 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000152 Value *RepLeader = nullptr;
Daniel Berlin26addef2017-01-20 21:04:30 +0000153 // If this is represented by a store, the value.
154 Value *RepStoredValue = nullptr;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000155 // If this class contains MemoryDefs, what is the represented memory state.
156 MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000157 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000158 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000159 // Actual members of this class.
160 MemberSet Members;
161
162 // True if this class has no members left. This is mainly used for assertion
163 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000164 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000165
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000166 // Number of stores in this congruence class.
167 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000168 int StoreCount = 0;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000169
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000170 // The most dominating leader after our current leader, because the member set
171 // is not sorted and is expensive to keep sorted all the time.
172 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
173
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000174 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000175 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000176 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000177};
178
Daniel Berlin06329a92017-03-18 15:41:40 +0000179// Return true if two congruence classes are equivalent to each other. This
180// means
181// that every field but the ID number and the dead field are equivalent.
182bool areClassesEquivalent(const CongruenceClass *A, const CongruenceClass *B) {
183 if (A == B)
184 return true;
185 if ((A && !B) || (B && !A))
186 return false;
187
188 if (std::tie(A->StoreCount, A->RepLeader, A->RepStoredValue,
189 A->RepMemoryAccess) != std::tie(B->StoreCount, B->RepLeader,
190 B->RepStoredValue,
191 B->RepMemoryAccess))
192 return false;
193 if (A->DefiningExpr != B->DefiningExpr)
194 if (!A->DefiningExpr || !B->DefiningExpr ||
195 *A->DefiningExpr != *B->DefiningExpr)
196 return false;
197 // We need some ordered set
198 std::set<Value *> AMembers(A->Members.begin(), A->Members.end());
199 std::set<Value *> BMembers(B->Members.begin(), B->Members.end());
200 return AMembers == BMembers;
201}
202
Davide Italiano7e274e02016-12-22 16:03:48 +0000203namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000204template <> struct DenseMapInfo<const Expression *> {
205 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000206 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000207 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
208 return reinterpret_cast<const Expression *>(Val);
209 }
210 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000211 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000212 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
213 return reinterpret_cast<const Expression *>(Val);
214 }
215 static unsigned getHashValue(const Expression *V) {
216 return static_cast<unsigned>(V->getHashValue());
217 }
218 static bool isEqual(const Expression *LHS, const Expression *RHS) {
219 if (LHS == RHS)
220 return true;
221 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
222 LHS == getEmptyKey() || RHS == getEmptyKey())
223 return false;
224 return *LHS == *RHS;
225 }
226};
Davide Italiano7e274e02016-12-22 16:03:48 +0000227} // end namespace llvm
228
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000229namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000230class NewGVN {
231 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000232 DominatorTree *DT;
Davide Italiano7e274e02016-12-22 16:03:48 +0000233 AssumptionCache *AC;
Daniel Berlin64e68992017-03-12 04:46:45 +0000234 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000235 AliasAnalysis *AA;
236 MemorySSA *MSSA;
237 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000238 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000239 std::unique_ptr<PredicateInfo> PredInfo;
Davide Italiano7e274e02016-12-22 16:03:48 +0000240 BumpPtrAllocator ExpressionAllocator;
241 ArrayRecycler<Value *> ArgRecycler;
242
Daniel Berlin1c087672017-02-11 15:07:01 +0000243 // Number of function arguments, used by ranking
244 unsigned int NumFuncArgs;
245
Davide Italiano7e274e02016-12-22 16:03:48 +0000246 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000247
248 // This class is called INITIAL in the paper. It is the class everything
249 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000250 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000251 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000252 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000253 std::vector<CongruenceClass *> CongruenceClasses;
254 unsigned NextCongruenceNum;
255
256 // Value Mappings.
257 DenseMap<Value *, CongruenceClass *> ValueToClass;
258 DenseMap<Value *, const Expression *> ValueToExpression;
259
Daniel Berlinf7d95802017-02-18 23:06:50 +0000260 // Mapping from predicate info we used to the instructions we used it with.
261 // In order to correctly ensure propagation, we must keep track of what
262 // comparisons we used, so that when the values of the comparisons change, we
263 // propagate the information to the places we used the comparison.
264 DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers;
265
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000266 // A table storing which memorydefs/phis represent a memory state provably
267 // equivalent to another memory state.
268 // We could use the congruence class machinery, but the MemoryAccess's are
269 // abstract memory states, so they can only ever be equivalent to each other,
270 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000271 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000272
Davide Italiano7e274e02016-12-22 16:03:48 +0000273 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000274 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000275 ExpressionClassMap ExpressionToClass;
276
277 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000278 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000279
280 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000281 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000282 DenseSet<BlockEdge> ReachableEdges;
283 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
284
285 // This is a bitvector because, on larger functions, we may have
286 // thousands of touched instructions at once (entire blocks,
287 // instructions with hundreds of uses, etc). Even with optimization
288 // for when we mark whole blocks as touched, when this was a
289 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
290 // the time in GVN just managing this list. The bitvector, on the
291 // other hand, efficiently supports test/set/clear of both
292 // individual and ranges, as well as "find next element" This
293 // enables us to use it as a worklist with essentially 0 cost.
294 BitVector TouchedInstructions;
295
296 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
297 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
298 DominatedInstRange;
299
300#ifndef NDEBUG
301 // Debugging for how many times each block and instruction got processed.
302 DenseMap<const Value *, unsigned> ProcessedCount;
303#endif
304
305 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000306 // This contains a mapping from Instructions to DFS numbers.
307 // The numbering starts at 1. An instruction with DFS number zero
308 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000309 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000310
311 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000312 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000313
314 // Deletion info.
315 SmallPtrSet<Instruction *, 8> InstructionsToErase;
316
317public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000318 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
319 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
320 const DataLayout &DL)
321 : F(F), DT(DT), AC(AC), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
322 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)) {}
323 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000324
325private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000326 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000327 const Expression *createExpression(Instruction *);
328 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000329 PHIExpression *createPHIExpression(Instruction *);
330 const VariableExpression *createVariableExpression(Value *);
331 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000332 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000333 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000334 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000335 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin97718e62017-01-31 22:32:03 +0000336 MemoryAccess *);
337 const CallExpression *createCallExpression(CallInst *, MemoryAccess *);
338 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
339 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000340
341 // Congruence class handling.
342 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000343 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000344 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000345 return result;
346 }
347
348 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000349 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000350 CClass->Members.insert(Member);
351 ValueToClass[Member] = CClass;
352 return CClass;
353 }
354 void initializeCongruenceClasses(Function &F);
355
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000356 // Value number an Instruction or MemoryPhi.
357 void valueNumberMemoryPhi(MemoryPhi *);
358 void valueNumberInstruction(Instruction *);
359
Davide Italiano7e274e02016-12-22 16:03:48 +0000360 // Symbolic evaluation.
361 const Expression *checkSimplificationResults(Expression *, Instruction *,
362 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000363 const Expression *performSymbolicEvaluation(Value *);
364 const Expression *performSymbolicLoadEvaluation(Instruction *);
365 const Expression *performSymbolicStoreEvaluation(Instruction *);
366 const Expression *performSymbolicCallEvaluation(Instruction *);
367 const Expression *performSymbolicPHIEvaluation(Instruction *);
368 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
369 const Expression *performSymbolicCmpEvaluation(Instruction *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000370 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000371
372 // Congruence finding.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000373 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000374 void performCongruenceFinding(Instruction *, const Expression *);
375 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000376 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000377 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
378 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000379 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1c087672017-02-11 15:07:01 +0000380 // Ranking
381 unsigned int getRank(const Value *) const;
382 bool shouldSwapOperands(const Value *, const Value *) const;
383
Davide Italiano7e274e02016-12-22 16:03:48 +0000384 // Reachability handling.
385 void updateReachableEdge(BasicBlock *, BasicBlock *);
386 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000387 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000388
389 // Elimination.
390 struct ValueDFS;
Daniel Berline3e69e12017-03-10 00:32:33 +0000391 void convertClassToDFSOrdered(const CongruenceClass::MemberSet &,
392 SmallVectorImpl<ValueDFS> &,
393 DenseMap<const Value *, unsigned int> &,
394 SmallPtrSetImpl<Instruction *> &);
395 void convertClassToLoadsAndStores(const CongruenceClass::MemberSet &,
Daniel Berlinc4796862017-01-27 02:37:11 +0000396 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000397
398 bool eliminateInstructions(Function &);
399 void replaceInstruction(Instruction *, Value *);
400 void markInstructionForDeletion(Instruction *);
401 void deleteInstructionsInBlock(BasicBlock *);
402
403 // New instruction creation.
404 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000405
406 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000407 void markUsersTouched(Value *);
408 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000409 void markPredicateUsersTouched(Instruction *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000410 void markLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000411 void addPredicateUsers(const PredicateBase *, Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000412
Daniel Berlin06329a92017-03-18 15:41:40 +0000413 // Main loop of value numbering
414 void iterateTouchedInstructions();
415
Davide Italiano7e274e02016-12-22 16:03:48 +0000416 // Utilities.
417 void cleanupTables();
418 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
419 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000420 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000421 void verifyIterationSettled(Function &F);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000422 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000423 BasicBlock *getBlockForValue(Value *V) const;
424 // Debug counter info. When verifying, we have to reset the value numbering
425 // debug counter to the same state it started in to get the same results.
426 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000427};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000428} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000429
Davide Italianob1114092016-12-28 13:37:17 +0000430template <typename T>
431static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
432 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000433 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000434 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000435 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000436 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000437 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000438 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000439 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000440 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000441 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000442 return true;
443}
444
Davide Italianob1114092016-12-28 13:37:17 +0000445bool LoadExpression::equals(const Expression &Other) const {
446 return equalsLoadStoreHelper(*this, Other);
447}
Davide Italiano7e274e02016-12-22 16:03:48 +0000448
Davide Italianob1114092016-12-28 13:37:17 +0000449bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000450 bool Result = equalsLoadStoreHelper(*this, Other);
451 // Make sure that store vs store includes the value operand.
452 if (Result)
453 if (const auto *S = dyn_cast<StoreExpression>(&Other))
454 if (getStoredValue() != S->getStoredValue())
455 return false;
456 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000457}
458
459#ifndef NDEBUG
460static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000461 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000462}
463#endif
464
Daniel Berlin06329a92017-03-18 15:41:40 +0000465// Get the basic block from an instruction/memory value.
466BasicBlock *NewGVN::getBlockForValue(Value *V) const {
467 if (auto *I = dyn_cast<Instruction>(V))
468 return I->getParent();
469 else if (auto *MP = dyn_cast<MemoryPhi>(V))
470 return MP->getBlock();
471 llvm_unreachable("Should have been able to figure out a block for our value");
472 return nullptr;
473}
474
Davide Italiano7e274e02016-12-22 16:03:48 +0000475PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000476 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000477 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000478 auto *E =
479 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000480
481 E->allocateOperands(ArgRecycler, ExpressionAllocator);
482 E->setType(I->getType());
483 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000484
Davide Italianob3886dd2017-01-25 23:37:49 +0000485 // Filter out unreachable phi operands.
486 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +0000487 return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000488 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000489
490 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
491 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000492 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000493 if (U == PN)
494 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000495 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000496 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000497 return E;
498}
499
500// Set basic expression info (Arguments, type, opcode) for Expression
501// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000502bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000503 bool AllConstant = true;
504 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
505 E->setType(GEP->getSourceElementType());
506 else
507 E->setType(I->getType());
508 E->setOpcode(I->getOpcode());
509 E->allocateOperands(ArgRecycler, ExpressionAllocator);
510
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000511 // Transform the operand array into an operand leader array, and keep track of
512 // whether all members are constant.
513 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000514 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000515 AllConstant &= isa<Constant>(Operand);
516 return Operand;
517 });
518
Davide Italiano7e274e02016-12-22 16:03:48 +0000519 return AllConstant;
520}
521
522const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000523 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000524 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000525
526 E->setType(T);
527 E->setOpcode(Opcode);
528 E->allocateOperands(ArgRecycler, ExpressionAllocator);
529 if (Instruction::isCommutative(Opcode)) {
530 // Ensure that commutative instructions that only differ by a permutation
531 // of their operands get the same value number by sorting the operand value
532 // numbers. Since all commutative instructions have two operands it is more
533 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000534 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000535 std::swap(Arg1, Arg2);
536 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000537 E->op_push_back(lookupOperandLeader(Arg1));
538 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000539
Daniel Berlin64e68992017-03-12 04:46:45 +0000540 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), DL, TLI,
Davide Italiano7e274e02016-12-22 16:03:48 +0000541 DT, AC);
542 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
543 return SimplifiedE;
544 return E;
545}
546
547// Take a Value returned by simplification of Expression E/Instruction
548// I, and see if it resulted in a simpler expression. If so, return
549// that expression.
550// TODO: Once finished, this should not take an Instruction, we only
551// use it for printing.
552const Expression *NewGVN::checkSimplificationResults(Expression *E,
553 Instruction *I, Value *V) {
554 if (!V)
555 return nullptr;
556 if (auto *C = dyn_cast<Constant>(V)) {
557 if (I)
558 DEBUG(dbgs() << "Simplified " << *I << " to "
559 << " constant " << *C << "\n");
560 NumGVNOpsSimplified++;
561 assert(isa<BasicExpression>(E) &&
562 "We should always have had a basic expression here");
563
564 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
565 ExpressionAllocator.Deallocate(E);
566 return createConstantExpression(C);
567 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
568 if (I)
569 DEBUG(dbgs() << "Simplified " << *I << " to "
570 << " variable " << *V << "\n");
571 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
572 ExpressionAllocator.Deallocate(E);
573 return createVariableExpression(V);
574 }
575
576 CongruenceClass *CC = ValueToClass.lookup(V);
577 if (CC && CC->DefiningExpr) {
578 if (I)
579 DEBUG(dbgs() << "Simplified " << *I << " to "
580 << " expression " << *V << "\n");
581 NumGVNOpsSimplified++;
582 assert(isa<BasicExpression>(E) &&
583 "We should always have had a basic expression here");
584 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
585 ExpressionAllocator.Deallocate(E);
586 return CC->DefiningExpr;
587 }
588 return nullptr;
589}
590
Daniel Berlin97718e62017-01-31 22:32:03 +0000591const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000592 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000593
Daniel Berlin97718e62017-01-31 22:32:03 +0000594 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000595
596 if (I->isCommutative()) {
597 // Ensure that commutative instructions that only differ by a permutation
598 // of their operands get the same value number by sorting the operand value
599 // numbers. Since all commutative instructions have two operands it is more
600 // efficient to sort by hand rather than using, say, std::sort.
601 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000602 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000603 E->swapOperands(0, 1);
604 }
605
606 // Perform simplificaiton
607 // TODO: Right now we only check to see if we get a constant result.
608 // We may get a less than constant, but still better, result for
609 // some operations.
610 // IE
611 // add 0, x -> x
612 // and x, x -> x
613 // We should handle this by simply rewriting the expression.
614 if (auto *CI = dyn_cast<CmpInst>(I)) {
615 // Sort the operand value numbers so x<y and y>x get the same value
616 // number.
617 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000618 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000619 E->swapOperands(0, 1);
620 Predicate = CmpInst::getSwappedPredicate(Predicate);
621 }
622 E->setOpcode((CI->getOpcode() << 8) | Predicate);
623 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000624 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
625 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000626 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
627 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000628 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000629 DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000630 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
631 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000632 } else if (isa<SelectInst>(I)) {
633 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000634 E->getOperand(0) == E->getOperand(1)) {
635 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
636 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000637 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000638 E->getOperand(2), DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000639 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
640 return SimplifiedE;
641 }
642 } else if (I->isBinaryOp()) {
643 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000644 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000645 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
646 return SimplifiedE;
647 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin64e68992017-03-12 04:46:45 +0000648 Value *V = SimplifyInstruction(BI, DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000649 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
650 return SimplifiedE;
651 } else if (isa<GetElementPtrInst>(I)) {
652 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000653 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Daniel Berlin64e68992017-03-12 04:46:45 +0000654 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000655 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
656 return SimplifiedE;
657 } else if (AllConstant) {
658 // We don't bother trying to simplify unless all of the operands
659 // were constant.
660 // TODO: There are a lot of Simplify*'s we could call here, if we
661 // wanted to. The original motivating case for this code was a
662 // zext i1 false to i8, which we don't have an interface to
663 // simplify (IE there is no SimplifyZExt).
664
665 SmallVector<Constant *, 8> C;
666 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000667 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000668
Daniel Berlin64e68992017-03-12 04:46:45 +0000669 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
671 return SimplifiedE;
672 }
673 return E;
674}
675
676const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000677NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000678 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000679 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000680 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000681 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000682 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000683 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000684 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000685 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000686 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000687 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000688 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000689 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000690 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000691 return E;
692 }
693 llvm_unreachable("Unhandled type of aggregate value operation");
694}
695
Daniel Berlin85f91b02016-12-26 20:06:58 +0000696const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000697 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000698 E->setOpcode(V->getValueID());
699 return E;
700}
701
Daniel Berlinf7d95802017-02-18 23:06:50 +0000702const Expression *NewGVN::createVariableOrConstant(Value *V) {
703 if (auto *C = dyn_cast<Constant>(V))
704 return createConstantExpression(C);
705 return createVariableExpression(V);
706}
707
Daniel Berlin85f91b02016-12-26 20:06:58 +0000708const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000709 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000710 E->setOpcode(C->getValueID());
711 return E;
712}
713
Daniel Berlin02c6b172017-01-02 18:00:53 +0000714const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
715 auto *E = new (ExpressionAllocator) UnknownExpression(I);
716 E->setOpcode(I->getOpcode());
717 return E;
718}
719
Davide Italiano7e274e02016-12-22 16:03:48 +0000720const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000721 MemoryAccess *HV) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000722 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000723 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000724 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
Daniel Berlin97718e62017-01-31 22:32:03 +0000725 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000726 return E;
727}
728
729// See if we have a congruence class and leader for this operand, and if so,
730// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000731Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000732 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000733 if (CC) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000734 // Everything in TOP is represneted by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000735 // We do have to make sure we get the type right though, so we can't set the
736 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000737 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +0000738 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000739 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000740 }
741
Davide Italiano7e274e02016-12-22 16:03:48 +0000742 return V;
743}
744
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000745MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000746 auto *CC = MemoryAccessToClass.lookup(MA);
747 if (CC && CC->RepMemoryAccess)
748 return CC->RepMemoryAccess;
749 // FIXME: We need to audit all the places that current set a nullptr To, and
750 // fix them. There should always be *some* congruence class, even if it is
751 // singular. Right now, we don't bother setting congruence classes for
752 // anything but stores, which means we have to return the original access
753 // here. Otherwise, this should be unreachable.
754 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000755}
756
Daniel Berlinc4796862017-01-27 02:37:11 +0000757// Return true if the MemoryAccess is really equivalent to everything. This is
758// equivalent to the lattice value "TOP" in most lattices. This is the initial
759// state of all memory accesses.
760bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000761 return MemoryAccessToClass.lookup(MA) == TOPClass;
Daniel Berlinc4796862017-01-27 02:37:11 +0000762}
763
Davide Italiano7e274e02016-12-22 16:03:48 +0000764LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin97718e62017-01-31 22:32:03 +0000765 LoadInst *LI, MemoryAccess *DA) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000766 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000767 E->allocateOperands(ArgRecycler, ExpressionAllocator);
768 E->setType(LoadType);
769
770 // Give store and loads same opcode so they value number together.
771 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000772 E->op_push_back(lookupOperandLeader(PointerOp));
Davide Italiano7e274e02016-12-22 16:03:48 +0000773 if (LI)
774 E->setAlignment(LI->getAlignment());
775
776 // TODO: Value number heap versions. We may be able to discover
777 // things alias analysis can't on it's own (IE that a store and a
778 // load have the same value, and thus, it isn't clobbering the load).
779 return E;
780}
781
782const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000783 MemoryAccess *DA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000784 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000785 auto *E = new (ExpressionAllocator)
786 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000787 E->allocateOperands(ArgRecycler, ExpressionAllocator);
788 E->setType(SI->getValueOperand()->getType());
789
790 // Give store and loads same opcode so they value number together.
791 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000792 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000793
794 // TODO: Value number heap versions. We may be able to discover
795 // things alias analysis can't on it's own (IE that a store and a
796 // load have the same value, and thus, it isn't clobbering the load).
797 return E;
798}
799
Daniel Berlin97718e62017-01-31 22:32:03 +0000800const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000801 // Unlike loads, we never try to eliminate stores, so we do not check if they
802 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000803 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000804 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000805 // Get the expression, if any, for the RHS of the MemoryDef.
806 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
807 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
808 // If we are defined by ourselves, use the live on entry def.
809 if (StoreRHS == StoreAccess)
810 StoreRHS = MSSA->getLiveOnEntryDef();
811
Daniel Berlin589cecc2017-01-02 18:00:46 +0000812 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000813 // See if we are defined by a previous store expression, it already has a
814 // value, and it's the same value as our current store. FIXME: Right now, we
815 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin97718e62017-01-31 22:32:03 +0000816 const Expression *OldStore = createStoreExpression(SI, StoreRHS);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000817 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000818 // Basically, check if the congruence class the store is in is defined by a
819 // store that isn't us, and has the same value. MemorySSA takes care of
820 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000821 // The RepStoredValue gets nulled if all the stores disappear in a class, so
822 // we don't need to check if the class contains a store besides us.
Daniel Berlin808e3ff2017-01-31 22:31:56 +0000823 if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin97718e62017-01-31 22:32:03 +0000824 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +0000825 // Also check if our value operand is defined by a load of the same memory
826 // location, and the memory state is the same as it was then
827 // (otherwise, it could have been overwritten later. See test32 in
828 // transforms/DeadStoreElimination/simple.ll)
829 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000830 if ((lookupOperandLeader(LI->getPointerOperand()) ==
831 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinc4796862017-01-27 02:37:11 +0000832 (lookupMemoryAccessEquiv(
833 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
834 return createVariableExpression(LI);
835 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000836 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000837 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000838}
839
Daniel Berlin97718e62017-01-31 22:32:03 +0000840const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000841 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000842
843 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000844 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000845 if (!LI->isSimple())
846 return nullptr;
847
Daniel Berlin203f47b2017-01-31 22:31:53 +0000848 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +0000849 // Load of undef is undef.
850 if (isa<UndefValue>(LoadAddressLeader))
851 return createConstantExpression(UndefValue::get(LI->getType()));
852
853 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
854
855 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
856 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
857 Instruction *DefiningInst = MD->getMemoryInst();
858 // If the defining instruction is not reachable, replace with undef.
859 if (!ReachableBlocks.count(DefiningInst->getParent()))
860 return createConstantExpression(UndefValue::get(LI->getType()));
861 }
862 }
863
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000864 const Expression *E =
865 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000866 lookupMemoryAccessEquiv(DefiningAccess));
Davide Italiano7e274e02016-12-22 16:03:48 +0000867 return E;
868}
869
Daniel Berlinf7d95802017-02-18 23:06:50 +0000870const Expression *
871NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
872 auto *PI = PredInfo->getPredicateInfoFor(I);
873 if (!PI)
874 return nullptr;
875
876 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +0000877
878 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
879 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +0000880 return nullptr;
881
Daniel Berlinfccbda92017-02-22 22:20:58 +0000882 auto *CopyOf = I->getOperand(0);
883 auto *Cond = PWC->Condition;
884
Daniel Berlinf7d95802017-02-18 23:06:50 +0000885 // If this a copy of the condition, it must be either true or false depending
886 // on the predicate info type and edge
887 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +0000888 // We should not need to add predicate users because the predicate info is
889 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +0000890 if (isa<PredicateAssume>(PI))
891 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
892 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
893 if (PBranch->TrueEdge)
894 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
895 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
896 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000897 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
898 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000899 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000900
Daniel Berlinf7d95802017-02-18 23:06:50 +0000901 // Not a copy of the condition, so see what the predicates tell us about this
902 // value. First, though, we check to make sure the value is actually a copy
903 // of one of the condition operands. It's possible, in certain cases, for it
904 // to be a copy of a predicateinfo copy. In particular, if two branch
905 // operations use the same condition, and one branch dominates the other, we
906 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +0000907 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +0000908 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000909
910 // Everything below relies on the condition being a comparison.
911 auto *Cmp = dyn_cast<CmpInst>(Cond);
912 if (!Cmp)
913 return nullptr;
914
915 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +0000916 DEBUG(dbgs() << "Copy is not of any condition operands!");
917 return nullptr;
918 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000919 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
920 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000921 bool SwappedOps = false;
922 // Sort the ops
923 if (shouldSwapOperands(FirstOp, SecondOp)) {
924 std::swap(FirstOp, SecondOp);
925 SwappedOps = true;
926 }
Daniel Berlinf7d95802017-02-18 23:06:50 +0000927 CmpInst::Predicate Predicate =
928 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
929
930 if (isa<PredicateAssume>(PI)) {
931 // If the comparison is true when the operands are equal, then we know the
932 // operands are equal, because assumes must always be true.
933 if (CmpInst::isTrueWhenEqual(Predicate)) {
934 addPredicateUsers(PI, I);
935 return createVariableOrConstant(FirstOp);
936 }
937 }
938 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
939 // If we are *not* a copy of the comparison, we may equal to the other
940 // operand when the predicate implies something about equality of
941 // operations. In particular, if the comparison is true/false when the
942 // operands are equal, and we are on the right edge, we know this operation
943 // is equal to something.
944 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
945 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
946 addPredicateUsers(PI, I);
947 return createVariableOrConstant(FirstOp);
948 }
949 // Handle the special case of floating point.
950 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
951 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
952 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
953 addPredicateUsers(PI, I);
954 return createConstantExpression(cast<Constant>(FirstOp));
955 }
956 }
957 return nullptr;
958}
959
Davide Italiano7e274e02016-12-22 16:03:48 +0000960// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000961const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000962 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000963 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
964 // Instrinsics with the returned attribute are copies of arguments.
965 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
966 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
967 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
968 return Result;
969 return createVariableOrConstant(ReturnedValue);
970 }
971 }
972 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlin97718e62017-01-31 22:32:03 +0000973 return createCallExpression(CI, nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000974 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000975 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin97718e62017-01-31 22:32:03 +0000976 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
Davide Italianob2225492016-12-27 18:15:39 +0000977 }
978 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000979}
980
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000981// Update the memory access equivalence table to say that From is equal to To,
982// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000983// FIXME: We need to audit all the places that current set a nullptr To, and fix
984// them. There should always be *some* congruence class, even if it is singular.
985bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
986 DEBUG(dbgs() << "Setting " << *From);
987 if (To) {
988 DEBUG(dbgs() << " equivalent to congruence class ");
989 DEBUG(dbgs() << To->ID << " with current memory access leader ");
990 DEBUG(dbgs() << *To->RepMemoryAccess);
991 } else {
992 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000993 }
Daniel Berlin9f376b72017-01-29 10:26:03 +0000994 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000995
996 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000997 bool Changed = false;
998 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000999 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001000 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001001 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001002 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001003 Changed = true;
1004 } else if (!To) {
1005 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001006 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001007 Changed = true;
1008 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001009 } else {
1010 assert(!To &&
1011 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001012 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001013
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001014 return Changed;
1015}
Davide Italiano7e274e02016-12-22 16:03:48 +00001016// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001017const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001018 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001019 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1020
1021 // See if all arguaments are the same.
1022 // We track if any were undef because they need special handling.
1023 bool HasUndef = false;
1024 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1025 if (Arg == I)
1026 return false;
1027 if (isa<UndefValue>(Arg)) {
1028 HasUndef = true;
1029 return false;
1030 }
1031 return true;
1032 });
1033 // If we are left with no operands, it's undef
1034 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001035 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1036 << "\n");
1037 E->deallocateOperands(ArgRecycler);
1038 ExpressionAllocator.Deallocate(E);
1039 return createConstantExpression(UndefValue::get(I->getType()));
1040 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001041 Value *AllSameValue = *(Filtered.begin());
1042 ++Filtered.begin();
1043 // Can't use std::equal here, sadly, because filter.begin moves.
1044 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
1045 return V == AllSameValue;
1046 })) {
1047 // In LLVM's non-standard representation of phi nodes, it's possible to have
1048 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1049 // on the original phi node), especially in weird CFG's where some arguments
1050 // are unreachable, or uninitialized along certain paths. This can cause
1051 // infinite loops during evaluation. We work around this by not trying to
1052 // really evaluate them independently, but instead using a variable
1053 // expression to say if one is equivalent to the other.
1054 // We also special case undef, so that if we have an undef, we can't use the
1055 // common value unless it dominates the phi block.
1056 if (HasUndef) {
1057 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001058 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001059 if (!DT->dominates(AllSameInst, I))
1060 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001061 }
1062
Davide Italiano7e274e02016-12-22 16:03:48 +00001063 NumGVNPhisAllSame++;
1064 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1065 << "\n");
1066 E->deallocateOperands(ArgRecycler);
1067 ExpressionAllocator.Deallocate(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001068 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001069 }
1070 return E;
1071}
1072
Daniel Berlin97718e62017-01-31 22:32:03 +00001073const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001074 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1075 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1076 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1077 unsigned Opcode = 0;
1078 // EI might be an extract from one of our recognised intrinsics. If it
1079 // is we'll synthesize a semantically equivalent expression instead on
1080 // an extract value expression.
1081 switch (II->getIntrinsicID()) {
1082 case Intrinsic::sadd_with_overflow:
1083 case Intrinsic::uadd_with_overflow:
1084 Opcode = Instruction::Add;
1085 break;
1086 case Intrinsic::ssub_with_overflow:
1087 case Intrinsic::usub_with_overflow:
1088 Opcode = Instruction::Sub;
1089 break;
1090 case Intrinsic::smul_with_overflow:
1091 case Intrinsic::umul_with_overflow:
1092 Opcode = Instruction::Mul;
1093 break;
1094 default:
1095 break;
1096 }
1097
1098 if (Opcode != 0) {
1099 // Intrinsic recognized. Grab its args to finish building the
1100 // expression.
1101 assert(II->getNumArgOperands() == 2 &&
1102 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001103 return createBinaryExpression(
1104 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001105 }
1106 }
1107 }
1108
Daniel Berlin97718e62017-01-31 22:32:03 +00001109 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001110}
Daniel Berlin97718e62017-01-31 22:32:03 +00001111const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001112 auto *CI = dyn_cast<CmpInst>(I);
1113 // See if our operands are equal to those of a previous predicate, and if so,
1114 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001115 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1116 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001117 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001118 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001119 std::swap(Op0, Op1);
1120 OurPredicate = CI->getSwappedPredicate();
1121 }
1122
1123 // Avoid processing the same info twice
1124 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001125 // See if we know something about the comparison itself, like it is the target
1126 // of an assume.
1127 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1128 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1129 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1130
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001131 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001132 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001133 if (CI->isTrueWhenEqual())
1134 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1135 else if (CI->isFalseWhenEqual())
1136 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1137 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001138
1139 // NOTE: Because we are comparing both operands here and below, and using
1140 // previous comparisons, we rely on fact that predicateinfo knows to mark
1141 // comparisons that use renamed operands as users of the earlier comparisons.
1142 // It is *not* enough to just mark predicateinfo renamed operands as users of
1143 // the earlier comparisons, because the *other* operand may have changed in a
1144 // previous iteration.
1145 // Example:
1146 // icmp slt %a, %b
1147 // %b.0 = ssa.copy(%b)
1148 // false branch:
1149 // icmp slt %c, %b.0
1150
1151 // %c and %a may start out equal, and thus, the code below will say the second
1152 // %icmp is false. c may become equal to something else, and in that case the
1153 // %second icmp *must* be reexamined, but would not if only the renamed
1154 // %operands are considered users of the icmp.
1155
1156 // *Currently* we only check one level of comparisons back, and only mark one
1157 // level back as touched when changes appen . If you modify this code to look
1158 // back farther through comparisons, you *must* mark the appropriate
1159 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1160 // we know something just from the operands themselves
1161
1162 // See if our operands have predicate info, so that we may be able to derive
1163 // something from a previous comparison.
1164 for (const auto &Op : CI->operands()) {
1165 auto *PI = PredInfo->getPredicateInfoFor(Op);
1166 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1167 if (PI == LastPredInfo)
1168 continue;
1169 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001170
Daniel Berlinf7d95802017-02-18 23:06:50 +00001171 // TODO: Along the false edge, we may know more things too, like icmp of
1172 // same operands is false.
1173 // TODO: We only handle actual comparison conditions below, not and/or.
1174 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1175 if (!BranchCond)
1176 continue;
1177 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1178 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1179 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001180 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001181 std::swap(BranchOp0, BranchOp1);
1182 BranchPredicate = BranchCond->getSwappedPredicate();
1183 }
1184 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1185 if (PBranch->TrueEdge) {
1186 // If we know the previous predicate is true and we are in the true
1187 // edge then we may be implied true or false.
1188 if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate,
1189 BranchPredicate)) {
1190 addPredicateUsers(PI, I);
1191 return createConstantExpression(
1192 ConstantInt::getTrue(CI->getType()));
1193 }
1194
1195 if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate,
1196 BranchPredicate)) {
1197 addPredicateUsers(PI, I);
1198 return createConstantExpression(
1199 ConstantInt::getFalse(CI->getType()));
1200 }
1201
1202 } else {
1203 // Just handle the ne and eq cases, where if we have the same
1204 // operands, we may know something.
1205 if (BranchPredicate == OurPredicate) {
1206 addPredicateUsers(PI, I);
1207 // Same predicate, same ops,we know it was false, so this is false.
1208 return createConstantExpression(
1209 ConstantInt::getFalse(CI->getType()));
1210 } else if (BranchPredicate ==
1211 CmpInst::getInversePredicate(OurPredicate)) {
1212 addPredicateUsers(PI, I);
1213 // Inverse predicate, we know the other was false, so this is true.
1214 // FIXME: Double check this
1215 return createConstantExpression(
1216 ConstantInt::getTrue(CI->getType()));
1217 }
1218 }
1219 }
1220 }
1221 }
1222 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001223 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001224}
Davide Italiano7e274e02016-12-22 16:03:48 +00001225
1226// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001227const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001228 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001229 if (auto *C = dyn_cast<Constant>(V))
1230 E = createConstantExpression(C);
1231 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1232 E = createVariableExpression(V);
1233 } else {
1234 // TODO: memory intrinsics.
1235 // TODO: Some day, we should do the forward propagation and reassociation
1236 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001237 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001238 switch (I->getOpcode()) {
1239 case Instruction::ExtractValue:
1240 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001241 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001242 break;
1243 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001244 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001245 break;
1246 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001247 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001248 break;
1249 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001250 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001251 break;
1252 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001253 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001254 break;
1255 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001256 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001257 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001258 case Instruction::ICmp:
1259 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001260 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001261 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001262 case Instruction::Add:
1263 case Instruction::FAdd:
1264 case Instruction::Sub:
1265 case Instruction::FSub:
1266 case Instruction::Mul:
1267 case Instruction::FMul:
1268 case Instruction::UDiv:
1269 case Instruction::SDiv:
1270 case Instruction::FDiv:
1271 case Instruction::URem:
1272 case Instruction::SRem:
1273 case Instruction::FRem:
1274 case Instruction::Shl:
1275 case Instruction::LShr:
1276 case Instruction::AShr:
1277 case Instruction::And:
1278 case Instruction::Or:
1279 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001280 case Instruction::Trunc:
1281 case Instruction::ZExt:
1282 case Instruction::SExt:
1283 case Instruction::FPToUI:
1284 case Instruction::FPToSI:
1285 case Instruction::UIToFP:
1286 case Instruction::SIToFP:
1287 case Instruction::FPTrunc:
1288 case Instruction::FPExt:
1289 case Instruction::PtrToInt:
1290 case Instruction::IntToPtr:
1291 case Instruction::Select:
1292 case Instruction::ExtractElement:
1293 case Instruction::InsertElement:
1294 case Instruction::ShuffleVector:
1295 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001296 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001297 break;
1298 default:
1299 return nullptr;
1300 }
1301 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001302 return E;
1303}
1304
Davide Italiano7e274e02016-12-22 16:03:48 +00001305void NewGVN::markUsersTouched(Value *V) {
1306 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001307 for (auto *User : V->users()) {
1308 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001309 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001310 }
1311}
1312
1313void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1314 for (auto U : MA->users()) {
1315 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001316 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001317 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001318 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001319 }
1320}
1321
Daniel Berlinf7d95802017-02-18 23:06:50 +00001322// Add I to the set of users of a given predicate.
1323void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1324 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1325 PredicateToUsers[PBranch->Condition].insert(I);
1326 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1327 PredicateToUsers[PAssume->Condition].insert(I);
1328}
1329
1330// Touch all the predicates that depend on this instruction.
1331void NewGVN::markPredicateUsersTouched(Instruction *I) {
1332 const auto Result = PredicateToUsers.find(I);
1333 if (Result != PredicateToUsers.end())
1334 for (auto *User : Result->second)
1335 TouchedInstructions.set(InstrDFS.lookup(User));
1336}
1337
Daniel Berlin32f8d562017-01-07 16:55:14 +00001338// Touch the instructions that need to be updated after a congruence class has a
1339// leader change, and mark changed values.
1340void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1341 for (auto M : CC->Members) {
1342 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001343 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001344 LeaderChanges.insert(M);
1345 }
1346}
1347
1348// Move a value, currently in OldClass, to be part of NewClass
1349// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001350void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1351 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001352 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001353 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001354 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001355
1356 if (I == OldClass->NextLeader.first)
1357 OldClass->NextLeader = {nullptr, ~0U};
1358
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001359 // It's possible, though unlikely, for us to discover equivalences such
1360 // that the current leader does not dominate the old one.
1361 // This statistic tracks how often this happens.
1362 // We assert on phi nodes when this happens, currently, for debugging, because
1363 // we want to make sure we name phi node cycles properly.
1364 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1365 I != NewClass->RepLeader &&
1366 DT->properlyDominates(
1367 I->getParent(),
1368 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1369 ++NumGVNNotMostDominatingLeader;
1370 assert(!isa<PHINode>(I) &&
1371 "New class for instruction should not be dominated by instruction");
1372 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001373
1374 if (NewClass->RepLeader != I) {
1375 auto DFSNum = InstrDFS.lookup(I);
1376 if (DFSNum < NewClass->NextLeader.second)
1377 NewClass->NextLeader = {I, DFSNum};
1378 }
1379
1380 OldClass->Members.erase(I);
1381 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001382 MemoryAccess *StoreAccess = nullptr;
1383 if (auto *SI = dyn_cast<StoreInst>(I)) {
1384 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001385 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001386 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001387 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001388 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001389 if (!NewClass->RepMemoryAccess) {
1390 // If we don't have a representative memory access, it better be the only
1391 // store in there.
1392 assert(NewClass->StoreCount == 1);
1393 NewClass->RepMemoryAccess = StoreAccess;
1394 }
1395 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001396 }
1397
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001398 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001399 // See if we destroyed the class or need to swap leaders.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001400 if (OldClass->Members.empty() && OldClass != TOPClass) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001401 if (OldClass->DefiningExpr) {
1402 OldClass->Dead = true;
1403 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1404 << " from table\n");
1405 ExpressionToClass.erase(OldClass->DefiningExpr);
1406 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001407 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001408 // When the leader changes, the value numbering of
1409 // everything may change due to symbolization changes, so we need to
1410 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001411 DEBUG(dbgs() << "Leader change!\n");
1412 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001413 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001414 if (OldClass->StoreCount == 0) {
1415 if (OldClass->RepStoredValue != nullptr)
1416 OldClass->RepStoredValue = nullptr;
1417 if (OldClass->RepMemoryAccess != nullptr)
1418 OldClass->RepMemoryAccess = nullptr;
1419 }
1420
1421 // If we destroy the old access leader, we have to effectively destroy the
1422 // congruence class. When it comes to scalars, anything with the same value
1423 // is as good as any other. That means that one leader is as good as
1424 // another, and as long as you have some leader for the value, you are
1425 // good.. When it comes to *memory states*, only one particular thing really
1426 // represents the definition of a given memory state. Once it goes away, we
1427 // need to re-evaluate which pieces of memory are really still
1428 // equivalent. The best way to do this is to re-value number things. The
1429 // only way to really make that happen is to destroy the rest of the class.
1430 // In order to effectively destroy the class, we reset ExpressionToClass for
1431 // each by using the ValueToExpression mapping. The members later get
1432 // marked as touched due to the leader change. We will create new
1433 // congruence classes, and the pieces that are still equivalent will end
1434 // back together in a new class. If this becomes too expensive, it is
1435 // possible to use a versioning scheme for the congruence classes to avoid
1436 // the expressions finding this old class.
1437 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1438 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1439 << " because memory access leader changed");
1440 for (auto Member : OldClass->Members)
1441 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1442 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001443
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001444 // We don't need to sort members if there is only 1, and we don't care about
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001445 // sorting the TOP class because everything either gets out of it or is
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001446 // unreachable.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001447 if (OldClass->Members.size() == 1 || OldClass == TOPClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001448 OldClass->RepLeader = *(OldClass->Members.begin());
1449 } else if (OldClass->NextLeader.first) {
1450 ++NumGVNAvoidedSortedLeaderChanges;
1451 OldClass->RepLeader = OldClass->NextLeader.first;
1452 OldClass->NextLeader = {nullptr, ~0U};
1453 } else {
1454 ++NumGVNSortedLeaderChanges;
1455 // TODO: If this ends up to slow, we can maintain a dual structure for
1456 // member testing/insertion, or keep things mostly sorted, and sort only
1457 // here, or ....
1458 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1459 for (const auto X : OldClass->Members) {
1460 auto DFSNum = InstrDFS.lookup(X);
1461 if (DFSNum < MinDFS.second)
1462 MinDFS = {X, DFSNum};
1463 }
1464 OldClass->RepLeader = MinDFS.first;
1465 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001466 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001467 }
1468}
1469
Davide Italiano7e274e02016-12-22 16:03:48 +00001470// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001471void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1472 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001473 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001474 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001475
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001476 CongruenceClass *IClass = ValueToClass[I];
1477 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001478 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001479 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001480
1481 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001482 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001483 EClass = ValueToClass[VE->getVariableValue()];
1484 } else {
1485 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1486
1487 // If it's not in the value table, create a new congruence class.
1488 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001489 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001490 auto place = lookupResult.first;
1491 place->second = NewClass;
1492
1493 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001494 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001495 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001496 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1497 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001498 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001499 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001500 // The RepMemoryAccess field will be filled in properly by the
1501 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001502 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001503 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001504 }
1505 assert(!isa<VariableExpression>(E) &&
1506 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001507
1508 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001509 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001510 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001511 << " and leader " << *(NewClass->RepLeader));
1512 if (NewClass->RepStoredValue)
1513 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1514 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001515 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1516 } else {
1517 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001518 if (isa<ConstantExpression>(E))
1519 assert(isa<Constant>(EClass->RepLeader) &&
1520 "Any class with a constant expression should have a "
1521 "constant leader");
1522
Davide Italiano7e274e02016-12-22 16:03:48 +00001523 assert(EClass && "Somehow don't have an eclass");
1524
1525 assert(!EClass->Dead && "We accidentally looked up a dead class");
1526 }
1527 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001528 bool ClassChanged = IClass != EClass;
1529 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001530 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001531 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1532 << "\n");
1533
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001534 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001535 moveValueToNewCongruenceClass(I, IClass, EClass);
1536 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001537 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001538 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001539 if (auto *CI = dyn_cast<CmpInst>(I))
1540 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00001541 }
1542}
1543
1544// Process the fact that Edge (from, to) is reachable, including marking
1545// any newly reachable blocks and instructions for processing.
1546void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1547 // Check if the Edge was reachable before.
1548 if (ReachableEdges.insert({From, To}).second) {
1549 // If this block wasn't reachable before, all instructions are touched.
1550 if (ReachableBlocks.insert(To).second) {
1551 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1552 const auto &InstRange = BlockInstRange.lookup(To);
1553 TouchedInstructions.set(InstRange.first, InstRange.second);
1554 } else {
1555 DEBUG(dbgs() << "Block " << getBlockName(To)
1556 << " was reachable, but new edge {" << getBlockName(From)
1557 << "," << getBlockName(To) << "} to it found\n");
1558
1559 // We've made an edge reachable to an existing block, which may
1560 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1561 // they are the only thing that depend on new edges. Anything using their
1562 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001563 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001564 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001565
Davide Italiano7e274e02016-12-22 16:03:48 +00001566 auto BI = To->begin();
1567 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001568 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001569 ++BI;
1570 }
1571 }
1572 }
1573}
1574
1575// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1576// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001577Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001578 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001579 if (isa<Constant>(Result))
1580 return Result;
1581 return nullptr;
1582}
1583
1584// Process the outgoing edges of a block for reachability.
1585void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1586 // Evaluate reachability of terminator instruction.
1587 BranchInst *BR;
1588 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1589 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001590 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001591 if (!CondEvaluated) {
1592 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001593 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001594 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1595 CondEvaluated = CE->getConstantValue();
1596 }
1597 } else if (isa<ConstantInt>(Cond)) {
1598 CondEvaluated = Cond;
1599 }
1600 }
1601 ConstantInt *CI;
1602 BasicBlock *TrueSucc = BR->getSuccessor(0);
1603 BasicBlock *FalseSucc = BR->getSuccessor(1);
1604 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1605 if (CI->isOne()) {
1606 DEBUG(dbgs() << "Condition for Terminator " << *TI
1607 << " evaluated to true\n");
1608 updateReachableEdge(B, TrueSucc);
1609 } else if (CI->isZero()) {
1610 DEBUG(dbgs() << "Condition for Terminator " << *TI
1611 << " evaluated to false\n");
1612 updateReachableEdge(B, FalseSucc);
1613 }
1614 } else {
1615 updateReachableEdge(B, TrueSucc);
1616 updateReachableEdge(B, FalseSucc);
1617 }
1618 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1619 // For switches, propagate the case values into the case
1620 // destinations.
1621
1622 // Remember how many outgoing edges there are to every successor.
1623 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1624
Davide Italiano7e274e02016-12-22 16:03:48 +00001625 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001626 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001627 // See if we were able to turn this switch statement into a constant.
1628 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001629 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001630 // We should be able to get case value for this.
1631 auto CaseVal = SI->findCaseValue(CondVal);
1632 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1633 // We proved the value is outside of the range of the case.
1634 // We can't do anything other than mark the default dest as reachable,
1635 // and go home.
1636 updateReachableEdge(B, SI->getDefaultDest());
1637 return;
1638 }
1639 // Now get where it goes and mark it reachable.
1640 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1641 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001642 } else {
1643 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1644 BasicBlock *TargetBlock = SI->getSuccessor(i);
1645 ++SwitchEdges[TargetBlock];
1646 updateReachableEdge(B, TargetBlock);
1647 }
1648 }
1649 } else {
1650 // Otherwise this is either unconditional, or a type we have no
1651 // idea about. Just mark successors as reachable.
1652 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1653 BasicBlock *TargetBlock = TI->getSuccessor(i);
1654 updateReachableEdge(B, TargetBlock);
1655 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001656
1657 // This also may be a memory defining terminator, in which case, set it
1658 // equivalent to nothing.
1659 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1660 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001661 }
1662}
1663
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001664// The algorithm initially places the values of the routine in the TOP
1665// congruence class. The leader of TOP is the undetermined value `undef`.
1666// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00001667void NewGVN::initializeCongruenceClasses(Function &F) {
1668 // FIXME now i can't remember why this is 2
1669 NextCongruenceNum = 2;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001670 // Initialize all other instructions to be in TOP class.
Davide Italiano7e274e02016-12-22 16:03:48 +00001671 CongruenceClass::MemberSet InitialValues;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001672 TOPClass = createCongruenceClass(nullptr, nullptr);
1673 TOPClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001674 for (auto &B : F) {
1675 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001676 MemoryAccessToClass[MP] = TOPClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001677
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001678 for (auto &I : B) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00001679 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001680 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00001681 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
1682 continue;
1683 InitialValues.insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001684 ValueToClass[&I] = TOPClass;
Daniel Berlin22a4a012017-02-11 15:20:15 +00001685
Daniel Berlin589cecc2017-01-02 18:00:46 +00001686 // All memory accesses are equivalent to live on entry to start. They must
1687 // be initialized to something so that initial changes are noticed. For
1688 // the maximal answer, we initialize them all to be the same as
1689 // liveOnEntry. Note that to save time, we only initialize the
1690 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1691 // other expression can generate a memory equivalence. If we start
1692 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001693 if (isa<StoreInst>(&I)) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001694 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = TOPClass;
1695 ++TOPClass->StoreCount;
1696 assert(TOPClass->StoreCount > 0);
Davide Italianoeac05f62017-01-11 23:41:24 +00001697 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001698 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001699 }
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001700 TOPClass->Members.swap(InitialValues);
Davide Italiano7e274e02016-12-22 16:03:48 +00001701
1702 // Initialize arguments to be in their own unique congruence classes
1703 for (auto &FA : F.args())
1704 createSingletonCongruenceClass(&FA);
1705}
1706
1707void NewGVN::cleanupTables() {
1708 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1709 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1710 << CongruenceClasses[i]->Members.size() << " members\n");
1711 // Make sure we delete the congruence class (probably worth switching to
1712 // a unique_ptr at some point.
1713 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001714 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001715 }
1716
1717 ValueToClass.clear();
1718 ArgRecycler.clear(ExpressionAllocator);
1719 ExpressionAllocator.Reset();
1720 CongruenceClasses.clear();
1721 ExpressionToClass.clear();
1722 ValueToExpression.clear();
1723 ReachableBlocks.clear();
1724 ReachableEdges.clear();
1725#ifndef NDEBUG
1726 ProcessedCount.clear();
1727#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001728 InstrDFS.clear();
1729 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001730 DFSToInstr.clear();
1731 BlockInstRange.clear();
1732 TouchedInstructions.clear();
1733 DominatedInstRange.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001734 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00001735 PredicateToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001736}
1737
1738std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1739 unsigned Start) {
1740 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001741 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1742 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001743 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001744 }
1745
Davide Italiano7e274e02016-12-22 16:03:48 +00001746 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00001747 // There's no need to call isInstructionTriviallyDead more than once on
1748 // an instruction. Therefore, once we know that an instruction is dead
1749 // we change its DFS number so that it doesn't get value numbered.
1750 if (isInstructionTriviallyDead(&I, TLI)) {
1751 InstrDFS[&I] = 0;
1752 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
1753 markInstructionForDeletion(&I);
1754 continue;
1755 }
1756
Davide Italiano7e274e02016-12-22 16:03:48 +00001757 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001758 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001759 }
1760
1761 // All of the range functions taken half-open ranges (open on the end side).
1762 // So we do not subtract one from count, because at this point it is one
1763 // greater than the last instruction.
1764 return std::make_pair(Start, End);
1765}
1766
1767void NewGVN::updateProcessedCount(Value *V) {
1768#ifndef NDEBUG
1769 if (ProcessedCount.count(V) == 0) {
1770 ProcessedCount.insert({V, 1});
1771 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001772 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001773 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001774 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001775 }
1776#endif
1777}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001778// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1779void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1780 // If all the arguments are the same, the MemoryPhi has the same value as the
1781 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001782 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00001783 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001784 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001785 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1786 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00001787 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001788 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001789 // If all that is left is nothing, our memoryphi is undef. We keep it as
1790 // InitialClass. Note: The only case this should happen is if we have at
1791 // least one self-argument.
1792 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001793 if (setMemoryAccessEquivTo(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00001794 markMemoryUsersTouched(MP);
1795 return;
1796 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001797
1798 // Transform the remaining operands into operand leaders.
1799 // FIXME: mapped_iterator should have a range version.
1800 auto LookupFunc = [&](const Use &U) {
1801 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1802 };
1803 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1804 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1805
1806 // and now check if all the elements are equal.
1807 // Sadly, we can't use std::equals since these are random access iterators.
1808 MemoryAccess *AllSameValue = *MappedBegin;
1809 ++MappedBegin;
1810 bool AllEqual = std::all_of(
1811 MappedBegin, MappedEnd,
1812 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1813
1814 if (AllEqual)
1815 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1816 else
1817 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1818
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001819 if (setMemoryAccessEquivTo(
1820 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001821 markMemoryUsersTouched(MP);
1822}
1823
1824// Value number a single instruction, symbolically evaluating, performing
1825// congruence finding, and updating mappings.
1826void NewGVN::valueNumberInstruction(Instruction *I) {
1827 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001828 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00001829 const Expression *Symbolized = nullptr;
1830 if (DebugCounter::shouldExecute(VNCounter)) {
1831 Symbolized = performSymbolicEvaluation(I);
1832 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00001833 // Mark the instruction as unused so we don't value number it again.
1834 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00001835 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00001836 // If we couldn't come up with a symbolic expression, use the unknown
1837 // expression
1838 if (Symbolized == nullptr)
1839 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001840 performCongruenceFinding(I, Symbolized);
1841 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001842 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00001843 // don't currently understand. We don't place non-value producing
1844 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001845 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001846 auto *Symbolized = createUnknownExpression(I);
1847 performCongruenceFinding(I, Symbolized);
1848 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001849 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1850 }
1851}
Davide Italiano7e274e02016-12-22 16:03:48 +00001852
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001853// Check if there is a path, using single or equal argument phi nodes, from
1854// First to Second.
1855bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1856 const MemoryAccess *Second) const {
1857 if (First == Second)
1858 return true;
1859
1860 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1861 auto *DefAccess = FirstDef->getDefiningAccess();
1862 return singleReachablePHIPath(DefAccess, Second);
1863 } else {
1864 auto *MP = cast<MemoryPhi>(First);
1865 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00001866 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001867 };
1868 auto FilteredPhiArgs =
1869 make_filter_range(MP->operands(), ReachableOperandPred);
1870 SmallVector<const Value *, 32> OperandList;
1871 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1872 std::back_inserter(OperandList));
1873 bool Okay = OperandList.size() == 1;
1874 if (!Okay)
1875 Okay = std::equal(OperandList.begin(), OperandList.end(),
1876 OperandList.begin());
1877 if (Okay)
1878 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1879 return false;
1880 }
1881}
1882
Daniel Berlin589cecc2017-01-02 18:00:46 +00001883// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001884// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001885// subject to very rare false negatives. It is only useful for
1886// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001887void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001888 // Anything equivalent in the memory access table should be in the same
1889 // congruence class.
1890
1891 // Filter out the unreachable and trivially dead entries, because they may
1892 // never have been updated if the instructions were not processed.
1893 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001894 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001895 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1896 if (!Result)
1897 return false;
1898 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1899 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1900 return true;
1901 };
1902
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001903 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001904 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001905 // Unreachable instructions may not have changed because we never process
1906 // them.
1907 if (!ReachableBlocks.count(KV.first->getBlock()))
1908 continue;
1909 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001910 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001911 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001912 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001913 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1914 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1915 "The instructions for these memory operations should have "
1916 "been in the same congruence class or reachable through"
1917 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001918 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1919
1920 // We can only sanely verify that MemoryDefs in the operand list all have
1921 // the same class.
1922 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00001923 return ReachableEdges.count(
1924 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00001925 isa<MemoryDef>(U);
1926
1927 };
1928 // All arguments should in the same class, ignoring unreachable arguments
1929 auto FilteredPhiArgs =
1930 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1931 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1932 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1933 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1934 const MemoryDef *MD = cast<MemoryDef>(U);
1935 return ValueToClass.lookup(MD->getMemoryInst());
1936 });
1937 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1938 PhiOpClasses.begin()) &&
1939 "All MemoryPhi arguments should be in the same class");
1940 }
1941 }
1942}
1943
Daniel Berlin06329a92017-03-18 15:41:40 +00001944// Verify that the sparse propagation we did actually found the maximal fixpoint
1945// We do this by storing the value to class mapping, touching all instructions,
1946// and redoing the iteration to see if anything changed.
1947void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001948#ifndef NDEBUG
Daniel Berlin06329a92017-03-18 15:41:40 +00001949 if (DebugCounter::isCounterSet(VNCounter))
1950 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
1951
1952 // Note that we have to store the actual classes, as we may change existing
1953 // classes during iteration. This is because our memory iteration propagation
1954 // is not perfect, and so may waste a little work. But it should generate
1955 // exactly the same congruence classes we have now, with different IDs.
1956 std::map<const Value *, CongruenceClass> BeforeIteration;
1957
1958 for (auto &KV : ValueToClass) {
1959 if (auto *I = dyn_cast<Instruction>(KV.first))
1960 // Skip unused/dead instructions.
1961 if (InstrDFS.lookup(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001962 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00001963 BeforeIteration.insert({KV.first, *KV.second});
1964 }
1965
1966 TouchedInstructions.set();
1967 TouchedInstructions.reset(0);
1968 iterateTouchedInstructions();
1969 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
1970 EqualClasses;
1971 for (const auto &KV : ValueToClass) {
1972 if (auto *I = dyn_cast<Instruction>(KV.first))
1973 // Skip unused/dead instructions.
1974 if (InstrDFS.lookup(I) == 0)
1975 continue;
1976 // We could sink these uses, but i think this adds a bit of clarity here as
1977 // to what we are comparing.
1978 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
1979 auto *AfterCC = KV.second;
1980 // Note that the classes can't change at this point, so we memoize the set
1981 // that are equal.
1982 if (!EqualClasses.count({BeforeCC, AfterCC})) {
1983 assert(areClassesEquivalent(BeforeCC, AfterCC) &&
1984 "Value number changed after main loop completed!");
1985 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00001986 }
1987 }
1988#endif
1989}
1990
Daniel Berlin06329a92017-03-18 15:41:40 +00001991// This is the main value numbering loop, it iterates over the initial touched
1992// instruction set, propagating value numbers, marking things touched, etc,
1993// until the set of touched instructions is completely empty.
1994void NewGVN::iterateTouchedInstructions() {
1995 unsigned int Iterations = 0;
1996 // Figure out where touchedinstructions starts
1997 int FirstInstr = TouchedInstructions.find_first();
1998 // Nothing set, nothing to iterate, just return.
1999 if (FirstInstr == -1)
2000 return;
2001 BasicBlock *LastBlock = getBlockForValue(DFSToInstr[FirstInstr]);
2002 while (TouchedInstructions.any()) {
2003 ++Iterations;
2004 // Walk through all the instructions in all the blocks in RPO.
2005 // TODO: As we hit a new block, we should push and pop equalities into a
2006 // table lookupOperandLeader can use, to catch things PredicateInfo
2007 // might miss, like edge-only equivalences.
2008 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2009 InstrNum = TouchedInstructions.find_next(InstrNum)) {
2010
2011 // This instruction was found to be dead. We don't bother looking
2012 // at it again.
2013 if (InstrNum == 0) {
2014 TouchedInstructions.reset(InstrNum);
2015 continue;
2016 }
2017
2018 Value *V = DFSToInstr[InstrNum];
2019 BasicBlock *CurrBlock = getBlockForValue(V);
2020
2021 // If we hit a new block, do reachability processing.
2022 if (CurrBlock != LastBlock) {
2023 LastBlock = CurrBlock;
2024 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2025 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2026
2027 // If it's not reachable, erase any touched instructions and move on.
2028 if (!BlockReachable) {
2029 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2030 DEBUG(dbgs() << "Skipping instructions in block "
2031 << getBlockName(CurrBlock)
2032 << " because it is unreachable\n");
2033 continue;
2034 }
2035 updateProcessedCount(CurrBlock);
2036 }
2037
2038 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2039 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2040 valueNumberMemoryPhi(MP);
2041 } else if (auto *I = dyn_cast<Instruction>(V)) {
2042 valueNumberInstruction(I);
2043 } else {
2044 llvm_unreachable("Should have been a MemoryPhi or Instruction");
2045 }
2046 updateProcessedCount(V);
2047 // Reset after processing (because we may mark ourselves as touched when
2048 // we propagate equalities).
2049 TouchedInstructions.reset(InstrNum);
2050 }
2051 }
2052 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2053}
2054
Daniel Berlin85f91b02016-12-26 20:06:58 +00002055// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00002056bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00002057 if (DebugCounter::isCounterSet(VNCounter))
2058 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00002059 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00002060 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00002061 MSSAWalker = MSSA->getWalker();
2062
2063 // Count number of instructions for sizing of hash tables, and come
2064 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002065 unsigned ICount = 1;
2066 // Add an empty instruction to account for the fact that we start at 1
2067 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002068 // Note: We want ideal RPO traversal of the blocks, which is not quite the
2069 // same as dominator tree order, particularly with regard whether backedges
2070 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00002071 // If we visit in the wrong order, we will end up performing N times as many
2072 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002073 // The dominator tree does guarantee that, for a given dom tree node, it's
2074 // parent must occur before it in the RPO ordering. Thus, we only need to sort
2075 // the siblings.
2076 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00002077 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00002078 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002079 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002080 auto *Node = DT->getNode(B);
2081 assert(Node && "RPO and Dominator tree should have same reachability");
2082 RPOOrdering[Node] = ++Counter;
2083 }
2084 // Sort dominator tree children arrays into RPO.
2085 for (auto &B : RPOT) {
2086 auto *Node = DT->getNode(B);
2087 if (Node->getChildren().size() > 1)
2088 std::sort(Node->begin(), Node->end(),
2089 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
2090 return RPOOrdering[A] < RPOOrdering[B];
2091 });
2092 }
2093
2094 // Now a standard depth first ordering of the domtree is equivalent to RPO.
2095 auto DFI = df_begin(DT->getRootNode());
2096 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
2097 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00002098 const auto &BlockRange = assignDFSNumbers(B, ICount);
2099 BlockInstRange.insert({B, BlockRange});
2100 ICount += BlockRange.second - BlockRange.first;
2101 }
2102
2103 // Handle forward unreachable blocks and figure out which blocks
2104 // have single preds.
2105 for (auto &B : F) {
2106 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002107 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002108 const auto &BlockRange = assignDFSNumbers(&B, ICount);
2109 BlockInstRange.insert({&B, BlockRange});
2110 ICount += BlockRange.second - BlockRange.first;
2111 }
2112 }
2113
Daniel Berline0bd37e2016-12-29 22:15:12 +00002114 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002115 DominatedInstRange.reserve(F.size());
2116 // Ensure we don't end up resizing the expressionToClass map, as
2117 // that can be quite expensive. At most, we have one expression per
2118 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002119 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002120
2121 // Initialize the touched instructions to include the entry block.
2122 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2123 TouchedInstructions.set(InstRange.first, InstRange.second);
2124 ReachableBlocks.insert(&F.getEntryBlock());
2125
2126 initializeCongruenceClasses(F);
Daniel Berlin06329a92017-03-18 15:41:40 +00002127 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00002128#ifndef NDEBUG
2129 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00002130 verifyIterationSettled(F);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002131#endif
Daniel Berlinf7d95802017-02-18 23:06:50 +00002132
Davide Italiano7e274e02016-12-22 16:03:48 +00002133 Changed |= eliminateInstructions(F);
2134
2135 // Delete all instructions marked for deletion.
2136 for (Instruction *ToErase : InstructionsToErase) {
2137 if (!ToErase->use_empty())
2138 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2139
2140 ToErase->eraseFromParent();
2141 }
2142
2143 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002144 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2145 return !ReachableBlocks.count(&BB);
2146 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002147
2148 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2149 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002150 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002151 deleteInstructionsInBlock(&BB);
2152 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002153 }
2154
2155 cleanupTables();
2156 return Changed;
2157}
2158
Davide Italiano7e274e02016-12-22 16:03:48 +00002159// Return true if V is a value that will always be available (IE can
2160// be placed anywhere) in the function. We don't do globals here
2161// because they are often worse to put in place.
2162// TODO: Separate cost from availability
2163static bool alwaysAvailable(Value *V) {
2164 return isa<Constant>(V) || isa<Argument>(V);
2165}
2166
Davide Italiano7e274e02016-12-22 16:03:48 +00002167struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002168 int DFSIn = 0;
2169 int DFSOut = 0;
2170 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002171 // Only one of Def and U will be set.
2172 Value *Def = nullptr;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002173 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002174 bool operator<(const ValueDFS &Other) const {
2175 // It's not enough that any given field be less than - we have sets
2176 // of fields that need to be evaluated together to give a proper ordering.
2177 // For example, if you have;
2178 // DFS (1, 3)
2179 // Val 0
2180 // DFS (1, 2)
2181 // Val 50
2182 // We want the second to be less than the first, but if we just go field
2183 // by field, we will get to Val 0 < Val 50 and say the first is less than
2184 // the second. We only want it to be less than if the DFS orders are equal.
2185 //
2186 // Each LLVM instruction only produces one value, and thus the lowest-level
2187 // differentiator that really matters for the stack (and what we use as as a
2188 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002189 // Everything else in the structure is instruction level, and only affects
2190 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002191 //
2192 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2193 // the order of replacement of uses does not matter.
2194 // IE given,
2195 // a = 5
2196 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002197 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2198 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002199 // The .val will be the same as well.
2200 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002201 // You will replace both, and it does not matter what order you replace them
2202 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2203 // operand 2).
2204 // Similarly for the case of same dfsin, dfsout, localnum, but different
2205 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002206 // a = 5
2207 // b = 6
2208 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002209 // in c, we will a valuedfs for a, and one for b,with everything the same
2210 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002211 // It does not matter what order we replace these operands in.
2212 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002213 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2214 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002215 Other.U);
2216 }
2217};
2218
Daniel Berlinc4796862017-01-27 02:37:11 +00002219// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002220// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00002221// reachable uses for each value is stored in UseCount, and instructions that
2222// seem
2223// dead (have no non-dead uses) are stored in ProbablyDead.
2224void NewGVN::convertClassToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00002225 const CongruenceClass::MemberSet &Dense,
Daniel Berline3e69e12017-03-10 00:32:33 +00002226 SmallVectorImpl<ValueDFS> &DFSOrderedSet,
2227 DenseMap<const Value *, unsigned int> &UseCounts,
2228 SmallPtrSetImpl<Instruction *> &ProbablyDead) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002229 for (auto D : Dense) {
2230 // First add the value.
2231 BasicBlock *BB = getBlockForValue(D);
2232 // Constants are handled prior to ever calling this function, so
2233 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002234 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002235 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002236 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002237 VDDef.DFSIn = DomNode->getDFSNumIn();
2238 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00002239 // If it's a store, use the leader of the value operand.
2240 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002241 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002242 VDDef.Def = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
Daniel Berlin26addef2017-01-20 21:04:30 +00002243 } else {
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002244 VDDef.Def = D;
Daniel Berlin26addef2017-01-20 21:04:30 +00002245 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002246 assert(isa<Instruction>(D) &&
2247 "The dense set member should always be an instruction");
2248 VDDef.LocalNum = InstrDFS.lookup(D);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002249 DFSOrderedSet.emplace_back(VDDef);
Daniel Berline3e69e12017-03-10 00:32:33 +00002250 Instruction *Def = cast<Instruction>(D);
2251 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002252 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00002253 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002254 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002255 // Don't try to replace into dead uses
2256 if (InstructionsToErase.count(I))
2257 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002258 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002259 // Put the phi node uses in the incoming block.
2260 BasicBlock *IBlock;
2261 if (auto *P = dyn_cast<PHINode>(I)) {
2262 IBlock = P->getIncomingBlock(U);
2263 // Make phi node users appear last in the incoming block
2264 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002265 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002266 } else {
2267 IBlock = I->getParent();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002268 VDUse.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002269 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002270
2271 // Skip uses in unreachable blocks, as we're going
2272 // to delete them.
2273 if (ReachableBlocks.count(IBlock) == 0)
2274 continue;
2275
Daniel Berlinb66164c2017-01-14 00:24:23 +00002276 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002277 VDUse.DFSIn = DomNode->getDFSNumIn();
2278 VDUse.DFSOut = DomNode->getDFSNumOut();
2279 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00002280 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002281 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002282 }
2283 }
Daniel Berline3e69e12017-03-10 00:32:33 +00002284
2285 // If there are no uses, it's probably dead (but it may have side-effects,
2286 // so not definitely dead. Otherwise, store the number of uses so we can
2287 // track if it becomes dead later).
2288 if (UseCount == 0)
2289 ProbablyDead.insert(Def);
2290 else
2291 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002292 }
2293}
2294
Daniel Berlinc4796862017-01-27 02:37:11 +00002295// This function converts the set of members for a congruence class from values,
2296// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00002297void NewGVN::convertClassToLoadsAndStores(
Daniel Berlinc4796862017-01-27 02:37:11 +00002298 const CongruenceClass::MemberSet &Dense,
2299 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2300 for (auto D : Dense) {
2301 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2302 continue;
2303
2304 BasicBlock *BB = getBlockForValue(D);
2305 ValueDFS VD;
2306 DomTreeNode *DomNode = DT->getNode(BB);
2307 VD.DFSIn = DomNode->getDFSNumIn();
2308 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002309 VD.Def = D;
Daniel Berlinc4796862017-01-27 02:37:11 +00002310
2311 // If it's an instruction, use the real local dfs number.
2312 if (auto *I = dyn_cast<Instruction>(D))
2313 VD.LocalNum = InstrDFS.lookup(I);
2314 else
2315 llvm_unreachable("Should have been an instruction");
2316
2317 LoadsAndStores.emplace_back(VD);
2318 }
2319}
2320
Davide Italiano7e274e02016-12-22 16:03:48 +00002321static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002322 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002323 if (!ReplInst)
2324 return;
2325
Davide Italiano7e274e02016-12-22 16:03:48 +00002326 // Patch the replacement so that it is not more restrictive than the value
2327 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002328 // Note that if 'I' is a load being replaced by some operation,
2329 // for example, by an arithmetic operation, then andIRFlags()
2330 // would just erase all math flags from the original arithmetic
2331 // operation, which is clearly not wanted and not needed.
2332 if (!isa<LoadInst>(I))
2333 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002334
Daniel Berlin86eab152017-02-12 22:25:20 +00002335 // FIXME: If both the original and replacement value are part of the
2336 // same control-flow region (meaning that the execution of one
2337 // guarantees the execution of the other), then we can combine the
2338 // noalias scopes here and do better than the general conservative
2339 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002340
Daniel Berlin86eab152017-02-12 22:25:20 +00002341 // In general, GVN unifies expressions over different control-flow
2342 // regions, and so we need a conservative combination of the noalias
2343 // scopes.
2344 static const unsigned KnownIDs[] = {
2345 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2346 LLVMContext::MD_noalias, LLVMContext::MD_range,
2347 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2348 LLVMContext::MD_invariant_group};
2349 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002350}
2351
2352static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2353 patchReplacementInstruction(I, Repl);
2354 I->replaceAllUsesWith(Repl);
2355}
2356
2357void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2358 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2359 ++NumGVNBlocksDeleted;
2360
Daniel Berline19f0e02017-01-30 17:06:55 +00002361 // Delete the instructions backwards, as it has a reduced likelihood of having
2362 // to update as many def-use and use-def chains. Start after the terminator.
2363 auto StartPoint = BB->rbegin();
2364 ++StartPoint;
2365 // Note that we explicitly recalculate BB->rend() on each iteration,
2366 // as it may change when we remove the first instruction.
2367 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2368 Instruction &Inst = *I++;
2369 if (!Inst.use_empty())
2370 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2371 if (isa<LandingPadInst>(Inst))
2372 continue;
2373
2374 Inst.eraseFromParent();
2375 ++NumGVNInstrDeleted;
2376 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002377 // Now insert something that simplifycfg will turn into an unreachable.
2378 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2379 new StoreInst(UndefValue::get(Int8Ty),
2380 Constant::getNullValue(Int8Ty->getPointerTo()),
2381 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002382}
2383
2384void NewGVN::markInstructionForDeletion(Instruction *I) {
2385 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2386 InstructionsToErase.insert(I);
2387}
2388
2389void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2390
2391 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2392 patchAndReplaceAllUsesWith(I, V);
2393 // We save the actual erasing to avoid invalidating memory
2394 // dependencies until we are done with everything.
2395 markInstructionForDeletion(I);
2396}
2397
2398namespace {
2399
2400// This is a stack that contains both the value and dfs info of where
2401// that value is valid.
2402class ValueDFSStack {
2403public:
2404 Value *back() const { return ValueStack.back(); }
2405 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2406
2407 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002408 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002409 DFSStack.emplace_back(DFSIn, DFSOut);
2410 }
2411 bool empty() const { return DFSStack.empty(); }
2412 bool isInScope(int DFSIn, int DFSOut) const {
2413 if (empty())
2414 return false;
2415 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2416 }
2417
2418 void popUntilDFSScope(int DFSIn, int DFSOut) {
2419
2420 // These two should always be in sync at this point.
2421 assert(ValueStack.size() == DFSStack.size() &&
2422 "Mismatch between ValueStack and DFSStack");
2423 while (
2424 !DFSStack.empty() &&
2425 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2426 DFSStack.pop_back();
2427 ValueStack.pop_back();
2428 }
2429 }
2430
2431private:
2432 SmallVector<Value *, 8> ValueStack;
2433 SmallVector<std::pair<int, int>, 8> DFSStack;
2434};
2435}
Daniel Berlin04443432017-01-07 03:23:47 +00002436
Davide Italiano7e274e02016-12-22 16:03:48 +00002437bool NewGVN::eliminateInstructions(Function &F) {
2438 // This is a non-standard eliminator. The normal way to eliminate is
2439 // to walk the dominator tree in order, keeping track of available
2440 // values, and eliminating them. However, this is mildly
2441 // pointless. It requires doing lookups on every instruction,
2442 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002443 // instructions part of most singleton congruence classes, we know we
2444 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002445
2446 // Instead, this eliminator looks at the congruence classes directly, sorts
2447 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002448 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002449 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002450 // last member. This is worst case O(E log E) where E = number of
2451 // instructions in a single congruence class. In theory, this is all
2452 // instructions. In practice, it is much faster, as most instructions are
2453 // either in singleton congruence classes or can't possibly be eliminated
2454 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002455 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002456 // for elimination purposes.
2457 // TODO: If we wanted to be faster, We could remove any members with no
2458 // overlapping ranges while sorting, as we will never eliminate anything
2459 // with those members, as they don't dominate anything else in our set.
2460
Davide Italiano7e274e02016-12-22 16:03:48 +00002461 bool AnythingReplaced = false;
2462
2463 // Since we are going to walk the domtree anyway, and we can't guarantee the
2464 // DFS numbers are updated, we compute some ourselves.
2465 DT->updateDFSNumbers();
2466
2467 for (auto &B : F) {
2468 if (!ReachableBlocks.count(&B)) {
2469 for (const auto S : successors(&B)) {
2470 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002471 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002472 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2473 << getBlockName(&B)
2474 << " with undef due to it being unreachable\n");
2475 for (auto &Operand : Phi.incoming_values())
2476 if (Phi.getIncomingBlock(Operand) == &B)
2477 Operand.set(UndefValue::get(Phi.getType()));
2478 }
2479 }
2480 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002481 }
2482
Daniel Berline3e69e12017-03-10 00:32:33 +00002483 // Map to store the use counts
2484 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlin4d547962017-02-12 23:24:45 +00002485 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002486 // Track the equivalent store info so we can decide whether to try
2487 // dead store elimination.
2488 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00002489 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlinb79f5362017-02-11 12:48:50 +00002490 if (CC->Dead)
Davide Italiano7e274e02016-12-22 16:03:48 +00002491 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002492 // Everything still in the TOP class is unreachable or dead.
2493 if (CC == TOPClass) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00002494#ifndef NDEBUG
2495 for (auto M : CC->Members)
2496 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2497 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002498 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00002499 "point");
2500#endif
2501 continue;
2502 }
2503
Davide Italiano7e274e02016-12-22 16:03:48 +00002504 assert(CC->RepLeader && "We should have had a leader");
2505
2506 // If this is a leader that is always available, and it's a
2507 // constant or has no equivalences, just replace everything with
2508 // it. We then update the congruence class with whatever members
2509 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002510 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2511 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002512 SmallPtrSet<Value *, 4> MembersLeft;
2513 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002514 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002515 // Void things have no uses we can replace.
Daniel Berline3e69e12017-03-10 00:32:33 +00002516 if (Member == Leader || Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002517 MembersLeft.insert(Member);
2518 continue;
2519 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002520 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2521 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002522 // Due to equality propagation, these may not always be
2523 // instructions, they may be real values. We don't really
2524 // care about trying to replace the non-instructions.
2525 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002526 assert(Leader != I && "About to accidentally remove our leader");
2527 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002528 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002529 continue;
2530 } else {
2531 MembersLeft.insert(I);
2532 }
2533 }
2534 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002535 } else {
2536 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2537 // If this is a singleton, we can skip it.
2538 if (CC->Members.size() != 1) {
2539
2540 // This is a stack because equality replacement/etc may place
2541 // constants in the middle of the member list, and we want to use
2542 // those constant values in preference to the current leader, over
2543 // the scope of those constants.
2544 ValueDFSStack EliminationStack;
2545
2546 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002547 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berline3e69e12017-03-10 00:32:33 +00002548 convertClassToDFSOrdered(CC->Members, DFSOrderedSet, UseCounts,
2549 ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00002550
2551 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002552 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002553 for (auto &VD : DFSOrderedSet) {
2554 int MemberDFSIn = VD.DFSIn;
2555 int MemberDFSOut = VD.DFSOut;
Daniel Berline3e69e12017-03-10 00:32:33 +00002556 Value *Def = VD.Def;
2557 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00002558 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002559 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00002560 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002561
2562 if (EliminationStack.empty()) {
2563 DEBUG(dbgs() << "Elimination Stack is empty\n");
2564 } else {
2565 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2566 << EliminationStack.dfs_back().first << ","
2567 << EliminationStack.dfs_back().second << ")\n");
2568 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002569
2570 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2571 << MemberDFSOut << ")\n");
2572 // First, we see if we are out of scope or empty. If so,
2573 // and there equivalences, we try to replace the top of
2574 // stack with equivalences (if it's on the stack, it must
2575 // not have been eliminated yet).
2576 // Then we synchronize to our current scope, by
2577 // popping until we are back within a DFS scope that
2578 // dominates the current member.
2579 // Then, what happens depends on a few factors
2580 // If the stack is now empty, we need to push
2581 // If we have a constant or a local equivalence we want to
2582 // start using, we also push.
2583 // Otherwise, we walk along, processing members who are
2584 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002585 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002586 bool OutOfScope =
2587 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2588
2589 if (OutOfScope || ShouldPush) {
2590 // Sync to our current scope.
2591 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00002592 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002593 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002594 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00002595 }
2596 }
2597
Daniel Berline3e69e12017-03-10 00:32:33 +00002598 // Skip the Def's, we only want to eliminate on their uses. But mark
2599 // dominated defs as dead.
2600 if (Def) {
2601 // For anything in this case, what and how we value number
2602 // guarantees that any side-effets that would have occurred (ie
2603 // throwing, etc) can be proven to either still occur (because it's
2604 // dominated by something that has the same side-effects), or never
2605 // occur. Otherwise, we would not have been able to prove it value
2606 // equivalent to something else. For these things, we can just mark
2607 // it all dead. Note that this is different from the "ProbablyDead"
2608 // set, which may not be dominated by anything, and thus, are only
2609 // easy to prove dead if they are also side-effect free.
2610 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
2611 isa<Instruction>(Def))
2612 markInstructionForDeletion(cast<Instruction>(Def));
2613 continue;
2614 }
2615 // At this point, we know it is a Use we are trying to possibly
2616 // replace.
2617
2618 assert(isa<Instruction>(U->get()) &&
2619 "Current def should have been an instruction");
2620 assert(isa<Instruction>(U->getUser()) &&
2621 "Current user should have been an instruction");
2622
2623 // If the thing we are replacing into is already marked to be dead,
2624 // this use is dead. Note that this is true regardless of whether
2625 // we have anything dominating the use or not. We do this here
2626 // because we are already walking all the uses anyway.
2627 Instruction *InstUse = cast<Instruction>(U->getUser());
2628 if (InstructionsToErase.count(InstUse)) {
2629 auto &UseCount = UseCounts[U->get()];
2630 if (--UseCount == 0) {
2631 ProbablyDead.insert(cast<Instruction>(U->get()));
2632 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002633 }
2634
Davide Italiano7e274e02016-12-22 16:03:48 +00002635 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00002636 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00002637 if (EliminationStack.empty())
2638 continue;
2639
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002640 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00002641
Daniel Berlind92e7f92017-01-07 00:01:42 +00002642 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00002643 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00002644 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002645 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00002646 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002647
2648 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00002649 // metadata. Skip this if we are replacing predicateinfo with its
2650 // original operand, as we already know we can just drop it.
2651 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002652 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
2653 if (!PI || DominatingLeader != PI->OriginalOp)
2654 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00002655 U->set(DominatingLeader);
2656 // This is now a use of the dominating leader, which means if the
2657 // dominating leader was dead, it's now live!
2658 auto &LeaderUseCount = UseCounts[DominatingLeader];
2659 // It's about to be alive again.
2660 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
2661 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
2662 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002663 AnythingReplaced = true;
2664 }
2665 }
2666 }
2667
Daniel Berline3e69e12017-03-10 00:32:33 +00002668 // At this point, anything still in the ProbablyDead set is actually dead if
2669 // would be trivially dead.
2670 for (auto *I : ProbablyDead)
2671 if (wouldInstructionBeTriviallyDead(I))
2672 markInstructionForDeletion(I);
2673
Davide Italiano7e274e02016-12-22 16:03:48 +00002674 // Cleanup the congruence class.
2675 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002676 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002677 if (Member->getType()->isVoidTy()) {
2678 MembersLeft.insert(Member);
2679 continue;
2680 }
2681
Davide Italiano7e274e02016-12-22 16:03:48 +00002682 MembersLeft.insert(Member);
2683 }
2684 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002685
2686 // If we have possible dead stores to look at, try to eliminate them.
2687 if (CC->StoreCount > 0) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002688 convertClassToLoadsAndStores(CC->Members, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00002689 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2690 ValueDFSStack EliminationStack;
2691 for (auto &VD : PossibleDeadStores) {
2692 int MemberDFSIn = VD.DFSIn;
2693 int MemberDFSOut = VD.DFSOut;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002694 Instruction *Member = cast<Instruction>(VD.Def);
Daniel Berlinc4796862017-01-27 02:37:11 +00002695 if (EliminationStack.empty() ||
2696 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2697 // Sync to our current scope.
2698 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2699 if (EliminationStack.empty()) {
2700 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2701 continue;
2702 }
2703 }
2704 // We already did load elimination, so nothing to do here.
2705 if (isa<LoadInst>(Member))
2706 continue;
2707 assert(!EliminationStack.empty());
2708 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002709 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002710 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2711 // Member is dominater by Leader, and thus dead
2712 DEBUG(dbgs() << "Marking dead store " << *Member
2713 << " that is dominated by " << *Leader << "\n");
2714 markInstructionForDeletion(Member);
2715 CC->Members.erase(Member);
2716 ++NumGVNDeadStores;
2717 }
2718 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002719 }
2720
2721 return AnythingReplaced;
2722}
Daniel Berlin1c087672017-02-11 15:07:01 +00002723
2724// This function provides global ranking of operations so that we can place them
2725// in a canonical order. Note that rank alone is not necessarily enough for a
2726// complete ordering, as constants all have the same rank. However, generally,
2727// we will simplify an operation with all constants so that it doesn't matter
2728// what order they appear in.
2729unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002730 // Prefer undef to anything else
2731 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00002732 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002733 if (isa<Constant>(V))
2734 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00002735 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002736 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00002737
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002738 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00002739 // the constant and argument ranking above.
2740 unsigned Result = InstrDFS.lookup(V);
2741 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002742 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00002743 // Unreachable or something else, just return a really large number.
2744 return ~0;
2745}
2746
2747// This is a function that says whether two commutative operations should
2748// have their order swapped when canonicalizing.
2749bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
2750 // Because we only care about a total ordering, and don't rewrite expressions
2751 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002752 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002753 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00002754}
Daniel Berlin64e68992017-03-12 04:46:45 +00002755
2756class NewGVNLegacyPass : public FunctionPass {
2757public:
2758 static char ID; // Pass identification, replacement for typeid.
2759 NewGVNLegacyPass() : FunctionPass(ID) {
2760 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
2761 }
2762 bool runOnFunction(Function &F) override;
2763
2764private:
2765 void getAnalysisUsage(AnalysisUsage &AU) const override {
2766 AU.addRequired<AssumptionCacheTracker>();
2767 AU.addRequired<DominatorTreeWrapperPass>();
2768 AU.addRequired<TargetLibraryInfoWrapperPass>();
2769 AU.addRequired<MemorySSAWrapperPass>();
2770 AU.addRequired<AAResultsWrapperPass>();
2771 AU.addPreserved<DominatorTreeWrapperPass>();
2772 AU.addPreserved<GlobalsAAWrapperPass>();
2773 }
2774};
2775
2776bool NewGVNLegacyPass::runOnFunction(Function &F) {
2777 if (skipFunction(F))
2778 return false;
2779 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2780 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2781 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2782 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
2783 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
2784 F.getParent()->getDataLayout())
2785 .runGVN();
2786}
2787
2788INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
2789 false, false)
2790INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2791INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2792INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2793INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2794INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2795INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2796INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
2797 false)
2798
2799char NewGVNLegacyPass::ID = 0;
2800
2801// createGVNPass - The public interface to this file.
2802FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
2803
2804PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
2805 // Apparently the order in which we get these results matter for
2806 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
2807 // the same order here, just in case.
2808 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2809 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2810 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2811 auto &AA = AM.getResult<AAManager>(F);
2812 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2813 bool Changed =
2814 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
2815 .runGVN();
2816 if (!Changed)
2817 return PreservedAnalyses::all();
2818 PreservedAnalyses PA;
2819 PA.preserve<DominatorTreeAnalysis>();
2820 PA.preserve<GlobalsAA>();
2821 return PA;
2822}