1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===// 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 transformation implements the well known scalar replacement of 11 /// aggregates transformation. It tries to identify promotable elements of an 12 /// aggregate alloca, and promote them to registers. It will also try to 13 /// convert uses of an element (or set of elements) of an alloca into a vector 14 /// or bitfield-style integer scalar if appropriate. 15 /// 16 /// It works to do this with minimal slicing of the alloca so that regions 17 /// which are merely transferred in and out of external memory remain unchanged 18 /// and are not decomposed to scalar code. 19 /// 20 /// Because this also performs alloca promotion, it can be thought of as also 21 /// serving the purpose of SSA formation. The algorithm iterates on the 22 /// function until all opportunities for promotion have been realized. 23 /// 24 //===----------------------------------------------------------------------===// 25 26 #include "llvm/Transforms/Scalar.h" 27 #include "llvm/ADT/STLExtras.h" 28 #include "llvm/ADT/SetVector.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/Analysis/AssumptionTracker.h" 32 #include "llvm/Analysis/Loads.h" 33 #include "llvm/Analysis/PtrUseVisitor.h" 34 #include "llvm/Analysis/ValueTracking.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DIBuilder.h" 37 #include "llvm/IR/DataLayout.h" 38 #include "llvm/IR/DebugInfo.h" 39 #include "llvm/IR/DerivedTypes.h" 40 #include "llvm/IR/Dominators.h" 41 #include "llvm/IR/Function.h" 42 #include "llvm/IR/IRBuilder.h" 43 #include "llvm/IR/InstVisitor.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/IR/IntrinsicInst.h" 46 #include "llvm/IR/LLVMContext.h" 47 #include "llvm/IR/Operator.h" 48 #include "llvm/Pass.h" 49 #include "llvm/Support/CommandLine.h" 50 #include "llvm/Support/Compiler.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/MathExtras.h" 54 #include "llvm/Support/TimeValue.h" 55 #include "llvm/Support/raw_ostream.h" 56 #include "llvm/Transforms/Utils/Local.h" 57 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 58 #include "llvm/Transforms/Utils/SSAUpdater.h" 59 60 #if __cplusplus >= 201103L && !defined(NDEBUG) 61 // We only use this for a debug check in C++11 62 #include <random> 63 #endif 64 65 using namespace llvm; 66 67 #define DEBUG_TYPE "sroa" 68 69 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement"); 70 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed"); 71 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca"); 72 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten"); 73 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition"); 74 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced"); 75 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values"); 76 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion"); 77 STATISTIC(NumDeleted, "Number of instructions deleted"); 78 STATISTIC(NumVectorized, "Number of vectorized aggregates"); 79 80 /// Hidden option to force the pass to not use DomTree and mem2reg, instead 81 /// forming SSA values through the SSAUpdater infrastructure. 82 static cl::opt<bool> 83 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden); 84 85 /// Hidden option to enable randomly shuffling the slices to help uncover 86 /// instability in their order. 87 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices", 88 cl::init(false), cl::Hidden); 89 90 /// Hidden option to experiment with completely strict handling of inbounds 91 /// GEPs. 92 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", 93 cl::init(false), cl::Hidden); 94 95 namespace { 96 /// \brief A custom IRBuilder inserter which prefixes all names if they are 97 /// preserved. 98 template <bool preserveNames = true> 99 class IRBuilderPrefixedInserter : 100 public IRBuilderDefaultInserter<preserveNames> { 101 std::string Prefix; 102 103 public: 104 void SetNamePrefix(const Twine &P) { Prefix = P.str(); } 105 106 protected: 107 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB, 108 BasicBlock::iterator InsertPt) const { 109 IRBuilderDefaultInserter<preserveNames>::InsertHelper( 110 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt); 111 } 112 }; 113 114 // Specialization for not preserving the name is trivial. 115 template <> 116 class IRBuilderPrefixedInserter<false> : 117 public IRBuilderDefaultInserter<false> { 118 public: 119 void SetNamePrefix(const Twine &P) {} 120 }; 121 122 /// \brief Provide a typedef for IRBuilder that drops names in release builds. 123 #ifndef NDEBUG 124 typedef llvm::IRBuilder<true, ConstantFolder, 125 IRBuilderPrefixedInserter<true> > IRBuilderTy; 126 #else 127 typedef llvm::IRBuilder<false, ConstantFolder, 128 IRBuilderPrefixedInserter<false> > IRBuilderTy; 129 #endif 130 } 131 132 namespace { 133 /// \brief A used slice of an alloca. 134 /// 135 /// This structure represents a slice of an alloca used by some instruction. It 136 /// stores both the begin and end offsets of this use, a pointer to the use 137 /// itself, and a flag indicating whether we can classify the use as splittable 138 /// or not when forming partitions of the alloca. 139 class Slice { 140 /// \brief The beginning offset of the range. 141 uint64_t BeginOffset; 142 143 /// \brief The ending offset, not included in the range. 144 uint64_t EndOffset; 145 146 /// \brief Storage for both the use of this slice and whether it can be 147 /// split. 148 PointerIntPair<Use *, 1, bool> UseAndIsSplittable; 149 150 public: 151 Slice() : BeginOffset(), EndOffset() {} 152 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable) 153 : BeginOffset(BeginOffset), EndOffset(EndOffset), 154 UseAndIsSplittable(U, IsSplittable) {} 155 156 uint64_t beginOffset() const { return BeginOffset; } 157 uint64_t endOffset() const { return EndOffset; } 158 159 bool isSplittable() const { return UseAndIsSplittable.getInt(); } 160 void makeUnsplittable() { UseAndIsSplittable.setInt(false); } 161 162 Use *getUse() const { return UseAndIsSplittable.getPointer(); } 163 164 bool isDead() const { return getUse() == nullptr; } 165 void kill() { UseAndIsSplittable.setPointer(nullptr); } 166 167 /// \brief Support for ordering ranges. 168 /// 169 /// This provides an ordering over ranges such that start offsets are 170 /// always increasing, and within equal start offsets, the end offsets are 171 /// decreasing. Thus the spanning range comes first in a cluster with the 172 /// same start position. 173 bool operator<(const Slice &RHS) const { 174 if (beginOffset() < RHS.beginOffset()) return true; 175 if (beginOffset() > RHS.beginOffset()) return false; 176 if (isSplittable() != RHS.isSplittable()) return !isSplittable(); 177 if (endOffset() > RHS.endOffset()) return true; 178 return false; 179 } 180 181 /// \brief Support comparison with a single offset to allow binary searches. 182 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS, 183 uint64_t RHSOffset) { 184 return LHS.beginOffset() < RHSOffset; 185 } 186 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset, 187 const Slice &RHS) { 188 return LHSOffset < RHS.beginOffset(); 189 } 190 191 bool operator==(const Slice &RHS) const { 192 return isSplittable() == RHS.isSplittable() && 193 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset(); 194 } 195 bool operator!=(const Slice &RHS) const { return !operator==(RHS); } 196 }; 197 } // end anonymous namespace 198 199 namespace llvm { 200 template <typename T> struct isPodLike; 201 template <> struct isPodLike<Slice> { 202 static const bool value = true; 203 }; 204 } 205 206 namespace { 207 /// \brief Representation of the alloca slices. 208 /// 209 /// This class represents the slices of an alloca which are formed by its 210 /// various uses. If a pointer escapes, we can't fully build a representation 211 /// for the slices used and we reflect that in this structure. The uses are 212 /// stored, sorted by increasing beginning offset and with unsplittable slices 213 /// starting at a particular offset before splittable slices. 214 class AllocaSlices { 215 public: 216 /// \brief Construct the slices of a particular alloca. 217 AllocaSlices(const DataLayout &DL, AllocaInst &AI); 218 219 /// \brief Test whether a pointer to the allocation escapes our analysis. 220 /// 221 /// If this is true, the slices are never fully built and should be 222 /// ignored. 223 bool isEscaped() const { return PointerEscapingInstr; } 224 225 /// \brief Support for iterating over the slices. 226 /// @{ 227 typedef SmallVectorImpl<Slice>::iterator iterator; 228 typedef iterator_range<iterator> range; 229 iterator begin() { return Slices.begin(); } 230 iterator end() { return Slices.end(); } 231 232 typedef SmallVectorImpl<Slice>::const_iterator const_iterator; 233 typedef iterator_range<const_iterator> const_range; 234 const_iterator begin() const { return Slices.begin(); } 235 const_iterator end() const { return Slices.end(); } 236 /// @} 237 238 /// \brief Access the dead users for this alloca. 239 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; } 240 241 /// \brief Access the dead operands referring to this alloca. 242 /// 243 /// These are operands which have cannot actually be used to refer to the 244 /// alloca as they are outside its range and the user doesn't correct for 245 /// that. These mostly consist of PHI node inputs and the like which we just 246 /// need to replace with undef. 247 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; } 248 249 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 250 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const; 251 void printSlice(raw_ostream &OS, const_iterator I, 252 StringRef Indent = " ") const; 253 void printUse(raw_ostream &OS, const_iterator I, 254 StringRef Indent = " ") const; 255 void print(raw_ostream &OS) const; 256 void dump(const_iterator I) const; 257 void dump() const; 258 #endif 259 260 private: 261 template <typename DerivedT, typename RetT = void> class BuilderBase; 262 class SliceBuilder; 263 friend class AllocaSlices::SliceBuilder; 264 265 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 266 /// \brief Handle to alloca instruction to simplify method interfaces. 267 AllocaInst &AI; 268 #endif 269 270 /// \brief The instruction responsible for this alloca not having a known set 271 /// of slices. 272 /// 273 /// When an instruction (potentially) escapes the pointer to the alloca, we 274 /// store a pointer to that here and abort trying to form slices of the 275 /// alloca. This will be null if the alloca slices are analyzed successfully. 276 Instruction *PointerEscapingInstr; 277 278 /// \brief The slices of the alloca. 279 /// 280 /// We store a vector of the slices formed by uses of the alloca here. This 281 /// vector is sorted by increasing begin offset, and then the unsplittable 282 /// slices before the splittable ones. See the Slice inner class for more 283 /// details. 284 SmallVector<Slice, 8> Slices; 285 286 /// \brief Instructions which will become dead if we rewrite the alloca. 287 /// 288 /// Note that these are not separated by slice. This is because we expect an 289 /// alloca to be completely rewritten or not rewritten at all. If rewritten, 290 /// all these instructions can simply be removed and replaced with undef as 291 /// they come from outside of the allocated space. 292 SmallVector<Instruction *, 8> DeadUsers; 293 294 /// \brief Operands which will become dead if we rewrite the alloca. 295 /// 296 /// These are operands that in their particular use can be replaced with 297 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs 298 /// to PHI nodes and the like. They aren't entirely dead (there might be 299 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we 300 /// want to swap this particular input for undef to simplify the use lists of 301 /// the alloca. 302 SmallVector<Use *, 8> DeadOperands; 303 }; 304 } 305 306 static Value *foldSelectInst(SelectInst &SI) { 307 // If the condition being selected on is a constant or the same value is 308 // being selected between, fold the select. Yes this does (rarely) happen 309 // early on. 310 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition())) 311 return SI.getOperand(1+CI->isZero()); 312 if (SI.getOperand(1) == SI.getOperand(2)) 313 return SI.getOperand(1); 314 315 return nullptr; 316 } 317 318 /// \brief A helper that folds a PHI node or a select. 319 static Value *foldPHINodeOrSelectInst(Instruction &I) { 320 if (PHINode *PN = dyn_cast<PHINode>(&I)) { 321 // If PN merges together the same value, return that value. 322 return PN->hasConstantValue(); 323 } 324 return foldSelectInst(cast<SelectInst>(I)); 325 } 326 327 /// \brief Builder for the alloca slices. 328 /// 329 /// This class builds a set of alloca slices by recursively visiting the uses 330 /// of an alloca and making a slice for each load and store at each offset. 331 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> { 332 friend class PtrUseVisitor<SliceBuilder>; 333 friend class InstVisitor<SliceBuilder>; 334 typedef PtrUseVisitor<SliceBuilder> Base; 335 336 const uint64_t AllocSize; 337 AllocaSlices &AS; 338 339 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap; 340 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes; 341 342 /// \brief Set to de-duplicate dead instructions found in the use walk. 343 SmallPtrSet<Instruction *, 4> VisitedDeadInsts; 344 345 public: 346 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS) 347 : PtrUseVisitor<SliceBuilder>(DL), 348 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {} 349 350 private: 351 void markAsDead(Instruction &I) { 352 if (VisitedDeadInsts.insert(&I).second) 353 AS.DeadUsers.push_back(&I); 354 } 355 356 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size, 357 bool IsSplittable = false) { 358 // Completely skip uses which have a zero size or start either before or 359 // past the end of the allocation. 360 if (Size == 0 || Offset.uge(AllocSize)) { 361 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset 362 << " which has zero size or starts outside of the " 363 << AllocSize << " byte alloca:\n" 364 << " alloca: " << AS.AI << "\n" 365 << " use: " << I << "\n"); 366 return markAsDead(I); 367 } 368 369 uint64_t BeginOffset = Offset.getZExtValue(); 370 uint64_t EndOffset = BeginOffset + Size; 371 372 // Clamp the end offset to the end of the allocation. Note that this is 373 // formulated to handle even the case where "BeginOffset + Size" overflows. 374 // This may appear superficially to be something we could ignore entirely, 375 // but that is not so! There may be widened loads or PHI-node uses where 376 // some instructions are dead but not others. We can't completely ignore 377 // them, and so have to record at least the information here. 378 assert(AllocSize >= BeginOffset); // Established above. 379 if (Size > AllocSize - BeginOffset) { 380 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset 381 << " to remain within the " << AllocSize << " byte alloca:\n" 382 << " alloca: " << AS.AI << "\n" 383 << " use: " << I << "\n"); 384 EndOffset = AllocSize; 385 } 386 387 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable)); 388 } 389 390 void visitBitCastInst(BitCastInst &BC) { 391 if (BC.use_empty()) 392 return markAsDead(BC); 393 394 return Base::visitBitCastInst(BC); 395 } 396 397 void visitGetElementPtrInst(GetElementPtrInst &GEPI) { 398 if (GEPI.use_empty()) 399 return markAsDead(GEPI); 400 401 if (SROAStrictInbounds && GEPI.isInBounds()) { 402 // FIXME: This is a manually un-factored variant of the basic code inside 403 // of GEPs with checking of the inbounds invariant specified in the 404 // langref in a very strict sense. If we ever want to enable 405 // SROAStrictInbounds, this code should be factored cleanly into 406 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds 407 // by writing out the code here where we have tho underlying allocation 408 // size readily available. 409 APInt GEPOffset = Offset; 410 for (gep_type_iterator GTI = gep_type_begin(GEPI), 411 GTE = gep_type_end(GEPI); 412 GTI != GTE; ++GTI) { 413 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); 414 if (!OpC) 415 break; 416 417 // Handle a struct index, which adds its field offset to the pointer. 418 if (StructType *STy = dyn_cast<StructType>(*GTI)) { 419 unsigned ElementIdx = OpC->getZExtValue(); 420 const StructLayout *SL = DL.getStructLayout(STy); 421 GEPOffset += 422 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx)); 423 } else { 424 // For array or vector indices, scale the index by the size of the type. 425 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth()); 426 GEPOffset += Index * APInt(Offset.getBitWidth(), 427 DL.getTypeAllocSize(GTI.getIndexedType())); 428 } 429 430 // If this index has computed an intermediate pointer which is not 431 // inbounds, then the result of the GEP is a poison value and we can 432 // delete it and all uses. 433 if (GEPOffset.ugt(AllocSize)) 434 return markAsDead(GEPI); 435 } 436 } 437 438 return Base::visitGetElementPtrInst(GEPI); 439 } 440 441 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset, 442 uint64_t Size, bool IsVolatile) { 443 // We allow splitting of loads and stores where the type is an integer type 444 // and cover the entire alloca. This prevents us from splitting over 445 // eagerly. 446 // FIXME: In the great blue eventually, we should eagerly split all integer 447 // loads and stores, and then have a separate step that merges adjacent 448 // alloca partitions into a single partition suitable for integer widening. 449 // Or we should skip the merge step and rely on GVN and other passes to 450 // merge adjacent loads and stores that survive mem2reg. 451 bool IsSplittable = 452 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize; 453 454 insertUse(I, Offset, Size, IsSplittable); 455 } 456 457 void visitLoadInst(LoadInst &LI) { 458 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) && 459 "All simple FCA loads should have been pre-split"); 460 461 if (!IsOffsetKnown) 462 return PI.setAborted(&LI); 463 464 uint64_t Size = DL.getTypeStoreSize(LI.getType()); 465 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile()); 466 } 467 468 void visitStoreInst(StoreInst &SI) { 469 Value *ValOp = SI.getValueOperand(); 470 if (ValOp == *U) 471 return PI.setEscapedAndAborted(&SI); 472 if (!IsOffsetKnown) 473 return PI.setAborted(&SI); 474 475 uint64_t Size = DL.getTypeStoreSize(ValOp->getType()); 476 477 // If this memory access can be shown to *statically* extend outside the 478 // bounds of of the allocation, it's behavior is undefined, so simply 479 // ignore it. Note that this is more strict than the generic clamping 480 // behavior of insertUse. We also try to handle cases which might run the 481 // risk of overflow. 482 // FIXME: We should instead consider the pointer to have escaped if this 483 // function is being instrumented for addressing bugs or race conditions. 484 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) { 485 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset 486 << " which extends past the end of the " << AllocSize 487 << " byte alloca:\n" 488 << " alloca: " << AS.AI << "\n" 489 << " use: " << SI << "\n"); 490 return markAsDead(SI); 491 } 492 493 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) && 494 "All simple FCA stores should have been pre-split"); 495 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile()); 496 } 497 498 499 void visitMemSetInst(MemSetInst &II) { 500 assert(II.getRawDest() == *U && "Pointer use is not the destination?"); 501 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); 502 if ((Length && Length->getValue() == 0) || 503 (IsOffsetKnown && Offset.uge(AllocSize))) 504 // Zero-length mem transfer intrinsics can be ignored entirely. 505 return markAsDead(II); 506 507 if (!IsOffsetKnown) 508 return PI.setAborted(&II); 509 510 insertUse(II, Offset, 511 Length ? Length->getLimitedValue() 512 : AllocSize - Offset.getLimitedValue(), 513 (bool)Length); 514 } 515 516 void visitMemTransferInst(MemTransferInst &II) { 517 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); 518 if (Length && Length->getValue() == 0) 519 // Zero-length mem transfer intrinsics can be ignored entirely. 520 return markAsDead(II); 521 522 // Because we can visit these intrinsics twice, also check to see if the 523 // first time marked this instruction as dead. If so, skip it. 524 if (VisitedDeadInsts.count(&II)) 525 return; 526 527 if (!IsOffsetKnown) 528 return PI.setAborted(&II); 529 530 // This side of the transfer is completely out-of-bounds, and so we can 531 // nuke the entire transfer. However, we also need to nuke the other side 532 // if already added to our partitions. 533 // FIXME: Yet another place we really should bypass this when 534 // instrumenting for ASan. 535 if (Offset.uge(AllocSize)) { 536 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II); 537 if (MTPI != MemTransferSliceMap.end()) 538 AS.Slices[MTPI->second].kill(); 539 return markAsDead(II); 540 } 541 542 uint64_t RawOffset = Offset.getLimitedValue(); 543 uint64_t Size = Length ? Length->getLimitedValue() 544 : AllocSize - RawOffset; 545 546 // Check for the special case where the same exact value is used for both 547 // source and dest. 548 if (*U == II.getRawDest() && *U == II.getRawSource()) { 549 // For non-volatile transfers this is a no-op. 550 if (!II.isVolatile()) 551 return markAsDead(II); 552 553 return insertUse(II, Offset, Size, /*IsSplittable=*/false); 554 } 555 556 // If we have seen both source and destination for a mem transfer, then 557 // they both point to the same alloca. 558 bool Inserted; 559 SmallDenseMap<Instruction *, unsigned>::iterator MTPI; 560 std::tie(MTPI, Inserted) = 561 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size())); 562 unsigned PrevIdx = MTPI->second; 563 if (!Inserted) { 564 Slice &PrevP = AS.Slices[PrevIdx]; 565 566 // Check if the begin offsets match and this is a non-volatile transfer. 567 // In that case, we can completely elide the transfer. 568 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) { 569 PrevP.kill(); 570 return markAsDead(II); 571 } 572 573 // Otherwise we have an offset transfer within the same alloca. We can't 574 // split those. 575 PrevP.makeUnsplittable(); 576 } 577 578 // Insert the use now that we've fixed up the splittable nature. 579 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length); 580 581 // Check that we ended up with a valid index in the map. 582 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II && 583 "Map index doesn't point back to a slice with this user."); 584 } 585 586 // Disable SRoA for any intrinsics except for lifetime invariants. 587 // FIXME: What about debug intrinsics? This matches old behavior, but 588 // doesn't make sense. 589 void visitIntrinsicInst(IntrinsicInst &II) { 590 if (!IsOffsetKnown) 591 return PI.setAborted(&II); 592 593 if (II.getIntrinsicID() == Intrinsic::lifetime_start || 594 II.getIntrinsicID() == Intrinsic::lifetime_end) { 595 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0)); 596 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(), 597 Length->getLimitedValue()); 598 insertUse(II, Offset, Size, true); 599 return; 600 } 601 602 Base::visitIntrinsicInst(II); 603 } 604 605 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) { 606 // We consider any PHI or select that results in a direct load or store of 607 // the same offset to be a viable use for slicing purposes. These uses 608 // are considered unsplittable and the size is the maximum loaded or stored 609 // size. 610 SmallPtrSet<Instruction *, 4> Visited; 611 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses; 612 Visited.insert(Root); 613 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root)); 614 // If there are no loads or stores, the access is dead. We mark that as 615 // a size zero access. 616 Size = 0; 617 do { 618 Instruction *I, *UsedI; 619 std::tie(UsedI, I) = Uses.pop_back_val(); 620 621 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 622 Size = std::max(Size, DL.getTypeStoreSize(LI->getType())); 623 continue; 624 } 625 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 626 Value *Op = SI->getOperand(0); 627 if (Op == UsedI) 628 return SI; 629 Size = std::max(Size, DL.getTypeStoreSize(Op->getType())); 630 continue; 631 } 632 633 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) { 634 if (!GEP->hasAllZeroIndices()) 635 return GEP; 636 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) && 637 !isa<SelectInst>(I)) { 638 return I; 639 } 640 641 for (User *U : I->users()) 642 if (Visited.insert(cast<Instruction>(U)).second) 643 Uses.push_back(std::make_pair(I, cast<Instruction>(U))); 644 } while (!Uses.empty()); 645 646 return nullptr; 647 } 648 649 void visitPHINodeOrSelectInst(Instruction &I) { 650 assert(isa<PHINode>(I) || isa<SelectInst>(I)); 651 if (I.use_empty()) 652 return markAsDead(I); 653 654 // TODO: We could use SimplifyInstruction here to fold PHINodes and 655 // SelectInsts. However, doing so requires to change the current 656 // dead-operand-tracking mechanism. For instance, suppose neither loading 657 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not 658 // trap either. However, if we simply replace %U with undef using the 659 // current dead-operand-tracking mechanism, "load (select undef, undef, 660 // %other)" may trap because the select may return the first operand 661 // "undef". 662 if (Value *Result = foldPHINodeOrSelectInst(I)) { 663 if (Result == *U) 664 // If the result of the constant fold will be the pointer, recurse 665 // through the PHI/select as if we had RAUW'ed it. 666 enqueueUsers(I); 667 else 668 // Otherwise the operand to the PHI/select is dead, and we can replace 669 // it with undef. 670 AS.DeadOperands.push_back(U); 671 672 return; 673 } 674 675 if (!IsOffsetKnown) 676 return PI.setAborted(&I); 677 678 // See if we already have computed info on this node. 679 uint64_t &Size = PHIOrSelectSizes[&I]; 680 if (!Size) { 681 // This is a new PHI/Select, check for an unsafe use of it. 682 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size)) 683 return PI.setAborted(UnsafeI); 684 } 685 686 // For PHI and select operands outside the alloca, we can't nuke the entire 687 // phi or select -- the other side might still be relevant, so we special 688 // case them here and use a separate structure to track the operands 689 // themselves which should be replaced with undef. 690 // FIXME: This should instead be escaped in the event we're instrumenting 691 // for address sanitization. 692 if (Offset.uge(AllocSize)) { 693 AS.DeadOperands.push_back(U); 694 return; 695 } 696 697 insertUse(I, Offset, Size); 698 } 699 700 void visitPHINode(PHINode &PN) { 701 visitPHINodeOrSelectInst(PN); 702 } 703 704 void visitSelectInst(SelectInst &SI) { 705 visitPHINodeOrSelectInst(SI); 706 } 707 708 /// \brief Disable SROA entirely if there are unhandled users of the alloca. 709 void visitInstruction(Instruction &I) { 710 PI.setAborted(&I); 711 } 712 }; 713 714 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI) 715 : 716 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 717 AI(AI), 718 #endif 719 PointerEscapingInstr(nullptr) { 720 SliceBuilder PB(DL, AI, *this); 721 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI); 722 if (PtrI.isEscaped() || PtrI.isAborted()) { 723 // FIXME: We should sink the escape vs. abort info into the caller nicely, 724 // possibly by just storing the PtrInfo in the AllocaSlices. 725 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst() 726 : PtrI.getAbortingInst(); 727 assert(PointerEscapingInstr && "Did not track a bad instruction"); 728 return; 729 } 730 731 Slices.erase(std::remove_if(Slices.begin(), Slices.end(), 732 std::mem_fun_ref(&Slice::isDead)), 733 Slices.end()); 734 735 #if __cplusplus >= 201103L && !defined(NDEBUG) 736 if (SROARandomShuffleSlices) { 737 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec())); 738 std::shuffle(Slices.begin(), Slices.end(), MT); 739 } 740 #endif 741 742 // Sort the uses. This arranges for the offsets to be in ascending order, 743 // and the sizes to be in descending order. 744 std::sort(Slices.begin(), Slices.end()); 745 } 746 747 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 748 749 void AllocaSlices::print(raw_ostream &OS, const_iterator I, 750 StringRef Indent) const { 751 printSlice(OS, I, Indent); 752 printUse(OS, I, Indent); 753 } 754 755 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I, 756 StringRef Indent) const { 757 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")" 758 << " slice #" << (I - begin()) 759 << (I->isSplittable() ? " (splittable)" : "") << "\n"; 760 } 761 762 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I, 763 StringRef Indent) const { 764 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n"; 765 } 766 767 void AllocaSlices::print(raw_ostream &OS) const { 768 if (PointerEscapingInstr) { 769 OS << "Can't analyze slices for alloca: " << AI << "\n" 770 << " A pointer to this alloca escaped by:\n" 771 << " " << *PointerEscapingInstr << "\n"; 772 return; 773 } 774 775 OS << "Slices of alloca: " << AI << "\n"; 776 for (const_iterator I = begin(), E = end(); I != E; ++I) 777 print(OS, I); 778 } 779 780 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const { 781 print(dbgs(), I); 782 } 783 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); } 784 785 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 786 787 namespace { 788 /// \brief Implementation of LoadAndStorePromoter for promoting allocas. 789 /// 790 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting 791 /// the loads and stores of an alloca instruction, as well as updating its 792 /// debug information. This is used when a domtree is unavailable and thus 793 /// mem2reg in its full form can't be used to handle promotion of allocas to 794 /// scalar values. 795 class AllocaPromoter : public LoadAndStorePromoter { 796 AllocaInst &AI; 797 DIBuilder &DIB; 798 799 SmallVector<DbgDeclareInst *, 4> DDIs; 800 SmallVector<DbgValueInst *, 4> DVIs; 801 802 public: 803 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S, 804 AllocaInst &AI, DIBuilder &DIB) 805 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {} 806 807 void run(const SmallVectorImpl<Instruction*> &Insts) { 808 // Retain the debug information attached to the alloca for use when 809 // rewriting loads and stores. 810 if (auto *L = LocalAsMetadata::getIfExists(&AI)) { 811 if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) { 812 for (User *U : DebugNode->users()) 813 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U)) 814 DDIs.push_back(DDI); 815 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U)) 816 DVIs.push_back(DVI); 817 } 818 } 819 820 LoadAndStorePromoter::run(Insts); 821 822 // While we have the debug information, clear it off of the alloca. The 823 // caller takes care of deleting the alloca. 824 while (!DDIs.empty()) 825 DDIs.pop_back_val()->eraseFromParent(); 826 while (!DVIs.empty()) 827 DVIs.pop_back_val()->eraseFromParent(); 828 } 829 830 bool isInstInList(Instruction *I, 831 const SmallVectorImpl<Instruction*> &Insts) const override { 832 Value *Ptr; 833 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 834 Ptr = LI->getOperand(0); 835 else 836 Ptr = cast<StoreInst>(I)->getPointerOperand(); 837 838 // Only used to detect cycles, which will be rare and quickly found as 839 // we're walking up a chain of defs rather than down through uses. 840 SmallPtrSet<Value *, 4> Visited; 841 842 do { 843 if (Ptr == &AI) 844 return true; 845 846 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) 847 Ptr = BCI->getOperand(0); 848 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) 849 Ptr = GEPI->getPointerOperand(); 850 else 851 return false; 852 853 } while (Visited.insert(Ptr).second); 854 855 return false; 856 } 857 858 void updateDebugInfo(Instruction *Inst) const override { 859 for (DbgDeclareInst *DDI : DDIs) 860 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 861 ConvertDebugDeclareToDebugValue(DDI, SI, DIB); 862 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 863 ConvertDebugDeclareToDebugValue(DDI, LI, DIB); 864 for (DbgValueInst *DVI : DVIs) { 865 Value *Arg = nullptr; 866 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 867 // If an argument is zero extended then use argument directly. The ZExt 868 // may be zapped by an optimization pass in future. 869 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0))) 870 Arg = dyn_cast<Argument>(ZExt->getOperand(0)); 871 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0))) 872 Arg = dyn_cast<Argument>(SExt->getOperand(0)); 873 if (!Arg) 874 Arg = SI->getValueOperand(); 875 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 876 Arg = LI->getPointerOperand(); 877 } else { 878 continue; 879 } 880 Instruction *DbgVal = 881 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()), 882 DIExpression(DVI->getExpression()), Inst); 883 DbgVal->setDebugLoc(DVI->getDebugLoc()); 884 } 885 } 886 }; 887 } // end anon namespace 888 889 890 namespace { 891 /// \brief An optimization pass providing Scalar Replacement of Aggregates. 892 /// 893 /// This pass takes allocations which can be completely analyzed (that is, they 894 /// don't escape) and tries to turn them into scalar SSA values. There are 895 /// a few steps to this process. 896 /// 897 /// 1) It takes allocations of aggregates and analyzes the ways in which they 898 /// are used to try to split them into smaller allocations, ideally of 899 /// a single scalar data type. It will split up memcpy and memset accesses 900 /// as necessary and try to isolate individual scalar accesses. 901 /// 2) It will transform accesses into forms which are suitable for SSA value 902 /// promotion. This can be replacing a memset with a scalar store of an 903 /// integer value, or it can involve speculating operations on a PHI or 904 /// select to be a PHI or select of the results. 905 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly 906 /// onto insert and extract operations on a vector value, and convert them to 907 /// this form. By doing so, it will enable promotion of vector aggregates to 908 /// SSA vector values. 909 class SROA : public FunctionPass { 910 const bool RequiresDomTree; 911 912 LLVMContext *C; 913 const DataLayout *DL; 914 DominatorTree *DT; 915 AssumptionTracker *AT; 916 917 /// \brief Worklist of alloca instructions to simplify. 918 /// 919 /// Each alloca in the function is added to this. Each new alloca formed gets 920 /// added to it as well to recursively simplify unless that alloca can be 921 /// directly promoted. Finally, each time we rewrite a use of an alloca other 922 /// the one being actively rewritten, we add it back onto the list if not 923 /// already present to ensure it is re-visited. 924 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist; 925 926 /// \brief A collection of instructions to delete. 927 /// We try to batch deletions to simplify code and make things a bit more 928 /// efficient. 929 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts; 930 931 /// \brief Post-promotion worklist. 932 /// 933 /// Sometimes we discover an alloca which has a high probability of becoming 934 /// viable for SROA after a round of promotion takes place. In those cases, 935 /// the alloca is enqueued here for re-processing. 936 /// 937 /// Note that we have to be very careful to clear allocas out of this list in 938 /// the event they are deleted. 939 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist; 940 941 /// \brief A collection of alloca instructions we can directly promote. 942 std::vector<AllocaInst *> PromotableAllocas; 943 944 /// \brief A worklist of PHIs to speculate prior to promoting allocas. 945 /// 946 /// All of these PHIs have been checked for the safety of speculation and by 947 /// being speculated will allow promoting allocas currently in the promotable 948 /// queue. 949 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs; 950 951 /// \brief A worklist of select instructions to speculate prior to promoting 952 /// allocas. 953 /// 954 /// All of these select instructions have been checked for the safety of 955 /// speculation and by being speculated will allow promoting allocas 956 /// currently in the promotable queue. 957 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects; 958 959 public: 960 SROA(bool RequiresDomTree = true) 961 : FunctionPass(ID), RequiresDomTree(RequiresDomTree), 962 C(nullptr), DL(nullptr), DT(nullptr) { 963 initializeSROAPass(*PassRegistry::getPassRegistry()); 964 } 965 bool runOnFunction(Function &F) override; 966 void getAnalysisUsage(AnalysisUsage &AU) const override; 967 968 const char *getPassName() const override { return "SROA"; } 969 static char ID; 970 971 private: 972 friend class PHIOrSelectSpeculator; 973 friend class AllocaSliceRewriter; 974 975 bool rewritePartition(AllocaInst &AI, AllocaSlices &AS, 976 AllocaSlices::iterator B, AllocaSlices::iterator E, 977 int64_t BeginOffset, int64_t EndOffset, 978 ArrayRef<AllocaSlices::iterator> SplitUses); 979 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS); 980 bool runOnAlloca(AllocaInst &AI); 981 void clobberUse(Use &U); 982 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas); 983 bool promoteAllocas(Function &F); 984 }; 985 } 986 987 char SROA::ID = 0; 988 989 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) { 990 return new SROA(RequiresDomTree); 991 } 992 993 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", 994 false, false) 995 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker) 996 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 997 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", 998 false, false) 999 1000 /// Walk the range of a partitioning looking for a common type to cover this 1001 /// sequence of slices. 1002 static Type *findCommonType(AllocaSlices::const_iterator B, 1003 AllocaSlices::const_iterator E, 1004 uint64_t EndOffset) { 1005 Type *Ty = nullptr; 1006 bool TyIsCommon = true; 1007 IntegerType *ITy = nullptr; 1008 1009 // Note that we need to look at *every* alloca slice's Use to ensure we 1010 // always get consistent results regardless of the order of slices. 1011 for (AllocaSlices::const_iterator I = B; I != E; ++I) { 1012 Use *U = I->getUse(); 1013 if (isa<IntrinsicInst>(*U->getUser())) 1014 continue; 1015 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset) 1016 continue; 1017 1018 Type *UserTy = nullptr; 1019 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 1020 UserTy = LI->getType(); 1021 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 1022 UserTy = SI->getValueOperand()->getType(); 1023 } 1024 1025 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) { 1026 // If the type is larger than the partition, skip it. We only encounter 1027 // this for split integer operations where we want to use the type of the 1028 // entity causing the split. Also skip if the type is not a byte width 1029 // multiple. 1030 if (UserITy->getBitWidth() % 8 != 0 || 1031 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset())) 1032 continue; 1033 1034 // Track the largest bitwidth integer type used in this way in case there 1035 // is no common type. 1036 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth()) 1037 ITy = UserITy; 1038 } 1039 1040 // To avoid depending on the order of slices, Ty and TyIsCommon must not 1041 // depend on types skipped above. 1042 if (!UserTy || (Ty && Ty != UserTy)) 1043 TyIsCommon = false; // Give up on anything but an iN type. 1044 else 1045 Ty = UserTy; 1046 } 1047 1048 return TyIsCommon ? Ty : ITy; 1049 } 1050 1051 /// PHI instructions that use an alloca and are subsequently loaded can be 1052 /// rewritten to load both input pointers in the pred blocks and then PHI the 1053 /// results, allowing the load of the alloca to be promoted. 1054 /// From this: 1055 /// %P2 = phi [i32* %Alloca, i32* %Other] 1056 /// %V = load i32* %P2 1057 /// to: 1058 /// %V1 = load i32* %Alloca -> will be mem2reg'd 1059 /// ... 1060 /// %V2 = load i32* %Other 1061 /// ... 1062 /// %V = phi [i32 %V1, i32 %V2] 1063 /// 1064 /// We can do this to a select if its only uses are loads and if the operands 1065 /// to the select can be loaded unconditionally. 1066 /// 1067 /// FIXME: This should be hoisted into a generic utility, likely in 1068 /// Transforms/Util/Local.h 1069 static bool isSafePHIToSpeculate(PHINode &PN, 1070 const DataLayout *DL = nullptr) { 1071 // For now, we can only do this promotion if the load is in the same block 1072 // as the PHI, and if there are no stores between the phi and load. 1073 // TODO: Allow recursive phi users. 1074 // TODO: Allow stores. 1075 BasicBlock *BB = PN.getParent(); 1076 unsigned MaxAlign = 0; 1077 bool HaveLoad = false; 1078 for (User *U : PN.users()) { 1079 LoadInst *LI = dyn_cast<LoadInst>(U); 1080 if (!LI || !LI->isSimple()) 1081 return false; 1082 1083 // For now we only allow loads in the same block as the PHI. This is 1084 // a common case that happens when instcombine merges two loads through 1085 // a PHI. 1086 if (LI->getParent() != BB) 1087 return false; 1088 1089 // Ensure that there are no instructions between the PHI and the load that 1090 // could store. 1091 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI) 1092 if (BBI->mayWriteToMemory()) 1093 return false; 1094 1095 MaxAlign = std::max(MaxAlign, LI->getAlignment()); 1096 HaveLoad = true; 1097 } 1098 1099 if (!HaveLoad) 1100 return false; 1101 1102 // We can only transform this if it is safe to push the loads into the 1103 // predecessor blocks. The only thing to watch out for is that we can't put 1104 // a possibly trapping load in the predecessor if it is a critical edge. 1105 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) { 1106 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator(); 1107 Value *InVal = PN.getIncomingValue(Idx); 1108 1109 // If the value is produced by the terminator of the predecessor (an 1110 // invoke) or it has side-effects, there is no valid place to put a load 1111 // in the predecessor. 1112 if (TI == InVal || TI->mayHaveSideEffects()) 1113 return false; 1114 1115 // If the predecessor has a single successor, then the edge isn't 1116 // critical. 1117 if (TI->getNumSuccessors() == 1) 1118 continue; 1119 1120 // If this pointer is always safe to load, or if we can prove that there 1121 // is already a load in the block, then we can move the load to the pred 1122 // block. 1123 if (InVal->isDereferenceablePointer(DL) || 1124 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL)) 1125 continue; 1126 1127 return false; 1128 } 1129 1130 return true; 1131 } 1132 1133 static void speculatePHINodeLoads(PHINode &PN) { 1134 DEBUG(dbgs() << " original: " << PN << "\n"); 1135 1136 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType(); 1137 IRBuilderTy PHIBuilder(&PN); 1138 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(), 1139 PN.getName() + ".sroa.speculated"); 1140 1141 // Get the AA tags and alignment to use from one of the loads. It doesn't 1142 // matter which one we get and if any differ. 1143 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back()); 1144 1145 AAMDNodes AATags; 1146 SomeLoad->getAAMetadata(AATags); 1147 unsigned Align = SomeLoad->getAlignment(); 1148 1149 // Rewrite all loads of the PN to use the new PHI. 1150 while (!PN.use_empty()) { 1151 LoadInst *LI = cast<LoadInst>(PN.user_back()); 1152 LI->replaceAllUsesWith(NewPN); 1153 LI->eraseFromParent(); 1154 } 1155 1156 // Inject loads into all of the pred blocks. 1157 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) { 1158 BasicBlock *Pred = PN.getIncomingBlock(Idx); 1159 TerminatorInst *TI = Pred->getTerminator(); 1160 Value *InVal = PN.getIncomingValue(Idx); 1161 IRBuilderTy PredBuilder(TI); 1162 1163 LoadInst *Load = PredBuilder.CreateLoad( 1164 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName())); 1165 ++NumLoadsSpeculated; 1166 Load->setAlignment(Align); 1167 if (AATags) 1168 Load->setAAMetadata(AATags); 1169 NewPN->addIncoming(Load, Pred); 1170 } 1171 1172 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n"); 1173 PN.eraseFromParent(); 1174 } 1175 1176 /// Select instructions that use an alloca and are subsequently loaded can be 1177 /// rewritten to load both input pointers and then select between the result, 1178 /// allowing the load of the alloca to be promoted. 1179 /// From this: 1180 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other 1181 /// %V = load i32* %P2 1182 /// to: 1183 /// %V1 = load i32* %Alloca -> will be mem2reg'd 1184 /// %V2 = load i32* %Other 1185 /// %V = select i1 %cond, i32 %V1, i32 %V2 1186 /// 1187 /// We can do this to a select if its only uses are loads and if the operand 1188 /// to the select can be loaded unconditionally. 1189 static bool isSafeSelectToSpeculate(SelectInst &SI, 1190 const DataLayout *DL = nullptr) { 1191 Value *TValue = SI.getTrueValue(); 1192 Value *FValue = SI.getFalseValue(); 1193 bool TDerefable = TValue->isDereferenceablePointer(DL); 1194 bool FDerefable = FValue->isDereferenceablePointer(DL); 1195 1196 for (User *U : SI.users()) { 1197 LoadInst *LI = dyn_cast<LoadInst>(U); 1198 if (!LI || !LI->isSimple()) 1199 return false; 1200 1201 // Both operands to the select need to be dereferencable, either 1202 // absolutely (e.g. allocas) or at this point because we can see other 1203 // accesses to it. 1204 if (!TDerefable && 1205 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL)) 1206 return false; 1207 if (!FDerefable && 1208 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL)) 1209 return false; 1210 } 1211 1212 return true; 1213 } 1214 1215 static void speculateSelectInstLoads(SelectInst &SI) { 1216 DEBUG(dbgs() << " original: " << SI << "\n"); 1217 1218 IRBuilderTy IRB(&SI); 1219 Value *TV = SI.getTrueValue(); 1220 Value *FV = SI.getFalseValue(); 1221 // Replace the loads of the select with a select of two loads. 1222 while (!SI.use_empty()) { 1223 LoadInst *LI = cast<LoadInst>(SI.user_back()); 1224 assert(LI->isSimple() && "We only speculate simple loads"); 1225 1226 IRB.SetInsertPoint(LI); 1227 LoadInst *TL = 1228 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true"); 1229 LoadInst *FL = 1230 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false"); 1231 NumLoadsSpeculated += 2; 1232 1233 // Transfer alignment and AA info if present. 1234 TL->setAlignment(LI->getAlignment()); 1235 FL->setAlignment(LI->getAlignment()); 1236 1237 AAMDNodes Tags; 1238 LI->getAAMetadata(Tags); 1239 if (Tags) { 1240 TL->setAAMetadata(Tags); 1241 FL->setAAMetadata(Tags); 1242 } 1243 1244 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL, 1245 LI->getName() + ".sroa.speculated"); 1246 1247 DEBUG(dbgs() << " speculated to: " << *V << "\n"); 1248 LI->replaceAllUsesWith(V); 1249 LI->eraseFromParent(); 1250 } 1251 SI.eraseFromParent(); 1252 } 1253 1254 /// \brief Build a GEP out of a base pointer and indices. 1255 /// 1256 /// This will return the BasePtr if that is valid, or build a new GEP 1257 /// instruction using the IRBuilder if GEP-ing is needed. 1258 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr, 1259 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) { 1260 if (Indices.empty()) 1261 return BasePtr; 1262 1263 // A single zero index is a no-op, so check for this and avoid building a GEP 1264 // in that case. 1265 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero()) 1266 return BasePtr; 1267 1268 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx"); 1269 } 1270 1271 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward 1272 /// TargetTy without changing the offset of the pointer. 1273 /// 1274 /// This routine assumes we've already established a properly offset GEP with 1275 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with 1276 /// zero-indices down through type layers until we find one the same as 1277 /// TargetTy. If we can't find one with the same type, we at least try to use 1278 /// one with the same size. If none of that works, we just produce the GEP as 1279 /// indicated by Indices to have the correct offset. 1280 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL, 1281 Value *BasePtr, Type *Ty, Type *TargetTy, 1282 SmallVectorImpl<Value *> &Indices, 1283 Twine NamePrefix) { 1284 if (Ty == TargetTy) 1285 return buildGEP(IRB, BasePtr, Indices, NamePrefix); 1286 1287 // Pointer size to use for the indices. 1288 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType()); 1289 1290 // See if we can descend into a struct and locate a field with the correct 1291 // type. 1292 unsigned NumLayers = 0; 1293 Type *ElementTy = Ty; 1294 do { 1295 if (ElementTy->isPointerTy()) 1296 break; 1297 1298 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) { 1299 ElementTy = ArrayTy->getElementType(); 1300 Indices.push_back(IRB.getIntN(PtrSize, 0)); 1301 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) { 1302 ElementTy = VectorTy->getElementType(); 1303 Indices.push_back(IRB.getInt32(0)); 1304 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) { 1305 if (STy->element_begin() == STy->element_end()) 1306 break; // Nothing left to descend into. 1307 ElementTy = *STy->element_begin(); 1308 Indices.push_back(IRB.getInt32(0)); 1309 } else { 1310 break; 1311 } 1312 ++NumLayers; 1313 } while (ElementTy != TargetTy); 1314 if (ElementTy != TargetTy) 1315 Indices.erase(Indices.end() - NumLayers, Indices.end()); 1316 1317 return buildGEP(IRB, BasePtr, Indices, NamePrefix); 1318 } 1319 1320 /// \brief Recursively compute indices for a natural GEP. 1321 /// 1322 /// This is the recursive step for getNaturalGEPWithOffset that walks down the 1323 /// element types adding appropriate indices for the GEP. 1324 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL, 1325 Value *Ptr, Type *Ty, APInt &Offset, 1326 Type *TargetTy, 1327 SmallVectorImpl<Value *> &Indices, 1328 Twine NamePrefix) { 1329 if (Offset == 0) 1330 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix); 1331 1332 // We can't recurse through pointer types. 1333 if (Ty->isPointerTy()) 1334 return nullptr; 1335 1336 // We try to analyze GEPs over vectors here, but note that these GEPs are 1337 // extremely poorly defined currently. The long-term goal is to remove GEPing 1338 // over a vector from the IR completely. 1339 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) { 1340 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType()); 1341 if (ElementSizeInBits % 8 != 0) { 1342 // GEPs over non-multiple of 8 size vector elements are invalid. 1343 return nullptr; 1344 } 1345 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8); 1346 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1347 if (NumSkippedElements.ugt(VecTy->getNumElements())) 1348 return nullptr; 1349 Offset -= NumSkippedElements * ElementSize; 1350 Indices.push_back(IRB.getInt(NumSkippedElements)); 1351 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(), 1352 Offset, TargetTy, Indices, NamePrefix); 1353 } 1354 1355 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) { 1356 Type *ElementTy = ArrTy->getElementType(); 1357 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy)); 1358 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1359 if (NumSkippedElements.ugt(ArrTy->getNumElements())) 1360 return nullptr; 1361 1362 Offset -= NumSkippedElements * ElementSize; 1363 Indices.push_back(IRB.getInt(NumSkippedElements)); 1364 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1365 Indices, NamePrefix); 1366 } 1367 1368 StructType *STy = dyn_cast<StructType>(Ty); 1369 if (!STy) 1370 return nullptr; 1371 1372 const StructLayout *SL = DL.getStructLayout(STy); 1373 uint64_t StructOffset = Offset.getZExtValue(); 1374 if (StructOffset >= SL->getSizeInBytes()) 1375 return nullptr; 1376 unsigned Index = SL->getElementContainingOffset(StructOffset); 1377 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index)); 1378 Type *ElementTy = STy->getElementType(Index); 1379 if (Offset.uge(DL.getTypeAllocSize(ElementTy))) 1380 return nullptr; // The offset points into alignment padding. 1381 1382 Indices.push_back(IRB.getInt32(Index)); 1383 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1384 Indices, NamePrefix); 1385 } 1386 1387 /// \brief Get a natural GEP from a base pointer to a particular offset and 1388 /// resulting in a particular type. 1389 /// 1390 /// The goal is to produce a "natural" looking GEP that works with the existing 1391 /// composite types to arrive at the appropriate offset and element type for 1392 /// a pointer. TargetTy is the element type the returned GEP should point-to if 1393 /// possible. We recurse by decreasing Offset, adding the appropriate index to 1394 /// Indices, and setting Ty to the result subtype. 1395 /// 1396 /// If no natural GEP can be constructed, this function returns null. 1397 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL, 1398 Value *Ptr, APInt Offset, Type *TargetTy, 1399 SmallVectorImpl<Value *> &Indices, 1400 Twine NamePrefix) { 1401 PointerType *Ty = cast<PointerType>(Ptr->getType()); 1402 1403 // Don't consider any GEPs through an i8* as natural unless the TargetTy is 1404 // an i8. 1405 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8)) 1406 return nullptr; 1407 1408 Type *ElementTy = Ty->getElementType(); 1409 if (!ElementTy->isSized()) 1410 return nullptr; // We can't GEP through an unsized element. 1411 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy)); 1412 if (ElementSize == 0) 1413 return nullptr; // Zero-length arrays can't help us build a natural GEP. 1414 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1415 1416 Offset -= NumSkippedElements * ElementSize; 1417 Indices.push_back(IRB.getInt(NumSkippedElements)); 1418 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1419 Indices, NamePrefix); 1420 } 1421 1422 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the 1423 /// resulting pointer has PointerTy. 1424 /// 1425 /// This tries very hard to compute a "natural" GEP which arrives at the offset 1426 /// and produces the pointer type desired. Where it cannot, it will try to use 1427 /// the natural GEP to arrive at the offset and bitcast to the type. Where that 1428 /// fails, it will try to use an existing i8* and GEP to the byte offset and 1429 /// bitcast to the type. 1430 /// 1431 /// The strategy for finding the more natural GEPs is to peel off layers of the 1432 /// pointer, walking back through bit casts and GEPs, searching for a base 1433 /// pointer from which we can compute a natural GEP with the desired 1434 /// properties. The algorithm tries to fold as many constant indices into 1435 /// a single GEP as possible, thus making each GEP more independent of the 1436 /// surrounding code. 1437 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, 1438 APInt Offset, Type *PointerTy, 1439 Twine NamePrefix) { 1440 // Even though we don't look through PHI nodes, we could be called on an 1441 // instruction in an unreachable block, which may be on a cycle. 1442 SmallPtrSet<Value *, 4> Visited; 1443 Visited.insert(Ptr); 1444 SmallVector<Value *, 4> Indices; 1445 1446 // We may end up computing an offset pointer that has the wrong type. If we 1447 // never are able to compute one directly that has the correct type, we'll 1448 // fall back to it, so keep it around here. 1449 Value *OffsetPtr = nullptr; 1450 1451 // Remember any i8 pointer we come across to re-use if we need to do a raw 1452 // byte offset. 1453 Value *Int8Ptr = nullptr; 1454 APInt Int8PtrOffset(Offset.getBitWidth(), 0); 1455 1456 Type *TargetTy = PointerTy->getPointerElementType(); 1457 1458 do { 1459 // First fold any existing GEPs into the offset. 1460 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) { 1461 APInt GEPOffset(Offset.getBitWidth(), 0); 1462 if (!GEP->accumulateConstantOffset(DL, GEPOffset)) 1463 break; 1464 Offset += GEPOffset; 1465 Ptr = GEP->getPointerOperand(); 1466 if (!Visited.insert(Ptr).second) 1467 break; 1468 } 1469 1470 // See if we can perform a natural GEP here. 1471 Indices.clear(); 1472 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy, 1473 Indices, NamePrefix)) { 1474 if (P->getType() == PointerTy) { 1475 // Zap any offset pointer that we ended up computing in previous rounds. 1476 if (OffsetPtr && OffsetPtr->use_empty()) 1477 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) 1478 I->eraseFromParent(); 1479 return P; 1480 } 1481 if (!OffsetPtr) { 1482 OffsetPtr = P; 1483 } 1484 } 1485 1486 // Stash this pointer if we've found an i8*. 1487 if (Ptr->getType()->isIntegerTy(8)) { 1488 Int8Ptr = Ptr; 1489 Int8PtrOffset = Offset; 1490 } 1491 1492 // Peel off a layer of the pointer and update the offset appropriately. 1493 if (Operator::getOpcode(Ptr) == Instruction::BitCast) { 1494 Ptr = cast<Operator>(Ptr)->getOperand(0); 1495 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) { 1496 if (GA->mayBeOverridden()) 1497 break; 1498 Ptr = GA->getAliasee(); 1499 } else { 1500 break; 1501 } 1502 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!"); 1503 } while (Visited.insert(Ptr).second); 1504 1505 if (!OffsetPtr) { 1506 if (!Int8Ptr) { 1507 Int8Ptr = IRB.CreateBitCast( 1508 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()), 1509 NamePrefix + "sroa_raw_cast"); 1510 Int8PtrOffset = Offset; 1511 } 1512 1513 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr : 1514 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset), 1515 NamePrefix + "sroa_raw_idx"); 1516 } 1517 Ptr = OffsetPtr; 1518 1519 // On the off chance we were targeting i8*, guard the bitcast here. 1520 if (Ptr->getType() != PointerTy) 1521 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast"); 1522 1523 return Ptr; 1524 } 1525 1526 /// \brief Test whether we can convert a value from the old to the new type. 1527 /// 1528 /// This predicate should be used to guard calls to convertValue in order to 1529 /// ensure that we only try to convert viable values. The strategy is that we 1530 /// will peel off single element struct and array wrappings to get to an 1531 /// underlying value, and convert that value. 1532 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) { 1533 if (OldTy == NewTy) 1534 return true; 1535 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy)) 1536 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy)) 1537 if (NewITy->getBitWidth() >= OldITy->getBitWidth()) 1538 return true; 1539 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy)) 1540 return false; 1541 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType()) 1542 return false; 1543 1544 // We can convert pointers to integers and vice-versa. Same for vectors 1545 // of pointers and integers. 1546 OldTy = OldTy->getScalarType(); 1547 NewTy = NewTy->getScalarType(); 1548 if (NewTy->isPointerTy() || OldTy->isPointerTy()) { 1549 if (NewTy->isPointerTy() && OldTy->isPointerTy()) 1550 return true; 1551 if (NewTy->isIntegerTy() || OldTy->isIntegerTy()) 1552 return true; 1553 return false; 1554 } 1555 1556 return true; 1557 } 1558 1559 /// \brief Generic routine to convert an SSA value to a value of a different 1560 /// type. 1561 /// 1562 /// This will try various different casting techniques, such as bitcasts, 1563 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test 1564 /// two types for viability with this routine. 1565 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V, 1566 Type *NewTy) { 1567 Type *OldTy = V->getType(); 1568 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type"); 1569 1570 if (OldTy == NewTy) 1571 return V; 1572 1573 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy)) 1574 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy)) 1575 if (NewITy->getBitWidth() > OldITy->getBitWidth()) 1576 return IRB.CreateZExt(V, NewITy); 1577 1578 // See if we need inttoptr for this type pair. A cast involving both scalars 1579 // and vectors requires and additional bitcast. 1580 if (OldTy->getScalarType()->isIntegerTy() && 1581 NewTy->getScalarType()->isPointerTy()) { 1582 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8* 1583 if (OldTy->isVectorTy() && !NewTy->isVectorTy()) 1584 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)), 1585 NewTy); 1586 1587 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*> 1588 if (!OldTy->isVectorTy() && NewTy->isVectorTy()) 1589 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)), 1590 NewTy); 1591 1592 return IRB.CreateIntToPtr(V, NewTy); 1593 } 1594 1595 // See if we need ptrtoint for this type pair. A cast involving both scalars 1596 // and vectors requires and additional bitcast. 1597 if (OldTy->getScalarType()->isPointerTy() && 1598 NewTy->getScalarType()->isIntegerTy()) { 1599 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128 1600 if (OldTy->isVectorTy() && !NewTy->isVectorTy()) 1601 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)), 1602 NewTy); 1603 1604 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32> 1605 if (!OldTy->isVectorTy() && NewTy->isVectorTy()) 1606 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)), 1607 NewTy); 1608 1609 return IRB.CreatePtrToInt(V, NewTy); 1610 } 1611 1612 return IRB.CreateBitCast(V, NewTy); 1613 } 1614 1615 /// \brief Test whether the given slice use can be promoted to a vector. 1616 /// 1617 /// This function is called to test each entry in a partioning which is slated 1618 /// for a single slice. 1619 static bool 1620 isVectorPromotionViableForSlice(const DataLayout &DL, uint64_t SliceBeginOffset, 1621 uint64_t SliceEndOffset, VectorType *Ty, 1622 uint64_t ElementSize, const Slice &S) { 1623 // First validate the slice offsets. 1624 uint64_t BeginOffset = 1625 std::max(S.beginOffset(), SliceBeginOffset) - SliceBeginOffset; 1626 uint64_t BeginIndex = BeginOffset / ElementSize; 1627 if (BeginIndex * ElementSize != BeginOffset || 1628 BeginIndex >= Ty->getNumElements()) 1629 return false; 1630 uint64_t EndOffset = 1631 std::min(S.endOffset(), SliceEndOffset) - SliceBeginOffset; 1632 uint64_t EndIndex = EndOffset / ElementSize; 1633 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements()) 1634 return false; 1635 1636 assert(EndIndex > BeginIndex && "Empty vector!"); 1637 uint64_t NumElements = EndIndex - BeginIndex; 1638 Type *SliceTy = (NumElements == 1) 1639 ? Ty->getElementType() 1640 : VectorType::get(Ty->getElementType(), NumElements); 1641 1642 Type *SplitIntTy = 1643 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8); 1644 1645 Use *U = S.getUse(); 1646 1647 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) { 1648 if (MI->isVolatile()) 1649 return false; 1650 if (!S.isSplittable()) 1651 return false; // Skip any unsplittable intrinsics. 1652 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) { 1653 if (II->getIntrinsicID() != Intrinsic::lifetime_start && 1654 II->getIntrinsicID() != Intrinsic::lifetime_end) 1655 return false; 1656 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) { 1657 // Disable vector promotion when there are loads or stores of an FCA. 1658 return false; 1659 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 1660 if (LI->isVolatile()) 1661 return false; 1662 Type *LTy = LI->getType(); 1663 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) { 1664 assert(LTy->isIntegerTy()); 1665 LTy = SplitIntTy; 1666 } 1667 if (!canConvertValue(DL, SliceTy, LTy)) 1668 return false; 1669 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 1670 if (SI->isVolatile()) 1671 return false; 1672 Type *STy = SI->getValueOperand()->getType(); 1673 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) { 1674 assert(STy->isIntegerTy()); 1675 STy = SplitIntTy; 1676 } 1677 if (!canConvertValue(DL, STy, SliceTy)) 1678 return false; 1679 } else { 1680 return false; 1681 } 1682 1683 return true; 1684 } 1685 1686 /// \brief Test whether the given alloca partitioning and range of slices can be 1687 /// promoted to a vector. 1688 /// 1689 /// This is a quick test to check whether we can rewrite a particular alloca 1690 /// partition (and its newly formed alloca) into a vector alloca with only 1691 /// whole-vector loads and stores such that it could be promoted to a vector 1692 /// SSA value. We only can ensure this for a limited set of operations, and we 1693 /// don't want to do the rewrites unless we are confident that the result will 1694 /// be promotable, so we have an early test here. 1695 static VectorType * 1696 isVectorPromotionViable(const DataLayout &DL, 1697 uint64_t SliceBeginOffset, uint64_t SliceEndOffset, 1698 AllocaSlices::const_range Slices, 1699 ArrayRef<AllocaSlices::iterator> SplitUses) { 1700 // Collect the candidate types for vector-based promotion. Also track whether 1701 // we have different element types. 1702 SmallVector<VectorType *, 4> CandidateTys; 1703 Type *CommonEltTy = nullptr; 1704 bool HaveCommonEltTy = true; 1705 auto CheckCandidateType = [&](Type *Ty) { 1706 if (auto *VTy = dyn_cast<VectorType>(Ty)) { 1707 CandidateTys.push_back(VTy); 1708 if (!CommonEltTy) 1709 CommonEltTy = VTy->getElementType(); 1710 else if (CommonEltTy != VTy->getElementType()) 1711 HaveCommonEltTy = false; 1712 } 1713 }; 1714 // Consider any loads or stores that are the exact size of the slice. 1715 for (const auto &S : Slices) 1716 if (S.beginOffset() == SliceBeginOffset && 1717 S.endOffset() == SliceEndOffset) { 1718 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser())) 1719 CheckCandidateType(LI->getType()); 1720 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) 1721 CheckCandidateType(SI->getValueOperand()->getType()); 1722 } 1723 1724 // If we didn't find a vector type, nothing to do here. 1725 if (CandidateTys.empty()) 1726 return nullptr; 1727 1728 // Remove non-integer vector types if we had multiple common element types. 1729 // FIXME: It'd be nice to replace them with integer vector types, but we can't 1730 // do that until all the backends are known to produce good code for all 1731 // integer vector types. 1732 if (!HaveCommonEltTy) { 1733 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(), 1734 [](VectorType *VTy) { 1735 return !VTy->getElementType()->isIntegerTy(); 1736 }), 1737 CandidateTys.end()); 1738 1739 // If there were no integer vector types, give up. 1740 if (CandidateTys.empty()) 1741 return nullptr; 1742 1743 // Rank the remaining candidate vector types. This is easy because we know 1744 // they're all integer vectors. We sort by ascending number of elements. 1745 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) { 1746 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) && 1747 "Cannot have vector types of different sizes!"); 1748 assert(RHSTy->getElementType()->isIntegerTy() && 1749 "All non-integer types eliminated!"); 1750 assert(LHSTy->getElementType()->isIntegerTy() && 1751 "All non-integer types eliminated!"); 1752 return RHSTy->getNumElements() < LHSTy->getNumElements(); 1753 }; 1754 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes); 1755 CandidateTys.erase( 1756 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes), 1757 CandidateTys.end()); 1758 } else { 1759 // The only way to have the same element type in every vector type is to 1760 // have the same vector type. Check that and remove all but one. 1761 #ifndef NDEBUG 1762 for (VectorType *VTy : CandidateTys) { 1763 assert(VTy->getElementType() == CommonEltTy && 1764 "Unaccounted for element type!"); 1765 assert(VTy == CandidateTys[0] && 1766 "Different vector types with the same element type!"); 1767 } 1768 #endif 1769 CandidateTys.resize(1); 1770 } 1771 1772 // Try each vector type, and return the one which works. 1773 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) { 1774 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType()); 1775 1776 // While the definition of LLVM vectors is bitpacked, we don't support sizes 1777 // that aren't byte sized. 1778 if (ElementSize % 8) 1779 return false; 1780 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 && 1781 "vector size not a multiple of element size?"); 1782 ElementSize /= 8; 1783 1784 for (const auto &S : Slices) 1785 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset, 1786 VTy, ElementSize, S)) 1787 return false; 1788 1789 for (const auto &SI : SplitUses) 1790 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset, 1791 VTy, ElementSize, *SI)) 1792 return false; 1793 1794 return true; 1795 }; 1796 for (VectorType *VTy : CandidateTys) 1797 if (CheckVectorTypeForPromotion(VTy)) 1798 return VTy; 1799 1800 return nullptr; 1801 } 1802 1803 /// \brief Test whether a slice of an alloca is valid for integer widening. 1804 /// 1805 /// This implements the necessary checking for the \c isIntegerWideningViable 1806 /// test below on a single slice of the alloca. 1807 static bool isIntegerWideningViableForSlice(const DataLayout &DL, 1808 Type *AllocaTy, 1809 uint64_t AllocBeginOffset, 1810 uint64_t Size, 1811 const Slice &S, 1812 bool &WholeAllocaOp) { 1813 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset; 1814 uint64_t RelEnd = S.endOffset() - AllocBeginOffset; 1815 1816 // We can't reasonably handle cases where the load or store extends past 1817 // the end of the aloca's type and into its padding. 1818 if (RelEnd > Size) 1819 return false; 1820 1821 Use *U = S.getUse(); 1822 1823 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 1824 if (LI->isVolatile()) 1825 return false; 1826 // Note that we don't count vector loads or stores as whole-alloca 1827 // operations which enable integer widening because we would prefer to use 1828 // vector widening instead. 1829 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size) 1830 WholeAllocaOp = true; 1831 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) { 1832 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy)) 1833 return false; 1834 } else if (RelBegin != 0 || RelEnd != Size || 1835 !canConvertValue(DL, AllocaTy, LI->getType())) { 1836 // Non-integer loads need to be convertible from the alloca type so that 1837 // they are promotable. 1838 return false; 1839 } 1840 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 1841 Type *ValueTy = SI->getValueOperand()->getType(); 1842 if (SI->isVolatile()) 1843 return false; 1844 // Note that we don't count vector loads or stores as whole-alloca 1845 // operations which enable integer widening because we would prefer to use 1846 // vector widening instead. 1847 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size) 1848 WholeAllocaOp = true; 1849 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) { 1850 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy)) 1851 return false; 1852 } else if (RelBegin != 0 || RelEnd != Size || 1853 !canConvertValue(DL, ValueTy, AllocaTy)) { 1854 // Non-integer stores need to be convertible to the alloca type so that 1855 // they are promotable. 1856 return false; 1857 } 1858 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) { 1859 if (MI->isVolatile() || !isa<Constant>(MI->getLength())) 1860 return false; 1861 if (!S.isSplittable()) 1862 return false; // Skip any unsplittable intrinsics. 1863 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) { 1864 if (II->getIntrinsicID() != Intrinsic::lifetime_start && 1865 II->getIntrinsicID() != Intrinsic::lifetime_end) 1866 return false; 1867 } else { 1868 return false; 1869 } 1870 1871 return true; 1872 } 1873 1874 /// \brief Test whether the given alloca partition's integer operations can be 1875 /// widened to promotable ones. 1876 /// 1877 /// This is a quick test to check whether we can rewrite the integer loads and 1878 /// stores to a particular alloca into wider loads and stores and be able to 1879 /// promote the resulting alloca. 1880 static bool 1881 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy, 1882 uint64_t AllocBeginOffset, 1883 AllocaSlices::const_range Slices, 1884 ArrayRef<AllocaSlices::iterator> SplitUses) { 1885 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy); 1886 // Don't create integer types larger than the maximum bitwidth. 1887 if (SizeInBits > IntegerType::MAX_INT_BITS) 1888 return false; 1889 1890 // Don't try to handle allocas with bit-padding. 1891 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy)) 1892 return false; 1893 1894 // We need to ensure that an integer type with the appropriate bitwidth can 1895 // be converted to the alloca type, whatever that is. We don't want to force 1896 // the alloca itself to have an integer type if there is a more suitable one. 1897 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits); 1898 if (!canConvertValue(DL, AllocaTy, IntTy) || 1899 !canConvertValue(DL, IntTy, AllocaTy)) 1900 return false; 1901 1902 uint64_t Size = DL.getTypeStoreSize(AllocaTy); 1903 1904 // While examining uses, we ensure that the alloca has a covering load or 1905 // store. We don't want to widen the integer operations only to fail to 1906 // promote due to some other unsplittable entry (which we may make splittable 1907 // later). However, if there are only splittable uses, go ahead and assume 1908 // that we cover the alloca. 1909 bool WholeAllocaOp = 1910 Slices.begin() != Slices.end() ? false : DL.isLegalInteger(SizeInBits); 1911 1912 for (const auto &S : Slices) 1913 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size, 1914 S, WholeAllocaOp)) 1915 return false; 1916 1917 for (const auto &SI : SplitUses) 1918 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size, 1919 *SI, WholeAllocaOp)) 1920 return false; 1921 1922 return WholeAllocaOp; 1923 } 1924 1925 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V, 1926 IntegerType *Ty, uint64_t Offset, 1927 const Twine &Name) { 1928 DEBUG(dbgs() << " start: " << *V << "\n"); 1929 IntegerType *IntTy = cast<IntegerType>(V->getType()); 1930 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) && 1931 "Element extends past full value"); 1932 uint64_t ShAmt = 8*Offset; 1933 if (DL.isBigEndian()) 1934 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset); 1935 if (ShAmt) { 1936 V = IRB.CreateLShr(V, ShAmt, Name + ".shift"); 1937 DEBUG(dbgs() << " shifted: " << *V << "\n"); 1938 } 1939 assert(Ty->getBitWidth() <= IntTy->getBitWidth() && 1940 "Cannot extract to a larger integer!"); 1941 if (Ty != IntTy) { 1942 V = IRB.CreateTrunc(V, Ty, Name + ".trunc"); 1943 DEBUG(dbgs() << " trunced: " << *V << "\n"); 1944 } 1945 return V; 1946 } 1947 1948 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old, 1949 Value *V, uint64_t Offset, const Twine &Name) { 1950 IntegerType *IntTy = cast<IntegerType>(Old->getType()); 1951 IntegerType *Ty = cast<IntegerType>(V->getType()); 1952 assert(Ty->getBitWidth() <= IntTy->getBitWidth() && 1953 "Cannot insert a larger integer!"); 1954 DEBUG(dbgs() << " start: " << *V << "\n"); 1955 if (Ty != IntTy) { 1956 V = IRB.CreateZExt(V, IntTy, Name + ".ext"); 1957 DEBUG(dbgs() << " extended: " << *V << "\n"); 1958 } 1959 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) && 1960 "Element store outside of alloca store"); 1961 uint64_t ShAmt = 8*Offset; 1962 if (DL.isBigEndian()) 1963 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset); 1964 if (ShAmt) { 1965 V = IRB.CreateShl(V, ShAmt, Name + ".shift"); 1966 DEBUG(dbgs() << " shifted: " << *V << "\n"); 1967 } 1968 1969 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) { 1970 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt); 1971 Old = IRB.CreateAnd(Old, Mask, Name + ".mask"); 1972 DEBUG(dbgs() << " masked: " << *Old << "\n"); 1973 V = IRB.CreateOr(Old, V, Name + ".insert"); 1974 DEBUG(dbgs() << " inserted: " << *V << "\n"); 1975 } 1976 return V; 1977 } 1978 1979 static Value *extractVector(IRBuilderTy &IRB, Value *V, 1980 unsigned BeginIndex, unsigned EndIndex, 1981 const Twine &Name) { 1982 VectorType *VecTy = cast<VectorType>(V->getType()); 1983 unsigned NumElements = EndIndex - BeginIndex; 1984 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 1985 1986 if (NumElements == VecTy->getNumElements()) 1987 return V; 1988 1989 if (NumElements == 1) { 1990 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex), 1991 Name + ".extract"); 1992 DEBUG(dbgs() << " extract: " << *V << "\n"); 1993 return V; 1994 } 1995 1996 SmallVector<Constant*, 8> Mask; 1997 Mask.reserve(NumElements); 1998 for (unsigned i = BeginIndex; i != EndIndex; ++i) 1999 Mask.push_back(IRB.getInt32(i)); 2000 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), 2001 ConstantVector::get(Mask), 2002 Name + ".extract"); 2003 DEBUG(dbgs() << " shuffle: " << *V << "\n"); 2004 return V; 2005 } 2006 2007 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V, 2008 unsigned BeginIndex, const Twine &Name) { 2009 VectorType *VecTy = cast<VectorType>(Old->getType()); 2010 assert(VecTy && "Can only insert a vector into a vector"); 2011 2012 VectorType *Ty = dyn_cast<VectorType>(V->getType()); 2013 if (!Ty) { 2014 // Single element to insert. 2015 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex), 2016 Name + ".insert"); 2017 DEBUG(dbgs() << " insert: " << *V << "\n"); 2018 return V; 2019 } 2020 2021 assert(Ty->getNumElements() <= VecTy->getNumElements() && 2022 "Too many elements!"); 2023 if (Ty->getNumElements() == VecTy->getNumElements()) { 2024 assert(V->getType() == VecTy && "Vector type mismatch"); 2025 return V; 2026 } 2027 unsigned EndIndex = BeginIndex + Ty->getNumElements(); 2028 2029 // When inserting a smaller vector into the larger to store, we first 2030 // use a shuffle vector to widen it with undef elements, and then 2031 // a second shuffle vector to select between the loaded vector and the 2032 // incoming vector. 2033 SmallVector<Constant*, 8> Mask; 2034 Mask.reserve(VecTy->getNumElements()); 2035 for (unsigned i = 0; i != VecTy->getNumElements(); ++i) 2036 if (i >= BeginIndex && i < EndIndex) 2037 Mask.push_back(IRB.getInt32(i - BeginIndex)); 2038 else 2039 Mask.push_back(UndefValue::get(IRB.getInt32Ty())); 2040 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), 2041 ConstantVector::get(Mask), 2042 Name + ".expand"); 2043 DEBUG(dbgs() << " shuffle: " << *V << "\n"); 2044 2045 Mask.clear(); 2046 for (unsigned i = 0; i != VecTy->getNumElements(); ++i) 2047 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex)); 2048 2049 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend"); 2050 2051 DEBUG(dbgs() << " blend: " << *V << "\n"); 2052 return V; 2053 } 2054 2055 namespace { 2056 /// \brief Visitor to rewrite instructions using p particular slice of an alloca 2057 /// to use a new alloca. 2058 /// 2059 /// Also implements the rewriting to vector-based accesses when the partition 2060 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic 2061 /// lives here. 2062 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> { 2063 // Befriend the base class so it can delegate to private visit methods. 2064 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>; 2065 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base; 2066 2067 const DataLayout &DL; 2068 AllocaSlices &AS; 2069 SROA &Pass; 2070 AllocaInst &OldAI, &NewAI; 2071 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset; 2072 Type *NewAllocaTy; 2073 2074 // This is a convenience and flag variable that will be null unless the new 2075 // alloca's integer operations should be widened to this integer type due to 2076 // passing isIntegerWideningViable above. If it is non-null, the desired 2077 // integer type will be stored here for easy access during rewriting. 2078 IntegerType *IntTy; 2079 2080 // If we are rewriting an alloca partition which can be written as pure 2081 // vector operations, we stash extra information here. When VecTy is 2082 // non-null, we have some strict guarantees about the rewritten alloca: 2083 // - The new alloca is exactly the size of the vector type here. 2084 // - The accesses all either map to the entire vector or to a single 2085 // element. 2086 // - The set of accessing instructions is only one of those handled above 2087 // in isVectorPromotionViable. Generally these are the same access kinds 2088 // which are promotable via mem2reg. 2089 VectorType *VecTy; 2090 Type *ElementTy; 2091 uint64_t ElementSize; 2092 2093 // The original offset of the slice currently being rewritten relative to 2094 // the original alloca. 2095 uint64_t BeginOffset, EndOffset; 2096 // The new offsets of the slice currently being rewritten relative to the 2097 // original alloca. 2098 uint64_t NewBeginOffset, NewEndOffset; 2099 2100 uint64_t SliceSize; 2101 bool IsSplittable; 2102 bool IsSplit; 2103 Use *OldUse; 2104 Instruction *OldPtr; 2105 2106 // Track post-rewrite users which are PHI nodes and Selects. 2107 SmallPtrSetImpl<PHINode *> &PHIUsers; 2108 SmallPtrSetImpl<SelectInst *> &SelectUsers; 2109 2110 // Utility IR builder, whose name prefix is setup for each visited use, and 2111 // the insertion point is set to point to the user. 2112 IRBuilderTy IRB; 2113 2114 public: 2115 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass, 2116 AllocaInst &OldAI, AllocaInst &NewAI, 2117 uint64_t NewAllocaBeginOffset, 2118 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable, 2119 VectorType *PromotableVecTy, 2120 SmallPtrSetImpl<PHINode *> &PHIUsers, 2121 SmallPtrSetImpl<SelectInst *> &SelectUsers) 2122 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI), 2123 NewAllocaBeginOffset(NewAllocaBeginOffset), 2124 NewAllocaEndOffset(NewAllocaEndOffset), 2125 NewAllocaTy(NewAI.getAllocatedType()), 2126 IntTy(IsIntegerPromotable 2127 ? Type::getIntNTy( 2128 NewAI.getContext(), 2129 DL.getTypeSizeInBits(NewAI.getAllocatedType())) 2130 : nullptr), 2131 VecTy(PromotableVecTy), 2132 ElementTy(VecTy ? VecTy->getElementType() : nullptr), 2133 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0), 2134 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(), 2135 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers), 2136 IRB(NewAI.getContext(), ConstantFolder()) { 2137 if (VecTy) { 2138 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 && 2139 "Only multiple-of-8 sized vector elements are viable"); 2140 ++NumVectorized; 2141 } 2142 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy)); 2143 } 2144 2145 bool visit(AllocaSlices::const_iterator I) { 2146 bool CanSROA = true; 2147 BeginOffset = I->beginOffset(); 2148 EndOffset = I->endOffset(); 2149 IsSplittable = I->isSplittable(); 2150 IsSplit = 2151 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset; 2152 2153 // Compute the intersecting offset range. 2154 assert(BeginOffset < NewAllocaEndOffset); 2155 assert(EndOffset > NewAllocaBeginOffset); 2156 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset); 2157 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset); 2158 2159 SliceSize = NewEndOffset - NewBeginOffset; 2160 2161 OldUse = I->getUse(); 2162 OldPtr = cast<Instruction>(OldUse->get()); 2163 2164 Instruction *OldUserI = cast<Instruction>(OldUse->getUser()); 2165 IRB.SetInsertPoint(OldUserI); 2166 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc()); 2167 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + "."); 2168 2169 CanSROA &= visit(cast<Instruction>(OldUse->getUser())); 2170 if (VecTy || IntTy) 2171 assert(CanSROA); 2172 return CanSROA; 2173 } 2174 2175 private: 2176 // Make sure the other visit overloads are visible. 2177 using Base::visit; 2178 2179 // Every instruction which can end up as a user must have a rewrite rule. 2180 bool visitInstruction(Instruction &I) { 2181 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n"); 2182 llvm_unreachable("No rewrite rule for this instruction!"); 2183 } 2184 2185 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) { 2186 // Note that the offset computation can use BeginOffset or NewBeginOffset 2187 // interchangeably for unsplit slices. 2188 assert(IsSplit || BeginOffset == NewBeginOffset); 2189 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2190 2191 #ifndef NDEBUG 2192 StringRef OldName = OldPtr->getName(); 2193 // Skip through the last '.sroa.' component of the name. 2194 size_t LastSROAPrefix = OldName.rfind(".sroa."); 2195 if (LastSROAPrefix != StringRef::npos) { 2196 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa.")); 2197 // Look for an SROA slice index. 2198 size_t IndexEnd = OldName.find_first_not_of("0123456789"); 2199 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') { 2200 // Strip the index and look for the offset. 2201 OldName = OldName.substr(IndexEnd + 1); 2202 size_t OffsetEnd = OldName.find_first_not_of("0123456789"); 2203 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.') 2204 // Strip the offset. 2205 OldName = OldName.substr(OffsetEnd + 1); 2206 } 2207 } 2208 // Strip any SROA suffixes as well. 2209 OldName = OldName.substr(0, OldName.find(".sroa_")); 2210 #endif 2211 2212 return getAdjustedPtr(IRB, DL, &NewAI, 2213 APInt(DL.getPointerSizeInBits(), Offset), PointerTy, 2214 #ifndef NDEBUG 2215 Twine(OldName) + "." 2216 #else 2217 Twine() 2218 #endif 2219 ); 2220 } 2221 2222 /// \brief Compute suitable alignment to access this slice of the *new* alloca. 2223 /// 2224 /// You can optionally pass a type to this routine and if that type's ABI 2225 /// alignment is itself suitable, this will return zero. 2226 unsigned getSliceAlign(Type *Ty = nullptr) { 2227 unsigned NewAIAlign = NewAI.getAlignment(); 2228 if (!NewAIAlign) 2229 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType()); 2230 unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset); 2231 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align; 2232 } 2233 2234 unsigned getIndex(uint64_t Offset) { 2235 assert(VecTy && "Can only call getIndex when rewriting a vector"); 2236 uint64_t RelOffset = Offset - NewAllocaBeginOffset; 2237 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds"); 2238 uint32_t Index = RelOffset / ElementSize; 2239 assert(Index * ElementSize == RelOffset); 2240 return Index; 2241 } 2242 2243 void deleteIfTriviallyDead(Value *V) { 2244 Instruction *I = cast<Instruction>(V); 2245 if (isInstructionTriviallyDead(I)) 2246 Pass.DeadInsts.insert(I); 2247 } 2248 2249 Value *rewriteVectorizedLoadInst() { 2250 unsigned BeginIndex = getIndex(NewBeginOffset); 2251 unsigned EndIndex = getIndex(NewEndOffset); 2252 assert(EndIndex > BeginIndex && "Empty vector!"); 2253 2254 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2255 "load"); 2256 return extractVector(IRB, V, BeginIndex, EndIndex, "vec"); 2257 } 2258 2259 Value *rewriteIntegerLoad(LoadInst &LI) { 2260 assert(IntTy && "We cannot insert an integer to the alloca"); 2261 assert(!LI.isVolatile()); 2262 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2263 "load"); 2264 V = convertValue(DL, IRB, V, IntTy); 2265 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); 2266 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2267 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) 2268 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset, 2269 "extract"); 2270 return V; 2271 } 2272 2273 bool visitLoadInst(LoadInst &LI) { 2274 DEBUG(dbgs() << " original: " << LI << "\n"); 2275 Value *OldOp = LI.getOperand(0); 2276 assert(OldOp == OldPtr); 2277 2278 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8) 2279 : LI.getType(); 2280 bool IsPtrAdjusted = false; 2281 Value *V; 2282 if (VecTy) { 2283 V = rewriteVectorizedLoadInst(); 2284 } else if (IntTy && LI.getType()->isIntegerTy()) { 2285 V = rewriteIntegerLoad(LI); 2286 } else if (NewBeginOffset == NewAllocaBeginOffset && 2287 canConvertValue(DL, NewAllocaTy, LI.getType())) { 2288 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2289 LI.isVolatile(), LI.getName()); 2290 } else { 2291 Type *LTy = TargetTy->getPointerTo(); 2292 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy), 2293 getSliceAlign(TargetTy), LI.isVolatile(), 2294 LI.getName()); 2295 IsPtrAdjusted = true; 2296 } 2297 V = convertValue(DL, IRB, V, TargetTy); 2298 2299 if (IsSplit) { 2300 assert(!LI.isVolatile()); 2301 assert(LI.getType()->isIntegerTy() && 2302 "Only integer type loads and stores are split"); 2303 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) && 2304 "Split load isn't smaller than original load"); 2305 assert(LI.getType()->getIntegerBitWidth() == 2306 DL.getTypeStoreSizeInBits(LI.getType()) && 2307 "Non-byte-multiple bit width"); 2308 // Move the insertion point just past the load so that we can refer to it. 2309 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI))); 2310 // Create a placeholder value with the same type as LI to use as the 2311 // basis for the new value. This allows us to replace the uses of LI with 2312 // the computed value, and then replace the placeholder with LI, leaving 2313 // LI only used for this computation. 2314 Value *Placeholder 2315 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo())); 2316 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset, 2317 "insert"); 2318 LI.replaceAllUsesWith(V); 2319 Placeholder->replaceAllUsesWith(&LI); 2320 delete Placeholder; 2321 } else { 2322 LI.replaceAllUsesWith(V); 2323 } 2324 2325 Pass.DeadInsts.insert(&LI); 2326 deleteIfTriviallyDead(OldOp); 2327 DEBUG(dbgs() << " to: " << *V << "\n"); 2328 return !LI.isVolatile() && !IsPtrAdjusted; 2329 } 2330 2331 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) { 2332 if (V->getType() != VecTy) { 2333 unsigned BeginIndex = getIndex(NewBeginOffset); 2334 unsigned EndIndex = getIndex(NewEndOffset); 2335 assert(EndIndex > BeginIndex && "Empty vector!"); 2336 unsigned NumElements = EndIndex - BeginIndex; 2337 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2338 Type *SliceTy = 2339 (NumElements == 1) ? ElementTy 2340 : VectorType::get(ElementTy, NumElements); 2341 if (V->getType() != SliceTy) 2342 V = convertValue(DL, IRB, V, SliceTy); 2343 2344 // Mix in the existing elements. 2345 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2346 "load"); 2347 V = insertVector(IRB, Old, V, BeginIndex, "vec"); 2348 } 2349 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment()); 2350 Pass.DeadInsts.insert(&SI); 2351 2352 (void)Store; 2353 DEBUG(dbgs() << " to: " << *Store << "\n"); 2354 return true; 2355 } 2356 2357 bool rewriteIntegerStore(Value *V, StoreInst &SI) { 2358 assert(IntTy && "We cannot extract an integer from the alloca"); 2359 assert(!SI.isVolatile()); 2360 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) { 2361 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2362 "oldload"); 2363 Old = convertValue(DL, IRB, Old, IntTy); 2364 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); 2365 uint64_t Offset = BeginOffset - NewAllocaBeginOffset; 2366 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, 2367 "insert"); 2368 } 2369 V = convertValue(DL, IRB, V, NewAllocaTy); 2370 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment()); 2371 Pass.DeadInsts.insert(&SI); 2372 (void)Store; 2373 DEBUG(dbgs() << " to: " << *Store << "\n"); 2374 return true; 2375 } 2376 2377 bool visitStoreInst(StoreInst &SI) { 2378 DEBUG(dbgs() << " original: " << SI << "\n"); 2379 Value *OldOp = SI.getOperand(1); 2380 assert(OldOp == OldPtr); 2381 2382 Value *V = SI.getValueOperand(); 2383 2384 // Strip all inbounds GEPs and pointer casts to try to dig out any root 2385 // alloca that should be re-examined after promoting this alloca. 2386 if (V->getType()->isPointerTy()) 2387 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets())) 2388 Pass.PostPromotionWorklist.insert(AI); 2389 2390 if (SliceSize < DL.getTypeStoreSize(V->getType())) { 2391 assert(!SI.isVolatile()); 2392 assert(V->getType()->isIntegerTy() && 2393 "Only integer type loads and stores are split"); 2394 assert(V->getType()->getIntegerBitWidth() == 2395 DL.getTypeStoreSizeInBits(V->getType()) && 2396 "Non-byte-multiple bit width"); 2397 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8); 2398 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset, 2399 "extract"); 2400 } 2401 2402 if (VecTy) 2403 return rewriteVectorizedStoreInst(V, SI, OldOp); 2404 if (IntTy && V->getType()->isIntegerTy()) 2405 return rewriteIntegerStore(V, SI); 2406 2407 StoreInst *NewSI; 2408 if (NewBeginOffset == NewAllocaBeginOffset && 2409 NewEndOffset == NewAllocaEndOffset && 2410 canConvertValue(DL, V->getType(), NewAllocaTy)) { 2411 V = convertValue(DL, IRB, V, NewAllocaTy); 2412 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(), 2413 SI.isVolatile()); 2414 } else { 2415 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo()); 2416 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()), 2417 SI.isVolatile()); 2418 } 2419 (void)NewSI; 2420 Pass.DeadInsts.insert(&SI); 2421 deleteIfTriviallyDead(OldOp); 2422 2423 DEBUG(dbgs() << " to: " << *NewSI << "\n"); 2424 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile(); 2425 } 2426 2427 /// \brief Compute an integer value from splatting an i8 across the given 2428 /// number of bytes. 2429 /// 2430 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't 2431 /// call this routine. 2432 /// FIXME: Heed the advice above. 2433 /// 2434 /// \param V The i8 value to splat. 2435 /// \param Size The number of bytes in the output (assuming i8 is one byte) 2436 Value *getIntegerSplat(Value *V, unsigned Size) { 2437 assert(Size > 0 && "Expected a positive number of bytes."); 2438 IntegerType *VTy = cast<IntegerType>(V->getType()); 2439 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte"); 2440 if (Size == 1) 2441 return V; 2442 2443 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8); 2444 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"), 2445 ConstantExpr::getUDiv( 2446 Constant::getAllOnesValue(SplatIntTy), 2447 ConstantExpr::getZExt( 2448 Constant::getAllOnesValue(V->getType()), 2449 SplatIntTy)), 2450 "isplat"); 2451 return V; 2452 } 2453 2454 /// \brief Compute a vector splat for a given element value. 2455 Value *getVectorSplat(Value *V, unsigned NumElements) { 2456 V = IRB.CreateVectorSplat(NumElements, V, "vsplat"); 2457 DEBUG(dbgs() << " splat: " << *V << "\n"); 2458 return V; 2459 } 2460 2461 bool visitMemSetInst(MemSetInst &II) { 2462 DEBUG(dbgs() << " original: " << II << "\n"); 2463 assert(II.getRawDest() == OldPtr); 2464 2465 // If the memset has a variable size, it cannot be split, just adjust the 2466 // pointer to the new alloca. 2467 if (!isa<Constant>(II.getLength())) { 2468 assert(!IsSplit); 2469 assert(NewBeginOffset == BeginOffset); 2470 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType())); 2471 Type *CstTy = II.getAlignmentCst()->getType(); 2472 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign())); 2473 2474 deleteIfTriviallyDead(OldPtr); 2475 return false; 2476 } 2477 2478 // Record this instruction for deletion. 2479 Pass.DeadInsts.insert(&II); 2480 2481 Type *AllocaTy = NewAI.getAllocatedType(); 2482 Type *ScalarTy = AllocaTy->getScalarType(); 2483 2484 // If this doesn't map cleanly onto the alloca type, and that type isn't 2485 // a single value type, just emit a memset. 2486 if (!VecTy && !IntTy && 2487 (BeginOffset > NewAllocaBeginOffset || 2488 EndOffset < NewAllocaEndOffset || 2489 SliceSize != DL.getTypeStoreSize(AllocaTy) || 2490 !AllocaTy->isSingleValueType() || 2491 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) || 2492 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) { 2493 Type *SizeTy = II.getLength()->getType(); 2494 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset); 2495 CallInst *New = IRB.CreateMemSet( 2496 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size, 2497 getSliceAlign(), II.isVolatile()); 2498 (void)New; 2499 DEBUG(dbgs() << " to: " << *New << "\n"); 2500 return false; 2501 } 2502 2503 // If we can represent this as a simple value, we have to build the actual 2504 // value to store, which requires expanding the byte present in memset to 2505 // a sensible representation for the alloca type. This is essentially 2506 // splatting the byte to a sufficiently wide integer, splatting it across 2507 // any desired vector width, and bitcasting to the final type. 2508 Value *V; 2509 2510 if (VecTy) { 2511 // If this is a memset of a vectorized alloca, insert it. 2512 assert(ElementTy == ScalarTy); 2513 2514 unsigned BeginIndex = getIndex(NewBeginOffset); 2515 unsigned EndIndex = getIndex(NewEndOffset); 2516 assert(EndIndex > BeginIndex && "Empty vector!"); 2517 unsigned NumElements = EndIndex - BeginIndex; 2518 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2519 2520 Value *Splat = 2521 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8); 2522 Splat = convertValue(DL, IRB, Splat, ElementTy); 2523 if (NumElements > 1) 2524 Splat = getVectorSplat(Splat, NumElements); 2525 2526 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2527 "oldload"); 2528 V = insertVector(IRB, Old, Splat, BeginIndex, "vec"); 2529 } else if (IntTy) { 2530 // If this is a memset on an alloca where we can widen stores, insert the 2531 // set integer. 2532 assert(!II.isVolatile()); 2533 2534 uint64_t Size = NewEndOffset - NewBeginOffset; 2535 V = getIntegerSplat(II.getValue(), Size); 2536 2537 if (IntTy && (BeginOffset != NewAllocaBeginOffset || 2538 EndOffset != NewAllocaBeginOffset)) { 2539 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2540 "oldload"); 2541 Old = convertValue(DL, IRB, Old, IntTy); 2542 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2543 V = insertInteger(DL, IRB, Old, V, Offset, "insert"); 2544 } else { 2545 assert(V->getType() == IntTy && 2546 "Wrong type for an alloca wide integer!"); 2547 } 2548 V = convertValue(DL, IRB, V, AllocaTy); 2549 } else { 2550 // Established these invariants above. 2551 assert(NewBeginOffset == NewAllocaBeginOffset); 2552 assert(NewEndOffset == NewAllocaEndOffset); 2553 2554 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8); 2555 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy)) 2556 V = getVectorSplat(V, AllocaVecTy->getNumElements()); 2557 2558 V = convertValue(DL, IRB, V, AllocaTy); 2559 } 2560 2561 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(), 2562 II.isVolatile()); 2563 (void)New; 2564 DEBUG(dbgs() << " to: " << *New << "\n"); 2565 return !II.isVolatile(); 2566 } 2567 2568 bool visitMemTransferInst(MemTransferInst &II) { 2569 // Rewriting of memory transfer instructions can be a bit tricky. We break 2570 // them into two categories: split intrinsics and unsplit intrinsics. 2571 2572 DEBUG(dbgs() << " original: " << II << "\n"); 2573 2574 bool IsDest = &II.getRawDestUse() == OldUse; 2575 assert((IsDest && II.getRawDest() == OldPtr) || 2576 (!IsDest && II.getRawSource() == OldPtr)); 2577 2578 unsigned SliceAlign = getSliceAlign(); 2579 2580 // For unsplit intrinsics, we simply modify the source and destination 2581 // pointers in place. This isn't just an optimization, it is a matter of 2582 // correctness. With unsplit intrinsics we may be dealing with transfers 2583 // within a single alloca before SROA ran, or with transfers that have 2584 // a variable length. We may also be dealing with memmove instead of 2585 // memcpy, and so simply updating the pointers is the necessary for us to 2586 // update both source and dest of a single call. 2587 if (!IsSplittable) { 2588 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2589 if (IsDest) 2590 II.setDest(AdjustedPtr); 2591 else 2592 II.setSource(AdjustedPtr); 2593 2594 if (II.getAlignment() > SliceAlign) { 2595 Type *CstTy = II.getAlignmentCst()->getType(); 2596 II.setAlignment( 2597 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign))); 2598 } 2599 2600 DEBUG(dbgs() << " to: " << II << "\n"); 2601 deleteIfTriviallyDead(OldPtr); 2602 return false; 2603 } 2604 // For split transfer intrinsics we have an incredibly useful assurance: 2605 // the source and destination do not reside within the same alloca, and at 2606 // least one of them does not escape. This means that we can replace 2607 // memmove with memcpy, and we don't need to worry about all manner of 2608 // downsides to splitting and transforming the operations. 2609 2610 // If this doesn't map cleanly onto the alloca type, and that type isn't 2611 // a single value type, just emit a memcpy. 2612 bool EmitMemCpy = 2613 !VecTy && !IntTy && 2614 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset || 2615 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) || 2616 !NewAI.getAllocatedType()->isSingleValueType()); 2617 2618 // If we're just going to emit a memcpy, the alloca hasn't changed, and the 2619 // size hasn't been shrunk based on analysis of the viable range, this is 2620 // a no-op. 2621 if (EmitMemCpy && &OldAI == &NewAI) { 2622 // Ensure the start lines up. 2623 assert(NewBeginOffset == BeginOffset); 2624 2625 // Rewrite the size as needed. 2626 if (NewEndOffset != EndOffset) 2627 II.setLength(ConstantInt::get(II.getLength()->getType(), 2628 NewEndOffset - NewBeginOffset)); 2629 return false; 2630 } 2631 // Record this instruction for deletion. 2632 Pass.DeadInsts.insert(&II); 2633 2634 // Strip all inbounds GEPs and pointer casts to try to dig out any root 2635 // alloca that should be re-examined after rewriting this instruction. 2636 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest(); 2637 if (AllocaInst *AI 2638 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) { 2639 assert(AI != &OldAI && AI != &NewAI && 2640 "Splittable transfers cannot reach the same alloca on both ends."); 2641 Pass.Worklist.insert(AI); 2642 } 2643 2644 Type *OtherPtrTy = OtherPtr->getType(); 2645 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace(); 2646 2647 // Compute the relative offset for the other pointer within the transfer. 2648 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS); 2649 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset); 2650 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1, 2651 OtherOffset.zextOrTrunc(64).getZExtValue()); 2652 2653 if (EmitMemCpy) { 2654 // Compute the other pointer, folding as much as possible to produce 2655 // a single, simple GEP in most cases. 2656 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy, 2657 OtherPtr->getName() + "."); 2658 2659 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2660 Type *SizeTy = II.getLength()->getType(); 2661 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset); 2662 2663 CallInst *New = IRB.CreateMemCpy( 2664 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size, 2665 MinAlign(SliceAlign, OtherAlign), II.isVolatile()); 2666 (void)New; 2667 DEBUG(dbgs() << " to: " << *New << "\n"); 2668 return false; 2669 } 2670 2671 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset && 2672 NewEndOffset == NewAllocaEndOffset; 2673 uint64_t Size = NewEndOffset - NewBeginOffset; 2674 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0; 2675 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0; 2676 unsigned NumElements = EndIndex - BeginIndex; 2677 IntegerType *SubIntTy 2678 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr; 2679 2680 // Reset the other pointer type to match the register type we're going to 2681 // use, but using the address space of the original other pointer. 2682 if (VecTy && !IsWholeAlloca) { 2683 if (NumElements == 1) 2684 OtherPtrTy = VecTy->getElementType(); 2685 else 2686 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements); 2687 2688 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS); 2689 } else if (IntTy && !IsWholeAlloca) { 2690 OtherPtrTy = SubIntTy->getPointerTo(OtherAS); 2691 } else { 2692 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS); 2693 } 2694 2695 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy, 2696 OtherPtr->getName() + "."); 2697 unsigned SrcAlign = OtherAlign; 2698 Value *DstPtr = &NewAI; 2699 unsigned DstAlign = SliceAlign; 2700 if (!IsDest) { 2701 std::swap(SrcPtr, DstPtr); 2702 std::swap(SrcAlign, DstAlign); 2703 } 2704 2705 Value *Src; 2706 if (VecTy && !IsWholeAlloca && !IsDest) { 2707 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2708 "load"); 2709 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec"); 2710 } else if (IntTy && !IsWholeAlloca && !IsDest) { 2711 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2712 "load"); 2713 Src = convertValue(DL, IRB, Src, IntTy); 2714 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2715 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract"); 2716 } else { 2717 Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), 2718 "copyload"); 2719 } 2720 2721 if (VecTy && !IsWholeAlloca && IsDest) { 2722 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2723 "oldload"); 2724 Src = insertVector(IRB, Old, Src, BeginIndex, "vec"); 2725 } else if (IntTy && !IsWholeAlloca && IsDest) { 2726 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2727 "oldload"); 2728 Old = convertValue(DL, IRB, Old, IntTy); 2729 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2730 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert"); 2731 Src = convertValue(DL, IRB, Src, NewAllocaTy); 2732 } 2733 2734 StoreInst *Store = cast<StoreInst>( 2735 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile())); 2736 (void)Store; 2737 DEBUG(dbgs() << " to: " << *Store << "\n"); 2738 return !II.isVolatile(); 2739 } 2740 2741 bool visitIntrinsicInst(IntrinsicInst &II) { 2742 assert(II.getIntrinsicID() == Intrinsic::lifetime_start || 2743 II.getIntrinsicID() == Intrinsic::lifetime_end); 2744 DEBUG(dbgs() << " original: " << II << "\n"); 2745 assert(II.getArgOperand(1) == OldPtr); 2746 2747 // Record this instruction for deletion. 2748 Pass.DeadInsts.insert(&II); 2749 2750 ConstantInt *Size 2751 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()), 2752 NewEndOffset - NewBeginOffset); 2753 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2754 Value *New; 2755 if (II.getIntrinsicID() == Intrinsic::lifetime_start) 2756 New = IRB.CreateLifetimeStart(Ptr, Size); 2757 else 2758 New = IRB.CreateLifetimeEnd(Ptr, Size); 2759 2760 (void)New; 2761 DEBUG(dbgs() << " to: " << *New << "\n"); 2762 return true; 2763 } 2764 2765 bool visitPHINode(PHINode &PN) { 2766 DEBUG(dbgs() << " original: " << PN << "\n"); 2767 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable"); 2768 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable"); 2769 2770 // We would like to compute a new pointer in only one place, but have it be 2771 // as local as possible to the PHI. To do that, we re-use the location of 2772 // the old pointer, which necessarily must be in the right position to 2773 // dominate the PHI. 2774 IRBuilderTy PtrBuilder(IRB); 2775 if (isa<PHINode>(OldPtr)) 2776 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt()); 2777 else 2778 PtrBuilder.SetInsertPoint(OldPtr); 2779 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc()); 2780 2781 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType()); 2782 // Replace the operands which were using the old pointer. 2783 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr); 2784 2785 DEBUG(dbgs() << " to: " << PN << "\n"); 2786 deleteIfTriviallyDead(OldPtr); 2787 2788 // PHIs can't be promoted on their own, but often can be speculated. We 2789 // check the speculation outside of the rewriter so that we see the 2790 // fully-rewritten alloca. 2791 PHIUsers.insert(&PN); 2792 return true; 2793 } 2794 2795 bool visitSelectInst(SelectInst &SI) { 2796 DEBUG(dbgs() << " original: " << SI << "\n"); 2797 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) && 2798 "Pointer isn't an operand!"); 2799 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable"); 2800 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable"); 2801 2802 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2803 // Replace the operands which were using the old pointer. 2804 if (SI.getOperand(1) == OldPtr) 2805 SI.setOperand(1, NewPtr); 2806 if (SI.getOperand(2) == OldPtr) 2807 SI.setOperand(2, NewPtr); 2808 2809 DEBUG(dbgs() << " to: " << SI << "\n"); 2810 deleteIfTriviallyDead(OldPtr); 2811 2812 // Selects can't be promoted on their own, but often can be speculated. We 2813 // check the speculation outside of the rewriter so that we see the 2814 // fully-rewritten alloca. 2815 SelectUsers.insert(&SI); 2816 return true; 2817 } 2818 2819 }; 2820 } 2821 2822 namespace { 2823 /// \brief Visitor to rewrite aggregate loads and stores as scalar. 2824 /// 2825 /// This pass aggressively rewrites all aggregate loads and stores on 2826 /// a particular pointer (or any pointer derived from it which we can identify) 2827 /// with scalar loads and stores. 2828 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> { 2829 // Befriend the base class so it can delegate to private visit methods. 2830 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>; 2831 2832 const DataLayout &DL; 2833 2834 /// Queue of pointer uses to analyze and potentially rewrite. 2835 SmallVector<Use *, 8> Queue; 2836 2837 /// Set to prevent us from cycling with phi nodes and loops. 2838 SmallPtrSet<User *, 8> Visited; 2839 2840 /// The current pointer use being rewritten. This is used to dig up the used 2841 /// value (as opposed to the user). 2842 Use *U; 2843 2844 public: 2845 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {} 2846 2847 /// Rewrite loads and stores through a pointer and all pointers derived from 2848 /// it. 2849 bool rewrite(Instruction &I) { 2850 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n"); 2851 enqueueUsers(I); 2852 bool Changed = false; 2853 while (!Queue.empty()) { 2854 U = Queue.pop_back_val(); 2855 Changed |= visit(cast<Instruction>(U->getUser())); 2856 } 2857 return Changed; 2858 } 2859 2860 private: 2861 /// Enqueue all the users of the given instruction for further processing. 2862 /// This uses a set to de-duplicate users. 2863 void enqueueUsers(Instruction &I) { 2864 for (Use &U : I.uses()) 2865 if (Visited.insert(U.getUser()).second) 2866 Queue.push_back(&U); 2867 } 2868 2869 // Conservative default is to not rewrite anything. 2870 bool visitInstruction(Instruction &I) { return false; } 2871 2872 /// \brief Generic recursive split emission class. 2873 template <typename Derived> 2874 class OpSplitter { 2875 protected: 2876 /// The builder used to form new instructions. 2877 IRBuilderTy IRB; 2878 /// The indices which to be used with insert- or extractvalue to select the 2879 /// appropriate value within the aggregate. 2880 SmallVector<unsigned, 4> Indices; 2881 /// The indices to a GEP instruction which will move Ptr to the correct slot 2882 /// within the aggregate. 2883 SmallVector<Value *, 4> GEPIndices; 2884 /// The base pointer of the original op, used as a base for GEPing the 2885 /// split operations. 2886 Value *Ptr; 2887 2888 /// Initialize the splitter with an insertion point, Ptr and start with a 2889 /// single zero GEP index. 2890 OpSplitter(Instruction *InsertionPoint, Value *Ptr) 2891 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {} 2892 2893 public: 2894 /// \brief Generic recursive split emission routine. 2895 /// 2896 /// This method recursively splits an aggregate op (load or store) into 2897 /// scalar or vector ops. It splits recursively until it hits a single value 2898 /// and emits that single value operation via the template argument. 2899 /// 2900 /// The logic of this routine relies on GEPs and insertvalue and 2901 /// extractvalue all operating with the same fundamental index list, merely 2902 /// formatted differently (GEPs need actual values). 2903 /// 2904 /// \param Ty The type being split recursively into smaller ops. 2905 /// \param Agg The aggregate value being built up or stored, depending on 2906 /// whether this is splitting a load or a store respectively. 2907 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) { 2908 if (Ty->isSingleValueType()) 2909 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name); 2910 2911 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 2912 unsigned OldSize = Indices.size(); 2913 (void)OldSize; 2914 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size; 2915 ++Idx) { 2916 assert(Indices.size() == OldSize && "Did not return to the old size"); 2917 Indices.push_back(Idx); 2918 GEPIndices.push_back(IRB.getInt32(Idx)); 2919 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx)); 2920 GEPIndices.pop_back(); 2921 Indices.pop_back(); 2922 } 2923 return; 2924 } 2925 2926 if (StructType *STy = dyn_cast<StructType>(Ty)) { 2927 unsigned OldSize = Indices.size(); 2928 (void)OldSize; 2929 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size; 2930 ++Idx) { 2931 assert(Indices.size() == OldSize && "Did not return to the old size"); 2932 Indices.push_back(Idx); 2933 GEPIndices.push_back(IRB.getInt32(Idx)); 2934 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx)); 2935 GEPIndices.pop_back(); 2936 Indices.pop_back(); 2937 } 2938 return; 2939 } 2940 2941 llvm_unreachable("Only arrays and structs are aggregate loadable types"); 2942 } 2943 }; 2944 2945 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> { 2946 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr) 2947 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {} 2948 2949 /// Emit a leaf load of a single value. This is called at the leaves of the 2950 /// recursive emission to actually load values. 2951 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) { 2952 assert(Ty->isSingleValueType()); 2953 // Load the single value and insert it using the indices. 2954 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"); 2955 Value *Load = IRB.CreateLoad(GEP, Name + ".load"); 2956 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert"); 2957 DEBUG(dbgs() << " to: " << *Load << "\n"); 2958 } 2959 }; 2960 2961 bool visitLoadInst(LoadInst &LI) { 2962 assert(LI.getPointerOperand() == *U); 2963 if (!LI.isSimple() || LI.getType()->isSingleValueType()) 2964 return false; 2965 2966 // We have an aggregate being loaded, split it apart. 2967 DEBUG(dbgs() << " original: " << LI << "\n"); 2968 LoadOpSplitter Splitter(&LI, *U); 2969 Value *V = UndefValue::get(LI.getType()); 2970 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca"); 2971 LI.replaceAllUsesWith(V); 2972 LI.eraseFromParent(); 2973 return true; 2974 } 2975 2976 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> { 2977 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr) 2978 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {} 2979 2980 /// Emit a leaf store of a single value. This is called at the leaves of the 2981 /// recursive emission to actually produce stores. 2982 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) { 2983 assert(Ty->isSingleValueType()); 2984 // Extract the single value and store it using the indices. 2985 Value *Store = IRB.CreateStore( 2986 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"), 2987 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep")); 2988 (void)Store; 2989 DEBUG(dbgs() << " to: " << *Store << "\n"); 2990 } 2991 }; 2992 2993 bool visitStoreInst(StoreInst &SI) { 2994 if (!SI.isSimple() || SI.getPointerOperand() != *U) 2995 return false; 2996 Value *V = SI.getValueOperand(); 2997 if (V->getType()->isSingleValueType()) 2998 return false; 2999 3000 // We have an aggregate being stored, split it apart. 3001 DEBUG(dbgs() << " original: " << SI << "\n"); 3002 StoreOpSplitter Splitter(&SI, *U); 3003 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca"); 3004 SI.eraseFromParent(); 3005 return true; 3006 } 3007 3008 bool visitBitCastInst(BitCastInst &BC) { 3009 enqueueUsers(BC); 3010 return false; 3011 } 3012 3013 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) { 3014 enqueueUsers(GEPI); 3015 return false; 3016 } 3017 3018 bool visitPHINode(PHINode &PN) { 3019 enqueueUsers(PN); 3020 return false; 3021 } 3022 3023 bool visitSelectInst(SelectInst &SI) { 3024 enqueueUsers(SI); 3025 return false; 3026 } 3027 }; 3028 } 3029 3030 /// \brief Strip aggregate type wrapping. 3031 /// 3032 /// This removes no-op aggregate types wrapping an underlying type. It will 3033 /// strip as many layers of types as it can without changing either the type 3034 /// size or the allocated size. 3035 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) { 3036 if (Ty->isSingleValueType()) 3037 return Ty; 3038 3039 uint64_t AllocSize = DL.getTypeAllocSize(Ty); 3040 uint64_t TypeSize = DL.getTypeSizeInBits(Ty); 3041 3042 Type *InnerTy; 3043 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) { 3044 InnerTy = ArrTy->getElementType(); 3045 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 3046 const StructLayout *SL = DL.getStructLayout(STy); 3047 unsigned Index = SL->getElementContainingOffset(0); 3048 InnerTy = STy->getElementType(Index); 3049 } else { 3050 return Ty; 3051 } 3052 3053 if (AllocSize > DL.getTypeAllocSize(InnerTy) || 3054 TypeSize > DL.getTypeSizeInBits(InnerTy)) 3055 return Ty; 3056 3057 return stripAggregateTypeWrapping(DL, InnerTy); 3058 } 3059 3060 /// \brief Try to find a partition of the aggregate type passed in for a given 3061 /// offset and size. 3062 /// 3063 /// This recurses through the aggregate type and tries to compute a subtype 3064 /// based on the offset and size. When the offset and size span a sub-section 3065 /// of an array, it will even compute a new array type for that sub-section, 3066 /// and the same for structs. 3067 /// 3068 /// Note that this routine is very strict and tries to find a partition of the 3069 /// type which produces the *exact* right offset and size. It is not forgiving 3070 /// when the size or offset cause either end of type-based partition to be off. 3071 /// Also, this is a best-effort routine. It is reasonable to give up and not 3072 /// return a type if necessary. 3073 static Type *getTypePartition(const DataLayout &DL, Type *Ty, 3074 uint64_t Offset, uint64_t Size) { 3075 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size) 3076 return stripAggregateTypeWrapping(DL, Ty); 3077 if (Offset > DL.getTypeAllocSize(Ty) || 3078 (DL.getTypeAllocSize(Ty) - Offset) < Size) 3079 return nullptr; 3080 3081 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) { 3082 // We can't partition pointers... 3083 if (SeqTy->isPointerTy()) 3084 return nullptr; 3085 3086 Type *ElementTy = SeqTy->getElementType(); 3087 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy); 3088 uint64_t NumSkippedElements = Offset / ElementSize; 3089 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) { 3090 if (NumSkippedElements >= ArrTy->getNumElements()) 3091 return nullptr; 3092 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) { 3093 if (NumSkippedElements >= VecTy->getNumElements()) 3094 return nullptr; 3095 } 3096 Offset -= NumSkippedElements * ElementSize; 3097 3098 // First check if we need to recurse. 3099 if (Offset > 0 || Size < ElementSize) { 3100 // Bail if the partition ends in a different array element. 3101 if ((Offset + Size) > ElementSize) 3102 return nullptr; 3103 // Recurse through the element type trying to peel off offset bytes. 3104 return getTypePartition(DL, ElementTy, Offset, Size); 3105 } 3106 assert(Offset == 0); 3107 3108 if (Size == ElementSize) 3109 return stripAggregateTypeWrapping(DL, ElementTy); 3110 assert(Size > ElementSize); 3111 uint64_t NumElements = Size / ElementSize; 3112 if (NumElements * ElementSize != Size) 3113 return nullptr; 3114 return ArrayType::get(ElementTy, NumElements); 3115 } 3116 3117 StructType *STy = dyn_cast<StructType>(Ty); 3118 if (!STy) 3119 return nullptr; 3120 3121 const StructLayout *SL = DL.getStructLayout(STy); 3122 if (Offset >= SL->getSizeInBytes()) 3123 return nullptr; 3124 uint64_t EndOffset = Offset + Size; 3125 if (EndOffset > SL->getSizeInBytes()) 3126 return nullptr; 3127 3128 unsigned Index = SL->getElementContainingOffset(Offset); 3129 Offset -= SL->getElementOffset(Index); 3130 3131 Type *ElementTy = STy->getElementType(Index); 3132 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy); 3133 if (Offset >= ElementSize) 3134 return nullptr; // The offset points into alignment padding. 3135 3136 // See if any partition must be contained by the element. 3137 if (Offset > 0 || Size < ElementSize) { 3138 if ((Offset + Size) > ElementSize) 3139 return nullptr; 3140 return getTypePartition(DL, ElementTy, Offset, Size); 3141 } 3142 assert(Offset == 0); 3143 3144 if (Size == ElementSize) 3145 return stripAggregateTypeWrapping(DL, ElementTy); 3146 3147 StructType::element_iterator EI = STy->element_begin() + Index, 3148 EE = STy->element_end(); 3149 if (EndOffset < SL->getSizeInBytes()) { 3150 unsigned EndIndex = SL->getElementContainingOffset(EndOffset); 3151 if (Index == EndIndex) 3152 return nullptr; // Within a single element and its padding. 3153 3154 // Don't try to form "natural" types if the elements don't line up with the 3155 // expected size. 3156 // FIXME: We could potentially recurse down through the last element in the 3157 // sub-struct to find a natural end point. 3158 if (SL->getElementOffset(EndIndex) != EndOffset) 3159 return nullptr; 3160 3161 assert(Index < EndIndex); 3162 EE = STy->element_begin() + EndIndex; 3163 } 3164 3165 // Try to build up a sub-structure. 3166 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE), 3167 STy->isPacked()); 3168 const StructLayout *SubSL = DL.getStructLayout(SubTy); 3169 if (Size != SubSL->getSizeInBytes()) 3170 return nullptr; // The sub-struct doesn't have quite the size needed. 3171 3172 return SubTy; 3173 } 3174 3175 /// \brief Rewrite an alloca partition's users. 3176 /// 3177 /// This routine drives both of the rewriting goals of the SROA pass. It tries 3178 /// to rewrite uses of an alloca partition to be conducive for SSA value 3179 /// promotion. If the partition needs a new, more refined alloca, this will 3180 /// build that new alloca, preserving as much type information as possible, and 3181 /// rewrite the uses of the old alloca to point at the new one and have the 3182 /// appropriate new offsets. It also evaluates how successful the rewrite was 3183 /// at enabling promotion and if it was successful queues the alloca to be 3184 /// promoted. 3185 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS, 3186 AllocaSlices::iterator B, AllocaSlices::iterator E, 3187 int64_t BeginOffset, int64_t EndOffset, 3188 ArrayRef<AllocaSlices::iterator> SplitUses) { 3189 assert(BeginOffset < EndOffset); 3190 uint64_t SliceSize = EndOffset - BeginOffset; 3191 3192 // Try to compute a friendly type for this partition of the alloca. This 3193 // won't always succeed, in which case we fall back to a legal integer type 3194 // or an i8 array of an appropriate size. 3195 Type *SliceTy = nullptr; 3196 if (Type *CommonUseTy = findCommonType(B, E, EndOffset)) 3197 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize) 3198 SliceTy = CommonUseTy; 3199 if (!SliceTy) 3200 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(), 3201 BeginOffset, SliceSize)) 3202 SliceTy = TypePartitionTy; 3203 if ((!SliceTy || (SliceTy->isArrayTy() && 3204 SliceTy->getArrayElementType()->isIntegerTy())) && 3205 DL->isLegalInteger(SliceSize * 8)) 3206 SliceTy = Type::getIntNTy(*C, SliceSize * 8); 3207 if (!SliceTy) 3208 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize); 3209 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize); 3210 3211 bool IsIntegerPromotable = isIntegerWideningViable( 3212 *DL, SliceTy, BeginOffset, AllocaSlices::const_range(B, E), SplitUses); 3213 3214 VectorType *VecTy = 3215 IsIntegerPromotable 3216 ? nullptr 3217 : isVectorPromotionViable(*DL, BeginOffset, EndOffset, 3218 AllocaSlices::const_range(B, E), SplitUses); 3219 if (VecTy) 3220 SliceTy = VecTy; 3221 3222 // Check for the case where we're going to rewrite to a new alloca of the 3223 // exact same type as the original, and with the same access offsets. In that 3224 // case, re-use the existing alloca, but still run through the rewriter to 3225 // perform phi and select speculation. 3226 AllocaInst *NewAI; 3227 if (SliceTy == AI.getAllocatedType()) { 3228 assert(BeginOffset == 0 && 3229 "Non-zero begin offset but same alloca type"); 3230 NewAI = &AI; 3231 // FIXME: We should be able to bail at this point with "nothing changed". 3232 // FIXME: We might want to defer PHI speculation until after here. 3233 } else { 3234 unsigned Alignment = AI.getAlignment(); 3235 if (!Alignment) { 3236 // The minimum alignment which users can rely on when the explicit 3237 // alignment is omitted or zero is that required by the ABI for this 3238 // type. 3239 Alignment = DL->getABITypeAlignment(AI.getAllocatedType()); 3240 } 3241 Alignment = MinAlign(Alignment, BeginOffset); 3242 // If we will get at least this much alignment from the type alone, leave 3243 // the alloca's alignment unconstrained. 3244 if (Alignment <= DL->getABITypeAlignment(SliceTy)) 3245 Alignment = 0; 3246 NewAI = 3247 new AllocaInst(SliceTy, nullptr, Alignment, 3248 AI.getName() + ".sroa." + Twine(B - AS.begin()), &AI); 3249 ++NumNewAllocas; 3250 } 3251 3252 DEBUG(dbgs() << "Rewriting alloca partition " 3253 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI 3254 << "\n"); 3255 3256 // Track the high watermark on the worklist as it is only relevant for 3257 // promoted allocas. We will reset it to this point if the alloca is not in 3258 // fact scheduled for promotion. 3259 unsigned PPWOldSize = PostPromotionWorklist.size(); 3260 unsigned NumUses = 0; 3261 SmallPtrSet<PHINode *, 8> PHIUsers; 3262 SmallPtrSet<SelectInst *, 8> SelectUsers; 3263 3264 AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, BeginOffset, 3265 EndOffset, IsIntegerPromotable, VecTy, PHIUsers, 3266 SelectUsers); 3267 bool Promotable = true; 3268 for (auto & SplitUse : SplitUses) { 3269 DEBUG(dbgs() << " rewriting split "); 3270 DEBUG(AS.printSlice(dbgs(), SplitUse, "")); 3271 Promotable &= Rewriter.visit(SplitUse); 3272 ++NumUses; 3273 } 3274 for (AllocaSlices::iterator I = B; I != E; ++I) { 3275 DEBUG(dbgs() << " rewriting "); 3276 DEBUG(AS.printSlice(dbgs(), I, "")); 3277 Promotable &= Rewriter.visit(I); 3278 ++NumUses; 3279 } 3280 3281 NumAllocaPartitionUses += NumUses; 3282 MaxUsesPerAllocaPartition = 3283 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition); 3284 3285 // Now that we've processed all the slices in the new partition, check if any 3286 // PHIs or Selects would block promotion. 3287 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(), 3288 E = PHIUsers.end(); 3289 I != E; ++I) 3290 if (!isSafePHIToSpeculate(**I, DL)) { 3291 Promotable = false; 3292 PHIUsers.clear(); 3293 SelectUsers.clear(); 3294 break; 3295 } 3296 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(), 3297 E = SelectUsers.end(); 3298 I != E; ++I) 3299 if (!isSafeSelectToSpeculate(**I, DL)) { 3300 Promotable = false; 3301 PHIUsers.clear(); 3302 SelectUsers.clear(); 3303 break; 3304 } 3305 3306 if (Promotable) { 3307 if (PHIUsers.empty() && SelectUsers.empty()) { 3308 // Promote the alloca. 3309 PromotableAllocas.push_back(NewAI); 3310 } else { 3311 // If we have either PHIs or Selects to speculate, add them to those 3312 // worklists and re-queue the new alloca so that we promote in on the 3313 // next iteration. 3314 for (PHINode *PHIUser : PHIUsers) 3315 SpeculatablePHIs.insert(PHIUser); 3316 for (SelectInst *SelectUser : SelectUsers) 3317 SpeculatableSelects.insert(SelectUser); 3318 Worklist.insert(NewAI); 3319 } 3320 } else { 3321 // If we can't promote the alloca, iterate on it to check for new 3322 // refinements exposed by splitting the current alloca. Don't iterate on an 3323 // alloca which didn't actually change and didn't get promoted. 3324 if (NewAI != &AI) 3325 Worklist.insert(NewAI); 3326 3327 // Drop any post-promotion work items if promotion didn't happen. 3328 while (PostPromotionWorklist.size() > PPWOldSize) 3329 PostPromotionWorklist.pop_back(); 3330 } 3331 3332 return true; 3333 } 3334 3335 static void 3336 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses, 3337 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) { 3338 if (Offset >= MaxSplitUseEndOffset) { 3339 SplitUses.clear(); 3340 MaxSplitUseEndOffset = 0; 3341 return; 3342 } 3343 3344 size_t SplitUsesOldSize = SplitUses.size(); 3345 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(), 3346 [Offset](const AllocaSlices::iterator &I) { 3347 return I->endOffset() <= Offset; 3348 }), 3349 SplitUses.end()); 3350 if (SplitUsesOldSize == SplitUses.size()) 3351 return; 3352 3353 // Recompute the max. While this is linear, so is remove_if. 3354 MaxSplitUseEndOffset = 0; 3355 for (AllocaSlices::iterator SplitUse : SplitUses) 3356 MaxSplitUseEndOffset = 3357 std::max(SplitUse->endOffset(), MaxSplitUseEndOffset); 3358 } 3359 3360 /// \brief Walks the slices of an alloca and form partitions based on them, 3361 /// rewriting each of their uses. 3362 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) { 3363 if (AS.begin() == AS.end()) 3364 return false; 3365 3366 unsigned NumPartitions = 0; 3367 bool Changed = false; 3368 SmallVector<AllocaSlices::iterator, 4> SplitUses; 3369 uint64_t MaxSplitUseEndOffset = 0; 3370 3371 uint64_t BeginOffset = AS.begin()->beginOffset(); 3372 3373 for (AllocaSlices::iterator SI = AS.begin(), SJ = std::next(SI), 3374 SE = AS.end(); 3375 SI != SE; SI = SJ) { 3376 uint64_t MaxEndOffset = SI->endOffset(); 3377 3378 if (!SI->isSplittable()) { 3379 // When we're forming an unsplittable region, it must always start at the 3380 // first slice and will extend through its end. 3381 assert(BeginOffset == SI->beginOffset()); 3382 3383 // Form a partition including all of the overlapping slices with this 3384 // unsplittable slice. 3385 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) { 3386 if (!SJ->isSplittable()) 3387 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset()); 3388 ++SJ; 3389 } 3390 } else { 3391 assert(SI->isSplittable()); // Established above. 3392 3393 // Collect all of the overlapping splittable slices. 3394 while (SJ != SE && SJ->beginOffset() < MaxEndOffset && 3395 SJ->isSplittable()) { 3396 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset()); 3397 ++SJ; 3398 } 3399 3400 // Back up MaxEndOffset and SJ if we ended the span early when 3401 // encountering an unsplittable slice. 3402 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) { 3403 assert(!SJ->isSplittable()); 3404 MaxEndOffset = SJ->beginOffset(); 3405 } 3406 } 3407 3408 // Check if we have managed to move the end offset forward yet. If so, 3409 // we'll have to rewrite uses and erase old split uses. 3410 if (BeginOffset < MaxEndOffset) { 3411 // Rewrite a sequence of overlapping slices. 3412 Changed |= rewritePartition(AI, AS, SI, SJ, BeginOffset, MaxEndOffset, 3413 SplitUses); 3414 ++NumPartitions; 3415 3416 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset); 3417 } 3418 3419 // Accumulate all the splittable slices from the [SI,SJ) region which 3420 // overlap going forward. 3421 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK) 3422 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) { 3423 SplitUses.push_back(SK); 3424 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset); 3425 } 3426 3427 // If we're already at the end and we have no split uses, we're done. 3428 if (SJ == SE && SplitUses.empty()) 3429 break; 3430 3431 // If we have no split uses or no gap in offsets, we're ready to move to 3432 // the next slice. 3433 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) { 3434 BeginOffset = SJ->beginOffset(); 3435 continue; 3436 } 3437 3438 // Even if we have split slices, if the next slice is splittable and the 3439 // split slices reach it, we can simply set up the beginning offset of the 3440 // next iteration to bridge between them. 3441 if (SJ != SE && SJ->isSplittable() && 3442 MaxSplitUseEndOffset > SJ->beginOffset()) { 3443 BeginOffset = MaxEndOffset; 3444 continue; 3445 } 3446 3447 // Otherwise, we have a tail of split slices. Rewrite them with an empty 3448 // range of slices. 3449 uint64_t PostSplitEndOffset = 3450 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset(); 3451 3452 Changed |= rewritePartition(AI, AS, SJ, SJ, MaxEndOffset, 3453 PostSplitEndOffset, SplitUses); 3454 ++NumPartitions; 3455 3456 if (SJ == SE) 3457 break; // Skip the rest, we don't need to do any cleanup. 3458 3459 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, 3460 PostSplitEndOffset); 3461 3462 // Now just reset the begin offset for the next iteration. 3463 BeginOffset = SJ->beginOffset(); 3464 } 3465 3466 NumAllocaPartitions += NumPartitions; 3467 MaxPartitionsPerAlloca = 3468 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca); 3469 3470 return Changed; 3471 } 3472 3473 /// \brief Clobber a use with undef, deleting the used value if it becomes dead. 3474 void SROA::clobberUse(Use &U) { 3475 Value *OldV = U; 3476 // Replace the use with an undef value. 3477 U = UndefValue::get(OldV->getType()); 3478 3479 // Check for this making an instruction dead. We have to garbage collect 3480 // all the dead instructions to ensure the uses of any alloca end up being 3481 // minimal. 3482 if (Instruction *OldI = dyn_cast<Instruction>(OldV)) 3483 if (isInstructionTriviallyDead(OldI)) { 3484 DeadInsts.insert(OldI); 3485 } 3486 } 3487 3488 /// \brief Analyze an alloca for SROA. 3489 /// 3490 /// This analyzes the alloca to ensure we can reason about it, builds 3491 /// the slices of the alloca, and then hands it off to be split and 3492 /// rewritten as needed. 3493 bool SROA::runOnAlloca(AllocaInst &AI) { 3494 DEBUG(dbgs() << "SROA alloca: " << AI << "\n"); 3495 ++NumAllocasAnalyzed; 3496 3497 // Special case dead allocas, as they're trivial. 3498 if (AI.use_empty()) { 3499 AI.eraseFromParent(); 3500 return true; 3501 } 3502 3503 // Skip alloca forms that this analysis can't handle. 3504 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() || 3505 DL->getTypeAllocSize(AI.getAllocatedType()) == 0) 3506 return false; 3507 3508 bool Changed = false; 3509 3510 // First, split any FCA loads and stores touching this alloca to promote 3511 // better splitting and promotion opportunities. 3512 AggLoadStoreRewriter AggRewriter(*DL); 3513 Changed |= AggRewriter.rewrite(AI); 3514 3515 // Build the slices using a recursive instruction-visiting builder. 3516 AllocaSlices AS(*DL, AI); 3517 DEBUG(AS.print(dbgs())); 3518 if (AS.isEscaped()) 3519 return Changed; 3520 3521 // Delete all the dead users of this alloca before splitting and rewriting it. 3522 for (Instruction *DeadUser : AS.getDeadUsers()) { 3523 // Free up everything used by this instruction. 3524 for (Use &DeadOp : DeadUser->operands()) 3525 clobberUse(DeadOp); 3526 3527 // Now replace the uses of this instruction. 3528 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType())); 3529 3530 // And mark it for deletion. 3531 DeadInsts.insert(DeadUser); 3532 Changed = true; 3533 } 3534 for (Use *DeadOp : AS.getDeadOperands()) { 3535 clobberUse(*DeadOp); 3536 Changed = true; 3537 } 3538 3539 // No slices to split. Leave the dead alloca for a later pass to clean up. 3540 if (AS.begin() == AS.end()) 3541 return Changed; 3542 3543 Changed |= splitAlloca(AI, AS); 3544 3545 DEBUG(dbgs() << " Speculating PHIs\n"); 3546 while (!SpeculatablePHIs.empty()) 3547 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val()); 3548 3549 DEBUG(dbgs() << " Speculating Selects\n"); 3550 while (!SpeculatableSelects.empty()) 3551 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val()); 3552 3553 return Changed; 3554 } 3555 3556 /// \brief Delete the dead instructions accumulated in this run. 3557 /// 3558 /// Recursively deletes the dead instructions we've accumulated. This is done 3559 /// at the very end to maximize locality of the recursive delete and to 3560 /// minimize the problems of invalidated instruction pointers as such pointers 3561 /// are used heavily in the intermediate stages of the algorithm. 3562 /// 3563 /// We also record the alloca instructions deleted here so that they aren't 3564 /// subsequently handed to mem2reg to promote. 3565 void SROA::deleteDeadInstructions(SmallPtrSetImpl<AllocaInst*> &DeletedAllocas) { 3566 while (!DeadInsts.empty()) { 3567 Instruction *I = DeadInsts.pop_back_val(); 3568 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n"); 3569 3570 I->replaceAllUsesWith(UndefValue::get(I->getType())); 3571 3572 for (Use &Operand : I->operands()) 3573 if (Instruction *U = dyn_cast<Instruction>(Operand)) { 3574 // Zero out the operand and see if it becomes trivially dead. 3575 Operand = nullptr; 3576 if (isInstructionTriviallyDead(U)) 3577 DeadInsts.insert(U); 3578 } 3579 3580 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 3581 DeletedAllocas.insert(AI); 3582 3583 ++NumDeleted; 3584 I->eraseFromParent(); 3585 } 3586 } 3587 3588 static void enqueueUsersInWorklist(Instruction &I, 3589 SmallVectorImpl<Instruction *> &Worklist, 3590 SmallPtrSetImpl<Instruction *> &Visited) { 3591 for (User *U : I.users()) 3592 if (Visited.insert(cast<Instruction>(U)).second) 3593 Worklist.push_back(cast<Instruction>(U)); 3594 } 3595 3596 /// \brief Promote the allocas, using the best available technique. 3597 /// 3598 /// This attempts to promote whatever allocas have been identified as viable in 3599 /// the PromotableAllocas list. If that list is empty, there is nothing to do. 3600 /// If there is a domtree available, we attempt to promote using the full power 3601 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is 3602 /// based on the SSAUpdater utilities. This function returns whether any 3603 /// promotion occurred. 3604 bool SROA::promoteAllocas(Function &F) { 3605 if (PromotableAllocas.empty()) 3606 return false; 3607 3608 NumPromoted += PromotableAllocas.size(); 3609 3610 if (DT && !ForceSSAUpdater) { 3611 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n"); 3612 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT); 3613 PromotableAllocas.clear(); 3614 return true; 3615 } 3616 3617 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n"); 3618 SSAUpdater SSA; 3619 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false); 3620 SmallVector<Instruction *, 64> Insts; 3621 3622 // We need a worklist to walk the uses of each alloca. 3623 SmallVector<Instruction *, 8> Worklist; 3624 SmallPtrSet<Instruction *, 8> Visited; 3625 SmallVector<Instruction *, 32> DeadInsts; 3626 3627 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) { 3628 AllocaInst *AI = PromotableAllocas[Idx]; 3629 Insts.clear(); 3630 Worklist.clear(); 3631 Visited.clear(); 3632 3633 enqueueUsersInWorklist(*AI, Worklist, Visited); 3634 3635 while (!Worklist.empty()) { 3636 Instruction *I = Worklist.pop_back_val(); 3637 3638 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about 3639 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs 3640 // leading to them) here. Eventually it should use them to optimize the 3641 // scalar values produced. 3642 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 3643 assert(II->getIntrinsicID() == Intrinsic::lifetime_start || 3644 II->getIntrinsicID() == Intrinsic::lifetime_end); 3645 II->eraseFromParent(); 3646 continue; 3647 } 3648 3649 // Push the loads and stores we find onto the list. SROA will already 3650 // have validated that all loads and stores are viable candidates for 3651 // promotion. 3652 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 3653 assert(LI->getType() == AI->getAllocatedType()); 3654 Insts.push_back(LI); 3655 continue; 3656 } 3657 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 3658 assert(SI->getValueOperand()->getType() == AI->getAllocatedType()); 3659 Insts.push_back(SI); 3660 continue; 3661 } 3662 3663 // For everything else, we know that only no-op bitcasts and GEPs will 3664 // make it this far, just recurse through them and recall them for later 3665 // removal. 3666 DeadInsts.push_back(I); 3667 enqueueUsersInWorklist(*I, Worklist, Visited); 3668 } 3669 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts); 3670 while (!DeadInsts.empty()) 3671 DeadInsts.pop_back_val()->eraseFromParent(); 3672 AI->eraseFromParent(); 3673 } 3674 3675 PromotableAllocas.clear(); 3676 return true; 3677 } 3678 3679 bool SROA::runOnFunction(Function &F) { 3680 if (skipOptnoneFunction(F)) 3681 return false; 3682 3683 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n"); 3684 C = &F.getContext(); 3685 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); 3686 if (!DLP) { 3687 DEBUG(dbgs() << " Skipping SROA -- no target data!\n"); 3688 return false; 3689 } 3690 DL = &DLP->getDataLayout(); 3691 DominatorTreeWrapperPass *DTWP = 3692 getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 3693 DT = DTWP ? &DTWP->getDomTree() : nullptr; 3694 AT = &getAnalysis<AssumptionTracker>(); 3695 3696 BasicBlock &EntryBB = F.getEntryBlock(); 3697 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end()); 3698 I != E; ++I) 3699 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 3700 Worklist.insert(AI); 3701 3702 bool Changed = false; 3703 // A set of deleted alloca instruction pointers which should be removed from 3704 // the list of promotable allocas. 3705 SmallPtrSet<AllocaInst *, 4> DeletedAllocas; 3706 3707 do { 3708 while (!Worklist.empty()) { 3709 Changed |= runOnAlloca(*Worklist.pop_back_val()); 3710 deleteDeadInstructions(DeletedAllocas); 3711 3712 // Remove the deleted allocas from various lists so that we don't try to 3713 // continue processing them. 3714 if (!DeletedAllocas.empty()) { 3715 auto IsInSet = [&](AllocaInst *AI) { 3716 return DeletedAllocas.count(AI); 3717 }; 3718 Worklist.remove_if(IsInSet); 3719 PostPromotionWorklist.remove_if(IsInSet); 3720 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(), 3721 PromotableAllocas.end(), 3722 IsInSet), 3723 PromotableAllocas.end()); 3724 DeletedAllocas.clear(); 3725 } 3726 } 3727 3728 Changed |= promoteAllocas(F); 3729 3730 Worklist = PostPromotionWorklist; 3731 PostPromotionWorklist.clear(); 3732 } while (!Worklist.empty()); 3733 3734 return Changed; 3735 } 3736 3737 void SROA::getAnalysisUsage(AnalysisUsage &AU) const { 3738 AU.addRequired<AssumptionTracker>(); 3739 if (RequiresDomTree) 3740 AU.addRequired<DominatorTreeWrapperPass>(); 3741 AU.setPreservesCFG(); 3742 } 3743