blob: 2d8f22962a963a608452263bcd3ea739c5c9d949 [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"
79#include "llvm/Transforms/Scalar.h"
80#include "llvm/Transforms/Scalar/GVNExpression.h"
81#include "llvm/Transforms/Utils/BasicBlockUtils.h"
82#include "llvm/Transforms/Utils/Local.h"
83#include "llvm/Transforms/Utils/MemorySSA.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000084#include <unordered_map>
85#include <utility>
86#include <vector>
87using namespace llvm;
88using namespace PatternMatch;
89using namespace llvm::GVNExpression;
90
91#define DEBUG_TYPE "newgvn"
92
93STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
94STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
95STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
96STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +000097STATISTIC(NumGVNMaxIterations,
98 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +000099STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
100STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
101STATISTIC(NumGVNAvoidedSortedLeaderChanges,
102 "Number of avoided sorted leader changes");
Daniel Berlin89fea6f2017-01-20 06:38:41 +0000103STATISTIC(NumGVNNotMostDominatingLeader,
104 "Number of times a member dominated it's new classes' leader");
Daniel Berlinc4796862017-01-27 02:37:11 +0000105STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Davide Italiano7e274e02016-12-22 16:03:48 +0000106
107//===----------------------------------------------------------------------===//
108// GVN Pass
109//===----------------------------------------------------------------------===//
110
111// Anchor methods.
112namespace llvm {
113namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000114Expression::~Expression() = default;
115BasicExpression::~BasicExpression() = default;
116CallExpression::~CallExpression() = default;
117LoadExpression::~LoadExpression() = default;
118StoreExpression::~StoreExpression() = default;
119AggregateValueExpression::~AggregateValueExpression() = default;
120PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000121}
122}
123
124// Congruence classes represent the set of expressions/instructions
125// that are all the same *during some scope in the function*.
126// That is, because of the way we perform equality propagation, and
127// because of memory value numbering, it is not correct to assume
128// you can willy-nilly replace any member with any other at any
129// point in the function.
130//
131// For any Value in the Member set, it is valid to replace any dominated member
132// with that Value.
133//
134// Every congruence class has a leader, and the leader is used to
135// symbolize instructions in a canonical way (IE every operand of an
136// instruction that is a member of the same congruence class will
137// always be replaced with leader during symbolization).
138// To simplify symbolization, we keep the leader as a constant if class can be
139// proved to be a constant value.
140// Otherwise, the leader is a randomly chosen member of the value set, it does
141// not matter which one is chosen.
142// Each congruence class also has a defining expression,
143// though the expression may be null. If it exists, it can be used for forward
144// propagation and reassociation of values.
145//
146struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000147 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000148 unsigned ID;
149 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000150 Value *RepLeader = nullptr;
Daniel Berlin26addef2017-01-20 21:04:30 +0000151 // If this is represented by a store, the value.
152 Value *RepStoredValue = nullptr;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000153 // If this class contains MemoryDefs, what is the represented memory state.
154 MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000155 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000156 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000157 // Actual members of this class.
158 MemberSet Members;
159
160 // True if this class has no members left. This is mainly used for assertion
161 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000162 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000163
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000164 // Number of stores in this congruence class.
165 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000166 int StoreCount = 0;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000167
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000168 // The most dominating leader after our current leader, because the member set
169 // is not sorted and is expensive to keep sorted all the time.
170 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
171
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000172 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000173 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000174 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000175};
176
177namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000178template <> struct DenseMapInfo<const Expression *> {
179 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000180 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000181 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
182 return reinterpret_cast<const Expression *>(Val);
183 }
184 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000185 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000186 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
187 return reinterpret_cast<const Expression *>(Val);
188 }
189 static unsigned getHashValue(const Expression *V) {
190 return static_cast<unsigned>(V->getHashValue());
191 }
192 static bool isEqual(const Expression *LHS, const Expression *RHS) {
193 if (LHS == RHS)
194 return true;
195 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
196 LHS == getEmptyKey() || RHS == getEmptyKey())
197 return false;
198 return *LHS == *RHS;
199 }
200};
Davide Italiano7e274e02016-12-22 16:03:48 +0000201} // end namespace llvm
202
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000203namespace {
Davide Italiano7e274e02016-12-22 16:03:48 +0000204class NewGVN : public FunctionPass {
205 DominatorTree *DT;
206 const DataLayout *DL;
207 const TargetLibraryInfo *TLI;
208 AssumptionCache *AC;
209 AliasAnalysis *AA;
210 MemorySSA *MSSA;
211 MemorySSAWalker *MSSAWalker;
212 BumpPtrAllocator ExpressionAllocator;
213 ArrayRecycler<Value *> ArgRecycler;
214
Daniel Berlin1c087672017-02-11 15:07:01 +0000215 // Number of function arguments, used by ranking
216 unsigned int NumFuncArgs;
217
Davide Italiano7e274e02016-12-22 16:03:48 +0000218 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000219
220 // This class is called INITIAL in the paper. It is the class everything
221 // startsout in, and represents any value. Being an optimistic analysis,
222 // anything in the INITIAL class has the value TOP, which is indeterminate and
223 // equivalent to everything.
Davide Italiano7e274e02016-12-22 16:03:48 +0000224 CongruenceClass *InitialClass;
225 std::vector<CongruenceClass *> CongruenceClasses;
226 unsigned NextCongruenceNum;
227
228 // Value Mappings.
229 DenseMap<Value *, CongruenceClass *> ValueToClass;
230 DenseMap<Value *, const Expression *> ValueToExpression;
231
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000232 // A table storing which memorydefs/phis represent a memory state provably
233 // equivalent to another memory state.
234 // We could use the congruence class machinery, but the MemoryAccess's are
235 // abstract memory states, so they can only ever be equivalent to each other,
236 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000237 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000238
Davide Italiano7e274e02016-12-22 16:03:48 +0000239 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000240 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000241 ExpressionClassMap ExpressionToClass;
242
243 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000244 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000245
246 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000247 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000248 DenseSet<BlockEdge> ReachableEdges;
249 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
250
251 // This is a bitvector because, on larger functions, we may have
252 // thousands of touched instructions at once (entire blocks,
253 // instructions with hundreds of uses, etc). Even with optimization
254 // for when we mark whole blocks as touched, when this was a
255 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
256 // the time in GVN just managing this list. The bitvector, on the
257 // other hand, efficiently supports test/set/clear of both
258 // individual and ranges, as well as "find next element" This
259 // enables us to use it as a worklist with essentially 0 cost.
260 BitVector TouchedInstructions;
261
262 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
263 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
264 DominatedInstRange;
265
266#ifndef NDEBUG
267 // Debugging for how many times each block and instruction got processed.
268 DenseMap<const Value *, unsigned> ProcessedCount;
269#endif
270
271 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000272 // This contains a mapping from Instructions to DFS numbers.
273 // The numbering starts at 1. An instruction with DFS number zero
274 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000275 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000276
277 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000278 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000279
280 // Deletion info.
281 SmallPtrSet<Instruction *, 8> InstructionsToErase;
282
283public:
284 static char ID; // Pass identification, replacement for typeid.
285 NewGVN() : FunctionPass(ID) {
286 initializeNewGVNPass(*PassRegistry::getPassRegistry());
287 }
288
289 bool runOnFunction(Function &F) override;
290 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000291 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000292
293private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000294 void getAnalysisUsage(AnalysisUsage &AU) const override {
295 AU.addRequired<AssumptionCacheTracker>();
296 AU.addRequired<DominatorTreeWrapperPass>();
297 AU.addRequired<TargetLibraryInfoWrapperPass>();
298 AU.addRequired<MemorySSAWrapperPass>();
299 AU.addRequired<AAResultsWrapperPass>();
300
301 AU.addPreserved<DominatorTreeWrapperPass>();
302 AU.addPreserved<GlobalsAAWrapperPass>();
303 }
304
305 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000306 const Expression *createExpression(Instruction *);
307 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000308 PHIExpression *createPHIExpression(Instruction *);
309 const VariableExpression *createVariableExpression(Value *);
310 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000311 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000312 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000313 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000314 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin97718e62017-01-31 22:32:03 +0000315 MemoryAccess *);
316 const CallExpression *createCallExpression(CallInst *, MemoryAccess *);
317 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
318 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000319
320 // Congruence class handling.
321 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000322 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000323 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000324 return result;
325 }
326
327 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000328 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000329 CClass->Members.insert(Member);
330 ValueToClass[Member] = CClass;
331 return CClass;
332 }
333 void initializeCongruenceClasses(Function &F);
334
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000335 // Value number an Instruction or MemoryPhi.
336 void valueNumberMemoryPhi(MemoryPhi *);
337 void valueNumberInstruction(Instruction *);
338
Davide Italiano7e274e02016-12-22 16:03:48 +0000339 // Symbolic evaluation.
340 const Expression *checkSimplificationResults(Expression *, Instruction *,
341 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000342 const Expression *performSymbolicEvaluation(Value *);
343 const Expression *performSymbolicLoadEvaluation(Instruction *);
344 const Expression *performSymbolicStoreEvaluation(Instruction *);
345 const Expression *performSymbolicCallEvaluation(Instruction *);
346 const Expression *performSymbolicPHIEvaluation(Instruction *);
347 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
348 const Expression *performSymbolicCmpEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000349
350 // Congruence finding.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000351 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000352 void performCongruenceFinding(Instruction *, const Expression *);
353 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000354 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000355 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
356 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000357 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000358
Daniel Berlin1c087672017-02-11 15:07:01 +0000359 // Ranking
360 unsigned int getRank(const Value *) const;
361 bool shouldSwapOperands(const Value *, const Value *) const;
362
Davide Italiano7e274e02016-12-22 16:03:48 +0000363 // Reachability handling.
364 void updateReachableEdge(BasicBlock *, BasicBlock *);
365 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000366 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Daniel Berlin97718e62017-01-31 22:32:03 +0000367 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000368
369 // Elimination.
370 struct ValueDFS;
Daniel Berlinc4796862017-01-27 02:37:11 +0000371 void convertDenseToDFSOrdered(const CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000372 SmallVectorImpl<ValueDFS> &);
Daniel Berlinc4796862017-01-27 02:37:11 +0000373 void convertDenseToLoadsAndStores(const CongruenceClass::MemberSet &,
374 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000375
376 bool eliminateInstructions(Function &);
377 void replaceInstruction(Instruction *, Value *);
378 void markInstructionForDeletion(Instruction *);
379 void deleteInstructionsInBlock(BasicBlock *);
380
381 // New instruction creation.
382 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000383
384 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000385 void markUsersTouched(Value *);
386 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000387 void markLeaderChangeTouched(CongruenceClass *CC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000388
389 // Utilities.
390 void cleanupTables();
391 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
392 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000393 void verifyMemoryCongruency() const;
394 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000395};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000396} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000397
398char NewGVN::ID = 0;
399
400// createGVNPass - The public interface to this file.
401FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
402
Davide Italianob1114092016-12-28 13:37:17 +0000403template <typename T>
404static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
405 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000406 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000407 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000408 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000409 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000410 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000411 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000412 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000413 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000414 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000415 return true;
416}
417
Davide Italianob1114092016-12-28 13:37:17 +0000418bool LoadExpression::equals(const Expression &Other) const {
419 return equalsLoadStoreHelper(*this, Other);
420}
Davide Italiano7e274e02016-12-22 16:03:48 +0000421
Davide Italianob1114092016-12-28 13:37:17 +0000422bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000423 bool Result = equalsLoadStoreHelper(*this, Other);
424 // Make sure that store vs store includes the value operand.
425 if (Result)
426 if (const auto *S = dyn_cast<StoreExpression>(&Other))
427 if (getStoredValue() != S->getStoredValue())
428 return false;
429 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000430}
431
432#ifndef NDEBUG
433static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000434 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000435}
436#endif
437
438INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
439INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
440INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
441INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
442INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
443INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
444INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
445INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
446
447PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000448 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000449 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000450 auto *E =
451 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000452
453 E->allocateOperands(ArgRecycler, ExpressionAllocator);
454 E->setType(I->getType());
455 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000456
Davide Italianob3886dd2017-01-25 23:37:49 +0000457 // Filter out unreachable phi operands.
458 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000459 return ReachableBlocks.count(PN->getIncomingBlock(U));
Davide Italianob3886dd2017-01-25 23:37:49 +0000460 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000461
462 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
463 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000464 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000465 if (U == PN)
466 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000467 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000468 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000469 return E;
470}
471
472// Set basic expression info (Arguments, type, opcode) for Expression
473// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000474bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000475 bool AllConstant = true;
476 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
477 E->setType(GEP->getSourceElementType());
478 else
479 E->setType(I->getType());
480 E->setOpcode(I->getOpcode());
481 E->allocateOperands(ArgRecycler, ExpressionAllocator);
482
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000483 // Transform the operand array into an operand leader array, and keep track of
484 // whether all members are constant.
485 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000486 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000487 AllConstant &= isa<Constant>(Operand);
488 return Operand;
489 });
490
Davide Italiano7e274e02016-12-22 16:03:48 +0000491 return AllConstant;
492}
493
494const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000495 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000496 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000497
498 E->setType(T);
499 E->setOpcode(Opcode);
500 E->allocateOperands(ArgRecycler, ExpressionAllocator);
501 if (Instruction::isCommutative(Opcode)) {
502 // Ensure that commutative instructions that only differ by a permutation
503 // of their operands get the same value number by sorting the operand value
504 // numbers. Since all commutative instructions have two operands it is more
505 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000506 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000507 std::swap(Arg1, Arg2);
508 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000509 E->op_push_back(lookupOperandLeader(Arg1));
510 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000511
512 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
513 DT, AC);
514 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
515 return SimplifiedE;
516 return E;
517}
518
519// Take a Value returned by simplification of Expression E/Instruction
520// I, and see if it resulted in a simpler expression. If so, return
521// that expression.
522// TODO: Once finished, this should not take an Instruction, we only
523// use it for printing.
524const Expression *NewGVN::checkSimplificationResults(Expression *E,
525 Instruction *I, Value *V) {
526 if (!V)
527 return nullptr;
528 if (auto *C = dyn_cast<Constant>(V)) {
529 if (I)
530 DEBUG(dbgs() << "Simplified " << *I << " to "
531 << " constant " << *C << "\n");
532 NumGVNOpsSimplified++;
533 assert(isa<BasicExpression>(E) &&
534 "We should always have had a basic expression here");
535
536 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
537 ExpressionAllocator.Deallocate(E);
538 return createConstantExpression(C);
539 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
540 if (I)
541 DEBUG(dbgs() << "Simplified " << *I << " to "
542 << " variable " << *V << "\n");
543 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
544 ExpressionAllocator.Deallocate(E);
545 return createVariableExpression(V);
546 }
547
548 CongruenceClass *CC = ValueToClass.lookup(V);
549 if (CC && CC->DefiningExpr) {
550 if (I)
551 DEBUG(dbgs() << "Simplified " << *I << " to "
552 << " expression " << *V << "\n");
553 NumGVNOpsSimplified++;
554 assert(isa<BasicExpression>(E) &&
555 "We should always have had a basic expression here");
556 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
557 ExpressionAllocator.Deallocate(E);
558 return CC->DefiningExpr;
559 }
560 return nullptr;
561}
562
Daniel Berlin97718e62017-01-31 22:32:03 +0000563const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000564 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000565
Daniel Berlin97718e62017-01-31 22:32:03 +0000566 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000567
568 if (I->isCommutative()) {
569 // Ensure that commutative instructions that only differ by a permutation
570 // of their operands get the same value number by sorting the operand value
571 // numbers. Since all commutative instructions have two operands it is more
572 // efficient to sort by hand rather than using, say, std::sort.
573 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
574 if (E->getOperand(0) > E->getOperand(1))
575 E->swapOperands(0, 1);
576 }
577
578 // Perform simplificaiton
579 // TODO: Right now we only check to see if we get a constant result.
580 // We may get a less than constant, but still better, result for
581 // some operations.
582 // IE
583 // add 0, x -> x
584 // and x, x -> x
585 // We should handle this by simply rewriting the expression.
586 if (auto *CI = dyn_cast<CmpInst>(I)) {
587 // Sort the operand value numbers so x<y and y>x get the same value
588 // number.
589 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000590 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000591 E->swapOperands(0, 1);
592 Predicate = CmpInst::getSwappedPredicate(Predicate);
593 }
594 E->setOpcode((CI->getOpcode() << 8) | Predicate);
595 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000596 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
597 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000598 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
599 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000600 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin97718e62017-01-31 22:32:03 +0000601 *DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000602 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
603 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000604 } else if (isa<SelectInst>(I)) {
605 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000606 E->getOperand(0) == E->getOperand(1)) {
607 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
608 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000609 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
610 E->getOperand(2), *DL, TLI, DT, AC);
611 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
612 return SimplifiedE;
613 }
614 } else if (I->isBinaryOp()) {
615 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
616 *DL, TLI, DT, AC);
617 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
618 return SimplifiedE;
619 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
620 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
621 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
622 return SimplifiedE;
623 } else if (isa<GetElementPtrInst>(I)) {
624 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000625 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000626 *DL, TLI, DT, AC);
627 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
628 return SimplifiedE;
629 } else if (AllConstant) {
630 // We don't bother trying to simplify unless all of the operands
631 // were constant.
632 // TODO: There are a lot of Simplify*'s we could call here, if we
633 // wanted to. The original motivating case for this code was a
634 // zext i1 false to i8, which we don't have an interface to
635 // simplify (IE there is no SimplifyZExt).
636
637 SmallVector<Constant *, 8> C;
638 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000639 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000640
641 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
642 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
643 return SimplifiedE;
644 }
645 return E;
646}
647
648const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000649NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000650 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000651 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000652 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000653 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000654 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000655 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000656 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000657 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000658 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000659 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000660 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000661 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000662 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000663 return E;
664 }
665 llvm_unreachable("Unhandled type of aggregate value operation");
666}
667
Daniel Berlin85f91b02016-12-26 20:06:58 +0000668const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000669 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 E->setOpcode(V->getValueID());
671 return E;
672}
673
Daniel Berlin97718e62017-01-31 22:32:03 +0000674const Expression *NewGVN::createVariableOrConstant(Value *V) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000675 auto Leader = lookupOperandLeader(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000676 if (auto *C = dyn_cast<Constant>(Leader))
677 return createConstantExpression(C);
678 return createVariableExpression(Leader);
679}
680
Daniel Berlin85f91b02016-12-26 20:06:58 +0000681const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000682 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000683 E->setOpcode(C->getValueID());
684 return E;
685}
686
Daniel Berlin02c6b172017-01-02 18:00:53 +0000687const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
688 auto *E = new (ExpressionAllocator) UnknownExpression(I);
689 E->setOpcode(I->getOpcode());
690 return E;
691}
692
Davide Italiano7e274e02016-12-22 16:03:48 +0000693const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000694 MemoryAccess *HV) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000695 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000696 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000697 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
Daniel Berlin97718e62017-01-31 22:32:03 +0000698 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000699 return E;
700}
701
702// See if we have a congruence class and leader for this operand, and if so,
703// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000704Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000705 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000706 if (CC) {
707 // Everything in INITIAL is represneted by undef, as it can be any value.
708 // We do have to make sure we get the type right though, so we can't set the
709 // RepLeader to undef.
710 if (CC == InitialClass)
711 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000712 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000713 }
714
Davide Italiano7e274e02016-12-22 16:03:48 +0000715 return V;
716}
717
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000718MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000719 auto *CC = MemoryAccessToClass.lookup(MA);
720 if (CC && CC->RepMemoryAccess)
721 return CC->RepMemoryAccess;
722 // FIXME: We need to audit all the places that current set a nullptr To, and
723 // fix them. There should always be *some* congruence class, even if it is
724 // singular. Right now, we don't bother setting congruence classes for
725 // anything but stores, which means we have to return the original access
726 // here. Otherwise, this should be unreachable.
727 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000728}
729
Daniel Berlinc4796862017-01-27 02:37:11 +0000730// Return true if the MemoryAccess is really equivalent to everything. This is
731// equivalent to the lattice value "TOP" in most lattices. This is the initial
732// state of all memory accesses.
733bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
734 return MemoryAccessToClass.lookup(MA) == InitialClass;
735}
736
Davide Italiano7e274e02016-12-22 16:03:48 +0000737LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin97718e62017-01-31 22:32:03 +0000738 LoadInst *LI, MemoryAccess *DA) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000739 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000740 E->allocateOperands(ArgRecycler, ExpressionAllocator);
741 E->setType(LoadType);
742
743 // Give store and loads same opcode so they value number together.
744 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000745 E->op_push_back(lookupOperandLeader(PointerOp));
Davide Italiano7e274e02016-12-22 16:03:48 +0000746 if (LI)
747 E->setAlignment(LI->getAlignment());
748
749 // TODO: Value number heap versions. We may be able to discover
750 // things alias analysis can't on it's own (IE that a store and a
751 // load have the same value, and thus, it isn't clobbering the load).
752 return E;
753}
754
755const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000756 MemoryAccess *DA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000757 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000758 auto *E = new (ExpressionAllocator)
759 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000760 E->allocateOperands(ArgRecycler, ExpressionAllocator);
761 E->setType(SI->getValueOperand()->getType());
762
763 // Give store and loads same opcode so they value number together.
764 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000765 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000766
767 // TODO: Value number heap versions. We may be able to discover
768 // things alias analysis can't on it's own (IE that a store and a
769 // load have the same value, and thus, it isn't clobbering the load).
770 return E;
771}
772
Daniel Berlin97718e62017-01-31 22:32:03 +0000773const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000774 // Unlike loads, we never try to eliminate stores, so we do not check if they
775 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000776 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000777 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000778 // Get the expression, if any, for the RHS of the MemoryDef.
779 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
780 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
781 // If we are defined by ourselves, use the live on entry def.
782 if (StoreRHS == StoreAccess)
783 StoreRHS = MSSA->getLiveOnEntryDef();
784
Daniel Berlin589cecc2017-01-02 18:00:46 +0000785 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000786 // See if we are defined by a previous store expression, it already has a
787 // value, and it's the same value as our current store. FIXME: Right now, we
788 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin97718e62017-01-31 22:32:03 +0000789 const Expression *OldStore = createStoreExpression(SI, StoreRHS);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000790 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000791 // Basically, check if the congruence class the store is in is defined by a
792 // store that isn't us, and has the same value. MemorySSA takes care of
793 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000794 // The RepStoredValue gets nulled if all the stores disappear in a class, so
795 // we don't need to check if the class contains a store besides us.
Daniel Berlin808e3ff2017-01-31 22:31:56 +0000796 if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin97718e62017-01-31 22:32:03 +0000797 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +0000798 // Also check if our value operand is defined by a load of the same memory
799 // location, and the memory state is the same as it was then
800 // (otherwise, it could have been overwritten later. See test32 in
801 // transforms/DeadStoreElimination/simple.ll)
802 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000803 if ((lookupOperandLeader(LI->getPointerOperand()) ==
804 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinc4796862017-01-27 02:37:11 +0000805 (lookupMemoryAccessEquiv(
806 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
807 return createVariableExpression(LI);
808 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000809 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000810 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000811}
812
Daniel Berlin97718e62017-01-31 22:32:03 +0000813const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000814 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000815
816 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000817 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000818 if (!LI->isSimple())
819 return nullptr;
820
Daniel Berlin203f47b2017-01-31 22:31:53 +0000821 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +0000822 // Load of undef is undef.
823 if (isa<UndefValue>(LoadAddressLeader))
824 return createConstantExpression(UndefValue::get(LI->getType()));
825
826 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
827
828 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
829 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
830 Instruction *DefiningInst = MD->getMemoryInst();
831 // If the defining instruction is not reachable, replace with undef.
832 if (!ReachableBlocks.count(DefiningInst->getParent()))
833 return createConstantExpression(UndefValue::get(LI->getType()));
834 }
835 }
836
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000837 const Expression *E =
838 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000839 lookupMemoryAccessEquiv(DefiningAccess));
Davide Italiano7e274e02016-12-22 16:03:48 +0000840 return E;
841}
842
843// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000844const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000845 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000846 if (AA->doesNotAccessMemory(CI))
Daniel Berlin97718e62017-01-31 22:32:03 +0000847 return createCallExpression(CI, nullptr);
Davide Italianob2225492016-12-27 18:15:39 +0000848 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000849 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin97718e62017-01-31 22:32:03 +0000850 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
Davide Italianob2225492016-12-27 18:15:39 +0000851 }
852 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000853}
854
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000855// Update the memory access equivalence table to say that From is equal to To,
856// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000857// FIXME: We need to audit all the places that current set a nullptr To, and fix
858// them. There should always be *some* congruence class, even if it is singular.
859bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
860 DEBUG(dbgs() << "Setting " << *From);
861 if (To) {
862 DEBUG(dbgs() << " equivalent to congruence class ");
863 DEBUG(dbgs() << To->ID << " with current memory access leader ");
864 DEBUG(dbgs() << *To->RepMemoryAccess);
865 } else {
866 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000867 }
Daniel Berlin9f376b72017-01-29 10:26:03 +0000868 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000869
870 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000871 bool Changed = false;
872 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000873 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000874 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000875 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000876 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000877 Changed = true;
878 } else if (!To) {
879 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000880 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000881 Changed = true;
882 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000883 } else {
884 assert(!To &&
885 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000886 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000887
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000888 return Changed;
889}
Davide Italiano7e274e02016-12-22 16:03:48 +0000890// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000891const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000892 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000893 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
894
895 // See if all arguaments are the same.
896 // We track if any were undef because they need special handling.
897 bool HasUndef = false;
898 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
899 if (Arg == I)
900 return false;
901 if (isa<UndefValue>(Arg)) {
902 HasUndef = true;
903 return false;
904 }
905 return true;
906 });
907 // If we are left with no operands, it's undef
908 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000909 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
910 << "\n");
911 E->deallocateOperands(ArgRecycler);
912 ExpressionAllocator.Deallocate(E);
913 return createConstantExpression(UndefValue::get(I->getType()));
914 }
Daniel Berlind92e7f92017-01-07 00:01:42 +0000915 Value *AllSameValue = *(Filtered.begin());
916 ++Filtered.begin();
917 // Can't use std::equal here, sadly, because filter.begin moves.
918 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
919 return V == AllSameValue;
920 })) {
921 // In LLVM's non-standard representation of phi nodes, it's possible to have
922 // phi nodes with cycles (IE dependent on other phis that are .... dependent
923 // on the original phi node), especially in weird CFG's where some arguments
924 // are unreachable, or uninitialized along certain paths. This can cause
925 // infinite loops during evaluation. We work around this by not trying to
926 // really evaluate them independently, but instead using a variable
927 // expression to say if one is equivalent to the other.
928 // We also special case undef, so that if we have an undef, we can't use the
929 // common value unless it dominates the phi block.
930 if (HasUndef) {
931 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +0000932 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +0000933 if (!DT->dominates(AllSameInst, I))
934 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000935 }
936
Davide Italiano7e274e02016-12-22 16:03:48 +0000937 NumGVNPhisAllSame++;
938 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
939 << "\n");
940 E->deallocateOperands(ArgRecycler);
941 ExpressionAllocator.Deallocate(E);
942 if (auto *C = dyn_cast<Constant>(AllSameValue))
943 return createConstantExpression(C);
944 return createVariableExpression(AllSameValue);
945 }
946 return E;
947}
948
Daniel Berlin97718e62017-01-31 22:32:03 +0000949const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000950 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
951 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
952 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
953 unsigned Opcode = 0;
954 // EI might be an extract from one of our recognised intrinsics. If it
955 // is we'll synthesize a semantically equivalent expression instead on
956 // an extract value expression.
957 switch (II->getIntrinsicID()) {
958 case Intrinsic::sadd_with_overflow:
959 case Intrinsic::uadd_with_overflow:
960 Opcode = Instruction::Add;
961 break;
962 case Intrinsic::ssub_with_overflow:
963 case Intrinsic::usub_with_overflow:
964 Opcode = Instruction::Sub;
965 break;
966 case Intrinsic::smul_with_overflow:
967 case Intrinsic::umul_with_overflow:
968 Opcode = Instruction::Mul;
969 break;
970 default:
971 break;
972 }
973
974 if (Opcode != 0) {
975 // Intrinsic recognized. Grab its args to finish building the
976 // expression.
977 assert(II->getNumArgOperands() == 2 &&
978 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +0000979 return createBinaryExpression(
980 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +0000981 }
982 }
983 }
984
Daniel Berlin97718e62017-01-31 22:32:03 +0000985 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000986}
Daniel Berlin97718e62017-01-31 22:32:03 +0000987const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinc22aafe2017-01-31 22:31:58 +0000988 CmpInst *CI = dyn_cast<CmpInst>(I);
989 // See if our operands are equal and that implies something.
990 auto Op0 = lookupOperandLeader(CI->getOperand(0));
991 auto Op1 = lookupOperandLeader(CI->getOperand(1));
992 if (Op0 == Op1) {
993 if (CI->isTrueWhenEqual())
994 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
995 else if (CI->isFalseWhenEqual())
996 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
997 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000998 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +0000999}
Davide Italiano7e274e02016-12-22 16:03:48 +00001000
1001// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001002const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001003 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001004 if (auto *C = dyn_cast<Constant>(V))
1005 E = createConstantExpression(C);
1006 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1007 E = createVariableExpression(V);
1008 } else {
1009 // TODO: memory intrinsics.
1010 // TODO: Some day, we should do the forward propagation and reassociation
1011 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001012 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001013 switch (I->getOpcode()) {
1014 case Instruction::ExtractValue:
1015 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001016 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001017 break;
1018 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001019 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001020 break;
1021 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001022 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001023 break;
1024 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001025 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001026 break;
1027 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001028 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001029 break;
1030 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001031 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001032 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001033 case Instruction::ICmp:
1034 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001035 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001036 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001037 case Instruction::Add:
1038 case Instruction::FAdd:
1039 case Instruction::Sub:
1040 case Instruction::FSub:
1041 case Instruction::Mul:
1042 case Instruction::FMul:
1043 case Instruction::UDiv:
1044 case Instruction::SDiv:
1045 case Instruction::FDiv:
1046 case Instruction::URem:
1047 case Instruction::SRem:
1048 case Instruction::FRem:
1049 case Instruction::Shl:
1050 case Instruction::LShr:
1051 case Instruction::AShr:
1052 case Instruction::And:
1053 case Instruction::Or:
1054 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001055 case Instruction::Trunc:
1056 case Instruction::ZExt:
1057 case Instruction::SExt:
1058 case Instruction::FPToUI:
1059 case Instruction::FPToSI:
1060 case Instruction::UIToFP:
1061 case Instruction::SIToFP:
1062 case Instruction::FPTrunc:
1063 case Instruction::FPExt:
1064 case Instruction::PtrToInt:
1065 case Instruction::IntToPtr:
1066 case Instruction::Select:
1067 case Instruction::ExtractElement:
1068 case Instruction::InsertElement:
1069 case Instruction::ShuffleVector:
1070 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001071 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001072 break;
1073 default:
1074 return nullptr;
1075 }
1076 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001077 return E;
1078}
1079
1080// There is an edge from 'Src' to 'Dst'. Return true if every path from
1081// the entry block to 'Dst' passes via this edge. In particular 'Dst'
1082// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +00001083bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001084
1085 // While in theory it is interesting to consider the case in which Dst has
1086 // more than one predecessor, because Dst might be part of a loop which is
1087 // only reachable from Src, in practice it is pointless since at the time
1088 // GVN runs all such loops have preheaders, which means that Dst will have
1089 // been changed to have only one predecessor, namely Src.
1090 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1091 const BasicBlock *Src = E.getStart();
1092 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
1093 (void)Src;
1094 return Pred != nullptr;
1095}
1096
1097void NewGVN::markUsersTouched(Value *V) {
1098 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001099 for (auto *User : V->users()) {
1100 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001101 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001102 }
1103}
1104
1105void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1106 for (auto U : MA->users()) {
1107 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001108 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001109 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001110 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001111 }
1112}
1113
Daniel Berlin32f8d562017-01-07 16:55:14 +00001114// Touch the instructions that need to be updated after a congruence class has a
1115// leader change, and mark changed values.
1116void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1117 for (auto M : CC->Members) {
1118 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001119 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001120 LeaderChanges.insert(M);
1121 }
1122}
1123
1124// Move a value, currently in OldClass, to be part of NewClass
1125// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001126void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1127 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001128 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001129 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001130 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001131
1132 if (I == OldClass->NextLeader.first)
1133 OldClass->NextLeader = {nullptr, ~0U};
1134
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001135 // It's possible, though unlikely, for us to discover equivalences such
1136 // that the current leader does not dominate the old one.
1137 // This statistic tracks how often this happens.
1138 // We assert on phi nodes when this happens, currently, for debugging, because
1139 // we want to make sure we name phi node cycles properly.
1140 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1141 I != NewClass->RepLeader &&
1142 DT->properlyDominates(
1143 I->getParent(),
1144 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1145 ++NumGVNNotMostDominatingLeader;
1146 assert(!isa<PHINode>(I) &&
1147 "New class for instruction should not be dominated by instruction");
1148 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001149
1150 if (NewClass->RepLeader != I) {
1151 auto DFSNum = InstrDFS.lookup(I);
1152 if (DFSNum < NewClass->NextLeader.second)
1153 NewClass->NextLeader = {I, DFSNum};
1154 }
1155
1156 OldClass->Members.erase(I);
1157 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001158 MemoryAccess *StoreAccess = nullptr;
1159 if (auto *SI = dyn_cast<StoreInst>(I)) {
1160 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001161 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001162 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001163 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001164 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001165 if (!NewClass->RepMemoryAccess) {
1166 // If we don't have a representative memory access, it better be the only
1167 // store in there.
1168 assert(NewClass->StoreCount == 1);
1169 NewClass->RepMemoryAccess = StoreAccess;
1170 }
1171 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001172 }
1173
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001174 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001175 // See if we destroyed the class or need to swap leaders.
1176 if (OldClass->Members.empty() && OldClass != InitialClass) {
1177 if (OldClass->DefiningExpr) {
1178 OldClass->Dead = true;
1179 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1180 << " from table\n");
1181 ExpressionToClass.erase(OldClass->DefiningExpr);
1182 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001183 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001184 // When the leader changes, the value numbering of
1185 // everything may change due to symbolization changes, so we need to
1186 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001187 DEBUG(dbgs() << "Leader change!\n");
1188 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001189 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001190 if (OldClass->StoreCount == 0) {
1191 if (OldClass->RepStoredValue != nullptr)
1192 OldClass->RepStoredValue = nullptr;
1193 if (OldClass->RepMemoryAccess != nullptr)
1194 OldClass->RepMemoryAccess = nullptr;
1195 }
1196
1197 // If we destroy the old access leader, we have to effectively destroy the
1198 // congruence class. When it comes to scalars, anything with the same value
1199 // is as good as any other. That means that one leader is as good as
1200 // another, and as long as you have some leader for the value, you are
1201 // good.. When it comes to *memory states*, only one particular thing really
1202 // represents the definition of a given memory state. Once it goes away, we
1203 // need to re-evaluate which pieces of memory are really still
1204 // equivalent. The best way to do this is to re-value number things. The
1205 // only way to really make that happen is to destroy the rest of the class.
1206 // In order to effectively destroy the class, we reset ExpressionToClass for
1207 // each by using the ValueToExpression mapping. The members later get
1208 // marked as touched due to the leader change. We will create new
1209 // congruence classes, and the pieces that are still equivalent will end
1210 // back together in a new class. If this becomes too expensive, it is
1211 // possible to use a versioning scheme for the congruence classes to avoid
1212 // the expressions finding this old class.
1213 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1214 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1215 << " because memory access leader changed");
1216 for (auto Member : OldClass->Members)
1217 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1218 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001219
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001220 // We don't need to sort members if there is only 1, and we don't care about
Daniel Berlinb79f5362017-02-11 12:48:50 +00001221 // sorting the INITIAL class because everything either gets out of it or is
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001222 // unreachable.
1223 if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1224 OldClass->RepLeader = *(OldClass->Members.begin());
1225 } else if (OldClass->NextLeader.first) {
1226 ++NumGVNAvoidedSortedLeaderChanges;
1227 OldClass->RepLeader = OldClass->NextLeader.first;
1228 OldClass->NextLeader = {nullptr, ~0U};
1229 } else {
1230 ++NumGVNSortedLeaderChanges;
1231 // TODO: If this ends up to slow, we can maintain a dual structure for
1232 // member testing/insertion, or keep things mostly sorted, and sort only
1233 // here, or ....
1234 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1235 for (const auto X : OldClass->Members) {
1236 auto DFSNum = InstrDFS.lookup(X);
1237 if (DFSNum < MinDFS.second)
1238 MinDFS = {X, DFSNum};
1239 }
1240 OldClass->RepLeader = MinDFS.first;
1241 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001242 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001243 }
1244}
1245
Davide Italiano7e274e02016-12-22 16:03:48 +00001246// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001247void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1248 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001249 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001250 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001251
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001252 CongruenceClass *IClass = ValueToClass[I];
1253 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001254 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001255 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001256
1257 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001258 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001259 EClass = ValueToClass[VE->getVariableValue()];
1260 } else {
1261 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1262
1263 // If it's not in the value table, create a new congruence class.
1264 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001265 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001266 auto place = lookupResult.first;
1267 place->second = NewClass;
1268
1269 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001270 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001271 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001272 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1273 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001274 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001275 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001276 // The RepMemoryAccess field will be filled in properly by the
1277 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001278 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001279 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001280 }
1281 assert(!isa<VariableExpression>(E) &&
1282 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001283
1284 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001285 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001286 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001287 << " and leader " << *(NewClass->RepLeader));
1288 if (NewClass->RepStoredValue)
1289 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1290 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001291 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1292 } else {
1293 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001294 if (isa<ConstantExpression>(E))
1295 assert(isa<Constant>(EClass->RepLeader) &&
1296 "Any class with a constant expression should have a "
1297 "constant leader");
1298
Davide Italiano7e274e02016-12-22 16:03:48 +00001299 assert(EClass && "Somehow don't have an eclass");
1300
1301 assert(!EClass->Dead && "We accidentally looked up a dead class");
1302 }
1303 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001304 bool ClassChanged = IClass != EClass;
1305 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001306 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001307 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1308 << "\n");
1309
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001310 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001311 moveValueToNewCongruenceClass(I, IClass, EClass);
1312 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001313 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001314 markMemoryUsersTouched(MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001315 }
1316}
1317
1318// Process the fact that Edge (from, to) is reachable, including marking
1319// any newly reachable blocks and instructions for processing.
1320void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1321 // Check if the Edge was reachable before.
1322 if (ReachableEdges.insert({From, To}).second) {
1323 // If this block wasn't reachable before, all instructions are touched.
1324 if (ReachableBlocks.insert(To).second) {
1325 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1326 const auto &InstRange = BlockInstRange.lookup(To);
1327 TouchedInstructions.set(InstRange.first, InstRange.second);
1328 } else {
1329 DEBUG(dbgs() << "Block " << getBlockName(To)
1330 << " was reachable, but new edge {" << getBlockName(From)
1331 << "," << getBlockName(To) << "} to it found\n");
1332
1333 // We've made an edge reachable to an existing block, which may
1334 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1335 // they are the only thing that depend on new edges. Anything using their
1336 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001337 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001338 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001339
Davide Italiano7e274e02016-12-22 16:03:48 +00001340 auto BI = To->begin();
1341 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001342 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001343 ++BI;
1344 }
1345 }
1346 }
1347}
1348
1349// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1350// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001351Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001352 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001353 if (isa<Constant>(Result))
1354 return Result;
1355 return nullptr;
1356}
1357
1358// Process the outgoing edges of a block for reachability.
1359void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1360 // Evaluate reachability of terminator instruction.
1361 BranchInst *BR;
1362 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1363 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001364 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001365 if (!CondEvaluated) {
1366 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001367 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001368 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1369 CondEvaluated = CE->getConstantValue();
1370 }
1371 } else if (isa<ConstantInt>(Cond)) {
1372 CondEvaluated = Cond;
1373 }
1374 }
1375 ConstantInt *CI;
1376 BasicBlock *TrueSucc = BR->getSuccessor(0);
1377 BasicBlock *FalseSucc = BR->getSuccessor(1);
1378 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1379 if (CI->isOne()) {
1380 DEBUG(dbgs() << "Condition for Terminator " << *TI
1381 << " evaluated to true\n");
1382 updateReachableEdge(B, TrueSucc);
1383 } else if (CI->isZero()) {
1384 DEBUG(dbgs() << "Condition for Terminator " << *TI
1385 << " evaluated to false\n");
1386 updateReachableEdge(B, FalseSucc);
1387 }
1388 } else {
1389 updateReachableEdge(B, TrueSucc);
1390 updateReachableEdge(B, FalseSucc);
1391 }
1392 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1393 // For switches, propagate the case values into the case
1394 // destinations.
1395
1396 // Remember how many outgoing edges there are to every successor.
1397 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1398
Davide Italiano7e274e02016-12-22 16:03:48 +00001399 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001400 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001401 // See if we were able to turn this switch statement into a constant.
1402 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001403 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001404 // We should be able to get case value for this.
1405 auto CaseVal = SI->findCaseValue(CondVal);
1406 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1407 // We proved the value is outside of the range of the case.
1408 // We can't do anything other than mark the default dest as reachable,
1409 // and go home.
1410 updateReachableEdge(B, SI->getDefaultDest());
1411 return;
1412 }
1413 // Now get where it goes and mark it reachable.
1414 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1415 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001416 } else {
1417 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1418 BasicBlock *TargetBlock = SI->getSuccessor(i);
1419 ++SwitchEdges[TargetBlock];
1420 updateReachableEdge(B, TargetBlock);
1421 }
1422 }
1423 } else {
1424 // Otherwise this is either unconditional, or a type we have no
1425 // idea about. Just mark successors as reachable.
1426 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1427 BasicBlock *TargetBlock = TI->getSuccessor(i);
1428 updateReachableEdge(B, TargetBlock);
1429 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001430
1431 // This also may be a memory defining terminator, in which case, set it
1432 // equivalent to nothing.
1433 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1434 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001435 }
1436}
1437
Daniel Berlin85f91b02016-12-26 20:06:58 +00001438// The algorithm initially places the values of the routine in the INITIAL
Daniel Berlinb79f5362017-02-11 12:48:50 +00001439// congruence class. The leader of INITIAL is the undetermined value `TOP`.
Davide Italiano7e274e02016-12-22 16:03:48 +00001440// When the algorithm has finished, values still in INITIAL are unreachable.
1441void NewGVN::initializeCongruenceClasses(Function &F) {
1442 // FIXME now i can't remember why this is 2
1443 NextCongruenceNum = 2;
1444 // Initialize all other instructions to be in INITIAL class.
1445 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001446 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001447 InitialClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001448 for (auto &B : F) {
1449 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001450 MemoryAccessToClass[MP] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001451
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001452 for (auto &I : B) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00001453 // Don't insert void terminators into the class
1454 if (!isa<TerminatorInst>(I) || !I.getType()->isVoidTy()) {
1455 InitialValues.insert(&I);
1456 ValueToClass[&I] = InitialClass;
1457 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001458 // All memory accesses are equivalent to live on entry to start. They must
1459 // be initialized to something so that initial changes are noticed. For
1460 // the maximal answer, we initialize them all to be the same as
1461 // liveOnEntry. Note that to save time, we only initialize the
1462 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1463 // other expression can generate a memory equivalence. If we start
1464 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001465 if (isa<StoreInst>(&I)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001466 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = InitialClass;
Davide Italianoeac05f62017-01-11 23:41:24 +00001467 ++InitialClass->StoreCount;
1468 assert(InitialClass->StoreCount > 0);
1469 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001470 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001471 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001472 InitialClass->Members.swap(InitialValues);
1473
1474 // Initialize arguments to be in their own unique congruence classes
1475 for (auto &FA : F.args())
1476 createSingletonCongruenceClass(&FA);
1477}
1478
1479void NewGVN::cleanupTables() {
1480 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1481 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1482 << CongruenceClasses[i]->Members.size() << " members\n");
1483 // Make sure we delete the congruence class (probably worth switching to
1484 // a unique_ptr at some point.
1485 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001486 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001487 }
1488
1489 ValueToClass.clear();
1490 ArgRecycler.clear(ExpressionAllocator);
1491 ExpressionAllocator.Reset();
1492 CongruenceClasses.clear();
1493 ExpressionToClass.clear();
1494 ValueToExpression.clear();
1495 ReachableBlocks.clear();
1496 ReachableEdges.clear();
1497#ifndef NDEBUG
1498 ProcessedCount.clear();
1499#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001500 InstrDFS.clear();
1501 InstructionsToErase.clear();
1502
1503 DFSToInstr.clear();
1504 BlockInstRange.clear();
1505 TouchedInstructions.clear();
1506 DominatedInstRange.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001507 MemoryAccessToClass.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001508}
1509
1510std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1511 unsigned Start) {
1512 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001513 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1514 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001515 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001516 }
1517
Davide Italiano7e274e02016-12-22 16:03:48 +00001518 for (auto &I : *B) {
1519 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001520 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001521 }
1522
1523 // All of the range functions taken half-open ranges (open on the end side).
1524 // So we do not subtract one from count, because at this point it is one
1525 // greater than the last instruction.
1526 return std::make_pair(Start, End);
1527}
1528
1529void NewGVN::updateProcessedCount(Value *V) {
1530#ifndef NDEBUG
1531 if (ProcessedCount.count(V) == 0) {
1532 ProcessedCount.insert({V, 1});
1533 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001534 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001535 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001536 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001537 }
1538#endif
1539}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001540// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1541void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1542 // If all the arguments are the same, the MemoryPhi has the same value as the
1543 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001544 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001545 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001546 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1547 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
1548 ReachableBlocks.count(MP->getIncomingBlock(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001549 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001550 // If all that is left is nothing, our memoryphi is undef. We keep it as
1551 // InitialClass. Note: The only case this should happen is if we have at
1552 // least one self-argument.
1553 if (Filtered.begin() == Filtered.end()) {
1554 if (setMemoryAccessEquivTo(MP, InitialClass))
1555 markMemoryUsersTouched(MP);
1556 return;
1557 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001558
1559 // Transform the remaining operands into operand leaders.
1560 // FIXME: mapped_iterator should have a range version.
1561 auto LookupFunc = [&](const Use &U) {
1562 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1563 };
1564 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1565 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1566
1567 // and now check if all the elements are equal.
1568 // Sadly, we can't use std::equals since these are random access iterators.
1569 MemoryAccess *AllSameValue = *MappedBegin;
1570 ++MappedBegin;
1571 bool AllEqual = std::all_of(
1572 MappedBegin, MappedEnd,
1573 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1574
1575 if (AllEqual)
1576 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1577 else
1578 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1579
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001580 if (setMemoryAccessEquivTo(
1581 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001582 markMemoryUsersTouched(MP);
1583}
1584
1585// Value number a single instruction, symbolically evaluating, performing
1586// congruence finding, and updating mappings.
1587void NewGVN::valueNumberInstruction(Instruction *I) {
1588 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001589
1590 // There's no need to call isInstructionTriviallyDead more than once on
1591 // an instruction. Therefore, once we know that an instruction is dead
1592 // we change its DFS number so that it doesn't get numbered again.
1593 if (InstrDFS[I] != 0 && isInstructionTriviallyDead(I, TLI)) {
1594 InstrDFS[I] = 0;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001595 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001596 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001597 return;
1598 }
1599 if (!I->isTerminator()) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001600 const auto *Symbolized = performSymbolicEvaluation(I);
Daniel Berlin02c6b172017-01-02 18:00:53 +00001601 // If we couldn't come up with a symbolic expression, use the unknown
1602 // expression
1603 if (Symbolized == nullptr)
1604 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001605 performCongruenceFinding(I, Symbolized);
1606 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001607 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00001608 // don't currently understand. We don't place non-value producing
1609 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001610 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001611 auto *Symbolized = createUnknownExpression(I);
1612 performCongruenceFinding(I, Symbolized);
1613 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001614 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1615 }
1616}
Davide Italiano7e274e02016-12-22 16:03:48 +00001617
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001618// Check if there is a path, using single or equal argument phi nodes, from
1619// First to Second.
1620bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1621 const MemoryAccess *Second) const {
1622 if (First == Second)
1623 return true;
1624
1625 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1626 auto *DefAccess = FirstDef->getDefiningAccess();
1627 return singleReachablePHIPath(DefAccess, Second);
1628 } else {
1629 auto *MP = cast<MemoryPhi>(First);
1630 auto ReachableOperandPred = [&](const Use &U) {
1631 return ReachableBlocks.count(MP->getIncomingBlock(U));
1632 };
1633 auto FilteredPhiArgs =
1634 make_filter_range(MP->operands(), ReachableOperandPred);
1635 SmallVector<const Value *, 32> OperandList;
1636 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1637 std::back_inserter(OperandList));
1638 bool Okay = OperandList.size() == 1;
1639 if (!Okay)
1640 Okay = std::equal(OperandList.begin(), OperandList.end(),
1641 OperandList.begin());
1642 if (Okay)
1643 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1644 return false;
1645 }
1646}
1647
Daniel Berlin589cecc2017-01-02 18:00:46 +00001648// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001649// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001650// subject to very rare false negatives. It is only useful for
1651// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001652void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001653 // Anything equivalent in the memory access table should be in the same
1654 // congruence class.
1655
1656 // Filter out the unreachable and trivially dead entries, because they may
1657 // never have been updated if the instructions were not processed.
1658 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001659 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001660 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1661 if (!Result)
1662 return false;
1663 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1664 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1665 return true;
1666 };
1667
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001668 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001669 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001670 // Unreachable instructions may not have changed because we never process
1671 // them.
1672 if (!ReachableBlocks.count(KV.first->getBlock()))
1673 continue;
1674 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001675 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001676 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001677 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001678 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1679 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1680 "The instructions for these memory operations should have "
1681 "been in the same congruence class or reachable through"
1682 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001683 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1684
1685 // We can only sanely verify that MemoryDefs in the operand list all have
1686 // the same class.
1687 auto ReachableOperandPred = [&](const Use &U) {
1688 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1689 isa<MemoryDef>(U);
1690
1691 };
1692 // All arguments should in the same class, ignoring unreachable arguments
1693 auto FilteredPhiArgs =
1694 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1695 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1696 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1697 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1698 const MemoryDef *MD = cast<MemoryDef>(U);
1699 return ValueToClass.lookup(MD->getMemoryInst());
1700 });
1701 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1702 PhiOpClasses.begin()) &&
1703 "All MemoryPhi arguments should be in the same class");
1704 }
1705 }
1706}
1707
Daniel Berlin85f91b02016-12-26 20:06:58 +00001708// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001709bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001710 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1711 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001712 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00001713 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00001714 DT = _DT;
1715 AC = _AC;
1716 TLI = _TLI;
1717 AA = _AA;
1718 MSSA = _MSSA;
1719 DL = &F.getParent()->getDataLayout();
1720 MSSAWalker = MSSA->getWalker();
1721
1722 // Count number of instructions for sizing of hash tables, and come
1723 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001724 unsigned ICount = 1;
1725 // Add an empty instruction to account for the fact that we start at 1
1726 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001727 // Note: We want RPO traversal of the blocks, which is not quite the same as
1728 // dominator tree order, particularly with regard whether backedges get
1729 // visited first or second, given a block with multiple successors.
1730 // If we visit in the wrong order, we will end up performing N times as many
1731 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001732 // The dominator tree does guarantee that, for a given dom tree node, it's
1733 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1734 // the siblings.
1735 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001736 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001737 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001738 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001739 auto *Node = DT->getNode(B);
1740 assert(Node && "RPO and Dominator tree should have same reachability");
1741 RPOOrdering[Node] = ++Counter;
1742 }
1743 // Sort dominator tree children arrays into RPO.
1744 for (auto &B : RPOT) {
1745 auto *Node = DT->getNode(B);
1746 if (Node->getChildren().size() > 1)
1747 std::sort(Node->begin(), Node->end(),
1748 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1749 return RPOOrdering[A] < RPOOrdering[B];
1750 });
1751 }
1752
1753 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1754 auto DFI = df_begin(DT->getRootNode());
1755 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1756 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001757 const auto &BlockRange = assignDFSNumbers(B, ICount);
1758 BlockInstRange.insert({B, BlockRange});
1759 ICount += BlockRange.second - BlockRange.first;
1760 }
1761
1762 // Handle forward unreachable blocks and figure out which blocks
1763 // have single preds.
1764 for (auto &B : F) {
1765 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001766 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001767 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1768 BlockInstRange.insert({&B, BlockRange});
1769 ICount += BlockRange.second - BlockRange.first;
1770 }
1771 }
1772
Daniel Berline0bd37e2016-12-29 22:15:12 +00001773 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001774 DominatedInstRange.reserve(F.size());
1775 // Ensure we don't end up resizing the expressionToClass map, as
1776 // that can be quite expensive. At most, we have one expression per
1777 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001778 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001779
1780 // Initialize the touched instructions to include the entry block.
1781 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1782 TouchedInstructions.set(InstRange.first, InstRange.second);
1783 ReachableBlocks.insert(&F.getEntryBlock());
1784
1785 initializeCongruenceClasses(F);
1786
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001787 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001788 // We start out in the entry block.
1789 BasicBlock *LastBlock = &F.getEntryBlock();
1790 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001791 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00001792 // Walk through all the instructions in all the blocks in RPO.
1793 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1794 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001795
1796 // This instruction was found to be dead. We don't bother looking
1797 // at it again.
1798 if (InstrNum == 0) {
1799 TouchedInstructions.reset(InstrNum);
1800 continue;
1801 }
1802
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001803 Value *V = DFSToInstr[InstrNum];
1804 BasicBlock *CurrBlock = nullptr;
1805
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001806 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001807 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001808 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001809 CurrBlock = MP->getBlock();
1810 else
1811 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001812
1813 // If we hit a new block, do reachability processing.
1814 if (CurrBlock != LastBlock) {
1815 LastBlock = CurrBlock;
1816 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1817 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1818
1819 // If it's not reachable, erase any touched instructions and move on.
1820 if (!BlockReachable) {
1821 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1822 DEBUG(dbgs() << "Skipping instructions in block "
1823 << getBlockName(CurrBlock)
1824 << " because it is unreachable\n");
1825 continue;
1826 }
1827 updateProcessedCount(CurrBlock);
1828 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001829
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001830 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001831 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1832 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001833 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001834 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001835 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001836 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001837 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001838 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001839 // Reset after processing (because we may mark ourselves as touched when
1840 // we propagate equalities).
1841 TouchedInstructions.reset(InstrNum);
1842 }
1843 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001844 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001845#ifndef NDEBUG
1846 verifyMemoryCongruency();
1847#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001848 Changed |= eliminateInstructions(F);
1849
1850 // Delete all instructions marked for deletion.
1851 for (Instruction *ToErase : InstructionsToErase) {
1852 if (!ToErase->use_empty())
1853 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1854
1855 ToErase->eraseFromParent();
1856 }
1857
1858 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001859 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1860 return !ReachableBlocks.count(&BB);
1861 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001862
1863 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1864 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001865 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001866 deleteInstructionsInBlock(&BB);
1867 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001868 }
1869
1870 cleanupTables();
1871 return Changed;
1872}
1873
1874bool NewGVN::runOnFunction(Function &F) {
1875 if (skipFunction(F))
1876 return false;
1877 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1878 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1879 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1880 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1881 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1882}
1883
Daniel Berlin85f91b02016-12-26 20:06:58 +00001884PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001885 NewGVN Impl;
1886
1887 // Apparently the order in which we get these results matter for
1888 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1889 // the same order here, just in case.
1890 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1891 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1892 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1893 auto &AA = AM.getResult<AAManager>(F);
1894 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1895 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1896 if (!Changed)
1897 return PreservedAnalyses::all();
1898 PreservedAnalyses PA;
1899 PA.preserve<DominatorTreeAnalysis>();
1900 PA.preserve<GlobalsAA>();
1901 return PA;
1902}
1903
1904// Return true if V is a value that will always be available (IE can
1905// be placed anywhere) in the function. We don't do globals here
1906// because they are often worse to put in place.
1907// TODO: Separate cost from availability
1908static bool alwaysAvailable(Value *V) {
1909 return isa<Constant>(V) || isa<Argument>(V);
1910}
1911
1912// Get the basic block from an instruction/value.
1913static BasicBlock *getBlockForValue(Value *V) {
1914 if (auto *I = dyn_cast<Instruction>(V))
1915 return I->getParent();
1916 return nullptr;
1917}
1918
1919struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001920 int DFSIn = 0;
1921 int DFSOut = 0;
1922 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001923 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001924 Value *Val = nullptr;
1925 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001926
1927 bool operator<(const ValueDFS &Other) const {
1928 // It's not enough that any given field be less than - we have sets
1929 // of fields that need to be evaluated together to give a proper ordering.
1930 // For example, if you have;
1931 // DFS (1, 3)
1932 // Val 0
1933 // DFS (1, 2)
1934 // Val 50
1935 // We want the second to be less than the first, but if we just go field
1936 // by field, we will get to Val 0 < Val 50 and say the first is less than
1937 // the second. We only want it to be less than if the DFS orders are equal.
1938 //
1939 // Each LLVM instruction only produces one value, and thus the lowest-level
1940 // differentiator that really matters for the stack (and what we use as as a
1941 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001942 // Everything else in the structure is instruction level, and only affects
1943 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001944 //
1945 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1946 // the order of replacement of uses does not matter.
1947 // IE given,
1948 // a = 5
1949 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001950 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1951 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001952 // The .val will be the same as well.
1953 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001954 // You will replace both, and it does not matter what order you replace them
1955 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1956 // operand 2).
1957 // Similarly for the case of same dfsin, dfsout, localnum, but different
1958 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001959 // a = 5
1960 // b = 6
1961 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001962 // in c, we will a valuedfs for a, and one for b,with everything the same
1963 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001964 // It does not matter what order we replace these operands in.
1965 // You will always end up with the same IR, and this is guaranteed.
1966 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1967 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1968 Other.U);
1969 }
1970};
1971
Daniel Berlinc4796862017-01-27 02:37:11 +00001972// This function converts the set of members for a congruence class from values,
1973// to sets of defs and uses with associated DFS info.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001974void NewGVN::convertDenseToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00001975 const CongruenceClass::MemberSet &Dense,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001976 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001977 for (auto D : Dense) {
1978 // First add the value.
1979 BasicBlock *BB = getBlockForValue(D);
1980 // Constants are handled prior to ever calling this function, so
1981 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001982 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001983 ValueDFS VD;
Daniel Berlinb66164c2017-01-14 00:24:23 +00001984 DomTreeNode *DomNode = DT->getNode(BB);
1985 VD.DFSIn = DomNode->getDFSNumIn();
1986 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00001987 // If it's a store, use the leader of the value operand.
1988 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001989 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001990 VD.Val = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
1991 } else {
1992 VD.Val = D;
1993 }
1994
Davide Italiano7e274e02016-12-22 16:03:48 +00001995 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlinaac56842017-01-15 09:18:41 +00001996 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001997 else
1998 llvm_unreachable("Should have been an instruction");
1999
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002000 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002001
Daniel Berlinb66164c2017-01-14 00:24:23 +00002002 // Now add the uses.
Davide Italiano7e274e02016-12-22 16:03:48 +00002003 for (auto &U : D->uses()) {
2004 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
2005 ValueDFS VD;
2006 // Put the phi node uses in the incoming block.
2007 BasicBlock *IBlock;
2008 if (auto *P = dyn_cast<PHINode>(I)) {
2009 IBlock = P->getIncomingBlock(U);
2010 // Make phi node users appear last in the incoming block
2011 // they are from.
2012 VD.LocalNum = InstrDFS.size() + 1;
2013 } else {
2014 IBlock = I->getParent();
Daniel Berlinaac56842017-01-15 09:18:41 +00002015 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002016 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002017
2018 // Skip uses in unreachable blocks, as we're going
2019 // to delete them.
2020 if (ReachableBlocks.count(IBlock) == 0)
2021 continue;
2022
Daniel Berlinb66164c2017-01-14 00:24:23 +00002023 DomTreeNode *DomNode = DT->getNode(IBlock);
2024 VD.DFSIn = DomNode->getDFSNumIn();
2025 VD.DFSOut = DomNode->getDFSNumOut();
Davide Italiano7e274e02016-12-22 16:03:48 +00002026 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002027 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002028 }
2029 }
2030 }
2031}
2032
Daniel Berlinc4796862017-01-27 02:37:11 +00002033// This function converts the set of members for a congruence class from values,
2034// to the set of defs for loads and stores, with associated DFS info.
2035void NewGVN::convertDenseToLoadsAndStores(
2036 const CongruenceClass::MemberSet &Dense,
2037 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2038 for (auto D : Dense) {
2039 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2040 continue;
2041
2042 BasicBlock *BB = getBlockForValue(D);
2043 ValueDFS VD;
2044 DomTreeNode *DomNode = DT->getNode(BB);
2045 VD.DFSIn = DomNode->getDFSNumIn();
2046 VD.DFSOut = DomNode->getDFSNumOut();
2047 VD.Val = D;
2048
2049 // If it's an instruction, use the real local dfs number.
2050 if (auto *I = dyn_cast<Instruction>(D))
2051 VD.LocalNum = InstrDFS.lookup(I);
2052 else
2053 llvm_unreachable("Should have been an instruction");
2054
2055 LoadsAndStores.emplace_back(VD);
2056 }
2057}
2058
Davide Italiano7e274e02016-12-22 16:03:48 +00002059static void patchReplacementInstruction(Instruction *I, Value *Repl) {
2060 // Patch the replacement so that it is not more restrictive than the value
2061 // being replaced.
2062 auto *Op = dyn_cast<BinaryOperator>(I);
2063 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
2064
2065 if (Op && ReplOp)
2066 ReplOp->andIRFlags(Op);
2067
2068 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
2069 // FIXME: If both the original and replacement value are part of the
2070 // same control-flow region (meaning that the execution of one
2071 // guarentees the executation of the other), then we can combine the
2072 // noalias scopes here and do better than the general conservative
2073 // answer used in combineMetadata().
2074
2075 // In general, GVN unifies expressions over different control-flow
2076 // regions, and so we need a conservative combination of the noalias
2077 // scopes.
2078 unsigned KnownIDs[] = {
2079 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2080 LLVMContext::MD_noalias, LLVMContext::MD_range,
2081 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2082 LLVMContext::MD_invariant_group};
2083 combineMetadata(ReplInst, I, KnownIDs);
2084 }
2085}
2086
2087static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2088 patchReplacementInstruction(I, Repl);
2089 I->replaceAllUsesWith(Repl);
2090}
2091
2092void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2093 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2094 ++NumGVNBlocksDeleted;
2095
Daniel Berline19f0e02017-01-30 17:06:55 +00002096 // Delete the instructions backwards, as it has a reduced likelihood of having
2097 // to update as many def-use and use-def chains. Start after the terminator.
2098 auto StartPoint = BB->rbegin();
2099 ++StartPoint;
2100 // Note that we explicitly recalculate BB->rend() on each iteration,
2101 // as it may change when we remove the first instruction.
2102 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2103 Instruction &Inst = *I++;
2104 if (!Inst.use_empty())
2105 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2106 if (isa<LandingPadInst>(Inst))
2107 continue;
2108
2109 Inst.eraseFromParent();
2110 ++NumGVNInstrDeleted;
2111 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002112 // Now insert something that simplifycfg will turn into an unreachable.
2113 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2114 new StoreInst(UndefValue::get(Int8Ty),
2115 Constant::getNullValue(Int8Ty->getPointerTo()),
2116 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002117}
2118
2119void NewGVN::markInstructionForDeletion(Instruction *I) {
2120 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2121 InstructionsToErase.insert(I);
2122}
2123
2124void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2125
2126 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2127 patchAndReplaceAllUsesWith(I, V);
2128 // We save the actual erasing to avoid invalidating memory
2129 // dependencies until we are done with everything.
2130 markInstructionForDeletion(I);
2131}
2132
2133namespace {
2134
2135// This is a stack that contains both the value and dfs info of where
2136// that value is valid.
2137class ValueDFSStack {
2138public:
2139 Value *back() const { return ValueStack.back(); }
2140 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2141
2142 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002143 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002144 DFSStack.emplace_back(DFSIn, DFSOut);
2145 }
2146 bool empty() const { return DFSStack.empty(); }
2147 bool isInScope(int DFSIn, int DFSOut) const {
2148 if (empty())
2149 return false;
2150 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2151 }
2152
2153 void popUntilDFSScope(int DFSIn, int DFSOut) {
2154
2155 // These two should always be in sync at this point.
2156 assert(ValueStack.size() == DFSStack.size() &&
2157 "Mismatch between ValueStack and DFSStack");
2158 while (
2159 !DFSStack.empty() &&
2160 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2161 DFSStack.pop_back();
2162 ValueStack.pop_back();
2163 }
2164 }
2165
2166private:
2167 SmallVector<Value *, 8> ValueStack;
2168 SmallVector<std::pair<int, int>, 8> DFSStack;
2169};
2170}
Daniel Berlin04443432017-01-07 03:23:47 +00002171
Davide Italiano7e274e02016-12-22 16:03:48 +00002172bool NewGVN::eliminateInstructions(Function &F) {
2173 // This is a non-standard eliminator. The normal way to eliminate is
2174 // to walk the dominator tree in order, keeping track of available
2175 // values, and eliminating them. However, this is mildly
2176 // pointless. It requires doing lookups on every instruction,
2177 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002178 // instructions part of most singleton congruence classes, we know we
2179 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002180
2181 // Instead, this eliminator looks at the congruence classes directly, sorts
2182 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002183 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002184 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002185 // last member. This is worst case O(E log E) where E = number of
2186 // instructions in a single congruence class. In theory, this is all
2187 // instructions. In practice, it is much faster, as most instructions are
2188 // either in singleton congruence classes or can't possibly be eliminated
2189 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002190 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002191 // for elimination purposes.
2192 // TODO: If we wanted to be faster, We could remove any members with no
2193 // overlapping ranges while sorting, as we will never eliminate anything
2194 // with those members, as they don't dominate anything else in our set.
2195
Davide Italiano7e274e02016-12-22 16:03:48 +00002196 bool AnythingReplaced = false;
2197
2198 // Since we are going to walk the domtree anyway, and we can't guarantee the
2199 // DFS numbers are updated, we compute some ourselves.
2200 DT->updateDFSNumbers();
2201
2202 for (auto &B : F) {
2203 if (!ReachableBlocks.count(&B)) {
2204 for (const auto S : successors(&B)) {
2205 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002206 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002207 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2208 << getBlockName(&B)
2209 << " with undef due to it being unreachable\n");
2210 for (auto &Operand : Phi.incoming_values())
2211 if (Phi.getIncomingBlock(Operand) == &B)
2212 Operand.set(UndefValue::get(Phi.getType()));
2213 }
2214 }
2215 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002216 }
2217
2218 for (CongruenceClass *CC : CongruenceClasses) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002219 // Track the equivalent store info so we can decide whether to try
2220 // dead store elimination.
2221 SmallVector<ValueDFS, 8> PossibleDeadStores;
2222
Daniel Berlinb79f5362017-02-11 12:48:50 +00002223 if (CC->Dead)
Davide Italiano7e274e02016-12-22 16:03:48 +00002224 continue;
Daniel Berlinb79f5362017-02-11 12:48:50 +00002225 // Everything still in the INITIAL class is unreachable or dead.
2226 if (CC == InitialClass) {
2227#ifndef NDEBUG
2228 for (auto M : CC->Members)
2229 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2230 InstructionsToErase.count(cast<Instruction>(M))) &&
2231 "Everything in INITIAL should be unreachable or dead at this "
2232 "point");
2233#endif
2234 continue;
2235 }
2236
Davide Italiano7e274e02016-12-22 16:03:48 +00002237 assert(CC->RepLeader && "We should have had a leader");
2238
2239 // If this is a leader that is always available, and it's a
2240 // constant or has no equivalences, just replace everything with
2241 // it. We then update the congruence class with whatever members
2242 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002243 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2244 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002245 SmallPtrSet<Value *, 4> MembersLeft;
2246 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002247 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002248 // Void things have no uses we can replace.
2249 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2250 MembersLeft.insert(Member);
2251 continue;
2252 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002253 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2254 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002255 // Due to equality propagation, these may not always be
2256 // instructions, they may be real values. We don't really
2257 // care about trying to replace the non-instructions.
2258 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002259 assert(Leader != I && "About to accidentally remove our leader");
2260 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002261 AnythingReplaced = true;
2262
2263 continue;
2264 } else {
2265 MembersLeft.insert(I);
2266 }
2267 }
2268 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002269 } else {
2270 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2271 // If this is a singleton, we can skip it.
2272 if (CC->Members.size() != 1) {
2273
2274 // This is a stack because equality replacement/etc may place
2275 // constants in the middle of the member list, and we want to use
2276 // those constant values in preference to the current leader, over
2277 // the scope of those constants.
2278 ValueDFSStack EliminationStack;
2279
2280 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002281 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002282 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2283
2284 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002285 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002286 for (auto &VD : DFSOrderedSet) {
2287 int MemberDFSIn = VD.DFSIn;
2288 int MemberDFSOut = VD.DFSOut;
2289 Value *Member = VD.Val;
2290 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002291
Daniel Berlinc4796862017-01-27 02:37:11 +00002292 // We ignore void things because we can't get a value from them.
2293 if (Member && Member->getType()->isVoidTy())
2294 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002295
2296 if (EliminationStack.empty()) {
2297 DEBUG(dbgs() << "Elimination Stack is empty\n");
2298 } else {
2299 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2300 << EliminationStack.dfs_back().first << ","
2301 << EliminationStack.dfs_back().second << ")\n");
2302 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002303
2304 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2305 << MemberDFSOut << ")\n");
2306 // First, we see if we are out of scope or empty. If so,
2307 // and there equivalences, we try to replace the top of
2308 // stack with equivalences (if it's on the stack, it must
2309 // not have been eliminated yet).
2310 // Then we synchronize to our current scope, by
2311 // popping until we are back within a DFS scope that
2312 // dominates the current member.
2313 // Then, what happens depends on a few factors
2314 // If the stack is now empty, we need to push
2315 // If we have a constant or a local equivalence we want to
2316 // start using, we also push.
2317 // Otherwise, we walk along, processing members who are
2318 // dominated by this scope, and eliminate them.
2319 bool ShouldPush =
2320 Member && (EliminationStack.empty() || isa<Constant>(Member));
2321 bool OutOfScope =
2322 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2323
2324 if (OutOfScope || ShouldPush) {
2325 // Sync to our current scope.
2326 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2327 ShouldPush |= Member && EliminationStack.empty();
2328 if (ShouldPush) {
2329 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2330 }
2331 }
2332
2333 // If we get to this point, and the stack is empty we must have a use
2334 // with nothing we can use to eliminate it, just skip it.
2335 if (EliminationStack.empty())
2336 continue;
2337
2338 // Skip the Value's, we only want to eliminate on their uses.
2339 if (Member)
2340 continue;
2341 Value *Result = EliminationStack.back();
2342
Daniel Berlind92e7f92017-01-07 00:01:42 +00002343 // Don't replace our existing users with ourselves.
2344 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002345 continue;
2346
2347 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2348 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2349 << "\n");
2350
2351 // If we replaced something in an instruction, handle the patching of
2352 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002353 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002354 patchReplacementInstruction(ReplacedInst, Result);
2355
2356 assert(isa<Instruction>(MemberUse->getUser()));
2357 MemberUse->set(Result);
2358 AnythingReplaced = true;
2359 }
2360 }
2361 }
2362
2363 // Cleanup the congruence class.
2364 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002365 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002366 if (Member->getType()->isVoidTy()) {
2367 MembersLeft.insert(Member);
2368 continue;
2369 }
2370
2371 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2372 if (isInstructionTriviallyDead(MemberInst)) {
2373 // TODO: Don't mark loads of undefs.
2374 markInstructionForDeletion(MemberInst);
2375 continue;
2376 }
2377 }
2378 MembersLeft.insert(Member);
2379 }
2380 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002381
2382 // If we have possible dead stores to look at, try to eliminate them.
2383 if (CC->StoreCount > 0) {
2384 convertDenseToLoadsAndStores(CC->Members, PossibleDeadStores);
2385 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2386 ValueDFSStack EliminationStack;
2387 for (auto &VD : PossibleDeadStores) {
2388 int MemberDFSIn = VD.DFSIn;
2389 int MemberDFSOut = VD.DFSOut;
2390 Instruction *Member = cast<Instruction>(VD.Val);
2391 if (EliminationStack.empty() ||
2392 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2393 // Sync to our current scope.
2394 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2395 if (EliminationStack.empty()) {
2396 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2397 continue;
2398 }
2399 }
2400 // We already did load elimination, so nothing to do here.
2401 if (isa<LoadInst>(Member))
2402 continue;
2403 assert(!EliminationStack.empty());
2404 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002405 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002406 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2407 // Member is dominater by Leader, and thus dead
2408 DEBUG(dbgs() << "Marking dead store " << *Member
2409 << " that is dominated by " << *Leader << "\n");
2410 markInstructionForDeletion(Member);
2411 CC->Members.erase(Member);
2412 ++NumGVNDeadStores;
2413 }
2414 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002415 }
2416
2417 return AnythingReplaced;
2418}
Daniel Berlin1c087672017-02-11 15:07:01 +00002419
2420// This function provides global ranking of operations so that we can place them
2421// in a canonical order. Note that rank alone is not necessarily enough for a
2422// complete ordering, as constants all have the same rank. However, generally,
2423// we will simplify an operation with all constants so that it doesn't matter
2424// what order they appear in.
2425unsigned int NewGVN::getRank(const Value *V) const {
2426 if (isa<Constant>(V))
2427 return 0;
2428 else if (auto *A = dyn_cast<Argument>(V))
2429 return 1 + A->getArgNo();
2430
2431 // Need to shift the instruction DFS by number of arguments + 2 to account for
2432 // the constant and argument ranking above.
2433 unsigned Result = InstrDFS.lookup(V);
2434 if (Result > 0)
2435 return 2 + NumFuncArgs + Result;
2436 // Unreachable or something else, just return a really large number.
2437 return ~0;
2438}
2439
2440// This is a function that says whether two commutative operations should
2441// have their order swapped when canonicalizing.
2442bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
2443 // Because we only care about a total ordering, and don't rewrite expressions
2444 // in this order, we order by rank, which will give a strict weak ordering to
2445 // everything but constants, and then we order by pointer address. This is
2446 // not deterministic for constants, but it should not matter because any
2447 // operation with only constants will be folded (except, usually, for undef).
2448 return std::make_pair(getRank(B), B) > std::make_pair(getRank(A), A);
2449}