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