Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1 | //===---- NewGVN.cpp - Global Value Numbering Pass --------------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | /// \file |
| 10 | /// This file implements the new LLVM's Global Value Numbering pass. |
| 11 | /// GVN partitions values computed by a function into congruence classes. |
| 12 | /// Values ending up in the same congruence class are guaranteed to be the same |
| 13 | /// for every execution of the program. In that respect, congruency is a |
| 14 | /// compile-time approximation of equivalence of values at runtime. |
| 15 | /// The algorithm implemented here uses a sparse formulation and it's based |
| 16 | /// on the ideas described in the paper: |
| 17 | /// "A Sparse Algorithm for Predicated Global Value Numbering" from |
| 18 | /// Karthik Gargi. |
| 19 | /// |
Daniel Berlin | db3c7be | 2017-01-26 21:39:49 +0000 | [diff] [blame] | 20 | /// A brief overview of the algorithm: The algorithm is essentially the same as |
| 21 | /// the standard RPO value numbering algorithm (a good reference is the paper |
| 22 | /// "SCC based value numbering" by L. Taylor Simpson) with one major difference: |
| 23 | /// The RPO algorithm proceeds, on every iteration, to process every reachable |
| 24 | /// block and every instruction in that block. This is because the standard RPO |
| 25 | /// algorithm does not track what things have the same value number, it only |
| 26 | /// tracks what the value number of a given operation is (the mapping is |
| 27 | /// operation -> value number). Thus, when a value number of an operation |
| 28 | /// changes, it must reprocess everything to ensure all uses of a value number |
| 29 | /// get updated properly. In constrast, the sparse algorithm we use *also* |
| 30 | /// tracks what operations have a given value number (IE it also tracks the |
| 31 | /// reverse mapping from value number -> operations with that value number), so |
| 32 | /// that it only needs to reprocess the instructions that are affected when |
| 33 | /// something's value number changes. The rest of the algorithm is devoted to |
| 34 | /// performing symbolic evaluation, forward propagation, and simplification of |
| 35 | /// operations based on the value numbers deduced so far. |
| 36 | /// |
| 37 | /// We also do not perform elimination by using any published algorithm. All |
| 38 | /// published algorithms are O(Instructions). Instead, we use a technique that |
| 39 | /// is O(number of operations with the same value number), enabling us to skip |
| 40 | /// trying to eliminate things that have unique value numbers. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 41 | //===----------------------------------------------------------------------===// |
| 42 | |
| 43 | #include "llvm/Transforms/Scalar/NewGVN.h" |
| 44 | #include "llvm/ADT/BitVector.h" |
| 45 | #include "llvm/ADT/DenseMap.h" |
| 46 | #include "llvm/ADT/DenseSet.h" |
| 47 | #include "llvm/ADT/DepthFirstIterator.h" |
| 48 | #include "llvm/ADT/Hashing.h" |
| 49 | #include "llvm/ADT/MapVector.h" |
| 50 | #include "llvm/ADT/PostOrderIterator.h" |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 51 | #include "llvm/ADT/STLExtras.h" |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 52 | #include "llvm/ADT/SmallPtrSet.h" |
| 53 | #include "llvm/ADT/SmallSet.h" |
| 54 | #include "llvm/ADT/SparseBitVector.h" |
| 55 | #include "llvm/ADT/Statistic.h" |
| 56 | #include "llvm/ADT/TinyPtrVector.h" |
| 57 | #include "llvm/Analysis/AliasAnalysis.h" |
| 58 | #include "llvm/Analysis/AssumptionCache.h" |
| 59 | #include "llvm/Analysis/CFG.h" |
| 60 | #include "llvm/Analysis/CFGPrinter.h" |
| 61 | #include "llvm/Analysis/ConstantFolding.h" |
| 62 | #include "llvm/Analysis/GlobalsModRef.h" |
| 63 | #include "llvm/Analysis/InstructionSimplify.h" |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 64 | #include "llvm/Analysis/MemoryBuiltins.h" |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 65 | #include "llvm/Analysis/MemoryLocation.h" |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 66 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 67 | #include "llvm/IR/DataLayout.h" |
| 68 | #include "llvm/IR/Dominators.h" |
| 69 | #include "llvm/IR/GlobalVariable.h" |
| 70 | #include "llvm/IR/IRBuilder.h" |
| 71 | #include "llvm/IR/IntrinsicInst.h" |
| 72 | #include "llvm/IR/LLVMContext.h" |
| 73 | #include "llvm/IR/Metadata.h" |
| 74 | #include "llvm/IR/PatternMatch.h" |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 75 | #include "llvm/IR/Type.h" |
| 76 | #include "llvm/Support/Allocator.h" |
| 77 | #include "llvm/Support/CommandLine.h" |
| 78 | #include "llvm/Support/Debug.h" |
Daniel Berlin | 283a608 | 2017-03-01 19:59:26 +0000 | [diff] [blame] | 79 | #include "llvm/Support/DebugCounter.h" |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 80 | #include "llvm/Transforms/Scalar.h" |
| 81 | #include "llvm/Transforms/Scalar/GVNExpression.h" |
| 82 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 83 | #include "llvm/Transforms/Utils/Local.h" |
| 84 | #include "llvm/Transforms/Utils/MemorySSA.h" |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 85 | #include "llvm/Transforms/Utils/PredicateInfo.h" |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 86 | #include <unordered_map> |
| 87 | #include <utility> |
| 88 | #include <vector> |
| 89 | using namespace llvm; |
| 90 | using namespace PatternMatch; |
| 91 | using namespace llvm::GVNExpression; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 92 | #define DEBUG_TYPE "newgvn" |
| 93 | |
| 94 | STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted"); |
| 95 | STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted"); |
| 96 | STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified"); |
| 97 | STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same"); |
Daniel Berlin | 0444343 | 2017-01-07 03:23:47 +0000 | [diff] [blame] | 98 | STATISTIC(NumGVNMaxIterations, |
| 99 | "Maximum Number of iterations it took to converge GVN"); |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 100 | STATISTIC(NumGVNLeaderChanges, "Number of leader changes"); |
| 101 | STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes"); |
| 102 | STATISTIC(NumGVNAvoidedSortedLeaderChanges, |
| 103 | "Number of avoided sorted leader changes"); |
Daniel Berlin | 89fea6f | 2017-01-20 06:38:41 +0000 | [diff] [blame] | 104 | STATISTIC(NumGVNNotMostDominatingLeader, |
| 105 | "Number of times a member dominated it's new classes' leader"); |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 106 | STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated"); |
Daniel Berlin | 283a608 | 2017-03-01 19:59:26 +0000 | [diff] [blame] | 107 | DEBUG_COUNTER(VNCounter, "newgvn-vn", |
| 108 | "Controls which instructions are value numbered") |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 109 | //===----------------------------------------------------------------------===// |
| 110 | // GVN Pass |
| 111 | //===----------------------------------------------------------------------===// |
| 112 | |
| 113 | // Anchor methods. |
| 114 | namespace llvm { |
| 115 | namespace GVNExpression { |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 116 | Expression::~Expression() = default; |
| 117 | BasicExpression::~BasicExpression() = default; |
| 118 | CallExpression::~CallExpression() = default; |
| 119 | LoadExpression::~LoadExpression() = default; |
| 120 | StoreExpression::~StoreExpression() = default; |
| 121 | AggregateValueExpression::~AggregateValueExpression() = default; |
| 122 | PHIExpression::~PHIExpression() = default; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 123 | } |
| 124 | } |
| 125 | |
| 126 | // Congruence classes represent the set of expressions/instructions |
| 127 | // that are all the same *during some scope in the function*. |
| 128 | // That is, because of the way we perform equality propagation, and |
| 129 | // because of memory value numbering, it is not correct to assume |
| 130 | // you can willy-nilly replace any member with any other at any |
| 131 | // point in the function. |
| 132 | // |
| 133 | // For any Value in the Member set, it is valid to replace any dominated member |
| 134 | // with that Value. |
| 135 | // |
| 136 | // Every congruence class has a leader, and the leader is used to |
| 137 | // symbolize instructions in a canonical way (IE every operand of an |
| 138 | // instruction that is a member of the same congruence class will |
| 139 | // always be replaced with leader during symbolization). |
| 140 | // To simplify symbolization, we keep the leader as a constant if class can be |
| 141 | // proved to be a constant value. |
| 142 | // Otherwise, the leader is a randomly chosen member of the value set, it does |
| 143 | // not matter which one is chosen. |
| 144 | // Each congruence class also has a defining expression, |
| 145 | // though the expression may be null. If it exists, it can be used for forward |
| 146 | // propagation and reassociation of values. |
| 147 | // |
| 148 | struct CongruenceClass { |
Piotr Padlewski | e4047b8 | 2016-12-28 19:29:26 +0000 | [diff] [blame] | 149 | using MemberSet = SmallPtrSet<Value *, 4>; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 150 | unsigned ID; |
| 151 | // Representative leader. |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 152 | Value *RepLeader = nullptr; |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 153 | // If this is represented by a store, the value. |
| 154 | Value *RepStoredValue = nullptr; |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 155 | // If this class contains MemoryDefs, what is the represented memory state. |
| 156 | MemoryAccess *RepMemoryAccess = nullptr; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 157 | // Defining Expression. |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 158 | const Expression *DefiningExpr = nullptr; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 159 | // Actual members of this class. |
| 160 | MemberSet Members; |
| 161 | |
| 162 | // True if this class has no members left. This is mainly used for assertion |
| 163 | // purposes, and for skipping empty classes. |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 164 | bool Dead = false; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 165 | |
Daniel Berlin | f6eba4b | 2017-01-11 20:22:36 +0000 | [diff] [blame] | 166 | // Number of stores in this congruence class. |
| 167 | // This is used so we can detect store equivalence changes properly. |
Davide Italiano | eac05f6 | 2017-01-11 23:41:24 +0000 | [diff] [blame] | 168 | int StoreCount = 0; |
Daniel Berlin | f6eba4b | 2017-01-11 20:22:36 +0000 | [diff] [blame] | 169 | |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 170 | // The most dominating leader after our current leader, because the member set |
| 171 | // is not sorted and is expensive to keep sorted all the time. |
| 172 | std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U}; |
| 173 | |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 174 | explicit CongruenceClass(unsigned ID) : ID(ID) {} |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 175 | CongruenceClass(unsigned ID, Value *Leader, const Expression *E) |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 176 | : ID(ID), RepLeader(Leader), DefiningExpr(E) {} |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 177 | }; |
| 178 | |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 179 | // Return true if two congruence classes are equivalent to each other. This |
| 180 | // means |
| 181 | // that every field but the ID number and the dead field are equivalent. |
| 182 | bool areClassesEquivalent(const CongruenceClass *A, const CongruenceClass *B) { |
| 183 | if (A == B) |
| 184 | return true; |
| 185 | if ((A && !B) || (B && !A)) |
| 186 | return false; |
| 187 | |
| 188 | if (std::tie(A->StoreCount, A->RepLeader, A->RepStoredValue, |
| 189 | A->RepMemoryAccess) != std::tie(B->StoreCount, B->RepLeader, |
| 190 | B->RepStoredValue, |
| 191 | B->RepMemoryAccess)) |
| 192 | return false; |
| 193 | if (A->DefiningExpr != B->DefiningExpr) |
| 194 | if (!A->DefiningExpr || !B->DefiningExpr || |
| 195 | *A->DefiningExpr != *B->DefiningExpr) |
| 196 | return false; |
| 197 | // We need some ordered set |
| 198 | std::set<Value *> AMembers(A->Members.begin(), A->Members.end()); |
| 199 | std::set<Value *> BMembers(B->Members.begin(), B->Members.end()); |
| 200 | return AMembers == BMembers; |
| 201 | } |
| 202 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 203 | namespace llvm { |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 204 | template <> struct DenseMapInfo<const Expression *> { |
| 205 | static const Expression *getEmptyKey() { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 206 | auto Val = static_cast<uintptr_t>(-1); |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 207 | Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable; |
| 208 | return reinterpret_cast<const Expression *>(Val); |
| 209 | } |
| 210 | static const Expression *getTombstoneKey() { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 211 | auto Val = static_cast<uintptr_t>(~1U); |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 212 | Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable; |
| 213 | return reinterpret_cast<const Expression *>(Val); |
| 214 | } |
| 215 | static unsigned getHashValue(const Expression *V) { |
| 216 | return static_cast<unsigned>(V->getHashValue()); |
| 217 | } |
| 218 | static bool isEqual(const Expression *LHS, const Expression *RHS) { |
| 219 | if (LHS == RHS) |
| 220 | return true; |
| 221 | if (LHS == getTombstoneKey() || RHS == getTombstoneKey() || |
| 222 | LHS == getEmptyKey() || RHS == getEmptyKey()) |
| 223 | return false; |
| 224 | return *LHS == *RHS; |
| 225 | } |
| 226 | }; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 227 | } // end namespace llvm |
| 228 | |
Benjamin Kramer | efcf06f | 2017-02-11 11:06:55 +0000 | [diff] [blame] | 229 | namespace { |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 230 | class NewGVN { |
| 231 | Function &F; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 232 | DominatorTree *DT; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 233 | AssumptionCache *AC; |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 234 | const TargetLibraryInfo *TLI; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 235 | AliasAnalysis *AA; |
| 236 | MemorySSA *MSSA; |
| 237 | MemorySSAWalker *MSSAWalker; |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 238 | const DataLayout &DL; |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 239 | std::unique_ptr<PredicateInfo> PredInfo; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 240 | BumpPtrAllocator ExpressionAllocator; |
| 241 | ArrayRecycler<Value *> ArgRecycler; |
| 242 | |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 243 | // Number of function arguments, used by ranking |
| 244 | unsigned int NumFuncArgs; |
| 245 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 246 | // Congruence class info. |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 247 | |
| 248 | // This class is called INITIAL in the paper. It is the class everything |
| 249 | // startsout in, and represents any value. Being an optimistic analysis, |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 250 | // anything in the TOP class has the value TOP, which is indeterminate and |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 251 | // equivalent to everything. |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 252 | CongruenceClass *TOPClass; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 253 | std::vector<CongruenceClass *> CongruenceClasses; |
| 254 | unsigned NextCongruenceNum; |
| 255 | |
| 256 | // Value Mappings. |
| 257 | DenseMap<Value *, CongruenceClass *> ValueToClass; |
| 258 | DenseMap<Value *, const Expression *> ValueToExpression; |
| 259 | |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 260 | // Mapping from predicate info we used to the instructions we used it with. |
| 261 | // In order to correctly ensure propagation, we must keep track of what |
| 262 | // comparisons we used, so that when the values of the comparisons change, we |
| 263 | // propagate the information to the places we used the comparison. |
| 264 | DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers; |
| 265 | |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 266 | // A table storing which memorydefs/phis represent a memory state provably |
| 267 | // equivalent to another memory state. |
| 268 | // We could use the congruence class machinery, but the MemoryAccess's are |
| 269 | // abstract memory states, so they can only ever be equivalent to each other, |
| 270 | // and not to constants, etc. |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 271 | DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass; |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 272 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 273 | // Expression to class mapping. |
Piotr Padlewski | e4047b8 | 2016-12-28 19:29:26 +0000 | [diff] [blame] | 274 | using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 275 | ExpressionClassMap ExpressionToClass; |
| 276 | |
| 277 | // Which values have changed as a result of leader changes. |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 278 | SmallPtrSet<Value *, 8> LeaderChanges; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 279 | |
| 280 | // Reachability info. |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 281 | using BlockEdge = BasicBlockEdge; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 282 | DenseSet<BlockEdge> ReachableEdges; |
| 283 | SmallPtrSet<const BasicBlock *, 8> ReachableBlocks; |
| 284 | |
| 285 | // This is a bitvector because, on larger functions, we may have |
| 286 | // thousands of touched instructions at once (entire blocks, |
| 287 | // instructions with hundreds of uses, etc). Even with optimization |
| 288 | // for when we mark whole blocks as touched, when this was a |
| 289 | // SmallPtrSet or DenseSet, for some functions, we spent >20% of all |
| 290 | // the time in GVN just managing this list. The bitvector, on the |
| 291 | // other hand, efficiently supports test/set/clear of both |
| 292 | // individual and ranges, as well as "find next element" This |
| 293 | // enables us to use it as a worklist with essentially 0 cost. |
| 294 | BitVector TouchedInstructions; |
| 295 | |
| 296 | DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 297 | |
| 298 | #ifndef NDEBUG |
| 299 | // Debugging for how many times each block and instruction got processed. |
| 300 | DenseMap<const Value *, unsigned> ProcessedCount; |
| 301 | #endif |
| 302 | |
| 303 | // DFS info. |
Davide Italiano | 71f2d9c | 2017-01-20 23:29:28 +0000 | [diff] [blame] | 304 | // This contains a mapping from Instructions to DFS numbers. |
| 305 | // The numbering starts at 1. An instruction with DFS number zero |
| 306 | // means that the instruction is dead. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 307 | DenseMap<const Value *, unsigned> InstrDFS; |
Davide Italiano | 71f2d9c | 2017-01-20 23:29:28 +0000 | [diff] [blame] | 308 | |
| 309 | // This contains the mapping DFS numbers to instructions. |
Daniel Berlin | 1f31fe52 | 2016-12-27 09:20:36 +0000 | [diff] [blame] | 310 | SmallVector<Value *, 32> DFSToInstr; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 311 | |
| 312 | // Deletion info. |
| 313 | SmallPtrSet<Instruction *, 8> InstructionsToErase; |
| 314 | |
| 315 | public: |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 316 | NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC, |
| 317 | TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA, |
| 318 | const DataLayout &DL) |
| 319 | : F(F), DT(DT), AC(AC), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL), |
| 320 | PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)) {} |
| 321 | bool runGVN(); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 322 | |
| 323 | private: |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 324 | // Expression handling. |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 325 | const Expression *createExpression(Instruction *); |
| 326 | const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 327 | PHIExpression *createPHIExpression(Instruction *); |
| 328 | const VariableExpression *createVariableExpression(Value *); |
| 329 | const ConstantExpression *createConstantExpression(Constant *); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 330 | const Expression *createVariableOrConstant(Value *V); |
Daniel Berlin | 02c6b17 | 2017-01-02 18:00:53 +0000 | [diff] [blame] | 331 | const UnknownExpression *createUnknownExpression(Instruction *); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 332 | const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 333 | LoadExpression *createLoadExpression(Type *, Value *, LoadInst *, |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 334 | MemoryAccess *); |
| 335 | const CallExpression *createCallExpression(CallInst *, MemoryAccess *); |
| 336 | const AggregateValueExpression *createAggregateValueExpression(Instruction *); |
| 337 | bool setBasicExpressionInfo(Instruction *, BasicExpression *); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 338 | |
| 339 | // Congruence class handling. |
| 340 | CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 341 | auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E); |
Piotr Padlewski | 6c37d29 | 2016-12-28 23:24:02 +0000 | [diff] [blame] | 342 | CongruenceClasses.emplace_back(result); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 343 | return result; |
| 344 | } |
| 345 | |
| 346 | CongruenceClass *createSingletonCongruenceClass(Value *Member) { |
Davide Italiano | 0e71480 | 2016-12-28 14:00:11 +0000 | [diff] [blame] | 347 | CongruenceClass *CClass = createCongruenceClass(Member, nullptr); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 348 | CClass->Members.insert(Member); |
| 349 | ValueToClass[Member] = CClass; |
| 350 | return CClass; |
| 351 | } |
| 352 | void initializeCongruenceClasses(Function &F); |
| 353 | |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 354 | // Value number an Instruction or MemoryPhi. |
| 355 | void valueNumberMemoryPhi(MemoryPhi *); |
| 356 | void valueNumberInstruction(Instruction *); |
| 357 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 358 | // Symbolic evaluation. |
| 359 | const Expression *checkSimplificationResults(Expression *, Instruction *, |
| 360 | Value *); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 361 | const Expression *performSymbolicEvaluation(Value *); |
| 362 | const Expression *performSymbolicLoadEvaluation(Instruction *); |
| 363 | const Expression *performSymbolicStoreEvaluation(Instruction *); |
| 364 | const Expression *performSymbolicCallEvaluation(Instruction *); |
| 365 | const Expression *performSymbolicPHIEvaluation(Instruction *); |
| 366 | const Expression *performSymbolicAggrValueEvaluation(Instruction *); |
| 367 | const Expression *performSymbolicCmpEvaluation(Instruction *); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 368 | const Expression *performSymbolicPredicateInfoEvaluation(Instruction *); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 369 | |
| 370 | // Congruence finding. |
Daniel Berlin | 9d0796e | 2017-03-24 05:30:34 +0000 | [diff] [blame] | 371 | bool someEquivalentDominates(const Instruction *, const Instruction *) const; |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 372 | Value *lookupOperandLeader(Value *) const; |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 373 | void performCongruenceFinding(Instruction *, const Expression *); |
| 374 | void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *, |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 375 | CongruenceClass *); |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 376 | bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To); |
| 377 | MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const; |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 378 | bool isMemoryAccessTop(const MemoryAccess *) const; |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 379 | // Ranking |
| 380 | unsigned int getRank(const Value *) const; |
| 381 | bool shouldSwapOperands(const Value *, const Value *) const; |
| 382 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 383 | // Reachability handling. |
| 384 | void updateReachableEdge(BasicBlock *, BasicBlock *); |
| 385 | void processOutgoingEdges(TerminatorInst *, BasicBlock *); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 386 | Value *findConditionEquivalence(Value *) const; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 387 | |
| 388 | // Elimination. |
| 389 | struct ValueDFS; |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 390 | void convertClassToDFSOrdered(const CongruenceClass::MemberSet &, |
| 391 | SmallVectorImpl<ValueDFS> &, |
| 392 | DenseMap<const Value *, unsigned int> &, |
| 393 | SmallPtrSetImpl<Instruction *> &); |
| 394 | void convertClassToLoadsAndStores(const CongruenceClass::MemberSet &, |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 395 | SmallVectorImpl<ValueDFS> &); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 396 | |
| 397 | bool eliminateInstructions(Function &); |
| 398 | void replaceInstruction(Instruction *, Value *); |
| 399 | void markInstructionForDeletion(Instruction *); |
| 400 | void deleteInstructionsInBlock(BasicBlock *); |
| 401 | |
| 402 | // New instruction creation. |
| 403 | void handleNewInstruction(Instruction *){}; |
Daniel Berlin | 32f8d56 | 2017-01-07 16:55:14 +0000 | [diff] [blame] | 404 | |
| 405 | // Various instruction touch utilities |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 406 | void markUsersTouched(Value *); |
| 407 | void markMemoryUsersTouched(MemoryAccess *); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 408 | void markPredicateUsersTouched(Instruction *); |
Daniel Berlin | 32f8d56 | 2017-01-07 16:55:14 +0000 | [diff] [blame] | 409 | void markLeaderChangeTouched(CongruenceClass *CC); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 410 | void addPredicateUsers(const PredicateBase *, Instruction *); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 411 | |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 412 | // Main loop of value numbering |
| 413 | void iterateTouchedInstructions(); |
| 414 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 415 | // Utilities. |
| 416 | void cleanupTables(); |
| 417 | std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned); |
| 418 | void updateProcessedCount(Value *V); |
Daniel Berlin | f6eba4b | 2017-01-11 20:22:36 +0000 | [diff] [blame] | 419 | void verifyMemoryCongruency() const; |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 420 | void verifyIterationSettled(Function &F); |
Daniel Berlin | f6eba4b | 2017-01-11 20:22:36 +0000 | [diff] [blame] | 421 | bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const; |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 422 | BasicBlock *getBlockForValue(Value *V) const; |
Daniel Berlin | 0e90011 | 2017-03-24 06:33:48 +0000 | [diff] [blame] | 423 | void deleteExpression(const Expression *E); |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 424 | // Debug counter info. When verifying, we have to reset the value numbering |
| 425 | // debug counter to the same state it started in to get the same results. |
| 426 | std::pair<int, int> StartingVNCounter; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 427 | }; |
Benjamin Kramer | efcf06f | 2017-02-11 11:06:55 +0000 | [diff] [blame] | 428 | } // end anonymous namespace |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 429 | |
Davide Italiano | b111409 | 2016-12-28 13:37:17 +0000 | [diff] [blame] | 430 | template <typename T> |
| 431 | static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) { |
| 432 | if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) || |
Daniel Berlin | 7ad1ea0 | 2016-12-29 00:49:32 +0000 | [diff] [blame] | 433 | !LHS.BasicExpression::equals(RHS)) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 434 | return false; |
Daniel Berlin | 7ad1ea0 | 2016-12-29 00:49:32 +0000 | [diff] [blame] | 435 | } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) { |
Davide Italiano | b111409 | 2016-12-28 13:37:17 +0000 | [diff] [blame] | 436 | if (LHS.getDefiningAccess() != L->getDefiningAccess()) |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 437 | return false; |
Daniel Berlin | 7ad1ea0 | 2016-12-29 00:49:32 +0000 | [diff] [blame] | 438 | } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) { |
Davide Italiano | b111409 | 2016-12-28 13:37:17 +0000 | [diff] [blame] | 439 | if (LHS.getDefiningAccess() != S->getDefiningAccess()) |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 440 | return false; |
Daniel Berlin | 7ad1ea0 | 2016-12-29 00:49:32 +0000 | [diff] [blame] | 441 | } |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 442 | return true; |
| 443 | } |
| 444 | |
Davide Italiano | b111409 | 2016-12-28 13:37:17 +0000 | [diff] [blame] | 445 | bool LoadExpression::equals(const Expression &Other) const { |
| 446 | return equalsLoadStoreHelper(*this, Other); |
| 447 | } |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 448 | |
Davide Italiano | b111409 | 2016-12-28 13:37:17 +0000 | [diff] [blame] | 449 | bool StoreExpression::equals(const Expression &Other) const { |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 450 | bool Result = equalsLoadStoreHelper(*this, Other); |
| 451 | // Make sure that store vs store includes the value operand. |
| 452 | if (Result) |
| 453 | if (const auto *S = dyn_cast<StoreExpression>(&Other)) |
| 454 | if (getStoredValue() != S->getStoredValue()) |
| 455 | return false; |
| 456 | return Result; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 457 | } |
| 458 | |
| 459 | #ifndef NDEBUG |
| 460 | static std::string getBlockName(const BasicBlock *B) { |
Davide Italiano | 0e71480 | 2016-12-28 14:00:11 +0000 | [diff] [blame] | 461 | return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 462 | } |
| 463 | #endif |
| 464 | |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 465 | // Get the basic block from an instruction/memory value. |
| 466 | BasicBlock *NewGVN::getBlockForValue(Value *V) const { |
| 467 | if (auto *I = dyn_cast<Instruction>(V)) |
| 468 | return I->getParent(); |
| 469 | else if (auto *MP = dyn_cast<MemoryPhi>(V)) |
| 470 | return MP->getBlock(); |
| 471 | llvm_unreachable("Should have been able to figure out a block for our value"); |
| 472 | return nullptr; |
| 473 | } |
| 474 | |
Daniel Berlin | 0e90011 | 2017-03-24 06:33:48 +0000 | [diff] [blame] | 475 | // Delete a definitely dead expression, so it can be reused by the expression |
| 476 | // allocator. Some of these are not in creation functions, so we have to accept |
| 477 | // const versions. |
| 478 | void NewGVN::deleteExpression(const Expression *E) { |
| 479 | assert(isa<BasicExpression>(E)); |
| 480 | auto *BE = cast<BasicExpression>(E); |
| 481 | const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler); |
| 482 | ExpressionAllocator.Deallocate(E); |
| 483 | } |
| 484 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 485 | PHIExpression *NewGVN::createPHIExpression(Instruction *I) { |
Daniel Berlin | d92e7f9 | 2017-01-07 00:01:42 +0000 | [diff] [blame] | 486 | BasicBlock *PHIBlock = I->getParent(); |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 487 | auto *PN = cast<PHINode>(I); |
Daniel Berlin | d92e7f9 | 2017-01-07 00:01:42 +0000 | [diff] [blame] | 488 | auto *E = |
| 489 | new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 490 | |
| 491 | E->allocateOperands(ArgRecycler, ExpressionAllocator); |
| 492 | E->setType(I->getType()); |
| 493 | E->setOpcode(I->getOpcode()); |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 494 | |
Davide Italiano | b3886dd | 2017-01-25 23:37:49 +0000 | [diff] [blame] | 495 | // Filter out unreachable phi operands. |
| 496 | auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) { |
Daniel Berlin | 41b3916 | 2017-03-18 15:41:36 +0000 | [diff] [blame] | 497 | return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock}); |
Davide Italiano | b3886dd | 2017-01-25 23:37:49 +0000 | [diff] [blame] | 498 | }); |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 499 | |
| 500 | std::transform(Filtered.begin(), Filtered.end(), op_inserter(E), |
| 501 | [&](const Use &U) -> Value * { |
Daniel Berlin | d92e7f9 | 2017-01-07 00:01:42 +0000 | [diff] [blame] | 502 | // Don't try to transform self-defined phis. |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 503 | if (U == PN) |
| 504 | return PN; |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 505 | return lookupOperandLeader(U); |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 506 | }); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 507 | return E; |
| 508 | } |
| 509 | |
| 510 | // Set basic expression info (Arguments, type, opcode) for Expression |
| 511 | // E from Instruction I in block B. |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 512 | bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 513 | bool AllConstant = true; |
| 514 | if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) |
| 515 | E->setType(GEP->getSourceElementType()); |
| 516 | else |
| 517 | E->setType(I->getType()); |
| 518 | E->setOpcode(I->getOpcode()); |
| 519 | E->allocateOperands(ArgRecycler, ExpressionAllocator); |
| 520 | |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 521 | // Transform the operand array into an operand leader array, and keep track of |
| 522 | // whether all members are constant. |
| 523 | std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) { |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 524 | auto Operand = lookupOperandLeader(O); |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 525 | AllConstant &= isa<Constant>(Operand); |
| 526 | return Operand; |
| 527 | }); |
| 528 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 529 | return AllConstant; |
| 530 | } |
| 531 | |
| 532 | const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T, |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 533 | Value *Arg1, Value *Arg2) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 534 | auto *E = new (ExpressionAllocator) BasicExpression(2); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 535 | |
| 536 | E->setType(T); |
| 537 | E->setOpcode(Opcode); |
| 538 | E->allocateOperands(ArgRecycler, ExpressionAllocator); |
| 539 | if (Instruction::isCommutative(Opcode)) { |
| 540 | // Ensure that commutative instructions that only differ by a permutation |
| 541 | // of their operands get the same value number by sorting the operand value |
| 542 | // numbers. Since all commutative instructions have two operands it is more |
| 543 | // efficient to sort by hand rather than using, say, std::sort. |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 544 | if (shouldSwapOperands(Arg1, Arg2)) |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 545 | std::swap(Arg1, Arg2); |
| 546 | } |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 547 | E->op_push_back(lookupOperandLeader(Arg1)); |
| 548 | E->op_push_back(lookupOperandLeader(Arg2)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 549 | |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 550 | Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), DL, TLI, |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 551 | DT, AC); |
| 552 | if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V)) |
| 553 | return SimplifiedE; |
| 554 | return E; |
| 555 | } |
| 556 | |
| 557 | // Take a Value returned by simplification of Expression E/Instruction |
| 558 | // I, and see if it resulted in a simpler expression. If so, return |
| 559 | // that expression. |
| 560 | // TODO: Once finished, this should not take an Instruction, we only |
| 561 | // use it for printing. |
| 562 | const Expression *NewGVN::checkSimplificationResults(Expression *E, |
| 563 | Instruction *I, Value *V) { |
| 564 | if (!V) |
| 565 | return nullptr; |
| 566 | if (auto *C = dyn_cast<Constant>(V)) { |
| 567 | if (I) |
| 568 | DEBUG(dbgs() << "Simplified " << *I << " to " |
| 569 | << " constant " << *C << "\n"); |
| 570 | NumGVNOpsSimplified++; |
| 571 | assert(isa<BasicExpression>(E) && |
| 572 | "We should always have had a basic expression here"); |
Daniel Berlin | 0e90011 | 2017-03-24 06:33:48 +0000 | [diff] [blame] | 573 | deleteExpression(E); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 574 | return createConstantExpression(C); |
| 575 | } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) { |
| 576 | if (I) |
| 577 | DEBUG(dbgs() << "Simplified " << *I << " to " |
| 578 | << " variable " << *V << "\n"); |
Daniel Berlin | 0e90011 | 2017-03-24 06:33:48 +0000 | [diff] [blame] | 579 | deleteExpression(E); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 580 | return createVariableExpression(V); |
| 581 | } |
| 582 | |
| 583 | CongruenceClass *CC = ValueToClass.lookup(V); |
| 584 | if (CC && CC->DefiningExpr) { |
| 585 | if (I) |
| 586 | DEBUG(dbgs() << "Simplified " << *I << " to " |
| 587 | << " expression " << *V << "\n"); |
| 588 | NumGVNOpsSimplified++; |
Daniel Berlin | 0e90011 | 2017-03-24 06:33:48 +0000 | [diff] [blame] | 589 | deleteExpression(E); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 590 | return CC->DefiningExpr; |
| 591 | } |
| 592 | return nullptr; |
| 593 | } |
| 594 | |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 595 | const Expression *NewGVN::createExpression(Instruction *I) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 596 | auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands()); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 597 | |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 598 | bool AllConstant = setBasicExpressionInfo(I, E); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 599 | |
| 600 | if (I->isCommutative()) { |
| 601 | // Ensure that commutative instructions that only differ by a permutation |
| 602 | // of their operands get the same value number by sorting the operand value |
| 603 | // numbers. Since all commutative instructions have two operands it is more |
| 604 | // efficient to sort by hand rather than using, say, std::sort. |
| 605 | assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!"); |
Daniel Berlin | 508a1de | 2017-02-12 23:24:42 +0000 | [diff] [blame] | 606 | if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 607 | E->swapOperands(0, 1); |
| 608 | } |
| 609 | |
| 610 | // Perform simplificaiton |
| 611 | // TODO: Right now we only check to see if we get a constant result. |
| 612 | // We may get a less than constant, but still better, result for |
| 613 | // some operations. |
| 614 | // IE |
| 615 | // add 0, x -> x |
| 616 | // and x, x -> x |
| 617 | // We should handle this by simply rewriting the expression. |
| 618 | if (auto *CI = dyn_cast<CmpInst>(I)) { |
| 619 | // Sort the operand value numbers so x<y and y>x get the same value |
| 620 | // number. |
| 621 | CmpInst::Predicate Predicate = CI->getPredicate(); |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 622 | if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 623 | E->swapOperands(0, 1); |
| 624 | Predicate = CmpInst::getSwappedPredicate(Predicate); |
| 625 | } |
| 626 | E->setOpcode((CI->getOpcode() << 8) | Predicate); |
| 627 | // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 628 | assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() && |
| 629 | "Wrong types on cmp instruction"); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 630 | assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() && |
| 631 | E->getOperand(1)->getType() == I->getOperand(1)->getType())); |
Daniel Berlin | ff12c92 | 2017-01-31 22:32:01 +0000 | [diff] [blame] | 632 | Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 633 | DL, TLI, DT, AC); |
Daniel Berlin | ff12c92 | 2017-01-31 22:32:01 +0000 | [diff] [blame] | 634 | if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V)) |
| 635 | return SimplifiedE; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 636 | } else if (isa<SelectInst>(I)) { |
| 637 | if (isa<Constant>(E->getOperand(0)) || |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 638 | E->getOperand(0) == E->getOperand(1)) { |
| 639 | assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() && |
| 640 | E->getOperand(2)->getType() == I->getOperand(2)->getType()); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 641 | Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1), |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 642 | E->getOperand(2), DL, TLI, DT, AC); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 643 | if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V)) |
| 644 | return SimplifiedE; |
| 645 | } |
| 646 | } else if (I->isBinaryOp()) { |
| 647 | Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 648 | DL, TLI, DT, AC); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 649 | if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V)) |
| 650 | return SimplifiedE; |
| 651 | } else if (auto *BI = dyn_cast<BitCastInst>(I)) { |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 652 | Value *V = SimplifyInstruction(BI, DL, TLI, DT, AC); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 653 | if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V)) |
| 654 | return SimplifiedE; |
| 655 | } else if (isa<GetElementPtrInst>(I)) { |
| 656 | Value *V = SimplifyGEPInst(E->getType(), |
Daniel Berlin | 65f5f0d | 2016-12-25 22:10:37 +0000 | [diff] [blame] | 657 | ArrayRef<Value *>(E->op_begin(), E->op_end()), |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 658 | DL, TLI, DT, AC); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 659 | if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V)) |
| 660 | return SimplifiedE; |
| 661 | } else if (AllConstant) { |
| 662 | // We don't bother trying to simplify unless all of the operands |
| 663 | // were constant. |
| 664 | // TODO: There are a lot of Simplify*'s we could call here, if we |
| 665 | // wanted to. The original motivating case for this code was a |
| 666 | // zext i1 false to i8, which we don't have an interface to |
| 667 | // simplify (IE there is no SimplifyZExt). |
| 668 | |
| 669 | SmallVector<Constant *, 8> C; |
| 670 | for (Value *Arg : E->operands()) |
Piotr Padlewski | 6c37d29 | 2016-12-28 23:24:02 +0000 | [diff] [blame] | 671 | C.emplace_back(cast<Constant>(Arg)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 672 | |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 673 | if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI)) |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 674 | if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V)) |
| 675 | return SimplifiedE; |
| 676 | } |
| 677 | return E; |
| 678 | } |
| 679 | |
| 680 | const AggregateValueExpression * |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 681 | NewGVN::createAggregateValueExpression(Instruction *I) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 682 | if (auto *II = dyn_cast<InsertValueInst>(I)) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 683 | auto *E = new (ExpressionAllocator) |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 684 | AggregateValueExpression(I->getNumOperands(), II->getNumIndices()); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 685 | setBasicExpressionInfo(I, E); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 686 | E->allocateIntOperands(ExpressionAllocator); |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 687 | std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 688 | return E; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 689 | } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 690 | auto *E = new (ExpressionAllocator) |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 691 | AggregateValueExpression(I->getNumOperands(), EI->getNumIndices()); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 692 | setBasicExpressionInfo(EI, E); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 693 | E->allocateIntOperands(ExpressionAllocator); |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 694 | std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 695 | return E; |
| 696 | } |
| 697 | llvm_unreachable("Unhandled type of aggregate value operation"); |
| 698 | } |
| 699 | |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 700 | const VariableExpression *NewGVN::createVariableExpression(Value *V) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 701 | auto *E = new (ExpressionAllocator) VariableExpression(V); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 702 | E->setOpcode(V->getValueID()); |
| 703 | return E; |
| 704 | } |
| 705 | |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 706 | const Expression *NewGVN::createVariableOrConstant(Value *V) { |
| 707 | if (auto *C = dyn_cast<Constant>(V)) |
| 708 | return createConstantExpression(C); |
| 709 | return createVariableExpression(V); |
| 710 | } |
| 711 | |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 712 | const ConstantExpression *NewGVN::createConstantExpression(Constant *C) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 713 | auto *E = new (ExpressionAllocator) ConstantExpression(C); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 714 | E->setOpcode(C->getValueID()); |
| 715 | return E; |
| 716 | } |
| 717 | |
Daniel Berlin | 02c6b17 | 2017-01-02 18:00:53 +0000 | [diff] [blame] | 718 | const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) { |
| 719 | auto *E = new (ExpressionAllocator) UnknownExpression(I); |
| 720 | E->setOpcode(I->getOpcode()); |
| 721 | return E; |
| 722 | } |
| 723 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 724 | const CallExpression *NewGVN::createCallExpression(CallInst *CI, |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 725 | MemoryAccess *HV) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 726 | // FIXME: Add operand bundles for calls. |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 727 | auto *E = |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 728 | new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 729 | setBasicExpressionInfo(CI, E); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 730 | return E; |
| 731 | } |
| 732 | |
Daniel Berlin | 9d0796e | 2017-03-24 05:30:34 +0000 | [diff] [blame] | 733 | // Return true if some equivalent of instruction Inst dominates instruction U. |
| 734 | bool NewGVN::someEquivalentDominates(const Instruction *Inst, |
| 735 | const Instruction *U) const { |
| 736 | auto *CC = ValueToClass.lookup(Inst); |
Daniel Berlin | ffc3078 | 2017-03-24 06:33:51 +0000 | [diff] [blame] | 737 | // This must be an instruction because we are only called from phi nodes |
| 738 | // in the case that the value it needs to check against is an instruction. |
| 739 | |
| 740 | // The most likely candiates for dominance are the leader and the next leader. |
| 741 | // The leader or nextleader will dominate in all cases where there is an |
| 742 | // equivalent that is higher up in the dom tree. |
| 743 | // We can't *only* check them, however, because the |
| 744 | // dominator tree could have an infinite number of non-dominating siblings |
| 745 | // with instructions that are in the right congruence class. |
| 746 | // A |
| 747 | // B C D E F G |
| 748 | // | |
| 749 | // H |
| 750 | // Instruction U could be in H, with equivalents in every other sibling. |
| 751 | // Depending on the rpo order picked, the leader could be the equivalent in |
| 752 | // any of these siblings. |
| 753 | if (!CC) |
| 754 | return false; |
| 755 | if (DT->dominates(cast<Instruction>(CC->RepLeader), U)) |
| 756 | return true; |
| 757 | if (CC->NextLeader.first && |
| 758 | DT->dominates(cast<Instruction>(CC->NextLeader.first), U)) |
| 759 | return true; |
| 760 | return llvm::any_of(CC->Members, [&](const Value *Member) { |
| 761 | return Member != CC->RepLeader && |
| 762 | DT->dominates(cast<Instruction>(Member), U); |
| 763 | }); |
Daniel Berlin | 9d0796e | 2017-03-24 05:30:34 +0000 | [diff] [blame] | 764 | } |
| 765 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 766 | // See if we have a congruence class and leader for this operand, and if so, |
| 767 | // return it. Otherwise, return the operand itself. |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 768 | Value *NewGVN::lookupOperandLeader(Value *V) const { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 769 | CongruenceClass *CC = ValueToClass.lookup(V); |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 770 | if (CC) { |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 771 | // Everything in TOP is represneted by undef, as it can be any value. |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 772 | // We do have to make sure we get the type right though, so we can't set the |
| 773 | // RepLeader to undef. |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 774 | if (CC == TOPClass) |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 775 | return UndefValue::get(V->getType()); |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 776 | return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader; |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 777 | } |
| 778 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 779 | return V; |
| 780 | } |
| 781 | |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 782 | MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const { |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 783 | auto *CC = MemoryAccessToClass.lookup(MA); |
| 784 | if (CC && CC->RepMemoryAccess) |
| 785 | return CC->RepMemoryAccess; |
| 786 | // FIXME: We need to audit all the places that current set a nullptr To, and |
| 787 | // fix them. There should always be *some* congruence class, even if it is |
| 788 | // singular. Right now, we don't bother setting congruence classes for |
| 789 | // anything but stores, which means we have to return the original access |
| 790 | // here. Otherwise, this should be unreachable. |
| 791 | return MA; |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 792 | } |
| 793 | |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 794 | // Return true if the MemoryAccess is really equivalent to everything. This is |
| 795 | // equivalent to the lattice value "TOP" in most lattices. This is the initial |
| 796 | // state of all memory accesses. |
| 797 | bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const { |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 798 | return MemoryAccessToClass.lookup(MA) == TOPClass; |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 799 | } |
| 800 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 801 | LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp, |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 802 | LoadInst *LI, MemoryAccess *DA) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 803 | auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 804 | E->allocateOperands(ArgRecycler, ExpressionAllocator); |
| 805 | E->setType(LoadType); |
| 806 | |
| 807 | // Give store and loads same opcode so they value number together. |
| 808 | E->setOpcode(0); |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 809 | E->op_push_back(lookupOperandLeader(PointerOp)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 810 | if (LI) |
| 811 | E->setAlignment(LI->getAlignment()); |
| 812 | |
| 813 | // TODO: Value number heap versions. We may be able to discover |
| 814 | // things alias analysis can't on it's own (IE that a store and a |
| 815 | // load have the same value, and thus, it isn't clobbering the load). |
| 816 | return E; |
| 817 | } |
| 818 | |
| 819 | const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI, |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 820 | MemoryAccess *DA) { |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 821 | auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand()); |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 822 | auto *E = new (ExpressionAllocator) |
| 823 | StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 824 | E->allocateOperands(ArgRecycler, ExpressionAllocator); |
| 825 | E->setType(SI->getValueOperand()->getType()); |
| 826 | |
| 827 | // Give store and loads same opcode so they value number together. |
| 828 | E->setOpcode(0); |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 829 | E->op_push_back(lookupOperandLeader(SI->getPointerOperand())); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 830 | |
| 831 | // TODO: Value number heap versions. We may be able to discover |
| 832 | // things alias analysis can't on it's own (IE that a store and a |
| 833 | // load have the same value, and thus, it isn't clobbering the load). |
| 834 | return E; |
| 835 | } |
| 836 | |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 837 | const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) { |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 838 | // Unlike loads, we never try to eliminate stores, so we do not check if they |
| 839 | // are simple and avoid value numbering them. |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 840 | auto *SI = cast<StoreInst>(I); |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 841 | MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI); |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 842 | // Get the expression, if any, for the RHS of the MemoryDef. |
| 843 | MemoryAccess *StoreRHS = lookupMemoryAccessEquiv( |
| 844 | cast<MemoryDef>(StoreAccess)->getDefiningAccess()); |
| 845 | // If we are defined by ourselves, use the live on entry def. |
| 846 | if (StoreRHS == StoreAccess) |
| 847 | StoreRHS = MSSA->getLiveOnEntryDef(); |
| 848 | |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 849 | if (SI->isSimple()) { |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 850 | // See if we are defined by a previous store expression, it already has a |
| 851 | // value, and it's the same value as our current store. FIXME: Right now, we |
| 852 | // only do this for simple stores, we should expand to cover memcpys, etc. |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 853 | const Expression *OldStore = createStoreExpression(SI, StoreRHS); |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 854 | CongruenceClass *CC = ExpressionToClass.lookup(OldStore); |
Daniel Berlin | b755aea | 2017-01-09 05:34:29 +0000 | [diff] [blame] | 855 | // Basically, check if the congruence class the store is in is defined by a |
| 856 | // store that isn't us, and has the same value. MemorySSA takes care of |
| 857 | // ensuring the store has the same memory state as us already. |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 858 | // The RepStoredValue gets nulled if all the stores disappear in a class, so |
| 859 | // we don't need to check if the class contains a store besides us. |
Daniel Berlin | 808e3ff | 2017-01-31 22:31:56 +0000 | [diff] [blame] | 860 | if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand())) |
Daniel Berlin | 0e90011 | 2017-03-24 06:33:48 +0000 | [diff] [blame] | 861 | return OldStore; |
| 862 | deleteExpression(OldStore); |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 863 | // Also check if our value operand is defined by a load of the same memory |
| 864 | // location, and the memory state is the same as it was then |
| 865 | // (otherwise, it could have been overwritten later. See test32 in |
| 866 | // transforms/DeadStoreElimination/simple.ll) |
| 867 | if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) { |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 868 | if ((lookupOperandLeader(LI->getPointerOperand()) == |
| 869 | lookupOperandLeader(SI->getPointerOperand())) && |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 870 | (lookupMemoryAccessEquiv( |
| 871 | MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS)) |
| 872 | return createVariableExpression(LI); |
| 873 | } |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 874 | } |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 875 | return createStoreExpression(SI, StoreAccess); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 876 | } |
| 877 | |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 878 | const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 879 | auto *LI = cast<LoadInst>(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 880 | |
| 881 | // We can eliminate in favor of non-simple loads, but we won't be able to |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 882 | // eliminate the loads themselves. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 883 | if (!LI->isSimple()) |
| 884 | return nullptr; |
| 885 | |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 886 | Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand()); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 887 | // Load of undef is undef. |
| 888 | if (isa<UndefValue>(LoadAddressLeader)) |
| 889 | return createConstantExpression(UndefValue::get(LI->getType())); |
| 890 | |
| 891 | MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I); |
| 892 | |
| 893 | if (!MSSA->isLiveOnEntryDef(DefiningAccess)) { |
| 894 | if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) { |
| 895 | Instruction *DefiningInst = MD->getMemoryInst(); |
| 896 | // If the defining instruction is not reachable, replace with undef. |
| 897 | if (!ReachableBlocks.count(DefiningInst->getParent())) |
| 898 | return createConstantExpression(UndefValue::get(LI->getType())); |
| 899 | } |
| 900 | } |
| 901 | |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 902 | const Expression *E = |
| 903 | createLoadExpression(LI->getType(), LI->getPointerOperand(), LI, |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 904 | lookupMemoryAccessEquiv(DefiningAccess)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 905 | return E; |
| 906 | } |
| 907 | |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 908 | const Expression * |
| 909 | NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) { |
| 910 | auto *PI = PredInfo->getPredicateInfoFor(I); |
| 911 | if (!PI) |
| 912 | return nullptr; |
| 913 | |
| 914 | DEBUG(dbgs() << "Found predicate info from instruction !\n"); |
Daniel Berlin | fccbda9 | 2017-02-22 22:20:58 +0000 | [diff] [blame] | 915 | |
| 916 | auto *PWC = dyn_cast<PredicateWithCondition>(PI); |
| 917 | if (!PWC) |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 918 | return nullptr; |
| 919 | |
Daniel Berlin | fccbda9 | 2017-02-22 22:20:58 +0000 | [diff] [blame] | 920 | auto *CopyOf = I->getOperand(0); |
| 921 | auto *Cond = PWC->Condition; |
| 922 | |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 923 | // If this a copy of the condition, it must be either true or false depending |
| 924 | // on the predicate info type and edge |
| 925 | if (CopyOf == Cond) { |
Daniel Berlin | fccbda9 | 2017-02-22 22:20:58 +0000 | [diff] [blame] | 926 | // We should not need to add predicate users because the predicate info is |
| 927 | // already a use of this operand. |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 928 | if (isa<PredicateAssume>(PI)) |
| 929 | return createConstantExpression(ConstantInt::getTrue(Cond->getType())); |
| 930 | if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) { |
| 931 | if (PBranch->TrueEdge) |
| 932 | return createConstantExpression(ConstantInt::getTrue(Cond->getType())); |
| 933 | return createConstantExpression(ConstantInt::getFalse(Cond->getType())); |
| 934 | } |
Daniel Berlin | fccbda9 | 2017-02-22 22:20:58 +0000 | [diff] [blame] | 935 | if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI)) |
| 936 | return createConstantExpression(cast<Constant>(PSwitch->CaseValue)); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 937 | } |
Daniel Berlin | fccbda9 | 2017-02-22 22:20:58 +0000 | [diff] [blame] | 938 | |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 939 | // Not a copy of the condition, so see what the predicates tell us about this |
| 940 | // value. First, though, we check to make sure the value is actually a copy |
| 941 | // of one of the condition operands. It's possible, in certain cases, for it |
| 942 | // to be a copy of a predicateinfo copy. In particular, if two branch |
| 943 | // operations use the same condition, and one branch dominates the other, we |
| 944 | // will end up with a copy of a copy. This is currently a small deficiency in |
Daniel Berlin | fccbda9 | 2017-02-22 22:20:58 +0000 | [diff] [blame] | 945 | // predicateinfo. What will end up happening here is that we will value |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 946 | // number both copies the same anyway. |
Daniel Berlin | fccbda9 | 2017-02-22 22:20:58 +0000 | [diff] [blame] | 947 | |
| 948 | // Everything below relies on the condition being a comparison. |
| 949 | auto *Cmp = dyn_cast<CmpInst>(Cond); |
| 950 | if (!Cmp) |
| 951 | return nullptr; |
| 952 | |
| 953 | if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) { |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 954 | DEBUG(dbgs() << "Copy is not of any condition operands!"); |
| 955 | return nullptr; |
| 956 | } |
Daniel Berlin | fccbda9 | 2017-02-22 22:20:58 +0000 | [diff] [blame] | 957 | Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0)); |
| 958 | Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1)); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 959 | bool SwappedOps = false; |
| 960 | // Sort the ops |
| 961 | if (shouldSwapOperands(FirstOp, SecondOp)) { |
| 962 | std::swap(FirstOp, SecondOp); |
| 963 | SwappedOps = true; |
| 964 | } |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 965 | CmpInst::Predicate Predicate = |
| 966 | SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate(); |
| 967 | |
| 968 | if (isa<PredicateAssume>(PI)) { |
| 969 | // If the comparison is true when the operands are equal, then we know the |
| 970 | // operands are equal, because assumes must always be true. |
| 971 | if (CmpInst::isTrueWhenEqual(Predicate)) { |
| 972 | addPredicateUsers(PI, I); |
| 973 | return createVariableOrConstant(FirstOp); |
| 974 | } |
| 975 | } |
| 976 | if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) { |
| 977 | // If we are *not* a copy of the comparison, we may equal to the other |
| 978 | // operand when the predicate implies something about equality of |
| 979 | // operations. In particular, if the comparison is true/false when the |
| 980 | // operands are equal, and we are on the right edge, we know this operation |
| 981 | // is equal to something. |
| 982 | if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) || |
| 983 | (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) { |
| 984 | addPredicateUsers(PI, I); |
| 985 | return createVariableOrConstant(FirstOp); |
| 986 | } |
| 987 | // Handle the special case of floating point. |
| 988 | if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) || |
| 989 | (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) && |
| 990 | isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) { |
| 991 | addPredicateUsers(PI, I); |
| 992 | return createConstantExpression(cast<Constant>(FirstOp)); |
| 993 | } |
| 994 | } |
| 995 | return nullptr; |
| 996 | } |
| 997 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 998 | // Evaluate read only and pure calls, and create an expression result. |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 999 | const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 1000 | auto *CI = cast<CallInst>(I); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1001 | if (auto *II = dyn_cast<IntrinsicInst>(I)) { |
| 1002 | // Instrinsics with the returned attribute are copies of arguments. |
| 1003 | if (auto *ReturnedValue = II->getReturnedArgOperand()) { |
| 1004 | if (II->getIntrinsicID() == Intrinsic::ssa_copy) |
| 1005 | if (const auto *Result = performSymbolicPredicateInfoEvaluation(I)) |
| 1006 | return Result; |
| 1007 | return createVariableOrConstant(ReturnedValue); |
| 1008 | } |
| 1009 | } |
| 1010 | if (AA->doesNotAccessMemory(CI)) { |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1011 | return createCallExpression(CI, nullptr); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1012 | } else if (AA->onlyReadsMemory(CI)) { |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 1013 | MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1014 | return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess)); |
Davide Italiano | b222549 | 2016-12-27 18:15:39 +0000 | [diff] [blame] | 1015 | } |
| 1016 | return nullptr; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1017 | } |
| 1018 | |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1019 | // Update the memory access equivalence table to say that From is equal to To, |
| 1020 | // and return true if this is different from what already existed in the table. |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1021 | // FIXME: We need to audit all the places that current set a nullptr To, and fix |
| 1022 | // them. There should always be *some* congruence class, even if it is singular. |
| 1023 | bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) { |
| 1024 | DEBUG(dbgs() << "Setting " << *From); |
| 1025 | if (To) { |
| 1026 | DEBUG(dbgs() << " equivalent to congruence class "); |
| 1027 | DEBUG(dbgs() << To->ID << " with current memory access leader "); |
| 1028 | DEBUG(dbgs() << *To->RepMemoryAccess); |
| 1029 | } else { |
| 1030 | DEBUG(dbgs() << " equivalent to itself"); |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1031 | } |
Daniel Berlin | 9f376b7 | 2017-01-29 10:26:03 +0000 | [diff] [blame] | 1032 | DEBUG(dbgs() << "\n"); |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1033 | |
| 1034 | auto LookupResult = MemoryAccessToClass.find(From); |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1035 | bool Changed = false; |
| 1036 | // If it's already in the table, see if the value changed. |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1037 | if (LookupResult != MemoryAccessToClass.end()) { |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1038 | if (To && LookupResult->second != To) { |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1039 | // It wasn't equivalent before, and now it is. |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1040 | LookupResult->second = To; |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1041 | Changed = true; |
| 1042 | } else if (!To) { |
| 1043 | // It used to be equivalent to something, and now it's not. |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1044 | MemoryAccessToClass.erase(LookupResult); |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1045 | Changed = true; |
| 1046 | } |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1047 | } else { |
| 1048 | assert(!To && |
| 1049 | "Memory equivalence should never change from nothing to something"); |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1050 | } |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1051 | |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1052 | return Changed; |
| 1053 | } |
Daniel Berlin | 0e90011 | 2017-03-24 06:33:48 +0000 | [diff] [blame] | 1054 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1055 | // Evaluate PHI nodes symbolically, and create an expression result. |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1056 | const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 1057 | auto *E = cast<PHIExpression>(createPHIExpression(I)); |
Daniel Berlin | d92e7f9 | 2017-01-07 00:01:42 +0000 | [diff] [blame] | 1058 | // We match the semantics of SimplifyPhiNode from InstructionSimplify here. |
| 1059 | |
| 1060 | // See if all arguaments are the same. |
| 1061 | // We track if any were undef because they need special handling. |
| 1062 | bool HasUndef = false; |
| 1063 | auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) { |
| 1064 | if (Arg == I) |
| 1065 | return false; |
| 1066 | if (isa<UndefValue>(Arg)) { |
| 1067 | HasUndef = true; |
| 1068 | return false; |
| 1069 | } |
| 1070 | return true; |
| 1071 | }); |
| 1072 | // If we are left with no operands, it's undef |
| 1073 | if (Filtered.begin() == Filtered.end()) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1074 | DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef" |
| 1075 | << "\n"); |
Daniel Berlin | 0e90011 | 2017-03-24 06:33:48 +0000 | [diff] [blame] | 1076 | deleteExpression(E); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1077 | return createConstantExpression(UndefValue::get(I->getType())); |
| 1078 | } |
Daniel Berlin | d92e7f9 | 2017-01-07 00:01:42 +0000 | [diff] [blame] | 1079 | Value *AllSameValue = *(Filtered.begin()); |
| 1080 | ++Filtered.begin(); |
| 1081 | // Can't use std::equal here, sadly, because filter.begin moves. |
| 1082 | if (llvm::all_of(Filtered, [AllSameValue](const Value *V) { |
| 1083 | return V == AllSameValue; |
| 1084 | })) { |
| 1085 | // In LLVM's non-standard representation of phi nodes, it's possible to have |
| 1086 | // phi nodes with cycles (IE dependent on other phis that are .... dependent |
| 1087 | // on the original phi node), especially in weird CFG's where some arguments |
| 1088 | // are unreachable, or uninitialized along certain paths. This can cause |
| 1089 | // infinite loops during evaluation. We work around this by not trying to |
| 1090 | // really evaluate them independently, but instead using a variable |
| 1091 | // expression to say if one is equivalent to the other. |
| 1092 | // We also special case undef, so that if we have an undef, we can't use the |
| 1093 | // common value unless it dominates the phi block. |
| 1094 | if (HasUndef) { |
| 1095 | // Only have to check for instructions |
Davide Italiano | 1b97fc3 | 2017-01-07 02:05:50 +0000 | [diff] [blame] | 1096 | if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue)) |
Daniel Berlin | 9d0796e | 2017-03-24 05:30:34 +0000 | [diff] [blame] | 1097 | if (!someEquivalentDominates(AllSameInst, I)) |
Daniel Berlin | d92e7f9 | 2017-01-07 00:01:42 +0000 | [diff] [blame] | 1098 | return E; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1099 | } |
| 1100 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1101 | NumGVNPhisAllSame++; |
| 1102 | DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue |
| 1103 | << "\n"); |
Daniel Berlin | 0e90011 | 2017-03-24 06:33:48 +0000 | [diff] [blame] | 1104 | deleteExpression(E); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1105 | return createVariableOrConstant(AllSameValue); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1106 | } |
| 1107 | return E; |
| 1108 | } |
| 1109 | |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1110 | const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1111 | if (auto *EI = dyn_cast<ExtractValueInst>(I)) { |
| 1112 | auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand()); |
| 1113 | if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) { |
| 1114 | unsigned Opcode = 0; |
| 1115 | // EI might be an extract from one of our recognised intrinsics. If it |
| 1116 | // is we'll synthesize a semantically equivalent expression instead on |
| 1117 | // an extract value expression. |
| 1118 | switch (II->getIntrinsicID()) { |
| 1119 | case Intrinsic::sadd_with_overflow: |
| 1120 | case Intrinsic::uadd_with_overflow: |
| 1121 | Opcode = Instruction::Add; |
| 1122 | break; |
| 1123 | case Intrinsic::ssub_with_overflow: |
| 1124 | case Intrinsic::usub_with_overflow: |
| 1125 | Opcode = Instruction::Sub; |
| 1126 | break; |
| 1127 | case Intrinsic::smul_with_overflow: |
| 1128 | case Intrinsic::umul_with_overflow: |
| 1129 | Opcode = Instruction::Mul; |
| 1130 | break; |
| 1131 | default: |
| 1132 | break; |
| 1133 | } |
| 1134 | |
| 1135 | if (Opcode != 0) { |
| 1136 | // Intrinsic recognized. Grab its args to finish building the |
| 1137 | // expression. |
| 1138 | assert(II->getNumArgOperands() == 2 && |
| 1139 | "Expect two args for recognised intrinsics."); |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 1140 | return createBinaryExpression( |
| 1141 | Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1142 | } |
| 1143 | } |
| 1144 | } |
| 1145 | |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1146 | return createAggregateValueExpression(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1147 | } |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1148 | const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) { |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1149 | auto *CI = dyn_cast<CmpInst>(I); |
| 1150 | // See if our operands are equal to those of a previous predicate, and if so, |
| 1151 | // if it implies true or false. |
Daniel Berlin | c22aafe | 2017-01-31 22:31:58 +0000 | [diff] [blame] | 1152 | auto Op0 = lookupOperandLeader(CI->getOperand(0)); |
| 1153 | auto Op1 = lookupOperandLeader(CI->getOperand(1)); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1154 | auto OurPredicate = CI->getPredicate(); |
Daniel Berlin | 0350a87 | 2017-03-04 00:44:43 +0000 | [diff] [blame] | 1155 | if (shouldSwapOperands(Op0, Op1)) { |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1156 | std::swap(Op0, Op1); |
| 1157 | OurPredicate = CI->getSwappedPredicate(); |
| 1158 | } |
| 1159 | |
| 1160 | // Avoid processing the same info twice |
| 1161 | const PredicateBase *LastPredInfo = nullptr; |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1162 | // See if we know something about the comparison itself, like it is the target |
| 1163 | // of an assume. |
| 1164 | auto *CmpPI = PredInfo->getPredicateInfoFor(I); |
| 1165 | if (dyn_cast_or_null<PredicateAssume>(CmpPI)) |
| 1166 | return createConstantExpression(ConstantInt::getTrue(CI->getType())); |
| 1167 | |
Daniel Berlin | c22aafe | 2017-01-31 22:31:58 +0000 | [diff] [blame] | 1168 | if (Op0 == Op1) { |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1169 | // This condition does not depend on predicates, no need to add users |
Daniel Berlin | c22aafe | 2017-01-31 22:31:58 +0000 | [diff] [blame] | 1170 | if (CI->isTrueWhenEqual()) |
| 1171 | return createConstantExpression(ConstantInt::getTrue(CI->getType())); |
| 1172 | else if (CI->isFalseWhenEqual()) |
| 1173 | return createConstantExpression(ConstantInt::getFalse(CI->getType())); |
| 1174 | } |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1175 | |
| 1176 | // NOTE: Because we are comparing both operands here and below, and using |
| 1177 | // previous comparisons, we rely on fact that predicateinfo knows to mark |
| 1178 | // comparisons that use renamed operands as users of the earlier comparisons. |
| 1179 | // It is *not* enough to just mark predicateinfo renamed operands as users of |
| 1180 | // the earlier comparisons, because the *other* operand may have changed in a |
| 1181 | // previous iteration. |
| 1182 | // Example: |
| 1183 | // icmp slt %a, %b |
| 1184 | // %b.0 = ssa.copy(%b) |
| 1185 | // false branch: |
| 1186 | // icmp slt %c, %b.0 |
| 1187 | |
| 1188 | // %c and %a may start out equal, and thus, the code below will say the second |
| 1189 | // %icmp is false. c may become equal to something else, and in that case the |
| 1190 | // %second icmp *must* be reexamined, but would not if only the renamed |
| 1191 | // %operands are considered users of the icmp. |
| 1192 | |
| 1193 | // *Currently* we only check one level of comparisons back, and only mark one |
| 1194 | // level back as touched when changes appen . If you modify this code to look |
| 1195 | // back farther through comparisons, you *must* mark the appropriate |
| 1196 | // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if |
| 1197 | // we know something just from the operands themselves |
| 1198 | |
| 1199 | // See if our operands have predicate info, so that we may be able to derive |
| 1200 | // something from a previous comparison. |
| 1201 | for (const auto &Op : CI->operands()) { |
| 1202 | auto *PI = PredInfo->getPredicateInfoFor(Op); |
| 1203 | if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) { |
| 1204 | if (PI == LastPredInfo) |
| 1205 | continue; |
| 1206 | LastPredInfo = PI; |
Daniel Berlin | fccbda9 | 2017-02-22 22:20:58 +0000 | [diff] [blame] | 1207 | |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1208 | // TODO: Along the false edge, we may know more things too, like icmp of |
| 1209 | // same operands is false. |
| 1210 | // TODO: We only handle actual comparison conditions below, not and/or. |
| 1211 | auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition); |
| 1212 | if (!BranchCond) |
| 1213 | continue; |
| 1214 | auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0)); |
| 1215 | auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1)); |
| 1216 | auto BranchPredicate = BranchCond->getPredicate(); |
Daniel Berlin | 0350a87 | 2017-03-04 00:44:43 +0000 | [diff] [blame] | 1217 | if (shouldSwapOperands(BranchOp0, BranchOp1)) { |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1218 | std::swap(BranchOp0, BranchOp1); |
| 1219 | BranchPredicate = BranchCond->getSwappedPredicate(); |
| 1220 | } |
| 1221 | if (BranchOp0 == Op0 && BranchOp1 == Op1) { |
| 1222 | if (PBranch->TrueEdge) { |
| 1223 | // If we know the previous predicate is true and we are in the true |
| 1224 | // edge then we may be implied true or false. |
| 1225 | if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate, |
| 1226 | BranchPredicate)) { |
| 1227 | addPredicateUsers(PI, I); |
| 1228 | return createConstantExpression( |
| 1229 | ConstantInt::getTrue(CI->getType())); |
| 1230 | } |
| 1231 | |
| 1232 | if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate, |
| 1233 | BranchPredicate)) { |
| 1234 | addPredicateUsers(PI, I); |
| 1235 | return createConstantExpression( |
| 1236 | ConstantInt::getFalse(CI->getType())); |
| 1237 | } |
| 1238 | |
| 1239 | } else { |
| 1240 | // Just handle the ne and eq cases, where if we have the same |
| 1241 | // operands, we may know something. |
| 1242 | if (BranchPredicate == OurPredicate) { |
| 1243 | addPredicateUsers(PI, I); |
| 1244 | // Same predicate, same ops,we know it was false, so this is false. |
| 1245 | return createConstantExpression( |
| 1246 | ConstantInt::getFalse(CI->getType())); |
| 1247 | } else if (BranchPredicate == |
| 1248 | CmpInst::getInversePredicate(OurPredicate)) { |
| 1249 | addPredicateUsers(PI, I); |
| 1250 | // Inverse predicate, we know the other was false, so this is true. |
| 1251 | // FIXME: Double check this |
| 1252 | return createConstantExpression( |
| 1253 | ConstantInt::getTrue(CI->getType())); |
| 1254 | } |
| 1255 | } |
| 1256 | } |
| 1257 | } |
| 1258 | } |
| 1259 | // Create expression will take care of simplifyCmpInst |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1260 | return createExpression(I); |
Daniel Berlin | c22aafe | 2017-01-31 22:31:58 +0000 | [diff] [blame] | 1261 | } |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1262 | |
| 1263 | // Substitute and symbolize the value before value numbering. |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1264 | const Expression *NewGVN::performSymbolicEvaluation(Value *V) { |
Davide Italiano | 0e71480 | 2016-12-28 14:00:11 +0000 | [diff] [blame] | 1265 | const Expression *E = nullptr; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1266 | if (auto *C = dyn_cast<Constant>(V)) |
| 1267 | E = createConstantExpression(C); |
| 1268 | else if (isa<Argument>(V) || isa<GlobalVariable>(V)) { |
| 1269 | E = createVariableExpression(V); |
| 1270 | } else { |
| 1271 | // TODO: memory intrinsics. |
| 1272 | // TODO: Some day, we should do the forward propagation and reassociation |
| 1273 | // parts of the algorithm. |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 1274 | auto *I = cast<Instruction>(V); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1275 | switch (I->getOpcode()) { |
| 1276 | case Instruction::ExtractValue: |
| 1277 | case Instruction::InsertValue: |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1278 | E = performSymbolicAggrValueEvaluation(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1279 | break; |
| 1280 | case Instruction::PHI: |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1281 | E = performSymbolicPHIEvaluation(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1282 | break; |
| 1283 | case Instruction::Call: |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1284 | E = performSymbolicCallEvaluation(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1285 | break; |
| 1286 | case Instruction::Store: |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1287 | E = performSymbolicStoreEvaluation(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1288 | break; |
| 1289 | case Instruction::Load: |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1290 | E = performSymbolicLoadEvaluation(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1291 | break; |
| 1292 | case Instruction::BitCast: { |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1293 | E = createExpression(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1294 | } break; |
Daniel Berlin | c22aafe | 2017-01-31 22:31:58 +0000 | [diff] [blame] | 1295 | case Instruction::ICmp: |
| 1296 | case Instruction::FCmp: { |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1297 | E = performSymbolicCmpEvaluation(I); |
Daniel Berlin | c22aafe | 2017-01-31 22:31:58 +0000 | [diff] [blame] | 1298 | } break; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1299 | case Instruction::Add: |
| 1300 | case Instruction::FAdd: |
| 1301 | case Instruction::Sub: |
| 1302 | case Instruction::FSub: |
| 1303 | case Instruction::Mul: |
| 1304 | case Instruction::FMul: |
| 1305 | case Instruction::UDiv: |
| 1306 | case Instruction::SDiv: |
| 1307 | case Instruction::FDiv: |
| 1308 | case Instruction::URem: |
| 1309 | case Instruction::SRem: |
| 1310 | case Instruction::FRem: |
| 1311 | case Instruction::Shl: |
| 1312 | case Instruction::LShr: |
| 1313 | case Instruction::AShr: |
| 1314 | case Instruction::And: |
| 1315 | case Instruction::Or: |
| 1316 | case Instruction::Xor: |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1317 | case Instruction::Trunc: |
| 1318 | case Instruction::ZExt: |
| 1319 | case Instruction::SExt: |
| 1320 | case Instruction::FPToUI: |
| 1321 | case Instruction::FPToSI: |
| 1322 | case Instruction::UIToFP: |
| 1323 | case Instruction::SIToFP: |
| 1324 | case Instruction::FPTrunc: |
| 1325 | case Instruction::FPExt: |
| 1326 | case Instruction::PtrToInt: |
| 1327 | case Instruction::IntToPtr: |
| 1328 | case Instruction::Select: |
| 1329 | case Instruction::ExtractElement: |
| 1330 | case Instruction::InsertElement: |
| 1331 | case Instruction::ShuffleVector: |
| 1332 | case Instruction::GetElementPtr: |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1333 | E = createExpression(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1334 | break; |
| 1335 | default: |
| 1336 | return nullptr; |
| 1337 | } |
| 1338 | } |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1339 | return E; |
| 1340 | } |
| 1341 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1342 | void NewGVN::markUsersTouched(Value *V) { |
| 1343 | // Now mark the users as touched. |
Daniel Berlin | e0bd37e | 2016-12-29 22:15:12 +0000 | [diff] [blame] | 1344 | for (auto *User : V->users()) { |
| 1345 | assert(isa<Instruction>(User) && "Use of value not within an instruction?"); |
Daniel Berlin | aac5684 | 2017-01-15 09:18:41 +0000 | [diff] [blame] | 1346 | TouchedInstructions.set(InstrDFS.lookup(User)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1347 | } |
| 1348 | } |
| 1349 | |
| 1350 | void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) { |
| 1351 | for (auto U : MA->users()) { |
| 1352 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(U)) |
Daniel Berlin | aac5684 | 2017-01-15 09:18:41 +0000 | [diff] [blame] | 1353 | TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst())); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1354 | else |
Daniel Berlin | aac5684 | 2017-01-15 09:18:41 +0000 | [diff] [blame] | 1355 | TouchedInstructions.set(InstrDFS.lookup(U)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1356 | } |
| 1357 | } |
| 1358 | |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1359 | // Add I to the set of users of a given predicate. |
| 1360 | void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) { |
| 1361 | if (auto *PBranch = dyn_cast<PredicateBranch>(PB)) |
| 1362 | PredicateToUsers[PBranch->Condition].insert(I); |
| 1363 | else if (auto *PAssume = dyn_cast<PredicateBranch>(PB)) |
| 1364 | PredicateToUsers[PAssume->Condition].insert(I); |
| 1365 | } |
| 1366 | |
| 1367 | // Touch all the predicates that depend on this instruction. |
| 1368 | void NewGVN::markPredicateUsersTouched(Instruction *I) { |
| 1369 | const auto Result = PredicateToUsers.find(I); |
Daniel Berlin | 46b72e6 | 2017-03-19 00:07:32 +0000 | [diff] [blame] | 1370 | if (Result != PredicateToUsers.end()) { |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1371 | for (auto *User : Result->second) |
| 1372 | TouchedInstructions.set(InstrDFS.lookup(User)); |
Daniel Berlin | 46b72e6 | 2017-03-19 00:07:32 +0000 | [diff] [blame] | 1373 | PredicateToUsers.erase(Result); |
| 1374 | } |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1375 | } |
| 1376 | |
Daniel Berlin | 32f8d56 | 2017-01-07 16:55:14 +0000 | [diff] [blame] | 1377 | // Touch the instructions that need to be updated after a congruence class has a |
| 1378 | // leader change, and mark changed values. |
| 1379 | void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) { |
| 1380 | for (auto M : CC->Members) { |
| 1381 | if (auto *I = dyn_cast<Instruction>(M)) |
Daniel Berlin | aac5684 | 2017-01-15 09:18:41 +0000 | [diff] [blame] | 1382 | TouchedInstructions.set(InstrDFS.lookup(I)); |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1383 | LeaderChanges.insert(M); |
| 1384 | } |
| 1385 | } |
| 1386 | |
| 1387 | // Move a value, currently in OldClass, to be part of NewClass |
| 1388 | // Update OldClass for the move (including changing leaders, etc) |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1389 | void NewGVN::moveValueToNewCongruenceClass(Instruction *I, |
| 1390 | CongruenceClass *OldClass, |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1391 | CongruenceClass *NewClass) { |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1392 | DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1393 | << "\n"); |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1394 | |
| 1395 | if (I == OldClass->NextLeader.first) |
| 1396 | OldClass->NextLeader = {nullptr, ~0U}; |
| 1397 | |
Daniel Berlin | 89fea6f | 2017-01-20 06:38:41 +0000 | [diff] [blame] | 1398 | // It's possible, though unlikely, for us to discover equivalences such |
| 1399 | // that the current leader does not dominate the old one. |
| 1400 | // This statistic tracks how often this happens. |
| 1401 | // We assert on phi nodes when this happens, currently, for debugging, because |
| 1402 | // we want to make sure we name phi node cycles properly. |
| 1403 | if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader && |
Daniel Berlin | ffc3078 | 2017-03-24 06:33:51 +0000 | [diff] [blame] | 1404 | I != NewClass->RepLeader) { |
| 1405 | auto *IBB = I->getParent(); |
| 1406 | auto *NCBB = cast<Instruction>(NewClass->RepLeader)->getParent(); |
| 1407 | bool Dominated = IBB == NCBB && |
| 1408 | InstrDFS.lookup(I) < InstrDFS.lookup(NewClass->RepLeader); |
| 1409 | Dominated = Dominated || DT->properlyDominates(IBB, NCBB); |
| 1410 | if (Dominated) { |
| 1411 | ++NumGVNNotMostDominatingLeader; |
| 1412 | assert( |
| 1413 | !isa<PHINode>(I) && |
| 1414 | "New class for instruction should not be dominated by instruction"); |
| 1415 | } |
Daniel Berlin | 89fea6f | 2017-01-20 06:38:41 +0000 | [diff] [blame] | 1416 | } |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1417 | |
| 1418 | if (NewClass->RepLeader != I) { |
| 1419 | auto DFSNum = InstrDFS.lookup(I); |
| 1420 | if (DFSNum < NewClass->NextLeader.second) |
| 1421 | NewClass->NextLeader = {I, DFSNum}; |
| 1422 | } |
| 1423 | |
| 1424 | OldClass->Members.erase(I); |
| 1425 | NewClass->Members.insert(I); |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1426 | MemoryAccess *StoreAccess = nullptr; |
| 1427 | if (auto *SI = dyn_cast<StoreInst>(I)) { |
| 1428 | StoreAccess = MSSA->getMemoryAccess(SI); |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1429 | --OldClass->StoreCount; |
Davide Italiano | 0dc68bf | 2017-01-11 22:00:29 +0000 | [diff] [blame] | 1430 | assert(OldClass->StoreCount >= 0); |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1431 | ++NewClass->StoreCount; |
Davide Italiano | eac05f6 | 2017-01-11 23:41:24 +0000 | [diff] [blame] | 1432 | assert(NewClass->StoreCount > 0); |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1433 | if (!NewClass->RepMemoryAccess) { |
| 1434 | // If we don't have a representative memory access, it better be the only |
| 1435 | // store in there. |
| 1436 | assert(NewClass->StoreCount == 1); |
| 1437 | NewClass->RepMemoryAccess = StoreAccess; |
| 1438 | } |
| 1439 | setMemoryAccessEquivTo(StoreAccess, NewClass); |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1440 | } |
| 1441 | |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1442 | ValueToClass[I] = NewClass; |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1443 | // See if we destroyed the class or need to swap leaders. |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1444 | if (OldClass->Members.empty() && OldClass != TOPClass) { |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1445 | if (OldClass->DefiningExpr) { |
| 1446 | OldClass->Dead = true; |
| 1447 | DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr |
| 1448 | << " from table\n"); |
| 1449 | ExpressionToClass.erase(OldClass->DefiningExpr); |
| 1450 | } |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1451 | } else if (OldClass->RepLeader == I) { |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1452 | // When the leader changes, the value numbering of |
| 1453 | // everything may change due to symbolization changes, so we need to |
| 1454 | // reprocess. |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1455 | DEBUG(dbgs() << "Leader change!\n"); |
| 1456 | ++NumGVNLeaderChanges; |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 1457 | // Destroy the stored value if there are no more stores to represent it. |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1458 | if (OldClass->StoreCount == 0) { |
| 1459 | if (OldClass->RepStoredValue != nullptr) |
| 1460 | OldClass->RepStoredValue = nullptr; |
| 1461 | if (OldClass->RepMemoryAccess != nullptr) |
| 1462 | OldClass->RepMemoryAccess = nullptr; |
| 1463 | } |
| 1464 | |
| 1465 | // If we destroy the old access leader, we have to effectively destroy the |
| 1466 | // congruence class. When it comes to scalars, anything with the same value |
| 1467 | // is as good as any other. That means that one leader is as good as |
| 1468 | // another, and as long as you have some leader for the value, you are |
| 1469 | // good.. When it comes to *memory states*, only one particular thing really |
| 1470 | // represents the definition of a given memory state. Once it goes away, we |
| 1471 | // need to re-evaluate which pieces of memory are really still |
| 1472 | // equivalent. The best way to do this is to re-value number things. The |
| 1473 | // only way to really make that happen is to destroy the rest of the class. |
| 1474 | // In order to effectively destroy the class, we reset ExpressionToClass for |
| 1475 | // each by using the ValueToExpression mapping. The members later get |
| 1476 | // marked as touched due to the leader change. We will create new |
| 1477 | // congruence classes, and the pieces that are still equivalent will end |
| 1478 | // back together in a new class. If this becomes too expensive, it is |
| 1479 | // possible to use a versioning scheme for the congruence classes to avoid |
| 1480 | // the expressions finding this old class. |
| 1481 | if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) { |
| 1482 | DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID |
| 1483 | << " because memory access leader changed"); |
| 1484 | for (auto Member : OldClass->Members) |
| 1485 | ExpressionToClass.erase(ValueToExpression.lookup(Member)); |
| 1486 | } |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 1487 | |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1488 | // We don't need to sort members if there is only 1, and we don't care about |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1489 | // sorting the TOP class because everything either gets out of it or is |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1490 | // unreachable. |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1491 | if (OldClass->Members.size() == 1 || OldClass == TOPClass) { |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1492 | OldClass->RepLeader = *(OldClass->Members.begin()); |
| 1493 | } else if (OldClass->NextLeader.first) { |
| 1494 | ++NumGVNAvoidedSortedLeaderChanges; |
| 1495 | OldClass->RepLeader = OldClass->NextLeader.first; |
| 1496 | OldClass->NextLeader = {nullptr, ~0U}; |
| 1497 | } else { |
| 1498 | ++NumGVNSortedLeaderChanges; |
| 1499 | // TODO: If this ends up to slow, we can maintain a dual structure for |
| 1500 | // member testing/insertion, or keep things mostly sorted, and sort only |
| 1501 | // here, or .... |
| 1502 | std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U}; |
| 1503 | for (const auto X : OldClass->Members) { |
| 1504 | auto DFSNum = InstrDFS.lookup(X); |
| 1505 | if (DFSNum < MinDFS.second) |
| 1506 | MinDFS = {X, DFSNum}; |
| 1507 | } |
| 1508 | OldClass->RepLeader = MinDFS.first; |
| 1509 | } |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1510 | markLeaderChangeTouched(OldClass); |
Daniel Berlin | 32f8d56 | 2017-01-07 16:55:14 +0000 | [diff] [blame] | 1511 | } |
| 1512 | } |
| 1513 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1514 | // Perform congruence finding on a given value numbering expression. |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1515 | void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) { |
| 1516 | ValueToExpression[I] = E; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1517 | // This is guaranteed to return something, since it will at least find |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 1518 | // TOP. |
Daniel Berlin | 32f8d56 | 2017-01-07 16:55:14 +0000 | [diff] [blame] | 1519 | |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1520 | CongruenceClass *IClass = ValueToClass[I]; |
| 1521 | assert(IClass && "Should have found a IClass"); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1522 | // Dead classes should have been eliminated from the mapping. |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1523 | assert(!IClass->Dead && "Found a dead class"); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1524 | |
| 1525 | CongruenceClass *EClass; |
Daniel Berlin | 02c6b17 | 2017-01-02 18:00:53 +0000 | [diff] [blame] | 1526 | if (const auto *VE = dyn_cast<VariableExpression>(E)) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1527 | EClass = ValueToClass[VE->getVariableValue()]; |
| 1528 | } else { |
| 1529 | auto lookupResult = ExpressionToClass.insert({E, nullptr}); |
| 1530 | |
| 1531 | // If it's not in the value table, create a new congruence class. |
| 1532 | if (lookupResult.second) { |
Davide Italiano | 0e71480 | 2016-12-28 14:00:11 +0000 | [diff] [blame] | 1533 | CongruenceClass *NewClass = createCongruenceClass(nullptr, E); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1534 | auto place = lookupResult.first; |
| 1535 | place->second = NewClass; |
| 1536 | |
| 1537 | // Constants and variables should always be made the leader. |
Daniel Berlin | 32f8d56 | 2017-01-07 16:55:14 +0000 | [diff] [blame] | 1538 | if (const auto *CE = dyn_cast<ConstantExpression>(E)) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1539 | NewClass->RepLeader = CE->getConstantValue(); |
Daniel Berlin | 32f8d56 | 2017-01-07 16:55:14 +0000 | [diff] [blame] | 1540 | } else if (const auto *SE = dyn_cast<StoreExpression>(E)) { |
| 1541 | StoreInst *SI = SE->getStoreInst(); |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 1542 | NewClass->RepLeader = SI; |
Daniel Berlin | 808e3ff | 2017-01-31 22:31:56 +0000 | [diff] [blame] | 1543 | NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand()); |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1544 | // The RepMemoryAccess field will be filled in properly by the |
| 1545 | // moveValueToNewCongruenceClass call. |
Daniel Berlin | 32f8d56 | 2017-01-07 16:55:14 +0000 | [diff] [blame] | 1546 | } else { |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1547 | NewClass->RepLeader = I; |
Daniel Berlin | 32f8d56 | 2017-01-07 16:55:14 +0000 | [diff] [blame] | 1548 | } |
| 1549 | assert(!isa<VariableExpression>(E) && |
| 1550 | "VariableExpression should have been handled already"); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1551 | |
| 1552 | EClass = NewClass; |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1553 | DEBUG(dbgs() << "Created new congruence class for " << *I |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1554 | << " using expression " << *E << " at " << NewClass->ID |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 1555 | << " and leader " << *(NewClass->RepLeader)); |
| 1556 | if (NewClass->RepStoredValue) |
| 1557 | DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue)); |
| 1558 | DEBUG(dbgs() << "\n"); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1559 | DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n"); |
| 1560 | } else { |
| 1561 | EClass = lookupResult.first->second; |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1562 | if (isa<ConstantExpression>(E)) |
| 1563 | assert(isa<Constant>(EClass->RepLeader) && |
| 1564 | "Any class with a constant expression should have a " |
| 1565 | "constant leader"); |
| 1566 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1567 | assert(EClass && "Somehow don't have an eclass"); |
| 1568 | |
| 1569 | assert(!EClass->Dead && "We accidentally looked up a dead class"); |
| 1570 | } |
| 1571 | } |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1572 | bool ClassChanged = IClass != EClass; |
| 1573 | bool LeaderChanged = LeaderChanges.erase(I); |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1574 | if (ClassChanged || LeaderChanged) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1575 | DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E |
| 1576 | << "\n"); |
| 1577 | |
Daniel Berlin | 3a1bd02 | 2017-01-11 20:22:05 +0000 | [diff] [blame] | 1578 | if (ClassChanged) |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1579 | moveValueToNewCongruenceClass(I, IClass, EClass); |
| 1580 | markUsersTouched(I); |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1581 | if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) |
Daniel Berlin | c0431fd | 2017-01-13 22:40:01 +0000 | [diff] [blame] | 1582 | markMemoryUsersTouched(MA); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1583 | if (auto *CI = dyn_cast<CmpInst>(I)) |
| 1584 | markPredicateUsersTouched(CI); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1585 | } |
| 1586 | } |
| 1587 | |
| 1588 | // Process the fact that Edge (from, to) is reachable, including marking |
| 1589 | // any newly reachable blocks and instructions for processing. |
| 1590 | void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) { |
| 1591 | // Check if the Edge was reachable before. |
| 1592 | if (ReachableEdges.insert({From, To}).second) { |
| 1593 | // If this block wasn't reachable before, all instructions are touched. |
| 1594 | if (ReachableBlocks.insert(To).second) { |
| 1595 | DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n"); |
| 1596 | const auto &InstRange = BlockInstRange.lookup(To); |
| 1597 | TouchedInstructions.set(InstRange.first, InstRange.second); |
| 1598 | } else { |
| 1599 | DEBUG(dbgs() << "Block " << getBlockName(To) |
| 1600 | << " was reachable, but new edge {" << getBlockName(From) |
| 1601 | << "," << getBlockName(To) << "} to it found\n"); |
| 1602 | |
| 1603 | // We've made an edge reachable to an existing block, which may |
| 1604 | // impact predicates. Otherwise, only mark the phi nodes as touched, as |
| 1605 | // they are the only thing that depend on new edges. Anything using their |
| 1606 | // values will get propagated to if necessary. |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1607 | if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To)) |
Daniel Berlin | aac5684 | 2017-01-15 09:18:41 +0000 | [diff] [blame] | 1608 | TouchedInstructions.set(InstrDFS.lookup(MemPhi)); |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1609 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1610 | auto BI = To->begin(); |
| 1611 | while (isa<PHINode>(BI)) { |
Daniel Berlin | aac5684 | 2017-01-15 09:18:41 +0000 | [diff] [blame] | 1612 | TouchedInstructions.set(InstrDFS.lookup(&*BI)); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1613 | ++BI; |
| 1614 | } |
| 1615 | } |
| 1616 | } |
| 1617 | } |
| 1618 | |
| 1619 | // Given a predicate condition (from a switch, cmp, or whatever) and a block, |
| 1620 | // see if we know some constant value for it already. |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1621 | Value *NewGVN::findConditionEquivalence(Value *Cond) const { |
Daniel Berlin | 203f47b | 2017-01-31 22:31:53 +0000 | [diff] [blame] | 1622 | auto Result = lookupOperandLeader(Cond); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1623 | if (isa<Constant>(Result)) |
| 1624 | return Result; |
| 1625 | return nullptr; |
| 1626 | } |
| 1627 | |
| 1628 | // Process the outgoing edges of a block for reachability. |
| 1629 | void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) { |
| 1630 | // Evaluate reachability of terminator instruction. |
| 1631 | BranchInst *BR; |
| 1632 | if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) { |
| 1633 | Value *Cond = BR->getCondition(); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1634 | Value *CondEvaluated = findConditionEquivalence(Cond); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1635 | if (!CondEvaluated) { |
| 1636 | if (auto *I = dyn_cast<Instruction>(Cond)) { |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1637 | const Expression *E = createExpression(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1638 | if (const auto *CE = dyn_cast<ConstantExpression>(E)) { |
| 1639 | CondEvaluated = CE->getConstantValue(); |
| 1640 | } |
| 1641 | } else if (isa<ConstantInt>(Cond)) { |
| 1642 | CondEvaluated = Cond; |
| 1643 | } |
| 1644 | } |
| 1645 | ConstantInt *CI; |
| 1646 | BasicBlock *TrueSucc = BR->getSuccessor(0); |
| 1647 | BasicBlock *FalseSucc = BR->getSuccessor(1); |
| 1648 | if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) { |
| 1649 | if (CI->isOne()) { |
| 1650 | DEBUG(dbgs() << "Condition for Terminator " << *TI |
| 1651 | << " evaluated to true\n"); |
| 1652 | updateReachableEdge(B, TrueSucc); |
| 1653 | } else if (CI->isZero()) { |
| 1654 | DEBUG(dbgs() << "Condition for Terminator " << *TI |
| 1655 | << " evaluated to false\n"); |
| 1656 | updateReachableEdge(B, FalseSucc); |
| 1657 | } |
| 1658 | } else { |
| 1659 | updateReachableEdge(B, TrueSucc); |
| 1660 | updateReachableEdge(B, FalseSucc); |
| 1661 | } |
| 1662 | } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { |
| 1663 | // For switches, propagate the case values into the case |
| 1664 | // destinations. |
| 1665 | |
| 1666 | // Remember how many outgoing edges there are to every successor. |
| 1667 | SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges; |
| 1668 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1669 | Value *SwitchCond = SI->getCondition(); |
Daniel Berlin | 97718e6 | 2017-01-31 22:32:03 +0000 | [diff] [blame] | 1670 | Value *CondEvaluated = findConditionEquivalence(SwitchCond); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1671 | // See if we were able to turn this switch statement into a constant. |
| 1672 | if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 1673 | auto *CondVal = cast<ConstantInt>(CondEvaluated); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1674 | // We should be able to get case value for this. |
| 1675 | auto CaseVal = SI->findCaseValue(CondVal); |
| 1676 | if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) { |
| 1677 | // We proved the value is outside of the range of the case. |
| 1678 | // We can't do anything other than mark the default dest as reachable, |
| 1679 | // and go home. |
| 1680 | updateReachableEdge(B, SI->getDefaultDest()); |
| 1681 | return; |
| 1682 | } |
| 1683 | // Now get where it goes and mark it reachable. |
| 1684 | BasicBlock *TargetBlock = CaseVal.getCaseSuccessor(); |
| 1685 | updateReachableEdge(B, TargetBlock); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1686 | } else { |
| 1687 | for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { |
| 1688 | BasicBlock *TargetBlock = SI->getSuccessor(i); |
| 1689 | ++SwitchEdges[TargetBlock]; |
| 1690 | updateReachableEdge(B, TargetBlock); |
| 1691 | } |
| 1692 | } |
| 1693 | } else { |
| 1694 | // Otherwise this is either unconditional, or a type we have no |
| 1695 | // idea about. Just mark successors as reachable. |
| 1696 | for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { |
| 1697 | BasicBlock *TargetBlock = TI->getSuccessor(i); |
| 1698 | updateReachableEdge(B, TargetBlock); |
| 1699 | } |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1700 | |
| 1701 | // This also may be a memory defining terminator, in which case, set it |
| 1702 | // equivalent to nothing. |
| 1703 | if (MemoryAccess *MA = MSSA->getMemoryAccess(TI)) |
| 1704 | setMemoryAccessEquivTo(MA, nullptr); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1705 | } |
| 1706 | } |
| 1707 | |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1708 | // The algorithm initially places the values of the routine in the TOP |
| 1709 | // congruence class. The leader of TOP is the undetermined value `undef`. |
| 1710 | // When the algorithm has finished, values still in TOP are unreachable. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1711 | void NewGVN::initializeCongruenceClasses(Function &F) { |
| 1712 | // FIXME now i can't remember why this is 2 |
| 1713 | NextCongruenceNum = 2; |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1714 | // Initialize all other instructions to be in TOP class. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1715 | CongruenceClass::MemberSet InitialValues; |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1716 | TOPClass = createCongruenceClass(nullptr, nullptr); |
| 1717 | TOPClass->RepMemoryAccess = MSSA->getLiveOnEntryDef(); |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1718 | for (auto &B : F) { |
| 1719 | if (auto *MP = MSSA->getMemoryAccess(&B)) |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1720 | MemoryAccessToClass[MP] = TOPClass; |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1721 | |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 1722 | for (auto &I : B) { |
Daniel Berlin | 22a4a01 | 2017-02-11 15:20:15 +0000 | [diff] [blame] | 1723 | // Don't insert void terminators into the class. We don't value number |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1724 | // them, and they just end up sitting in TOP. |
Daniel Berlin | 22a4a01 | 2017-02-11 15:20:15 +0000 | [diff] [blame] | 1725 | if (isa<TerminatorInst>(I) && I.getType()->isVoidTy()) |
| 1726 | continue; |
| 1727 | InitialValues.insert(&I); |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1728 | ValueToClass[&I] = TOPClass; |
Daniel Berlin | 22a4a01 | 2017-02-11 15:20:15 +0000 | [diff] [blame] | 1729 | |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1730 | // All memory accesses are equivalent to live on entry to start. They must |
| 1731 | // be initialized to something so that initial changes are noticed. For |
| 1732 | // the maximal answer, we initialize them all to be the same as |
| 1733 | // liveOnEntry. Note that to save time, we only initialize the |
| 1734 | // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no |
| 1735 | // other expression can generate a memory equivalence. If we start |
| 1736 | // handling memcpy/etc, we can expand this. |
Davide Italiano | eac05f6 | 2017-01-11 23:41:24 +0000 | [diff] [blame] | 1737 | if (isa<StoreInst>(&I)) { |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1738 | MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = TOPClass; |
| 1739 | ++TOPClass->StoreCount; |
| 1740 | assert(TOPClass->StoreCount > 0); |
Davide Italiano | eac05f6 | 2017-01-11 23:41:24 +0000 | [diff] [blame] | 1741 | } |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 1742 | } |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1743 | } |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1744 | TOPClass->Members.swap(InitialValues); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1745 | |
| 1746 | // Initialize arguments to be in their own unique congruence classes |
| 1747 | for (auto &FA : F.args()) |
| 1748 | createSingletonCongruenceClass(&FA); |
| 1749 | } |
| 1750 | |
| 1751 | void NewGVN::cleanupTables() { |
| 1752 | for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) { |
| 1753 | DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has " |
| 1754 | << CongruenceClasses[i]->Members.size() << " members\n"); |
| 1755 | // Make sure we delete the congruence class (probably worth switching to |
| 1756 | // a unique_ptr at some point. |
| 1757 | delete CongruenceClasses[i]; |
Davide Italiano | 0e71480 | 2016-12-28 14:00:11 +0000 | [diff] [blame] | 1758 | CongruenceClasses[i] = nullptr; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1759 | } |
| 1760 | |
| 1761 | ValueToClass.clear(); |
| 1762 | ArgRecycler.clear(ExpressionAllocator); |
| 1763 | ExpressionAllocator.Reset(); |
| 1764 | CongruenceClasses.clear(); |
| 1765 | ExpressionToClass.clear(); |
| 1766 | ValueToExpression.clear(); |
| 1767 | ReachableBlocks.clear(); |
| 1768 | ReachableEdges.clear(); |
| 1769 | #ifndef NDEBUG |
| 1770 | ProcessedCount.clear(); |
| 1771 | #endif |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1772 | InstrDFS.clear(); |
| 1773 | InstructionsToErase.clear(); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1774 | DFSToInstr.clear(); |
| 1775 | BlockInstRange.clear(); |
| 1776 | TouchedInstructions.clear(); |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1777 | MemoryAccessToClass.clear(); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1778 | PredicateToUsers.clear(); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1779 | } |
| 1780 | |
| 1781 | std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B, |
| 1782 | unsigned Start) { |
| 1783 | unsigned End = Start; |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1784 | if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) { |
| 1785 | InstrDFS[MemPhi] = End++; |
Piotr Padlewski | 6c37d29 | 2016-12-28 23:24:02 +0000 | [diff] [blame] | 1786 | DFSToInstr.emplace_back(MemPhi); |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1787 | } |
| 1788 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1789 | for (auto &I : *B) { |
Daniel Berlin | 856fa14 | 2017-03-06 18:42:27 +0000 | [diff] [blame] | 1790 | // There's no need to call isInstructionTriviallyDead more than once on |
| 1791 | // an instruction. Therefore, once we know that an instruction is dead |
| 1792 | // we change its DFS number so that it doesn't get value numbered. |
| 1793 | if (isInstructionTriviallyDead(&I, TLI)) { |
| 1794 | InstrDFS[&I] = 0; |
| 1795 | DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n"); |
| 1796 | markInstructionForDeletion(&I); |
| 1797 | continue; |
| 1798 | } |
| 1799 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1800 | InstrDFS[&I] = End++; |
Piotr Padlewski | 6c37d29 | 2016-12-28 23:24:02 +0000 | [diff] [blame] | 1801 | DFSToInstr.emplace_back(&I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1802 | } |
| 1803 | |
| 1804 | // All of the range functions taken half-open ranges (open on the end side). |
| 1805 | // So we do not subtract one from count, because at this point it is one |
| 1806 | // greater than the last instruction. |
| 1807 | return std::make_pair(Start, End); |
| 1808 | } |
| 1809 | |
| 1810 | void NewGVN::updateProcessedCount(Value *V) { |
| 1811 | #ifndef NDEBUG |
| 1812 | if (ProcessedCount.count(V) == 0) { |
| 1813 | ProcessedCount.insert({V, 1}); |
| 1814 | } else { |
Davide Italiano | 7cf29dc | 2017-01-14 20:13:18 +0000 | [diff] [blame] | 1815 | ++ProcessedCount[V]; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1816 | assert(ProcessedCount[V] < 100 && |
Davide Italiano | 75e39f9 | 2016-12-30 15:01:17 +0000 | [diff] [blame] | 1817 | "Seem to have processed the same Value a lot"); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1818 | } |
| 1819 | #endif |
| 1820 | } |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1821 | // Evaluate MemoryPhi nodes symbolically, just like PHI nodes |
| 1822 | void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) { |
| 1823 | // If all the arguments are the same, the MemoryPhi has the same value as the |
| 1824 | // argument. |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 1825 | // Filter out unreachable blocks and self phis from our operands. |
Daniel Berlin | 41b3916 | 2017-03-18 15:41:36 +0000 | [diff] [blame] | 1826 | const BasicBlock *PHIBlock = MP->getBlock(); |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1827 | auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) { |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 1828 | return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP && |
| 1829 | !isMemoryAccessTop(cast<MemoryAccess>(U)) && |
Daniel Berlin | 41b3916 | 2017-03-18 15:41:36 +0000 | [diff] [blame] | 1830 | ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock}); |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1831 | }); |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 1832 | // If all that is left is nothing, our memoryphi is undef. We keep it as |
| 1833 | // InitialClass. Note: The only case this should happen is if we have at |
| 1834 | // least one self-argument. |
| 1835 | if (Filtered.begin() == Filtered.end()) { |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 1836 | if (setMemoryAccessEquivTo(MP, TOPClass)) |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 1837 | markMemoryUsersTouched(MP); |
| 1838 | return; |
| 1839 | } |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1840 | |
| 1841 | // Transform the remaining operands into operand leaders. |
| 1842 | // FIXME: mapped_iterator should have a range version. |
| 1843 | auto LookupFunc = [&](const Use &U) { |
| 1844 | return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)); |
| 1845 | }; |
| 1846 | auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc); |
| 1847 | auto MappedEnd = map_iterator(Filtered.end(), LookupFunc); |
| 1848 | |
| 1849 | // and now check if all the elements are equal. |
| 1850 | // Sadly, we can't use std::equals since these are random access iterators. |
| 1851 | MemoryAccess *AllSameValue = *MappedBegin; |
| 1852 | ++MappedBegin; |
| 1853 | bool AllEqual = std::all_of( |
| 1854 | MappedBegin, MappedEnd, |
| 1855 | [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; }); |
| 1856 | |
| 1857 | if (AllEqual) |
| 1858 | DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n"); |
| 1859 | else |
| 1860 | DEBUG(dbgs() << "Memory Phi value numbered to itself\n"); |
| 1861 | |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1862 | if (setMemoryAccessEquivTo( |
| 1863 | MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr)) |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1864 | markMemoryUsersTouched(MP); |
| 1865 | } |
| 1866 | |
| 1867 | // Value number a single instruction, symbolically evaluating, performing |
| 1868 | // congruence finding, and updating mappings. |
| 1869 | void NewGVN::valueNumberInstruction(Instruction *I) { |
| 1870 | DEBUG(dbgs() << "Processing instruction " << *I << "\n"); |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1871 | if (!I->isTerminator()) { |
Daniel Berlin | 283a608 | 2017-03-01 19:59:26 +0000 | [diff] [blame] | 1872 | const Expression *Symbolized = nullptr; |
| 1873 | if (DebugCounter::shouldExecute(VNCounter)) { |
| 1874 | Symbolized = performSymbolicEvaluation(I); |
| 1875 | } else { |
Daniel Berlin | 343576a | 2017-03-06 18:42:39 +0000 | [diff] [blame] | 1876 | // Mark the instruction as unused so we don't value number it again. |
| 1877 | InstrDFS[I] = 0; |
Daniel Berlin | 283a608 | 2017-03-01 19:59:26 +0000 | [diff] [blame] | 1878 | } |
Daniel Berlin | 02c6b17 | 2017-01-02 18:00:53 +0000 | [diff] [blame] | 1879 | // If we couldn't come up with a symbolic expression, use the unknown |
| 1880 | // expression |
| 1881 | if (Symbolized == nullptr) |
| 1882 | Symbolized = createUnknownExpression(I); |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1883 | performCongruenceFinding(I, Symbolized); |
| 1884 | } else { |
Daniel Berlin | 02c6b17 | 2017-01-02 18:00:53 +0000 | [diff] [blame] | 1885 | // Handle terminators that return values. All of them produce values we |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 1886 | // don't currently understand. We don't place non-value producing |
| 1887 | // terminators in a class. |
Daniel Berlin | 25f05b0 | 2017-01-02 18:22:38 +0000 | [diff] [blame] | 1888 | if (!I->getType()->isVoidTy()) { |
Daniel Berlin | 02c6b17 | 2017-01-02 18:00:53 +0000 | [diff] [blame] | 1889 | auto *Symbolized = createUnknownExpression(I); |
| 1890 | performCongruenceFinding(I, Symbolized); |
| 1891 | } |
Daniel Berlin | d7c12ee | 2016-12-25 22:23:49 +0000 | [diff] [blame] | 1892 | processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent()); |
| 1893 | } |
| 1894 | } |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 1895 | |
Daniel Berlin | f6eba4b | 2017-01-11 20:22:36 +0000 | [diff] [blame] | 1896 | // Check if there is a path, using single or equal argument phi nodes, from |
| 1897 | // First to Second. |
| 1898 | bool NewGVN::singleReachablePHIPath(const MemoryAccess *First, |
| 1899 | const MemoryAccess *Second) const { |
| 1900 | if (First == Second) |
| 1901 | return true; |
| 1902 | |
| 1903 | if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) { |
| 1904 | auto *DefAccess = FirstDef->getDefiningAccess(); |
| 1905 | return singleReachablePHIPath(DefAccess, Second); |
| 1906 | } else { |
| 1907 | auto *MP = cast<MemoryPhi>(First); |
| 1908 | auto ReachableOperandPred = [&](const Use &U) { |
Daniel Berlin | 41b3916 | 2017-03-18 15:41:36 +0000 | [diff] [blame] | 1909 | return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()}); |
Daniel Berlin | f6eba4b | 2017-01-11 20:22:36 +0000 | [diff] [blame] | 1910 | }; |
| 1911 | auto FilteredPhiArgs = |
| 1912 | make_filter_range(MP->operands(), ReachableOperandPred); |
| 1913 | SmallVector<const Value *, 32> OperandList; |
| 1914 | std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(), |
| 1915 | std::back_inserter(OperandList)); |
| 1916 | bool Okay = OperandList.size() == 1; |
| 1917 | if (!Okay) |
| 1918 | Okay = std::equal(OperandList.begin(), OperandList.end(), |
| 1919 | OperandList.begin()); |
| 1920 | if (Okay) |
| 1921 | return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second); |
| 1922 | return false; |
| 1923 | } |
| 1924 | } |
| 1925 | |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1926 | // Verify the that the memory equivalence table makes sense relative to the |
Daniel Berlin | f6eba4b | 2017-01-11 20:22:36 +0000 | [diff] [blame] | 1927 | // congruence classes. Note that this checking is not perfect, and is currently |
Davide Italiano | ed67f19 | 2017-01-14 20:15:04 +0000 | [diff] [blame] | 1928 | // subject to very rare false negatives. It is only useful for |
| 1929 | // testing/debugging. |
Daniel Berlin | f6eba4b | 2017-01-11 20:22:36 +0000 | [diff] [blame] | 1930 | void NewGVN::verifyMemoryCongruency() const { |
Davide Italiano | e9781e7 | 2017-03-25 02:40:02 +0000 | [diff] [blame^] | 1931 | #ifndef NDEBUG |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1932 | // Anything equivalent in the memory access table should be in the same |
| 1933 | // congruence class. |
| 1934 | |
| 1935 | // Filter out the unreachable and trivially dead entries, because they may |
| 1936 | // never have been updated if the instructions were not processed. |
| 1937 | auto ReachableAccessPred = |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1938 | [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) { |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1939 | bool Result = ReachableBlocks.count(Pair.first->getBlock()); |
| 1940 | if (!Result) |
| 1941 | return false; |
| 1942 | if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first)) |
| 1943 | return !isInstructionTriviallyDead(MemDef->getMemoryInst()); |
| 1944 | return true; |
| 1945 | }; |
| 1946 | |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1947 | auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred); |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1948 | for (auto KV : Filtered) { |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1949 | // Unreachable instructions may not have changed because we never process |
| 1950 | // them. |
| 1951 | if (!ReachableBlocks.count(KV.first->getBlock())) |
| 1952 | continue; |
| 1953 | if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) { |
Daniel Berlin | 1ea5f32 | 2017-01-26 22:21:48 +0000 | [diff] [blame] | 1954 | auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess); |
Davide Italiano | 67ada75 | 2017-01-02 19:03:16 +0000 | [diff] [blame] | 1955 | if (FirstMUD && SecondMUD) |
Davide Italiano | ff69405 | 2017-01-11 21:58:42 +0000 | [diff] [blame] | 1956 | assert((singleReachablePHIPath(FirstMUD, SecondMUD) || |
Davide Italiano | ed67f19 | 2017-01-14 20:15:04 +0000 | [diff] [blame] | 1957 | ValueToClass.lookup(FirstMUD->getMemoryInst()) == |
| 1958 | ValueToClass.lookup(SecondMUD->getMemoryInst())) && |
| 1959 | "The instructions for these memory operations should have " |
| 1960 | "been in the same congruence class or reachable through" |
| 1961 | "a single argument phi"); |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1962 | } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) { |
| 1963 | |
| 1964 | // We can only sanely verify that MemoryDefs in the operand list all have |
| 1965 | // the same class. |
| 1966 | auto ReachableOperandPred = [&](const Use &U) { |
Daniel Berlin | 41b3916 | 2017-03-18 15:41:36 +0000 | [diff] [blame] | 1967 | return ReachableEdges.count( |
| 1968 | {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) && |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1969 | isa<MemoryDef>(U); |
| 1970 | |
| 1971 | }; |
| 1972 | // All arguments should in the same class, ignoring unreachable arguments |
| 1973 | auto FilteredPhiArgs = |
| 1974 | make_filter_range(FirstMP->operands(), ReachableOperandPred); |
| 1975 | SmallVector<const CongruenceClass *, 16> PhiOpClasses; |
| 1976 | std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(), |
| 1977 | std::back_inserter(PhiOpClasses), [&](const Use &U) { |
| 1978 | const MemoryDef *MD = cast<MemoryDef>(U); |
| 1979 | return ValueToClass.lookup(MD->getMemoryInst()); |
| 1980 | }); |
| 1981 | assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(), |
| 1982 | PhiOpClasses.begin()) && |
| 1983 | "All MemoryPhi arguments should be in the same class"); |
| 1984 | } |
| 1985 | } |
Davide Italiano | e9781e7 | 2017-03-25 02:40:02 +0000 | [diff] [blame^] | 1986 | #endif |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 1987 | } |
| 1988 | |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 1989 | // Verify that the sparse propagation we did actually found the maximal fixpoint |
| 1990 | // We do this by storing the value to class mapping, touching all instructions, |
| 1991 | // and redoing the iteration to see if anything changed. |
| 1992 | void NewGVN::verifyIterationSettled(Function &F) { |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 1993 | #ifndef NDEBUG |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 1994 | if (DebugCounter::isCounterSet(VNCounter)) |
| 1995 | DebugCounter::setCounterValue(VNCounter, StartingVNCounter); |
| 1996 | |
| 1997 | // Note that we have to store the actual classes, as we may change existing |
| 1998 | // classes during iteration. This is because our memory iteration propagation |
| 1999 | // is not perfect, and so may waste a little work. But it should generate |
| 2000 | // exactly the same congruence classes we have now, with different IDs. |
| 2001 | std::map<const Value *, CongruenceClass> BeforeIteration; |
| 2002 | |
| 2003 | for (auto &KV : ValueToClass) { |
| 2004 | if (auto *I = dyn_cast<Instruction>(KV.first)) |
| 2005 | // Skip unused/dead instructions. |
| 2006 | if (InstrDFS.lookup(I) == 0) |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 2007 | continue; |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 2008 | BeforeIteration.insert({KV.first, *KV.second}); |
| 2009 | } |
| 2010 | |
| 2011 | TouchedInstructions.set(); |
| 2012 | TouchedInstructions.reset(0); |
| 2013 | iterateTouchedInstructions(); |
| 2014 | DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>> |
| 2015 | EqualClasses; |
| 2016 | for (const auto &KV : ValueToClass) { |
| 2017 | if (auto *I = dyn_cast<Instruction>(KV.first)) |
| 2018 | // Skip unused/dead instructions. |
| 2019 | if (InstrDFS.lookup(I) == 0) |
| 2020 | continue; |
| 2021 | // We could sink these uses, but i think this adds a bit of clarity here as |
| 2022 | // to what we are comparing. |
| 2023 | auto *BeforeCC = &BeforeIteration.find(KV.first)->second; |
| 2024 | auto *AfterCC = KV.second; |
| 2025 | // Note that the classes can't change at this point, so we memoize the set |
| 2026 | // that are equal. |
| 2027 | if (!EqualClasses.count({BeforeCC, AfterCC})) { |
| 2028 | assert(areClassesEquivalent(BeforeCC, AfterCC) && |
| 2029 | "Value number changed after main loop completed!"); |
| 2030 | EqualClasses.insert({BeforeCC, AfterCC}); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 2031 | } |
| 2032 | } |
| 2033 | #endif |
| 2034 | } |
| 2035 | |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 2036 | // This is the main value numbering loop, it iterates over the initial touched |
| 2037 | // instruction set, propagating value numbers, marking things touched, etc, |
| 2038 | // until the set of touched instructions is completely empty. |
| 2039 | void NewGVN::iterateTouchedInstructions() { |
| 2040 | unsigned int Iterations = 0; |
| 2041 | // Figure out where touchedinstructions starts |
| 2042 | int FirstInstr = TouchedInstructions.find_first(); |
| 2043 | // Nothing set, nothing to iterate, just return. |
| 2044 | if (FirstInstr == -1) |
| 2045 | return; |
| 2046 | BasicBlock *LastBlock = getBlockForValue(DFSToInstr[FirstInstr]); |
| 2047 | while (TouchedInstructions.any()) { |
| 2048 | ++Iterations; |
| 2049 | // Walk through all the instructions in all the blocks in RPO. |
| 2050 | // TODO: As we hit a new block, we should push and pop equalities into a |
| 2051 | // table lookupOperandLeader can use, to catch things PredicateInfo |
| 2052 | // might miss, like edge-only equivalences. |
| 2053 | for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1; |
| 2054 | InstrNum = TouchedInstructions.find_next(InstrNum)) { |
| 2055 | |
| 2056 | // This instruction was found to be dead. We don't bother looking |
| 2057 | // at it again. |
| 2058 | if (InstrNum == 0) { |
| 2059 | TouchedInstructions.reset(InstrNum); |
| 2060 | continue; |
| 2061 | } |
| 2062 | |
| 2063 | Value *V = DFSToInstr[InstrNum]; |
| 2064 | BasicBlock *CurrBlock = getBlockForValue(V); |
| 2065 | |
| 2066 | // If we hit a new block, do reachability processing. |
| 2067 | if (CurrBlock != LastBlock) { |
| 2068 | LastBlock = CurrBlock; |
| 2069 | bool BlockReachable = ReachableBlocks.count(CurrBlock); |
| 2070 | const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock); |
| 2071 | |
| 2072 | // If it's not reachable, erase any touched instructions and move on. |
| 2073 | if (!BlockReachable) { |
| 2074 | TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second); |
| 2075 | DEBUG(dbgs() << "Skipping instructions in block " |
| 2076 | << getBlockName(CurrBlock) |
| 2077 | << " because it is unreachable\n"); |
| 2078 | continue; |
| 2079 | } |
| 2080 | updateProcessedCount(CurrBlock); |
| 2081 | } |
| 2082 | |
| 2083 | if (auto *MP = dyn_cast<MemoryPhi>(V)) { |
| 2084 | DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n"); |
| 2085 | valueNumberMemoryPhi(MP); |
| 2086 | } else if (auto *I = dyn_cast<Instruction>(V)) { |
| 2087 | valueNumberInstruction(I); |
| 2088 | } else { |
| 2089 | llvm_unreachable("Should have been a MemoryPhi or Instruction"); |
| 2090 | } |
| 2091 | updateProcessedCount(V); |
| 2092 | // Reset after processing (because we may mark ourselves as touched when |
| 2093 | // we propagate equalities). |
| 2094 | TouchedInstructions.reset(InstrNum); |
| 2095 | } |
| 2096 | } |
| 2097 | NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations); |
| 2098 | } |
| 2099 | |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 2100 | // This is the main transformation entry point. |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 2101 | bool NewGVN::runGVN() { |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 2102 | if (DebugCounter::isCounterSet(VNCounter)) |
| 2103 | StartingVNCounter = DebugCounter::getCounterValue(VNCounter); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2104 | bool Changed = false; |
Daniel Berlin | 1529bb9 | 2017-02-11 15:13:49 +0000 | [diff] [blame] | 2105 | NumFuncArgs = F.arg_size(); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2106 | MSSAWalker = MSSA->getWalker(); |
| 2107 | |
| 2108 | // Count number of instructions for sizing of hash tables, and come |
| 2109 | // up with a global dfs numbering for instructions. |
Daniel Berlin | e0bd37e | 2016-12-29 22:15:12 +0000 | [diff] [blame] | 2110 | unsigned ICount = 1; |
| 2111 | // Add an empty instruction to account for the fact that we start at 1 |
| 2112 | DFSToInstr.emplace_back(nullptr); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 2113 | // Note: We want ideal RPO traversal of the blocks, which is not quite the |
| 2114 | // same as dominator tree order, particularly with regard whether backedges |
| 2115 | // get visited first or second, given a block with multiple successors. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2116 | // If we visit in the wrong order, we will end up performing N times as many |
| 2117 | // iterations. |
Daniel Berlin | 6658cc9 | 2016-12-29 01:12:36 +0000 | [diff] [blame] | 2118 | // The dominator tree does guarantee that, for a given dom tree node, it's |
| 2119 | // parent must occur before it in the RPO ordering. Thus, we only need to sort |
| 2120 | // the siblings. |
| 2121 | DenseMap<const DomTreeNode *, unsigned> RPOOrdering; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2122 | ReversePostOrderTraversal<Function *> RPOT(&F); |
Daniel Berlin | 6658cc9 | 2016-12-29 01:12:36 +0000 | [diff] [blame] | 2123 | unsigned Counter = 0; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2124 | for (auto &B : RPOT) { |
Daniel Berlin | 6658cc9 | 2016-12-29 01:12:36 +0000 | [diff] [blame] | 2125 | auto *Node = DT->getNode(B); |
| 2126 | assert(Node && "RPO and Dominator tree should have same reachability"); |
| 2127 | RPOOrdering[Node] = ++Counter; |
| 2128 | } |
| 2129 | // Sort dominator tree children arrays into RPO. |
| 2130 | for (auto &B : RPOT) { |
| 2131 | auto *Node = DT->getNode(B); |
| 2132 | if (Node->getChildren().size() > 1) |
| 2133 | std::sort(Node->begin(), Node->end(), |
| 2134 | [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) { |
| 2135 | return RPOOrdering[A] < RPOOrdering[B]; |
| 2136 | }); |
| 2137 | } |
| 2138 | |
| 2139 | // Now a standard depth first ordering of the domtree is equivalent to RPO. |
| 2140 | auto DFI = df_begin(DT->getRootNode()); |
| 2141 | for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) { |
| 2142 | BasicBlock *B = DFI->getBlock(); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2143 | const auto &BlockRange = assignDFSNumbers(B, ICount); |
| 2144 | BlockInstRange.insert({B, BlockRange}); |
| 2145 | ICount += BlockRange.second - BlockRange.first; |
| 2146 | } |
| 2147 | |
| 2148 | // Handle forward unreachable blocks and figure out which blocks |
| 2149 | // have single preds. |
| 2150 | for (auto &B : F) { |
| 2151 | // Assign numbers to unreachable blocks. |
Daniel Berlin | 6658cc9 | 2016-12-29 01:12:36 +0000 | [diff] [blame] | 2152 | if (!DFI.nodeVisited(DT->getNode(&B))) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2153 | const auto &BlockRange = assignDFSNumbers(&B, ICount); |
| 2154 | BlockInstRange.insert({&B, BlockRange}); |
| 2155 | ICount += BlockRange.second - BlockRange.first; |
| 2156 | } |
| 2157 | } |
| 2158 | |
Daniel Berlin | e0bd37e | 2016-12-29 22:15:12 +0000 | [diff] [blame] | 2159 | TouchedInstructions.resize(ICount); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2160 | // Ensure we don't end up resizing the expressionToClass map, as |
| 2161 | // that can be quite expensive. At most, we have one expression per |
| 2162 | // instruction. |
Daniel Berlin | e0bd37e | 2016-12-29 22:15:12 +0000 | [diff] [blame] | 2163 | ExpressionToClass.reserve(ICount); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2164 | |
| 2165 | // Initialize the touched instructions to include the entry block. |
| 2166 | const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock()); |
| 2167 | TouchedInstructions.set(InstRange.first, InstRange.second); |
| 2168 | ReachableBlocks.insert(&F.getEntryBlock()); |
| 2169 | |
| 2170 | initializeCongruenceClasses(F); |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 2171 | iterateTouchedInstructions(); |
Daniel Berlin | 589cecc | 2017-01-02 18:00:46 +0000 | [diff] [blame] | 2172 | verifyMemoryCongruency(); |
Daniel Berlin | 06329a9 | 2017-03-18 15:41:40 +0000 | [diff] [blame] | 2173 | verifyIterationSettled(F); |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 2174 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2175 | Changed |= eliminateInstructions(F); |
| 2176 | |
| 2177 | // Delete all instructions marked for deletion. |
| 2178 | for (Instruction *ToErase : InstructionsToErase) { |
| 2179 | if (!ToErase->use_empty()) |
| 2180 | ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType())); |
| 2181 | |
| 2182 | ToErase->eraseFromParent(); |
| 2183 | } |
| 2184 | |
| 2185 | // Delete all unreachable blocks. |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 2186 | auto UnreachableBlockPred = [&](const BasicBlock &BB) { |
| 2187 | return !ReachableBlocks.count(&BB); |
| 2188 | }; |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 2189 | |
| 2190 | for (auto &BB : make_filter_range(F, UnreachableBlockPred)) { |
| 2191 | DEBUG(dbgs() << "We believe block " << getBlockName(&BB) |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 2192 | << " is unreachable\n"); |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 2193 | deleteInstructionsInBlock(&BB); |
| 2194 | Changed = true; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2195 | } |
| 2196 | |
| 2197 | cleanupTables(); |
| 2198 | return Changed; |
| 2199 | } |
| 2200 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2201 | // Return true if V is a value that will always be available (IE can |
| 2202 | // be placed anywhere) in the function. We don't do globals here |
| 2203 | // because they are often worse to put in place. |
| 2204 | // TODO: Separate cost from availability |
| 2205 | static bool alwaysAvailable(Value *V) { |
| 2206 | return isa<Constant>(V) || isa<Argument>(V); |
| 2207 | } |
| 2208 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2209 | struct NewGVN::ValueDFS { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 2210 | int DFSIn = 0; |
| 2211 | int DFSOut = 0; |
| 2212 | int LocalNum = 0; |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2213 | // Only one of Def and U will be set. |
| 2214 | Value *Def = nullptr; |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 2215 | Use *U = nullptr; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2216 | bool operator<(const ValueDFS &Other) const { |
| 2217 | // It's not enough that any given field be less than - we have sets |
| 2218 | // of fields that need to be evaluated together to give a proper ordering. |
| 2219 | // For example, if you have; |
| 2220 | // DFS (1, 3) |
| 2221 | // Val 0 |
| 2222 | // DFS (1, 2) |
| 2223 | // Val 50 |
| 2224 | // We want the second to be less than the first, but if we just go field |
| 2225 | // by field, we will get to Val 0 < Val 50 and say the first is less than |
| 2226 | // the second. We only want it to be less than if the DFS orders are equal. |
| 2227 | // |
| 2228 | // Each LLVM instruction only produces one value, and thus the lowest-level |
| 2229 | // differentiator that really matters for the stack (and what we use as as a |
| 2230 | // replacement) is the local dfs number. |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 2231 | // Everything else in the structure is instruction level, and only affects |
| 2232 | // the order in which we will replace operands of a given instruction. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2233 | // |
| 2234 | // For a given instruction (IE things with equal dfsin, dfsout, localnum), |
| 2235 | // the order of replacement of uses does not matter. |
| 2236 | // IE given, |
| 2237 | // a = 5 |
| 2238 | // b = a + a |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 2239 | // When you hit b, you will have two valuedfs with the same dfsin, out, and |
| 2240 | // localnum. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2241 | // The .val will be the same as well. |
| 2242 | // The .u's will be different. |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 2243 | // You will replace both, and it does not matter what order you replace them |
| 2244 | // in (IE whether you replace operand 2, then operand 1, or operand 1, then |
| 2245 | // operand 2). |
| 2246 | // Similarly for the case of same dfsin, dfsout, localnum, but different |
| 2247 | // .val's |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2248 | // a = 5 |
| 2249 | // b = 6 |
| 2250 | // c = a + b |
Daniel Berlin | 85f91b0 | 2016-12-26 20:06:58 +0000 | [diff] [blame] | 2251 | // in c, we will a valuedfs for a, and one for b,with everything the same |
| 2252 | // but .val and .u. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2253 | // It does not matter what order we replace these operands in. |
| 2254 | // You will always end up with the same IR, and this is guaranteed. |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2255 | return std::tie(DFSIn, DFSOut, LocalNum, Def, U) < |
| 2256 | std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def, |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2257 | Other.U); |
| 2258 | } |
| 2259 | }; |
| 2260 | |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2261 | // This function converts the set of members for a congruence class from values, |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2262 | // to sets of defs and uses with associated DFS info. The total number of |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2263 | // reachable uses for each value is stored in UseCount, and instructions that |
| 2264 | // seem |
| 2265 | // dead (have no non-dead uses) are stored in ProbablyDead. |
| 2266 | void NewGVN::convertClassToDFSOrdered( |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2267 | const CongruenceClass::MemberSet &Dense, |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2268 | SmallVectorImpl<ValueDFS> &DFSOrderedSet, |
| 2269 | DenseMap<const Value *, unsigned int> &UseCounts, |
| 2270 | SmallPtrSetImpl<Instruction *> &ProbablyDead) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2271 | for (auto D : Dense) { |
| 2272 | // First add the value. |
| 2273 | BasicBlock *BB = getBlockForValue(D); |
| 2274 | // Constants are handled prior to ever calling this function, so |
| 2275 | // we should only be left with instructions as members. |
Chandler Carruth | ee08676 | 2016-12-23 01:38:06 +0000 | [diff] [blame] | 2276 | assert(BB && "Should have figured out a basic block for value"); |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2277 | ValueDFS VDDef; |
Daniel Berlin | b66164c | 2017-01-14 00:24:23 +0000 | [diff] [blame] | 2278 | DomTreeNode *DomNode = DT->getNode(BB); |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2279 | VDDef.DFSIn = DomNode->getDFSNumIn(); |
| 2280 | VDDef.DFSOut = DomNode->getDFSNumOut(); |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 2281 | // If it's a store, use the leader of the value operand. |
| 2282 | if (auto *SI = dyn_cast<StoreInst>(D)) { |
Daniel Berlin | 808e3ff | 2017-01-31 22:31:56 +0000 | [diff] [blame] | 2283 | auto Leader = lookupOperandLeader(SI->getValueOperand()); |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2284 | VDDef.Def = alwaysAvailable(Leader) ? Leader : SI->getValueOperand(); |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 2285 | } else { |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2286 | VDDef.Def = D; |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 2287 | } |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2288 | assert(isa<Instruction>(D) && |
| 2289 | "The dense set member should always be an instruction"); |
| 2290 | VDDef.LocalNum = InstrDFS.lookup(D); |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2291 | DFSOrderedSet.emplace_back(VDDef); |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2292 | Instruction *Def = cast<Instruction>(D); |
| 2293 | unsigned int UseCount = 0; |
Daniel Berlin | b66164c | 2017-01-14 00:24:23 +0000 | [diff] [blame] | 2294 | // Now add the uses. |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2295 | for (auto &U : Def->uses()) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2296 | if (auto *I = dyn_cast<Instruction>(U.getUser())) { |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2297 | // Don't try to replace into dead uses |
| 2298 | if (InstructionsToErase.count(I)) |
| 2299 | continue; |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2300 | ValueDFS VDUse; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2301 | // Put the phi node uses in the incoming block. |
| 2302 | BasicBlock *IBlock; |
| 2303 | if (auto *P = dyn_cast<PHINode>(I)) { |
| 2304 | IBlock = P->getIncomingBlock(U); |
| 2305 | // Make phi node users appear last in the incoming block |
| 2306 | // they are from. |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2307 | VDUse.LocalNum = InstrDFS.size() + 1; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2308 | } else { |
| 2309 | IBlock = I->getParent(); |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2310 | VDUse.LocalNum = InstrDFS.lookup(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2311 | } |
Davide Italiano | ccbbc83 | 2017-01-26 00:42:42 +0000 | [diff] [blame] | 2312 | |
| 2313 | // Skip uses in unreachable blocks, as we're going |
| 2314 | // to delete them. |
| 2315 | if (ReachableBlocks.count(IBlock) == 0) |
| 2316 | continue; |
| 2317 | |
Daniel Berlin | b66164c | 2017-01-14 00:24:23 +0000 | [diff] [blame] | 2318 | DomTreeNode *DomNode = DT->getNode(IBlock); |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2319 | VDUse.DFSIn = DomNode->getDFSNumIn(); |
| 2320 | VDUse.DFSOut = DomNode->getDFSNumOut(); |
| 2321 | VDUse.U = &U; |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2322 | ++UseCount; |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2323 | DFSOrderedSet.emplace_back(VDUse); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2324 | } |
| 2325 | } |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2326 | |
| 2327 | // If there are no uses, it's probably dead (but it may have side-effects, |
| 2328 | // so not definitely dead. Otherwise, store the number of uses so we can |
| 2329 | // track if it becomes dead later). |
| 2330 | if (UseCount == 0) |
| 2331 | ProbablyDead.insert(Def); |
| 2332 | else |
| 2333 | UseCounts[Def] = UseCount; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2334 | } |
| 2335 | } |
| 2336 | |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2337 | // This function converts the set of members for a congruence class from values, |
| 2338 | // to the set of defs for loads and stores, with associated DFS info. |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2339 | void NewGVN::convertClassToLoadsAndStores( |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2340 | const CongruenceClass::MemberSet &Dense, |
| 2341 | SmallVectorImpl<ValueDFS> &LoadsAndStores) { |
| 2342 | for (auto D : Dense) { |
| 2343 | if (!isa<LoadInst>(D) && !isa<StoreInst>(D)) |
| 2344 | continue; |
| 2345 | |
| 2346 | BasicBlock *BB = getBlockForValue(D); |
| 2347 | ValueDFS VD; |
| 2348 | DomTreeNode *DomNode = DT->getNode(BB); |
| 2349 | VD.DFSIn = DomNode->getDFSNumIn(); |
| 2350 | VD.DFSOut = DomNode->getDFSNumOut(); |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2351 | VD.Def = D; |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2352 | |
| 2353 | // If it's an instruction, use the real local dfs number. |
| 2354 | if (auto *I = dyn_cast<Instruction>(D)) |
| 2355 | VD.LocalNum = InstrDFS.lookup(I); |
| 2356 | else |
| 2357 | llvm_unreachable("Should have been an instruction"); |
| 2358 | |
| 2359 | LoadsAndStores.emplace_back(VD); |
| 2360 | } |
| 2361 | } |
| 2362 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2363 | static void patchReplacementInstruction(Instruction *I, Value *Repl) { |
Daniel Berlin | 4d54796 | 2017-02-12 23:24:45 +0000 | [diff] [blame] | 2364 | auto *ReplInst = dyn_cast<Instruction>(Repl); |
Daniel Berlin | 86eab15 | 2017-02-12 22:25:20 +0000 | [diff] [blame] | 2365 | if (!ReplInst) |
| 2366 | return; |
| 2367 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2368 | // Patch the replacement so that it is not more restrictive than the value |
| 2369 | // being replaced. |
Daniel Berlin | 86eab15 | 2017-02-12 22:25:20 +0000 | [diff] [blame] | 2370 | // Note that if 'I' is a load being replaced by some operation, |
| 2371 | // for example, by an arithmetic operation, then andIRFlags() |
| 2372 | // would just erase all math flags from the original arithmetic |
| 2373 | // operation, which is clearly not wanted and not needed. |
| 2374 | if (!isa<LoadInst>(I)) |
| 2375 | ReplInst->andIRFlags(I); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2376 | |
Daniel Berlin | 86eab15 | 2017-02-12 22:25:20 +0000 | [diff] [blame] | 2377 | // FIXME: If both the original and replacement value are part of the |
| 2378 | // same control-flow region (meaning that the execution of one |
| 2379 | // guarantees the execution of the other), then we can combine the |
| 2380 | // noalias scopes here and do better than the general conservative |
| 2381 | // answer used in combineMetadata(). |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2382 | |
Daniel Berlin | 86eab15 | 2017-02-12 22:25:20 +0000 | [diff] [blame] | 2383 | // In general, GVN unifies expressions over different control-flow |
| 2384 | // regions, and so we need a conservative combination of the noalias |
| 2385 | // scopes. |
| 2386 | static const unsigned KnownIDs[] = { |
| 2387 | LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, |
| 2388 | LLVMContext::MD_noalias, LLVMContext::MD_range, |
| 2389 | LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load, |
| 2390 | LLVMContext::MD_invariant_group}; |
| 2391 | combineMetadata(ReplInst, I, KnownIDs); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2392 | } |
| 2393 | |
| 2394 | static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) { |
| 2395 | patchReplacementInstruction(I, Repl); |
| 2396 | I->replaceAllUsesWith(Repl); |
| 2397 | } |
| 2398 | |
| 2399 | void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) { |
| 2400 | DEBUG(dbgs() << " BasicBlock Dead:" << *BB); |
| 2401 | ++NumGVNBlocksDeleted; |
| 2402 | |
Daniel Berlin | e19f0e0 | 2017-01-30 17:06:55 +0000 | [diff] [blame] | 2403 | // Delete the instructions backwards, as it has a reduced likelihood of having |
| 2404 | // to update as many def-use and use-def chains. Start after the terminator. |
| 2405 | auto StartPoint = BB->rbegin(); |
| 2406 | ++StartPoint; |
| 2407 | // Note that we explicitly recalculate BB->rend() on each iteration, |
| 2408 | // as it may change when we remove the first instruction. |
| 2409 | for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) { |
| 2410 | Instruction &Inst = *I++; |
| 2411 | if (!Inst.use_empty()) |
| 2412 | Inst.replaceAllUsesWith(UndefValue::get(Inst.getType())); |
| 2413 | if (isa<LandingPadInst>(Inst)) |
| 2414 | continue; |
| 2415 | |
| 2416 | Inst.eraseFromParent(); |
| 2417 | ++NumGVNInstrDeleted; |
| 2418 | } |
Daniel Berlin | a53a722 | 2017-01-30 18:12:56 +0000 | [diff] [blame] | 2419 | // Now insert something that simplifycfg will turn into an unreachable. |
| 2420 | Type *Int8Ty = Type::getInt8Ty(BB->getContext()); |
| 2421 | new StoreInst(UndefValue::get(Int8Ty), |
| 2422 | Constant::getNullValue(Int8Ty->getPointerTo()), |
| 2423 | BB->getTerminator()); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2424 | } |
| 2425 | |
| 2426 | void NewGVN::markInstructionForDeletion(Instruction *I) { |
| 2427 | DEBUG(dbgs() << "Marking " << *I << " for deletion\n"); |
| 2428 | InstructionsToErase.insert(I); |
| 2429 | } |
| 2430 | |
| 2431 | void NewGVN::replaceInstruction(Instruction *I, Value *V) { |
| 2432 | |
| 2433 | DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n"); |
| 2434 | patchAndReplaceAllUsesWith(I, V); |
| 2435 | // We save the actual erasing to avoid invalidating memory |
| 2436 | // dependencies until we are done with everything. |
| 2437 | markInstructionForDeletion(I); |
| 2438 | } |
| 2439 | |
| 2440 | namespace { |
| 2441 | |
| 2442 | // This is a stack that contains both the value and dfs info of where |
| 2443 | // that value is valid. |
| 2444 | class ValueDFSStack { |
| 2445 | public: |
| 2446 | Value *back() const { return ValueStack.back(); } |
| 2447 | std::pair<int, int> dfs_back() const { return DFSStack.back(); } |
| 2448 | |
| 2449 | void push_back(Value *V, int DFSIn, int DFSOut) { |
Piotr Padlewski | 6c37d29 | 2016-12-28 23:24:02 +0000 | [diff] [blame] | 2450 | ValueStack.emplace_back(V); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2451 | DFSStack.emplace_back(DFSIn, DFSOut); |
| 2452 | } |
| 2453 | bool empty() const { return DFSStack.empty(); } |
| 2454 | bool isInScope(int DFSIn, int DFSOut) const { |
| 2455 | if (empty()) |
| 2456 | return false; |
| 2457 | return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second; |
| 2458 | } |
| 2459 | |
| 2460 | void popUntilDFSScope(int DFSIn, int DFSOut) { |
| 2461 | |
| 2462 | // These two should always be in sync at this point. |
| 2463 | assert(ValueStack.size() == DFSStack.size() && |
| 2464 | "Mismatch between ValueStack and DFSStack"); |
| 2465 | while ( |
| 2466 | !DFSStack.empty() && |
| 2467 | !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) { |
| 2468 | DFSStack.pop_back(); |
| 2469 | ValueStack.pop_back(); |
| 2470 | } |
| 2471 | } |
| 2472 | |
| 2473 | private: |
| 2474 | SmallVector<Value *, 8> ValueStack; |
| 2475 | SmallVector<std::pair<int, int>, 8> DFSStack; |
| 2476 | }; |
| 2477 | } |
Daniel Berlin | 0444343 | 2017-01-07 03:23:47 +0000 | [diff] [blame] | 2478 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2479 | bool NewGVN::eliminateInstructions(Function &F) { |
| 2480 | // This is a non-standard eliminator. The normal way to eliminate is |
| 2481 | // to walk the dominator tree in order, keeping track of available |
| 2482 | // values, and eliminating them. However, this is mildly |
| 2483 | // pointless. It requires doing lookups on every instruction, |
| 2484 | // regardless of whether we will ever eliminate it. For |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 2485 | // instructions part of most singleton congruence classes, we know we |
| 2486 | // will never eliminate them. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2487 | |
| 2488 | // Instead, this eliminator looks at the congruence classes directly, sorts |
| 2489 | // them into a DFS ordering of the dominator tree, and then we just |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 2490 | // perform elimination straight on the sets by walking the congruence |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2491 | // class member uses in order, and eliminate the ones dominated by the |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 2492 | // last member. This is worst case O(E log E) where E = number of |
| 2493 | // instructions in a single congruence class. In theory, this is all |
| 2494 | // instructions. In practice, it is much faster, as most instructions are |
| 2495 | // either in singleton congruence classes or can't possibly be eliminated |
| 2496 | // anyway (if there are no overlapping DFS ranges in class). |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2497 | // When we find something not dominated, it becomes the new leader |
Daniel Berlin | 85cbc8c | 2016-12-26 19:57:25 +0000 | [diff] [blame] | 2498 | // for elimination purposes. |
| 2499 | // TODO: If we wanted to be faster, We could remove any members with no |
| 2500 | // overlapping ranges while sorting, as we will never eliminate anything |
| 2501 | // with those members, as they don't dominate anything else in our set. |
| 2502 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2503 | bool AnythingReplaced = false; |
| 2504 | |
| 2505 | // Since we are going to walk the domtree anyway, and we can't guarantee the |
| 2506 | // DFS numbers are updated, we compute some ourselves. |
| 2507 | DT->updateDFSNumbers(); |
| 2508 | |
| 2509 | for (auto &B : F) { |
| 2510 | if (!ReachableBlocks.count(&B)) { |
| 2511 | for (const auto S : successors(&B)) { |
| 2512 | for (auto II = S->begin(); isa<PHINode>(II); ++II) { |
Piotr Padlewski | fc5727b | 2016-12-28 19:17:17 +0000 | [diff] [blame] | 2513 | auto &Phi = cast<PHINode>(*II); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2514 | DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block " |
| 2515 | << getBlockName(&B) |
| 2516 | << " with undef due to it being unreachable\n"); |
| 2517 | for (auto &Operand : Phi.incoming_values()) |
| 2518 | if (Phi.getIncomingBlock(Operand) == &B) |
| 2519 | Operand.set(UndefValue::get(Phi.getType())); |
| 2520 | } |
| 2521 | } |
| 2522 | } |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2523 | } |
| 2524 | |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2525 | // Map to store the use counts |
| 2526 | DenseMap<const Value *, unsigned int> UseCounts; |
Daniel Berlin | 4d54796 | 2017-02-12 23:24:45 +0000 | [diff] [blame] | 2527 | for (CongruenceClass *CC : reverse(CongruenceClasses)) { |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2528 | // Track the equivalent store info so we can decide whether to try |
| 2529 | // dead store elimination. |
| 2530 | SmallVector<ValueDFS, 8> PossibleDeadStores; |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2531 | SmallPtrSet<Instruction *, 8> ProbablyDead; |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 2532 | if (CC->Dead) |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2533 | continue; |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 2534 | // Everything still in the TOP class is unreachable or dead. |
| 2535 | if (CC == TOPClass) { |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 2536 | #ifndef NDEBUG |
| 2537 | for (auto M : CC->Members) |
| 2538 | assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) || |
| 2539 | InstructionsToErase.count(cast<Instruction>(M))) && |
Daniel Berlin | 5c338ff | 2017-03-10 19:05:04 +0000 | [diff] [blame] | 2540 | "Everything in TOP should be unreachable or dead at this " |
Daniel Berlin | b79f536 | 2017-02-11 12:48:50 +0000 | [diff] [blame] | 2541 | "point"); |
| 2542 | #endif |
| 2543 | continue; |
| 2544 | } |
| 2545 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2546 | assert(CC->RepLeader && "We should have had a leader"); |
| 2547 | |
| 2548 | // If this is a leader that is always available, and it's a |
| 2549 | // constant or has no equivalences, just replace everything with |
| 2550 | // it. We then update the congruence class with whatever members |
| 2551 | // are left. |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 2552 | Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader; |
| 2553 | if (alwaysAvailable(Leader)) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2554 | SmallPtrSet<Value *, 4> MembersLeft; |
| 2555 | for (auto M : CC->Members) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2556 | Value *Member = M; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2557 | // Void things have no uses we can replace. |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2558 | if (Member == Leader || Member->getType()->isVoidTy()) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2559 | MembersLeft.insert(Member); |
| 2560 | continue; |
| 2561 | } |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 2562 | DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member |
| 2563 | << "\n"); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2564 | // Due to equality propagation, these may not always be |
| 2565 | // instructions, they may be real values. We don't really |
| 2566 | // care about trying to replace the non-instructions. |
| 2567 | if (auto *I = dyn_cast<Instruction>(Member)) { |
Daniel Berlin | 26addef | 2017-01-20 21:04:30 +0000 | [diff] [blame] | 2568 | assert(Leader != I && "About to accidentally remove our leader"); |
| 2569 | replaceInstruction(I, Leader); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2570 | AnythingReplaced = true; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2571 | continue; |
| 2572 | } else { |
| 2573 | MembersLeft.insert(I); |
| 2574 | } |
| 2575 | } |
| 2576 | CC->Members.swap(MembersLeft); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2577 | } else { |
| 2578 | DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n"); |
| 2579 | // If this is a singleton, we can skip it. |
| 2580 | if (CC->Members.size() != 1) { |
| 2581 | |
| 2582 | // This is a stack because equality replacement/etc may place |
| 2583 | // constants in the middle of the member list, and we want to use |
| 2584 | // those constant values in preference to the current leader, over |
| 2585 | // the scope of those constants. |
| 2586 | ValueDFSStack EliminationStack; |
| 2587 | |
| 2588 | // Convert the members to DFS ordered sets and then merge them. |
Daniel Berlin | 2f1fbcc | 2017-01-09 05:34:19 +0000 | [diff] [blame] | 2589 | SmallVector<ValueDFS, 8> DFSOrderedSet; |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2590 | convertClassToDFSOrdered(CC->Members, DFSOrderedSet, UseCounts, |
| 2591 | ProbablyDead); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2592 | |
| 2593 | // Sort the whole thing. |
Daniel Berlin | 2f1fbcc | 2017-01-09 05:34:19 +0000 | [diff] [blame] | 2594 | std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end()); |
Daniel Berlin | 2f1fbcc | 2017-01-09 05:34:19 +0000 | [diff] [blame] | 2595 | for (auto &VD : DFSOrderedSet) { |
| 2596 | int MemberDFSIn = VD.DFSIn; |
| 2597 | int MemberDFSOut = VD.DFSOut; |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2598 | Value *Def = VD.Def; |
| 2599 | Use *U = VD.U; |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2600 | // We ignore void things because we can't get a value from them. |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2601 | if (Def && Def->getType()->isVoidTy()) |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2602 | continue; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2603 | |
| 2604 | if (EliminationStack.empty()) { |
| 2605 | DEBUG(dbgs() << "Elimination Stack is empty\n"); |
| 2606 | } else { |
| 2607 | DEBUG(dbgs() << "Elimination Stack Top DFS numbers are (" |
| 2608 | << EliminationStack.dfs_back().first << "," |
| 2609 | << EliminationStack.dfs_back().second << ")\n"); |
| 2610 | } |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2611 | |
| 2612 | DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << "," |
| 2613 | << MemberDFSOut << ")\n"); |
| 2614 | // First, we see if we are out of scope or empty. If so, |
| 2615 | // and there equivalences, we try to replace the top of |
| 2616 | // stack with equivalences (if it's on the stack, it must |
| 2617 | // not have been eliminated yet). |
| 2618 | // Then we synchronize to our current scope, by |
| 2619 | // popping until we are back within a DFS scope that |
| 2620 | // dominates the current member. |
| 2621 | // Then, what happens depends on a few factors |
| 2622 | // If the stack is now empty, we need to push |
| 2623 | // If we have a constant or a local equivalence we want to |
| 2624 | // start using, we also push. |
| 2625 | // Otherwise, we walk along, processing members who are |
| 2626 | // dominated by this scope, and eliminate them. |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2627 | bool ShouldPush = Def && EliminationStack.empty(); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2628 | bool OutOfScope = |
| 2629 | !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut); |
| 2630 | |
| 2631 | if (OutOfScope || ShouldPush) { |
| 2632 | // Sync to our current scope. |
| 2633 | EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut); |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2634 | bool ShouldPush = Def && EliminationStack.empty(); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2635 | if (ShouldPush) { |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2636 | EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2637 | } |
| 2638 | } |
| 2639 | |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2640 | // Skip the Def's, we only want to eliminate on their uses. But mark |
| 2641 | // dominated defs as dead. |
| 2642 | if (Def) { |
| 2643 | // For anything in this case, what and how we value number |
| 2644 | // guarantees that any side-effets that would have occurred (ie |
| 2645 | // throwing, etc) can be proven to either still occur (because it's |
| 2646 | // dominated by something that has the same side-effects), or never |
| 2647 | // occur. Otherwise, we would not have been able to prove it value |
| 2648 | // equivalent to something else. For these things, we can just mark |
| 2649 | // it all dead. Note that this is different from the "ProbablyDead" |
| 2650 | // set, which may not be dominated by anything, and thus, are only |
| 2651 | // easy to prove dead if they are also side-effect free. |
| 2652 | if (!EliminationStack.empty() && Def != EliminationStack.back() && |
| 2653 | isa<Instruction>(Def)) |
| 2654 | markInstructionForDeletion(cast<Instruction>(Def)); |
| 2655 | continue; |
| 2656 | } |
| 2657 | // At this point, we know it is a Use we are trying to possibly |
| 2658 | // replace. |
| 2659 | |
| 2660 | assert(isa<Instruction>(U->get()) && |
| 2661 | "Current def should have been an instruction"); |
| 2662 | assert(isa<Instruction>(U->getUser()) && |
| 2663 | "Current user should have been an instruction"); |
| 2664 | |
| 2665 | // If the thing we are replacing into is already marked to be dead, |
| 2666 | // this use is dead. Note that this is true regardless of whether |
| 2667 | // we have anything dominating the use or not. We do this here |
| 2668 | // because we are already walking all the uses anyway. |
| 2669 | Instruction *InstUse = cast<Instruction>(U->getUser()); |
| 2670 | if (InstructionsToErase.count(InstUse)) { |
| 2671 | auto &UseCount = UseCounts[U->get()]; |
| 2672 | if (--UseCount == 0) { |
| 2673 | ProbablyDead.insert(cast<Instruction>(U->get())); |
| 2674 | } |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2675 | } |
| 2676 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2677 | // If we get to this point, and the stack is empty we must have a use |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2678 | // with nothing we can use to eliminate this use, so just skip it. |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2679 | if (EliminationStack.empty()) |
| 2680 | continue; |
| 2681 | |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2682 | Value *DominatingLeader = EliminationStack.back(); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2683 | |
Daniel Berlin | d92e7f9 | 2017-01-07 00:01:42 +0000 | [diff] [blame] | 2684 | // Don't replace our existing users with ourselves. |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2685 | if (U->get() == DominatingLeader) |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2686 | continue; |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2687 | DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for " |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2688 | << *U->get() << " in " << *(U->getUser()) << "\n"); |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2689 | |
| 2690 | // If we replaced something in an instruction, handle the patching of |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2691 | // metadata. Skip this if we are replacing predicateinfo with its |
| 2692 | // original operand, as we already know we can just drop it. |
| 2693 | auto *ReplacedInst = cast<Instruction>(U->get()); |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2694 | auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst); |
| 2695 | if (!PI || DominatingLeader != PI->OriginalOp) |
| 2696 | patchReplacementInstruction(ReplacedInst, DominatingLeader); |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2697 | U->set(DominatingLeader); |
| 2698 | // This is now a use of the dominating leader, which means if the |
| 2699 | // dominating leader was dead, it's now live! |
| 2700 | auto &LeaderUseCount = UseCounts[DominatingLeader]; |
| 2701 | // It's about to be alive again. |
| 2702 | if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader)) |
| 2703 | ProbablyDead.erase(cast<Instruction>(DominatingLeader)); |
| 2704 | ++LeaderUseCount; |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2705 | AnythingReplaced = true; |
| 2706 | } |
| 2707 | } |
| 2708 | } |
| 2709 | |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2710 | // At this point, anything still in the ProbablyDead set is actually dead if |
| 2711 | // would be trivially dead. |
| 2712 | for (auto *I : ProbablyDead) |
| 2713 | if (wouldInstructionBeTriviallyDead(I)) |
| 2714 | markInstructionForDeletion(I); |
| 2715 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2716 | // Cleanup the congruence class. |
| 2717 | SmallPtrSet<Value *, 4> MembersLeft; |
Daniel Berlin | 25f05b0 | 2017-01-02 18:22:38 +0000 | [diff] [blame] | 2718 | for (Value *Member : CC->Members) { |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2719 | if (Member->getType()->isVoidTy()) { |
| 2720 | MembersLeft.insert(Member); |
| 2721 | continue; |
| 2722 | } |
| 2723 | |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2724 | MembersLeft.insert(Member); |
| 2725 | } |
| 2726 | CC->Members.swap(MembersLeft); |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2727 | |
| 2728 | // If we have possible dead stores to look at, try to eliminate them. |
| 2729 | if (CC->StoreCount > 0) { |
Daniel Berlin | e3e69e1 | 2017-03-10 00:32:33 +0000 | [diff] [blame] | 2730 | convertClassToLoadsAndStores(CC->Members, PossibleDeadStores); |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2731 | std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end()); |
| 2732 | ValueDFSStack EliminationStack; |
| 2733 | for (auto &VD : PossibleDeadStores) { |
| 2734 | int MemberDFSIn = VD.DFSIn; |
| 2735 | int MemberDFSOut = VD.DFSOut; |
Daniel Berlin | c0e008d | 2017-03-10 00:32:26 +0000 | [diff] [blame] | 2736 | Instruction *Member = cast<Instruction>(VD.Def); |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2737 | if (EliminationStack.empty() || |
| 2738 | !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) { |
| 2739 | // Sync to our current scope. |
| 2740 | EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut); |
| 2741 | if (EliminationStack.empty()) { |
| 2742 | EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut); |
| 2743 | continue; |
| 2744 | } |
| 2745 | } |
| 2746 | // We already did load elimination, so nothing to do here. |
| 2747 | if (isa<LoadInst>(Member)) |
| 2748 | continue; |
| 2749 | assert(!EliminationStack.empty()); |
| 2750 | Instruction *Leader = cast<Instruction>(EliminationStack.back()); |
Richard Trieu | 0b79aa3 | 2017-01-27 06:06:05 +0000 | [diff] [blame] | 2751 | (void)Leader; |
Daniel Berlin | c479686 | 2017-01-27 02:37:11 +0000 | [diff] [blame] | 2752 | assert(DT->dominates(Leader->getParent(), Member->getParent())); |
| 2753 | // Member is dominater by Leader, and thus dead |
| 2754 | DEBUG(dbgs() << "Marking dead store " << *Member |
| 2755 | << " that is dominated by " << *Leader << "\n"); |
| 2756 | markInstructionForDeletion(Member); |
| 2757 | CC->Members.erase(Member); |
| 2758 | ++NumGVNDeadStores; |
| 2759 | } |
| 2760 | } |
Davide Italiano | 7e274e0 | 2016-12-22 16:03:48 +0000 | [diff] [blame] | 2761 | } |
| 2762 | |
| 2763 | return AnythingReplaced; |
| 2764 | } |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 2765 | |
| 2766 | // This function provides global ranking of operations so that we can place them |
| 2767 | // in a canonical order. Note that rank alone is not necessarily enough for a |
| 2768 | // complete ordering, as constants all have the same rank. However, generally, |
| 2769 | // we will simplify an operation with all constants so that it doesn't matter |
| 2770 | // what order they appear in. |
| 2771 | unsigned int NewGVN::getRank(const Value *V) const { |
Daniel Berlin | b355c4f | 2017-02-18 23:06:47 +0000 | [diff] [blame] | 2772 | // Prefer undef to anything else |
| 2773 | if (isa<UndefValue>(V)) |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 2774 | return 0; |
Daniel Berlin | b355c4f | 2017-02-18 23:06:47 +0000 | [diff] [blame] | 2775 | if (isa<Constant>(V)) |
| 2776 | return 1; |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 2777 | else if (auto *A = dyn_cast<Argument>(V)) |
Daniel Berlin | b355c4f | 2017-02-18 23:06:47 +0000 | [diff] [blame] | 2778 | return 2 + A->getArgNo(); |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 2779 | |
Daniel Berlin | b355c4f | 2017-02-18 23:06:47 +0000 | [diff] [blame] | 2780 | // Need to shift the instruction DFS by number of arguments + 3 to account for |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 2781 | // the constant and argument ranking above. |
| 2782 | unsigned Result = InstrDFS.lookup(V); |
| 2783 | if (Result > 0) |
Daniel Berlin | b355c4f | 2017-02-18 23:06:47 +0000 | [diff] [blame] | 2784 | return 3 + NumFuncArgs + Result; |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 2785 | // Unreachable or something else, just return a really large number. |
| 2786 | return ~0; |
| 2787 | } |
| 2788 | |
| 2789 | // This is a function that says whether two commutative operations should |
| 2790 | // have their order swapped when canonicalizing. |
| 2791 | bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const { |
| 2792 | // Because we only care about a total ordering, and don't rewrite expressions |
| 2793 | // in this order, we order by rank, which will give a strict weak ordering to |
Daniel Berlin | b355c4f | 2017-02-18 23:06:47 +0000 | [diff] [blame] | 2794 | // everything but constants, and then we order by pointer address. |
Daniel Berlin | f7d9580 | 2017-02-18 23:06:50 +0000 | [diff] [blame] | 2795 | return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B); |
Daniel Berlin | 1c08767 | 2017-02-11 15:07:01 +0000 | [diff] [blame] | 2796 | } |
Daniel Berlin | 64e6899 | 2017-03-12 04:46:45 +0000 | [diff] [blame] | 2797 | |
| 2798 | class NewGVNLegacyPass : public FunctionPass { |
| 2799 | public: |
| 2800 | static char ID; // Pass identification, replacement for typeid. |
| 2801 | NewGVNLegacyPass() : FunctionPass(ID) { |
| 2802 | initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry()); |
| 2803 | } |
| 2804 | bool runOnFunction(Function &F) override; |
| 2805 | |
| 2806 | private: |
| 2807 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 2808 | AU.addRequired<AssumptionCacheTracker>(); |
| 2809 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 2810 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
| 2811 | AU.addRequired<MemorySSAWrapperPass>(); |
| 2812 | AU.addRequired<AAResultsWrapperPass>(); |
| 2813 | AU.addPreserved<DominatorTreeWrapperPass>(); |
| 2814 | AU.addPreserved<GlobalsAAWrapperPass>(); |
| 2815 | } |
| 2816 | }; |
| 2817 | |
| 2818 | bool NewGVNLegacyPass::runOnFunction(Function &F) { |
| 2819 | if (skipFunction(F)) |
| 2820 | return false; |
| 2821 | return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 2822 | &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), |
| 2823 | &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), |
| 2824 | &getAnalysis<AAResultsWrapperPass>().getAAResults(), |
| 2825 | &getAnalysis<MemorySSAWrapperPass>().getMSSA(), |
| 2826 | F.getParent()->getDataLayout()) |
| 2827 | .runGVN(); |
| 2828 | } |
| 2829 | |
| 2830 | INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering", |
| 2831 | false, false) |
| 2832 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 2833 | INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) |
| 2834 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 2835 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 2836 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
| 2837 | INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) |
| 2838 | INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false, |
| 2839 | false) |
| 2840 | |
| 2841 | char NewGVNLegacyPass::ID = 0; |
| 2842 | |
| 2843 | // createGVNPass - The public interface to this file. |
| 2844 | FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); } |
| 2845 | |
| 2846 | PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) { |
| 2847 | // Apparently the order in which we get these results matter for |
| 2848 | // the old GVN (see Chandler's comment in GVN.cpp). I'll keep |
| 2849 | // the same order here, just in case. |
| 2850 | auto &AC = AM.getResult<AssumptionAnalysis>(F); |
| 2851 | auto &DT = AM.getResult<DominatorTreeAnalysis>(F); |
| 2852 | auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); |
| 2853 | auto &AA = AM.getResult<AAManager>(F); |
| 2854 | auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); |
| 2855 | bool Changed = |
| 2856 | NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout()) |
| 2857 | .runGVN(); |
| 2858 | if (!Changed) |
| 2859 | return PreservedAnalyses::all(); |
| 2860 | PreservedAnalyses PA; |
| 2861 | PA.preserve<DominatorTreeAnalysis>(); |
| 2862 | PA.preserve<GlobalsAA>(); |
| 2863 | return PA; |
| 2864 | } |