blob: 48624a07d7c34898d8ca7987d58a1023dc39837b [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 {
90 Expression::~Expression() = default;
91 BasicExpression::~BasicExpression() = default;
92 CallExpression::~CallExpression() = default;
93 LoadExpression::~LoadExpression() = default;
94 StoreExpression::~StoreExpression() = default;
95 AggregateValueExpression::~AggregateValueExpression() = default;
96 PHIExpression::~PHIExpression() = default;
97}
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 {
123 typedef SmallPtrSet<Value *, 4> MemberSet;
124 unsigned ID;
125 // Representative leader.
126 Value *RepLeader;
127 // Defining Expression.
128 const Expression *DefiningExpr;
129 // 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.
134 bool Dead;
135
136 explicit CongruenceClass(unsigned ID)
137 : ID(ID), RepLeader(0), DefiningExpr(0), Dead(false) {}
138 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
139 : ID(ID), RepLeader(Leader), DefiningExpr(E), Dead(false) {}
140};
141
142namespace llvm {
143 template <> struct DenseMapInfo<const Expression *> {
144 static const Expression *getEmptyKey() {
145 uintptr_t Val = static_cast<uintptr_t>(-1);
146 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
147 return reinterpret_cast<const Expression *>(Val);
148 }
149 static const Expression *getTombstoneKey() {
150 uintptr_t Val = static_cast<uintptr_t>(~1U);
151 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
152 return reinterpret_cast<const Expression *>(Val);
153 }
154 static unsigned getHashValue(const Expression *V) {
155 return static_cast<unsigned>(V->getHashValue());
156 }
157 static bool isEqual(const Expression *LHS, const Expression *RHS) {
158 if (LHS == RHS)
159 return true;
160 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
161 LHS == getEmptyKey() || RHS == getEmptyKey())
162 return false;
163 return *LHS == *RHS;
164 }
165 };
166} // end namespace llvm
167
168class NewGVN : public FunctionPass {
169 DominatorTree *DT;
170 const DataLayout *DL;
171 const TargetLibraryInfo *TLI;
172 AssumptionCache *AC;
173 AliasAnalysis *AA;
174 MemorySSA *MSSA;
175 MemorySSAWalker *MSSAWalker;
176 BumpPtrAllocator ExpressionAllocator;
177 ArrayRecycler<Value *> ArgRecycler;
178
179 // Congruence class info.
180 CongruenceClass *InitialClass;
181 std::vector<CongruenceClass *> CongruenceClasses;
182 unsigned NextCongruenceNum;
183
184 // Value Mappings.
185 DenseMap<Value *, CongruenceClass *> ValueToClass;
186 DenseMap<Value *, const Expression *> ValueToExpression;
187
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000188 // A table storing which memorydefs/phis represent a memory state provably
189 // equivalent to another memory state.
190 // We could use the congruence class machinery, but the MemoryAccess's are
191 // abstract memory states, so they can only ever be equivalent to each other,
192 // and not to constants, etc.
193 DenseMap<MemoryAccess *, MemoryAccess *> MemoryAccessEquiv;
194
Davide Italiano7e274e02016-12-22 16:03:48 +0000195 // Expression to class mapping.
196 typedef DenseMap<const Expression *, CongruenceClass *> ExpressionClassMap;
197 ExpressionClassMap ExpressionToClass;
198
199 // Which values have changed as a result of leader changes.
200 SmallPtrSet<Value *, 8> ChangedValues;
201
202 // Reachability info.
203 typedef BasicBlockEdge BlockEdge;
204 DenseSet<BlockEdge> ReachableEdges;
205 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
206
207 // This is a bitvector because, on larger functions, we may have
208 // thousands of touched instructions at once (entire blocks,
209 // instructions with hundreds of uses, etc). Even with optimization
210 // for when we mark whole blocks as touched, when this was a
211 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
212 // the time in GVN just managing this list. The bitvector, on the
213 // other hand, efficiently supports test/set/clear of both
214 // individual and ranges, as well as "find next element" This
215 // enables us to use it as a worklist with essentially 0 cost.
216 BitVector TouchedInstructions;
217
218 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
219 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
220 DominatedInstRange;
221
222#ifndef NDEBUG
223 // Debugging for how many times each block and instruction got processed.
224 DenseMap<const Value *, unsigned> ProcessedCount;
225#endif
226
227 // DFS info.
228 DenseMap<const BasicBlock *, std::pair<int, int>> DFSDomMap;
229 DenseMap<const Value *, unsigned> InstrDFS;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000230 std::vector<Value *> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000231
232 // Deletion info.
233 SmallPtrSet<Instruction *, 8> InstructionsToErase;
234
235public:
236 static char ID; // Pass identification, replacement for typeid.
237 NewGVN() : FunctionPass(ID) {
238 initializeNewGVNPass(*PassRegistry::getPassRegistry());
239 }
240
241 bool runOnFunction(Function &F) override;
242 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
243 TargetLibraryInfo *TLI, AliasAnalysis *AA,
244 MemorySSA *MSSA);
245
246private:
247 // This transformation requires dominator postdominator info.
248 void getAnalysisUsage(AnalysisUsage &AU) const override {
249 AU.addRequired<AssumptionCacheTracker>();
250 AU.addRequired<DominatorTreeWrapperPass>();
251 AU.addRequired<TargetLibraryInfoWrapperPass>();
252 AU.addRequired<MemorySSAWrapperPass>();
253 AU.addRequired<AAResultsWrapperPass>();
254
255 AU.addPreserved<DominatorTreeWrapperPass>();
256 AU.addPreserved<GlobalsAAWrapperPass>();
257 }
258
259 // Expression handling.
260 const Expression *createExpression(Instruction *, const BasicBlock *);
261 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
262 const BasicBlock *);
263 PHIExpression *createPHIExpression(Instruction *);
264 const VariableExpression *createVariableExpression(Value *);
265 const ConstantExpression *createConstantExpression(Constant *);
266 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
267 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
268 const BasicBlock *);
269 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
270 MemoryAccess *, const BasicBlock *);
271
272 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
273 const BasicBlock *);
274 const AggregateValueExpression *
275 createAggregateValueExpression(Instruction *, const BasicBlock *);
276 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
277 const BasicBlock *);
278
279 // Congruence class handling.
280 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
281 CongruenceClass *result =
282 new CongruenceClass(NextCongruenceNum++, Leader, E);
283 CongruenceClasses.emplace_back(result);
284 return result;
285 }
286
287 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
288 CongruenceClass *CClass = createCongruenceClass(Member, NULL);
289 CClass->Members.insert(Member);
290 ValueToClass[Member] = CClass;
291 return CClass;
292 }
293 void initializeCongruenceClasses(Function &F);
294
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000295 // Value number an Instruction or MemoryPhi.
296 void valueNumberMemoryPhi(MemoryPhi *);
297 void valueNumberInstruction(Instruction *);
298
Davide Italiano7e274e02016-12-22 16:03:48 +0000299 // Symbolic evaluation.
300 const Expression *checkSimplificationResults(Expression *, Instruction *,
301 Value *);
302 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
303 const Expression *performSymbolicLoadEvaluation(Instruction *,
304 const BasicBlock *);
305 const Expression *performSymbolicStoreEvaluation(Instruction *,
306 const BasicBlock *);
307 const Expression *performSymbolicCallEvaluation(Instruction *,
308 const BasicBlock *);
309 const Expression *performSymbolicPHIEvaluation(Instruction *,
310 const BasicBlock *);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000311 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To);
Davide Italiano7e274e02016-12-22 16:03:48 +0000312 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
313 const BasicBlock *);
314
315 // Congruence finding.
316 // Templated to allow them to work both on BB's and BB-edges.
317 template <class T>
318 Value *lookupOperandLeader(Value *, const User *, const T &) const;
319 void performCongruenceFinding(Value *, const Expression *);
320
321 // Reachability handling.
322 void updateReachableEdge(BasicBlock *, BasicBlock *);
323 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000324 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000325 Value *findConditionEquivalence(Value *, BasicBlock *) const;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000326 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000327
328 // Elimination.
329 struct ValueDFS;
330 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &,
331 std::vector<ValueDFS> &);
332
333 bool eliminateInstructions(Function &);
334 void replaceInstruction(Instruction *, Value *);
335 void markInstructionForDeletion(Instruction *);
336 void deleteInstructionsInBlock(BasicBlock *);
337
338 // New instruction creation.
339 void handleNewInstruction(Instruction *){};
340 void markUsersTouched(Value *);
341 void markMemoryUsersTouched(MemoryAccess *);
342
343 // Utilities.
344 void cleanupTables();
345 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
346 void updateProcessedCount(Value *V);
347};
348
349char NewGVN::ID = 0;
350
351// createGVNPass - The public interface to this file.
352FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
353
354bool LoadExpression::equals(const Expression &Other) const {
355 if (!isa<LoadExpression>(Other) && !isa<StoreExpression>(Other))
356 return false;
357 if (!this->BasicExpression::equals(Other))
358 return false;
359 if (const auto *OtherL = dyn_cast<LoadExpression>(&Other)) {
360 if (DefiningAccess != OtherL->getDefiningAccess())
361 return false;
362 } else if (const auto *OtherS = dyn_cast<StoreExpression>(&Other)) {
363 if (DefiningAccess != OtherS->getDefiningAccess())
364 return false;
365 }
366
367 return true;
368}
369
370bool StoreExpression::equals(const Expression &Other) const {
371 if (!isa<LoadExpression>(Other) && !isa<StoreExpression>(Other))
372 return false;
373 if (!this->BasicExpression::equals(Other))
374 return false;
375 if (const auto *OtherL = dyn_cast<LoadExpression>(&Other)) {
376 if (DefiningAccess != OtherL->getDefiningAccess())
377 return false;
378 } else if (const auto *OtherS = dyn_cast<StoreExpression>(&Other)) {
379 if (DefiningAccess != OtherS->getDefiningAccess())
380 return false;
381 }
382
383 return true;
384}
385
386#ifndef NDEBUG
387static std::string getBlockName(const BasicBlock *B) {
388 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, NULL);
389}
390#endif
391
392INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
393INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
394INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
395INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
396INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
397INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
398INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
399INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
400
401PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
402 BasicBlock *PhiBlock = I->getParent();
403 PHINode *PN = cast<PHINode>(I);
404 PHIExpression *E = new (ExpressionAllocator)
405 PHIExpression(PN->getNumOperands(), I->getParent());
406
407 E->allocateOperands(ArgRecycler, ExpressionAllocator);
408 E->setType(I->getType());
409 E->setOpcode(I->getOpcode());
410 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
411 BasicBlock *B = PN->getIncomingBlock(i);
412 if (!ReachableBlocks.count(B)) {
413 DEBUG(dbgs() << "Skipping unreachable block " << getBlockName(B)
414 << " in PHI node " << *PN << "\n");
415 continue;
416 }
417 if (I->getOperand(i) != I) {
418 const BasicBlockEdge BBE(B, PhiBlock);
Davide Italianoa312ca82016-12-26 16:19:34 +0000419 E->op_push_back(lookupOperandLeader(I->getOperand(i), I, BBE));
Davide Italiano7e274e02016-12-22 16:03:48 +0000420 } else {
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000421 E->op_push_back(I->getOperand(i));
Davide Italiano7e274e02016-12-22 16:03:48 +0000422 }
423 }
424 return E;
425}
426
427// Set basic expression info (Arguments, type, opcode) for Expression
428// E from Instruction I in block B.
429bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
430 const BasicBlock *B) {
431 bool AllConstant = true;
432 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
433 E->setType(GEP->getSourceElementType());
434 else
435 E->setType(I->getType());
436 E->setOpcode(I->getOpcode());
437 E->allocateOperands(ArgRecycler, ExpressionAllocator);
438
439 for (auto &O : I->operands()) {
440 auto Operand = lookupOperandLeader(O, I, B);
441 if (!isa<Constant>(Operand))
442 AllConstant = false;
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000443 E->op_push_back(Operand);
Davide Italiano7e274e02016-12-22 16:03:48 +0000444 }
445 return AllConstant;
446}
447
448const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
449 Value *Arg1, Value *Arg2,
450 const BasicBlock *B) {
451 BasicExpression *E = new (ExpressionAllocator) BasicExpression(2);
452
453 E->setType(T);
454 E->setOpcode(Opcode);
455 E->allocateOperands(ArgRecycler, ExpressionAllocator);
456 if (Instruction::isCommutative(Opcode)) {
457 // Ensure that commutative instructions that only differ by a permutation
458 // of their operands get the same value number by sorting the operand value
459 // numbers. Since all commutative instructions have two operands it is more
460 // efficient to sort by hand rather than using, say, std::sort.
461 if (Arg1 > Arg2)
462 std::swap(Arg1, Arg2);
463 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000464 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
465 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000466
467 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
468 DT, AC);
469 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
470 return SimplifiedE;
471 return E;
472}
473
474// Take a Value returned by simplification of Expression E/Instruction
475// I, and see if it resulted in a simpler expression. If so, return
476// that expression.
477// TODO: Once finished, this should not take an Instruction, we only
478// use it for printing.
479const Expression *NewGVN::checkSimplificationResults(Expression *E,
480 Instruction *I, Value *V) {
481 if (!V)
482 return nullptr;
483 if (auto *C = dyn_cast<Constant>(V)) {
484 if (I)
485 DEBUG(dbgs() << "Simplified " << *I << " to "
486 << " constant " << *C << "\n");
487 NumGVNOpsSimplified++;
488 assert(isa<BasicExpression>(E) &&
489 "We should always have had a basic expression here");
490
491 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
492 ExpressionAllocator.Deallocate(E);
493 return createConstantExpression(C);
494 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
495 if (I)
496 DEBUG(dbgs() << "Simplified " << *I << " to "
497 << " variable " << *V << "\n");
498 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
499 ExpressionAllocator.Deallocate(E);
500 return createVariableExpression(V);
501 }
502
503 CongruenceClass *CC = ValueToClass.lookup(V);
504 if (CC && CC->DefiningExpr) {
505 if (I)
506 DEBUG(dbgs() << "Simplified " << *I << " to "
507 << " expression " << *V << "\n");
508 NumGVNOpsSimplified++;
509 assert(isa<BasicExpression>(E) &&
510 "We should always have had a basic expression here");
511 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
512 ExpressionAllocator.Deallocate(E);
513 return CC->DefiningExpr;
514 }
515 return nullptr;
516}
517
518const Expression *NewGVN::createExpression(Instruction *I,
519 const BasicBlock *B) {
520
521 BasicExpression *E =
522 new (ExpressionAllocator) BasicExpression(I->getNumOperands());
523
524 bool AllConstant = setBasicExpressionInfo(I, E, B);
525
526 if (I->isCommutative()) {
527 // Ensure that commutative instructions that only differ by a permutation
528 // of their operands get the same value number by sorting the operand value
529 // numbers. Since all commutative instructions have two operands it is more
530 // efficient to sort by hand rather than using, say, std::sort.
531 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
532 if (E->getOperand(0) > E->getOperand(1))
533 E->swapOperands(0, 1);
534 }
535
536 // Perform simplificaiton
537 // TODO: Right now we only check to see if we get a constant result.
538 // We may get a less than constant, but still better, result for
539 // some operations.
540 // IE
541 // add 0, x -> x
542 // and x, x -> x
543 // We should handle this by simply rewriting the expression.
544 if (auto *CI = dyn_cast<CmpInst>(I)) {
545 // Sort the operand value numbers so x<y and y>x get the same value
546 // number.
547 CmpInst::Predicate Predicate = CI->getPredicate();
548 if (E->getOperand(0) > E->getOperand(1)) {
549 E->swapOperands(0, 1);
550 Predicate = CmpInst::getSwappedPredicate(Predicate);
551 }
552 E->setOpcode((CI->getOpcode() << 8) | Predicate);
553 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
554 // TODO: Since we noop bitcasts, we may need to check types before
555 // simplifying, so that we don't end up simplifying based on a wrong
556 // type assumption. We should clean this up so we can use constants of the
557 // wrong type
558
559 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
560 "Wrong types on cmp instruction");
561 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
562 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
563 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
564 *DL, TLI, DT, AC);
565 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
566 return SimplifiedE;
567 }
568 } else if (isa<SelectInst>(I)) {
569 if (isa<Constant>(E->getOperand(0)) ||
570 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
571 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
572 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
573 E->getOperand(2), *DL, TLI, DT, AC);
574 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
575 return SimplifiedE;
576 }
577 } else if (I->isBinaryOp()) {
578 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
579 *DL, TLI, DT, AC);
580 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
581 return SimplifiedE;
582 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
583 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
584 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
585 return SimplifiedE;
586 } else if (isa<GetElementPtrInst>(I)) {
587 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000588 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000589 *DL, TLI, DT, AC);
590 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
591 return SimplifiedE;
592 } else if (AllConstant) {
593 // We don't bother trying to simplify unless all of the operands
594 // were constant.
595 // TODO: There are a lot of Simplify*'s we could call here, if we
596 // wanted to. The original motivating case for this code was a
597 // zext i1 false to i8, which we don't have an interface to
598 // simplify (IE there is no SimplifyZExt).
599
600 SmallVector<Constant *, 8> C;
601 for (Value *Arg : E->operands())
602 C.emplace_back(cast<Constant>(Arg));
603
604 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
605 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
606 return SimplifiedE;
607 }
608 return E;
609}
610
611const AggregateValueExpression *
612NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
613 if (auto *II = dyn_cast<InsertValueInst>(I)) {
614 AggregateValueExpression *E = new (ExpressionAllocator)
615 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
616 setBasicExpressionInfo(I, E, B);
617 E->allocateIntOperands(ExpressionAllocator);
618
619 for (auto &Index : II->indices())
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000620 E->int_op_push_back(Index);
Davide Italiano7e274e02016-12-22 16:03:48 +0000621 return E;
622
623 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
624 AggregateValueExpression *E = new (ExpressionAllocator)
625 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
626 setBasicExpressionInfo(EI, E, B);
627 E->allocateIntOperands(ExpressionAllocator);
628
629 for (auto &Index : EI->indices())
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000630 E->int_op_push_back(Index);
Davide Italiano7e274e02016-12-22 16:03:48 +0000631 return E;
632 }
633 llvm_unreachable("Unhandled type of aggregate value operation");
634}
635
636const VariableExpression *
637NewGVN::createVariableExpression(Value *V) {
638 VariableExpression *E = new (ExpressionAllocator) VariableExpression(V);
639 E->setOpcode(V->getValueID());
640 return E;
641}
642
643const Expression *NewGVN::createVariableOrConstant(Value *V,
644 const BasicBlock *B) {
645 auto Leader = lookupOperandLeader(V, nullptr, B);
646 if (auto *C = dyn_cast<Constant>(Leader))
647 return createConstantExpression(C);
648 return createVariableExpression(Leader);
649}
650
651const ConstantExpression *
652NewGVN::createConstantExpression(Constant *C) {
653 ConstantExpression *E = new (ExpressionAllocator) ConstantExpression(C);
654 E->setOpcode(C->getValueID());
655 return E;
656}
657
658const CallExpression *NewGVN::createCallExpression(CallInst *CI,
659 MemoryAccess *HV,
660 const BasicBlock *B) {
661 // FIXME: Add operand bundles for calls.
662 CallExpression *E =
663 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
664 setBasicExpressionInfo(CI, E, B);
665 return E;
666}
667
668// See if we have a congruence class and leader for this operand, and if so,
669// return it. Otherwise, return the operand itself.
670template <class T>
671Value *NewGVN::lookupOperandLeader(Value *V, const User *U,
672 const T &B) const {
673 CongruenceClass *CC = ValueToClass.lookup(V);
674 if (CC && (CC != InitialClass))
675 return CC->RepLeader;
676 return V;
677}
678
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000679MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
680 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
681 return Result ? Result : MA;
682}
683
Davide Italiano7e274e02016-12-22 16:03:48 +0000684LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
685 LoadInst *LI, MemoryAccess *DA,
686 const BasicBlock *B) {
687 LoadExpression *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
688 E->allocateOperands(ArgRecycler, ExpressionAllocator);
689 E->setType(LoadType);
690
691 // Give store and loads same opcode so they value number together.
692 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000693 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000694 if (LI)
695 E->setAlignment(LI->getAlignment());
696
697 // TODO: Value number heap versions. We may be able to discover
698 // things alias analysis can't on it's own (IE that a store and a
699 // load have the same value, and thus, it isn't clobbering the load).
700 return E;
701}
702
703const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
704 MemoryAccess *DA,
705 const BasicBlock *B) {
706 StoreExpression *E =
707 new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, DA);
708 E->allocateOperands(ArgRecycler, ExpressionAllocator);
709 E->setType(SI->getValueOperand()->getType());
710
711 // Give store and loads same opcode so they value number together.
712 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000713 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000714
715 // TODO: Value number heap versions. We may be able to discover
716 // things alias analysis can't on it's own (IE that a store and a
717 // load have the same value, and thus, it isn't clobbering the load).
718 return E;
719}
720
721const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
722 const BasicBlock *B) {
723 StoreInst *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000724 // If this store's memorydef stores the same value as the last store, the
725 // memory accesses are equivalent.
726 // Get the expression, if any, for the RHS of the MemoryDef.
727 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
728 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
729 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
730 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
731 // See if this store expression already has a value, and it's the same as our
732 // current store.
733 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
734 if (CC &&
735 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B)) {
736 setMemoryAccessEquivTo(StoreAccess, StoreRHS);
737 return OldStore;
738 }
739 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000740}
741
742const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
743 const BasicBlock *B) {
744 LoadInst *LI = cast<LoadInst>(I);
745
746 // We can eliminate in favor of non-simple loads, but we won't be able to
747 // eliminate them.
748 if (!LI->isSimple())
749 return nullptr;
750
751 Value *LoadAddressLeader =
752 lookupOperandLeader(LI->getPointerOperand(), I, B);
753 // Load of undef is undef.
754 if (isa<UndefValue>(LoadAddressLeader))
755 return createConstantExpression(UndefValue::get(LI->getType()));
756
757 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
758
759 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
760 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
761 Instruction *DefiningInst = MD->getMemoryInst();
762 // If the defining instruction is not reachable, replace with undef.
763 if (!ReachableBlocks.count(DefiningInst->getParent()))
764 return createConstantExpression(UndefValue::get(LI->getType()));
765 }
766 }
767
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000768 const Expression *E =
769 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
770 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000771 return E;
772}
773
774// Evaluate read only and pure calls, and create an expression result.
775const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
776 const BasicBlock *B) {
777 CallInst *CI = cast<CallInst>(I);
778 if (AA->doesNotAccessMemory(CI))
779 return createCallExpression(CI, nullptr, B);
780 else if (AA->onlyReadsMemory(CI))
781 return createCallExpression(CI, MSSAWalker->getClobberingMemoryAccess(CI),
782 B);
783 else
784 return nullptr;
785}
786
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000787// Update the memory access equivalence table to say that From is equal to To,
788// and return true if this is different from what already existed in the table.
789bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
790 auto LookupResult = MemoryAccessEquiv.insert({From, nullptr});
791 bool Changed = false;
792 // If it's already in the table, see if the value changed.
793 if (LookupResult.second) {
794 if (To && LookupResult.first->second != To) {
795 // It wasn't equivalent before, and now it is.
796 LookupResult.first->second = To;
797 Changed = true;
798 } else if (!To) {
799 // It used to be equivalent to something, and now it's not.
800 MemoryAccessEquiv.erase(LookupResult.first);
801 Changed = true;
802 }
803 } else if (To) {
804 // It wasn't in the table, but is equivalent to something.
805 LookupResult.first->second = To;
806 Changed = true;
807 }
808 return Changed;
809}
Davide Italiano7e274e02016-12-22 16:03:48 +0000810// Evaluate PHI nodes symbolically, and create an expression result.
811const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
812 const BasicBlock *B) {
813 PHIExpression *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000814 if (E->op_empty()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000815 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
816 << "\n");
817 E->deallocateOperands(ArgRecycler);
818 ExpressionAllocator.Deallocate(E);
819 return createConstantExpression(UndefValue::get(I->getType()));
820 }
821
822 Value *AllSameValue = E->getOperand(0);
823
824 // See if all arguments are the same, ignoring undef arguments, because we can
825 // choose a value that is the same for them.
826 for (const Value *Arg : E->operands())
827 if (Arg != AllSameValue && !isa<UndefValue>(Arg)) {
828 AllSameValue = NULL;
829 break;
830 }
831
832 if (AllSameValue) {
833 // It's possible to have phi nodes with cycles (IE dependent on
834 // other phis that are .... dependent on the original phi node),
835 // especially in weird CFG's where some arguments are unreachable, or
836 // uninitialized along certain paths.
837 // This can cause infinite loops during evaluation (even if you disable
838 // the recursion below, you will simply ping-pong between congruence
839 // classes). If a phi node symbolically evaluates to another phi node,
840 // just leave it alone. If they are really the same, we will still
841 // eliminate them in favor of each other.
842 if (isa<PHINode>(AllSameValue))
843 return E;
844 NumGVNPhisAllSame++;
845 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
846 << "\n");
847 E->deallocateOperands(ArgRecycler);
848 ExpressionAllocator.Deallocate(E);
849 if (auto *C = dyn_cast<Constant>(AllSameValue))
850 return createConstantExpression(C);
851 return createVariableExpression(AllSameValue);
852 }
853 return E;
854}
855
856const Expression *
857NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
858 const BasicBlock *B) {
859 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
860 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
861 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
862 unsigned Opcode = 0;
863 // EI might be an extract from one of our recognised intrinsics. If it
864 // is we'll synthesize a semantically equivalent expression instead on
865 // an extract value expression.
866 switch (II->getIntrinsicID()) {
867 case Intrinsic::sadd_with_overflow:
868 case Intrinsic::uadd_with_overflow:
869 Opcode = Instruction::Add;
870 break;
871 case Intrinsic::ssub_with_overflow:
872 case Intrinsic::usub_with_overflow:
873 Opcode = Instruction::Sub;
874 break;
875 case Intrinsic::smul_with_overflow:
876 case Intrinsic::umul_with_overflow:
877 Opcode = Instruction::Mul;
878 break;
879 default:
880 break;
881 }
882
883 if (Opcode != 0) {
884 // Intrinsic recognized. Grab its args to finish building the
885 // expression.
886 assert(II->getNumArgOperands() == 2 &&
887 "Expect two args for recognised intrinsics.");
888 return createBinaryExpression(Opcode, EI->getType(),
889 II->getArgOperand(0),
890 II->getArgOperand(1), B);
891 }
892 }
893 }
894
895 return createAggregateValueExpression(I, B);
896}
897
898// Substitute and symbolize the value before value numbering.
899const Expression *NewGVN::performSymbolicEvaluation(Value *V,
900 const BasicBlock *B) {
901 const Expression *E = NULL;
902 if (auto *C = dyn_cast<Constant>(V))
903 E = createConstantExpression(C);
904 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
905 E = createVariableExpression(V);
906 } else {
907 // TODO: memory intrinsics.
908 // TODO: Some day, we should do the forward propagation and reassociation
909 // parts of the algorithm.
910 Instruction *I = cast<Instruction>(V);
911 switch (I->getOpcode()) {
912 case Instruction::ExtractValue:
913 case Instruction::InsertValue:
914 E = performSymbolicAggrValueEvaluation(I, B);
915 break;
916 case Instruction::PHI:
917 E = performSymbolicPHIEvaluation(I, B);
918 break;
919 case Instruction::Call:
920 E = performSymbolicCallEvaluation(I, B);
921 break;
922 case Instruction::Store:
923 E = performSymbolicStoreEvaluation(I, B);
924 break;
925 case Instruction::Load:
926 E = performSymbolicLoadEvaluation(I, B);
927 break;
928 case Instruction::BitCast: {
929 E = createExpression(I, B);
930 } break;
931
932 case Instruction::Add:
933 case Instruction::FAdd:
934 case Instruction::Sub:
935 case Instruction::FSub:
936 case Instruction::Mul:
937 case Instruction::FMul:
938 case Instruction::UDiv:
939 case Instruction::SDiv:
940 case Instruction::FDiv:
941 case Instruction::URem:
942 case Instruction::SRem:
943 case Instruction::FRem:
944 case Instruction::Shl:
945 case Instruction::LShr:
946 case Instruction::AShr:
947 case Instruction::And:
948 case Instruction::Or:
949 case Instruction::Xor:
950 case Instruction::ICmp:
951 case Instruction::FCmp:
952 case Instruction::Trunc:
953 case Instruction::ZExt:
954 case Instruction::SExt:
955 case Instruction::FPToUI:
956 case Instruction::FPToSI:
957 case Instruction::UIToFP:
958 case Instruction::SIToFP:
959 case Instruction::FPTrunc:
960 case Instruction::FPExt:
961 case Instruction::PtrToInt:
962 case Instruction::IntToPtr:
963 case Instruction::Select:
964 case Instruction::ExtractElement:
965 case Instruction::InsertElement:
966 case Instruction::ShuffleVector:
967 case Instruction::GetElementPtr:
968 E = createExpression(I, B);
969 break;
970 default:
971 return nullptr;
972 }
973 }
974 if (!E)
975 return nullptr;
976 return E;
977}
978
979// There is an edge from 'Src' to 'Dst'. Return true if every path from
980// the entry block to 'Dst' passes via this edge. In particular 'Dst'
981// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000982bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000983
984 // While in theory it is interesting to consider the case in which Dst has
985 // more than one predecessor, because Dst might be part of a loop which is
986 // only reachable from Src, in practice it is pointless since at the time
987 // GVN runs all such loops have preheaders, which means that Dst will have
988 // been changed to have only one predecessor, namely Src.
989 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
990 const BasicBlock *Src = E.getStart();
991 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
992 (void)Src;
993 return Pred != nullptr;
994}
995
996void NewGVN::markUsersTouched(Value *V) {
997 // Now mark the users as touched.
998 for (auto &U : V->uses()) {
999 auto *User = dyn_cast<Instruction>(U.getUser());
1000 assert(User && "Use of value not within an instruction?");
1001 TouchedInstructions.set(InstrDFS[User]);
1002 }
1003}
1004
1005void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1006 for (auto U : MA->users()) {
1007 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
1008 TouchedInstructions.set(InstrDFS[MUD->getMemoryInst()]);
1009 else
1010 TouchedInstructions.set(InstrDFS[MA]);
1011 }
1012}
1013
1014// Perform congruence finding on a given value numbering expression.
1015void NewGVN::performCongruenceFinding(Value *V, const Expression *E) {
1016
1017 ValueToExpression[V] = E;
1018 // This is guaranteed to return something, since it will at least find
1019 // INITIAL.
1020 CongruenceClass *VClass = ValueToClass[V];
1021 assert(VClass && "Should have found a vclass");
1022 // Dead classes should have been eliminated from the mapping.
1023 assert(!VClass->Dead && "Found a dead class");
1024
1025 CongruenceClass *EClass;
1026 // Expressions we can't symbolize are always in their own unique
1027 // congruence class.
1028 if (E == NULL) {
1029 // We may have already made a unique class.
1030 if (VClass->Members.size() != 1 || VClass->RepLeader != V) {
1031 CongruenceClass *NewClass = createCongruenceClass(V, NULL);
1032 // We should always be adding the member in the below code.
1033 EClass = NewClass;
1034 DEBUG(dbgs() << "Created new congruence class for " << *V
1035 << " due to NULL expression\n");
1036 } else {
1037 EClass = VClass;
1038 }
1039 } else if (const auto *VE = dyn_cast<VariableExpression>(E)) {
1040 EClass = ValueToClass[VE->getVariableValue()];
1041 } else {
1042 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1043
1044 // If it's not in the value table, create a new congruence class.
1045 if (lookupResult.second) {
1046 CongruenceClass *NewClass = createCongruenceClass(NULL, E);
1047 auto place = lookupResult.first;
1048 place->second = NewClass;
1049
1050 // Constants and variables should always be made the leader.
1051 if (const auto *CE = dyn_cast<ConstantExpression>(E))
1052 NewClass->RepLeader = CE->getConstantValue();
1053 else if (const auto *VE = dyn_cast<VariableExpression>(E))
1054 NewClass->RepLeader = VE->getVariableValue();
1055 else if (const auto *SE = dyn_cast<StoreExpression>(E))
1056 NewClass->RepLeader = SE->getStoreInst()->getValueOperand();
1057 else
1058 NewClass->RepLeader = V;
1059
1060 EClass = NewClass;
1061 DEBUG(dbgs() << "Created new congruence class for " << *V
1062 << " using expression " << *E << " at " << NewClass->ID
1063 << "\n");
1064 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1065 } else {
1066 EClass = lookupResult.first->second;
1067 assert(EClass && "Somehow don't have an eclass");
1068
1069 assert(!EClass->Dead && "We accidentally looked up a dead class");
1070 }
1071 }
1072 bool WasInChanged = ChangedValues.erase(V);
1073 if (VClass != EClass || WasInChanged) {
1074 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1075 << "\n");
1076
1077 if (VClass != EClass) {
1078 DEBUG(dbgs() << "New congruence class for " << V << " is " << EClass->ID
1079 << "\n");
1080
1081 VClass->Members.erase(V);
1082 EClass->Members.insert(V);
1083 ValueToClass[V] = EClass;
1084 // See if we destroyed the class or need to swap leaders.
1085 if (VClass->Members.empty() && VClass != InitialClass) {
1086 if (VClass->DefiningExpr) {
1087 VClass->Dead = true;
1088 DEBUG(dbgs() << "Erasing expression " << *E << " from table\n");
1089 ExpressionToClass.erase(VClass->DefiningExpr);
1090 }
1091 } else if (VClass->RepLeader == V) {
1092 // FIXME: When the leader changes, the value numbering of
1093 // everything may change, so we need to reprocess.
1094 VClass->RepLeader = *(VClass->Members.begin());
1095 for (auto M : VClass->Members) {
1096 if (auto *I = dyn_cast<Instruction>(M))
1097 TouchedInstructions.set(InstrDFS[I]);
1098 ChangedValues.insert(M);
1099 }
1100 }
1101 }
1102 markUsersTouched(V);
Davide Italiano463c32e2016-12-24 17:17:21 +00001103 if (auto *I = dyn_cast<Instruction>(V))
Davide Italiano7e274e02016-12-22 16:03:48 +00001104 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
1105 markMemoryUsersTouched(MA);
1106 }
1107}
1108
1109// Process the fact that Edge (from, to) is reachable, including marking
1110// any newly reachable blocks and instructions for processing.
1111void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1112 // Check if the Edge was reachable before.
1113 if (ReachableEdges.insert({From, To}).second) {
1114 // If this block wasn't reachable before, all instructions are touched.
1115 if (ReachableBlocks.insert(To).second) {
1116 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1117 const auto &InstRange = BlockInstRange.lookup(To);
1118 TouchedInstructions.set(InstRange.first, InstRange.second);
1119 } else {
1120 DEBUG(dbgs() << "Block " << getBlockName(To)
1121 << " was reachable, but new edge {" << getBlockName(From)
1122 << "," << getBlockName(To) << "} to it found\n");
1123
1124 // We've made an edge reachable to an existing block, which may
1125 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1126 // they are the only thing that depend on new edges. Anything using their
1127 // values will get propagated to if necessary.
1128 auto BI = To->begin();
1129 while (isa<PHINode>(BI)) {
1130 TouchedInstructions.set(InstrDFS[&*BI]);
1131 ++BI;
1132 }
1133 }
1134 }
1135}
1136
1137// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1138// see if we know some constant value for it already.
1139Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1140 auto Result = lookupOperandLeader(Cond, nullptr, B);
1141 if (isa<Constant>(Result))
1142 return Result;
1143 return nullptr;
1144}
1145
1146// Process the outgoing edges of a block for reachability.
1147void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1148 // Evaluate reachability of terminator instruction.
1149 BranchInst *BR;
1150 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1151 Value *Cond = BR->getCondition();
1152 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1153 if (!CondEvaluated) {
1154 if (auto *I = dyn_cast<Instruction>(Cond)) {
1155 const Expression *E = createExpression(I, B);
1156 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1157 CondEvaluated = CE->getConstantValue();
1158 }
1159 } else if (isa<ConstantInt>(Cond)) {
1160 CondEvaluated = Cond;
1161 }
1162 }
1163 ConstantInt *CI;
1164 BasicBlock *TrueSucc = BR->getSuccessor(0);
1165 BasicBlock *FalseSucc = BR->getSuccessor(1);
1166 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1167 if (CI->isOne()) {
1168 DEBUG(dbgs() << "Condition for Terminator " << *TI
1169 << " evaluated to true\n");
1170 updateReachableEdge(B, TrueSucc);
1171 } else if (CI->isZero()) {
1172 DEBUG(dbgs() << "Condition for Terminator " << *TI
1173 << " evaluated to false\n");
1174 updateReachableEdge(B, FalseSucc);
1175 }
1176 } else {
1177 updateReachableEdge(B, TrueSucc);
1178 updateReachableEdge(B, FalseSucc);
1179 }
1180 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1181 // For switches, propagate the case values into the case
1182 // destinations.
1183
1184 // Remember how many outgoing edges there are to every successor.
1185 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1186
Davide Italiano7e274e02016-12-22 16:03:48 +00001187 Value *SwitchCond = SI->getCondition();
1188 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1189 // See if we were able to turn this switch statement into a constant.
1190 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
1191 ConstantInt *CondVal = cast<ConstantInt>(CondEvaluated);
1192 // We should be able to get case value for this.
1193 auto CaseVal = SI->findCaseValue(CondVal);
1194 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1195 // We proved the value is outside of the range of the case.
1196 // We can't do anything other than mark the default dest as reachable,
1197 // and go home.
1198 updateReachableEdge(B, SI->getDefaultDest());
1199 return;
1200 }
1201 // Now get where it goes and mark it reachable.
1202 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1203 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001204 } else {
1205 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1206 BasicBlock *TargetBlock = SI->getSuccessor(i);
1207 ++SwitchEdges[TargetBlock];
1208 updateReachableEdge(B, TargetBlock);
1209 }
1210 }
1211 } else {
1212 // Otherwise this is either unconditional, or a type we have no
1213 // idea about. Just mark successors as reachable.
1214 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1215 BasicBlock *TargetBlock = TI->getSuccessor(i);
1216 updateReachableEdge(B, TargetBlock);
1217 }
1218 }
1219}
1220
1221// The algorithm initially places the values of the routine in the INITIAL congruence
1222// class. The leader of INITIAL is the undetermined value `TOP`.
1223// When the algorithm has finished, values still in INITIAL are unreachable.
1224void NewGVN::initializeCongruenceClasses(Function &F) {
1225 // FIXME now i can't remember why this is 2
1226 NextCongruenceNum = 2;
1227 // Initialize all other instructions to be in INITIAL class.
1228 CongruenceClass::MemberSet InitialValues;
1229 for (auto &B : F)
1230 for (auto &I : B)
1231 InitialValues.insert(&I);
1232
1233 InitialClass = createCongruenceClass(NULL, NULL);
1234 for (auto L : InitialValues)
1235 ValueToClass[L] = InitialClass;
1236 InitialClass->Members.swap(InitialValues);
1237
1238 // Initialize arguments to be in their own unique congruence classes
1239 for (auto &FA : F.args())
1240 createSingletonCongruenceClass(&FA);
1241}
1242
1243void NewGVN::cleanupTables() {
1244 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1245 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1246 << CongruenceClasses[i]->Members.size() << " members\n");
1247 // Make sure we delete the congruence class (probably worth switching to
1248 // a unique_ptr at some point.
1249 delete CongruenceClasses[i];
1250 CongruenceClasses[i] = NULL;
1251 }
1252
1253 ValueToClass.clear();
1254 ArgRecycler.clear(ExpressionAllocator);
1255 ExpressionAllocator.Reset();
1256 CongruenceClasses.clear();
1257 ExpressionToClass.clear();
1258 ValueToExpression.clear();
1259 ReachableBlocks.clear();
1260 ReachableEdges.clear();
1261#ifndef NDEBUG
1262 ProcessedCount.clear();
1263#endif
1264 DFSDomMap.clear();
1265 InstrDFS.clear();
1266 InstructionsToErase.clear();
1267
1268 DFSToInstr.clear();
1269 BlockInstRange.clear();
1270 TouchedInstructions.clear();
1271 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001272 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001273}
1274
1275std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1276 unsigned Start) {
1277 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001278 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1279 InstrDFS[MemPhi] = End++;
1280 DFSToInstr.emplace_back(MemPhi);
1281 }
1282
Davide Italiano7e274e02016-12-22 16:03:48 +00001283 for (auto &I : *B) {
1284 InstrDFS[&I] = End++;
1285 DFSToInstr.emplace_back(&I);
1286 }
1287
1288 // All of the range functions taken half-open ranges (open on the end side).
1289 // So we do not subtract one from count, because at this point it is one
1290 // greater than the last instruction.
1291 return std::make_pair(Start, End);
1292}
1293
1294void NewGVN::updateProcessedCount(Value *V) {
1295#ifndef NDEBUG
1296 if (ProcessedCount.count(V) == 0) {
1297 ProcessedCount.insert({V, 1});
1298 } else {
1299 ProcessedCount[V] += 1;
1300 assert(ProcessedCount[V] < 100 &&
1301 "Seem to have processed the same Value a lot\n");
1302 }
1303#endif
1304}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001305// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1306void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1307 // If all the arguments are the same, the MemoryPhi has the same value as the
1308 // argument.
1309 // Filter out unreachable blocks from our operands.
1310 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1311 return ReachableBlocks.count(MP->getIncomingBlock(U));
1312 });
1313
1314 assert(Filtered.begin() != Filtered.end() &&
1315 "We should not be processing a MemoryPhi in a completely "
1316 "unreachable block");
1317
1318 // Transform the remaining operands into operand leaders.
1319 // FIXME: mapped_iterator should have a range version.
1320 auto LookupFunc = [&](const Use &U) {
1321 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1322 };
1323 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1324 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1325
1326 // and now check if all the elements are equal.
1327 // Sadly, we can't use std::equals since these are random access iterators.
1328 MemoryAccess *AllSameValue = *MappedBegin;
1329 ++MappedBegin;
1330 bool AllEqual = std::all_of(
1331 MappedBegin, MappedEnd,
1332 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1333
1334 if (AllEqual)
1335 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1336 else
1337 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1338
1339 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1340 markMemoryUsersTouched(MP);
1341}
1342
1343// Value number a single instruction, symbolically evaluating, performing
1344// congruence finding, and updating mappings.
1345void NewGVN::valueNumberInstruction(Instruction *I) {
1346 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
1347 if (I->use_empty() && !I->getType()->isVoidTy()) {
1348 DEBUG(dbgs() << "Skipping unused instruction\n");
1349 if (isInstructionTriviallyDead(I, TLI))
1350 markInstructionForDeletion(I);
1351 return;
1352 }
1353 if (!I->isTerminator()) {
1354 const Expression *Symbolized = performSymbolicEvaluation(I, I->getParent());
1355 performCongruenceFinding(I, Symbolized);
1356 } else {
1357 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1358 }
1359}
Davide Italiano7e274e02016-12-22 16:03:48 +00001360
1361// This is the main transformation entry point.
1362bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
1363 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1364 MemorySSA *_MSSA) {
1365 bool Changed = false;
1366 DT = _DT;
1367 AC = _AC;
1368 TLI = _TLI;
1369 AA = _AA;
1370 MSSA = _MSSA;
1371 DL = &F.getParent()->getDataLayout();
1372 MSSAWalker = MSSA->getWalker();
1373
1374 // Count number of instructions for sizing of hash tables, and come
1375 // up with a global dfs numbering for instructions.
1376 unsigned ICount = 0;
1377 SmallPtrSet<BasicBlock *, 16> VisitedBlocks;
1378
1379 // Note: We want RPO traversal of the blocks, which is not quite the same as
1380 // dominator tree order, particularly with regard whether backedges get
1381 // visited first or second, given a block with multiple successors.
1382 // If we visit in the wrong order, we will end up performing N times as many
1383 // iterations.
1384 ReversePostOrderTraversal<Function *> RPOT(&F);
1385 for (auto &B : RPOT) {
1386 VisitedBlocks.insert(B);
1387 const auto &BlockRange = assignDFSNumbers(B, ICount);
1388 BlockInstRange.insert({B, BlockRange});
1389 ICount += BlockRange.second - BlockRange.first;
1390 }
1391
1392 // Handle forward unreachable blocks and figure out which blocks
1393 // have single preds.
1394 for (auto &B : F) {
1395 // Assign numbers to unreachable blocks.
1396 if (!VisitedBlocks.count(&B)) {
1397 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1398 BlockInstRange.insert({&B, BlockRange});
1399 ICount += BlockRange.second - BlockRange.first;
1400 }
1401 }
1402
1403 TouchedInstructions.resize(ICount + 1);
1404 DominatedInstRange.reserve(F.size());
1405 // Ensure we don't end up resizing the expressionToClass map, as
1406 // that can be quite expensive. At most, we have one expression per
1407 // instruction.
1408 ExpressionToClass.reserve(ICount + 1);
1409
1410 // Initialize the touched instructions to include the entry block.
1411 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1412 TouchedInstructions.set(InstRange.first, InstRange.second);
1413 ReachableBlocks.insert(&F.getEntryBlock());
1414
1415 initializeCongruenceClasses(F);
1416
1417 // We start out in the entry block.
1418 BasicBlock *LastBlock = &F.getEntryBlock();
1419 while (TouchedInstructions.any()) {
1420 // Walk through all the instructions in all the blocks in RPO.
1421 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1422 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001423 Value *V = DFSToInstr[InstrNum];
1424 BasicBlock *CurrBlock = nullptr;
1425
1426 if (Instruction *I = dyn_cast<Instruction>(V))
1427 CurrBlock = I->getParent();
1428 else if (MemoryPhi *MP = dyn_cast<MemoryPhi>(V))
1429 CurrBlock = MP->getBlock();
1430 else
1431 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001432
1433 // If we hit a new block, do reachability processing.
1434 if (CurrBlock != LastBlock) {
1435 LastBlock = CurrBlock;
1436 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1437 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1438
1439 // If it's not reachable, erase any touched instructions and move on.
1440 if (!BlockReachable) {
1441 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1442 DEBUG(dbgs() << "Skipping instructions in block "
1443 << getBlockName(CurrBlock)
1444 << " because it is unreachable\n");
1445 continue;
1446 }
1447 updateProcessedCount(CurrBlock);
1448 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001449
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001450 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(V)) {
1451 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1452 valueNumberMemoryPhi(MP);
1453 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
1454 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001455 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001456 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001457 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001458 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001459 // Reset after processing (because we may mark ourselves as touched when
1460 // we propagate equalities).
1461 TouchedInstructions.reset(InstrNum);
1462 }
1463 }
1464
1465 Changed |= eliminateInstructions(F);
1466
1467 // Delete all instructions marked for deletion.
1468 for (Instruction *ToErase : InstructionsToErase) {
1469 if (!ToErase->use_empty())
1470 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1471
1472 ToErase->eraseFromParent();
1473 }
1474
1475 // Delete all unreachable blocks.
1476 for (auto &B : F) {
1477 BasicBlock *BB = &B;
1478 if (!ReachableBlocks.count(BB)) {
1479 DEBUG(dbgs() << "We believe block " << getBlockName(BB)
1480 << " is unreachable\n");
1481 deleteInstructionsInBlock(BB);
1482 Changed = true;
1483 }
1484 }
1485
1486 cleanupTables();
1487 return Changed;
1488}
1489
1490bool NewGVN::runOnFunction(Function &F) {
1491 if (skipFunction(F))
1492 return false;
1493 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1494 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1495 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1496 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1497 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1498}
1499
1500PreservedAnalyses NewGVNPass::run(Function &F,
1501 AnalysisManager<Function> &AM) {
1502 NewGVN Impl;
1503
1504 // Apparently the order in which we get these results matter for
1505 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1506 // the same order here, just in case.
1507 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1508 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1509 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1510 auto &AA = AM.getResult<AAManager>(F);
1511 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1512 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1513 if (!Changed)
1514 return PreservedAnalyses::all();
1515 PreservedAnalyses PA;
1516 PA.preserve<DominatorTreeAnalysis>();
1517 PA.preserve<GlobalsAA>();
1518 return PA;
1519}
1520
1521// Return true if V is a value that will always be available (IE can
1522// be placed anywhere) in the function. We don't do globals here
1523// because they are often worse to put in place.
1524// TODO: Separate cost from availability
1525static bool alwaysAvailable(Value *V) {
1526 return isa<Constant>(V) || isa<Argument>(V);
1527}
1528
1529// Get the basic block from an instruction/value.
1530static BasicBlock *getBlockForValue(Value *V) {
1531 if (auto *I = dyn_cast<Instruction>(V))
1532 return I->getParent();
1533 return nullptr;
1534}
1535
1536struct NewGVN::ValueDFS {
1537 int DFSIn;
1538 int DFSOut;
1539 int LocalNum;
1540 // Only one of these will be set.
1541 Value *Val;
1542 Use *U;
1543 ValueDFS()
1544 : DFSIn(0), DFSOut(0), LocalNum(0), Val(nullptr), U(nullptr) {}
1545
1546 bool operator<(const ValueDFS &Other) const {
1547 // It's not enough that any given field be less than - we have sets
1548 // of fields that need to be evaluated together to give a proper ordering.
1549 // For example, if you have;
1550 // DFS (1, 3)
1551 // Val 0
1552 // DFS (1, 2)
1553 // Val 50
1554 // We want the second to be less than the first, but if we just go field
1555 // by field, we will get to Val 0 < Val 50 and say the first is less than
1556 // the second. We only want it to be less than if the DFS orders are equal.
1557 //
1558 // Each LLVM instruction only produces one value, and thus the lowest-level
1559 // differentiator that really matters for the stack (and what we use as as a
1560 // replacement) is the local dfs number.
1561 // Everything else in the structure is instruction level, and only affects the
1562 // order in which we will replace operands of a given instruction.
1563 //
1564 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1565 // the order of replacement of uses does not matter.
1566 // IE given,
1567 // a = 5
1568 // b = a + a
1569 // When you hit b, you will have two valuedfs with the same dfsin, out, and localnum.
1570 // The .val will be the same as well.
1571 // The .u's will be different.
1572 // You will replace both, and it does not matter what order you replace them in
1573 // (IE whether you replace operand 2, then operand 1, or operand 1, then operand 2).
1574 // Similarly for the case of same dfsin, dfsout, localnum, but different .val's
1575 // a = 5
1576 // b = 6
1577 // c = a + b
1578 // in c, we will a valuedfs for a, and one for b,with everything the same but
1579 // .val and .u.
1580 // It does not matter what order we replace these operands in.
1581 // You will always end up with the same IR, and this is guaranteed.
1582 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1583 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1584 Other.U);
1585 }
1586};
1587
1588void NewGVN::convertDenseToDFSOrdered(CongruenceClass::MemberSet &Dense,
1589 std::vector<ValueDFS> &DFSOrderedSet) {
1590 for (auto D : Dense) {
1591 // First add the value.
1592 BasicBlock *BB = getBlockForValue(D);
1593 // Constants are handled prior to ever calling this function, so
1594 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001595 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001596 ValueDFS VD;
1597
1598 std::pair<int, int> DFSPair = DFSDomMap[BB];
1599 assert(DFSPair.first != -1 && DFSPair.second != -1 && "Invalid DFS Pair");
1600 VD.DFSIn = DFSPair.first;
1601 VD.DFSOut = DFSPair.second;
1602 VD.Val = D;
1603 // If it's an instruction, use the real local dfs number.
1604 if (auto *I = dyn_cast<Instruction>(D))
1605 VD.LocalNum = InstrDFS[I];
1606 else
1607 llvm_unreachable("Should have been an instruction");
1608
1609 DFSOrderedSet.emplace_back(VD);
1610
1611 // Now add the users.
1612 for (auto &U : D->uses()) {
1613 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1614 ValueDFS VD;
1615 // Put the phi node uses in the incoming block.
1616 BasicBlock *IBlock;
1617 if (auto *P = dyn_cast<PHINode>(I)) {
1618 IBlock = P->getIncomingBlock(U);
1619 // Make phi node users appear last in the incoming block
1620 // they are from.
1621 VD.LocalNum = InstrDFS.size() + 1;
1622 } else {
1623 IBlock = I->getParent();
1624 VD.LocalNum = InstrDFS[I];
1625 }
1626 std::pair<int, int> DFSPair = DFSDomMap[IBlock];
1627 VD.DFSIn = DFSPair.first;
1628 VD.DFSOut = DFSPair.second;
1629 VD.U = &U;
1630 DFSOrderedSet.emplace_back(VD);
1631 }
1632 }
1633 }
1634}
1635
1636static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1637 // Patch the replacement so that it is not more restrictive than the value
1638 // being replaced.
1639 auto *Op = dyn_cast<BinaryOperator>(I);
1640 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1641
1642 if (Op && ReplOp)
1643 ReplOp->andIRFlags(Op);
1644
1645 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1646 // FIXME: If both the original and replacement value are part of the
1647 // same control-flow region (meaning that the execution of one
1648 // guarentees the executation of the other), then we can combine the
1649 // noalias scopes here and do better than the general conservative
1650 // answer used in combineMetadata().
1651
1652 // In general, GVN unifies expressions over different control-flow
1653 // regions, and so we need a conservative combination of the noalias
1654 // scopes.
1655 unsigned KnownIDs[] = {
1656 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1657 LLVMContext::MD_noalias, LLVMContext::MD_range,
1658 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1659 LLVMContext::MD_invariant_group};
1660 combineMetadata(ReplInst, I, KnownIDs);
1661 }
1662}
1663
1664static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1665 patchReplacementInstruction(I, Repl);
1666 I->replaceAllUsesWith(Repl);
1667}
1668
1669void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
1670 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1671 ++NumGVNBlocksDeleted;
1672
1673 // Check to see if there are non-terminating instructions to delete.
1674 if (isa<TerminatorInst>(BB->begin()))
1675 return;
1676
1677 // Delete the instructions backwards, as it has a reduced likelihood of having
1678 // to update as many def-use and use-def chains. Start after the terminator.
1679 auto StartPoint = BB->rbegin();
1680 ++StartPoint;
1681 // Note that we explicitly recalculate BB->rend() on each iteration,
1682 // as it may change when we remove the first instruction.
1683 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
1684 Instruction &Inst = *I++;
1685 if (!Inst.use_empty())
1686 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
1687 if (isa<LandingPadInst>(Inst))
1688 continue;
1689
1690 Inst.eraseFromParent();
1691 ++NumGVNInstrDeleted;
1692 }
1693}
1694
1695void NewGVN::markInstructionForDeletion(Instruction *I) {
1696 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
1697 InstructionsToErase.insert(I);
1698}
1699
1700void NewGVN::replaceInstruction(Instruction *I, Value *V) {
1701
1702 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
1703 patchAndReplaceAllUsesWith(I, V);
1704 // We save the actual erasing to avoid invalidating memory
1705 // dependencies until we are done with everything.
1706 markInstructionForDeletion(I);
1707}
1708
1709namespace {
1710
1711// This is a stack that contains both the value and dfs info of where
1712// that value is valid.
1713class ValueDFSStack {
1714public:
1715 Value *back() const { return ValueStack.back(); }
1716 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
1717
1718 void push_back(Value *V, int DFSIn, int DFSOut) {
1719 ValueStack.emplace_back(V);
1720 DFSStack.emplace_back(DFSIn, DFSOut);
1721 }
1722 bool empty() const { return DFSStack.empty(); }
1723 bool isInScope(int DFSIn, int DFSOut) const {
1724 if (empty())
1725 return false;
1726 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
1727 }
1728
1729 void popUntilDFSScope(int DFSIn, int DFSOut) {
1730
1731 // These two should always be in sync at this point.
1732 assert(ValueStack.size() == DFSStack.size() &&
1733 "Mismatch between ValueStack and DFSStack");
1734 while (
1735 !DFSStack.empty() &&
1736 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
1737 DFSStack.pop_back();
1738 ValueStack.pop_back();
1739 }
1740 }
1741
1742private:
1743 SmallVector<Value *, 8> ValueStack;
1744 SmallVector<std::pair<int, int>, 8> DFSStack;
1745};
1746}
1747
1748bool NewGVN::eliminateInstructions(Function &F) {
1749 // This is a non-standard eliminator. The normal way to eliminate is
1750 // to walk the dominator tree in order, keeping track of available
1751 // values, and eliminating them. However, this is mildly
1752 // pointless. It requires doing lookups on every instruction,
1753 // regardless of whether we will ever eliminate it. For
1754 // instructions part of most singleton congruence class, we know we
1755 // will never eliminate it.
1756
1757 // Instead, this eliminator looks at the congruence classes directly, sorts
1758 // them into a DFS ordering of the dominator tree, and then we just
1759 // perform eliminate straight on the sets by walking the congruence
1760 // class member uses in order, and eliminate the ones dominated by the
1761 // last member. This is technically O(N log N) where N = number of
1762 // instructions (since in theory all instructions may be in the same
1763 // congruence class).
1764 // When we find something not dominated, it becomes the new leader
1765 // for elimination purposes
1766
1767 bool AnythingReplaced = false;
1768
1769 // Since we are going to walk the domtree anyway, and we can't guarantee the
1770 // DFS numbers are updated, we compute some ourselves.
1771 DT->updateDFSNumbers();
1772
1773 for (auto &B : F) {
1774 if (!ReachableBlocks.count(&B)) {
1775 for (const auto S : successors(&B)) {
1776 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
1777 PHINode &Phi = cast<PHINode>(*II);
1778 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
1779 << getBlockName(&B)
1780 << " with undef due to it being unreachable\n");
1781 for (auto &Operand : Phi.incoming_values())
1782 if (Phi.getIncomingBlock(Operand) == &B)
1783 Operand.set(UndefValue::get(Phi.getType()));
1784 }
1785 }
1786 }
1787 DomTreeNode *Node = DT->getNode(&B);
1788 if (Node)
1789 DFSDomMap[&B] = {Node->getDFSNumIn(), Node->getDFSNumOut()};
1790 }
1791
1792 for (CongruenceClass *CC : CongruenceClasses) {
1793 // FIXME: We should eventually be able to replace everything still
1794 // in the initial class with undef, as they should be unreachable.
1795 // Right now, initial still contains some things we skip value
1796 // numbering of (UNREACHABLE's, for example).
1797 if (CC == InitialClass || CC->Dead)
1798 continue;
1799 assert(CC->RepLeader && "We should have had a leader");
1800
1801 // If this is a leader that is always available, and it's a
1802 // constant or has no equivalences, just replace everything with
1803 // it. We then update the congruence class with whatever members
1804 // are left.
1805 if (alwaysAvailable(CC->RepLeader)) {
1806 SmallPtrSet<Value *, 4> MembersLeft;
1807 for (auto M : CC->Members) {
1808
1809 Value *Member = M;
1810
1811 // Void things have no uses we can replace.
1812 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
1813 MembersLeft.insert(Member);
1814 continue;
1815 }
1816
1817 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for "
1818 << *Member << "\n");
1819 // Due to equality propagation, these may not always be
1820 // instructions, they may be real values. We don't really
1821 // care about trying to replace the non-instructions.
1822 if (auto *I = dyn_cast<Instruction>(Member)) {
1823 assert(CC->RepLeader != I &&
1824 "About to accidentally remove our leader");
1825 replaceInstruction(I, CC->RepLeader);
1826 AnythingReplaced = true;
1827
1828 continue;
1829 } else {
1830 MembersLeft.insert(I);
1831 }
1832 }
1833 CC->Members.swap(MembersLeft);
1834
1835 } else {
1836 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
1837 // If this is a singleton, we can skip it.
1838 if (CC->Members.size() != 1) {
1839
1840 // This is a stack because equality replacement/etc may place
1841 // constants in the middle of the member list, and we want to use
1842 // those constant values in preference to the current leader, over
1843 // the scope of those constants.
1844 ValueDFSStack EliminationStack;
1845
1846 // Convert the members to DFS ordered sets and then merge them.
1847 std::vector<ValueDFS> DFSOrderedSet;
1848 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
1849
1850 // Sort the whole thing.
1851 sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
1852
1853 for (auto &C : DFSOrderedSet) {
1854 int MemberDFSIn = C.DFSIn;
1855 int MemberDFSOut = C.DFSOut;
1856 Value *Member = C.Val;
1857 Use *MemberUse = C.U;
1858
1859 // We ignore void things because we can't get a value from them.
1860 if (Member && Member->getType()->isVoidTy())
1861 continue;
1862
1863 if (EliminationStack.empty()) {
1864 DEBUG(dbgs() << "Elimination Stack is empty\n");
1865 } else {
1866 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
1867 << EliminationStack.dfs_back().first << ","
1868 << EliminationStack.dfs_back().second << ")\n");
1869 }
1870 if (Member && isa<Constant>(Member))
1871 assert(isa<Constant>(CC->RepLeader));
1872
1873 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
1874 << MemberDFSOut << ")\n");
1875 // First, we see if we are out of scope or empty. If so,
1876 // and there equivalences, we try to replace the top of
1877 // stack with equivalences (if it's on the stack, it must
1878 // not have been eliminated yet).
1879 // Then we synchronize to our current scope, by
1880 // popping until we are back within a DFS scope that
1881 // dominates the current member.
1882 // Then, what happens depends on a few factors
1883 // If the stack is now empty, we need to push
1884 // If we have a constant or a local equivalence we want to
1885 // start using, we also push.
1886 // Otherwise, we walk along, processing members who are
1887 // dominated by this scope, and eliminate them.
1888 bool ShouldPush =
1889 Member && (EliminationStack.empty() || isa<Constant>(Member));
1890 bool OutOfScope =
1891 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
1892
1893 if (OutOfScope || ShouldPush) {
1894 // Sync to our current scope.
1895 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
1896 ShouldPush |= Member && EliminationStack.empty();
1897 if (ShouldPush) {
1898 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
1899 }
1900 }
1901
1902 // If we get to this point, and the stack is empty we must have a use
1903 // with nothing we can use to eliminate it, just skip it.
1904 if (EliminationStack.empty())
1905 continue;
1906
1907 // Skip the Value's, we only want to eliminate on their uses.
1908 if (Member)
1909 continue;
1910 Value *Result = EliminationStack.back();
1911
1912 // Don't replace our existing users with ourselves.
1913 if (MemberUse->get() == Result)
1914 continue;
1915
1916 DEBUG(dbgs() << "Found replacement " << *Result << " for "
1917 << *MemberUse->get() << " in " << *(MemberUse->getUser())
1918 << "\n");
1919
1920 // If we replaced something in an instruction, handle the patching of
1921 // metadata.
1922 if (auto *ReplacedInst =
1923 dyn_cast<Instruction>(MemberUse->get()))
1924 patchReplacementInstruction(ReplacedInst, Result);
1925
1926 assert(isa<Instruction>(MemberUse->getUser()));
1927 MemberUse->set(Result);
1928 AnythingReplaced = true;
1929 }
1930 }
1931 }
1932
1933 // Cleanup the congruence class.
1934 SmallPtrSet<Value *, 4> MembersLeft;
1935 for (auto MI = CC->Members.begin(), ME = CC->Members.end(); MI != ME;) {
1936 auto CurrIter = MI;
1937 ++MI;
1938 Value *Member = *CurrIter;
1939 if (Member->getType()->isVoidTy()) {
1940 MembersLeft.insert(Member);
1941 continue;
1942 }
1943
1944 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
1945 if (isInstructionTriviallyDead(MemberInst)) {
1946 // TODO: Don't mark loads of undefs.
1947 markInstructionForDeletion(MemberInst);
1948 continue;
1949 }
1950 }
1951 MembersLeft.insert(Member);
1952 }
1953 CC->Members.swap(MembersLeft);
1954 }
1955
1956 return AnythingReplaced;
1957}
1958