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