Eli Bendersky | a108a65 | 2014-05-01 18:38:36 +0000 | [diff] [blame^] | 1 | //===-- SeparateConstOffsetFromGEP.cpp - ------------------------*- 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 | // |
| 10 | // Loop unrolling may create many similar GEPs for array accesses. |
| 11 | // e.g., a 2-level loop |
| 12 | // |
| 13 | // float a[32][32]; // global variable |
| 14 | // |
| 15 | // for (int i = 0; i < 2; ++i) { |
| 16 | // for (int j = 0; j < 2; ++j) { |
| 17 | // ... |
| 18 | // ... = a[x + i][y + j]; |
| 19 | // ... |
| 20 | // } |
| 21 | // } |
| 22 | // |
| 23 | // will probably be unrolled to: |
| 24 | // |
| 25 | // gep %a, 0, %x, %y; load |
| 26 | // gep %a, 0, %x, %y + 1; load |
| 27 | // gep %a, 0, %x + 1, %y; load |
| 28 | // gep %a, 0, %x + 1, %y + 1; load |
| 29 | // |
| 30 | // LLVM's GVN does not use partial redundancy elimination yet, and is thus |
| 31 | // unable to reuse (gep %a, 0, %x, %y). As a result, this misoptimization incurs |
| 32 | // significant slowdown in targets with limited addressing modes. For instance, |
| 33 | // because the PTX target does not support the reg+reg addressing mode, the |
| 34 | // NVPTX backend emits PTX code that literally computes the pointer address of |
| 35 | // each GEP, wasting tons of registers. It emits the following PTX for the |
| 36 | // first load and similar PTX for other loads. |
| 37 | // |
| 38 | // mov.u32 %r1, %x; |
| 39 | // mov.u32 %r2, %y; |
| 40 | // mul.wide.u32 %rl2, %r1, 128; |
| 41 | // mov.u64 %rl3, a; |
| 42 | // add.s64 %rl4, %rl3, %rl2; |
| 43 | // mul.wide.u32 %rl5, %r2, 4; |
| 44 | // add.s64 %rl6, %rl4, %rl5; |
| 45 | // ld.global.f32 %f1, [%rl6]; |
| 46 | // |
| 47 | // To reduce the register pressure, the optimization implemented in this file |
| 48 | // merges the common part of a group of GEPs, so we can compute each pointer |
| 49 | // address by adding a simple offset to the common part, saving many registers. |
| 50 | // |
| 51 | // It works by splitting each GEP into a variadic base and a constant offset. |
| 52 | // The variadic base can be computed once and reused by multiple GEPs, and the |
| 53 | // constant offsets can be nicely folded into the reg+immediate addressing mode |
| 54 | // (supported by most targets) without using any extra register. |
| 55 | // |
| 56 | // For instance, we transform the four GEPs and four loads in the above example |
| 57 | // into: |
| 58 | // |
| 59 | // base = gep a, 0, x, y |
| 60 | // load base |
| 61 | // laod base + 1 * sizeof(float) |
| 62 | // load base + 32 * sizeof(float) |
| 63 | // load base + 33 * sizeof(float) |
| 64 | // |
| 65 | // Given the transformed IR, a backend that supports the reg+immediate |
| 66 | // addressing mode can easily fold the pointer arithmetics into the loads. For |
| 67 | // example, the NVPTX backend can easily fold the pointer arithmetics into the |
| 68 | // ld.global.f32 instructions, and the resultant PTX uses much fewer registers. |
| 69 | // |
| 70 | // mov.u32 %r1, %tid.x; |
| 71 | // mov.u32 %r2, %tid.y; |
| 72 | // mul.wide.u32 %rl2, %r1, 128; |
| 73 | // mov.u64 %rl3, a; |
| 74 | // add.s64 %rl4, %rl3, %rl2; |
| 75 | // mul.wide.u32 %rl5, %r2, 4; |
| 76 | // add.s64 %rl6, %rl4, %rl5; |
| 77 | // ld.global.f32 %f1, [%rl6]; // so far the same as unoptimized PTX |
| 78 | // ld.global.f32 %f2, [%rl6+4]; // much better |
| 79 | // ld.global.f32 %f3, [%rl6+128]; // much better |
| 80 | // ld.global.f32 %f4, [%rl6+132]; // much better |
| 81 | // |
| 82 | //===----------------------------------------------------------------------===// |
| 83 | |
| 84 | #include "llvm/Analysis/TargetTransformInfo.h" |
| 85 | #include "llvm/Analysis/ValueTracking.h" |
| 86 | #include "llvm/IR/Constants.h" |
| 87 | #include "llvm/IR/DataLayout.h" |
| 88 | #include "llvm/IR/Instructions.h" |
| 89 | #include "llvm/IR/LLVMContext.h" |
| 90 | #include "llvm/IR/Module.h" |
| 91 | #include "llvm/IR/Operator.h" |
| 92 | #include "llvm/Support/CommandLine.h" |
| 93 | #include "llvm/Support/raw_ostream.h" |
| 94 | #include "llvm/Transforms/Scalar.h" |
| 95 | |
| 96 | using namespace llvm; |
| 97 | |
| 98 | static cl::opt<bool> DisableSeparateConstOffsetFromGEP( |
| 99 | "disable-separate-const-offset-from-gep", cl::init(false), |
| 100 | cl::desc("Do not separate the constant offset from a GEP instruction"), |
| 101 | cl::Hidden); |
| 102 | |
| 103 | namespace { |
| 104 | |
| 105 | /// \brief A helper class for separating a constant offset from a GEP index. |
| 106 | /// |
| 107 | /// In real programs, a GEP index may be more complicated than a simple addition |
| 108 | /// of something and a constant integer which can be trivially splitted. For |
| 109 | /// example, to split ((a << 3) | 5) + b, we need to search deeper for the |
| 110 | /// constant offset, so that we can seperate the index to (a << 3) + b and 5. |
| 111 | /// |
| 112 | /// Therefore, this class looks into the expression that computes a given GEP |
| 113 | /// index, and tries to find a constant integer that can be hoisted to the |
| 114 | /// outermost level of the expression as an addition. Not every constant in an |
| 115 | /// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a + |
| 116 | /// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case, |
| 117 | /// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15). |
| 118 | class ConstantOffsetExtractor { |
| 119 | public: |
| 120 | /// Extracts a constant offset from the given GEP index. It outputs the |
| 121 | /// numeric value of the extracted constant offset (0 if failed), and a |
| 122 | /// new index representing the remainder (equal to the original index minus |
| 123 | /// the constant offset). |
| 124 | /// \p Idx The given GEP index |
| 125 | /// \p NewIdx The new index to replace |
| 126 | /// \p DL The datalayout of the module |
| 127 | /// \p IP Calculating the new index requires new instructions. IP indicates |
| 128 | /// where to insert them (typically right before the GEP). |
| 129 | static int64_t Extract(Value *Idx, Value *&NewIdx, const DataLayout *DL, |
| 130 | Instruction *IP); |
| 131 | /// Looks for a constant offset without extracting it. The meaning of the |
| 132 | /// arguments and the return value are the same as Extract. |
| 133 | static int64_t Find(Value *Idx, const DataLayout *DL); |
| 134 | |
| 135 | private: |
| 136 | ConstantOffsetExtractor(const DataLayout *Layout, Instruction *InsertionPt) |
| 137 | : DL(Layout), IP(InsertionPt) {} |
| 138 | /// Searches the expression that computes V for a constant offset. If the |
| 139 | /// searching is successful, update UserChain as a path from V to the constant |
| 140 | /// offset. |
| 141 | int64_t find(Value *V); |
| 142 | /// A helper function to look into both operands of a binary operator U. |
| 143 | /// \p IsSub Whether U is a sub operator. If so, we need to negate the |
| 144 | /// constant offset at some point. |
| 145 | int64_t findInEitherOperand(User *U, bool IsSub); |
| 146 | /// After finding the constant offset and how it is reached from the GEP |
| 147 | /// index, we build a new index which is a clone of the old one except the |
| 148 | /// constant offset is removed. For example, given (a + (b + 5)) and knowning |
| 149 | /// the constant offset is 5, this function returns (a + b). |
| 150 | /// |
| 151 | /// We cannot simply change the constant to zero because the expression that |
| 152 | /// computes the index or its intermediate result may be used by others. |
| 153 | Value *rebuildWithoutConstantOffset(); |
| 154 | // A helper function for rebuildWithoutConstantOffset that rebuilds the direct |
| 155 | // user (U) of the constant offset (C). |
| 156 | Value *rebuildLeafWithoutConstantOffset(User *U, Value *C); |
| 157 | /// Returns a clone of U except the first occurrence of From with To. |
| 158 | Value *cloneAndReplace(User *U, Value *From, Value *To); |
| 159 | |
| 160 | /// Returns true if LHS and RHS have no bits in common, i.e., LHS | RHS == 0. |
| 161 | bool NoCommonBits(Value *LHS, Value *RHS) const; |
| 162 | /// Computes which bits are known to be one or zero. |
| 163 | /// \p KnownOne Mask of all bits that are known to be one. |
| 164 | /// \p KnownZero Mask of all bits that are known to be zero. |
| 165 | void ComputeKnownBits(Value *V, APInt &KnownOne, APInt &KnownZero) const; |
| 166 | /// Finds the first use of Used in U. Returns -1 if not found. |
| 167 | static unsigned FindFirstUse(User *U, Value *Used); |
| 168 | |
| 169 | /// The path from the constant offset to the old GEP index. e.g., if the GEP |
| 170 | /// index is "a * b + (c + 5)". After running function find, UserChain[0] will |
| 171 | /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and |
| 172 | /// UserChain[2] will be the entire expression "a * b + (c + 5)". |
| 173 | /// |
| 174 | /// This path helps rebuildWithoutConstantOffset rebuild the new GEP index. |
| 175 | SmallVector<User *, 8> UserChain; |
| 176 | /// The data layout of the module. Used in ComputeKnownBits. |
| 177 | const DataLayout *DL; |
| 178 | Instruction *IP; /// Insertion position of cloned instructions. |
| 179 | }; |
| 180 | |
| 181 | /// \brief A pass that tries to split every GEP in the function into a variadic |
| 182 | /// base and a constant offset. It is a FuntionPass because searching for the |
| 183 | /// constant offset may inspect other basic blocks. |
| 184 | class SeparateConstOffsetFromGEP : public FunctionPass { |
| 185 | public: |
| 186 | static char ID; |
| 187 | SeparateConstOffsetFromGEP() : FunctionPass(ID) { |
| 188 | initializeSeparateConstOffsetFromGEPPass(*PassRegistry::getPassRegistry()); |
| 189 | } |
| 190 | |
| 191 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 192 | AU.addRequired<DataLayoutPass>(); |
| 193 | AU.addRequired<TargetTransformInfo>(); |
| 194 | } |
| 195 | bool runOnFunction(Function &F) override; |
| 196 | |
| 197 | private: |
| 198 | /// Tries to split the given GEP into a variadic base and a constant offset, |
| 199 | /// and returns true if the splitting succeeds. |
| 200 | bool splitGEP(GetElementPtrInst *GEP); |
| 201 | /// Finds the constant offset within each index, and accumulates them. This |
| 202 | /// function only inspects the GEP without changing it. The output |
| 203 | /// NeedsExtraction indicates whether we can extract a non-zero constant |
| 204 | /// offset from any index. |
| 205 | int64_t accumulateByteOffset(GetElementPtrInst *GEP, const DataLayout *DL, |
| 206 | bool &NeedsExtraction); |
| 207 | }; |
| 208 | } // anonymous namespace |
| 209 | |
| 210 | char SeparateConstOffsetFromGEP::ID = 0; |
| 211 | INITIALIZE_PASS_BEGIN( |
| 212 | SeparateConstOffsetFromGEP, "separate-const-offset-from-gep", |
| 213 | "Split GEPs to a variadic base and a constant offset for better CSE", false, |
| 214 | false) |
| 215 | INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) |
| 216 | INITIALIZE_PASS_DEPENDENCY(DataLayoutPass) |
| 217 | INITIALIZE_PASS_END( |
| 218 | SeparateConstOffsetFromGEP, "separate-const-offset-from-gep", |
| 219 | "Split GEPs to a variadic base and a constant offset for better CSE", false, |
| 220 | false) |
| 221 | |
| 222 | FunctionPass *llvm::createSeparateConstOffsetFromGEPPass() { |
| 223 | return new SeparateConstOffsetFromGEP(); |
| 224 | } |
| 225 | |
| 226 | int64_t ConstantOffsetExtractor::findInEitherOperand(User *U, bool IsSub) { |
| 227 | assert(U->getNumOperands() == 2); |
| 228 | int64_t ConstantOffset = find(U->getOperand(0)); |
| 229 | // If we found a constant offset in the left operand, stop and return that. |
| 230 | // This shortcut might cause us to miss opportunities of combining the |
| 231 | // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9. |
| 232 | // However, such cases are probably already handled by -instcombine, |
| 233 | // given this pass runs after the standard optimizations. |
| 234 | if (ConstantOffset != 0) return ConstantOffset; |
| 235 | ConstantOffset = find(U->getOperand(1)); |
| 236 | // If U is a sub operator, negate the constant offset found in the right |
| 237 | // operand. |
| 238 | return IsSub ? -ConstantOffset : ConstantOffset; |
| 239 | } |
| 240 | |
| 241 | int64_t ConstantOffsetExtractor::find(Value *V) { |
| 242 | // TODO(jingyue): We can even trace into integer/pointer casts, such as |
| 243 | // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only |
| 244 | // integers because it gives good enough results for our benchmarks. |
| 245 | assert(V->getType()->isIntegerTy()); |
| 246 | |
| 247 | User *U = dyn_cast<User>(V); |
| 248 | // We cannot do much with Values that are not a User, such as BasicBlock and |
| 249 | // MDNode. |
| 250 | if (U == nullptr) return 0; |
| 251 | |
| 252 | int64_t ConstantOffset = 0; |
| 253 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U)) { |
| 254 | // Hooray, we found it! |
| 255 | ConstantOffset = CI->getSExtValue(); |
| 256 | } else if (Operator *O = dyn_cast<Operator>(U)) { |
| 257 | // The GEP index may be more complicated than a simple addition of a |
| 258 | // varaible and a constant. Therefore, we trace into subexpressions for more |
| 259 | // hoisting opportunities. |
| 260 | switch (O->getOpcode()) { |
| 261 | case Instruction::Add: { |
| 262 | ConstantOffset = findInEitherOperand(U, false); |
| 263 | break; |
| 264 | } |
| 265 | case Instruction::Sub: { |
| 266 | ConstantOffset = findInEitherOperand(U, true); |
| 267 | break; |
| 268 | } |
| 269 | case Instruction::Or: { |
| 270 | // If LHS and RHS don't have common bits, (LHS | RHS) is equivalent to |
| 271 | // (LHS + RHS). |
| 272 | if (NoCommonBits(U->getOperand(0), U->getOperand(1))) |
| 273 | ConstantOffset = findInEitherOperand(U, false); |
| 274 | break; |
| 275 | } |
| 276 | case Instruction::SExt: { |
| 277 | // For safety, we trace into sext only when its operand is marked |
| 278 | // "nsw" because xxx.nsw guarantees no signed wrap. e.g., we can safely |
| 279 | // transform "sext (add nsw a, 5)" into "add nsw (sext a), 5". |
| 280 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) { |
| 281 | if (BO->hasNoSignedWrap()) |
| 282 | ConstantOffset = find(U->getOperand(0)); |
| 283 | } |
| 284 | break; |
| 285 | } |
| 286 | case Instruction::ZExt: { |
| 287 | // Similarly, we trace into zext only when its operand is marked with |
| 288 | // "nuw" because zext (add nuw a, b) == add nuw (zext a), (zext b). |
| 289 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) { |
| 290 | if (BO->hasNoUnsignedWrap()) |
| 291 | ConstantOffset = find(U->getOperand(0)); |
| 292 | } |
| 293 | break; |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | // If we found a non-zero constant offset, adds it to the path for future |
| 298 | // transformation (rebuildWithoutConstantOffset). Zero is a valid constant |
| 299 | // offset, but doesn't help this optimization. |
| 300 | if (ConstantOffset != 0) |
| 301 | UserChain.push_back(U); |
| 302 | return ConstantOffset; |
| 303 | } |
| 304 | |
| 305 | unsigned ConstantOffsetExtractor::FindFirstUse(User *U, Value *Used) { |
| 306 | for (unsigned I = 0, E = U->getNumOperands(); I < E; ++I) { |
| 307 | if (U->getOperand(I) == Used) |
| 308 | return I; |
| 309 | } |
| 310 | return -1; |
| 311 | } |
| 312 | |
| 313 | Value *ConstantOffsetExtractor::cloneAndReplace(User *U, Value *From, |
| 314 | Value *To) { |
| 315 | // Finds in U the first use of From. It is safe to ignore future occurrences |
| 316 | // of From, because findInEitherOperand similarly stops searching the right |
| 317 | // operand when the first operand has a non-zero constant offset. |
| 318 | unsigned OpNo = FindFirstUse(U, From); |
| 319 | assert(OpNo != (unsigned)-1 && "UserChain wasn't built correctly"); |
| 320 | |
| 321 | // ConstantOffsetExtractor::find only follows Operators (i.e., Instructions |
| 322 | // and ConstantExprs). Therefore, U is either an Instruction or a |
| 323 | // ConstantExpr. |
| 324 | if (Instruction *I = dyn_cast<Instruction>(U)) { |
| 325 | Instruction *Clone = I->clone(); |
| 326 | Clone->setOperand(OpNo, To); |
| 327 | Clone->insertBefore(IP); |
| 328 | return Clone; |
| 329 | } |
| 330 | // cast<Constant>(To) is safe because a ConstantExpr only uses Constants. |
| 331 | return cast<ConstantExpr>(U) |
| 332 | ->getWithOperandReplaced(OpNo, cast<Constant>(To)); |
| 333 | } |
| 334 | |
| 335 | Value *ConstantOffsetExtractor::rebuildLeafWithoutConstantOffset(User *U, |
| 336 | Value *C) { |
| 337 | assert(U->getNumOperands() <= 2 && |
| 338 | "We didn't trace into any operator with more than 2 operands"); |
| 339 | // If U has only one operand which is the constant offset, removing the |
| 340 | // constant offset leaves U as a null value. |
| 341 | if (U->getNumOperands() == 1) |
| 342 | return Constant::getNullValue(U->getType()); |
| 343 | |
| 344 | // U->getNumOperands() == 2 |
| 345 | unsigned OpNo = FindFirstUse(U, C); // U->getOperand(OpNo) == C |
| 346 | assert(OpNo < 2 && "UserChain wasn't built correctly"); |
| 347 | Value *TheOther = U->getOperand(1 - OpNo); // The other operand of U |
| 348 | // If U = C - X, removing C makes U = -X; otherwise U will simply be X. |
| 349 | if (!isa<SubOperator>(U) || OpNo == 1) |
| 350 | return TheOther; |
| 351 | if (isa<ConstantExpr>(U)) |
| 352 | return ConstantExpr::getNeg(cast<Constant>(TheOther)); |
| 353 | return BinaryOperator::CreateNeg(TheOther, "", IP); |
| 354 | } |
| 355 | |
| 356 | Value *ConstantOffsetExtractor::rebuildWithoutConstantOffset() { |
| 357 | assert(UserChain.size() > 0 && "you at least found a constant, right?"); |
| 358 | // Start with the constant and go up through UserChain, each time building a |
| 359 | // clone of the subexpression but with the constant removed. |
| 360 | // e.g., to build a clone of (a + (b + (c + 5)) but with the 5 removed, we |
| 361 | // first c, then (b + c), and finally (a + (b + c)). |
| 362 | // |
| 363 | // Fast path: if the GEP index is a constant, simply returns 0. |
| 364 | if (UserChain.size() == 1) |
| 365 | return ConstantInt::get(UserChain[0]->getType(), 0); |
| 366 | |
| 367 | Value *Remainder = |
| 368 | rebuildLeafWithoutConstantOffset(UserChain[1], UserChain[0]); |
| 369 | for (size_t I = 2; I < UserChain.size(); ++I) |
| 370 | Remainder = cloneAndReplace(UserChain[I], UserChain[I - 1], Remainder); |
| 371 | return Remainder; |
| 372 | } |
| 373 | |
| 374 | int64_t ConstantOffsetExtractor::Extract(Value *Idx, Value *&NewIdx, |
| 375 | const DataLayout *DL, |
| 376 | Instruction *IP) { |
| 377 | ConstantOffsetExtractor Extractor(DL, IP); |
| 378 | // Find a non-zero constant offset first. |
| 379 | int64_t ConstantOffset = Extractor.find(Idx); |
| 380 | if (ConstantOffset == 0) |
| 381 | return 0; |
| 382 | // Then rebuild a new index with the constant removed. |
| 383 | NewIdx = Extractor.rebuildWithoutConstantOffset(); |
| 384 | return ConstantOffset; |
| 385 | } |
| 386 | |
| 387 | int64_t ConstantOffsetExtractor::Find(Value *Idx, const DataLayout *DL) { |
| 388 | return ConstantOffsetExtractor(DL, nullptr).find(Idx); |
| 389 | } |
| 390 | |
| 391 | void ConstantOffsetExtractor::ComputeKnownBits(Value *V, APInt &KnownOne, |
| 392 | APInt &KnownZero) const { |
| 393 | IntegerType *IT = cast<IntegerType>(V->getType()); |
| 394 | KnownOne = APInt(IT->getBitWidth(), 0); |
| 395 | KnownZero = APInt(IT->getBitWidth(), 0); |
| 396 | llvm::ComputeMaskedBits(V, KnownZero, KnownOne, DL, 0); |
| 397 | } |
| 398 | |
| 399 | bool ConstantOffsetExtractor::NoCommonBits(Value *LHS, Value *RHS) const { |
| 400 | assert(LHS->getType() == RHS->getType() && |
| 401 | "LHS and RHS should have the same type"); |
| 402 | APInt LHSKnownOne, LHSKnownZero, RHSKnownOne, RHSKnownZero; |
| 403 | ComputeKnownBits(LHS, LHSKnownOne, LHSKnownZero); |
| 404 | ComputeKnownBits(RHS, RHSKnownOne, RHSKnownZero); |
| 405 | return (LHSKnownZero | RHSKnownZero).isAllOnesValue(); |
| 406 | } |
| 407 | |
| 408 | int64_t SeparateConstOffsetFromGEP::accumulateByteOffset( |
| 409 | GetElementPtrInst *GEP, const DataLayout *DL, bool &NeedsExtraction) { |
| 410 | NeedsExtraction = false; |
| 411 | int64_t AccumulativeByteOffset = 0; |
| 412 | gep_type_iterator GTI = gep_type_begin(*GEP); |
| 413 | for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) { |
| 414 | if (isa<SequentialType>(*GTI)) { |
| 415 | // Tries to extract a constant offset from this GEP index. |
| 416 | int64_t ConstantOffset = |
| 417 | ConstantOffsetExtractor::Find(GEP->getOperand(I), DL); |
| 418 | if (ConstantOffset != 0) { |
| 419 | NeedsExtraction = true; |
| 420 | // A GEP may have multiple indices. We accumulate the extracted |
| 421 | // constant offset to a byte offset, and later offset the remainder of |
| 422 | // the original GEP with this byte offset. |
| 423 | AccumulativeByteOffset += |
| 424 | ConstantOffset * DL->getTypeAllocSize(GTI.getIndexedType()); |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | return AccumulativeByteOffset; |
| 429 | } |
| 430 | |
| 431 | bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) { |
| 432 | // Skip vector GEPs. |
| 433 | if (GEP->getType()->isVectorTy()) |
| 434 | return false; |
| 435 | |
| 436 | // The backend can already nicely handle the case where all indices are |
| 437 | // constant. |
| 438 | if (GEP->hasAllConstantIndices()) |
| 439 | return false; |
| 440 | |
| 441 | bool Changed = false; |
| 442 | |
| 443 | // Shortcuts integer casts. Eliminating these explicit casts can make |
| 444 | // subsequent optimizations more obvious: ConstantOffsetExtractor needn't |
| 445 | // trace into these casts. |
| 446 | if (GEP->isInBounds()) { |
| 447 | // Doing this to inbounds GEPs is safe because their indices are guaranteed |
| 448 | // to be non-negative and in bounds. |
| 449 | gep_type_iterator GTI = gep_type_begin(*GEP); |
| 450 | for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) { |
| 451 | if (isa<SequentialType>(*GTI)) { |
| 452 | if (Operator *O = dyn_cast<Operator>(GEP->getOperand(I))) { |
| 453 | if (O->getOpcode() == Instruction::SExt || |
| 454 | O->getOpcode() == Instruction::ZExt) { |
| 455 | GEP->setOperand(I, O->getOperand(0)); |
| 456 | Changed = true; |
| 457 | } |
| 458 | } |
| 459 | } |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | const DataLayout *DL = &getAnalysis<DataLayoutPass>().getDataLayout(); |
| 464 | bool NeedsExtraction; |
| 465 | int64_t AccumulativeByteOffset = |
| 466 | accumulateByteOffset(GEP, DL, NeedsExtraction); |
| 467 | |
| 468 | if (!NeedsExtraction) |
| 469 | return Changed; |
| 470 | // Before really splitting the GEP, check whether the backend supports the |
| 471 | // addressing mode we are about to produce. If no, this splitting probably |
| 472 | // won't be beneficial. |
| 473 | TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>(); |
| 474 | if (!TTI.isLegalAddressingMode(GEP->getType()->getElementType(), |
| 475 | /*BaseGV=*/nullptr, AccumulativeByteOffset, |
| 476 | /*HasBaseReg=*/true, /*Scale=*/0)) { |
| 477 | return Changed; |
| 478 | } |
| 479 | |
| 480 | // Remove the constant offset in each GEP index. The resultant GEP computes |
| 481 | // the variadic base. |
| 482 | gep_type_iterator GTI = gep_type_begin(*GEP); |
| 483 | for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) { |
| 484 | if (isa<SequentialType>(*GTI)) { |
| 485 | Value *NewIdx = nullptr; |
| 486 | // Tries to extract a constant offset from this GEP index. |
| 487 | int64_t ConstantOffset = |
| 488 | ConstantOffsetExtractor::Extract(GEP->getOperand(I), NewIdx, DL, GEP); |
| 489 | if (ConstantOffset != 0) { |
| 490 | assert(NewIdx && "ConstantOffset != 0 implies NewIdx is set"); |
| 491 | GEP->setOperand(I, NewIdx); |
| 492 | // Clear the inbounds attribute because the new index may be off-bound. |
| 493 | // e.g., |
| 494 | // |
| 495 | // b = add i64 a, 5 |
| 496 | // addr = gep inbounds float* p, i64 b |
| 497 | // |
| 498 | // is transformed to: |
| 499 | // |
| 500 | // addr2 = gep float* p, i64 a |
| 501 | // addr = gep float* addr2, i64 5 |
| 502 | // |
| 503 | // If a is -4, although the old index b is in bounds, the new index a is |
| 504 | // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the |
| 505 | // inbounds keyword is not present, the offsets are added to the base |
| 506 | // address with silently-wrapping two's complement arithmetic". |
| 507 | // Therefore, the final code will be a semantically equivalent. |
| 508 | // |
| 509 | // TODO(jingyue): do some range analysis to keep as many inbounds as |
| 510 | // possible. GEPs with inbounds are more friendly to alias analysis. |
| 511 | GEP->setIsInBounds(false); |
| 512 | Changed = true; |
| 513 | } |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | // Offsets the base with the accumulative byte offset. |
| 518 | // |
| 519 | // %gep ; the base |
| 520 | // ... %gep ... |
| 521 | // |
| 522 | // => add the offset |
| 523 | // |
| 524 | // %gep2 ; clone of %gep |
| 525 | // %0 = ptrtoint %gep2 |
| 526 | // %1 = add %0, <offset> |
| 527 | // %new.gep = inttoptr %1 |
| 528 | // %gep ; will be removed |
| 529 | // ... %gep ... |
| 530 | // |
| 531 | // => replace all uses of %gep with %new.gep and remove %gep |
| 532 | // |
| 533 | // %gep2 ; clone of %gep |
| 534 | // %0 = ptrtoint %gep2 |
| 535 | // %1 = add %0, <offset> |
| 536 | // %new.gep = inttoptr %1 |
| 537 | // ... %new.gep ... |
| 538 | // |
| 539 | // TODO(jingyue): Emit a GEP instead of an "uglygep" |
| 540 | // (http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep) to make the IR |
| 541 | // prettier and more alias analysis friendly. One caveat: if the original GEP |
| 542 | // ends with a StructType, we need to split the GEP at the last |
| 543 | // SequentialType. For instance, consider the following IR: |
| 544 | // |
| 545 | // %struct.S = type { float, double } |
| 546 | // @array = global [1024 x %struct.S] |
| 547 | // %p = getelementptr %array, 0, %i + 5, 1 |
| 548 | // |
| 549 | // To separate the constant 5 from %p, we would need to split %p at the last |
| 550 | // array index so that we have: |
| 551 | // |
| 552 | // %addr = gep %array, 0, %i |
| 553 | // %p = gep %addr, 5, 1 |
| 554 | Instruction *NewGEP = GEP->clone(); |
| 555 | NewGEP->insertBefore(GEP); |
| 556 | Type *IntPtrTy = DL->getIntPtrType(GEP->getType()); |
| 557 | Value *Addr = new PtrToIntInst(NewGEP, IntPtrTy, "", GEP); |
| 558 | Addr = BinaryOperator::CreateAdd( |
| 559 | Addr, ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true), "", GEP); |
| 560 | Addr = new IntToPtrInst(Addr, GEP->getType(), "", GEP); |
| 561 | |
| 562 | GEP->replaceAllUsesWith(Addr); |
| 563 | GEP->eraseFromParent(); |
| 564 | |
| 565 | return true; |
| 566 | } |
| 567 | |
| 568 | bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) { |
| 569 | if (DisableSeparateConstOffsetFromGEP) |
| 570 | return false; |
| 571 | |
| 572 | bool Changed = false; |
| 573 | for (Function::iterator B = F.begin(), BE = F.end(); B != BE; ++B) { |
| 574 | for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ) { |
| 575 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++)) { |
| 576 | Changed |= splitGEP(GEP); |
| 577 | } |
| 578 | // No need to split GEP ConstantExprs because all its indices are constant |
| 579 | // already. |
| 580 | } |
| 581 | } |
| 582 | return Changed; |
| 583 | } |