blob: a387b556be42ba3c3b6f1a5af357eee552ae6307 [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///
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar/NewGVN.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/DepthFirstIterator.h"
27#include "llvm/ADT/Hashing.h"
28#include "llvm/ADT/MapVector.h"
29#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000030#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SparseBitVector.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/TinyPtrVector.h"
36#include "llvm/Analysis/AliasAnalysis.h"
37#include "llvm/Analysis/AssumptionCache.h"
38#include "llvm/Analysis/CFG.h"
39#include "llvm/Analysis/CFGPrinter.h"
40#include "llvm/Analysis/ConstantFolding.h"
41#include "llvm/Analysis/GlobalsModRef.h"
42#include "llvm/Analysis/InstructionSimplify.h"
43#include "llvm/Analysis/Loads.h"
44#include "llvm/Analysis/MemoryBuiltins.h"
45#include "llvm/Analysis/MemoryDependenceAnalysis.h"
46#include "llvm/Analysis/MemoryLocation.h"
47#include "llvm/Analysis/PHITransAddr.h"
48#include "llvm/Analysis/TargetLibraryInfo.h"
49#include "llvm/Analysis/ValueTracking.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/GlobalVariable.h"
53#include "llvm/IR/IRBuilder.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
57#include "llvm/IR/PatternMatch.h"
58#include "llvm/IR/PredIteratorCache.h"
59#include "llvm/IR/Type.h"
60#include "llvm/Support/Allocator.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/Debug.h"
63#include "llvm/Transforms/Scalar.h"
64#include "llvm/Transforms/Scalar/GVNExpression.h"
65#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66#include "llvm/Transforms/Utils/Local.h"
67#include "llvm/Transforms/Utils/MemorySSA.h"
68#include "llvm/Transforms/Utils/SSAUpdater.h"
69#include <unordered_map>
70#include <utility>
71#include <vector>
72using namespace llvm;
73using namespace PatternMatch;
74using namespace llvm::GVNExpression;
75
76#define DEBUG_TYPE "newgvn"
77
78STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
79STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
80STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
81STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +000082STATISTIC(NumGVNMaxIterations,
83 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +000084STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
85STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
86STATISTIC(NumGVNAvoidedSortedLeaderChanges,
87 "Number of avoided sorted leader changes");
Davide Italiano7e274e02016-12-22 16:03:48 +000088
89//===----------------------------------------------------------------------===//
90// GVN Pass
91//===----------------------------------------------------------------------===//
92
93// Anchor methods.
94namespace llvm {
95namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +000096Expression::~Expression() = default;
97BasicExpression::~BasicExpression() = default;
98CallExpression::~CallExpression() = default;
99LoadExpression::~LoadExpression() = default;
100StoreExpression::~StoreExpression() = default;
101AggregateValueExpression::~AggregateValueExpression() = default;
102PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000103}
104}
105
106// Congruence classes represent the set of expressions/instructions
107// that are all the same *during some scope in the function*.
108// That is, because of the way we perform equality propagation, and
109// because of memory value numbering, it is not correct to assume
110// you can willy-nilly replace any member with any other at any
111// point in the function.
112//
113// For any Value in the Member set, it is valid to replace any dominated member
114// with that Value.
115//
116// Every congruence class has a leader, and the leader is used to
117// symbolize instructions in a canonical way (IE every operand of an
118// instruction that is a member of the same congruence class will
119// always be replaced with leader during symbolization).
120// To simplify symbolization, we keep the leader as a constant if class can be
121// proved to be a constant value.
122// Otherwise, the leader is a randomly chosen member of the value set, it does
123// not matter which one is chosen.
124// Each congruence class also has a defining expression,
125// though the expression may be null. If it exists, it can be used for forward
126// propagation and reassociation of values.
127//
128struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000129 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000130 unsigned ID;
131 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000132 Value *RepLeader = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000133 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000134 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000135 // Actual members of this class.
136 MemberSet Members;
137
138 // True if this class has no members left. This is mainly used for assertion
139 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000140 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000141
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000142 // Number of stores in this congruence class.
143 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000144 int StoreCount = 0;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000145
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000146 // The most dominating leader after our current leader, because the member set
147 // is not sorted and is expensive to keep sorted all the time.
148 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
149
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000150 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000151 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000152 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000153};
154
155namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000156template <> struct DenseMapInfo<const Expression *> {
157 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000158 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000159 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
160 return reinterpret_cast<const Expression *>(Val);
161 }
162 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000163 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000164 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
165 return reinterpret_cast<const Expression *>(Val);
166 }
167 static unsigned getHashValue(const Expression *V) {
168 return static_cast<unsigned>(V->getHashValue());
169 }
170 static bool isEqual(const Expression *LHS, const Expression *RHS) {
171 if (LHS == RHS)
172 return true;
173 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
174 LHS == getEmptyKey() || RHS == getEmptyKey())
175 return false;
176 return *LHS == *RHS;
177 }
178};
Davide Italiano7e274e02016-12-22 16:03:48 +0000179} // end namespace llvm
180
181class NewGVN : public FunctionPass {
182 DominatorTree *DT;
183 const DataLayout *DL;
184 const TargetLibraryInfo *TLI;
185 AssumptionCache *AC;
186 AliasAnalysis *AA;
187 MemorySSA *MSSA;
188 MemorySSAWalker *MSSAWalker;
189 BumpPtrAllocator ExpressionAllocator;
190 ArrayRecycler<Value *> ArgRecycler;
191
192 // Congruence class info.
193 CongruenceClass *InitialClass;
194 std::vector<CongruenceClass *> CongruenceClasses;
195 unsigned NextCongruenceNum;
196
197 // Value Mappings.
198 DenseMap<Value *, CongruenceClass *> ValueToClass;
199 DenseMap<Value *, const Expression *> ValueToExpression;
200
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000201 // A table storing which memorydefs/phis represent a memory state provably
202 // equivalent to another memory state.
203 // We could use the congruence class machinery, but the MemoryAccess's are
204 // abstract memory states, so they can only ever be equivalent to each other,
205 // and not to constants, etc.
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000206 DenseMap<const MemoryAccess *, MemoryAccess *> MemoryAccessEquiv;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000207
Davide Italiano7e274e02016-12-22 16:03:48 +0000208 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000209 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000210 ExpressionClassMap ExpressionToClass;
211
212 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000213 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000214
215 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000216 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000217 DenseSet<BlockEdge> ReachableEdges;
218 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
219
220 // This is a bitvector because, on larger functions, we may have
221 // thousands of touched instructions at once (entire blocks,
222 // instructions with hundreds of uses, etc). Even with optimization
223 // for when we mark whole blocks as touched, when this was a
224 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
225 // the time in GVN just managing this list. The bitvector, on the
226 // other hand, efficiently supports test/set/clear of both
227 // individual and ranges, as well as "find next element" This
228 // enables us to use it as a worklist with essentially 0 cost.
229 BitVector TouchedInstructions;
230
231 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
232 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
233 DominatedInstRange;
234
235#ifndef NDEBUG
236 // Debugging for how many times each block and instruction got processed.
237 DenseMap<const Value *, unsigned> ProcessedCount;
238#endif
239
240 // DFS info.
Davide Italiano7e274e02016-12-22 16:03:48 +0000241 DenseMap<const Value *, unsigned> InstrDFS;
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000242 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000243
244 // Deletion info.
245 SmallPtrSet<Instruction *, 8> InstructionsToErase;
246
247public:
248 static char ID; // Pass identification, replacement for typeid.
249 NewGVN() : FunctionPass(ID) {
250 initializeNewGVNPass(*PassRegistry::getPassRegistry());
251 }
252
253 bool runOnFunction(Function &F) override;
254 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000255 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000256
257private:
258 // This transformation requires dominator postdominator info.
259 void getAnalysisUsage(AnalysisUsage &AU) const override {
260 AU.addRequired<AssumptionCacheTracker>();
261 AU.addRequired<DominatorTreeWrapperPass>();
262 AU.addRequired<TargetLibraryInfoWrapperPass>();
263 AU.addRequired<MemorySSAWrapperPass>();
264 AU.addRequired<AAResultsWrapperPass>();
265
266 AU.addPreserved<DominatorTreeWrapperPass>();
267 AU.addPreserved<GlobalsAAWrapperPass>();
268 }
269
270 // Expression handling.
271 const Expression *createExpression(Instruction *, const BasicBlock *);
272 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
273 const BasicBlock *);
274 PHIExpression *createPHIExpression(Instruction *);
275 const VariableExpression *createVariableExpression(Value *);
276 const ConstantExpression *createConstantExpression(Constant *);
277 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000278 const UnknownExpression *createUnknownExpression(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000279 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
280 const BasicBlock *);
281 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
282 MemoryAccess *, const BasicBlock *);
283
284 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
285 const BasicBlock *);
286 const AggregateValueExpression *
287 createAggregateValueExpression(Instruction *, const BasicBlock *);
288 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
289 const BasicBlock *);
290
291 // Congruence class handling.
292 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000293 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000294 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000295 return result;
296 }
297
298 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000299 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000300 CClass->Members.insert(Member);
301 ValueToClass[Member] = CClass;
302 return CClass;
303 }
304 void initializeCongruenceClasses(Function &F);
305
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000306 // Value number an Instruction or MemoryPhi.
307 void valueNumberMemoryPhi(MemoryPhi *);
308 void valueNumberInstruction(Instruction *);
309
Davide Italiano7e274e02016-12-22 16:03:48 +0000310 // Symbolic evaluation.
311 const Expression *checkSimplificationResults(Expression *, Instruction *,
312 Value *);
313 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
314 const Expression *performSymbolicLoadEvaluation(Instruction *,
315 const BasicBlock *);
316 const Expression *performSymbolicStoreEvaluation(Instruction *,
317 const BasicBlock *);
318 const Expression *performSymbolicCallEvaluation(Instruction *,
319 const BasicBlock *);
320 const Expression *performSymbolicPHIEvaluation(Instruction *,
321 const BasicBlock *);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000322 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To);
Davide Italiano7e274e02016-12-22 16:03:48 +0000323 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
324 const BasicBlock *);
325
326 // Congruence finding.
327 // Templated to allow them to work both on BB's and BB-edges.
328 template <class T>
329 Value *lookupOperandLeader(Value *, const User *, const T &) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000330 void performCongruenceFinding(Instruction *, const Expression *);
331 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000332 CongruenceClass *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000333 // Reachability handling.
334 void updateReachableEdge(BasicBlock *, BasicBlock *);
335 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000336 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000337 Value *findConditionEquivalence(Value *, BasicBlock *) const;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000338 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000339
340 // Elimination.
341 struct ValueDFS;
342 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000343 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000344
345 bool eliminateInstructions(Function &);
346 void replaceInstruction(Instruction *, Value *);
347 void markInstructionForDeletion(Instruction *);
348 void deleteInstructionsInBlock(BasicBlock *);
349
350 // New instruction creation.
351 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000352
353 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000354 void markUsersTouched(Value *);
355 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000356 void markLeaderChangeTouched(CongruenceClass *CC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000357
358 // Utilities.
359 void cleanupTables();
360 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
361 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000362 void verifyMemoryCongruency() const;
363 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000364};
365
366char NewGVN::ID = 0;
367
368// createGVNPass - The public interface to this file.
369FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
370
Davide Italianob1114092016-12-28 13:37:17 +0000371template <typename T>
372static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
373 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000374 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000375 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000376 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000377 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000378 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000379 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000380 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000381 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000382 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000383 return true;
384}
385
Davide Italianob1114092016-12-28 13:37:17 +0000386bool LoadExpression::equals(const Expression &Other) const {
387 return equalsLoadStoreHelper(*this, Other);
388}
Davide Italiano7e274e02016-12-22 16:03:48 +0000389
Davide Italianob1114092016-12-28 13:37:17 +0000390bool StoreExpression::equals(const Expression &Other) const {
391 return equalsLoadStoreHelper(*this, Other);
Davide Italiano7e274e02016-12-22 16:03:48 +0000392}
393
394#ifndef NDEBUG
395static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000396 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000397}
398#endif
399
400INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
401INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
402INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
403INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
404INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
405INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
406INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
407INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
408
409PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000410 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000411 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000412 auto *E =
413 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000414
415 E->allocateOperands(ArgRecycler, ExpressionAllocator);
416 E->setType(I->getType());
417 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000418
419 auto ReachablePhiArg = [&](const Use &U) {
420 return ReachableBlocks.count(PN->getIncomingBlock(U));
421 };
422
423 // Filter out unreachable operands
424 auto Filtered = make_filter_range(PN->operands(), ReachablePhiArg);
425
426 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
427 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000428 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000429 if (U == PN)
430 return PN;
Daniel Berlind92e7f92017-01-07 00:01:42 +0000431 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PHIBlock);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000432 return lookupOperandLeader(U, I, BBE);
433 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000434 return E;
435}
436
437// Set basic expression info (Arguments, type, opcode) for Expression
438// E from Instruction I in block B.
439bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
440 const BasicBlock *B) {
441 bool AllConstant = true;
442 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
443 E->setType(GEP->getSourceElementType());
444 else
445 E->setType(I->getType());
446 E->setOpcode(I->getOpcode());
447 E->allocateOperands(ArgRecycler, ExpressionAllocator);
448
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000449 // Transform the operand array into an operand leader array, and keep track of
450 // whether all members are constant.
451 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000452 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000453 AllConstant &= isa<Constant>(Operand);
454 return Operand;
455 });
456
Davide Italiano7e274e02016-12-22 16:03:48 +0000457 return AllConstant;
458}
459
460const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
461 Value *Arg1, Value *Arg2,
462 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000463 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000464
465 E->setType(T);
466 E->setOpcode(Opcode);
467 E->allocateOperands(ArgRecycler, ExpressionAllocator);
468 if (Instruction::isCommutative(Opcode)) {
469 // Ensure that commutative instructions that only differ by a permutation
470 // of their operands get the same value number by sorting the operand value
471 // numbers. Since all commutative instructions have two operands it is more
472 // efficient to sort by hand rather than using, say, std::sort.
473 if (Arg1 > Arg2)
474 std::swap(Arg1, Arg2);
475 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000476 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
477 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000478
479 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
480 DT, AC);
481 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
482 return SimplifiedE;
483 return E;
484}
485
486// Take a Value returned by simplification of Expression E/Instruction
487// I, and see if it resulted in a simpler expression. If so, return
488// that expression.
489// TODO: Once finished, this should not take an Instruction, we only
490// use it for printing.
491const Expression *NewGVN::checkSimplificationResults(Expression *E,
492 Instruction *I, Value *V) {
493 if (!V)
494 return nullptr;
495 if (auto *C = dyn_cast<Constant>(V)) {
496 if (I)
497 DEBUG(dbgs() << "Simplified " << *I << " to "
498 << " constant " << *C << "\n");
499 NumGVNOpsSimplified++;
500 assert(isa<BasicExpression>(E) &&
501 "We should always have had a basic expression here");
502
503 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
504 ExpressionAllocator.Deallocate(E);
505 return createConstantExpression(C);
506 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
507 if (I)
508 DEBUG(dbgs() << "Simplified " << *I << " to "
509 << " variable " << *V << "\n");
510 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
511 ExpressionAllocator.Deallocate(E);
512 return createVariableExpression(V);
513 }
514
515 CongruenceClass *CC = ValueToClass.lookup(V);
516 if (CC && CC->DefiningExpr) {
517 if (I)
518 DEBUG(dbgs() << "Simplified " << *I << " to "
519 << " expression " << *V << "\n");
520 NumGVNOpsSimplified++;
521 assert(isa<BasicExpression>(E) &&
522 "We should always have had a basic expression here");
523 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
524 ExpressionAllocator.Deallocate(E);
525 return CC->DefiningExpr;
526 }
527 return nullptr;
528}
529
530const Expression *NewGVN::createExpression(Instruction *I,
531 const BasicBlock *B) {
532
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000533 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000534
535 bool AllConstant = setBasicExpressionInfo(I, E, B);
536
537 if (I->isCommutative()) {
538 // Ensure that commutative instructions that only differ by a permutation
539 // of their operands get the same value number by sorting the operand value
540 // numbers. Since all commutative instructions have two operands it is more
541 // efficient to sort by hand rather than using, say, std::sort.
542 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
543 if (E->getOperand(0) > E->getOperand(1))
544 E->swapOperands(0, 1);
545 }
546
547 // Perform simplificaiton
548 // TODO: Right now we only check to see if we get a constant result.
549 // We may get a less than constant, but still better, result for
550 // some operations.
551 // IE
552 // add 0, x -> x
553 // and x, x -> x
554 // We should handle this by simply rewriting the expression.
555 if (auto *CI = dyn_cast<CmpInst>(I)) {
556 // Sort the operand value numbers so x<y and y>x get the same value
557 // number.
558 CmpInst::Predicate Predicate = CI->getPredicate();
559 if (E->getOperand(0) > E->getOperand(1)) {
560 E->swapOperands(0, 1);
561 Predicate = CmpInst::getSwappedPredicate(Predicate);
562 }
563 E->setOpcode((CI->getOpcode() << 8) | Predicate);
564 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
565 // TODO: Since we noop bitcasts, we may need to check types before
566 // simplifying, so that we don't end up simplifying based on a wrong
567 // type assumption. We should clean this up so we can use constants of the
568 // wrong type
569
570 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
571 "Wrong types on cmp instruction");
572 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
573 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
574 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
575 *DL, TLI, DT, AC);
576 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
577 return SimplifiedE;
578 }
579 } else if (isa<SelectInst>(I)) {
580 if (isa<Constant>(E->getOperand(0)) ||
581 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
582 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
583 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
584 E->getOperand(2), *DL, TLI, DT, AC);
585 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
586 return SimplifiedE;
587 }
588 } else if (I->isBinaryOp()) {
589 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
590 *DL, TLI, DT, AC);
591 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
592 return SimplifiedE;
593 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
594 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
595 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
596 return SimplifiedE;
597 } else if (isa<GetElementPtrInst>(I)) {
598 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000599 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000600 *DL, TLI, DT, AC);
601 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
602 return SimplifiedE;
603 } else if (AllConstant) {
604 // We don't bother trying to simplify unless all of the operands
605 // were constant.
606 // TODO: There are a lot of Simplify*'s we could call here, if we
607 // wanted to. The original motivating case for this code was a
608 // zext i1 false to i8, which we don't have an interface to
609 // simplify (IE there is no SimplifyZExt).
610
611 SmallVector<Constant *, 8> C;
612 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000613 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000614
615 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
616 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
617 return SimplifiedE;
618 }
619 return E;
620}
621
622const AggregateValueExpression *
623NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
624 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000625 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000626 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
627 setBasicExpressionInfo(I, E, B);
628 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000629 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000630 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000631 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000632 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000633 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
634 setBasicExpressionInfo(EI, E, B);
635 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000636 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000637 return E;
638 }
639 llvm_unreachable("Unhandled type of aggregate value operation");
640}
641
Daniel Berlin85f91b02016-12-26 20:06:58 +0000642const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000643 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000644 E->setOpcode(V->getValueID());
645 return E;
646}
647
648const Expression *NewGVN::createVariableOrConstant(Value *V,
649 const BasicBlock *B) {
650 auto Leader = lookupOperandLeader(V, nullptr, B);
651 if (auto *C = dyn_cast<Constant>(Leader))
652 return createConstantExpression(C);
653 return createVariableExpression(Leader);
654}
655
Daniel Berlin85f91b02016-12-26 20:06:58 +0000656const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000657 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000658 E->setOpcode(C->getValueID());
659 return E;
660}
661
Daniel Berlin02c6b172017-01-02 18:00:53 +0000662const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
663 auto *E = new (ExpressionAllocator) UnknownExpression(I);
664 E->setOpcode(I->getOpcode());
665 return E;
666}
667
Davide Italiano7e274e02016-12-22 16:03:48 +0000668const CallExpression *NewGVN::createCallExpression(CallInst *CI,
669 MemoryAccess *HV,
670 const BasicBlock *B) {
671 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000672 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000673 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
674 setBasicExpressionInfo(CI, E, B);
675 return E;
676}
677
678// See if we have a congruence class and leader for this operand, and if so,
679// return it. Otherwise, return the operand itself.
680template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000681Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000682 CongruenceClass *CC = ValueToClass.lookup(V);
683 if (CC && (CC != InitialClass))
684 return CC->RepLeader;
685 return V;
686}
687
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000688MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
689 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
690 return Result ? Result : MA;
691}
692
Davide Italiano7e274e02016-12-22 16:03:48 +0000693LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
694 LoadInst *LI, MemoryAccess *DA,
695 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000696 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000697 E->allocateOperands(ArgRecycler, ExpressionAllocator);
698 E->setType(LoadType);
699
700 // Give store and loads same opcode so they value number together.
701 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000702 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000703 if (LI)
704 E->setAlignment(LI->getAlignment());
705
706 // TODO: Value number heap versions. We may be able to discover
707 // things alias analysis can't on it's own (IE that a store and a
708 // load have the same value, and thus, it isn't clobbering the load).
709 return E;
710}
711
712const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
713 MemoryAccess *DA,
714 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000715 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000716 new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, DA);
717 E->allocateOperands(ArgRecycler, ExpressionAllocator);
718 E->setType(SI->getValueOperand()->getType());
719
720 // Give store and loads same opcode so they value number together.
721 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000722 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000723
724 // TODO: Value number heap versions. We may be able to discover
725 // things alias analysis can't on it's own (IE that a store and a
726 // load have the same value, and thus, it isn't clobbering the load).
727 return E;
728}
729
Daniel Berlinb755aea2017-01-09 05:34:29 +0000730// Utility function to check whether the congruence class has a member other
731// than the given instruction.
732bool hasMemberOtherThanUs(const CongruenceClass *CC, Instruction *I) {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000733 // Either it has more than one store, in which case it must contain something
734 // other than us (because it's indexed by value), or if it only has one store
Daniel Berlinb755aea2017-01-09 05:34:29 +0000735 // right now, that member should not be us.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000736 return CC->StoreCount > 1 || CC->Members.count(I) == 0;
Daniel Berlinb755aea2017-01-09 05:34:29 +0000737}
738
Davide Italiano7e274e02016-12-22 16:03:48 +0000739const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
740 const BasicBlock *B) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000741 // Unlike loads, we never try to eliminate stores, so we do not check if they
742 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000743 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000744 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinde43ef92017-01-02 19:49:17 +0000745 // See if we are defined by a previous store expression, it already has a
746 // value, and it's the same value as our current store. FIXME: Right now, we
747 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000748 if (SI->isSimple()) {
Daniel Berlinde43ef92017-01-02 19:49:17 +0000749 // Get the expression, if any, for the RHS of the MemoryDef.
750 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
751 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
752 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000753 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000754 // Basically, check if the congruence class the store is in is defined by a
755 // store that isn't us, and has the same value. MemorySSA takes care of
756 // ensuring the store has the same memory state as us already.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000757 if (CC && CC->DefiningExpr && isa<StoreExpression>(CC->DefiningExpr) &&
Daniel Berlinb755aea2017-01-09 05:34:29 +0000758 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B) &&
759 hasMemberOtherThanUs(CC, I))
Daniel Berlin589cecc2017-01-02 18:00:46 +0000760 return createStoreExpression(SI, StoreRHS, B);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000761 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000762
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000763 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000764}
765
766const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
767 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000768 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000769
770 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000771 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000772 if (!LI->isSimple())
773 return nullptr;
774
Daniel Berlin85f91b02016-12-26 20:06:58 +0000775 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000776 // Load of undef is undef.
777 if (isa<UndefValue>(LoadAddressLeader))
778 return createConstantExpression(UndefValue::get(LI->getType()));
779
780 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
781
782 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
783 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
784 Instruction *DefiningInst = MD->getMemoryInst();
785 // If the defining instruction is not reachable, replace with undef.
786 if (!ReachableBlocks.count(DefiningInst->getParent()))
787 return createConstantExpression(UndefValue::get(LI->getType()));
788 }
789 }
790
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000791 const Expression *E =
792 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
793 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000794 return E;
795}
796
797// Evaluate read only and pure calls, and create an expression result.
798const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
799 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000800 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000801 if (AA->doesNotAccessMemory(CI))
802 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000803 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000804 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000805 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000806 }
807 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000808}
809
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000810// Update the memory access equivalence table to say that From is equal to To,
811// and return true if this is different from what already existed in the table.
812bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
Davide Italiano84126162017-01-02 18:41:34 +0000813 DEBUG(dbgs() << "Setting " << *From << " equivalent to ");
814 if (!To)
815 DEBUG(dbgs() << "itself");
816 else
817 DEBUG(dbgs() << *To);
818 DEBUG(dbgs() << "\n");
Daniel Berlin589cecc2017-01-02 18:00:46 +0000819 auto LookupResult = MemoryAccessEquiv.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000820 bool Changed = false;
821 // If it's already in the table, see if the value changed.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000822 if (LookupResult != MemoryAccessEquiv.end()) {
823 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000824 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000825 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000826 Changed = true;
827 } else if (!To) {
828 // It used to be equivalent to something, and now it's not.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000829 MemoryAccessEquiv.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000830 Changed = true;
831 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000832 } else {
833 assert(!To &&
834 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000835 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000836
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000837 return Changed;
838}
Davide Italiano7e274e02016-12-22 16:03:48 +0000839// Evaluate PHI nodes symbolically, and create an expression result.
840const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
841 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000842 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000843 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
844
845 // See if all arguaments are the same.
846 // We track if any were undef because they need special handling.
847 bool HasUndef = false;
848 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
849 if (Arg == I)
850 return false;
851 if (isa<UndefValue>(Arg)) {
852 HasUndef = true;
853 return false;
854 }
855 return true;
856 });
857 // If we are left with no operands, it's undef
858 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000859 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
860 << "\n");
861 E->deallocateOperands(ArgRecycler);
862 ExpressionAllocator.Deallocate(E);
863 return createConstantExpression(UndefValue::get(I->getType()));
864 }
Daniel Berlind92e7f92017-01-07 00:01:42 +0000865 Value *AllSameValue = *(Filtered.begin());
866 ++Filtered.begin();
867 // Can't use std::equal here, sadly, because filter.begin moves.
868 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
869 return V == AllSameValue;
870 })) {
871 // In LLVM's non-standard representation of phi nodes, it's possible to have
872 // phi nodes with cycles (IE dependent on other phis that are .... dependent
873 // on the original phi node), especially in weird CFG's where some arguments
874 // are unreachable, or uninitialized along certain paths. This can cause
875 // infinite loops during evaluation. We work around this by not trying to
876 // really evaluate them independently, but instead using a variable
877 // expression to say if one is equivalent to the other.
878 // We also special case undef, so that if we have an undef, we can't use the
879 // common value unless it dominates the phi block.
880 if (HasUndef) {
881 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +0000882 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +0000883 if (!DT->dominates(AllSameInst, I))
884 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000885 }
886
Davide Italiano7e274e02016-12-22 16:03:48 +0000887 NumGVNPhisAllSame++;
888 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
889 << "\n");
890 E->deallocateOperands(ArgRecycler);
891 ExpressionAllocator.Deallocate(E);
892 if (auto *C = dyn_cast<Constant>(AllSameValue))
893 return createConstantExpression(C);
894 return createVariableExpression(AllSameValue);
895 }
896 return E;
897}
898
899const Expression *
900NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
901 const BasicBlock *B) {
902 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
903 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
904 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
905 unsigned Opcode = 0;
906 // EI might be an extract from one of our recognised intrinsics. If it
907 // is we'll synthesize a semantically equivalent expression instead on
908 // an extract value expression.
909 switch (II->getIntrinsicID()) {
910 case Intrinsic::sadd_with_overflow:
911 case Intrinsic::uadd_with_overflow:
912 Opcode = Instruction::Add;
913 break;
914 case Intrinsic::ssub_with_overflow:
915 case Intrinsic::usub_with_overflow:
916 Opcode = Instruction::Sub;
917 break;
918 case Intrinsic::smul_with_overflow:
919 case Intrinsic::umul_with_overflow:
920 Opcode = Instruction::Mul;
921 break;
922 default:
923 break;
924 }
925
926 if (Opcode != 0) {
927 // Intrinsic recognized. Grab its args to finish building the
928 // expression.
929 assert(II->getNumArgOperands() == 2 &&
930 "Expect two args for recognised intrinsics.");
931 return createBinaryExpression(Opcode, EI->getType(),
932 II->getArgOperand(0),
933 II->getArgOperand(1), B);
934 }
935 }
936 }
937
938 return createAggregateValueExpression(I, B);
939}
940
941// Substitute and symbolize the value before value numbering.
942const Expression *NewGVN::performSymbolicEvaluation(Value *V,
943 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000944 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000945 if (auto *C = dyn_cast<Constant>(V))
946 E = createConstantExpression(C);
947 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
948 E = createVariableExpression(V);
949 } else {
950 // TODO: memory intrinsics.
951 // TODO: Some day, we should do the forward propagation and reassociation
952 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000953 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000954 switch (I->getOpcode()) {
955 case Instruction::ExtractValue:
956 case Instruction::InsertValue:
957 E = performSymbolicAggrValueEvaluation(I, B);
958 break;
959 case Instruction::PHI:
960 E = performSymbolicPHIEvaluation(I, B);
961 break;
962 case Instruction::Call:
963 E = performSymbolicCallEvaluation(I, B);
964 break;
965 case Instruction::Store:
966 E = performSymbolicStoreEvaluation(I, B);
967 break;
968 case Instruction::Load:
969 E = performSymbolicLoadEvaluation(I, B);
970 break;
971 case Instruction::BitCast: {
972 E = createExpression(I, B);
973 } break;
974
975 case Instruction::Add:
976 case Instruction::FAdd:
977 case Instruction::Sub:
978 case Instruction::FSub:
979 case Instruction::Mul:
980 case Instruction::FMul:
981 case Instruction::UDiv:
982 case Instruction::SDiv:
983 case Instruction::FDiv:
984 case Instruction::URem:
985 case Instruction::SRem:
986 case Instruction::FRem:
987 case Instruction::Shl:
988 case Instruction::LShr:
989 case Instruction::AShr:
990 case Instruction::And:
991 case Instruction::Or:
992 case Instruction::Xor:
993 case Instruction::ICmp:
994 case Instruction::FCmp:
995 case Instruction::Trunc:
996 case Instruction::ZExt:
997 case Instruction::SExt:
998 case Instruction::FPToUI:
999 case Instruction::FPToSI:
1000 case Instruction::UIToFP:
1001 case Instruction::SIToFP:
1002 case Instruction::FPTrunc:
1003 case Instruction::FPExt:
1004 case Instruction::PtrToInt:
1005 case Instruction::IntToPtr:
1006 case Instruction::Select:
1007 case Instruction::ExtractElement:
1008 case Instruction::InsertElement:
1009 case Instruction::ShuffleVector:
1010 case Instruction::GetElementPtr:
1011 E = createExpression(I, B);
1012 break;
1013 default:
1014 return nullptr;
1015 }
1016 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001017 return E;
1018}
1019
1020// There is an edge from 'Src' to 'Dst'. Return true if every path from
1021// the entry block to 'Dst' passes via this edge. In particular 'Dst'
1022// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +00001023bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001024
1025 // While in theory it is interesting to consider the case in which Dst has
1026 // more than one predecessor, because Dst might be part of a loop which is
1027 // only reachable from Src, in practice it is pointless since at the time
1028 // GVN runs all such loops have preheaders, which means that Dst will have
1029 // been changed to have only one predecessor, namely Src.
1030 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1031 const BasicBlock *Src = E.getStart();
1032 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
1033 (void)Src;
1034 return Pred != nullptr;
1035}
1036
1037void NewGVN::markUsersTouched(Value *V) {
1038 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001039 for (auto *User : V->users()) {
1040 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Davide Italiano7e274e02016-12-22 16:03:48 +00001041 TouchedInstructions.set(InstrDFS[User]);
1042 }
1043}
1044
1045void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1046 for (auto U : MA->users()) {
1047 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
1048 TouchedInstructions.set(InstrDFS[MUD->getMemoryInst()]);
1049 else
Daniel Berline0bd37e2016-12-29 22:15:12 +00001050 TouchedInstructions.set(InstrDFS[U]);
Davide Italiano7e274e02016-12-22 16:03:48 +00001051 }
1052}
1053
Daniel Berlin32f8d562017-01-07 16:55:14 +00001054// Touch the instructions that need to be updated after a congruence class has a
1055// leader change, and mark changed values.
1056void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1057 for (auto M : CC->Members) {
1058 if (auto *I = dyn_cast<Instruction>(M))
1059 TouchedInstructions.set(InstrDFS[I]);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001060 LeaderChanges.insert(M);
1061 }
1062}
1063
1064// Move a value, currently in OldClass, to be part of NewClass
1065// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001066void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1067 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001068 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001069 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001070 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001071
1072 if (I == OldClass->NextLeader.first)
1073 OldClass->NextLeader = {nullptr, ~0U};
1074
1075 // The new instruction and new class leader may either be siblings in the
1076 // dominator tree, or the new class leader should dominate the new member
1077 // instruction. We simply check that the member instruction does not properly
1078 // dominate the new class leader.
1079 assert(
1080 !isa<Instruction>(NewClass->RepLeader) || !NewClass->RepLeader ||
1081 I == NewClass->RepLeader ||
1082 !DT->properlyDominates(
1083 I->getParent(),
1084 cast<Instruction>(NewClass->RepLeader)->getParent()) &&
1085 "New class for instruction should not be dominated by instruction");
1086
1087 if (NewClass->RepLeader != I) {
1088 auto DFSNum = InstrDFS.lookup(I);
1089 if (DFSNum < NewClass->NextLeader.second)
1090 NewClass->NextLeader = {I, DFSNum};
1091 }
1092
1093 OldClass->Members.erase(I);
1094 NewClass->Members.insert(I);
1095 if (isa<StoreInst>(I)) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001096 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001097 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001098 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001099 assert(NewClass->StoreCount > 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001100 }
1101
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001102 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001103 // See if we destroyed the class or need to swap leaders.
1104 if (OldClass->Members.empty() && OldClass != InitialClass) {
1105 if (OldClass->DefiningExpr) {
1106 OldClass->Dead = true;
1107 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1108 << " from table\n");
1109 ExpressionToClass.erase(OldClass->DefiningExpr);
1110 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001111 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001112 // When the leader changes, the value numbering of
1113 // everything may change due to symbolization changes, so we need to
1114 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001115 DEBUG(dbgs() << "Leader change!\n");
1116 ++NumGVNLeaderChanges;
1117 // We don't need to sort members if there is only 1, and we don't care about
1118 // sorting the initial class because everything either gets out of it or is
1119 // unreachable.
1120 if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1121 OldClass->RepLeader = *(OldClass->Members.begin());
1122 } else if (OldClass->NextLeader.first) {
1123 ++NumGVNAvoidedSortedLeaderChanges;
1124 OldClass->RepLeader = OldClass->NextLeader.first;
1125 OldClass->NextLeader = {nullptr, ~0U};
1126 } else {
1127 ++NumGVNSortedLeaderChanges;
1128 // TODO: If this ends up to slow, we can maintain a dual structure for
1129 // member testing/insertion, or keep things mostly sorted, and sort only
1130 // here, or ....
1131 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1132 for (const auto X : OldClass->Members) {
1133 auto DFSNum = InstrDFS.lookup(X);
1134 if (DFSNum < MinDFS.second)
1135 MinDFS = {X, DFSNum};
1136 }
1137 OldClass->RepLeader = MinDFS.first;
1138 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001139 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001140 }
1141}
1142
Davide Italiano7e274e02016-12-22 16:03:48 +00001143// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001144void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1145 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001146 // This is guaranteed to return something, since it will at least find
1147 // INITIAL.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001148
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001149 CongruenceClass *IClass = ValueToClass[I];
1150 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001151 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001152 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001153
1154 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001155 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001156 EClass = ValueToClass[VE->getVariableValue()];
1157 } else {
1158 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1159
1160 // If it's not in the value table, create a new congruence class.
1161 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001162 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001163 auto place = lookupResult.first;
1164 place->second = NewClass;
1165
1166 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001167 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001168 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001169 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1170 StoreInst *SI = SE->getStoreInst();
1171 NewClass->RepLeader =
1172 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
1173 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001174 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001175 }
1176 assert(!isa<VariableExpression>(E) &&
1177 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001178
1179 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001180 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001181 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin589cecc2017-01-02 18:00:46 +00001182 << " and leader " << *(NewClass->RepLeader) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001183 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1184 } else {
1185 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001186 if (isa<ConstantExpression>(E))
1187 assert(isa<Constant>(EClass->RepLeader) &&
1188 "Any class with a constant expression should have a "
1189 "constant leader");
1190
Davide Italiano7e274e02016-12-22 16:03:48 +00001191 assert(EClass && "Somehow don't have an eclass");
1192
1193 assert(!EClass->Dead && "We accidentally looked up a dead class");
1194 }
1195 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001196 bool ClassChanged = IClass != EClass;
1197 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001198 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001199 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1200 << "\n");
1201
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001202 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001203 moveValueToNewCongruenceClass(I, IClass, EClass);
1204 markUsersTouched(I);
1205 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
1206 // If this is a MemoryDef, we need to update the equivalence table. If
1207 // we determined the expression is congruent to a different memory
1208 // state, use that different memory state. If we determined it didn't,
1209 // we update that as well. Right now, we only support store
1210 // expressions.
1211 if (!isa<MemoryUse>(MA) && isa<StoreExpression>(E) &&
1212 EClass->Members.size() != 1) {
1213 auto *DefAccess = cast<StoreExpression>(E)->getDefiningAccess();
1214 setMemoryAccessEquivTo(MA, DefAccess != MA ? DefAccess : nullptr);
1215 } else {
1216 setMemoryAccessEquivTo(MA, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001217 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001218 markMemoryUsersTouched(MA);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001219 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001220 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001221 // There is, sadly, one complicating thing for stores. Stores do not
1222 // produce values, only consume them. However, in order to make loads and
1223 // stores value number the same, we ignore the value operand of the store.
1224 // But the value operand will still be the leader of our class, and thus, it
1225 // may change. Because the store is a use, the store will get reprocessed,
1226 // but nothing will change about it, and so nothing above will catch it
1227 // (since the class will not change). In order to make sure everything ends
1228 // up okay, we need to recheck the leader of the class. Since stores of
1229 // different values value number differently due to different memorydefs, we
1230 // are guaranteed the leader is always the same between stores in the same
1231 // class.
1232 DEBUG(dbgs() << "Checking store leader\n");
1233 auto ProperLeader =
1234 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
1235 if (EClass->RepLeader != ProperLeader) {
1236 DEBUG(dbgs() << "Store leader changed, fixing\n");
1237 EClass->RepLeader = ProperLeader;
1238 markLeaderChangeTouched(EClass);
1239 markMemoryUsersTouched(MSSA->getMemoryAccess(SI));
1240 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001241 }
1242}
1243
1244// Process the fact that Edge (from, to) is reachable, including marking
1245// any newly reachable blocks and instructions for processing.
1246void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1247 // Check if the Edge was reachable before.
1248 if (ReachableEdges.insert({From, To}).second) {
1249 // If this block wasn't reachable before, all instructions are touched.
1250 if (ReachableBlocks.insert(To).second) {
1251 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1252 const auto &InstRange = BlockInstRange.lookup(To);
1253 TouchedInstructions.set(InstRange.first, InstRange.second);
1254 } else {
1255 DEBUG(dbgs() << "Block " << getBlockName(To)
1256 << " was reachable, but new edge {" << getBlockName(From)
1257 << "," << getBlockName(To) << "} to it found\n");
1258
1259 // We've made an edge reachable to an existing block, which may
1260 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1261 // they are the only thing that depend on new edges. Anything using their
1262 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001263 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
1264 TouchedInstructions.set(InstrDFS[MemPhi]);
1265
Davide Italiano7e274e02016-12-22 16:03:48 +00001266 auto BI = To->begin();
1267 while (isa<PHINode>(BI)) {
1268 TouchedInstructions.set(InstrDFS[&*BI]);
1269 ++BI;
1270 }
1271 }
1272 }
1273}
1274
1275// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1276// see if we know some constant value for it already.
1277Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1278 auto Result = lookupOperandLeader(Cond, nullptr, B);
1279 if (isa<Constant>(Result))
1280 return Result;
1281 return nullptr;
1282}
1283
1284// Process the outgoing edges of a block for reachability.
1285void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1286 // Evaluate reachability of terminator instruction.
1287 BranchInst *BR;
1288 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1289 Value *Cond = BR->getCondition();
1290 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1291 if (!CondEvaluated) {
1292 if (auto *I = dyn_cast<Instruction>(Cond)) {
1293 const Expression *E = createExpression(I, B);
1294 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1295 CondEvaluated = CE->getConstantValue();
1296 }
1297 } else if (isa<ConstantInt>(Cond)) {
1298 CondEvaluated = Cond;
1299 }
1300 }
1301 ConstantInt *CI;
1302 BasicBlock *TrueSucc = BR->getSuccessor(0);
1303 BasicBlock *FalseSucc = BR->getSuccessor(1);
1304 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1305 if (CI->isOne()) {
1306 DEBUG(dbgs() << "Condition for Terminator " << *TI
1307 << " evaluated to true\n");
1308 updateReachableEdge(B, TrueSucc);
1309 } else if (CI->isZero()) {
1310 DEBUG(dbgs() << "Condition for Terminator " << *TI
1311 << " evaluated to false\n");
1312 updateReachableEdge(B, FalseSucc);
1313 }
1314 } else {
1315 updateReachableEdge(B, TrueSucc);
1316 updateReachableEdge(B, FalseSucc);
1317 }
1318 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1319 // For switches, propagate the case values into the case
1320 // destinations.
1321
1322 // Remember how many outgoing edges there are to every successor.
1323 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1324
Davide Italiano7e274e02016-12-22 16:03:48 +00001325 Value *SwitchCond = SI->getCondition();
1326 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1327 // See if we were able to turn this switch statement into a constant.
1328 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001329 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001330 // We should be able to get case value for this.
1331 auto CaseVal = SI->findCaseValue(CondVal);
1332 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1333 // We proved the value is outside of the range of the case.
1334 // We can't do anything other than mark the default dest as reachable,
1335 // and go home.
1336 updateReachableEdge(B, SI->getDefaultDest());
1337 return;
1338 }
1339 // Now get where it goes and mark it reachable.
1340 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1341 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001342 } else {
1343 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1344 BasicBlock *TargetBlock = SI->getSuccessor(i);
1345 ++SwitchEdges[TargetBlock];
1346 updateReachableEdge(B, TargetBlock);
1347 }
1348 }
1349 } else {
1350 // Otherwise this is either unconditional, or a type we have no
1351 // idea about. Just mark successors as reachable.
1352 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1353 BasicBlock *TargetBlock = TI->getSuccessor(i);
1354 updateReachableEdge(B, TargetBlock);
1355 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001356
1357 // This also may be a memory defining terminator, in which case, set it
1358 // equivalent to nothing.
1359 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1360 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001361 }
1362}
1363
Daniel Berlin85f91b02016-12-26 20:06:58 +00001364// The algorithm initially places the values of the routine in the INITIAL
1365// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001366// class. The leader of INITIAL is the undetermined value `TOP`.
1367// When the algorithm has finished, values still in INITIAL are unreachable.
1368void NewGVN::initializeCongruenceClasses(Function &F) {
1369 // FIXME now i can't remember why this is 2
1370 NextCongruenceNum = 2;
1371 // Initialize all other instructions to be in INITIAL class.
1372 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001373 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001374 for (auto &B : F) {
1375 if (auto *MP = MSSA->getMemoryAccess(&B))
1376 MemoryAccessEquiv.insert({MP, MSSA->getLiveOnEntryDef()});
1377
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001378 for (auto &I : B) {
1379 InitialValues.insert(&I);
1380 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001381 // All memory accesses are equivalent to live on entry to start. They must
1382 // be initialized to something so that initial changes are noticed. For
1383 // the maximal answer, we initialize them all to be the same as
1384 // liveOnEntry. Note that to save time, we only initialize the
1385 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1386 // other expression can generate a memory equivalence. If we start
1387 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001388 if (isa<StoreInst>(&I)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001389 MemoryAccessEquiv.insert(
1390 {MSSA->getMemoryAccess(&I), MSSA->getLiveOnEntryDef()});
Davide Italianoeac05f62017-01-11 23:41:24 +00001391 ++InitialClass->StoreCount;
1392 assert(InitialClass->StoreCount > 0);
1393 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001394 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001395 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001396 InitialClass->Members.swap(InitialValues);
1397
1398 // Initialize arguments to be in their own unique congruence classes
1399 for (auto &FA : F.args())
1400 createSingletonCongruenceClass(&FA);
1401}
1402
1403void NewGVN::cleanupTables() {
1404 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1405 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1406 << CongruenceClasses[i]->Members.size() << " members\n");
1407 // Make sure we delete the congruence class (probably worth switching to
1408 // a unique_ptr at some point.
1409 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001410 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001411 }
1412
1413 ValueToClass.clear();
1414 ArgRecycler.clear(ExpressionAllocator);
1415 ExpressionAllocator.Reset();
1416 CongruenceClasses.clear();
1417 ExpressionToClass.clear();
1418 ValueToExpression.clear();
1419 ReachableBlocks.clear();
1420 ReachableEdges.clear();
1421#ifndef NDEBUG
1422 ProcessedCount.clear();
1423#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001424 InstrDFS.clear();
1425 InstructionsToErase.clear();
1426
1427 DFSToInstr.clear();
1428 BlockInstRange.clear();
1429 TouchedInstructions.clear();
1430 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001431 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001432}
1433
1434std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1435 unsigned Start) {
1436 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001437 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1438 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001439 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001440 }
1441
Davide Italiano7e274e02016-12-22 16:03:48 +00001442 for (auto &I : *B) {
1443 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001444 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001445 }
1446
1447 // All of the range functions taken half-open ranges (open on the end side).
1448 // So we do not subtract one from count, because at this point it is one
1449 // greater than the last instruction.
1450 return std::make_pair(Start, End);
1451}
1452
1453void NewGVN::updateProcessedCount(Value *V) {
1454#ifndef NDEBUG
1455 if (ProcessedCount.count(V) == 0) {
1456 ProcessedCount.insert({V, 1});
1457 } else {
1458 ProcessedCount[V] += 1;
1459 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001460 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001461 }
1462#endif
1463}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001464// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1465void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1466 // If all the arguments are the same, the MemoryPhi has the same value as the
1467 // argument.
1468 // Filter out unreachable blocks from our operands.
1469 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1470 return ReachableBlocks.count(MP->getIncomingBlock(U));
1471 });
1472
1473 assert(Filtered.begin() != Filtered.end() &&
1474 "We should not be processing a MemoryPhi in a completely "
1475 "unreachable block");
1476
1477 // Transform the remaining operands into operand leaders.
1478 // FIXME: mapped_iterator should have a range version.
1479 auto LookupFunc = [&](const Use &U) {
1480 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1481 };
1482 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1483 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1484
1485 // and now check if all the elements are equal.
1486 // Sadly, we can't use std::equals since these are random access iterators.
1487 MemoryAccess *AllSameValue = *MappedBegin;
1488 ++MappedBegin;
1489 bool AllEqual = std::all_of(
1490 MappedBegin, MappedEnd,
1491 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1492
1493 if (AllEqual)
1494 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1495 else
1496 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1497
1498 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1499 markMemoryUsersTouched(MP);
1500}
1501
1502// Value number a single instruction, symbolically evaluating, performing
1503// congruence finding, and updating mappings.
1504void NewGVN::valueNumberInstruction(Instruction *I) {
1505 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001506 if (isInstructionTriviallyDead(I, TLI)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001507 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001508 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001509 return;
1510 }
1511 if (!I->isTerminator()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001512 const auto *Symbolized = performSymbolicEvaluation(I, I->getParent());
1513 // If we couldn't come up with a symbolic expression, use the unknown
1514 // expression
1515 if (Symbolized == nullptr)
1516 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001517 performCongruenceFinding(I, Symbolized);
1518 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001519 // Handle terminators that return values. All of them produce values we
1520 // don't currently understand.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001521 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001522 auto *Symbolized = createUnknownExpression(I);
1523 performCongruenceFinding(I, Symbolized);
1524 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001525 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1526 }
1527}
Davide Italiano7e274e02016-12-22 16:03:48 +00001528
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001529// Check if there is a path, using single or equal argument phi nodes, from
1530// First to Second.
1531bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1532 const MemoryAccess *Second) const {
1533 if (First == Second)
1534 return true;
1535
1536 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1537 auto *DefAccess = FirstDef->getDefiningAccess();
1538 return singleReachablePHIPath(DefAccess, Second);
1539 } else {
1540 auto *MP = cast<MemoryPhi>(First);
1541 auto ReachableOperandPred = [&](const Use &U) {
1542 return ReachableBlocks.count(MP->getIncomingBlock(U));
1543 };
1544 auto FilteredPhiArgs =
1545 make_filter_range(MP->operands(), ReachableOperandPred);
1546 SmallVector<const Value *, 32> OperandList;
1547 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1548 std::back_inserter(OperandList));
1549 bool Okay = OperandList.size() == 1;
1550 if (!Okay)
1551 Okay = std::equal(OperandList.begin(), OperandList.end(),
1552 OperandList.begin());
1553 if (Okay)
1554 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1555 return false;
1556 }
1557}
1558
Daniel Berlin589cecc2017-01-02 18:00:46 +00001559// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001560// congruence classes. Note that this checking is not perfect, and is currently
1561// subject to very rare false negatives. It is only useful for testing/debugging.
1562void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001563 // Anything equivalent in the memory access table should be in the same
1564 // congruence class.
1565
1566 // Filter out the unreachable and trivially dead entries, because they may
1567 // never have been updated if the instructions were not processed.
1568 auto ReachableAccessPred =
1569 [&](const std::pair<const MemoryAccess *, MemoryAccess *> Pair) {
1570 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1571 if (!Result)
1572 return false;
1573 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1574 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1575 return true;
1576 };
1577
1578 auto Filtered = make_filter_range(MemoryAccessEquiv, ReachableAccessPred);
1579 for (auto KV : Filtered) {
1580 assert(KV.first != KV.second &&
1581 "We added a useless equivalence to the memory equivalence table");
1582 // Unreachable instructions may not have changed because we never process
1583 // them.
1584 if (!ReachableBlocks.count(KV.first->getBlock()))
1585 continue;
1586 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
1587 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second);
Davide Italiano67ada752017-01-02 19:03:16 +00001588 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001589 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001590 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
Davide Italianoff694052017-01-11 21:58:42 +00001591 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001592 "The instructions for these memory operations should have "
Davide Italianoff694052017-01-11 21:58:42 +00001593 "been in the same congruence class or reachable through"
1594 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001595 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1596
1597 // We can only sanely verify that MemoryDefs in the operand list all have
1598 // the same class.
1599 auto ReachableOperandPred = [&](const Use &U) {
1600 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1601 isa<MemoryDef>(U);
1602
1603 };
1604 // All arguments should in the same class, ignoring unreachable arguments
1605 auto FilteredPhiArgs =
1606 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1607 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1608 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1609 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1610 const MemoryDef *MD = cast<MemoryDef>(U);
1611 return ValueToClass.lookup(MD->getMemoryInst());
1612 });
1613 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1614 PhiOpClasses.begin()) &&
1615 "All MemoryPhi arguments should be in the same class");
1616 }
1617 }
1618}
1619
Daniel Berlin85f91b02016-12-26 20:06:58 +00001620// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001621bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001622 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1623 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001624 bool Changed = false;
1625 DT = _DT;
1626 AC = _AC;
1627 TLI = _TLI;
1628 AA = _AA;
1629 MSSA = _MSSA;
1630 DL = &F.getParent()->getDataLayout();
1631 MSSAWalker = MSSA->getWalker();
1632
1633 // Count number of instructions for sizing of hash tables, and come
1634 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001635 unsigned ICount = 1;
1636 // Add an empty instruction to account for the fact that we start at 1
1637 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001638 // Note: We want RPO traversal of the blocks, which is not quite the same as
1639 // dominator tree order, particularly with regard whether backedges get
1640 // visited first or second, given a block with multiple successors.
1641 // If we visit in the wrong order, we will end up performing N times as many
1642 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001643 // The dominator tree does guarantee that, for a given dom tree node, it's
1644 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1645 // the siblings.
1646 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001647 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001648 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001649 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001650 auto *Node = DT->getNode(B);
1651 assert(Node && "RPO and Dominator tree should have same reachability");
1652 RPOOrdering[Node] = ++Counter;
1653 }
1654 // Sort dominator tree children arrays into RPO.
1655 for (auto &B : RPOT) {
1656 auto *Node = DT->getNode(B);
1657 if (Node->getChildren().size() > 1)
1658 std::sort(Node->begin(), Node->end(),
1659 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1660 return RPOOrdering[A] < RPOOrdering[B];
1661 });
1662 }
1663
1664 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1665 auto DFI = df_begin(DT->getRootNode());
1666 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1667 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001668 const auto &BlockRange = assignDFSNumbers(B, ICount);
1669 BlockInstRange.insert({B, BlockRange});
1670 ICount += BlockRange.second - BlockRange.first;
1671 }
1672
1673 // Handle forward unreachable blocks and figure out which blocks
1674 // have single preds.
1675 for (auto &B : F) {
1676 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001677 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001678 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1679 BlockInstRange.insert({&B, BlockRange});
1680 ICount += BlockRange.second - BlockRange.first;
1681 }
1682 }
1683
Daniel Berline0bd37e2016-12-29 22:15:12 +00001684 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001685 DominatedInstRange.reserve(F.size());
1686 // Ensure we don't end up resizing the expressionToClass map, as
1687 // that can be quite expensive. At most, we have one expression per
1688 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001689 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001690
1691 // Initialize the touched instructions to include the entry block.
1692 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1693 TouchedInstructions.set(InstRange.first, InstRange.second);
1694 ReachableBlocks.insert(&F.getEntryBlock());
1695
1696 initializeCongruenceClasses(F);
1697
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001698 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001699 // We start out in the entry block.
1700 BasicBlock *LastBlock = &F.getEntryBlock();
1701 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001702 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00001703 // Walk through all the instructions in all the blocks in RPO.
1704 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1705 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Daniel Berline0bd37e2016-12-29 22:15:12 +00001706 assert(InstrNum != 0 && "Bit 0 should never be set, something touched an "
1707 "instruction not in the lookup table");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001708 Value *V = DFSToInstr[InstrNum];
1709 BasicBlock *CurrBlock = nullptr;
1710
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001711 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001712 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001713 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001714 CurrBlock = MP->getBlock();
1715 else
1716 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001717
1718 // If we hit a new block, do reachability processing.
1719 if (CurrBlock != LastBlock) {
1720 LastBlock = CurrBlock;
1721 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1722 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1723
1724 // If it's not reachable, erase any touched instructions and move on.
1725 if (!BlockReachable) {
1726 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1727 DEBUG(dbgs() << "Skipping instructions in block "
1728 << getBlockName(CurrBlock)
1729 << " because it is unreachable\n");
1730 continue;
1731 }
1732 updateProcessedCount(CurrBlock);
1733 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001734
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001735 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001736 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1737 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001738 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001739 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001740 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001741 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001742 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001743 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001744 // Reset after processing (because we may mark ourselves as touched when
1745 // we propagate equalities).
1746 TouchedInstructions.reset(InstrNum);
1747 }
1748 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001749 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001750#ifndef NDEBUG
1751 verifyMemoryCongruency();
1752#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001753 Changed |= eliminateInstructions(F);
1754
1755 // Delete all instructions marked for deletion.
1756 for (Instruction *ToErase : InstructionsToErase) {
1757 if (!ToErase->use_empty())
1758 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1759
1760 ToErase->eraseFromParent();
1761 }
1762
1763 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001764 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1765 return !ReachableBlocks.count(&BB);
1766 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001767
1768 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1769 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001770 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001771 deleteInstructionsInBlock(&BB);
1772 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001773 }
1774
1775 cleanupTables();
1776 return Changed;
1777}
1778
1779bool NewGVN::runOnFunction(Function &F) {
1780 if (skipFunction(F))
1781 return false;
1782 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1783 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1784 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1785 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1786 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1787}
1788
Daniel Berlin85f91b02016-12-26 20:06:58 +00001789PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001790 NewGVN Impl;
1791
1792 // Apparently the order in which we get these results matter for
1793 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1794 // the same order here, just in case.
1795 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1796 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1797 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1798 auto &AA = AM.getResult<AAManager>(F);
1799 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1800 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1801 if (!Changed)
1802 return PreservedAnalyses::all();
1803 PreservedAnalyses PA;
1804 PA.preserve<DominatorTreeAnalysis>();
1805 PA.preserve<GlobalsAA>();
1806 return PA;
1807}
1808
1809// Return true if V is a value that will always be available (IE can
1810// be placed anywhere) in the function. We don't do globals here
1811// because they are often worse to put in place.
1812// TODO: Separate cost from availability
1813static bool alwaysAvailable(Value *V) {
1814 return isa<Constant>(V) || isa<Argument>(V);
1815}
1816
1817// Get the basic block from an instruction/value.
1818static BasicBlock *getBlockForValue(Value *V) {
1819 if (auto *I = dyn_cast<Instruction>(V))
1820 return I->getParent();
1821 return nullptr;
1822}
1823
1824struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001825 int DFSIn = 0;
1826 int DFSOut = 0;
1827 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001828 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001829 Value *Val = nullptr;
1830 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001831
1832 bool operator<(const ValueDFS &Other) const {
1833 // It's not enough that any given field be less than - we have sets
1834 // of fields that need to be evaluated together to give a proper ordering.
1835 // For example, if you have;
1836 // DFS (1, 3)
1837 // Val 0
1838 // DFS (1, 2)
1839 // Val 50
1840 // We want the second to be less than the first, but if we just go field
1841 // by field, we will get to Val 0 < Val 50 and say the first is less than
1842 // the second. We only want it to be less than if the DFS orders are equal.
1843 //
1844 // Each LLVM instruction only produces one value, and thus the lowest-level
1845 // differentiator that really matters for the stack (and what we use as as a
1846 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001847 // Everything else in the structure is instruction level, and only affects
1848 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001849 //
1850 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1851 // the order of replacement of uses does not matter.
1852 // IE given,
1853 // a = 5
1854 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001855 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1856 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001857 // The .val will be the same as well.
1858 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001859 // You will replace both, and it does not matter what order you replace them
1860 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1861 // operand 2).
1862 // Similarly for the case of same dfsin, dfsout, localnum, but different
1863 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001864 // a = 5
1865 // b = 6
1866 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001867 // in c, we will a valuedfs for a, and one for b,with everything the same
1868 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001869 // It does not matter what order we replace these operands in.
1870 // You will always end up with the same IR, and this is guaranteed.
1871 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1872 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1873 Other.U);
1874 }
1875};
1876
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001877void NewGVN::convertDenseToDFSOrdered(
1878 CongruenceClass::MemberSet &Dense,
1879 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001880 for (auto D : Dense) {
1881 // First add the value.
1882 BasicBlock *BB = getBlockForValue(D);
1883 // Constants are handled prior to ever calling this function, so
1884 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001885 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001886 ValueDFS VD;
1887
Daniel Berlinb66164c2017-01-14 00:24:23 +00001888 DomTreeNode *DomNode = DT->getNode(BB);
1889 VD.DFSIn = DomNode->getDFSNumIn();
1890 VD.DFSOut = DomNode->getDFSNumOut();
Davide Italiano7e274e02016-12-22 16:03:48 +00001891 VD.Val = D;
1892 // If it's an instruction, use the real local dfs number.
1893 if (auto *I = dyn_cast<Instruction>(D))
1894 VD.LocalNum = InstrDFS[I];
1895 else
1896 llvm_unreachable("Should have been an instruction");
1897
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001898 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001899
Daniel Berlinb66164c2017-01-14 00:24:23 +00001900 // Now add the uses.
Davide Italiano7e274e02016-12-22 16:03:48 +00001901 for (auto &U : D->uses()) {
1902 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1903 ValueDFS VD;
1904 // Put the phi node uses in the incoming block.
1905 BasicBlock *IBlock;
1906 if (auto *P = dyn_cast<PHINode>(I)) {
1907 IBlock = P->getIncomingBlock(U);
1908 // Make phi node users appear last in the incoming block
1909 // they are from.
1910 VD.LocalNum = InstrDFS.size() + 1;
1911 } else {
1912 IBlock = I->getParent();
1913 VD.LocalNum = InstrDFS[I];
1914 }
Daniel Berlinb66164c2017-01-14 00:24:23 +00001915 DomTreeNode *DomNode = DT->getNode(IBlock);
1916 VD.DFSIn = DomNode->getDFSNumIn();
1917 VD.DFSOut = DomNode->getDFSNumOut();
Davide Italiano7e274e02016-12-22 16:03:48 +00001918 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001919 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001920 }
1921 }
1922 }
1923}
1924
1925static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1926 // Patch the replacement so that it is not more restrictive than the value
1927 // being replaced.
1928 auto *Op = dyn_cast<BinaryOperator>(I);
1929 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1930
1931 if (Op && ReplOp)
1932 ReplOp->andIRFlags(Op);
1933
1934 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1935 // FIXME: If both the original and replacement value are part of the
1936 // same control-flow region (meaning that the execution of one
1937 // guarentees the executation of the other), then we can combine the
1938 // noalias scopes here and do better than the general conservative
1939 // answer used in combineMetadata().
1940
1941 // In general, GVN unifies expressions over different control-flow
1942 // regions, and so we need a conservative combination of the noalias
1943 // scopes.
1944 unsigned KnownIDs[] = {
1945 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1946 LLVMContext::MD_noalias, LLVMContext::MD_range,
1947 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1948 LLVMContext::MD_invariant_group};
1949 combineMetadata(ReplInst, I, KnownIDs);
1950 }
1951}
1952
1953static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1954 patchReplacementInstruction(I, Repl);
1955 I->replaceAllUsesWith(Repl);
1956}
1957
1958void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
1959 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1960 ++NumGVNBlocksDeleted;
1961
1962 // Check to see if there are non-terminating instructions to delete.
1963 if (isa<TerminatorInst>(BB->begin()))
1964 return;
1965
1966 // Delete the instructions backwards, as it has a reduced likelihood of having
1967 // to update as many def-use and use-def chains. Start after the terminator.
1968 auto StartPoint = BB->rbegin();
1969 ++StartPoint;
1970 // Note that we explicitly recalculate BB->rend() on each iteration,
1971 // as it may change when we remove the first instruction.
1972 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
1973 Instruction &Inst = *I++;
1974 if (!Inst.use_empty())
1975 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
1976 if (isa<LandingPadInst>(Inst))
1977 continue;
1978
1979 Inst.eraseFromParent();
1980 ++NumGVNInstrDeleted;
1981 }
1982}
1983
1984void NewGVN::markInstructionForDeletion(Instruction *I) {
1985 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
1986 InstructionsToErase.insert(I);
1987}
1988
1989void NewGVN::replaceInstruction(Instruction *I, Value *V) {
1990
1991 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
1992 patchAndReplaceAllUsesWith(I, V);
1993 // We save the actual erasing to avoid invalidating memory
1994 // dependencies until we are done with everything.
1995 markInstructionForDeletion(I);
1996}
1997
1998namespace {
1999
2000// This is a stack that contains both the value and dfs info of where
2001// that value is valid.
2002class ValueDFSStack {
2003public:
2004 Value *back() const { return ValueStack.back(); }
2005 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2006
2007 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002008 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002009 DFSStack.emplace_back(DFSIn, DFSOut);
2010 }
2011 bool empty() const { return DFSStack.empty(); }
2012 bool isInScope(int DFSIn, int DFSOut) const {
2013 if (empty())
2014 return false;
2015 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2016 }
2017
2018 void popUntilDFSScope(int DFSIn, int DFSOut) {
2019
2020 // These two should always be in sync at this point.
2021 assert(ValueStack.size() == DFSStack.size() &&
2022 "Mismatch between ValueStack and DFSStack");
2023 while (
2024 !DFSStack.empty() &&
2025 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2026 DFSStack.pop_back();
2027 ValueStack.pop_back();
2028 }
2029 }
2030
2031private:
2032 SmallVector<Value *, 8> ValueStack;
2033 SmallVector<std::pair<int, int>, 8> DFSStack;
2034};
2035}
Daniel Berlin04443432017-01-07 03:23:47 +00002036
Davide Italiano7e274e02016-12-22 16:03:48 +00002037bool NewGVN::eliminateInstructions(Function &F) {
2038 // This is a non-standard eliminator. The normal way to eliminate is
2039 // to walk the dominator tree in order, keeping track of available
2040 // values, and eliminating them. However, this is mildly
2041 // pointless. It requires doing lookups on every instruction,
2042 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002043 // instructions part of most singleton congruence classes, we know we
2044 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002045
2046 // Instead, this eliminator looks at the congruence classes directly, sorts
2047 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002048 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002049 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002050 // last member. This is worst case O(E log E) where E = number of
2051 // instructions in a single congruence class. In theory, this is all
2052 // instructions. In practice, it is much faster, as most instructions are
2053 // either in singleton congruence classes or can't possibly be eliminated
2054 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002055 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002056 // for elimination purposes.
2057 // TODO: If we wanted to be faster, We could remove any members with no
2058 // overlapping ranges while sorting, as we will never eliminate anything
2059 // with those members, as they don't dominate anything else in our set.
2060
Davide Italiano7e274e02016-12-22 16:03:48 +00002061 bool AnythingReplaced = false;
2062
2063 // Since we are going to walk the domtree anyway, and we can't guarantee the
2064 // DFS numbers are updated, we compute some ourselves.
2065 DT->updateDFSNumbers();
2066
2067 for (auto &B : F) {
2068 if (!ReachableBlocks.count(&B)) {
2069 for (const auto S : successors(&B)) {
2070 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002071 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002072 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2073 << getBlockName(&B)
2074 << " with undef due to it being unreachable\n");
2075 for (auto &Operand : Phi.incoming_values())
2076 if (Phi.getIncomingBlock(Operand) == &B)
2077 Operand.set(UndefValue::get(Phi.getType()));
2078 }
2079 }
2080 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002081 }
2082
2083 for (CongruenceClass *CC : CongruenceClasses) {
2084 // FIXME: We should eventually be able to replace everything still
2085 // in the initial class with undef, as they should be unreachable.
2086 // Right now, initial still contains some things we skip value
2087 // numbering of (UNREACHABLE's, for example).
2088 if (CC == InitialClass || CC->Dead)
2089 continue;
2090 assert(CC->RepLeader && "We should have had a leader");
2091
2092 // If this is a leader that is always available, and it's a
2093 // constant or has no equivalences, just replace everything with
2094 // it. We then update the congruence class with whatever members
2095 // are left.
2096 if (alwaysAvailable(CC->RepLeader)) {
2097 SmallPtrSet<Value *, 4> MembersLeft;
2098 for (auto M : CC->Members) {
2099
2100 Value *Member = M;
2101
2102 // Void things have no uses we can replace.
2103 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2104 MembersLeft.insert(Member);
2105 continue;
2106 }
2107
2108 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for "
2109 << *Member << "\n");
2110 // Due to equality propagation, these may not always be
2111 // instructions, they may be real values. We don't really
2112 // care about trying to replace the non-instructions.
2113 if (auto *I = dyn_cast<Instruction>(Member)) {
2114 assert(CC->RepLeader != I &&
2115 "About to accidentally remove our leader");
2116 replaceInstruction(I, CC->RepLeader);
2117 AnythingReplaced = true;
2118
2119 continue;
2120 } else {
2121 MembersLeft.insert(I);
2122 }
2123 }
2124 CC->Members.swap(MembersLeft);
2125
2126 } else {
2127 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2128 // If this is a singleton, we can skip it.
2129 if (CC->Members.size() != 1) {
2130
2131 // This is a stack because equality replacement/etc may place
2132 // constants in the middle of the member list, and we want to use
2133 // those constant values in preference to the current leader, over
2134 // the scope of those constants.
2135 ValueDFSStack EliminationStack;
2136
2137 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002138 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002139 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2140
2141 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002142 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Davide Italiano7e274e02016-12-22 16:03:48 +00002143
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002144 for (auto &VD : DFSOrderedSet) {
2145 int MemberDFSIn = VD.DFSIn;
2146 int MemberDFSOut = VD.DFSOut;
2147 Value *Member = VD.Val;
2148 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002149
Daniel Berlind92e7f92017-01-07 00:01:42 +00002150 if (Member) {
2151 // We ignore void things because we can't get a value from them.
2152 // FIXME: We could actually use this to kill dead stores that are
2153 // dominated by equivalent earlier stores.
2154 if (Member->getType()->isVoidTy())
2155 continue;
2156 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002157
2158 if (EliminationStack.empty()) {
2159 DEBUG(dbgs() << "Elimination Stack is empty\n");
2160 } else {
2161 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2162 << EliminationStack.dfs_back().first << ","
2163 << EliminationStack.dfs_back().second << ")\n");
2164 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002165
2166 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2167 << MemberDFSOut << ")\n");
2168 // First, we see if we are out of scope or empty. If so,
2169 // and there equivalences, we try to replace the top of
2170 // stack with equivalences (if it's on the stack, it must
2171 // not have been eliminated yet).
2172 // Then we synchronize to our current scope, by
2173 // popping until we are back within a DFS scope that
2174 // dominates the current member.
2175 // Then, what happens depends on a few factors
2176 // If the stack is now empty, we need to push
2177 // If we have a constant or a local equivalence we want to
2178 // start using, we also push.
2179 // Otherwise, we walk along, processing members who are
2180 // dominated by this scope, and eliminate them.
2181 bool ShouldPush =
2182 Member && (EliminationStack.empty() || isa<Constant>(Member));
2183 bool OutOfScope =
2184 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2185
2186 if (OutOfScope || ShouldPush) {
2187 // Sync to our current scope.
2188 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2189 ShouldPush |= Member && EliminationStack.empty();
2190 if (ShouldPush) {
2191 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2192 }
2193 }
2194
2195 // If we get to this point, and the stack is empty we must have a use
2196 // with nothing we can use to eliminate it, just skip it.
2197 if (EliminationStack.empty())
2198 continue;
2199
2200 // Skip the Value's, we only want to eliminate on their uses.
2201 if (Member)
2202 continue;
2203 Value *Result = EliminationStack.back();
2204
Daniel Berlind92e7f92017-01-07 00:01:42 +00002205 // Don't replace our existing users with ourselves.
2206 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002207 continue;
2208
2209 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2210 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2211 << "\n");
2212
2213 // If we replaced something in an instruction, handle the patching of
2214 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002215 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002216 patchReplacementInstruction(ReplacedInst, Result);
2217
2218 assert(isa<Instruction>(MemberUse->getUser()));
2219 MemberUse->set(Result);
2220 AnythingReplaced = true;
2221 }
2222 }
2223 }
2224
2225 // Cleanup the congruence class.
2226 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002227 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002228 if (Member->getType()->isVoidTy()) {
2229 MembersLeft.insert(Member);
2230 continue;
2231 }
2232
2233 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2234 if (isInstructionTriviallyDead(MemberInst)) {
2235 // TODO: Don't mark loads of undefs.
2236 markInstructionForDeletion(MemberInst);
2237 continue;
2238 }
2239 }
2240 MembersLeft.insert(Member);
2241 }
2242 CC->Members.swap(MembersLeft);
2243 }
2244
2245 return AnythingReplaced;
2246}