blob: d4200fc39085722f5f3fc2bb1e7b7d5ed3f0561e [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");
82
83//===----------------------------------------------------------------------===//
84// GVN Pass
85//===----------------------------------------------------------------------===//
86
87// Anchor methods.
88namespace llvm {
89namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +000090Expression::~Expression() = default;
91BasicExpression::~BasicExpression() = default;
92CallExpression::~CallExpression() = default;
93LoadExpression::~LoadExpression() = default;
94StoreExpression::~StoreExpression() = default;
95AggregateValueExpression::~AggregateValueExpression() = default;
96PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +000097}
98}
99
100// Congruence classes represent the set of expressions/instructions
101// that are all the same *during some scope in the function*.
102// That is, because of the way we perform equality propagation, and
103// because of memory value numbering, it is not correct to assume
104// you can willy-nilly replace any member with any other at any
105// point in the function.
106//
107// For any Value in the Member set, it is valid to replace any dominated member
108// with that Value.
109//
110// Every congruence class has a leader, and the leader is used to
111// symbolize instructions in a canonical way (IE every operand of an
112// instruction that is a member of the same congruence class will
113// always be replaced with leader during symbolization).
114// To simplify symbolization, we keep the leader as a constant if class can be
115// proved to be a constant value.
116// Otherwise, the leader is a randomly chosen member of the value set, it does
117// not matter which one is chosen.
118// Each congruence class also has a defining expression,
119// though the expression may be null. If it exists, it can be used for forward
120// propagation and reassociation of values.
121//
122struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000123 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000124 unsigned ID;
125 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000126 Value *RepLeader = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000127 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000128 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000129 // Actual members of this class.
130 MemberSet Members;
131
132 // True if this class has no members left. This is mainly used for assertion
133 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000134 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000135
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000136 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000137 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000138 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000139};
140
141namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000142template <> struct DenseMapInfo<const Expression *> {
143 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000144 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000145 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
146 return reinterpret_cast<const Expression *>(Val);
147 }
148 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000149 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000150 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
151 return reinterpret_cast<const Expression *>(Val);
152 }
153 static unsigned getHashValue(const Expression *V) {
154 return static_cast<unsigned>(V->getHashValue());
155 }
156 static bool isEqual(const Expression *LHS, const Expression *RHS) {
157 if (LHS == RHS)
158 return true;
159 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
160 LHS == getEmptyKey() || RHS == getEmptyKey())
161 return false;
162 return *LHS == *RHS;
163 }
164};
Davide Italiano7e274e02016-12-22 16:03:48 +0000165} // end namespace llvm
166
167class NewGVN : public FunctionPass {
168 DominatorTree *DT;
169 const DataLayout *DL;
170 const TargetLibraryInfo *TLI;
171 AssumptionCache *AC;
172 AliasAnalysis *AA;
173 MemorySSA *MSSA;
174 MemorySSAWalker *MSSAWalker;
175 BumpPtrAllocator ExpressionAllocator;
176 ArrayRecycler<Value *> ArgRecycler;
177
178 // Congruence class info.
179 CongruenceClass *InitialClass;
180 std::vector<CongruenceClass *> CongruenceClasses;
181 unsigned NextCongruenceNum;
182
183 // Value Mappings.
184 DenseMap<Value *, CongruenceClass *> ValueToClass;
185 DenseMap<Value *, const Expression *> ValueToExpression;
186
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000187 // A table storing which memorydefs/phis represent a memory state provably
188 // equivalent to another memory state.
189 // We could use the congruence class machinery, but the MemoryAccess's are
190 // abstract memory states, so they can only ever be equivalent to each other,
191 // and not to constants, etc.
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000192 DenseMap<const MemoryAccess *, MemoryAccess *> MemoryAccessEquiv;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000193
Davide Italiano7e274e02016-12-22 16:03:48 +0000194 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000195 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000196 ExpressionClassMap ExpressionToClass;
197
198 // Which values have changed as a result of leader changes.
199 SmallPtrSet<Value *, 8> ChangedValues;
200
201 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000202 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000203 DenseSet<BlockEdge> ReachableEdges;
204 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
205
206 // This is a bitvector because, on larger functions, we may have
207 // thousands of touched instructions at once (entire blocks,
208 // instructions with hundreds of uses, etc). Even with optimization
209 // for when we mark whole blocks as touched, when this was a
210 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
211 // the time in GVN just managing this list. The bitvector, on the
212 // other hand, efficiently supports test/set/clear of both
213 // individual and ranges, as well as "find next element" This
214 // enables us to use it as a worklist with essentially 0 cost.
215 BitVector TouchedInstructions;
216
217 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
218 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
219 DominatedInstRange;
220
221#ifndef NDEBUG
222 // Debugging for how many times each block and instruction got processed.
223 DenseMap<const Value *, unsigned> ProcessedCount;
224#endif
225
226 // DFS info.
227 DenseMap<const BasicBlock *, std::pair<int, int>> DFSDomMap;
228 DenseMap<const Value *, unsigned> InstrDFS;
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000229 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000230
231 // Deletion info.
232 SmallPtrSet<Instruction *, 8> InstructionsToErase;
233
234public:
235 static char ID; // Pass identification, replacement for typeid.
236 NewGVN() : FunctionPass(ID) {
237 initializeNewGVNPass(*PassRegistry::getPassRegistry());
238 }
239
240 bool runOnFunction(Function &F) override;
241 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000242 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000243
244private:
245 // This transformation requires dominator postdominator info.
246 void getAnalysisUsage(AnalysisUsage &AU) const override {
247 AU.addRequired<AssumptionCacheTracker>();
248 AU.addRequired<DominatorTreeWrapperPass>();
249 AU.addRequired<TargetLibraryInfoWrapperPass>();
250 AU.addRequired<MemorySSAWrapperPass>();
251 AU.addRequired<AAResultsWrapperPass>();
252
253 AU.addPreserved<DominatorTreeWrapperPass>();
254 AU.addPreserved<GlobalsAAWrapperPass>();
255 }
256
257 // Expression handling.
258 const Expression *createExpression(Instruction *, const BasicBlock *);
259 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
260 const BasicBlock *);
261 PHIExpression *createPHIExpression(Instruction *);
262 const VariableExpression *createVariableExpression(Value *);
263 const ConstantExpression *createConstantExpression(Constant *);
264 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000265 const UnknownExpression *createUnknownExpression(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000266 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
267 const BasicBlock *);
268 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
269 MemoryAccess *, const BasicBlock *);
270
271 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
272 const BasicBlock *);
273 const AggregateValueExpression *
274 createAggregateValueExpression(Instruction *, const BasicBlock *);
275 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
276 const BasicBlock *);
277
278 // Congruence class handling.
279 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000280 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000281 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000282 return result;
283 }
284
285 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000286 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000287 CClass->Members.insert(Member);
288 ValueToClass[Member] = CClass;
289 return CClass;
290 }
291 void initializeCongruenceClasses(Function &F);
292
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000293 // Value number an Instruction or MemoryPhi.
294 void valueNumberMemoryPhi(MemoryPhi *);
295 void valueNumberInstruction(Instruction *);
296
Davide Italiano7e274e02016-12-22 16:03:48 +0000297 // Symbolic evaluation.
298 const Expression *checkSimplificationResults(Expression *, Instruction *,
299 Value *);
300 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
301 const Expression *performSymbolicLoadEvaluation(Instruction *,
302 const BasicBlock *);
303 const Expression *performSymbolicStoreEvaluation(Instruction *,
304 const BasicBlock *);
305 const Expression *performSymbolicCallEvaluation(Instruction *,
306 const BasicBlock *);
307 const Expression *performSymbolicPHIEvaluation(Instruction *,
308 const BasicBlock *);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000309 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To);
Davide Italiano7e274e02016-12-22 16:03:48 +0000310 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
311 const BasicBlock *);
312
313 // Congruence finding.
314 // Templated to allow them to work both on BB's and BB-edges.
315 template <class T>
316 Value *lookupOperandLeader(Value *, const User *, const T &) const;
317 void performCongruenceFinding(Value *, const Expression *);
318
319 // Reachability handling.
320 void updateReachableEdge(BasicBlock *, BasicBlock *);
321 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000322 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000323 Value *findConditionEquivalence(Value *, BasicBlock *) const;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000324 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000325
326 // Elimination.
327 struct ValueDFS;
328 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &,
329 std::vector<ValueDFS> &);
330
331 bool eliminateInstructions(Function &);
332 void replaceInstruction(Instruction *, Value *);
333 void markInstructionForDeletion(Instruction *);
334 void deleteInstructionsInBlock(BasicBlock *);
335
336 // New instruction creation.
337 void handleNewInstruction(Instruction *){};
338 void markUsersTouched(Value *);
339 void markMemoryUsersTouched(MemoryAccess *);
340
341 // Utilities.
342 void cleanupTables();
343 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
344 void updateProcessedCount(Value *V);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000345 void verifyMemoryCongruency();
Davide Italiano7e274e02016-12-22 16:03:48 +0000346};
347
348char NewGVN::ID = 0;
349
350// createGVNPass - The public interface to this file.
351FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
352
Davide Italianob1114092016-12-28 13:37:17 +0000353template <typename T>
354static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
355 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000356 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000357 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000358 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000359 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000360 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000361 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000362 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000363 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000364 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000365 return true;
366}
367
Davide Italianob1114092016-12-28 13:37:17 +0000368bool LoadExpression::equals(const Expression &Other) const {
369 return equalsLoadStoreHelper(*this, Other);
370}
Davide Italiano7e274e02016-12-22 16:03:48 +0000371
Davide Italianob1114092016-12-28 13:37:17 +0000372bool StoreExpression::equals(const Expression &Other) const {
373 return equalsLoadStoreHelper(*this, Other);
Davide Italiano7e274e02016-12-22 16:03:48 +0000374}
375
376#ifndef NDEBUG
377static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000378 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000379}
380#endif
381
382INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
383INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
384INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
385INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
386INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
387INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
388INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
389INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
390
391PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
392 BasicBlock *PhiBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000393 auto *PN = cast<PHINode>(I);
394 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000395 PHIExpression(PN->getNumOperands(), I->getParent());
396
397 E->allocateOperands(ArgRecycler, ExpressionAllocator);
398 E->setType(I->getType());
399 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000400
401 auto ReachablePhiArg = [&](const Use &U) {
402 return ReachableBlocks.count(PN->getIncomingBlock(U));
403 };
404
405 // Filter out unreachable operands
406 auto Filtered = make_filter_range(PN->operands(), ReachablePhiArg);
407
408 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
409 [&](const Use &U) -> Value * {
410 // Don't try to transform self-defined phis
411 if (U == PN)
412 return PN;
413 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PhiBlock);
414 return lookupOperandLeader(U, I, BBE);
415 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000416 return E;
417}
418
419// Set basic expression info (Arguments, type, opcode) for Expression
420// E from Instruction I in block B.
421bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
422 const BasicBlock *B) {
423 bool AllConstant = true;
424 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
425 E->setType(GEP->getSourceElementType());
426 else
427 E->setType(I->getType());
428 E->setOpcode(I->getOpcode());
429 E->allocateOperands(ArgRecycler, ExpressionAllocator);
430
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000431 // Transform the operand array into an operand leader array, and keep track of
432 // whether all members are constant.
433 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000434 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000435 AllConstant &= isa<Constant>(Operand);
436 return Operand;
437 });
438
Davide Italiano7e274e02016-12-22 16:03:48 +0000439 return AllConstant;
440}
441
442const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
443 Value *Arg1, Value *Arg2,
444 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000445 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000446
447 E->setType(T);
448 E->setOpcode(Opcode);
449 E->allocateOperands(ArgRecycler, ExpressionAllocator);
450 if (Instruction::isCommutative(Opcode)) {
451 // Ensure that commutative instructions that only differ by a permutation
452 // of their operands get the same value number by sorting the operand value
453 // numbers. Since all commutative instructions have two operands it is more
454 // efficient to sort by hand rather than using, say, std::sort.
455 if (Arg1 > Arg2)
456 std::swap(Arg1, Arg2);
457 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000458 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
459 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000460
461 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
462 DT, AC);
463 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
464 return SimplifiedE;
465 return E;
466}
467
468// Take a Value returned by simplification of Expression E/Instruction
469// I, and see if it resulted in a simpler expression. If so, return
470// that expression.
471// TODO: Once finished, this should not take an Instruction, we only
472// use it for printing.
473const Expression *NewGVN::checkSimplificationResults(Expression *E,
474 Instruction *I, Value *V) {
475 if (!V)
476 return nullptr;
477 if (auto *C = dyn_cast<Constant>(V)) {
478 if (I)
479 DEBUG(dbgs() << "Simplified " << *I << " to "
480 << " constant " << *C << "\n");
481 NumGVNOpsSimplified++;
482 assert(isa<BasicExpression>(E) &&
483 "We should always have had a basic expression here");
484
485 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
486 ExpressionAllocator.Deallocate(E);
487 return createConstantExpression(C);
488 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
489 if (I)
490 DEBUG(dbgs() << "Simplified " << *I << " to "
491 << " variable " << *V << "\n");
492 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
493 ExpressionAllocator.Deallocate(E);
494 return createVariableExpression(V);
495 }
496
497 CongruenceClass *CC = ValueToClass.lookup(V);
498 if (CC && CC->DefiningExpr) {
499 if (I)
500 DEBUG(dbgs() << "Simplified " << *I << " to "
501 << " expression " << *V << "\n");
502 NumGVNOpsSimplified++;
503 assert(isa<BasicExpression>(E) &&
504 "We should always have had a basic expression here");
505 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
506 ExpressionAllocator.Deallocate(E);
507 return CC->DefiningExpr;
508 }
509 return nullptr;
510}
511
512const Expression *NewGVN::createExpression(Instruction *I,
513 const BasicBlock *B) {
514
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000515 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000516
517 bool AllConstant = setBasicExpressionInfo(I, E, B);
518
519 if (I->isCommutative()) {
520 // Ensure that commutative instructions that only differ by a permutation
521 // of their operands get the same value number by sorting the operand value
522 // numbers. Since all commutative instructions have two operands it is more
523 // efficient to sort by hand rather than using, say, std::sort.
524 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
525 if (E->getOperand(0) > E->getOperand(1))
526 E->swapOperands(0, 1);
527 }
528
529 // Perform simplificaiton
530 // TODO: Right now we only check to see if we get a constant result.
531 // We may get a less than constant, but still better, result for
532 // some operations.
533 // IE
534 // add 0, x -> x
535 // and x, x -> x
536 // We should handle this by simply rewriting the expression.
537 if (auto *CI = dyn_cast<CmpInst>(I)) {
538 // Sort the operand value numbers so x<y and y>x get the same value
539 // number.
540 CmpInst::Predicate Predicate = CI->getPredicate();
541 if (E->getOperand(0) > E->getOperand(1)) {
542 E->swapOperands(0, 1);
543 Predicate = CmpInst::getSwappedPredicate(Predicate);
544 }
545 E->setOpcode((CI->getOpcode() << 8) | Predicate);
546 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
547 // TODO: Since we noop bitcasts, we may need to check types before
548 // simplifying, so that we don't end up simplifying based on a wrong
549 // type assumption. We should clean this up so we can use constants of the
550 // wrong type
551
552 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
553 "Wrong types on cmp instruction");
554 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
555 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
556 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
557 *DL, TLI, DT, AC);
558 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
559 return SimplifiedE;
560 }
561 } else if (isa<SelectInst>(I)) {
562 if (isa<Constant>(E->getOperand(0)) ||
563 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
564 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
565 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
566 E->getOperand(2), *DL, TLI, DT, AC);
567 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
568 return SimplifiedE;
569 }
570 } else if (I->isBinaryOp()) {
571 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
572 *DL, TLI, DT, AC);
573 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
574 return SimplifiedE;
575 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
576 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
577 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
578 return SimplifiedE;
579 } else if (isa<GetElementPtrInst>(I)) {
580 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000581 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000582 *DL, TLI, DT, AC);
583 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
584 return SimplifiedE;
585 } else if (AllConstant) {
586 // We don't bother trying to simplify unless all of the operands
587 // were constant.
588 // TODO: There are a lot of Simplify*'s we could call here, if we
589 // wanted to. The original motivating case for this code was a
590 // zext i1 false to i8, which we don't have an interface to
591 // simplify (IE there is no SimplifyZExt).
592
593 SmallVector<Constant *, 8> C;
594 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000595 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000596
597 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
598 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
599 return SimplifiedE;
600 }
601 return E;
602}
603
604const AggregateValueExpression *
605NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
606 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000607 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000608 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
609 setBasicExpressionInfo(I, E, B);
610 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000611 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000612 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000613 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000614 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000615 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
616 setBasicExpressionInfo(EI, E, B);
617 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000618 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000619 return E;
620 }
621 llvm_unreachable("Unhandled type of aggregate value operation");
622}
623
Daniel Berlin85f91b02016-12-26 20:06:58 +0000624const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000625 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000626 E->setOpcode(V->getValueID());
627 return E;
628}
629
630const Expression *NewGVN::createVariableOrConstant(Value *V,
631 const BasicBlock *B) {
632 auto Leader = lookupOperandLeader(V, nullptr, B);
633 if (auto *C = dyn_cast<Constant>(Leader))
634 return createConstantExpression(C);
635 return createVariableExpression(Leader);
636}
637
Daniel Berlin85f91b02016-12-26 20:06:58 +0000638const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000639 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000640 E->setOpcode(C->getValueID());
641 return E;
642}
643
Daniel Berlin02c6b172017-01-02 18:00:53 +0000644const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
645 auto *E = new (ExpressionAllocator) UnknownExpression(I);
646 E->setOpcode(I->getOpcode());
647 return E;
648}
649
Davide Italiano7e274e02016-12-22 16:03:48 +0000650const CallExpression *NewGVN::createCallExpression(CallInst *CI,
651 MemoryAccess *HV,
652 const BasicBlock *B) {
653 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000654 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000655 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
656 setBasicExpressionInfo(CI, E, B);
657 return E;
658}
659
660// See if we have a congruence class and leader for this operand, and if so,
661// return it. Otherwise, return the operand itself.
662template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000663Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000664 CongruenceClass *CC = ValueToClass.lookup(V);
665 if (CC && (CC != InitialClass))
666 return CC->RepLeader;
667 return V;
668}
669
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000670MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
671 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
672 return Result ? Result : MA;
673}
674
Davide Italiano7e274e02016-12-22 16:03:48 +0000675LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
676 LoadInst *LI, MemoryAccess *DA,
677 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000678 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000679 E->allocateOperands(ArgRecycler, ExpressionAllocator);
680 E->setType(LoadType);
681
682 // Give store and loads same opcode so they value number together.
683 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000684 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000685 if (LI)
686 E->setAlignment(LI->getAlignment());
687
688 // TODO: Value number heap versions. We may be able to discover
689 // things alias analysis can't on it's own (IE that a store and a
690 // load have the same value, and thus, it isn't clobbering the load).
691 return E;
692}
693
694const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
695 MemoryAccess *DA,
696 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000697 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000698 new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, DA);
699 E->allocateOperands(ArgRecycler, ExpressionAllocator);
700 E->setType(SI->getValueOperand()->getType());
701
702 // Give store and loads same opcode so they value number together.
703 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000704 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000705
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 Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
713 const BasicBlock *B) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000714 // Unlike loads, we never try to eliminate stores, so we do not check if they
715 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000716 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000717 // If this store's memorydef stores the same value as the last store, the
718 // memory accesses are equivalent.
719 // Get the expression, if any, for the RHS of the MemoryDef.
720 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
721 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
722 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
723 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
724 // See if this store expression already has a value, and it's the same as our
Daniel Berlin589cecc2017-01-02 18:00:46 +0000725 // current store. FIXME: Right now, we only do this for simple stores.
726 if (SI->isSimple()) {
727 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
728 if (CC && CC->DefiningExpr && isa<StoreExpression>(CC->DefiningExpr) &&
729 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B))
730 return createStoreExpression(SI, StoreRHS, B);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000731 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000732
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000733 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000734}
735
736const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
737 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000738 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000739
740 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000741 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000742 if (!LI->isSimple())
743 return nullptr;
744
Daniel Berlin85f91b02016-12-26 20:06:58 +0000745 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000746 // Load of undef is undef.
747 if (isa<UndefValue>(LoadAddressLeader))
748 return createConstantExpression(UndefValue::get(LI->getType()));
749
750 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
751
752 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
753 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
754 Instruction *DefiningInst = MD->getMemoryInst();
755 // If the defining instruction is not reachable, replace with undef.
756 if (!ReachableBlocks.count(DefiningInst->getParent()))
757 return createConstantExpression(UndefValue::get(LI->getType()));
758 }
759 }
760
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000761 const Expression *E =
762 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
763 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000764 return E;
765}
766
767// Evaluate read only and pure calls, and create an expression result.
768const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
769 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000770 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000771 if (AA->doesNotAccessMemory(CI))
772 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000773 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000774 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000775 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000776 }
777 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000778}
779
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000780// Update the memory access equivalence table to say that From is equal to To,
781// and return true if this is different from what already existed in the table.
782bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
Davide Italiano84126162017-01-02 18:41:34 +0000783 DEBUG(dbgs() << "Setting " << *From << " equivalent to ");
784 if (!To)
785 DEBUG(dbgs() << "itself");
786 else
787 DEBUG(dbgs() << *To);
788 DEBUG(dbgs() << "\n");
Daniel Berlin589cecc2017-01-02 18:00:46 +0000789 auto LookupResult = MemoryAccessEquiv.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000790 bool Changed = false;
791 // If it's already in the table, see if the value changed.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000792 if (LookupResult != MemoryAccessEquiv.end()) {
793 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000794 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000795 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000796 Changed = true;
797 } else if (!To) {
798 // It used to be equivalent to something, and now it's not.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000799 MemoryAccessEquiv.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000800 Changed = true;
801 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000802 } else {
803 assert(!To &&
804 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000805 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000806
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000807 return Changed;
808}
Davide Italiano7e274e02016-12-22 16:03:48 +0000809// Evaluate PHI nodes symbolically, and create an expression result.
810const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
811 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000812 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000813 if (E->op_empty()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000814 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
815 << "\n");
816 E->deallocateOperands(ArgRecycler);
817 ExpressionAllocator.Deallocate(E);
818 return createConstantExpression(UndefValue::get(I->getType()));
819 }
820
821 Value *AllSameValue = E->getOperand(0);
822
823 // See if all arguments are the same, ignoring undef arguments, because we can
824 // choose a value that is the same for them.
825 for (const Value *Arg : E->operands())
826 if (Arg != AllSameValue && !isa<UndefValue>(Arg)) {
Davide Italiano0e714802016-12-28 14:00:11 +0000827 AllSameValue = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000828 break;
829 }
830
831 if (AllSameValue) {
832 // It's possible to have phi nodes with cycles (IE dependent on
833 // other phis that are .... dependent on the original phi node),
834 // especially in weird CFG's where some arguments are unreachable, or
835 // uninitialized along certain paths.
836 // This can cause infinite loops during evaluation (even if you disable
837 // the recursion below, you will simply ping-pong between congruence
838 // classes). If a phi node symbolically evaluates to another phi node,
839 // just leave it alone. If they are really the same, we will still
840 // eliminate them in favor of each other.
841 if (isa<PHINode>(AllSameValue))
842 return E;
843 NumGVNPhisAllSame++;
844 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
845 << "\n");
846 E->deallocateOperands(ArgRecycler);
847 ExpressionAllocator.Deallocate(E);
848 if (auto *C = dyn_cast<Constant>(AllSameValue))
849 return createConstantExpression(C);
850 return createVariableExpression(AllSameValue);
851 }
852 return E;
853}
854
855const Expression *
856NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
857 const BasicBlock *B) {
858 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
859 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
860 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
861 unsigned Opcode = 0;
862 // EI might be an extract from one of our recognised intrinsics. If it
863 // is we'll synthesize a semantically equivalent expression instead on
864 // an extract value expression.
865 switch (II->getIntrinsicID()) {
866 case Intrinsic::sadd_with_overflow:
867 case Intrinsic::uadd_with_overflow:
868 Opcode = Instruction::Add;
869 break;
870 case Intrinsic::ssub_with_overflow:
871 case Intrinsic::usub_with_overflow:
872 Opcode = Instruction::Sub;
873 break;
874 case Intrinsic::smul_with_overflow:
875 case Intrinsic::umul_with_overflow:
876 Opcode = Instruction::Mul;
877 break;
878 default:
879 break;
880 }
881
882 if (Opcode != 0) {
883 // Intrinsic recognized. Grab its args to finish building the
884 // expression.
885 assert(II->getNumArgOperands() == 2 &&
886 "Expect two args for recognised intrinsics.");
887 return createBinaryExpression(Opcode, EI->getType(),
888 II->getArgOperand(0),
889 II->getArgOperand(1), B);
890 }
891 }
892 }
893
894 return createAggregateValueExpression(I, B);
895}
896
897// Substitute and symbolize the value before value numbering.
898const Expression *NewGVN::performSymbolicEvaluation(Value *V,
899 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000900 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000901 if (auto *C = dyn_cast<Constant>(V))
902 E = createConstantExpression(C);
903 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
904 E = createVariableExpression(V);
905 } else {
906 // TODO: memory intrinsics.
907 // TODO: Some day, we should do the forward propagation and reassociation
908 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000909 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000910 switch (I->getOpcode()) {
911 case Instruction::ExtractValue:
912 case Instruction::InsertValue:
913 E = performSymbolicAggrValueEvaluation(I, B);
914 break;
915 case Instruction::PHI:
916 E = performSymbolicPHIEvaluation(I, B);
917 break;
918 case Instruction::Call:
919 E = performSymbolicCallEvaluation(I, B);
920 break;
921 case Instruction::Store:
922 E = performSymbolicStoreEvaluation(I, B);
923 break;
924 case Instruction::Load:
925 E = performSymbolicLoadEvaluation(I, B);
926 break;
927 case Instruction::BitCast: {
928 E = createExpression(I, B);
929 } break;
930
931 case Instruction::Add:
932 case Instruction::FAdd:
933 case Instruction::Sub:
934 case Instruction::FSub:
935 case Instruction::Mul:
936 case Instruction::FMul:
937 case Instruction::UDiv:
938 case Instruction::SDiv:
939 case Instruction::FDiv:
940 case Instruction::URem:
941 case Instruction::SRem:
942 case Instruction::FRem:
943 case Instruction::Shl:
944 case Instruction::LShr:
945 case Instruction::AShr:
946 case Instruction::And:
947 case Instruction::Or:
948 case Instruction::Xor:
949 case Instruction::ICmp:
950 case Instruction::FCmp:
951 case Instruction::Trunc:
952 case Instruction::ZExt:
953 case Instruction::SExt:
954 case Instruction::FPToUI:
955 case Instruction::FPToSI:
956 case Instruction::UIToFP:
957 case Instruction::SIToFP:
958 case Instruction::FPTrunc:
959 case Instruction::FPExt:
960 case Instruction::PtrToInt:
961 case Instruction::IntToPtr:
962 case Instruction::Select:
963 case Instruction::ExtractElement:
964 case Instruction::InsertElement:
965 case Instruction::ShuffleVector:
966 case Instruction::GetElementPtr:
967 E = createExpression(I, B);
968 break;
969 default:
970 return nullptr;
971 }
972 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000973 return E;
974}
975
976// There is an edge from 'Src' to 'Dst'. Return true if every path from
977// the entry block to 'Dst' passes via this edge. In particular 'Dst'
978// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000979bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000980
981 // While in theory it is interesting to consider the case in which Dst has
982 // more than one predecessor, because Dst might be part of a loop which is
983 // only reachable from Src, in practice it is pointless since at the time
984 // GVN runs all such loops have preheaders, which means that Dst will have
985 // been changed to have only one predecessor, namely Src.
986 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
987 const BasicBlock *Src = E.getStart();
988 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
989 (void)Src;
990 return Pred != nullptr;
991}
992
993void NewGVN::markUsersTouched(Value *V) {
994 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +0000995 for (auto *User : V->users()) {
996 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Davide Italiano7e274e02016-12-22 16:03:48 +0000997 TouchedInstructions.set(InstrDFS[User]);
998 }
999}
1000
1001void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1002 for (auto U : MA->users()) {
1003 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
1004 TouchedInstructions.set(InstrDFS[MUD->getMemoryInst()]);
1005 else
Daniel Berline0bd37e2016-12-29 22:15:12 +00001006 TouchedInstructions.set(InstrDFS[U]);
Davide Italiano7e274e02016-12-22 16:03:48 +00001007 }
1008}
1009
1010// Perform congruence finding on a given value numbering expression.
1011void NewGVN::performCongruenceFinding(Value *V, const Expression *E) {
1012
1013 ValueToExpression[V] = E;
1014 // This is guaranteed to return something, since it will at least find
1015 // INITIAL.
1016 CongruenceClass *VClass = ValueToClass[V];
1017 assert(VClass && "Should have found a vclass");
1018 // Dead classes should have been eliminated from the mapping.
1019 assert(!VClass->Dead && "Found a dead class");
1020
1021 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001022 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001023 EClass = ValueToClass[VE->getVariableValue()];
1024 } else {
1025 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1026
1027 // If it's not in the value table, create a new congruence class.
1028 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001029 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001030 auto place = lookupResult.first;
1031 place->second = NewClass;
1032
1033 // Constants and variables should always be made the leader.
1034 if (const auto *CE = dyn_cast<ConstantExpression>(E))
1035 NewClass->RepLeader = CE->getConstantValue();
1036 else if (const auto *VE = dyn_cast<VariableExpression>(E))
1037 NewClass->RepLeader = VE->getVariableValue();
1038 else if (const auto *SE = dyn_cast<StoreExpression>(E))
1039 NewClass->RepLeader = SE->getStoreInst()->getValueOperand();
1040 else
1041 NewClass->RepLeader = V;
1042
1043 EClass = NewClass;
1044 DEBUG(dbgs() << "Created new congruence class for " << *V
1045 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin589cecc2017-01-02 18:00:46 +00001046 << " and leader " << *(NewClass->RepLeader) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001047 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1048 } else {
1049 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001050 if (isa<ConstantExpression>(E))
1051 assert(isa<Constant>(EClass->RepLeader) &&
1052 "Any class with a constant expression should have a "
1053 "constant leader");
1054
Davide Italiano7e274e02016-12-22 16:03:48 +00001055 assert(EClass && "Somehow don't have an eclass");
1056
1057 assert(!EClass->Dead && "We accidentally looked up a dead class");
1058 }
1059 }
1060 bool WasInChanged = ChangedValues.erase(V);
1061 if (VClass != EClass || WasInChanged) {
1062 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1063 << "\n");
1064
1065 if (VClass != EClass) {
1066 DEBUG(dbgs() << "New congruence class for " << V << " is " << EClass->ID
1067 << "\n");
1068
1069 VClass->Members.erase(V);
1070 EClass->Members.insert(V);
1071 ValueToClass[V] = EClass;
1072 // See if we destroyed the class or need to swap leaders.
1073 if (VClass->Members.empty() && VClass != InitialClass) {
1074 if (VClass->DefiningExpr) {
1075 VClass->Dead = true;
1076 DEBUG(dbgs() << "Erasing expression " << *E << " from table\n");
1077 ExpressionToClass.erase(VClass->DefiningExpr);
1078 }
1079 } else if (VClass->RepLeader == V) {
1080 // FIXME: When the leader changes, the value numbering of
1081 // everything may change, so we need to reprocess.
1082 VClass->RepLeader = *(VClass->Members.begin());
1083 for (auto M : VClass->Members) {
1084 if (auto *I = dyn_cast<Instruction>(M))
1085 TouchedInstructions.set(InstrDFS[I]);
1086 ChangedValues.insert(M);
1087 }
1088 }
1089 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001090
Davide Italiano7e274e02016-12-22 16:03:48 +00001091 markUsersTouched(V);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001092 if (auto *I = dyn_cast<Instruction>(V)) {
1093 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
1094 // If this is a MemoryDef, we need to update the equivalence table. If
Daniel Berlin25f05b02017-01-02 18:22:38 +00001095 // we determined the expression is congruent to a different memory
1096 // state, use that different memory state. If we determined it didn't,
1097 // we update that as well.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001098 // Right now, the only way they can be equivalent is for store
Daniel Berlin25f05b02017-01-02 18:22:38 +00001099 // expressions.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001100 if (!isa<MemoryUse>(MA)) {
1101 if (E && isa<StoreExpression>(E) && EClass->Members.size() != 1) {
1102 auto *DefAccess = cast<StoreExpression>(E)->getDefiningAccess();
1103 setMemoryAccessEquivTo(MA, DefAccess != MA ? DefAccess : nullptr);
1104 } else {
1105 setMemoryAccessEquivTo(MA, nullptr);
1106 }
1107 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001108 markMemoryUsersTouched(MA);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001109 }
1110 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001111 }
1112}
1113
1114// Process the fact that Edge (from, to) is reachable, including marking
1115// any newly reachable blocks and instructions for processing.
1116void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1117 // Check if the Edge was reachable before.
1118 if (ReachableEdges.insert({From, To}).second) {
1119 // If this block wasn't reachable before, all instructions are touched.
1120 if (ReachableBlocks.insert(To).second) {
1121 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1122 const auto &InstRange = BlockInstRange.lookup(To);
1123 TouchedInstructions.set(InstRange.first, InstRange.second);
1124 } else {
1125 DEBUG(dbgs() << "Block " << getBlockName(To)
1126 << " was reachable, but new edge {" << getBlockName(From)
1127 << "," << getBlockName(To) << "} to it found\n");
1128
1129 // We've made an edge reachable to an existing block, which may
1130 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1131 // they are the only thing that depend on new edges. Anything using their
1132 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001133 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
1134 TouchedInstructions.set(InstrDFS[MemPhi]);
1135
Davide Italiano7e274e02016-12-22 16:03:48 +00001136 auto BI = To->begin();
1137 while (isa<PHINode>(BI)) {
1138 TouchedInstructions.set(InstrDFS[&*BI]);
1139 ++BI;
1140 }
1141 }
1142 }
1143}
1144
1145// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1146// see if we know some constant value for it already.
1147Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1148 auto Result = lookupOperandLeader(Cond, nullptr, B);
1149 if (isa<Constant>(Result))
1150 return Result;
1151 return nullptr;
1152}
1153
1154// Process the outgoing edges of a block for reachability.
1155void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1156 // Evaluate reachability of terminator instruction.
1157 BranchInst *BR;
1158 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1159 Value *Cond = BR->getCondition();
1160 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1161 if (!CondEvaluated) {
1162 if (auto *I = dyn_cast<Instruction>(Cond)) {
1163 const Expression *E = createExpression(I, B);
1164 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1165 CondEvaluated = CE->getConstantValue();
1166 }
1167 } else if (isa<ConstantInt>(Cond)) {
1168 CondEvaluated = Cond;
1169 }
1170 }
1171 ConstantInt *CI;
1172 BasicBlock *TrueSucc = BR->getSuccessor(0);
1173 BasicBlock *FalseSucc = BR->getSuccessor(1);
1174 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1175 if (CI->isOne()) {
1176 DEBUG(dbgs() << "Condition for Terminator " << *TI
1177 << " evaluated to true\n");
1178 updateReachableEdge(B, TrueSucc);
1179 } else if (CI->isZero()) {
1180 DEBUG(dbgs() << "Condition for Terminator " << *TI
1181 << " evaluated to false\n");
1182 updateReachableEdge(B, FalseSucc);
1183 }
1184 } else {
1185 updateReachableEdge(B, TrueSucc);
1186 updateReachableEdge(B, FalseSucc);
1187 }
1188 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1189 // For switches, propagate the case values into the case
1190 // destinations.
1191
1192 // Remember how many outgoing edges there are to every successor.
1193 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1194
Davide Italiano7e274e02016-12-22 16:03:48 +00001195 Value *SwitchCond = SI->getCondition();
1196 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1197 // See if we were able to turn this switch statement into a constant.
1198 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001199 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001200 // We should be able to get case value for this.
1201 auto CaseVal = SI->findCaseValue(CondVal);
1202 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1203 // We proved the value is outside of the range of the case.
1204 // We can't do anything other than mark the default dest as reachable,
1205 // and go home.
1206 updateReachableEdge(B, SI->getDefaultDest());
1207 return;
1208 }
1209 // Now get where it goes and mark it reachable.
1210 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1211 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001212 } else {
1213 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1214 BasicBlock *TargetBlock = SI->getSuccessor(i);
1215 ++SwitchEdges[TargetBlock];
1216 updateReachableEdge(B, TargetBlock);
1217 }
1218 }
1219 } else {
1220 // Otherwise this is either unconditional, or a type we have no
1221 // idea about. Just mark successors as reachable.
1222 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1223 BasicBlock *TargetBlock = TI->getSuccessor(i);
1224 updateReachableEdge(B, TargetBlock);
1225 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001226
1227 // This also may be a memory defining terminator, in which case, set it
1228 // equivalent to nothing.
1229 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1230 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001231 }
1232}
1233
Daniel Berlin85f91b02016-12-26 20:06:58 +00001234// The algorithm initially places the values of the routine in the INITIAL
1235// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001236// class. The leader of INITIAL is the undetermined value `TOP`.
1237// When the algorithm has finished, values still in INITIAL are unreachable.
1238void NewGVN::initializeCongruenceClasses(Function &F) {
1239 // FIXME now i can't remember why this is 2
1240 NextCongruenceNum = 2;
1241 // Initialize all other instructions to be in INITIAL class.
1242 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001243 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001244 for (auto &B : F) {
1245 if (auto *MP = MSSA->getMemoryAccess(&B))
1246 MemoryAccessEquiv.insert({MP, MSSA->getLiveOnEntryDef()});
1247
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001248 for (auto &I : B) {
1249 InitialValues.insert(&I);
1250 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001251 // All memory accesses are equivalent to live on entry to start. They must
1252 // be initialized to something so that initial changes are noticed. For
1253 // the maximal answer, we initialize them all to be the same as
1254 // liveOnEntry. Note that to save time, we only initialize the
1255 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1256 // other expression can generate a memory equivalence. If we start
1257 // handling memcpy/etc, we can expand this.
1258 if (isa<StoreInst>(&I))
1259 MemoryAccessEquiv.insert(
1260 {MSSA->getMemoryAccess(&I), MSSA->getLiveOnEntryDef()});
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001261 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001262 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001263 InitialClass->Members.swap(InitialValues);
1264
1265 // Initialize arguments to be in their own unique congruence classes
1266 for (auto &FA : F.args())
1267 createSingletonCongruenceClass(&FA);
1268}
1269
1270void NewGVN::cleanupTables() {
1271 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1272 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1273 << CongruenceClasses[i]->Members.size() << " members\n");
1274 // Make sure we delete the congruence class (probably worth switching to
1275 // a unique_ptr at some point.
1276 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001277 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001278 }
1279
1280 ValueToClass.clear();
1281 ArgRecycler.clear(ExpressionAllocator);
1282 ExpressionAllocator.Reset();
1283 CongruenceClasses.clear();
1284 ExpressionToClass.clear();
1285 ValueToExpression.clear();
1286 ReachableBlocks.clear();
1287 ReachableEdges.clear();
1288#ifndef NDEBUG
1289 ProcessedCount.clear();
1290#endif
1291 DFSDomMap.clear();
1292 InstrDFS.clear();
1293 InstructionsToErase.clear();
1294
1295 DFSToInstr.clear();
1296 BlockInstRange.clear();
1297 TouchedInstructions.clear();
1298 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001299 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001300}
1301
1302std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1303 unsigned Start) {
1304 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001305 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1306 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001307 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001308 }
1309
Davide Italiano7e274e02016-12-22 16:03:48 +00001310 for (auto &I : *B) {
1311 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001312 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001313 }
1314
1315 // All of the range functions taken half-open ranges (open on the end side).
1316 // So we do not subtract one from count, because at this point it is one
1317 // greater than the last instruction.
1318 return std::make_pair(Start, End);
1319}
1320
1321void NewGVN::updateProcessedCount(Value *V) {
1322#ifndef NDEBUG
1323 if (ProcessedCount.count(V) == 0) {
1324 ProcessedCount.insert({V, 1});
1325 } else {
1326 ProcessedCount[V] += 1;
1327 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001328 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001329 }
1330#endif
1331}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001332// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1333void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1334 // If all the arguments are the same, the MemoryPhi has the same value as the
1335 // argument.
1336 // Filter out unreachable blocks from our operands.
1337 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1338 return ReachableBlocks.count(MP->getIncomingBlock(U));
1339 });
1340
1341 assert(Filtered.begin() != Filtered.end() &&
1342 "We should not be processing a MemoryPhi in a completely "
1343 "unreachable block");
1344
1345 // Transform the remaining operands into operand leaders.
1346 // FIXME: mapped_iterator should have a range version.
1347 auto LookupFunc = [&](const Use &U) {
1348 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1349 };
1350 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1351 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1352
1353 // and now check if all the elements are equal.
1354 // Sadly, we can't use std::equals since these are random access iterators.
1355 MemoryAccess *AllSameValue = *MappedBegin;
1356 ++MappedBegin;
1357 bool AllEqual = std::all_of(
1358 MappedBegin, MappedEnd,
1359 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1360
1361 if (AllEqual)
1362 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1363 else
1364 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1365
1366 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1367 markMemoryUsersTouched(MP);
1368}
1369
1370// Value number a single instruction, symbolically evaluating, performing
1371// congruence finding, and updating mappings.
1372void NewGVN::valueNumberInstruction(Instruction *I) {
1373 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001374 if (isInstructionTriviallyDead(I, TLI)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001375 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001376 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001377 return;
1378 }
1379 if (!I->isTerminator()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001380 const auto *Symbolized = performSymbolicEvaluation(I, I->getParent());
1381 // If we couldn't come up with a symbolic expression, use the unknown
1382 // expression
1383 if (Symbolized == nullptr)
1384 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001385 performCongruenceFinding(I, Symbolized);
1386 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001387 // Handle terminators that return values. All of them produce values we
1388 // don't currently understand.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001389 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001390 auto *Symbolized = createUnknownExpression(I);
1391 performCongruenceFinding(I, Symbolized);
1392 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001393 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1394 }
1395}
Davide Italiano7e274e02016-12-22 16:03:48 +00001396
Daniel Berlin589cecc2017-01-02 18:00:46 +00001397// Verify the that the memory equivalence table makes sense relative to the
1398// congruence classes.
1399void NewGVN::verifyMemoryCongruency() {
1400 // Anything equivalent in the memory access table should be in the same
1401 // congruence class.
1402
1403 // Filter out the unreachable and trivially dead entries, because they may
1404 // never have been updated if the instructions were not processed.
1405 auto ReachableAccessPred =
1406 [&](const std::pair<const MemoryAccess *, MemoryAccess *> Pair) {
1407 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1408 if (!Result)
1409 return false;
1410 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1411 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1412 return true;
1413 };
1414
1415 auto Filtered = make_filter_range(MemoryAccessEquiv, ReachableAccessPred);
1416 for (auto KV : Filtered) {
1417 assert(KV.first != KV.second &&
1418 "We added a useless equivalence to the memory equivalence table");
1419 // Unreachable instructions may not have changed because we never process
1420 // them.
1421 if (!ReachableBlocks.count(KV.first->getBlock()))
1422 continue;
1423 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
1424 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second);
Davide Italiano67ada752017-01-02 19:03:16 +00001425 if (FirstMUD && SecondMUD)
Daniel Berlin589cecc2017-01-02 18:00:46 +00001426 assert(
Davide Italiano67ada752017-01-02 19:03:16 +00001427 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1428 ValueToClass.lookup(SecondMUD->getMemoryInst()) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00001429 "The instructions for these memory operations should have been in "
1430 "the same congruence class");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001431 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1432
1433 // We can only sanely verify that MemoryDefs in the operand list all have
1434 // the same class.
1435 auto ReachableOperandPred = [&](const Use &U) {
1436 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1437 isa<MemoryDef>(U);
1438
1439 };
1440 // All arguments should in the same class, ignoring unreachable arguments
1441 auto FilteredPhiArgs =
1442 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1443 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1444 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1445 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1446 const MemoryDef *MD = cast<MemoryDef>(U);
1447 return ValueToClass.lookup(MD->getMemoryInst());
1448 });
1449 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1450 PhiOpClasses.begin()) &&
1451 "All MemoryPhi arguments should be in the same class");
1452 }
1453 }
1454}
1455
Daniel Berlin85f91b02016-12-26 20:06:58 +00001456// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001457bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001458 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1459 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001460 bool Changed = false;
1461 DT = _DT;
1462 AC = _AC;
1463 TLI = _TLI;
1464 AA = _AA;
1465 MSSA = _MSSA;
1466 DL = &F.getParent()->getDataLayout();
1467 MSSAWalker = MSSA->getWalker();
1468
1469 // Count number of instructions for sizing of hash tables, and come
1470 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001471 unsigned ICount = 1;
1472 // Add an empty instruction to account for the fact that we start at 1
1473 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001474 // Note: We want RPO traversal of the blocks, which is not quite the same as
1475 // dominator tree order, particularly with regard whether backedges get
1476 // visited first or second, given a block with multiple successors.
1477 // If we visit in the wrong order, we will end up performing N times as many
1478 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001479 // The dominator tree does guarantee that, for a given dom tree node, it's
1480 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1481 // the siblings.
1482 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001483 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001484 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001485 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001486 auto *Node = DT->getNode(B);
1487 assert(Node && "RPO and Dominator tree should have same reachability");
1488 RPOOrdering[Node] = ++Counter;
1489 }
1490 // Sort dominator tree children arrays into RPO.
1491 for (auto &B : RPOT) {
1492 auto *Node = DT->getNode(B);
1493 if (Node->getChildren().size() > 1)
1494 std::sort(Node->begin(), Node->end(),
1495 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1496 return RPOOrdering[A] < RPOOrdering[B];
1497 });
1498 }
1499
1500 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1501 auto DFI = df_begin(DT->getRootNode());
1502 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1503 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001504 const auto &BlockRange = assignDFSNumbers(B, ICount);
1505 BlockInstRange.insert({B, BlockRange});
1506 ICount += BlockRange.second - BlockRange.first;
1507 }
1508
1509 // Handle forward unreachable blocks and figure out which blocks
1510 // have single preds.
1511 for (auto &B : F) {
1512 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001513 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001514 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1515 BlockInstRange.insert({&B, BlockRange});
1516 ICount += BlockRange.second - BlockRange.first;
1517 }
1518 }
1519
Daniel Berline0bd37e2016-12-29 22:15:12 +00001520 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001521 DominatedInstRange.reserve(F.size());
1522 // Ensure we don't end up resizing the expressionToClass map, as
1523 // that can be quite expensive. At most, we have one expression per
1524 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001525 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001526
1527 // Initialize the touched instructions to include the entry block.
1528 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1529 TouchedInstructions.set(InstRange.first, InstRange.second);
1530 ReachableBlocks.insert(&F.getEntryBlock());
1531
1532 initializeCongruenceClasses(F);
1533
1534 // We start out in the entry block.
1535 BasicBlock *LastBlock = &F.getEntryBlock();
1536 while (TouchedInstructions.any()) {
1537 // Walk through all the instructions in all the blocks in RPO.
1538 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1539 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Daniel Berline0bd37e2016-12-29 22:15:12 +00001540 assert(InstrNum != 0 && "Bit 0 should never be set, something touched an "
1541 "instruction not in the lookup table");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001542 Value *V = DFSToInstr[InstrNum];
1543 BasicBlock *CurrBlock = nullptr;
1544
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001545 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001546 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001547 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001548 CurrBlock = MP->getBlock();
1549 else
1550 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001551
1552 // If we hit a new block, do reachability processing.
1553 if (CurrBlock != LastBlock) {
1554 LastBlock = CurrBlock;
1555 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1556 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1557
1558 // If it's not reachable, erase any touched instructions and move on.
1559 if (!BlockReachable) {
1560 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1561 DEBUG(dbgs() << "Skipping instructions in block "
1562 << getBlockName(CurrBlock)
1563 << " because it is unreachable\n");
1564 continue;
1565 }
1566 updateProcessedCount(CurrBlock);
1567 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001568
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001569 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001570 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1571 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001572 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001573 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001574 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001575 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001576 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001577 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001578 // Reset after processing (because we may mark ourselves as touched when
1579 // we propagate equalities).
1580 TouchedInstructions.reset(InstrNum);
1581 }
1582 }
1583
Daniel Berlin589cecc2017-01-02 18:00:46 +00001584#ifndef NDEBUG
1585 verifyMemoryCongruency();
1586#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001587 Changed |= eliminateInstructions(F);
1588
1589 // Delete all instructions marked for deletion.
1590 for (Instruction *ToErase : InstructionsToErase) {
1591 if (!ToErase->use_empty())
1592 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1593
1594 ToErase->eraseFromParent();
1595 }
1596
1597 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001598 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1599 return !ReachableBlocks.count(&BB);
1600 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001601
1602 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1603 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001604 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001605 deleteInstructionsInBlock(&BB);
1606 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001607 }
1608
1609 cleanupTables();
1610 return Changed;
1611}
1612
1613bool NewGVN::runOnFunction(Function &F) {
1614 if (skipFunction(F))
1615 return false;
1616 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1617 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1618 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1619 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1620 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1621}
1622
Daniel Berlin85f91b02016-12-26 20:06:58 +00001623PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001624 NewGVN Impl;
1625
1626 // Apparently the order in which we get these results matter for
1627 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1628 // the same order here, just in case.
1629 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1630 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1631 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1632 auto &AA = AM.getResult<AAManager>(F);
1633 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1634 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1635 if (!Changed)
1636 return PreservedAnalyses::all();
1637 PreservedAnalyses PA;
1638 PA.preserve<DominatorTreeAnalysis>();
1639 PA.preserve<GlobalsAA>();
1640 return PA;
1641}
1642
1643// Return true if V is a value that will always be available (IE can
1644// be placed anywhere) in the function. We don't do globals here
1645// because they are often worse to put in place.
1646// TODO: Separate cost from availability
1647static bool alwaysAvailable(Value *V) {
1648 return isa<Constant>(V) || isa<Argument>(V);
1649}
1650
1651// Get the basic block from an instruction/value.
1652static BasicBlock *getBlockForValue(Value *V) {
1653 if (auto *I = dyn_cast<Instruction>(V))
1654 return I->getParent();
1655 return nullptr;
1656}
1657
1658struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001659 int DFSIn = 0;
1660 int DFSOut = 0;
1661 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001662 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001663 Value *Val = nullptr;
1664 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001665
1666 bool operator<(const ValueDFS &Other) const {
1667 // It's not enough that any given field be less than - we have sets
1668 // of fields that need to be evaluated together to give a proper ordering.
1669 // For example, if you have;
1670 // DFS (1, 3)
1671 // Val 0
1672 // DFS (1, 2)
1673 // Val 50
1674 // We want the second to be less than the first, but if we just go field
1675 // by field, we will get to Val 0 < Val 50 and say the first is less than
1676 // the second. We only want it to be less than if the DFS orders are equal.
1677 //
1678 // Each LLVM instruction only produces one value, and thus the lowest-level
1679 // differentiator that really matters for the stack (and what we use as as a
1680 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001681 // Everything else in the structure is instruction level, and only affects
1682 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001683 //
1684 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1685 // the order of replacement of uses does not matter.
1686 // IE given,
1687 // a = 5
1688 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001689 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1690 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001691 // The .val will be the same as well.
1692 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001693 // You will replace both, and it does not matter what order you replace them
1694 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1695 // operand 2).
1696 // Similarly for the case of same dfsin, dfsout, localnum, but different
1697 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001698 // a = 5
1699 // b = 6
1700 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001701 // in c, we will a valuedfs for a, and one for b,with everything the same
1702 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001703 // It does not matter what order we replace these operands in.
1704 // You will always end up with the same IR, and this is guaranteed.
1705 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1706 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1707 Other.U);
1708 }
1709};
1710
1711void NewGVN::convertDenseToDFSOrdered(CongruenceClass::MemberSet &Dense,
1712 std::vector<ValueDFS> &DFSOrderedSet) {
1713 for (auto D : Dense) {
1714 // First add the value.
1715 BasicBlock *BB = getBlockForValue(D);
1716 // Constants are handled prior to ever calling this function, so
1717 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001718 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001719 ValueDFS VD;
1720
1721 std::pair<int, int> DFSPair = DFSDomMap[BB];
1722 assert(DFSPair.first != -1 && DFSPair.second != -1 && "Invalid DFS Pair");
1723 VD.DFSIn = DFSPair.first;
1724 VD.DFSOut = DFSPair.second;
1725 VD.Val = D;
1726 // If it's an instruction, use the real local dfs number.
1727 if (auto *I = dyn_cast<Instruction>(D))
1728 VD.LocalNum = InstrDFS[I];
1729 else
1730 llvm_unreachable("Should have been an instruction");
1731
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001732 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001733
1734 // Now add the users.
1735 for (auto &U : D->uses()) {
1736 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1737 ValueDFS VD;
1738 // Put the phi node uses in the incoming block.
1739 BasicBlock *IBlock;
1740 if (auto *P = dyn_cast<PHINode>(I)) {
1741 IBlock = P->getIncomingBlock(U);
1742 // Make phi node users appear last in the incoming block
1743 // they are from.
1744 VD.LocalNum = InstrDFS.size() + 1;
1745 } else {
1746 IBlock = I->getParent();
1747 VD.LocalNum = InstrDFS[I];
1748 }
1749 std::pair<int, int> DFSPair = DFSDomMap[IBlock];
1750 VD.DFSIn = DFSPair.first;
1751 VD.DFSOut = DFSPair.second;
1752 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001753 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001754 }
1755 }
1756 }
1757}
1758
1759static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1760 // Patch the replacement so that it is not more restrictive than the value
1761 // being replaced.
1762 auto *Op = dyn_cast<BinaryOperator>(I);
1763 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1764
1765 if (Op && ReplOp)
1766 ReplOp->andIRFlags(Op);
1767
1768 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1769 // FIXME: If both the original and replacement value are part of the
1770 // same control-flow region (meaning that the execution of one
1771 // guarentees the executation of the other), then we can combine the
1772 // noalias scopes here and do better than the general conservative
1773 // answer used in combineMetadata().
1774
1775 // In general, GVN unifies expressions over different control-flow
1776 // regions, and so we need a conservative combination of the noalias
1777 // scopes.
1778 unsigned KnownIDs[] = {
1779 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1780 LLVMContext::MD_noalias, LLVMContext::MD_range,
1781 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1782 LLVMContext::MD_invariant_group};
1783 combineMetadata(ReplInst, I, KnownIDs);
1784 }
1785}
1786
1787static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1788 patchReplacementInstruction(I, Repl);
1789 I->replaceAllUsesWith(Repl);
1790}
1791
1792void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
1793 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1794 ++NumGVNBlocksDeleted;
1795
1796 // Check to see if there are non-terminating instructions to delete.
1797 if (isa<TerminatorInst>(BB->begin()))
1798 return;
1799
1800 // Delete the instructions backwards, as it has a reduced likelihood of having
1801 // to update as many def-use and use-def chains. Start after the terminator.
1802 auto StartPoint = BB->rbegin();
1803 ++StartPoint;
1804 // Note that we explicitly recalculate BB->rend() on each iteration,
1805 // as it may change when we remove the first instruction.
1806 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
1807 Instruction &Inst = *I++;
1808 if (!Inst.use_empty())
1809 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
1810 if (isa<LandingPadInst>(Inst))
1811 continue;
1812
1813 Inst.eraseFromParent();
1814 ++NumGVNInstrDeleted;
1815 }
1816}
1817
1818void NewGVN::markInstructionForDeletion(Instruction *I) {
1819 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
1820 InstructionsToErase.insert(I);
1821}
1822
1823void NewGVN::replaceInstruction(Instruction *I, Value *V) {
1824
1825 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
1826 patchAndReplaceAllUsesWith(I, V);
1827 // We save the actual erasing to avoid invalidating memory
1828 // dependencies until we are done with everything.
1829 markInstructionForDeletion(I);
1830}
1831
1832namespace {
1833
1834// This is a stack that contains both the value and dfs info of where
1835// that value is valid.
1836class ValueDFSStack {
1837public:
1838 Value *back() const { return ValueStack.back(); }
1839 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
1840
1841 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001842 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001843 DFSStack.emplace_back(DFSIn, DFSOut);
1844 }
1845 bool empty() const { return DFSStack.empty(); }
1846 bool isInScope(int DFSIn, int DFSOut) const {
1847 if (empty())
1848 return false;
1849 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
1850 }
1851
1852 void popUntilDFSScope(int DFSIn, int DFSOut) {
1853
1854 // These two should always be in sync at this point.
1855 assert(ValueStack.size() == DFSStack.size() &&
1856 "Mismatch between ValueStack and DFSStack");
1857 while (
1858 !DFSStack.empty() &&
1859 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
1860 DFSStack.pop_back();
1861 ValueStack.pop_back();
1862 }
1863 }
1864
1865private:
1866 SmallVector<Value *, 8> ValueStack;
1867 SmallVector<std::pair<int, int>, 8> DFSStack;
1868};
1869}
1870
1871bool NewGVN::eliminateInstructions(Function &F) {
1872 // This is a non-standard eliminator. The normal way to eliminate is
1873 // to walk the dominator tree in order, keeping track of available
1874 // values, and eliminating them. However, this is mildly
1875 // pointless. It requires doing lookups on every instruction,
1876 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001877 // instructions part of most singleton congruence classes, we know we
1878 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00001879
1880 // Instead, this eliminator looks at the congruence classes directly, sorts
1881 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001882 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001883 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001884 // last member. This is worst case O(E log E) where E = number of
1885 // instructions in a single congruence class. In theory, this is all
1886 // instructions. In practice, it is much faster, as most instructions are
1887 // either in singleton congruence classes or can't possibly be eliminated
1888 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00001889 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001890 // for elimination purposes.
1891 // TODO: If we wanted to be faster, We could remove any members with no
1892 // overlapping ranges while sorting, as we will never eliminate anything
1893 // with those members, as they don't dominate anything else in our set.
1894
Davide Italiano7e274e02016-12-22 16:03:48 +00001895 bool AnythingReplaced = false;
1896
1897 // Since we are going to walk the domtree anyway, and we can't guarantee the
1898 // DFS numbers are updated, we compute some ourselves.
1899 DT->updateDFSNumbers();
1900
1901 for (auto &B : F) {
1902 if (!ReachableBlocks.count(&B)) {
1903 for (const auto S : successors(&B)) {
1904 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001905 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00001906 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
1907 << getBlockName(&B)
1908 << " with undef due to it being unreachable\n");
1909 for (auto &Operand : Phi.incoming_values())
1910 if (Phi.getIncomingBlock(Operand) == &B)
1911 Operand.set(UndefValue::get(Phi.getType()));
1912 }
1913 }
1914 }
1915 DomTreeNode *Node = DT->getNode(&B);
1916 if (Node)
1917 DFSDomMap[&B] = {Node->getDFSNumIn(), Node->getDFSNumOut()};
1918 }
1919
1920 for (CongruenceClass *CC : CongruenceClasses) {
1921 // FIXME: We should eventually be able to replace everything still
1922 // in the initial class with undef, as they should be unreachable.
1923 // Right now, initial still contains some things we skip value
1924 // numbering of (UNREACHABLE's, for example).
1925 if (CC == InitialClass || CC->Dead)
1926 continue;
1927 assert(CC->RepLeader && "We should have had a leader");
1928
1929 // If this is a leader that is always available, and it's a
1930 // constant or has no equivalences, just replace everything with
1931 // it. We then update the congruence class with whatever members
1932 // are left.
1933 if (alwaysAvailable(CC->RepLeader)) {
1934 SmallPtrSet<Value *, 4> MembersLeft;
1935 for (auto M : CC->Members) {
1936
1937 Value *Member = M;
1938
1939 // Void things have no uses we can replace.
1940 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
1941 MembersLeft.insert(Member);
1942 continue;
1943 }
1944
1945 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for "
1946 << *Member << "\n");
1947 // Due to equality propagation, these may not always be
1948 // instructions, they may be real values. We don't really
1949 // care about trying to replace the non-instructions.
1950 if (auto *I = dyn_cast<Instruction>(Member)) {
1951 assert(CC->RepLeader != I &&
1952 "About to accidentally remove our leader");
1953 replaceInstruction(I, CC->RepLeader);
1954 AnythingReplaced = true;
1955
1956 continue;
1957 } else {
1958 MembersLeft.insert(I);
1959 }
1960 }
1961 CC->Members.swap(MembersLeft);
1962
1963 } else {
1964 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
1965 // If this is a singleton, we can skip it.
1966 if (CC->Members.size() != 1) {
1967
1968 // This is a stack because equality replacement/etc may place
1969 // constants in the middle of the member list, and we want to use
1970 // those constant values in preference to the current leader, over
1971 // the scope of those constants.
1972 ValueDFSStack EliminationStack;
1973
1974 // Convert the members to DFS ordered sets and then merge them.
1975 std::vector<ValueDFS> DFSOrderedSet;
1976 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
1977
1978 // Sort the whole thing.
1979 sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
1980
1981 for (auto &C : DFSOrderedSet) {
1982 int MemberDFSIn = C.DFSIn;
1983 int MemberDFSOut = C.DFSOut;
1984 Value *Member = C.Val;
1985 Use *MemberUse = C.U;
1986
1987 // We ignore void things because we can't get a value from them.
1988 if (Member && Member->getType()->isVoidTy())
1989 continue;
1990
1991 if (EliminationStack.empty()) {
1992 DEBUG(dbgs() << "Elimination Stack is empty\n");
1993 } else {
1994 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
1995 << EliminationStack.dfs_back().first << ","
1996 << EliminationStack.dfs_back().second << ")\n");
1997 }
1998 if (Member && isa<Constant>(Member))
1999 assert(isa<Constant>(CC->RepLeader));
2000
2001 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2002 << MemberDFSOut << ")\n");
2003 // First, we see if we are out of scope or empty. If so,
2004 // and there equivalences, we try to replace the top of
2005 // stack with equivalences (if it's on the stack, it must
2006 // not have been eliminated yet).
2007 // Then we synchronize to our current scope, by
2008 // popping until we are back within a DFS scope that
2009 // dominates the current member.
2010 // Then, what happens depends on a few factors
2011 // If the stack is now empty, we need to push
2012 // If we have a constant or a local equivalence we want to
2013 // start using, we also push.
2014 // Otherwise, we walk along, processing members who are
2015 // dominated by this scope, and eliminate them.
2016 bool ShouldPush =
2017 Member && (EliminationStack.empty() || isa<Constant>(Member));
2018 bool OutOfScope =
2019 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2020
2021 if (OutOfScope || ShouldPush) {
2022 // Sync to our current scope.
2023 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2024 ShouldPush |= Member && EliminationStack.empty();
2025 if (ShouldPush) {
2026 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2027 }
2028 }
2029
2030 // If we get to this point, and the stack is empty we must have a use
2031 // with nothing we can use to eliminate it, just skip it.
2032 if (EliminationStack.empty())
2033 continue;
2034
2035 // Skip the Value's, we only want to eliminate on their uses.
2036 if (Member)
2037 continue;
2038 Value *Result = EliminationStack.back();
2039
Daniel Berline0bd37e2016-12-29 22:15:12 +00002040 // Don't replace our existing users with ourselves, and don't replace
2041 // phi node arguments with the result of the same phi node.
2042 // IE tmp = phi(tmp11, undef); tmp11 = foo -> tmp = phi(tmp, undef)
2043 if (MemberUse->get() == Result ||
2044 (isa<PHINode>(Result) && MemberUse->getUser() == Result))
Davide Italiano7e274e02016-12-22 16:03:48 +00002045 continue;
2046
2047 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2048 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2049 << "\n");
2050
2051 // If we replaced something in an instruction, handle the patching of
2052 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002053 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002054 patchReplacementInstruction(ReplacedInst, Result);
2055
2056 assert(isa<Instruction>(MemberUse->getUser()));
2057 MemberUse->set(Result);
2058 AnythingReplaced = true;
2059 }
2060 }
2061 }
2062
2063 // Cleanup the congruence class.
2064 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002065 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002066 if (Member->getType()->isVoidTy()) {
2067 MembersLeft.insert(Member);
2068 continue;
2069 }
2070
2071 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2072 if (isInstructionTriviallyDead(MemberInst)) {
2073 // TODO: Don't mark loads of undefs.
2074 markInstructionForDeletion(MemberInst);
2075 continue;
2076 }
2077 }
2078 MembersLeft.insert(Member);
2079 }
2080 CC->Members.swap(MembersLeft);
2081 }
2082
2083 return AnythingReplaced;
2084}