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/SROA.h" 27 #include "llvm/ADT/APInt.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/PointerIntPair.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SetVector.h" 33 #include "llvm/ADT/SmallBitVector.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/Statistic.h" 37 #include "llvm/ADT/StringRef.h" 38 #include "llvm/ADT/Twine.h" 39 #include "llvm/ADT/iterator.h" 40 #include "llvm/ADT/iterator_range.h" 41 #include "llvm/Analysis/AssumptionCache.h" 42 #include "llvm/Analysis/GlobalsModRef.h" 43 #include "llvm/Analysis/Loads.h" 44 #include "llvm/Analysis/PtrUseVisitor.h" 45 #include "llvm/Transforms/Utils/Local.h" 46 #include "llvm/Config/llvm-config.h" 47 #include "llvm/IR/BasicBlock.h" 48 #include "llvm/IR/Constant.h" 49 #include "llvm/IR/ConstantFolder.h" 50 #include "llvm/IR/Constants.h" 51 #include "llvm/IR/DIBuilder.h" 52 #include "llvm/IR/DataLayout.h" 53 #include "llvm/IR/DebugInfoMetadata.h" 54 #include "llvm/IR/DerivedTypes.h" 55 #include "llvm/IR/Dominators.h" 56 #include "llvm/IR/Function.h" 57 #include "llvm/IR/GetElementPtrTypeIterator.h" 58 #include "llvm/IR/GlobalAlias.h" 59 #include "llvm/IR/IRBuilder.h" 60 #include "llvm/IR/InstVisitor.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Intrinsics.h" 66 #include "llvm/IR/LLVMContext.h" 67 #include "llvm/IR/Metadata.h" 68 #include "llvm/IR/Module.h" 69 #include "llvm/IR/Operator.h" 70 #include "llvm/IR/PassManager.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/User.h" 74 #include "llvm/IR/Value.h" 75 #include "llvm/Pass.h" 76 #include "llvm/Support/Casting.h" 77 #include "llvm/Support/CommandLine.h" 78 #include "llvm/Support/Compiler.h" 79 #include "llvm/Support/Debug.h" 80 #include "llvm/Support/ErrorHandling.h" 81 #include "llvm/Support/MathExtras.h" 82 #include "llvm/Support/raw_ostream.h" 83 #include "llvm/Transforms/Scalar.h" 84 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 85 #include <algorithm> 86 #include <cassert> 87 #include <chrono> 88 #include <cstddef> 89 #include <cstdint> 90 #include <cstring> 91 #include <iterator> 92 #include <string> 93 #include <tuple> 94 #include <utility> 95 #include <vector> 96 97 #ifndef NDEBUG 98 // We only use this for a debug check. 99 #include <random> 100 #endif 101 102 using namespace llvm; 103 using namespace llvm::sroa; 104 105 #define DEBUG_TYPE "sroa" 106 107 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement"); 108 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed"); 109 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca"); 110 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten"); 111 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition"); 112 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced"); 113 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values"); 114 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion"); 115 STATISTIC(NumDeleted, "Number of instructions deleted"); 116 STATISTIC(NumVectorized, "Number of vectorized aggregates"); 117 118 /// Hidden option to enable randomly shuffling the slices to help uncover 119 /// instability in their order. 120 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices", 121 cl::init(false), cl::Hidden); 122 123 /// Hidden option to experiment with completely strict handling of inbounds 124 /// GEPs. 125 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false), 126 cl::Hidden); 127 128 namespace { 129 130 /// A custom IRBuilder inserter which prefixes all names, but only in 131 /// Assert builds. 132 class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter { 133 std::string Prefix; 134 135 const Twine getNameWithPrefix(const Twine &Name) const { 136 return Name.isTriviallyEmpty() ? Name : Prefix + Name; 137 } 138 139 public: 140 void SetNamePrefix(const Twine &P) { Prefix = P.str(); } 141 142 protected: 143 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB, 144 BasicBlock::iterator InsertPt) const { 145 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB, 146 InsertPt); 147 } 148 }; 149 150 /// Provide a type for IRBuilder that drops names in release builds. 151 using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>; 152 153 /// A used slice of an alloca. 154 /// 155 /// This structure represents a slice of an alloca used by some instruction. It 156 /// stores both the begin and end offsets of this use, a pointer to the use 157 /// itself, and a flag indicating whether we can classify the use as splittable 158 /// or not when forming partitions of the alloca. 159 class Slice { 160 /// The beginning offset of the range. 161 uint64_t BeginOffset = 0; 162 163 /// The ending offset, not included in the range. 164 uint64_t EndOffset = 0; 165 166 /// Storage for both the use of this slice and whether it can be 167 /// split. 168 PointerIntPair<Use *, 1, bool> UseAndIsSplittable; 169 170 public: 171 Slice() = default; 172 173 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable) 174 : BeginOffset(BeginOffset), EndOffset(EndOffset), 175 UseAndIsSplittable(U, IsSplittable) {} 176 177 uint64_t beginOffset() const { return BeginOffset; } 178 uint64_t endOffset() const { return EndOffset; } 179 180 bool isSplittable() const { return UseAndIsSplittable.getInt(); } 181 void makeUnsplittable() { UseAndIsSplittable.setInt(false); } 182 183 Use *getUse() const { return UseAndIsSplittable.getPointer(); } 184 185 bool isDead() const { return getUse() == nullptr; } 186 void kill() { UseAndIsSplittable.setPointer(nullptr); } 187 188 /// Support for ordering ranges. 189 /// 190 /// This provides an ordering over ranges such that start offsets are 191 /// always increasing, and within equal start offsets, the end offsets are 192 /// decreasing. Thus the spanning range comes first in a cluster with the 193 /// same start position. 194 bool operator<(const Slice &RHS) const { 195 if (beginOffset() < RHS.beginOffset()) 196 return true; 197 if (beginOffset() > RHS.beginOffset()) 198 return false; 199 if (isSplittable() != RHS.isSplittable()) 200 return !isSplittable(); 201 if (endOffset() > RHS.endOffset()) 202 return true; 203 return false; 204 } 205 206 /// Support comparison with a single offset to allow binary searches. 207 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS, 208 uint64_t RHSOffset) { 209 return LHS.beginOffset() < RHSOffset; 210 } 211 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset, 212 const Slice &RHS) { 213 return LHSOffset < RHS.beginOffset(); 214 } 215 216 bool operator==(const Slice &RHS) const { 217 return isSplittable() == RHS.isSplittable() && 218 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset(); 219 } 220 bool operator!=(const Slice &RHS) const { return !operator==(RHS); } 221 }; 222 223 } // end anonymous namespace 224 225 namespace llvm { 226 227 template <typename T> struct isPodLike; 228 template <> struct isPodLike<Slice> { static const bool value = true; }; 229 230 } // end namespace llvm 231 232 /// Representation of the alloca slices. 233 /// 234 /// This class represents the slices of an alloca which are formed by its 235 /// various uses. If a pointer escapes, we can't fully build a representation 236 /// for the slices used and we reflect that in this structure. The uses are 237 /// stored, sorted by increasing beginning offset and with unsplittable slices 238 /// starting at a particular offset before splittable slices. 239 class llvm::sroa::AllocaSlices { 240 public: 241 /// Construct the slices of a particular alloca. 242 AllocaSlices(const DataLayout &DL, AllocaInst &AI); 243 244 /// Test whether a pointer to the allocation escapes our analysis. 245 /// 246 /// If this is true, the slices are never fully built and should be 247 /// ignored. 248 bool isEscaped() const { return PointerEscapingInstr; } 249 250 /// Support for iterating over the slices. 251 /// @{ 252 using iterator = SmallVectorImpl<Slice>::iterator; 253 using range = iterator_range<iterator>; 254 255 iterator begin() { return Slices.begin(); } 256 iterator end() { return Slices.end(); } 257 258 using const_iterator = SmallVectorImpl<Slice>::const_iterator; 259 using const_range = iterator_range<const_iterator>; 260 261 const_iterator begin() const { return Slices.begin(); } 262 const_iterator end() const { return Slices.end(); } 263 /// @} 264 265 /// Erase a range of slices. 266 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); } 267 268 /// Insert new slices for this alloca. 269 /// 270 /// This moves the slices into the alloca's slices collection, and re-sorts 271 /// everything so that the usual ordering properties of the alloca's slices 272 /// hold. 273 void insert(ArrayRef<Slice> NewSlices) { 274 int OldSize = Slices.size(); 275 Slices.append(NewSlices.begin(), NewSlices.end()); 276 auto SliceI = Slices.begin() + OldSize; 277 llvm::sort(SliceI, Slices.end()); 278 std::inplace_merge(Slices.begin(), SliceI, Slices.end()); 279 } 280 281 // Forward declare the iterator and range accessor for walking the 282 // partitions. 283 class partition_iterator; 284 iterator_range<partition_iterator> partitions(); 285 286 /// Access the dead users for this alloca. 287 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; } 288 289 /// Access the dead operands referring to this alloca. 290 /// 291 /// These are operands which have cannot actually be used to refer to the 292 /// alloca as they are outside its range and the user doesn't correct for 293 /// that. These mostly consist of PHI node inputs and the like which we just 294 /// need to replace with undef. 295 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; } 296 297 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 298 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const; 299 void printSlice(raw_ostream &OS, const_iterator I, 300 StringRef Indent = " ") const; 301 void printUse(raw_ostream &OS, const_iterator I, 302 StringRef Indent = " ") const; 303 void print(raw_ostream &OS) const; 304 void dump(const_iterator I) const; 305 void dump() const; 306 #endif 307 308 private: 309 template <typename DerivedT, typename RetT = void> class BuilderBase; 310 class SliceBuilder; 311 312 friend class AllocaSlices::SliceBuilder; 313 314 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 315 /// Handle to alloca instruction to simplify method interfaces. 316 AllocaInst &AI; 317 #endif 318 319 /// The instruction responsible for this alloca not having a known set 320 /// of slices. 321 /// 322 /// When an instruction (potentially) escapes the pointer to the alloca, we 323 /// store a pointer to that here and abort trying to form slices of the 324 /// alloca. This will be null if the alloca slices are analyzed successfully. 325 Instruction *PointerEscapingInstr; 326 327 /// The slices of the alloca. 328 /// 329 /// We store a vector of the slices formed by uses of the alloca here. This 330 /// vector is sorted by increasing begin offset, and then the unsplittable 331 /// slices before the splittable ones. See the Slice inner class for more 332 /// details. 333 SmallVector<Slice, 8> Slices; 334 335 /// Instructions which will become dead if we rewrite the alloca. 336 /// 337 /// Note that these are not separated by slice. This is because we expect an 338 /// alloca to be completely rewritten or not rewritten at all. If rewritten, 339 /// all these instructions can simply be removed and replaced with undef as 340 /// they come from outside of the allocated space. 341 SmallVector<Instruction *, 8> DeadUsers; 342 343 /// Operands which will become dead if we rewrite the alloca. 344 /// 345 /// These are operands that in their particular use can be replaced with 346 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs 347 /// to PHI nodes and the like. They aren't entirely dead (there might be 348 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we 349 /// want to swap this particular input for undef to simplify the use lists of 350 /// the alloca. 351 SmallVector<Use *, 8> DeadOperands; 352 }; 353 354 /// A partition of the slices. 355 /// 356 /// An ephemeral representation for a range of slices which can be viewed as 357 /// a partition of the alloca. This range represents a span of the alloca's 358 /// memory which cannot be split, and provides access to all of the slices 359 /// overlapping some part of the partition. 360 /// 361 /// Objects of this type are produced by traversing the alloca's slices, but 362 /// are only ephemeral and not persistent. 363 class llvm::sroa::Partition { 364 private: 365 friend class AllocaSlices; 366 friend class AllocaSlices::partition_iterator; 367 368 using iterator = AllocaSlices::iterator; 369 370 /// The beginning and ending offsets of the alloca for this 371 /// partition. 372 uint64_t BeginOffset, EndOffset; 373 374 /// The start and end iterators of this partition. 375 iterator SI, SJ; 376 377 /// A collection of split slice tails overlapping the partition. 378 SmallVector<Slice *, 4> SplitTails; 379 380 /// Raw constructor builds an empty partition starting and ending at 381 /// the given iterator. 382 Partition(iterator SI) : SI(SI), SJ(SI) {} 383 384 public: 385 /// The start offset of this partition. 386 /// 387 /// All of the contained slices start at or after this offset. 388 uint64_t beginOffset() const { return BeginOffset; } 389 390 /// The end offset of this partition. 391 /// 392 /// All of the contained slices end at or before this offset. 393 uint64_t endOffset() const { return EndOffset; } 394 395 /// The size of the partition. 396 /// 397 /// Note that this can never be zero. 398 uint64_t size() const { 399 assert(BeginOffset < EndOffset && "Partitions must span some bytes!"); 400 return EndOffset - BeginOffset; 401 } 402 403 /// Test whether this partition contains no slices, and merely spans 404 /// a region occupied by split slices. 405 bool empty() const { return SI == SJ; } 406 407 /// \name Iterate slices that start within the partition. 408 /// These may be splittable or unsplittable. They have a begin offset >= the 409 /// partition begin offset. 410 /// @{ 411 // FIXME: We should probably define a "concat_iterator" helper and use that 412 // to stitch together pointee_iterators over the split tails and the 413 // contiguous iterators of the partition. That would give a much nicer 414 // interface here. We could then additionally expose filtered iterators for 415 // split, unsplit, and unsplittable splices based on the usage patterns. 416 iterator begin() const { return SI; } 417 iterator end() const { return SJ; } 418 /// @} 419 420 /// Get the sequence of split slice tails. 421 /// 422 /// These tails are of slices which start before this partition but are 423 /// split and overlap into the partition. We accumulate these while forming 424 /// partitions. 425 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; } 426 }; 427 428 /// An iterator over partitions of the alloca's slices. 429 /// 430 /// This iterator implements the core algorithm for partitioning the alloca's 431 /// slices. It is a forward iterator as we don't support backtracking for 432 /// efficiency reasons, and re-use a single storage area to maintain the 433 /// current set of split slices. 434 /// 435 /// It is templated on the slice iterator type to use so that it can operate 436 /// with either const or non-const slice iterators. 437 class AllocaSlices::partition_iterator 438 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag, 439 Partition> { 440 friend class AllocaSlices; 441 442 /// Most of the state for walking the partitions is held in a class 443 /// with a nice interface for examining them. 444 Partition P; 445 446 /// We need to keep the end of the slices to know when to stop. 447 AllocaSlices::iterator SE; 448 449 /// We also need to keep track of the maximum split end offset seen. 450 /// FIXME: Do we really? 451 uint64_t MaxSplitSliceEndOffset = 0; 452 453 /// Sets the partition to be empty at given iterator, and sets the 454 /// end iterator. 455 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE) 456 : P(SI), SE(SE) { 457 // If not already at the end, advance our state to form the initial 458 // partition. 459 if (SI != SE) 460 advance(); 461 } 462 463 /// Advance the iterator to the next partition. 464 /// 465 /// Requires that the iterator not be at the end of the slices. 466 void advance() { 467 assert((P.SI != SE || !P.SplitTails.empty()) && 468 "Cannot advance past the end of the slices!"); 469 470 // Clear out any split uses which have ended. 471 if (!P.SplitTails.empty()) { 472 if (P.EndOffset >= MaxSplitSliceEndOffset) { 473 // If we've finished all splits, this is easy. 474 P.SplitTails.clear(); 475 MaxSplitSliceEndOffset = 0; 476 } else { 477 // Remove the uses which have ended in the prior partition. This 478 // cannot change the max split slice end because we just checked that 479 // the prior partition ended prior to that max. 480 P.SplitTails.erase(llvm::remove_if(P.SplitTails, 481 [&](Slice *S) { 482 return S->endOffset() <= 483 P.EndOffset; 484 }), 485 P.SplitTails.end()); 486 assert(llvm::any_of(P.SplitTails, 487 [&](Slice *S) { 488 return S->endOffset() == MaxSplitSliceEndOffset; 489 }) && 490 "Could not find the current max split slice offset!"); 491 assert(llvm::all_of(P.SplitTails, 492 [&](Slice *S) { 493 return S->endOffset() <= MaxSplitSliceEndOffset; 494 }) && 495 "Max split slice end offset is not actually the max!"); 496 } 497 } 498 499 // If P.SI is already at the end, then we've cleared the split tail and 500 // now have an end iterator. 501 if (P.SI == SE) { 502 assert(P.SplitTails.empty() && "Failed to clear the split slices!"); 503 return; 504 } 505 506 // If we had a non-empty partition previously, set up the state for 507 // subsequent partitions. 508 if (P.SI != P.SJ) { 509 // Accumulate all the splittable slices which started in the old 510 // partition into the split list. 511 for (Slice &S : P) 512 if (S.isSplittable() && S.endOffset() > P.EndOffset) { 513 P.SplitTails.push_back(&S); 514 MaxSplitSliceEndOffset = 515 std::max(S.endOffset(), MaxSplitSliceEndOffset); 516 } 517 518 // Start from the end of the previous partition. 519 P.SI = P.SJ; 520 521 // If P.SI is now at the end, we at most have a tail of split slices. 522 if (P.SI == SE) { 523 P.BeginOffset = P.EndOffset; 524 P.EndOffset = MaxSplitSliceEndOffset; 525 return; 526 } 527 528 // If the we have split slices and the next slice is after a gap and is 529 // not splittable immediately form an empty partition for the split 530 // slices up until the next slice begins. 531 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset && 532 !P.SI->isSplittable()) { 533 P.BeginOffset = P.EndOffset; 534 P.EndOffset = P.SI->beginOffset(); 535 return; 536 } 537 } 538 539 // OK, we need to consume new slices. Set the end offset based on the 540 // current slice, and step SJ past it. The beginning offset of the 541 // partition is the beginning offset of the next slice unless we have 542 // pre-existing split slices that are continuing, in which case we begin 543 // at the prior end offset. 544 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset; 545 P.EndOffset = P.SI->endOffset(); 546 ++P.SJ; 547 548 // There are two strategies to form a partition based on whether the 549 // partition starts with an unsplittable slice or a splittable slice. 550 if (!P.SI->isSplittable()) { 551 // When we're forming an unsplittable region, it must always start at 552 // the first slice and will extend through its end. 553 assert(P.BeginOffset == P.SI->beginOffset()); 554 555 // Form a partition including all of the overlapping slices with this 556 // unsplittable slice. 557 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) { 558 if (!P.SJ->isSplittable()) 559 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset()); 560 ++P.SJ; 561 } 562 563 // We have a partition across a set of overlapping unsplittable 564 // partitions. 565 return; 566 } 567 568 // If we're starting with a splittable slice, then we need to form 569 // a synthetic partition spanning it and any other overlapping splittable 570 // splices. 571 assert(P.SI->isSplittable() && "Forming a splittable partition!"); 572 573 // Collect all of the overlapping splittable slices. 574 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset && 575 P.SJ->isSplittable()) { 576 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset()); 577 ++P.SJ; 578 } 579 580 // Back upiP.EndOffset if we ended the span early when encountering an 581 // unsplittable slice. This synthesizes the early end offset of 582 // a partition spanning only splittable slices. 583 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) { 584 assert(!P.SJ->isSplittable()); 585 P.EndOffset = P.SJ->beginOffset(); 586 } 587 } 588 589 public: 590 bool operator==(const partition_iterator &RHS) const { 591 assert(SE == RHS.SE && 592 "End iterators don't match between compared partition iterators!"); 593 594 // The observed positions of partitions is marked by the P.SI iterator and 595 // the emptiness of the split slices. The latter is only relevant when 596 // P.SI == SE, as the end iterator will additionally have an empty split 597 // slices list, but the prior may have the same P.SI and a tail of split 598 // slices. 599 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) { 600 assert(P.SJ == RHS.P.SJ && 601 "Same set of slices formed two different sized partitions!"); 602 assert(P.SplitTails.size() == RHS.P.SplitTails.size() && 603 "Same slice position with differently sized non-empty split " 604 "slice tails!"); 605 return true; 606 } 607 return false; 608 } 609 610 partition_iterator &operator++() { 611 advance(); 612 return *this; 613 } 614 615 Partition &operator*() { return P; } 616 }; 617 618 /// A forward range over the partitions of the alloca's slices. 619 /// 620 /// This accesses an iterator range over the partitions of the alloca's 621 /// slices. It computes these partitions on the fly based on the overlapping 622 /// offsets of the slices and the ability to split them. It will visit "empty" 623 /// partitions to cover regions of the alloca only accessed via split 624 /// slices. 625 iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() { 626 return make_range(partition_iterator(begin(), end()), 627 partition_iterator(end(), end())); 628 } 629 630 static Value *foldSelectInst(SelectInst &SI) { 631 // If the condition being selected on is a constant or the same value is 632 // being selected between, fold the select. Yes this does (rarely) happen 633 // early on. 634 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition())) 635 return SI.getOperand(1 + CI->isZero()); 636 if (SI.getOperand(1) == SI.getOperand(2)) 637 return SI.getOperand(1); 638 639 return nullptr; 640 } 641 642 /// A helper that folds a PHI node or a select. 643 static Value *foldPHINodeOrSelectInst(Instruction &I) { 644 if (PHINode *PN = dyn_cast<PHINode>(&I)) { 645 // If PN merges together the same value, return that value. 646 return PN->hasConstantValue(); 647 } 648 return foldSelectInst(cast<SelectInst>(I)); 649 } 650 651 /// Builder for the alloca slices. 652 /// 653 /// This class builds a set of alloca slices by recursively visiting the uses 654 /// of an alloca and making a slice for each load and store at each offset. 655 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> { 656 friend class PtrUseVisitor<SliceBuilder>; 657 friend class InstVisitor<SliceBuilder>; 658 659 using Base = PtrUseVisitor<SliceBuilder>; 660 661 const uint64_t AllocSize; 662 AllocaSlices &AS; 663 664 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap; 665 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes; 666 667 /// Set to de-duplicate dead instructions found in the use walk. 668 SmallPtrSet<Instruction *, 4> VisitedDeadInsts; 669 670 public: 671 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS) 672 : PtrUseVisitor<SliceBuilder>(DL), 673 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {} 674 675 private: 676 void markAsDead(Instruction &I) { 677 if (VisitedDeadInsts.insert(&I).second) 678 AS.DeadUsers.push_back(&I); 679 } 680 681 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size, 682 bool IsSplittable = false) { 683 // Completely skip uses which have a zero size or start either before or 684 // past the end of the allocation. 685 if (Size == 0 || Offset.uge(AllocSize)) { 686 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" 687 << Offset 688 << " which has zero size or starts outside of the " 689 << AllocSize << " byte alloca:\n" 690 << " alloca: " << AS.AI << "\n" 691 << " use: " << I << "\n"); 692 return markAsDead(I); 693 } 694 695 uint64_t BeginOffset = Offset.getZExtValue(); 696 uint64_t EndOffset = BeginOffset + Size; 697 698 // Clamp the end offset to the end of the allocation. Note that this is 699 // formulated to handle even the case where "BeginOffset + Size" overflows. 700 // This may appear superficially to be something we could ignore entirely, 701 // but that is not so! There may be widened loads or PHI-node uses where 702 // some instructions are dead but not others. We can't completely ignore 703 // them, and so have to record at least the information here. 704 assert(AllocSize >= BeginOffset); // Established above. 705 if (Size > AllocSize - BeginOffset) { 706 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" 707 << Offset << " to remain within the " << AllocSize 708 << " byte alloca:\n" 709 << " alloca: " << AS.AI << "\n" 710 << " use: " << I << "\n"); 711 EndOffset = AllocSize; 712 } 713 714 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable)); 715 } 716 717 void visitBitCastInst(BitCastInst &BC) { 718 if (BC.use_empty()) 719 return markAsDead(BC); 720 721 return Base::visitBitCastInst(BC); 722 } 723 724 void visitGetElementPtrInst(GetElementPtrInst &GEPI) { 725 if (GEPI.use_empty()) 726 return markAsDead(GEPI); 727 728 if (SROAStrictInbounds && GEPI.isInBounds()) { 729 // FIXME: This is a manually un-factored variant of the basic code inside 730 // of GEPs with checking of the inbounds invariant specified in the 731 // langref in a very strict sense. If we ever want to enable 732 // SROAStrictInbounds, this code should be factored cleanly into 733 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds 734 // by writing out the code here where we have the underlying allocation 735 // size readily available. 736 APInt GEPOffset = Offset; 737 const DataLayout &DL = GEPI.getModule()->getDataLayout(); 738 for (gep_type_iterator GTI = gep_type_begin(GEPI), 739 GTE = gep_type_end(GEPI); 740 GTI != GTE; ++GTI) { 741 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); 742 if (!OpC) 743 break; 744 745 // Handle a struct index, which adds its field offset to the pointer. 746 if (StructType *STy = GTI.getStructTypeOrNull()) { 747 unsigned ElementIdx = OpC->getZExtValue(); 748 const StructLayout *SL = DL.getStructLayout(STy); 749 GEPOffset += 750 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx)); 751 } else { 752 // For array or vector indices, scale the index by the size of the 753 // type. 754 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth()); 755 GEPOffset += Index * APInt(Offset.getBitWidth(), 756 DL.getTypeAllocSize(GTI.getIndexedType())); 757 } 758 759 // If this index has computed an intermediate pointer which is not 760 // inbounds, then the result of the GEP is a poison value and we can 761 // delete it and all uses. 762 if (GEPOffset.ugt(AllocSize)) 763 return markAsDead(GEPI); 764 } 765 } 766 767 return Base::visitGetElementPtrInst(GEPI); 768 } 769 770 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset, 771 uint64_t Size, bool IsVolatile) { 772 // We allow splitting of non-volatile loads and stores where the type is an 773 // integer type. These may be used to implement 'memcpy' or other "transfer 774 // of bits" patterns. 775 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile; 776 777 insertUse(I, Offset, Size, IsSplittable); 778 } 779 780 void visitLoadInst(LoadInst &LI) { 781 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) && 782 "All simple FCA loads should have been pre-split"); 783 784 if (!IsOffsetKnown) 785 return PI.setAborted(&LI); 786 787 const DataLayout &DL = LI.getModule()->getDataLayout(); 788 uint64_t Size = DL.getTypeStoreSize(LI.getType()); 789 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile()); 790 } 791 792 void visitStoreInst(StoreInst &SI) { 793 Value *ValOp = SI.getValueOperand(); 794 if (ValOp == *U) 795 return PI.setEscapedAndAborted(&SI); 796 if (!IsOffsetKnown) 797 return PI.setAborted(&SI); 798 799 const DataLayout &DL = SI.getModule()->getDataLayout(); 800 uint64_t Size = DL.getTypeStoreSize(ValOp->getType()); 801 802 // If this memory access can be shown to *statically* extend outside the 803 // bounds of the allocation, it's behavior is undefined, so simply 804 // ignore it. Note that this is more strict than the generic clamping 805 // behavior of insertUse. We also try to handle cases which might run the 806 // risk of overflow. 807 // FIXME: We should instead consider the pointer to have escaped if this 808 // function is being instrumented for addressing bugs or race conditions. 809 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) { 810 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" 811 << Offset << " which extends past the end of the " 812 << AllocSize << " byte alloca:\n" 813 << " alloca: " << AS.AI << "\n" 814 << " use: " << SI << "\n"); 815 return markAsDead(SI); 816 } 817 818 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) && 819 "All simple FCA stores should have been pre-split"); 820 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile()); 821 } 822 823 void visitMemSetInst(MemSetInst &II) { 824 assert(II.getRawDest() == *U && "Pointer use is not the destination?"); 825 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); 826 if ((Length && Length->getValue() == 0) || 827 (IsOffsetKnown && Offset.uge(AllocSize))) 828 // Zero-length mem transfer intrinsics can be ignored entirely. 829 return markAsDead(II); 830 831 if (!IsOffsetKnown) 832 return PI.setAborted(&II); 833 834 insertUse(II, Offset, Length ? Length->getLimitedValue() 835 : AllocSize - Offset.getLimitedValue(), 836 (bool)Length); 837 } 838 839 void visitMemTransferInst(MemTransferInst &II) { 840 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); 841 if (Length && Length->getValue() == 0) 842 // Zero-length mem transfer intrinsics can be ignored entirely. 843 return markAsDead(II); 844 845 // Because we can visit these intrinsics twice, also check to see if the 846 // first time marked this instruction as dead. If so, skip it. 847 if (VisitedDeadInsts.count(&II)) 848 return; 849 850 if (!IsOffsetKnown) 851 return PI.setAborted(&II); 852 853 // This side of the transfer is completely out-of-bounds, and so we can 854 // nuke the entire transfer. However, we also need to nuke the other side 855 // if already added to our partitions. 856 // FIXME: Yet another place we really should bypass this when 857 // instrumenting for ASan. 858 if (Offset.uge(AllocSize)) { 859 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = 860 MemTransferSliceMap.find(&II); 861 if (MTPI != MemTransferSliceMap.end()) 862 AS.Slices[MTPI->second].kill(); 863 return markAsDead(II); 864 } 865 866 uint64_t RawOffset = Offset.getLimitedValue(); 867 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset; 868 869 // Check for the special case where the same exact value is used for both 870 // source and dest. 871 if (*U == II.getRawDest() && *U == II.getRawSource()) { 872 // For non-volatile transfers this is a no-op. 873 if (!II.isVolatile()) 874 return markAsDead(II); 875 876 return insertUse(II, Offset, Size, /*IsSplittable=*/false); 877 } 878 879 // If we have seen both source and destination for a mem transfer, then 880 // they both point to the same alloca. 881 bool Inserted; 882 SmallDenseMap<Instruction *, unsigned>::iterator MTPI; 883 std::tie(MTPI, Inserted) = 884 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size())); 885 unsigned PrevIdx = MTPI->second; 886 if (!Inserted) { 887 Slice &PrevP = AS.Slices[PrevIdx]; 888 889 // Check if the begin offsets match and this is a non-volatile transfer. 890 // In that case, we can completely elide the transfer. 891 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) { 892 PrevP.kill(); 893 return markAsDead(II); 894 } 895 896 // Otherwise we have an offset transfer within the same alloca. We can't 897 // split those. 898 PrevP.makeUnsplittable(); 899 } 900 901 // Insert the use now that we've fixed up the splittable nature. 902 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length); 903 904 // Check that we ended up with a valid index in the map. 905 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II && 906 "Map index doesn't point back to a slice with this user."); 907 } 908 909 // Disable SRoA for any intrinsics except for lifetime invariants. 910 // FIXME: What about debug intrinsics? This matches old behavior, but 911 // doesn't make sense. 912 void visitIntrinsicInst(IntrinsicInst &II) { 913 if (!IsOffsetKnown) 914 return PI.setAborted(&II); 915 916 if (II.isLifetimeStartOrEnd()) { 917 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0)); 918 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(), 919 Length->getLimitedValue()); 920 insertUse(II, Offset, Size, true); 921 return; 922 } 923 924 Base::visitIntrinsicInst(II); 925 } 926 927 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) { 928 // We consider any PHI or select that results in a direct load or store of 929 // the same offset to be a viable use for slicing purposes. These uses 930 // are considered unsplittable and the size is the maximum loaded or stored 931 // size. 932 SmallPtrSet<Instruction *, 4> Visited; 933 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses; 934 Visited.insert(Root); 935 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root)); 936 const DataLayout &DL = Root->getModule()->getDataLayout(); 937 // If there are no loads or stores, the access is dead. We mark that as 938 // a size zero access. 939 Size = 0; 940 do { 941 Instruction *I, *UsedI; 942 std::tie(UsedI, I) = Uses.pop_back_val(); 943 944 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 945 Size = std::max(Size, DL.getTypeStoreSize(LI->getType())); 946 continue; 947 } 948 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 949 Value *Op = SI->getOperand(0); 950 if (Op == UsedI) 951 return SI; 952 Size = std::max(Size, DL.getTypeStoreSize(Op->getType())); 953 continue; 954 } 955 956 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) { 957 if (!GEP->hasAllZeroIndices()) 958 return GEP; 959 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) && 960 !isa<SelectInst>(I)) { 961 return I; 962 } 963 964 for (User *U : I->users()) 965 if (Visited.insert(cast<Instruction>(U)).second) 966 Uses.push_back(std::make_pair(I, cast<Instruction>(U))); 967 } while (!Uses.empty()); 968 969 return nullptr; 970 } 971 972 void visitPHINodeOrSelectInst(Instruction &I) { 973 assert(isa<PHINode>(I) || isa<SelectInst>(I)); 974 if (I.use_empty()) 975 return markAsDead(I); 976 977 // TODO: We could use SimplifyInstruction here to fold PHINodes and 978 // SelectInsts. However, doing so requires to change the current 979 // dead-operand-tracking mechanism. For instance, suppose neither loading 980 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not 981 // trap either. However, if we simply replace %U with undef using the 982 // current dead-operand-tracking mechanism, "load (select undef, undef, 983 // %other)" may trap because the select may return the first operand 984 // "undef". 985 if (Value *Result = foldPHINodeOrSelectInst(I)) { 986 if (Result == *U) 987 // If the result of the constant fold will be the pointer, recurse 988 // through the PHI/select as if we had RAUW'ed it. 989 enqueueUsers(I); 990 else 991 // Otherwise the operand to the PHI/select is dead, and we can replace 992 // it with undef. 993 AS.DeadOperands.push_back(U); 994 995 return; 996 } 997 998 if (!IsOffsetKnown) 999 return PI.setAborted(&I); 1000 1001 // See if we already have computed info on this node. 1002 uint64_t &Size = PHIOrSelectSizes[&I]; 1003 if (!Size) { 1004 // This is a new PHI/Select, check for an unsafe use of it. 1005 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size)) 1006 return PI.setAborted(UnsafeI); 1007 } 1008 1009 // For PHI and select operands outside the alloca, we can't nuke the entire 1010 // phi or select -- the other side might still be relevant, so we special 1011 // case them here and use a separate structure to track the operands 1012 // themselves which should be replaced with undef. 1013 // FIXME: This should instead be escaped in the event we're instrumenting 1014 // for address sanitization. 1015 if (Offset.uge(AllocSize)) { 1016 AS.DeadOperands.push_back(U); 1017 return; 1018 } 1019 1020 insertUse(I, Offset, Size); 1021 } 1022 1023 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); } 1024 1025 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); } 1026 1027 /// Disable SROA entirely if there are unhandled users of the alloca. 1028 void visitInstruction(Instruction &I) { PI.setAborted(&I); } 1029 }; 1030 1031 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI) 1032 : 1033 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1034 AI(AI), 1035 #endif 1036 PointerEscapingInstr(nullptr) { 1037 SliceBuilder PB(DL, AI, *this); 1038 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI); 1039 if (PtrI.isEscaped() || PtrI.isAborted()) { 1040 // FIXME: We should sink the escape vs. abort info into the caller nicely, 1041 // possibly by just storing the PtrInfo in the AllocaSlices. 1042 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst() 1043 : PtrI.getAbortingInst(); 1044 assert(PointerEscapingInstr && "Did not track a bad instruction"); 1045 return; 1046 } 1047 1048 Slices.erase( 1049 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }), 1050 Slices.end()); 1051 1052 #ifndef NDEBUG 1053 if (SROARandomShuffleSlices) { 1054 std::mt19937 MT(static_cast<unsigned>( 1055 std::chrono::system_clock::now().time_since_epoch().count())); 1056 std::shuffle(Slices.begin(), Slices.end(), MT); 1057 } 1058 #endif 1059 1060 // Sort the uses. This arranges for the offsets to be in ascending order, 1061 // and the sizes to be in descending order. 1062 llvm::sort(Slices); 1063 } 1064 1065 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1066 1067 void AllocaSlices::print(raw_ostream &OS, const_iterator I, 1068 StringRef Indent) const { 1069 printSlice(OS, I, Indent); 1070 OS << "\n"; 1071 printUse(OS, I, Indent); 1072 } 1073 1074 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I, 1075 StringRef Indent) const { 1076 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")" 1077 << " slice #" << (I - begin()) 1078 << (I->isSplittable() ? " (splittable)" : ""); 1079 } 1080 1081 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I, 1082 StringRef Indent) const { 1083 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n"; 1084 } 1085 1086 void AllocaSlices::print(raw_ostream &OS) const { 1087 if (PointerEscapingInstr) { 1088 OS << "Can't analyze slices for alloca: " << AI << "\n" 1089 << " A pointer to this alloca escaped by:\n" 1090 << " " << *PointerEscapingInstr << "\n"; 1091 return; 1092 } 1093 1094 OS << "Slices of alloca: " << AI << "\n"; 1095 for (const_iterator I = begin(), E = end(); I != E; ++I) 1096 print(OS, I); 1097 } 1098 1099 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const { 1100 print(dbgs(), I); 1101 } 1102 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); } 1103 1104 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1105 1106 /// Walk the range of a partitioning looking for a common type to cover this 1107 /// sequence of slices. 1108 static Type *findCommonType(AllocaSlices::const_iterator B, 1109 AllocaSlices::const_iterator E, 1110 uint64_t EndOffset) { 1111 Type *Ty = nullptr; 1112 bool TyIsCommon = true; 1113 IntegerType *ITy = nullptr; 1114 1115 // Note that we need to look at *every* alloca slice's Use to ensure we 1116 // always get consistent results regardless of the order of slices. 1117 for (AllocaSlices::const_iterator I = B; I != E; ++I) { 1118 Use *U = I->getUse(); 1119 if (isa<IntrinsicInst>(*U->getUser())) 1120 continue; 1121 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset) 1122 continue; 1123 1124 Type *UserTy = nullptr; 1125 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 1126 UserTy = LI->getType(); 1127 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 1128 UserTy = SI->getValueOperand()->getType(); 1129 } 1130 1131 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) { 1132 // If the type is larger than the partition, skip it. We only encounter 1133 // this for split integer operations where we want to use the type of the 1134 // entity causing the split. Also skip if the type is not a byte width 1135 // multiple. 1136 if (UserITy->getBitWidth() % 8 != 0 || 1137 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset())) 1138 continue; 1139 1140 // Track the largest bitwidth integer type used in this way in case there 1141 // is no common type. 1142 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth()) 1143 ITy = UserITy; 1144 } 1145 1146 // To avoid depending on the order of slices, Ty and TyIsCommon must not 1147 // depend on types skipped above. 1148 if (!UserTy || (Ty && Ty != UserTy)) 1149 TyIsCommon = false; // Give up on anything but an iN type. 1150 else 1151 Ty = UserTy; 1152 } 1153 1154 return TyIsCommon ? Ty : ITy; 1155 } 1156 1157 /// PHI instructions that use an alloca and are subsequently loaded can be 1158 /// rewritten to load both input pointers in the pred blocks and then PHI the 1159 /// results, allowing the load of the alloca to be promoted. 1160 /// From this: 1161 /// %P2 = phi [i32* %Alloca, i32* %Other] 1162 /// %V = load i32* %P2 1163 /// to: 1164 /// %V1 = load i32* %Alloca -> will be mem2reg'd 1165 /// ... 1166 /// %V2 = load i32* %Other 1167 /// ... 1168 /// %V = phi [i32 %V1, i32 %V2] 1169 /// 1170 /// We can do this to a select if its only uses are loads and if the operands 1171 /// to the select can be loaded unconditionally. 1172 /// 1173 /// FIXME: This should be hoisted into a generic utility, likely in 1174 /// Transforms/Util/Local.h 1175 static bool isSafePHIToSpeculate(PHINode &PN) { 1176 // For now, we can only do this promotion if the load is in the same block 1177 // as the PHI, and if there are no stores between the phi and load. 1178 // TODO: Allow recursive phi users. 1179 // TODO: Allow stores. 1180 BasicBlock *BB = PN.getParent(); 1181 unsigned MaxAlign = 0; 1182 bool HaveLoad = false; 1183 for (User *U : PN.users()) { 1184 LoadInst *LI = dyn_cast<LoadInst>(U); 1185 if (!LI || !LI->isSimple()) 1186 return false; 1187 1188 // For now we only allow loads in the same block as the PHI. This is 1189 // a common case that happens when instcombine merges two loads through 1190 // a PHI. 1191 if (LI->getParent() != BB) 1192 return false; 1193 1194 // Ensure that there are no instructions between the PHI and the load that 1195 // could store. 1196 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI) 1197 if (BBI->mayWriteToMemory()) 1198 return false; 1199 1200 MaxAlign = std::max(MaxAlign, LI->getAlignment()); 1201 HaveLoad = true; 1202 } 1203 1204 if (!HaveLoad) 1205 return false; 1206 1207 const DataLayout &DL = PN.getModule()->getDataLayout(); 1208 1209 // We can only transform this if it is safe to push the loads into the 1210 // predecessor blocks. The only thing to watch out for is that we can't put 1211 // a possibly trapping load in the predecessor if it is a critical edge. 1212 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) { 1213 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator(); 1214 Value *InVal = PN.getIncomingValue(Idx); 1215 1216 // If the value is produced by the terminator of the predecessor (an 1217 // invoke) or it has side-effects, there is no valid place to put a load 1218 // in the predecessor. 1219 if (TI == InVal || TI->mayHaveSideEffects()) 1220 return false; 1221 1222 // If the predecessor has a single successor, then the edge isn't 1223 // critical. 1224 if (TI->getNumSuccessors() == 1) 1225 continue; 1226 1227 // If this pointer is always safe to load, or if we can prove that there 1228 // is already a load in the block, then we can move the load to the pred 1229 // block. 1230 if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI)) 1231 continue; 1232 1233 return false; 1234 } 1235 1236 return true; 1237 } 1238 1239 static void speculatePHINodeLoads(PHINode &PN) { 1240 LLVM_DEBUG(dbgs() << " original: " << PN << "\n"); 1241 1242 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType(); 1243 IRBuilderTy PHIBuilder(&PN); 1244 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(), 1245 PN.getName() + ".sroa.speculated"); 1246 1247 // Get the AA tags and alignment to use from one of the loads. It doesn't 1248 // matter which one we get and if any differ. 1249 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back()); 1250 1251 AAMDNodes AATags; 1252 SomeLoad->getAAMetadata(AATags); 1253 unsigned Align = SomeLoad->getAlignment(); 1254 1255 // Rewrite all loads of the PN to use the new PHI. 1256 while (!PN.use_empty()) { 1257 LoadInst *LI = cast<LoadInst>(PN.user_back()); 1258 LI->replaceAllUsesWith(NewPN); 1259 LI->eraseFromParent(); 1260 } 1261 1262 // Inject loads into all of the pred blocks. 1263 DenseMap<BasicBlock*, Value*> InjectedLoads; 1264 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) { 1265 BasicBlock *Pred = PN.getIncomingBlock(Idx); 1266 Value *InVal = PN.getIncomingValue(Idx); 1267 1268 // A PHI node is allowed to have multiple (duplicated) entries for the same 1269 // basic block, as long as the value is the same. So if we already injected 1270 // a load in the predecessor, then we should reuse the same load for all 1271 // duplicated entries. 1272 if (Value* V = InjectedLoads.lookup(Pred)) { 1273 NewPN->addIncoming(V, Pred); 1274 continue; 1275 } 1276 1277 Instruction *TI = Pred->getTerminator(); 1278 IRBuilderTy PredBuilder(TI); 1279 1280 LoadInst *Load = PredBuilder.CreateLoad( 1281 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName())); 1282 ++NumLoadsSpeculated; 1283 Load->setAlignment(Align); 1284 if (AATags) 1285 Load->setAAMetadata(AATags); 1286 NewPN->addIncoming(Load, Pred); 1287 InjectedLoads[Pred] = Load; 1288 } 1289 1290 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n"); 1291 PN.eraseFromParent(); 1292 } 1293 1294 /// Select instructions that use an alloca and are subsequently loaded can be 1295 /// rewritten to load both input pointers and then select between the result, 1296 /// allowing the load of the alloca to be promoted. 1297 /// From this: 1298 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other 1299 /// %V = load i32* %P2 1300 /// to: 1301 /// %V1 = load i32* %Alloca -> will be mem2reg'd 1302 /// %V2 = load i32* %Other 1303 /// %V = select i1 %cond, i32 %V1, i32 %V2 1304 /// 1305 /// We can do this to a select if its only uses are loads and if the operand 1306 /// to the select can be loaded unconditionally. 1307 static bool isSafeSelectToSpeculate(SelectInst &SI) { 1308 Value *TValue = SI.getTrueValue(); 1309 Value *FValue = SI.getFalseValue(); 1310 const DataLayout &DL = SI.getModule()->getDataLayout(); 1311 1312 for (User *U : SI.users()) { 1313 LoadInst *LI = dyn_cast<LoadInst>(U); 1314 if (!LI || !LI->isSimple()) 1315 return false; 1316 1317 // Both operands to the select need to be dereferenceable, either 1318 // absolutely (e.g. allocas) or at this point because we can see other 1319 // accesses to it. 1320 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI)) 1321 return false; 1322 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI)) 1323 return false; 1324 } 1325 1326 return true; 1327 } 1328 1329 static void speculateSelectInstLoads(SelectInst &SI) { 1330 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 1331 1332 IRBuilderTy IRB(&SI); 1333 Value *TV = SI.getTrueValue(); 1334 Value *FV = SI.getFalseValue(); 1335 // Replace the loads of the select with a select of two loads. 1336 while (!SI.use_empty()) { 1337 LoadInst *LI = cast<LoadInst>(SI.user_back()); 1338 assert(LI->isSimple() && "We only speculate simple loads"); 1339 1340 IRB.SetInsertPoint(LI); 1341 LoadInst *TL = 1342 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true"); 1343 LoadInst *FL = 1344 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false"); 1345 NumLoadsSpeculated += 2; 1346 1347 // Transfer alignment and AA info if present. 1348 TL->setAlignment(LI->getAlignment()); 1349 FL->setAlignment(LI->getAlignment()); 1350 1351 AAMDNodes Tags; 1352 LI->getAAMetadata(Tags); 1353 if (Tags) { 1354 TL->setAAMetadata(Tags); 1355 FL->setAAMetadata(Tags); 1356 } 1357 1358 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL, 1359 LI->getName() + ".sroa.speculated"); 1360 1361 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n"); 1362 LI->replaceAllUsesWith(V); 1363 LI->eraseFromParent(); 1364 } 1365 SI.eraseFromParent(); 1366 } 1367 1368 /// Build a GEP out of a base pointer and indices. 1369 /// 1370 /// This will return the BasePtr if that is valid, or build a new GEP 1371 /// instruction using the IRBuilder if GEP-ing is needed. 1372 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr, 1373 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) { 1374 if (Indices.empty()) 1375 return BasePtr; 1376 1377 // A single zero index is a no-op, so check for this and avoid building a GEP 1378 // in that case. 1379 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero()) 1380 return BasePtr; 1381 1382 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices, 1383 NamePrefix + "sroa_idx"); 1384 } 1385 1386 /// Get a natural GEP off of the BasePtr walking through Ty toward 1387 /// TargetTy without changing the offset of the pointer. 1388 /// 1389 /// This routine assumes we've already established a properly offset GEP with 1390 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with 1391 /// zero-indices down through type layers until we find one the same as 1392 /// TargetTy. If we can't find one with the same type, we at least try to use 1393 /// one with the same size. If none of that works, we just produce the GEP as 1394 /// indicated by Indices to have the correct offset. 1395 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL, 1396 Value *BasePtr, Type *Ty, Type *TargetTy, 1397 SmallVectorImpl<Value *> &Indices, 1398 Twine NamePrefix) { 1399 if (Ty == TargetTy) 1400 return buildGEP(IRB, BasePtr, Indices, NamePrefix); 1401 1402 // Offset size to use for the indices. 1403 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType()); 1404 1405 // See if we can descend into a struct and locate a field with the correct 1406 // type. 1407 unsigned NumLayers = 0; 1408 Type *ElementTy = Ty; 1409 do { 1410 if (ElementTy->isPointerTy()) 1411 break; 1412 1413 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) { 1414 ElementTy = ArrayTy->getElementType(); 1415 Indices.push_back(IRB.getIntN(OffsetSize, 0)); 1416 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) { 1417 ElementTy = VectorTy->getElementType(); 1418 Indices.push_back(IRB.getInt32(0)); 1419 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) { 1420 if (STy->element_begin() == STy->element_end()) 1421 break; // Nothing left to descend into. 1422 ElementTy = *STy->element_begin(); 1423 Indices.push_back(IRB.getInt32(0)); 1424 } else { 1425 break; 1426 } 1427 ++NumLayers; 1428 } while (ElementTy != TargetTy); 1429 if (ElementTy != TargetTy) 1430 Indices.erase(Indices.end() - NumLayers, Indices.end()); 1431 1432 return buildGEP(IRB, BasePtr, Indices, NamePrefix); 1433 } 1434 1435 /// Recursively compute indices for a natural GEP. 1436 /// 1437 /// This is the recursive step for getNaturalGEPWithOffset that walks down the 1438 /// element types adding appropriate indices for the GEP. 1439 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL, 1440 Value *Ptr, Type *Ty, APInt &Offset, 1441 Type *TargetTy, 1442 SmallVectorImpl<Value *> &Indices, 1443 Twine NamePrefix) { 1444 if (Offset == 0) 1445 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, 1446 NamePrefix); 1447 1448 // We can't recurse through pointer types. 1449 if (Ty->isPointerTy()) 1450 return nullptr; 1451 1452 // We try to analyze GEPs over vectors here, but note that these GEPs are 1453 // extremely poorly defined currently. The long-term goal is to remove GEPing 1454 // over a vector from the IR completely. 1455 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) { 1456 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType()); 1457 if (ElementSizeInBits % 8 != 0) { 1458 // GEPs over non-multiple of 8 size vector elements are invalid. 1459 return nullptr; 1460 } 1461 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8); 1462 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1463 if (NumSkippedElements.ugt(VecTy->getNumElements())) 1464 return nullptr; 1465 Offset -= NumSkippedElements * ElementSize; 1466 Indices.push_back(IRB.getInt(NumSkippedElements)); 1467 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(), 1468 Offset, TargetTy, Indices, NamePrefix); 1469 } 1470 1471 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) { 1472 Type *ElementTy = ArrTy->getElementType(); 1473 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy)); 1474 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1475 if (NumSkippedElements.ugt(ArrTy->getNumElements())) 1476 return nullptr; 1477 1478 Offset -= NumSkippedElements * ElementSize; 1479 Indices.push_back(IRB.getInt(NumSkippedElements)); 1480 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1481 Indices, NamePrefix); 1482 } 1483 1484 StructType *STy = dyn_cast<StructType>(Ty); 1485 if (!STy) 1486 return nullptr; 1487 1488 const StructLayout *SL = DL.getStructLayout(STy); 1489 uint64_t StructOffset = Offset.getZExtValue(); 1490 if (StructOffset >= SL->getSizeInBytes()) 1491 return nullptr; 1492 unsigned Index = SL->getElementContainingOffset(StructOffset); 1493 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index)); 1494 Type *ElementTy = STy->getElementType(Index); 1495 if (Offset.uge(DL.getTypeAllocSize(ElementTy))) 1496 return nullptr; // The offset points into alignment padding. 1497 1498 Indices.push_back(IRB.getInt32(Index)); 1499 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1500 Indices, NamePrefix); 1501 } 1502 1503 /// Get a natural GEP from a base pointer to a particular offset and 1504 /// resulting in a particular type. 1505 /// 1506 /// The goal is to produce a "natural" looking GEP that works with the existing 1507 /// composite types to arrive at the appropriate offset and element type for 1508 /// a pointer. TargetTy is the element type the returned GEP should point-to if 1509 /// possible. We recurse by decreasing Offset, adding the appropriate index to 1510 /// Indices, and setting Ty to the result subtype. 1511 /// 1512 /// If no natural GEP can be constructed, this function returns null. 1513 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL, 1514 Value *Ptr, APInt Offset, Type *TargetTy, 1515 SmallVectorImpl<Value *> &Indices, 1516 Twine NamePrefix) { 1517 PointerType *Ty = cast<PointerType>(Ptr->getType()); 1518 1519 // Don't consider any GEPs through an i8* as natural unless the TargetTy is 1520 // an i8. 1521 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8)) 1522 return nullptr; 1523 1524 Type *ElementTy = Ty->getElementType(); 1525 if (!ElementTy->isSized()) 1526 return nullptr; // We can't GEP through an unsized element. 1527 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy)); 1528 if (ElementSize == 0) 1529 return nullptr; // Zero-length arrays can't help us build a natural GEP. 1530 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1531 1532 Offset -= NumSkippedElements * ElementSize; 1533 Indices.push_back(IRB.getInt(NumSkippedElements)); 1534 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1535 Indices, NamePrefix); 1536 } 1537 1538 /// Compute an adjusted pointer from Ptr by Offset bytes where the 1539 /// resulting pointer has PointerTy. 1540 /// 1541 /// This tries very hard to compute a "natural" GEP which arrives at the offset 1542 /// and produces the pointer type desired. Where it cannot, it will try to use 1543 /// the natural GEP to arrive at the offset and bitcast to the type. Where that 1544 /// fails, it will try to use an existing i8* and GEP to the byte offset and 1545 /// bitcast to the type. 1546 /// 1547 /// The strategy for finding the more natural GEPs is to peel off layers of the 1548 /// pointer, walking back through bit casts and GEPs, searching for a base 1549 /// pointer from which we can compute a natural GEP with the desired 1550 /// properties. The algorithm tries to fold as many constant indices into 1551 /// a single GEP as possible, thus making each GEP more independent of the 1552 /// surrounding code. 1553 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, 1554 APInt Offset, Type *PointerTy, Twine NamePrefix) { 1555 // Even though we don't look through PHI nodes, we could be called on an 1556 // instruction in an unreachable block, which may be on a cycle. 1557 SmallPtrSet<Value *, 4> Visited; 1558 Visited.insert(Ptr); 1559 SmallVector<Value *, 4> Indices; 1560 1561 // We may end up computing an offset pointer that has the wrong type. If we 1562 // never are able to compute one directly that has the correct type, we'll 1563 // fall back to it, so keep it and the base it was computed from around here. 1564 Value *OffsetPtr = nullptr; 1565 Value *OffsetBasePtr; 1566 1567 // Remember any i8 pointer we come across to re-use if we need to do a raw 1568 // byte offset. 1569 Value *Int8Ptr = nullptr; 1570 APInt Int8PtrOffset(Offset.getBitWidth(), 0); 1571 1572 Type *TargetTy = PointerTy->getPointerElementType(); 1573 1574 do { 1575 // First fold any existing GEPs into the offset. 1576 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) { 1577 APInt GEPOffset(Offset.getBitWidth(), 0); 1578 if (!GEP->accumulateConstantOffset(DL, GEPOffset)) 1579 break; 1580 Offset += GEPOffset; 1581 Ptr = GEP->getPointerOperand(); 1582 if (!Visited.insert(Ptr).second) 1583 break; 1584 } 1585 1586 // See if we can perform a natural GEP here. 1587 Indices.clear(); 1588 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy, 1589 Indices, NamePrefix)) { 1590 // If we have a new natural pointer at the offset, clear out any old 1591 // offset pointer we computed. Unless it is the base pointer or 1592 // a non-instruction, we built a GEP we don't need. Zap it. 1593 if (OffsetPtr && OffsetPtr != OffsetBasePtr) 1594 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) { 1595 assert(I->use_empty() && "Built a GEP with uses some how!"); 1596 I->eraseFromParent(); 1597 } 1598 OffsetPtr = P; 1599 OffsetBasePtr = Ptr; 1600 // If we also found a pointer of the right type, we're done. 1601 if (P->getType() == PointerTy) 1602 return P; 1603 } 1604 1605 // Stash this pointer if we've found an i8*. 1606 if (Ptr->getType()->isIntegerTy(8)) { 1607 Int8Ptr = Ptr; 1608 Int8PtrOffset = Offset; 1609 } 1610 1611 // Peel off a layer of the pointer and update the offset appropriately. 1612 if (Operator::getOpcode(Ptr) == Instruction::BitCast) { 1613 Ptr = cast<Operator>(Ptr)->getOperand(0); 1614 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) { 1615 if (GA->isInterposable()) 1616 break; 1617 Ptr = GA->getAliasee(); 1618 } else { 1619 break; 1620 } 1621 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!"); 1622 } while (Visited.insert(Ptr).second); 1623 1624 if (!OffsetPtr) { 1625 if (!Int8Ptr) { 1626 Int8Ptr = IRB.CreateBitCast( 1627 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()), 1628 NamePrefix + "sroa_raw_cast"); 1629 Int8PtrOffset = Offset; 1630 } 1631 1632 OffsetPtr = Int8PtrOffset == 0 1633 ? Int8Ptr 1634 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr, 1635 IRB.getInt(Int8PtrOffset), 1636 NamePrefix + "sroa_raw_idx"); 1637 } 1638 Ptr = OffsetPtr; 1639 1640 // On the off chance we were targeting i8*, guard the bitcast here. 1641 if (Ptr->getType() != PointerTy) 1642 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast"); 1643 1644 return Ptr; 1645 } 1646 1647 /// Compute the adjusted alignment for a load or store from an offset. 1648 static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset, 1649 const DataLayout &DL) { 1650 unsigned Alignment; 1651 Type *Ty; 1652 if (auto *LI = dyn_cast<LoadInst>(I)) { 1653 Alignment = LI->getAlignment(); 1654 Ty = LI->getType(); 1655 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 1656 Alignment = SI->getAlignment(); 1657 Ty = SI->getValueOperand()->getType(); 1658 } else { 1659 llvm_unreachable("Only loads and stores are allowed!"); 1660 } 1661 1662 if (!Alignment) 1663 Alignment = DL.getABITypeAlignment(Ty); 1664 1665 return MinAlign(Alignment, Offset); 1666 } 1667 1668 /// Test whether we can convert a value from the old to the new type. 1669 /// 1670 /// This predicate should be used to guard calls to convertValue in order to 1671 /// ensure that we only try to convert viable values. The strategy is that we 1672 /// will peel off single element struct and array wrappings to get to an 1673 /// underlying value, and convert that value. 1674 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) { 1675 if (OldTy == NewTy) 1676 return true; 1677 1678 // For integer types, we can't handle any bit-width differences. This would 1679 // break both vector conversions with extension and introduce endianness 1680 // issues when in conjunction with loads and stores. 1681 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) { 1682 assert(cast<IntegerType>(OldTy)->getBitWidth() != 1683 cast<IntegerType>(NewTy)->getBitWidth() && 1684 "We can't have the same bitwidth for different int types"); 1685 return false; 1686 } 1687 1688 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy)) 1689 return false; 1690 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType()) 1691 return false; 1692 1693 // We can convert pointers to integers and vice-versa. Same for vectors 1694 // of pointers and integers. 1695 OldTy = OldTy->getScalarType(); 1696 NewTy = NewTy->getScalarType(); 1697 if (NewTy->isPointerTy() || OldTy->isPointerTy()) { 1698 if (NewTy->isPointerTy() && OldTy->isPointerTy()) { 1699 return cast<PointerType>(NewTy)->getPointerAddressSpace() == 1700 cast<PointerType>(OldTy)->getPointerAddressSpace(); 1701 } 1702 1703 // We can convert integers to integral pointers, but not to non-integral 1704 // pointers. 1705 if (OldTy->isIntegerTy()) 1706 return !DL.isNonIntegralPointerType(NewTy); 1707 1708 // We can convert integral pointers to integers, but non-integral pointers 1709 // need to remain pointers. 1710 if (!DL.isNonIntegralPointerType(OldTy)) 1711 return NewTy->isIntegerTy(); 1712 1713 return false; 1714 } 1715 1716 return true; 1717 } 1718 1719 /// Generic routine to convert an SSA value to a value of a different 1720 /// type. 1721 /// 1722 /// This will try various different casting techniques, such as bitcasts, 1723 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test 1724 /// two types for viability with this routine. 1725 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V, 1726 Type *NewTy) { 1727 Type *OldTy = V->getType(); 1728 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type"); 1729 1730 if (OldTy == NewTy) 1731 return V; 1732 1733 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) && 1734 "Integer types must be the exact same to convert."); 1735 1736 // See if we need inttoptr for this type pair. A cast involving both scalars 1737 // and vectors requires and additional bitcast. 1738 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) { 1739 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8* 1740 if (OldTy->isVectorTy() && !NewTy->isVectorTy()) 1741 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)), 1742 NewTy); 1743 1744 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*> 1745 if (!OldTy->isVectorTy() && NewTy->isVectorTy()) 1746 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)), 1747 NewTy); 1748 1749 return IRB.CreateIntToPtr(V, NewTy); 1750 } 1751 1752 // See if we need ptrtoint for this type pair. A cast involving both scalars 1753 // and vectors requires and additional bitcast. 1754 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) { 1755 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128 1756 if (OldTy->isVectorTy() && !NewTy->isVectorTy()) 1757 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)), 1758 NewTy); 1759 1760 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32> 1761 if (!OldTy->isVectorTy() && NewTy->isVectorTy()) 1762 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)), 1763 NewTy); 1764 1765 return IRB.CreatePtrToInt(V, NewTy); 1766 } 1767 1768 return IRB.CreateBitCast(V, NewTy); 1769 } 1770 1771 /// Test whether the given slice use can be promoted to a vector. 1772 /// 1773 /// This function is called to test each entry in a partition which is slated 1774 /// for a single slice. 1775 static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S, 1776 VectorType *Ty, 1777 uint64_t ElementSize, 1778 const DataLayout &DL) { 1779 // First validate the slice offsets. 1780 uint64_t BeginOffset = 1781 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset(); 1782 uint64_t BeginIndex = BeginOffset / ElementSize; 1783 if (BeginIndex * ElementSize != BeginOffset || 1784 BeginIndex >= Ty->getNumElements()) 1785 return false; 1786 uint64_t EndOffset = 1787 std::min(S.endOffset(), P.endOffset()) - P.beginOffset(); 1788 uint64_t EndIndex = EndOffset / ElementSize; 1789 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements()) 1790 return false; 1791 1792 assert(EndIndex > BeginIndex && "Empty vector!"); 1793 uint64_t NumElements = EndIndex - BeginIndex; 1794 Type *SliceTy = (NumElements == 1) 1795 ? Ty->getElementType() 1796 : VectorType::get(Ty->getElementType(), NumElements); 1797 1798 Type *SplitIntTy = 1799 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8); 1800 1801 Use *U = S.getUse(); 1802 1803 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) { 1804 if (MI->isVolatile()) 1805 return false; 1806 if (!S.isSplittable()) 1807 return false; // Skip any unsplittable intrinsics. 1808 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) { 1809 if (!II->isLifetimeStartOrEnd()) 1810 return false; 1811 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) { 1812 // Disable vector promotion when there are loads or stores of an FCA. 1813 return false; 1814 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 1815 if (LI->isVolatile()) 1816 return false; 1817 Type *LTy = LI->getType(); 1818 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) { 1819 assert(LTy->isIntegerTy()); 1820 LTy = SplitIntTy; 1821 } 1822 if (!canConvertValue(DL, SliceTy, LTy)) 1823 return false; 1824 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 1825 if (SI->isVolatile()) 1826 return false; 1827 Type *STy = SI->getValueOperand()->getType(); 1828 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) { 1829 assert(STy->isIntegerTy()); 1830 STy = SplitIntTy; 1831 } 1832 if (!canConvertValue(DL, STy, SliceTy)) 1833 return false; 1834 } else { 1835 return false; 1836 } 1837 1838 return true; 1839 } 1840 1841 /// Test whether the given alloca partitioning and range of slices can be 1842 /// promoted to a vector. 1843 /// 1844 /// This is a quick test to check whether we can rewrite a particular alloca 1845 /// partition (and its newly formed alloca) into a vector alloca with only 1846 /// whole-vector loads and stores such that it could be promoted to a vector 1847 /// SSA value. We only can ensure this for a limited set of operations, and we 1848 /// don't want to do the rewrites unless we are confident that the result will 1849 /// be promotable, so we have an early test here. 1850 static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) { 1851 // Collect the candidate types for vector-based promotion. Also track whether 1852 // we have different element types. 1853 SmallVector<VectorType *, 4> CandidateTys; 1854 Type *CommonEltTy = nullptr; 1855 bool HaveCommonEltTy = true; 1856 auto CheckCandidateType = [&](Type *Ty) { 1857 if (auto *VTy = dyn_cast<VectorType>(Ty)) { 1858 CandidateTys.push_back(VTy); 1859 if (!CommonEltTy) 1860 CommonEltTy = VTy->getElementType(); 1861 else if (CommonEltTy != VTy->getElementType()) 1862 HaveCommonEltTy = false; 1863 } 1864 }; 1865 // Consider any loads or stores that are the exact size of the slice. 1866 for (const Slice &S : P) 1867 if (S.beginOffset() == P.beginOffset() && 1868 S.endOffset() == P.endOffset()) { 1869 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser())) 1870 CheckCandidateType(LI->getType()); 1871 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) 1872 CheckCandidateType(SI->getValueOperand()->getType()); 1873 } 1874 1875 // If we didn't find a vector type, nothing to do here. 1876 if (CandidateTys.empty()) 1877 return nullptr; 1878 1879 // Remove non-integer vector types if we had multiple common element types. 1880 // FIXME: It'd be nice to replace them with integer vector types, but we can't 1881 // do that until all the backends are known to produce good code for all 1882 // integer vector types. 1883 if (!HaveCommonEltTy) { 1884 CandidateTys.erase( 1885 llvm::remove_if(CandidateTys, 1886 [](VectorType *VTy) { 1887 return !VTy->getElementType()->isIntegerTy(); 1888 }), 1889 CandidateTys.end()); 1890 1891 // If there were no integer vector types, give up. 1892 if (CandidateTys.empty()) 1893 return nullptr; 1894 1895 // Rank the remaining candidate vector types. This is easy because we know 1896 // they're all integer vectors. We sort by ascending number of elements. 1897 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) { 1898 (void)DL; 1899 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) && 1900 "Cannot have vector types of different sizes!"); 1901 assert(RHSTy->getElementType()->isIntegerTy() && 1902 "All non-integer types eliminated!"); 1903 assert(LHSTy->getElementType()->isIntegerTy() && 1904 "All non-integer types eliminated!"); 1905 return RHSTy->getNumElements() < LHSTy->getNumElements(); 1906 }; 1907 llvm::sort(CandidateTys, RankVectorTypes); 1908 CandidateTys.erase( 1909 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes), 1910 CandidateTys.end()); 1911 } else { 1912 // The only way to have the same element type in every vector type is to 1913 // have the same vector type. Check that and remove all but one. 1914 #ifndef NDEBUG 1915 for (VectorType *VTy : CandidateTys) { 1916 assert(VTy->getElementType() == CommonEltTy && 1917 "Unaccounted for element type!"); 1918 assert(VTy == CandidateTys[0] && 1919 "Different vector types with the same element type!"); 1920 } 1921 #endif 1922 CandidateTys.resize(1); 1923 } 1924 1925 // Try each vector type, and return the one which works. 1926 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) { 1927 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType()); 1928 1929 // While the definition of LLVM vectors is bitpacked, we don't support sizes 1930 // that aren't byte sized. 1931 if (ElementSize % 8) 1932 return false; 1933 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 && 1934 "vector size not a multiple of element size?"); 1935 ElementSize /= 8; 1936 1937 for (const Slice &S : P) 1938 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL)) 1939 return false; 1940 1941 for (const Slice *S : P.splitSliceTails()) 1942 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL)) 1943 return false; 1944 1945 return true; 1946 }; 1947 for (VectorType *VTy : CandidateTys) 1948 if (CheckVectorTypeForPromotion(VTy)) 1949 return VTy; 1950 1951 return nullptr; 1952 } 1953 1954 /// Test whether a slice of an alloca is valid for integer widening. 1955 /// 1956 /// This implements the necessary checking for the \c isIntegerWideningViable 1957 /// test below on a single slice of the alloca. 1958 static bool isIntegerWideningViableForSlice(const Slice &S, 1959 uint64_t AllocBeginOffset, 1960 Type *AllocaTy, 1961 const DataLayout &DL, 1962 bool &WholeAllocaOp) { 1963 uint64_t Size = DL.getTypeStoreSize(AllocaTy); 1964 1965 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset; 1966 uint64_t RelEnd = S.endOffset() - AllocBeginOffset; 1967 1968 // We can't reasonably handle cases where the load or store extends past 1969 // the end of the alloca's type and into its padding. 1970 if (RelEnd > Size) 1971 return false; 1972 1973 Use *U = S.getUse(); 1974 1975 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 1976 if (LI->isVolatile()) 1977 return false; 1978 // We can't handle loads that extend past the allocated memory. 1979 if (DL.getTypeStoreSize(LI->getType()) > Size) 1980 return false; 1981 // So far, AllocaSliceRewriter does not support widening split slice tails 1982 // in rewriteIntegerLoad. 1983 if (S.beginOffset() < AllocBeginOffset) 1984 return false; 1985 // Note that we don't count vector loads or stores as whole-alloca 1986 // operations which enable integer widening because we would prefer to use 1987 // vector widening instead. 1988 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size) 1989 WholeAllocaOp = true; 1990 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) { 1991 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy)) 1992 return false; 1993 } else if (RelBegin != 0 || RelEnd != Size || 1994 !canConvertValue(DL, AllocaTy, LI->getType())) { 1995 // Non-integer loads need to be convertible from the alloca type so that 1996 // they are promotable. 1997 return false; 1998 } 1999 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 2000 Type *ValueTy = SI->getValueOperand()->getType(); 2001 if (SI->isVolatile()) 2002 return false; 2003 // We can't handle stores that extend past the allocated memory. 2004 if (DL.getTypeStoreSize(ValueTy) > Size) 2005 return false; 2006 // So far, AllocaSliceRewriter does not support widening split slice tails 2007 // in rewriteIntegerStore. 2008 if (S.beginOffset() < AllocBeginOffset) 2009 return false; 2010 // Note that we don't count vector loads or stores as whole-alloca 2011 // operations which enable integer widening because we would prefer to use 2012 // vector widening instead. 2013 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size) 2014 WholeAllocaOp = true; 2015 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) { 2016 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy)) 2017 return false; 2018 } else if (RelBegin != 0 || RelEnd != Size || 2019 !canConvertValue(DL, ValueTy, AllocaTy)) { 2020 // Non-integer stores need to be convertible to the alloca type so that 2021 // they are promotable. 2022 return false; 2023 } 2024 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) { 2025 if (MI->isVolatile() || !isa<Constant>(MI->getLength())) 2026 return false; 2027 if (!S.isSplittable()) 2028 return false; // Skip any unsplittable intrinsics. 2029 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) { 2030 if (!II->isLifetimeStartOrEnd()) 2031 return false; 2032 } else { 2033 return false; 2034 } 2035 2036 return true; 2037 } 2038 2039 /// Test whether the given alloca partition's integer operations can be 2040 /// widened to promotable ones. 2041 /// 2042 /// This is a quick test to check whether we can rewrite the integer loads and 2043 /// stores to a particular alloca into wider loads and stores and be able to 2044 /// promote the resulting alloca. 2045 static bool isIntegerWideningViable(Partition &P, Type *AllocaTy, 2046 const DataLayout &DL) { 2047 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy); 2048 // Don't create integer types larger than the maximum bitwidth. 2049 if (SizeInBits > IntegerType::MAX_INT_BITS) 2050 return false; 2051 2052 // Don't try to handle allocas with bit-padding. 2053 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy)) 2054 return false; 2055 2056 // We need to ensure that an integer type with the appropriate bitwidth can 2057 // be converted to the alloca type, whatever that is. We don't want to force 2058 // the alloca itself to have an integer type if there is a more suitable one. 2059 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits); 2060 if (!canConvertValue(DL, AllocaTy, IntTy) || 2061 !canConvertValue(DL, IntTy, AllocaTy)) 2062 return false; 2063 2064 // While examining uses, we ensure that the alloca has a covering load or 2065 // store. We don't want to widen the integer operations only to fail to 2066 // promote due to some other unsplittable entry (which we may make splittable 2067 // later). However, if there are only splittable uses, go ahead and assume 2068 // that we cover the alloca. 2069 // FIXME: We shouldn't consider split slices that happen to start in the 2070 // partition here... 2071 bool WholeAllocaOp = 2072 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits); 2073 2074 for (const Slice &S : P) 2075 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL, 2076 WholeAllocaOp)) 2077 return false; 2078 2079 for (const Slice *S : P.splitSliceTails()) 2080 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL, 2081 WholeAllocaOp)) 2082 return false; 2083 2084 return WholeAllocaOp; 2085 } 2086 2087 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V, 2088 IntegerType *Ty, uint64_t Offset, 2089 const Twine &Name) { 2090 LLVM_DEBUG(dbgs() << " start: " << *V << "\n"); 2091 IntegerType *IntTy = cast<IntegerType>(V->getType()); 2092 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) && 2093 "Element extends past full value"); 2094 uint64_t ShAmt = 8 * Offset; 2095 if (DL.isBigEndian()) 2096 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset); 2097 if (ShAmt) { 2098 V = IRB.CreateLShr(V, ShAmt, Name + ".shift"); 2099 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n"); 2100 } 2101 assert(Ty->getBitWidth() <= IntTy->getBitWidth() && 2102 "Cannot extract to a larger integer!"); 2103 if (Ty != IntTy) { 2104 V = IRB.CreateTrunc(V, Ty, Name + ".trunc"); 2105 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n"); 2106 } 2107 return V; 2108 } 2109 2110 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old, 2111 Value *V, uint64_t Offset, const Twine &Name) { 2112 IntegerType *IntTy = cast<IntegerType>(Old->getType()); 2113 IntegerType *Ty = cast<IntegerType>(V->getType()); 2114 assert(Ty->getBitWidth() <= IntTy->getBitWidth() && 2115 "Cannot insert a larger integer!"); 2116 LLVM_DEBUG(dbgs() << " start: " << *V << "\n"); 2117 if (Ty != IntTy) { 2118 V = IRB.CreateZExt(V, IntTy, Name + ".ext"); 2119 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n"); 2120 } 2121 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) && 2122 "Element store outside of alloca store"); 2123 uint64_t ShAmt = 8 * Offset; 2124 if (DL.isBigEndian()) 2125 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset); 2126 if (ShAmt) { 2127 V = IRB.CreateShl(V, ShAmt, Name + ".shift"); 2128 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n"); 2129 } 2130 2131 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) { 2132 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt); 2133 Old = IRB.CreateAnd(Old, Mask, Name + ".mask"); 2134 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n"); 2135 V = IRB.CreateOr(Old, V, Name + ".insert"); 2136 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n"); 2137 } 2138 return V; 2139 } 2140 2141 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, 2142 unsigned EndIndex, const Twine &Name) { 2143 VectorType *VecTy = cast<VectorType>(V->getType()); 2144 unsigned NumElements = EndIndex - BeginIndex; 2145 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2146 2147 if (NumElements == VecTy->getNumElements()) 2148 return V; 2149 2150 if (NumElements == 1) { 2151 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex), 2152 Name + ".extract"); 2153 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n"); 2154 return V; 2155 } 2156 2157 SmallVector<Constant *, 8> Mask; 2158 Mask.reserve(NumElements); 2159 for (unsigned i = BeginIndex; i != EndIndex; ++i) 2160 Mask.push_back(IRB.getInt32(i)); 2161 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), 2162 ConstantVector::get(Mask), Name + ".extract"); 2163 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n"); 2164 return V; 2165 } 2166 2167 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V, 2168 unsigned BeginIndex, const Twine &Name) { 2169 VectorType *VecTy = cast<VectorType>(Old->getType()); 2170 assert(VecTy && "Can only insert a vector into a vector"); 2171 2172 VectorType *Ty = dyn_cast<VectorType>(V->getType()); 2173 if (!Ty) { 2174 // Single element to insert. 2175 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex), 2176 Name + ".insert"); 2177 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n"); 2178 return V; 2179 } 2180 2181 assert(Ty->getNumElements() <= VecTy->getNumElements() && 2182 "Too many elements!"); 2183 if (Ty->getNumElements() == VecTy->getNumElements()) { 2184 assert(V->getType() == VecTy && "Vector type mismatch"); 2185 return V; 2186 } 2187 unsigned EndIndex = BeginIndex + Ty->getNumElements(); 2188 2189 // When inserting a smaller vector into the larger to store, we first 2190 // use a shuffle vector to widen it with undef elements, and then 2191 // a second shuffle vector to select between the loaded vector and the 2192 // incoming vector. 2193 SmallVector<Constant *, 8> Mask; 2194 Mask.reserve(VecTy->getNumElements()); 2195 for (unsigned i = 0; i != VecTy->getNumElements(); ++i) 2196 if (i >= BeginIndex && i < EndIndex) 2197 Mask.push_back(IRB.getInt32(i - BeginIndex)); 2198 else 2199 Mask.push_back(UndefValue::get(IRB.getInt32Ty())); 2200 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), 2201 ConstantVector::get(Mask), Name + ".expand"); 2202 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n"); 2203 2204 Mask.clear(); 2205 for (unsigned i = 0; i != VecTy->getNumElements(); ++i) 2206 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex)); 2207 2208 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend"); 2209 2210 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n"); 2211 return V; 2212 } 2213 2214 /// Visitor to rewrite instructions using p particular slice of an alloca 2215 /// to use a new alloca. 2216 /// 2217 /// Also implements the rewriting to vector-based accesses when the partition 2218 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic 2219 /// lives here. 2220 class llvm::sroa::AllocaSliceRewriter 2221 : public InstVisitor<AllocaSliceRewriter, bool> { 2222 // Befriend the base class so it can delegate to private visit methods. 2223 friend class InstVisitor<AllocaSliceRewriter, bool>; 2224 2225 using Base = InstVisitor<AllocaSliceRewriter, bool>; 2226 2227 const DataLayout &DL; 2228 AllocaSlices &AS; 2229 SROA &Pass; 2230 AllocaInst &OldAI, &NewAI; 2231 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset; 2232 Type *NewAllocaTy; 2233 2234 // This is a convenience and flag variable that will be null unless the new 2235 // alloca's integer operations should be widened to this integer type due to 2236 // passing isIntegerWideningViable above. If it is non-null, the desired 2237 // integer type will be stored here for easy access during rewriting. 2238 IntegerType *IntTy; 2239 2240 // If we are rewriting an alloca partition which can be written as pure 2241 // vector operations, we stash extra information here. When VecTy is 2242 // non-null, we have some strict guarantees about the rewritten alloca: 2243 // - The new alloca is exactly the size of the vector type here. 2244 // - The accesses all either map to the entire vector or to a single 2245 // element. 2246 // - The set of accessing instructions is only one of those handled above 2247 // in isVectorPromotionViable. Generally these are the same access kinds 2248 // which are promotable via mem2reg. 2249 VectorType *VecTy; 2250 Type *ElementTy; 2251 uint64_t ElementSize; 2252 2253 // The original offset of the slice currently being rewritten relative to 2254 // the original alloca. 2255 uint64_t BeginOffset = 0; 2256 uint64_t EndOffset = 0; 2257 2258 // The new offsets of the slice currently being rewritten relative to the 2259 // original alloca. 2260 uint64_t NewBeginOffset, NewEndOffset; 2261 2262 uint64_t SliceSize; 2263 bool IsSplittable = false; 2264 bool IsSplit = false; 2265 Use *OldUse = nullptr; 2266 Instruction *OldPtr = nullptr; 2267 2268 // Track post-rewrite users which are PHI nodes and Selects. 2269 SmallSetVector<PHINode *, 8> &PHIUsers; 2270 SmallSetVector<SelectInst *, 8> &SelectUsers; 2271 2272 // Utility IR builder, whose name prefix is setup for each visited use, and 2273 // the insertion point is set to point to the user. 2274 IRBuilderTy IRB; 2275 2276 public: 2277 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass, 2278 AllocaInst &OldAI, AllocaInst &NewAI, 2279 uint64_t NewAllocaBeginOffset, 2280 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable, 2281 VectorType *PromotableVecTy, 2282 SmallSetVector<PHINode *, 8> &PHIUsers, 2283 SmallSetVector<SelectInst *, 8> &SelectUsers) 2284 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI), 2285 NewAllocaBeginOffset(NewAllocaBeginOffset), 2286 NewAllocaEndOffset(NewAllocaEndOffset), 2287 NewAllocaTy(NewAI.getAllocatedType()), 2288 IntTy(IsIntegerPromotable 2289 ? Type::getIntNTy( 2290 NewAI.getContext(), 2291 DL.getTypeSizeInBits(NewAI.getAllocatedType())) 2292 : nullptr), 2293 VecTy(PromotableVecTy), 2294 ElementTy(VecTy ? VecTy->getElementType() : nullptr), 2295 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0), 2296 PHIUsers(PHIUsers), SelectUsers(SelectUsers), 2297 IRB(NewAI.getContext(), ConstantFolder()) { 2298 if (VecTy) { 2299 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 && 2300 "Only multiple-of-8 sized vector elements are viable"); 2301 ++NumVectorized; 2302 } 2303 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy)); 2304 } 2305 2306 bool visit(AllocaSlices::const_iterator I) { 2307 bool CanSROA = true; 2308 BeginOffset = I->beginOffset(); 2309 EndOffset = I->endOffset(); 2310 IsSplittable = I->isSplittable(); 2311 IsSplit = 2312 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset; 2313 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : "")); 2314 LLVM_DEBUG(AS.printSlice(dbgs(), I, "")); 2315 LLVM_DEBUG(dbgs() << "\n"); 2316 2317 // Compute the intersecting offset range. 2318 assert(BeginOffset < NewAllocaEndOffset); 2319 assert(EndOffset > NewAllocaBeginOffset); 2320 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset); 2321 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset); 2322 2323 SliceSize = NewEndOffset - NewBeginOffset; 2324 2325 OldUse = I->getUse(); 2326 OldPtr = cast<Instruction>(OldUse->get()); 2327 2328 Instruction *OldUserI = cast<Instruction>(OldUse->getUser()); 2329 IRB.SetInsertPoint(OldUserI); 2330 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc()); 2331 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + "."); 2332 2333 CanSROA &= visit(cast<Instruction>(OldUse->getUser())); 2334 if (VecTy || IntTy) 2335 assert(CanSROA); 2336 return CanSROA; 2337 } 2338 2339 private: 2340 // Make sure the other visit overloads are visible. 2341 using Base::visit; 2342 2343 // Every instruction which can end up as a user must have a rewrite rule. 2344 bool visitInstruction(Instruction &I) { 2345 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n"); 2346 llvm_unreachable("No rewrite rule for this instruction!"); 2347 } 2348 2349 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) { 2350 // Note that the offset computation can use BeginOffset or NewBeginOffset 2351 // interchangeably for unsplit slices. 2352 assert(IsSplit || BeginOffset == NewBeginOffset); 2353 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2354 2355 #ifndef NDEBUG 2356 StringRef OldName = OldPtr->getName(); 2357 // Skip through the last '.sroa.' component of the name. 2358 size_t LastSROAPrefix = OldName.rfind(".sroa."); 2359 if (LastSROAPrefix != StringRef::npos) { 2360 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa.")); 2361 // Look for an SROA slice index. 2362 size_t IndexEnd = OldName.find_first_not_of("0123456789"); 2363 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') { 2364 // Strip the index and look for the offset. 2365 OldName = OldName.substr(IndexEnd + 1); 2366 size_t OffsetEnd = OldName.find_first_not_of("0123456789"); 2367 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.') 2368 // Strip the offset. 2369 OldName = OldName.substr(OffsetEnd + 1); 2370 } 2371 } 2372 // Strip any SROA suffixes as well. 2373 OldName = OldName.substr(0, OldName.find(".sroa_")); 2374 #endif 2375 2376 return getAdjustedPtr(IRB, DL, &NewAI, 2377 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset), 2378 PointerTy, 2379 #ifndef NDEBUG 2380 Twine(OldName) + "." 2381 #else 2382 Twine() 2383 #endif 2384 ); 2385 } 2386 2387 /// Compute suitable alignment to access this slice of the *new* 2388 /// alloca. 2389 /// 2390 /// You can optionally pass a type to this routine and if that type's ABI 2391 /// alignment is itself suitable, this will return zero. 2392 unsigned getSliceAlign(Type *Ty = nullptr) { 2393 unsigned NewAIAlign = NewAI.getAlignment(); 2394 if (!NewAIAlign) 2395 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType()); 2396 unsigned Align = 2397 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset); 2398 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align; 2399 } 2400 2401 unsigned getIndex(uint64_t Offset) { 2402 assert(VecTy && "Can only call getIndex when rewriting a vector"); 2403 uint64_t RelOffset = Offset - NewAllocaBeginOffset; 2404 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds"); 2405 uint32_t Index = RelOffset / ElementSize; 2406 assert(Index * ElementSize == RelOffset); 2407 return Index; 2408 } 2409 2410 void deleteIfTriviallyDead(Value *V) { 2411 Instruction *I = cast<Instruction>(V); 2412 if (isInstructionTriviallyDead(I)) 2413 Pass.DeadInsts.insert(I); 2414 } 2415 2416 Value *rewriteVectorizedLoadInst() { 2417 unsigned BeginIndex = getIndex(NewBeginOffset); 2418 unsigned EndIndex = getIndex(NewEndOffset); 2419 assert(EndIndex > BeginIndex && "Empty vector!"); 2420 2421 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load"); 2422 return extractVector(IRB, V, BeginIndex, EndIndex, "vec"); 2423 } 2424 2425 Value *rewriteIntegerLoad(LoadInst &LI) { 2426 assert(IntTy && "We cannot insert an integer to the alloca"); 2427 assert(!LI.isVolatile()); 2428 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load"); 2429 V = convertValue(DL, IRB, V, IntTy); 2430 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); 2431 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2432 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) { 2433 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8); 2434 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract"); 2435 } 2436 // It is possible that the extracted type is not the load type. This 2437 // happens if there is a load past the end of the alloca, and as 2438 // a consequence the slice is narrower but still a candidate for integer 2439 // lowering. To handle this case, we just zero extend the extracted 2440 // integer. 2441 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 && 2442 "Can only handle an extract for an overly wide load"); 2443 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8) 2444 V = IRB.CreateZExt(V, LI.getType()); 2445 return V; 2446 } 2447 2448 bool visitLoadInst(LoadInst &LI) { 2449 LLVM_DEBUG(dbgs() << " original: " << LI << "\n"); 2450 Value *OldOp = LI.getOperand(0); 2451 assert(OldOp == OldPtr); 2452 2453 AAMDNodes AATags; 2454 LI.getAAMetadata(AATags); 2455 2456 unsigned AS = LI.getPointerAddressSpace(); 2457 2458 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8) 2459 : LI.getType(); 2460 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize; 2461 bool IsPtrAdjusted = false; 2462 Value *V; 2463 if (VecTy) { 2464 V = rewriteVectorizedLoadInst(); 2465 } else if (IntTy && LI.getType()->isIntegerTy()) { 2466 V = rewriteIntegerLoad(LI); 2467 } else if (NewBeginOffset == NewAllocaBeginOffset && 2468 NewEndOffset == NewAllocaEndOffset && 2469 (canConvertValue(DL, NewAllocaTy, TargetTy) || 2470 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() && 2471 TargetTy->isIntegerTy()))) { 2472 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), 2473 LI.isVolatile(), LI.getName()); 2474 if (AATags) 2475 NewLI->setAAMetadata(AATags); 2476 if (LI.isVolatile()) 2477 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 2478 2479 // Any !nonnull metadata or !range metadata on the old load is also valid 2480 // on the new load. This is even true in some cases even when the loads 2481 // are different types, for example by mapping !nonnull metadata to 2482 // !range metadata by modeling the null pointer constant converted to the 2483 // integer type. 2484 // FIXME: Add support for range metadata here. Currently the utilities 2485 // for this don't propagate range metadata in trivial cases from one 2486 // integer load to another, don't handle non-addrspace-0 null pointers 2487 // correctly, and don't have any support for mapping ranges as the 2488 // integer type becomes winder or narrower. 2489 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull)) 2490 copyNonnullMetadata(LI, N, *NewLI); 2491 2492 // Try to preserve nonnull metadata 2493 V = NewLI; 2494 2495 // If this is an integer load past the end of the slice (which means the 2496 // bytes outside the slice are undef or this load is dead) just forcibly 2497 // fix the integer size with correct handling of endianness. 2498 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy)) 2499 if (auto *TITy = dyn_cast<IntegerType>(TargetTy)) 2500 if (AITy->getBitWidth() < TITy->getBitWidth()) { 2501 V = IRB.CreateZExt(V, TITy, "load.ext"); 2502 if (DL.isBigEndian()) 2503 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(), 2504 "endian_shift"); 2505 } 2506 } else { 2507 Type *LTy = TargetTy->getPointerTo(AS); 2508 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy), 2509 getSliceAlign(TargetTy), 2510 LI.isVolatile(), LI.getName()); 2511 if (AATags) 2512 NewLI->setAAMetadata(AATags); 2513 if (LI.isVolatile()) 2514 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 2515 2516 V = NewLI; 2517 IsPtrAdjusted = true; 2518 } 2519 V = convertValue(DL, IRB, V, TargetTy); 2520 2521 if (IsSplit) { 2522 assert(!LI.isVolatile()); 2523 assert(LI.getType()->isIntegerTy() && 2524 "Only integer type loads and stores are split"); 2525 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) && 2526 "Split load isn't smaller than original load"); 2527 assert(LI.getType()->getIntegerBitWidth() == 2528 DL.getTypeStoreSizeInBits(LI.getType()) && 2529 "Non-byte-multiple bit width"); 2530 // Move the insertion point just past the load so that we can refer to it. 2531 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI))); 2532 // Create a placeholder value with the same type as LI to use as the 2533 // basis for the new value. This allows us to replace the uses of LI with 2534 // the computed value, and then replace the placeholder with LI, leaving 2535 // LI only used for this computation. 2536 Value *Placeholder = 2537 new LoadInst(UndefValue::get(LI.getType()->getPointerTo(AS))); 2538 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset, 2539 "insert"); 2540 LI.replaceAllUsesWith(V); 2541 Placeholder->replaceAllUsesWith(&LI); 2542 Placeholder->deleteValue(); 2543 } else { 2544 LI.replaceAllUsesWith(V); 2545 } 2546 2547 Pass.DeadInsts.insert(&LI); 2548 deleteIfTriviallyDead(OldOp); 2549 LLVM_DEBUG(dbgs() << " to: " << *V << "\n"); 2550 return !LI.isVolatile() && !IsPtrAdjusted; 2551 } 2552 2553 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp, 2554 AAMDNodes AATags) { 2555 if (V->getType() != VecTy) { 2556 unsigned BeginIndex = getIndex(NewBeginOffset); 2557 unsigned EndIndex = getIndex(NewEndOffset); 2558 assert(EndIndex > BeginIndex && "Empty vector!"); 2559 unsigned NumElements = EndIndex - BeginIndex; 2560 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2561 Type *SliceTy = (NumElements == 1) 2562 ? ElementTy 2563 : VectorType::get(ElementTy, NumElements); 2564 if (V->getType() != SliceTy) 2565 V = convertValue(DL, IRB, V, SliceTy); 2566 2567 // Mix in the existing elements. 2568 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load"); 2569 V = insertVector(IRB, Old, V, BeginIndex, "vec"); 2570 } 2571 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment()); 2572 if (AATags) 2573 Store->setAAMetadata(AATags); 2574 Pass.DeadInsts.insert(&SI); 2575 2576 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 2577 return true; 2578 } 2579 2580 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) { 2581 assert(IntTy && "We cannot extract an integer from the alloca"); 2582 assert(!SI.isVolatile()); 2583 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) { 2584 Value *Old = 2585 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload"); 2586 Old = convertValue(DL, IRB, Old, IntTy); 2587 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); 2588 uint64_t Offset = BeginOffset - NewAllocaBeginOffset; 2589 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert"); 2590 } 2591 V = convertValue(DL, IRB, V, NewAllocaTy); 2592 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment()); 2593 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access, 2594 LLVMContext::MD_access_group}); 2595 if (AATags) 2596 Store->setAAMetadata(AATags); 2597 Pass.DeadInsts.insert(&SI); 2598 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 2599 return true; 2600 } 2601 2602 bool visitStoreInst(StoreInst &SI) { 2603 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 2604 Value *OldOp = SI.getOperand(1); 2605 assert(OldOp == OldPtr); 2606 2607 AAMDNodes AATags; 2608 SI.getAAMetadata(AATags); 2609 2610 Value *V = SI.getValueOperand(); 2611 2612 // Strip all inbounds GEPs and pointer casts to try to dig out any root 2613 // alloca that should be re-examined after promoting this alloca. 2614 if (V->getType()->isPointerTy()) 2615 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets())) 2616 Pass.PostPromotionWorklist.insert(AI); 2617 2618 if (SliceSize < DL.getTypeStoreSize(V->getType())) { 2619 assert(!SI.isVolatile()); 2620 assert(V->getType()->isIntegerTy() && 2621 "Only integer type loads and stores are split"); 2622 assert(V->getType()->getIntegerBitWidth() == 2623 DL.getTypeStoreSizeInBits(V->getType()) && 2624 "Non-byte-multiple bit width"); 2625 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8); 2626 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset, 2627 "extract"); 2628 } 2629 2630 if (VecTy) 2631 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags); 2632 if (IntTy && V->getType()->isIntegerTy()) 2633 return rewriteIntegerStore(V, SI, AATags); 2634 2635 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize; 2636 StoreInst *NewSI; 2637 if (NewBeginOffset == NewAllocaBeginOffset && 2638 NewEndOffset == NewAllocaEndOffset && 2639 (canConvertValue(DL, V->getType(), NewAllocaTy) || 2640 (IsStorePastEnd && NewAllocaTy->isIntegerTy() && 2641 V->getType()->isIntegerTy()))) { 2642 // If this is an integer store past the end of slice (and thus the bytes 2643 // past that point are irrelevant or this is unreachable), truncate the 2644 // value prior to storing. 2645 if (auto *VITy = dyn_cast<IntegerType>(V->getType())) 2646 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy)) 2647 if (VITy->getBitWidth() > AITy->getBitWidth()) { 2648 if (DL.isBigEndian()) 2649 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(), 2650 "endian_shift"); 2651 V = IRB.CreateTrunc(V, AITy, "load.trunc"); 2652 } 2653 2654 V = convertValue(DL, IRB, V, NewAllocaTy); 2655 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(), 2656 SI.isVolatile()); 2657 } else { 2658 unsigned AS = SI.getPointerAddressSpace(); 2659 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS)); 2660 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()), 2661 SI.isVolatile()); 2662 } 2663 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access, 2664 LLVMContext::MD_access_group}); 2665 if (AATags) 2666 NewSI->setAAMetadata(AATags); 2667 if (SI.isVolatile()) 2668 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID()); 2669 Pass.DeadInsts.insert(&SI); 2670 deleteIfTriviallyDead(OldOp); 2671 2672 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n"); 2673 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile(); 2674 } 2675 2676 /// Compute an integer value from splatting an i8 across the given 2677 /// number of bytes. 2678 /// 2679 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't 2680 /// call this routine. 2681 /// FIXME: Heed the advice above. 2682 /// 2683 /// \param V The i8 value to splat. 2684 /// \param Size The number of bytes in the output (assuming i8 is one byte) 2685 Value *getIntegerSplat(Value *V, unsigned Size) { 2686 assert(Size > 0 && "Expected a positive number of bytes."); 2687 IntegerType *VTy = cast<IntegerType>(V->getType()); 2688 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte"); 2689 if (Size == 1) 2690 return V; 2691 2692 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8); 2693 V = IRB.CreateMul( 2694 IRB.CreateZExt(V, SplatIntTy, "zext"), 2695 ConstantExpr::getUDiv( 2696 Constant::getAllOnesValue(SplatIntTy), 2697 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()), 2698 SplatIntTy)), 2699 "isplat"); 2700 return V; 2701 } 2702 2703 /// Compute a vector splat for a given element value. 2704 Value *getVectorSplat(Value *V, unsigned NumElements) { 2705 V = IRB.CreateVectorSplat(NumElements, V, "vsplat"); 2706 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n"); 2707 return V; 2708 } 2709 2710 bool visitMemSetInst(MemSetInst &II) { 2711 LLVM_DEBUG(dbgs() << " original: " << II << "\n"); 2712 assert(II.getRawDest() == OldPtr); 2713 2714 AAMDNodes AATags; 2715 II.getAAMetadata(AATags); 2716 2717 // If the memset has a variable size, it cannot be split, just adjust the 2718 // pointer to the new alloca. 2719 if (!isa<Constant>(II.getLength())) { 2720 assert(!IsSplit); 2721 assert(NewBeginOffset == BeginOffset); 2722 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType())); 2723 II.setDestAlignment(getSliceAlign()); 2724 2725 deleteIfTriviallyDead(OldPtr); 2726 return false; 2727 } 2728 2729 // Record this instruction for deletion. 2730 Pass.DeadInsts.insert(&II); 2731 2732 Type *AllocaTy = NewAI.getAllocatedType(); 2733 Type *ScalarTy = AllocaTy->getScalarType(); 2734 2735 // If this doesn't map cleanly onto the alloca type, and that type isn't 2736 // a single value type, just emit a memset. 2737 if (!VecTy && !IntTy && 2738 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset || 2739 SliceSize != DL.getTypeStoreSize(AllocaTy) || 2740 !AllocaTy->isSingleValueType() || 2741 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) || 2742 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) { 2743 Type *SizeTy = II.getLength()->getType(); 2744 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset); 2745 CallInst *New = IRB.CreateMemSet( 2746 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size, 2747 getSliceAlign(), II.isVolatile()); 2748 if (AATags) 2749 New->setAAMetadata(AATags); 2750 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 2751 return false; 2752 } 2753 2754 // If we can represent this as a simple value, we have to build the actual 2755 // value to store, which requires expanding the byte present in memset to 2756 // a sensible representation for the alloca type. This is essentially 2757 // splatting the byte to a sufficiently wide integer, splatting it across 2758 // any desired vector width, and bitcasting to the final type. 2759 Value *V; 2760 2761 if (VecTy) { 2762 // If this is a memset of a vectorized alloca, insert it. 2763 assert(ElementTy == ScalarTy); 2764 2765 unsigned BeginIndex = getIndex(NewBeginOffset); 2766 unsigned EndIndex = getIndex(NewEndOffset); 2767 assert(EndIndex > BeginIndex && "Empty vector!"); 2768 unsigned NumElements = EndIndex - BeginIndex; 2769 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2770 2771 Value *Splat = 2772 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8); 2773 Splat = convertValue(DL, IRB, Splat, ElementTy); 2774 if (NumElements > 1) 2775 Splat = getVectorSplat(Splat, NumElements); 2776 2777 Value *Old = 2778 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload"); 2779 V = insertVector(IRB, Old, Splat, BeginIndex, "vec"); 2780 } else if (IntTy) { 2781 // If this is a memset on an alloca where we can widen stores, insert the 2782 // set integer. 2783 assert(!II.isVolatile()); 2784 2785 uint64_t Size = NewEndOffset - NewBeginOffset; 2786 V = getIntegerSplat(II.getValue(), Size); 2787 2788 if (IntTy && (BeginOffset != NewAllocaBeginOffset || 2789 EndOffset != NewAllocaBeginOffset)) { 2790 Value *Old = 2791 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload"); 2792 Old = convertValue(DL, IRB, Old, IntTy); 2793 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2794 V = insertInteger(DL, IRB, Old, V, Offset, "insert"); 2795 } else { 2796 assert(V->getType() == IntTy && 2797 "Wrong type for an alloca wide integer!"); 2798 } 2799 V = convertValue(DL, IRB, V, AllocaTy); 2800 } else { 2801 // Established these invariants above. 2802 assert(NewBeginOffset == NewAllocaBeginOffset); 2803 assert(NewEndOffset == NewAllocaEndOffset); 2804 2805 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8); 2806 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy)) 2807 V = getVectorSplat(V, AllocaVecTy->getNumElements()); 2808 2809 V = convertValue(DL, IRB, V, AllocaTy); 2810 } 2811 2812 StoreInst *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(), 2813 II.isVolatile()); 2814 if (AATags) 2815 New->setAAMetadata(AATags); 2816 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 2817 return !II.isVolatile(); 2818 } 2819 2820 bool visitMemTransferInst(MemTransferInst &II) { 2821 // Rewriting of memory transfer instructions can be a bit tricky. We break 2822 // them into two categories: split intrinsics and unsplit intrinsics. 2823 2824 LLVM_DEBUG(dbgs() << " original: " << II << "\n"); 2825 2826 AAMDNodes AATags; 2827 II.getAAMetadata(AATags); 2828 2829 bool IsDest = &II.getRawDestUse() == OldUse; 2830 assert((IsDest && II.getRawDest() == OldPtr) || 2831 (!IsDest && II.getRawSource() == OldPtr)); 2832 2833 unsigned SliceAlign = getSliceAlign(); 2834 2835 // For unsplit intrinsics, we simply modify the source and destination 2836 // pointers in place. This isn't just an optimization, it is a matter of 2837 // correctness. With unsplit intrinsics we may be dealing with transfers 2838 // within a single alloca before SROA ran, or with transfers that have 2839 // a variable length. We may also be dealing with memmove instead of 2840 // memcpy, and so simply updating the pointers is the necessary for us to 2841 // update both source and dest of a single call. 2842 if (!IsSplittable) { 2843 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2844 if (IsDest) { 2845 II.setDest(AdjustedPtr); 2846 II.setDestAlignment(SliceAlign); 2847 } 2848 else { 2849 II.setSource(AdjustedPtr); 2850 II.setSourceAlignment(SliceAlign); 2851 } 2852 2853 LLVM_DEBUG(dbgs() << " to: " << II << "\n"); 2854 deleteIfTriviallyDead(OldPtr); 2855 return false; 2856 } 2857 // For split transfer intrinsics we have an incredibly useful assurance: 2858 // the source and destination do not reside within the same alloca, and at 2859 // least one of them does not escape. This means that we can replace 2860 // memmove with memcpy, and we don't need to worry about all manner of 2861 // downsides to splitting and transforming the operations. 2862 2863 // If this doesn't map cleanly onto the alloca type, and that type isn't 2864 // a single value type, just emit a memcpy. 2865 bool EmitMemCpy = 2866 !VecTy && !IntTy && 2867 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset || 2868 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) || 2869 !NewAI.getAllocatedType()->isSingleValueType()); 2870 2871 // If we're just going to emit a memcpy, the alloca hasn't changed, and the 2872 // size hasn't been shrunk based on analysis of the viable range, this is 2873 // a no-op. 2874 if (EmitMemCpy && &OldAI == &NewAI) { 2875 // Ensure the start lines up. 2876 assert(NewBeginOffset == BeginOffset); 2877 2878 // Rewrite the size as needed. 2879 if (NewEndOffset != EndOffset) 2880 II.setLength(ConstantInt::get(II.getLength()->getType(), 2881 NewEndOffset - NewBeginOffset)); 2882 return false; 2883 } 2884 // Record this instruction for deletion. 2885 Pass.DeadInsts.insert(&II); 2886 2887 // Strip all inbounds GEPs and pointer casts to try to dig out any root 2888 // alloca that should be re-examined after rewriting this instruction. 2889 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest(); 2890 if (AllocaInst *AI = 2891 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) { 2892 assert(AI != &OldAI && AI != &NewAI && 2893 "Splittable transfers cannot reach the same alloca on both ends."); 2894 Pass.Worklist.insert(AI); 2895 } 2896 2897 Type *OtherPtrTy = OtherPtr->getType(); 2898 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace(); 2899 2900 // Compute the relative offset for the other pointer within the transfer. 2901 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS); 2902 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset); 2903 unsigned OtherAlign = 2904 IsDest ? II.getSourceAlignment() : II.getDestAlignment(); 2905 OtherAlign = MinAlign(OtherAlign ? OtherAlign : 1, 2906 OtherOffset.zextOrTrunc(64).getZExtValue()); 2907 2908 if (EmitMemCpy) { 2909 // Compute the other pointer, folding as much as possible to produce 2910 // a single, simple GEP in most cases. 2911 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy, 2912 OtherPtr->getName() + "."); 2913 2914 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2915 Type *SizeTy = II.getLength()->getType(); 2916 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset); 2917 2918 Value *DestPtr, *SrcPtr; 2919 unsigned DestAlign, SrcAlign; 2920 // Note: IsDest is true iff we're copying into the new alloca slice 2921 if (IsDest) { 2922 DestPtr = OurPtr; 2923 DestAlign = SliceAlign; 2924 SrcPtr = OtherPtr; 2925 SrcAlign = OtherAlign; 2926 } else { 2927 DestPtr = OtherPtr; 2928 DestAlign = OtherAlign; 2929 SrcPtr = OurPtr; 2930 SrcAlign = SliceAlign; 2931 } 2932 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign, 2933 Size, II.isVolatile()); 2934 if (AATags) 2935 New->setAAMetadata(AATags); 2936 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 2937 return false; 2938 } 2939 2940 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset && 2941 NewEndOffset == NewAllocaEndOffset; 2942 uint64_t Size = NewEndOffset - NewBeginOffset; 2943 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0; 2944 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0; 2945 unsigned NumElements = EndIndex - BeginIndex; 2946 IntegerType *SubIntTy = 2947 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr; 2948 2949 // Reset the other pointer type to match the register type we're going to 2950 // use, but using the address space of the original other pointer. 2951 if (VecTy && !IsWholeAlloca) { 2952 if (NumElements == 1) 2953 OtherPtrTy = VecTy->getElementType(); 2954 else 2955 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements); 2956 2957 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS); 2958 } else if (IntTy && !IsWholeAlloca) { 2959 OtherPtrTy = SubIntTy->getPointerTo(OtherAS); 2960 } else { 2961 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS); 2962 } 2963 2964 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy, 2965 OtherPtr->getName() + "."); 2966 unsigned SrcAlign = OtherAlign; 2967 Value *DstPtr = &NewAI; 2968 unsigned DstAlign = SliceAlign; 2969 if (!IsDest) { 2970 std::swap(SrcPtr, DstPtr); 2971 std::swap(SrcAlign, DstAlign); 2972 } 2973 2974 Value *Src; 2975 if (VecTy && !IsWholeAlloca && !IsDest) { 2976 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load"); 2977 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec"); 2978 } else if (IntTy && !IsWholeAlloca && !IsDest) { 2979 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load"); 2980 Src = convertValue(DL, IRB, Src, IntTy); 2981 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2982 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract"); 2983 } else { 2984 LoadInst *Load = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), 2985 "copyload"); 2986 if (AATags) 2987 Load->setAAMetadata(AATags); 2988 Src = Load; 2989 } 2990 2991 if (VecTy && !IsWholeAlloca && IsDest) { 2992 Value *Old = 2993 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload"); 2994 Src = insertVector(IRB, Old, Src, BeginIndex, "vec"); 2995 } else if (IntTy && !IsWholeAlloca && IsDest) { 2996 Value *Old = 2997 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload"); 2998 Old = convertValue(DL, IRB, Old, IntTy); 2999 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 3000 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert"); 3001 Src = convertValue(DL, IRB, Src, NewAllocaTy); 3002 } 3003 3004 StoreInst *Store = cast<StoreInst>( 3005 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile())); 3006 if (AATags) 3007 Store->setAAMetadata(AATags); 3008 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 3009 return !II.isVolatile(); 3010 } 3011 3012 bool visitIntrinsicInst(IntrinsicInst &II) { 3013 assert(II.isLifetimeStartOrEnd()); 3014 LLVM_DEBUG(dbgs() << " original: " << II << "\n"); 3015 assert(II.getArgOperand(1) == OldPtr); 3016 3017 // Record this instruction for deletion. 3018 Pass.DeadInsts.insert(&II); 3019 3020 // Lifetime intrinsics are only promotable if they cover the whole alloca. 3021 // Therefore, we drop lifetime intrinsics which don't cover the whole 3022 // alloca. 3023 // (In theory, intrinsics which partially cover an alloca could be 3024 // promoted, but PromoteMemToReg doesn't handle that case.) 3025 // FIXME: Check whether the alloca is promotable before dropping the 3026 // lifetime intrinsics? 3027 if (NewBeginOffset != NewAllocaBeginOffset || 3028 NewEndOffset != NewAllocaEndOffset) 3029 return true; 3030 3031 ConstantInt *Size = 3032 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()), 3033 NewEndOffset - NewBeginOffset); 3034 // Lifetime intrinsics always expect an i8* so directly get such a pointer 3035 // for the new alloca slice. 3036 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace()); 3037 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy); 3038 Value *New; 3039 if (II.getIntrinsicID() == Intrinsic::lifetime_start) 3040 New = IRB.CreateLifetimeStart(Ptr, Size); 3041 else 3042 New = IRB.CreateLifetimeEnd(Ptr, Size); 3043 3044 (void)New; 3045 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 3046 3047 return true; 3048 } 3049 3050 void fixLoadStoreAlign(Instruction &Root) { 3051 // This algorithm implements the same visitor loop as 3052 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load 3053 // or store found. 3054 SmallPtrSet<Instruction *, 4> Visited; 3055 SmallVector<Instruction *, 4> Uses; 3056 Visited.insert(&Root); 3057 Uses.push_back(&Root); 3058 do { 3059 Instruction *I = Uses.pop_back_val(); 3060 3061 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 3062 unsigned LoadAlign = LI->getAlignment(); 3063 if (!LoadAlign) 3064 LoadAlign = DL.getABITypeAlignment(LI->getType()); 3065 LI->setAlignment(std::min(LoadAlign, getSliceAlign())); 3066 continue; 3067 } 3068 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 3069 unsigned StoreAlign = SI->getAlignment(); 3070 if (!StoreAlign) { 3071 Value *Op = SI->getOperand(0); 3072 StoreAlign = DL.getABITypeAlignment(Op->getType()); 3073 } 3074 SI->setAlignment(std::min(StoreAlign, getSliceAlign())); 3075 continue; 3076 } 3077 3078 assert(isa<BitCastInst>(I) || isa<PHINode>(I) || 3079 isa<SelectInst>(I) || isa<GetElementPtrInst>(I)); 3080 for (User *U : I->users()) 3081 if (Visited.insert(cast<Instruction>(U)).second) 3082 Uses.push_back(cast<Instruction>(U)); 3083 } while (!Uses.empty()); 3084 } 3085 3086 bool visitPHINode(PHINode &PN) { 3087 LLVM_DEBUG(dbgs() << " original: " << PN << "\n"); 3088 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable"); 3089 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable"); 3090 3091 // We would like to compute a new pointer in only one place, but have it be 3092 // as local as possible to the PHI. To do that, we re-use the location of 3093 // the old pointer, which necessarily must be in the right position to 3094 // dominate the PHI. 3095 IRBuilderTy PtrBuilder(IRB); 3096 if (isa<PHINode>(OldPtr)) 3097 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt()); 3098 else 3099 PtrBuilder.SetInsertPoint(OldPtr); 3100 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc()); 3101 3102 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType()); 3103 // Replace the operands which were using the old pointer. 3104 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr); 3105 3106 LLVM_DEBUG(dbgs() << " to: " << PN << "\n"); 3107 deleteIfTriviallyDead(OldPtr); 3108 3109 // Fix the alignment of any loads or stores using this PHI node. 3110 fixLoadStoreAlign(PN); 3111 3112 // PHIs can't be promoted on their own, but often can be speculated. We 3113 // check the speculation outside of the rewriter so that we see the 3114 // fully-rewritten alloca. 3115 PHIUsers.insert(&PN); 3116 return true; 3117 } 3118 3119 bool visitSelectInst(SelectInst &SI) { 3120 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 3121 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) && 3122 "Pointer isn't an operand!"); 3123 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable"); 3124 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable"); 3125 3126 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 3127 // Replace the operands which were using the old pointer. 3128 if (SI.getOperand(1) == OldPtr) 3129 SI.setOperand(1, NewPtr); 3130 if (SI.getOperand(2) == OldPtr) 3131 SI.setOperand(2, NewPtr); 3132 3133 LLVM_DEBUG(dbgs() << " to: " << SI << "\n"); 3134 deleteIfTriviallyDead(OldPtr); 3135 3136 // Fix the alignment of any loads or stores using this select. 3137 fixLoadStoreAlign(SI); 3138 3139 // Selects can't be promoted on their own, but often can be speculated. We 3140 // check the speculation outside of the rewriter so that we see the 3141 // fully-rewritten alloca. 3142 SelectUsers.insert(&SI); 3143 return true; 3144 } 3145 }; 3146 3147 namespace { 3148 3149 /// Visitor to rewrite aggregate loads and stores as scalar. 3150 /// 3151 /// This pass aggressively rewrites all aggregate loads and stores on 3152 /// a particular pointer (or any pointer derived from it which we can identify) 3153 /// with scalar loads and stores. 3154 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> { 3155 // Befriend the base class so it can delegate to private visit methods. 3156 friend class InstVisitor<AggLoadStoreRewriter, bool>; 3157 3158 /// Queue of pointer uses to analyze and potentially rewrite. 3159 SmallVector<Use *, 8> Queue; 3160 3161 /// Set to prevent us from cycling with phi nodes and loops. 3162 SmallPtrSet<User *, 8> Visited; 3163 3164 /// The current pointer use being rewritten. This is used to dig up the used 3165 /// value (as opposed to the user). 3166 Use *U; 3167 3168 /// Used to calculate offsets, and hence alignment, of subobjects. 3169 const DataLayout &DL; 3170 3171 public: 3172 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {} 3173 3174 /// Rewrite loads and stores through a pointer and all pointers derived from 3175 /// it. 3176 bool rewrite(Instruction &I) { 3177 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n"); 3178 enqueueUsers(I); 3179 bool Changed = false; 3180 while (!Queue.empty()) { 3181 U = Queue.pop_back_val(); 3182 Changed |= visit(cast<Instruction>(U->getUser())); 3183 } 3184 return Changed; 3185 } 3186 3187 private: 3188 /// Enqueue all the users of the given instruction for further processing. 3189 /// This uses a set to de-duplicate users. 3190 void enqueueUsers(Instruction &I) { 3191 for (Use &U : I.uses()) 3192 if (Visited.insert(U.getUser()).second) 3193 Queue.push_back(&U); 3194 } 3195 3196 // Conservative default is to not rewrite anything. 3197 bool visitInstruction(Instruction &I) { return false; } 3198 3199 /// Generic recursive split emission class. 3200 template <typename Derived> class OpSplitter { 3201 protected: 3202 /// The builder used to form new instructions. 3203 IRBuilderTy IRB; 3204 3205 /// The indices which to be used with insert- or extractvalue to select the 3206 /// appropriate value within the aggregate. 3207 SmallVector<unsigned, 4> Indices; 3208 3209 /// The indices to a GEP instruction which will move Ptr to the correct slot 3210 /// within the aggregate. 3211 SmallVector<Value *, 4> GEPIndices; 3212 3213 /// The base pointer of the original op, used as a base for GEPing the 3214 /// split operations. 3215 Value *Ptr; 3216 3217 /// The base pointee type being GEPed into. 3218 Type *BaseTy; 3219 3220 /// Known alignment of the base pointer. 3221 unsigned BaseAlign; 3222 3223 /// To calculate offset of each component so we can correctly deduce 3224 /// alignments. 3225 const DataLayout &DL; 3226 3227 /// Initialize the splitter with an insertion point, Ptr and start with a 3228 /// single zero GEP index. 3229 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy, 3230 unsigned BaseAlign, const DataLayout &DL) 3231 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), 3232 BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {} 3233 3234 public: 3235 /// Generic recursive split emission routine. 3236 /// 3237 /// This method recursively splits an aggregate op (load or store) into 3238 /// scalar or vector ops. It splits recursively until it hits a single value 3239 /// and emits that single value operation via the template argument. 3240 /// 3241 /// The logic of this routine relies on GEPs and insertvalue and 3242 /// extractvalue all operating with the same fundamental index list, merely 3243 /// formatted differently (GEPs need actual values). 3244 /// 3245 /// \param Ty The type being split recursively into smaller ops. 3246 /// \param Agg The aggregate value being built up or stored, depending on 3247 /// whether this is splitting a load or a store respectively. 3248 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) { 3249 if (Ty->isSingleValueType()) { 3250 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices); 3251 return static_cast<Derived *>(this)->emitFunc( 3252 Ty, Agg, MinAlign(BaseAlign, Offset), Name); 3253 } 3254 3255 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 3256 unsigned OldSize = Indices.size(); 3257 (void)OldSize; 3258 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size; 3259 ++Idx) { 3260 assert(Indices.size() == OldSize && "Did not return to the old size"); 3261 Indices.push_back(Idx); 3262 GEPIndices.push_back(IRB.getInt32(Idx)); 3263 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx)); 3264 GEPIndices.pop_back(); 3265 Indices.pop_back(); 3266 } 3267 return; 3268 } 3269 3270 if (StructType *STy = dyn_cast<StructType>(Ty)) { 3271 unsigned OldSize = Indices.size(); 3272 (void)OldSize; 3273 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size; 3274 ++Idx) { 3275 assert(Indices.size() == OldSize && "Did not return to the old size"); 3276 Indices.push_back(Idx); 3277 GEPIndices.push_back(IRB.getInt32(Idx)); 3278 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx)); 3279 GEPIndices.pop_back(); 3280 Indices.pop_back(); 3281 } 3282 return; 3283 } 3284 3285 llvm_unreachable("Only arrays and structs are aggregate loadable types"); 3286 } 3287 }; 3288 3289 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> { 3290 AAMDNodes AATags; 3291 3292 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy, 3293 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL) 3294 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, 3295 DL), AATags(AATags) {} 3296 3297 /// Emit a leaf load of a single value. This is called at the leaves of the 3298 /// recursive emission to actually load values. 3299 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) { 3300 assert(Ty->isSingleValueType()); 3301 // Load the single value and insert it using the indices. 3302 Value *GEP = 3303 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep"); 3304 LoadInst *Load = IRB.CreateAlignedLoad(GEP, Align, Name + ".load"); 3305 if (AATags) 3306 Load->setAAMetadata(AATags); 3307 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert"); 3308 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n"); 3309 } 3310 }; 3311 3312 bool visitLoadInst(LoadInst &LI) { 3313 assert(LI.getPointerOperand() == *U); 3314 if (!LI.isSimple() || LI.getType()->isSingleValueType()) 3315 return false; 3316 3317 // We have an aggregate being loaded, split it apart. 3318 LLVM_DEBUG(dbgs() << " original: " << LI << "\n"); 3319 AAMDNodes AATags; 3320 LI.getAAMetadata(AATags); 3321 LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags, 3322 getAdjustedAlignment(&LI, 0, DL), DL); 3323 Value *V = UndefValue::get(LI.getType()); 3324 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca"); 3325 LI.replaceAllUsesWith(V); 3326 LI.eraseFromParent(); 3327 return true; 3328 } 3329 3330 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> { 3331 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy, 3332 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL) 3333 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, 3334 DL), 3335 AATags(AATags) {} 3336 AAMDNodes AATags; 3337 /// Emit a leaf store of a single value. This is called at the leaves of the 3338 /// recursive emission to actually produce stores. 3339 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) { 3340 assert(Ty->isSingleValueType()); 3341 // Extract the single value and store it using the indices. 3342 // 3343 // The gep and extractvalue values are factored out of the CreateStore 3344 // call to make the output independent of the argument evaluation order. 3345 Value *ExtractValue = 3346 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"); 3347 Value *InBoundsGEP = 3348 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep"); 3349 StoreInst *Store = 3350 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Align); 3351 if (AATags) 3352 Store->setAAMetadata(AATags); 3353 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 3354 } 3355 }; 3356 3357 bool visitStoreInst(StoreInst &SI) { 3358 if (!SI.isSimple() || SI.getPointerOperand() != *U) 3359 return false; 3360 Value *V = SI.getValueOperand(); 3361 if (V->getType()->isSingleValueType()) 3362 return false; 3363 3364 // We have an aggregate being stored, split it apart. 3365 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 3366 AAMDNodes AATags; 3367 SI.getAAMetadata(AATags); 3368 StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags, 3369 getAdjustedAlignment(&SI, 0, DL), DL); 3370 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca"); 3371 SI.eraseFromParent(); 3372 return true; 3373 } 3374 3375 bool visitBitCastInst(BitCastInst &BC) { 3376 enqueueUsers(BC); 3377 return false; 3378 } 3379 3380 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) { 3381 enqueueUsers(GEPI); 3382 return false; 3383 } 3384 3385 bool visitPHINode(PHINode &PN) { 3386 enqueueUsers(PN); 3387 return false; 3388 } 3389 3390 bool visitSelectInst(SelectInst &SI) { 3391 enqueueUsers(SI); 3392 return false; 3393 } 3394 }; 3395 3396 } // end anonymous namespace 3397 3398 /// Strip aggregate type wrapping. 3399 /// 3400 /// This removes no-op aggregate types wrapping an underlying type. It will 3401 /// strip as many layers of types as it can without changing either the type 3402 /// size or the allocated size. 3403 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) { 3404 if (Ty->isSingleValueType()) 3405 return Ty; 3406 3407 uint64_t AllocSize = DL.getTypeAllocSize(Ty); 3408 uint64_t TypeSize = DL.getTypeSizeInBits(Ty); 3409 3410 Type *InnerTy; 3411 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) { 3412 InnerTy = ArrTy->getElementType(); 3413 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 3414 const StructLayout *SL = DL.getStructLayout(STy); 3415 unsigned Index = SL->getElementContainingOffset(0); 3416 InnerTy = STy->getElementType(Index); 3417 } else { 3418 return Ty; 3419 } 3420 3421 if (AllocSize > DL.getTypeAllocSize(InnerTy) || 3422 TypeSize > DL.getTypeSizeInBits(InnerTy)) 3423 return Ty; 3424 3425 return stripAggregateTypeWrapping(DL, InnerTy); 3426 } 3427 3428 /// Try to find a partition of the aggregate type passed in for a given 3429 /// offset and size. 3430 /// 3431 /// This recurses through the aggregate type and tries to compute a subtype 3432 /// based on the offset and size. When the offset and size span a sub-section 3433 /// of an array, it will even compute a new array type for that sub-section, 3434 /// and the same for structs. 3435 /// 3436 /// Note that this routine is very strict and tries to find a partition of the 3437 /// type which produces the *exact* right offset and size. It is not forgiving 3438 /// when the size or offset cause either end of type-based partition to be off. 3439 /// Also, this is a best-effort routine. It is reasonable to give up and not 3440 /// return a type if necessary. 3441 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset, 3442 uint64_t Size) { 3443 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size) 3444 return stripAggregateTypeWrapping(DL, Ty); 3445 if (Offset > DL.getTypeAllocSize(Ty) || 3446 (DL.getTypeAllocSize(Ty) - Offset) < Size) 3447 return nullptr; 3448 3449 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) { 3450 Type *ElementTy = SeqTy->getElementType(); 3451 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy); 3452 uint64_t NumSkippedElements = Offset / ElementSize; 3453 if (NumSkippedElements >= SeqTy->getNumElements()) 3454 return nullptr; 3455 Offset -= NumSkippedElements * ElementSize; 3456 3457 // First check if we need to recurse. 3458 if (Offset > 0 || Size < ElementSize) { 3459 // Bail if the partition ends in a different array element. 3460 if ((Offset + Size) > ElementSize) 3461 return nullptr; 3462 // Recurse through the element type trying to peel off offset bytes. 3463 return getTypePartition(DL, ElementTy, Offset, Size); 3464 } 3465 assert(Offset == 0); 3466 3467 if (Size == ElementSize) 3468 return stripAggregateTypeWrapping(DL, ElementTy); 3469 assert(Size > ElementSize); 3470 uint64_t NumElements = Size / ElementSize; 3471 if (NumElements * ElementSize != Size) 3472 return nullptr; 3473 return ArrayType::get(ElementTy, NumElements); 3474 } 3475 3476 StructType *STy = dyn_cast<StructType>(Ty); 3477 if (!STy) 3478 return nullptr; 3479 3480 const StructLayout *SL = DL.getStructLayout(STy); 3481 if (Offset >= SL->getSizeInBytes()) 3482 return nullptr; 3483 uint64_t EndOffset = Offset + Size; 3484 if (EndOffset > SL->getSizeInBytes()) 3485 return nullptr; 3486 3487 unsigned Index = SL->getElementContainingOffset(Offset); 3488 Offset -= SL->getElementOffset(Index); 3489 3490 Type *ElementTy = STy->getElementType(Index); 3491 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy); 3492 if (Offset >= ElementSize) 3493 return nullptr; // The offset points into alignment padding. 3494 3495 // See if any partition must be contained by the element. 3496 if (Offset > 0 || Size < ElementSize) { 3497 if ((Offset + Size) > ElementSize) 3498 return nullptr; 3499 return getTypePartition(DL, ElementTy, Offset, Size); 3500 } 3501 assert(Offset == 0); 3502 3503 if (Size == ElementSize) 3504 return stripAggregateTypeWrapping(DL, ElementTy); 3505 3506 StructType::element_iterator EI = STy->element_begin() + Index, 3507 EE = STy->element_end(); 3508 if (EndOffset < SL->getSizeInBytes()) { 3509 unsigned EndIndex = SL->getElementContainingOffset(EndOffset); 3510 if (Index == EndIndex) 3511 return nullptr; // Within a single element and its padding. 3512 3513 // Don't try to form "natural" types if the elements don't line up with the 3514 // expected size. 3515 // FIXME: We could potentially recurse down through the last element in the 3516 // sub-struct to find a natural end point. 3517 if (SL->getElementOffset(EndIndex) != EndOffset) 3518 return nullptr; 3519 3520 assert(Index < EndIndex); 3521 EE = STy->element_begin() + EndIndex; 3522 } 3523 3524 // Try to build up a sub-structure. 3525 StructType *SubTy = 3526 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked()); 3527 const StructLayout *SubSL = DL.getStructLayout(SubTy); 3528 if (Size != SubSL->getSizeInBytes()) 3529 return nullptr; // The sub-struct doesn't have quite the size needed. 3530 3531 return SubTy; 3532 } 3533 3534 /// Pre-split loads and stores to simplify rewriting. 3535 /// 3536 /// We want to break up the splittable load+store pairs as much as 3537 /// possible. This is important to do as a preprocessing step, as once we 3538 /// start rewriting the accesses to partitions of the alloca we lose the 3539 /// necessary information to correctly split apart paired loads and stores 3540 /// which both point into this alloca. The case to consider is something like 3541 /// the following: 3542 /// 3543 /// %a = alloca [12 x i8] 3544 /// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0 3545 /// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4 3546 /// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8 3547 /// %iptr1 = bitcast i8* %gep1 to i64* 3548 /// %iptr2 = bitcast i8* %gep2 to i64* 3549 /// %fptr1 = bitcast i8* %gep1 to float* 3550 /// %fptr2 = bitcast i8* %gep2 to float* 3551 /// %fptr3 = bitcast i8* %gep3 to float* 3552 /// store float 0.0, float* %fptr1 3553 /// store float 1.0, float* %fptr2 3554 /// %v = load i64* %iptr1 3555 /// store i64 %v, i64* %iptr2 3556 /// %f1 = load float* %fptr2 3557 /// %f2 = load float* %fptr3 3558 /// 3559 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and 3560 /// promote everything so we recover the 2 SSA values that should have been 3561 /// there all along. 3562 /// 3563 /// \returns true if any changes are made. 3564 bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) { 3565 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n"); 3566 3567 // Track the loads and stores which are candidates for pre-splitting here, in 3568 // the order they first appear during the partition scan. These give stable 3569 // iteration order and a basis for tracking which loads and stores we 3570 // actually split. 3571 SmallVector<LoadInst *, 4> Loads; 3572 SmallVector<StoreInst *, 4> Stores; 3573 3574 // We need to accumulate the splits required of each load or store where we 3575 // can find them via a direct lookup. This is important to cross-check loads 3576 // and stores against each other. We also track the slice so that we can kill 3577 // all the slices that end up split. 3578 struct SplitOffsets { 3579 Slice *S; 3580 std::vector<uint64_t> Splits; 3581 }; 3582 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap; 3583 3584 // Track loads out of this alloca which cannot, for any reason, be pre-split. 3585 // This is important as we also cannot pre-split stores of those loads! 3586 // FIXME: This is all pretty gross. It means that we can be more aggressive 3587 // in pre-splitting when the load feeding the store happens to come from 3588 // a separate alloca. Put another way, the effectiveness of SROA would be 3589 // decreased by a frontend which just concatenated all of its local allocas 3590 // into one big flat alloca. But defeating such patterns is exactly the job 3591 // SROA is tasked with! Sadly, to not have this discrepancy we would have 3592 // change store pre-splitting to actually force pre-splitting of the load 3593 // that feeds it *and all stores*. That makes pre-splitting much harder, but 3594 // maybe it would make it more principled? 3595 SmallPtrSet<LoadInst *, 8> UnsplittableLoads; 3596 3597 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n"); 3598 for (auto &P : AS.partitions()) { 3599 for (Slice &S : P) { 3600 Instruction *I = cast<Instruction>(S.getUse()->getUser()); 3601 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) { 3602 // If this is a load we have to track that it can't participate in any 3603 // pre-splitting. If this is a store of a load we have to track that 3604 // that load also can't participate in any pre-splitting. 3605 if (auto *LI = dyn_cast<LoadInst>(I)) 3606 UnsplittableLoads.insert(LI); 3607 else if (auto *SI = dyn_cast<StoreInst>(I)) 3608 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand())) 3609 UnsplittableLoads.insert(LI); 3610 continue; 3611 } 3612 assert(P.endOffset() > S.beginOffset() && 3613 "Empty or backwards partition!"); 3614 3615 // Determine if this is a pre-splittable slice. 3616 if (auto *LI = dyn_cast<LoadInst>(I)) { 3617 assert(!LI->isVolatile() && "Cannot split volatile loads!"); 3618 3619 // The load must be used exclusively to store into other pointers for 3620 // us to be able to arbitrarily pre-split it. The stores must also be 3621 // simple to avoid changing semantics. 3622 auto IsLoadSimplyStored = [](LoadInst *LI) { 3623 for (User *LU : LI->users()) { 3624 auto *SI = dyn_cast<StoreInst>(LU); 3625 if (!SI || !SI->isSimple()) 3626 return false; 3627 } 3628 return true; 3629 }; 3630 if (!IsLoadSimplyStored(LI)) { 3631 UnsplittableLoads.insert(LI); 3632 continue; 3633 } 3634 3635 Loads.push_back(LI); 3636 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 3637 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex())) 3638 // Skip stores *of* pointers. FIXME: This shouldn't even be possible! 3639 continue; 3640 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand()); 3641 if (!StoredLoad || !StoredLoad->isSimple()) 3642 continue; 3643 assert(!SI->isVolatile() && "Cannot split volatile stores!"); 3644 3645 Stores.push_back(SI); 3646 } else { 3647 // Other uses cannot be pre-split. 3648 continue; 3649 } 3650 3651 // Record the initial split. 3652 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n"); 3653 auto &Offsets = SplitOffsetsMap[I]; 3654 assert(Offsets.Splits.empty() && 3655 "Should not have splits the first time we see an instruction!"); 3656 Offsets.S = &S; 3657 Offsets.Splits.push_back(P.endOffset() - S.beginOffset()); 3658 } 3659 3660 // Now scan the already split slices, and add a split for any of them which 3661 // we're going to pre-split. 3662 for (Slice *S : P.splitSliceTails()) { 3663 auto SplitOffsetsMapI = 3664 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser())); 3665 if (SplitOffsetsMapI == SplitOffsetsMap.end()) 3666 continue; 3667 auto &Offsets = SplitOffsetsMapI->second; 3668 3669 assert(Offsets.S == S && "Found a mismatched slice!"); 3670 assert(!Offsets.Splits.empty() && 3671 "Cannot have an empty set of splits on the second partition!"); 3672 assert(Offsets.Splits.back() == 3673 P.beginOffset() - Offsets.S->beginOffset() && 3674 "Previous split does not end where this one begins!"); 3675 3676 // Record each split. The last partition's end isn't needed as the size 3677 // of the slice dictates that. 3678 if (S->endOffset() > P.endOffset()) 3679 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset()); 3680 } 3681 } 3682 3683 // We may have split loads where some of their stores are split stores. For 3684 // such loads and stores, we can only pre-split them if their splits exactly 3685 // match relative to their starting offset. We have to verify this prior to 3686 // any rewriting. 3687 Stores.erase( 3688 llvm::remove_if(Stores, 3689 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) { 3690 // Lookup the load we are storing in our map of split 3691 // offsets. 3692 auto *LI = cast<LoadInst>(SI->getValueOperand()); 3693 // If it was completely unsplittable, then we're done, 3694 // and this store can't be pre-split. 3695 if (UnsplittableLoads.count(LI)) 3696 return true; 3697 3698 auto LoadOffsetsI = SplitOffsetsMap.find(LI); 3699 if (LoadOffsetsI == SplitOffsetsMap.end()) 3700 return false; // Unrelated loads are definitely safe. 3701 auto &LoadOffsets = LoadOffsetsI->second; 3702 3703 // Now lookup the store's offsets. 3704 auto &StoreOffsets = SplitOffsetsMap[SI]; 3705 3706 // If the relative offsets of each split in the load and 3707 // store match exactly, then we can split them and we 3708 // don't need to remove them here. 3709 if (LoadOffsets.Splits == StoreOffsets.Splits) 3710 return false; 3711 3712 LLVM_DEBUG( 3713 dbgs() 3714 << " Mismatched splits for load and store:\n" 3715 << " " << *LI << "\n" 3716 << " " << *SI << "\n"); 3717 3718 // We've found a store and load that we need to split 3719 // with mismatched relative splits. Just give up on them 3720 // and remove both instructions from our list of 3721 // candidates. 3722 UnsplittableLoads.insert(LI); 3723 return true; 3724 }), 3725 Stores.end()); 3726 // Now we have to go *back* through all the stores, because a later store may 3727 // have caused an earlier store's load to become unsplittable and if it is 3728 // unsplittable for the later store, then we can't rely on it being split in 3729 // the earlier store either. 3730 Stores.erase(llvm::remove_if(Stores, 3731 [&UnsplittableLoads](StoreInst *SI) { 3732 auto *LI = 3733 cast<LoadInst>(SI->getValueOperand()); 3734 return UnsplittableLoads.count(LI); 3735 }), 3736 Stores.end()); 3737 // Once we've established all the loads that can't be split for some reason, 3738 // filter any that made it into our list out. 3739 Loads.erase(llvm::remove_if(Loads, 3740 [&UnsplittableLoads](LoadInst *LI) { 3741 return UnsplittableLoads.count(LI); 3742 }), 3743 Loads.end()); 3744 3745 // If no loads or stores are left, there is no pre-splitting to be done for 3746 // this alloca. 3747 if (Loads.empty() && Stores.empty()) 3748 return false; 3749 3750 // From here on, we can't fail and will be building new accesses, so rig up 3751 // an IR builder. 3752 IRBuilderTy IRB(&AI); 3753 3754 // Collect the new slices which we will merge into the alloca slices. 3755 SmallVector<Slice, 4> NewSlices; 3756 3757 // Track any allocas we end up splitting loads and stores for so we iterate 3758 // on them. 3759 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas; 3760 3761 // At this point, we have collected all of the loads and stores we can 3762 // pre-split, and the specific splits needed for them. We actually do the 3763 // splitting in a specific order in order to handle when one of the loads in 3764 // the value operand to one of the stores. 3765 // 3766 // First, we rewrite all of the split loads, and just accumulate each split 3767 // load in a parallel structure. We also build the slices for them and append 3768 // them to the alloca slices. 3769 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap; 3770 std::vector<LoadInst *> SplitLoads; 3771 const DataLayout &DL = AI.getModule()->getDataLayout(); 3772 for (LoadInst *LI : Loads) { 3773 SplitLoads.clear(); 3774 3775 IntegerType *Ty = cast<IntegerType>(LI->getType()); 3776 uint64_t LoadSize = Ty->getBitWidth() / 8; 3777 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!"); 3778 3779 auto &Offsets = SplitOffsetsMap[LI]; 3780 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && 3781 "Slice size should always match load size exactly!"); 3782 uint64_t BaseOffset = Offsets.S->beginOffset(); 3783 assert(BaseOffset + LoadSize > BaseOffset && 3784 "Cannot represent alloca access size using 64-bit integers!"); 3785 3786 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand()); 3787 IRB.SetInsertPoint(LI); 3788 3789 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n"); 3790 3791 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front(); 3792 int Idx = 0, Size = Offsets.Splits.size(); 3793 for (;;) { 3794 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8); 3795 auto AS = LI->getPointerAddressSpace(); 3796 auto *PartPtrTy = PartTy->getPointerTo(AS); 3797 LoadInst *PLoad = IRB.CreateAlignedLoad( 3798 getAdjustedPtr(IRB, DL, BasePtr, 3799 APInt(DL.getIndexSizeInBits(AS), PartOffset), 3800 PartPtrTy, BasePtr->getName() + "."), 3801 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false, 3802 LI->getName()); 3803 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access, 3804 LLVMContext::MD_access_group}); 3805 3806 // Append this load onto the list of split loads so we can find it later 3807 // to rewrite the stores. 3808 SplitLoads.push_back(PLoad); 3809 3810 // Now build a new slice for the alloca. 3811 NewSlices.push_back( 3812 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize, 3813 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()), 3814 /*IsSplittable*/ false)); 3815 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset() 3816 << ", " << NewSlices.back().endOffset() 3817 << "): " << *PLoad << "\n"); 3818 3819 // See if we've handled all the splits. 3820 if (Idx >= Size) 3821 break; 3822 3823 // Setup the next partition. 3824 PartOffset = Offsets.Splits[Idx]; 3825 ++Idx; 3826 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset; 3827 } 3828 3829 // Now that we have the split loads, do the slow walk over all uses of the 3830 // load and rewrite them as split stores, or save the split loads to use 3831 // below if the store is going to be split there anyways. 3832 bool DeferredStores = false; 3833 for (User *LU : LI->users()) { 3834 StoreInst *SI = cast<StoreInst>(LU); 3835 if (!Stores.empty() && SplitOffsetsMap.count(SI)) { 3836 DeferredStores = true; 3837 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI 3838 << "\n"); 3839 continue; 3840 } 3841 3842 Value *StoreBasePtr = SI->getPointerOperand(); 3843 IRB.SetInsertPoint(SI); 3844 3845 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n"); 3846 3847 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) { 3848 LoadInst *PLoad = SplitLoads[Idx]; 3849 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1]; 3850 auto *PartPtrTy = 3851 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace()); 3852 3853 auto AS = SI->getPointerAddressSpace(); 3854 StoreInst *PStore = IRB.CreateAlignedStore( 3855 PLoad, 3856 getAdjustedPtr(IRB, DL, StoreBasePtr, 3857 APInt(DL.getIndexSizeInBits(AS), PartOffset), 3858 PartPtrTy, StoreBasePtr->getName() + "."), 3859 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false); 3860 PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access, 3861 LLVMContext::MD_access_group}); 3862 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n"); 3863 } 3864 3865 // We want to immediately iterate on any allocas impacted by splitting 3866 // this store, and we have to track any promotable alloca (indicated by 3867 // a direct store) as needing to be resplit because it is no longer 3868 // promotable. 3869 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) { 3870 ResplitPromotableAllocas.insert(OtherAI); 3871 Worklist.insert(OtherAI); 3872 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>( 3873 StoreBasePtr->stripInBoundsOffsets())) { 3874 Worklist.insert(OtherAI); 3875 } 3876 3877 // Mark the original store as dead. 3878 DeadInsts.insert(SI); 3879 } 3880 3881 // Save the split loads if there are deferred stores among the users. 3882 if (DeferredStores) 3883 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads))); 3884 3885 // Mark the original load as dead and kill the original slice. 3886 DeadInsts.insert(LI); 3887 Offsets.S->kill(); 3888 } 3889 3890 // Second, we rewrite all of the split stores. At this point, we know that 3891 // all loads from this alloca have been split already. For stores of such 3892 // loads, we can simply look up the pre-existing split loads. For stores of 3893 // other loads, we split those loads first and then write split stores of 3894 // them. 3895 for (StoreInst *SI : Stores) { 3896 auto *LI = cast<LoadInst>(SI->getValueOperand()); 3897 IntegerType *Ty = cast<IntegerType>(LI->getType()); 3898 uint64_t StoreSize = Ty->getBitWidth() / 8; 3899 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!"); 3900 3901 auto &Offsets = SplitOffsetsMap[SI]; 3902 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && 3903 "Slice size should always match load size exactly!"); 3904 uint64_t BaseOffset = Offsets.S->beginOffset(); 3905 assert(BaseOffset + StoreSize > BaseOffset && 3906 "Cannot represent alloca access size using 64-bit integers!"); 3907 3908 Value *LoadBasePtr = LI->getPointerOperand(); 3909 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand()); 3910 3911 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n"); 3912 3913 // Check whether we have an already split load. 3914 auto SplitLoadsMapI = SplitLoadsMap.find(LI); 3915 std::vector<LoadInst *> *SplitLoads = nullptr; 3916 if (SplitLoadsMapI != SplitLoadsMap.end()) { 3917 SplitLoads = &SplitLoadsMapI->second; 3918 assert(SplitLoads->size() == Offsets.Splits.size() + 1 && 3919 "Too few split loads for the number of splits in the store!"); 3920 } else { 3921 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n"); 3922 } 3923 3924 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front(); 3925 int Idx = 0, Size = Offsets.Splits.size(); 3926 for (;;) { 3927 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8); 3928 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace()); 3929 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace()); 3930 3931 // Either lookup a split load or create one. 3932 LoadInst *PLoad; 3933 if (SplitLoads) { 3934 PLoad = (*SplitLoads)[Idx]; 3935 } else { 3936 IRB.SetInsertPoint(LI); 3937 auto AS = LI->getPointerAddressSpace(); 3938 PLoad = IRB.CreateAlignedLoad( 3939 getAdjustedPtr(IRB, DL, LoadBasePtr, 3940 APInt(DL.getIndexSizeInBits(AS), PartOffset), 3941 LoadPartPtrTy, LoadBasePtr->getName() + "."), 3942 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false, 3943 LI->getName()); 3944 } 3945 3946 // And store this partition. 3947 IRB.SetInsertPoint(SI); 3948 auto AS = SI->getPointerAddressSpace(); 3949 StoreInst *PStore = IRB.CreateAlignedStore( 3950 PLoad, 3951 getAdjustedPtr(IRB, DL, StoreBasePtr, 3952 APInt(DL.getIndexSizeInBits(AS), PartOffset), 3953 StorePartPtrTy, StoreBasePtr->getName() + "."), 3954 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false); 3955 3956 // Now build a new slice for the alloca. 3957 NewSlices.push_back( 3958 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize, 3959 &PStore->getOperandUse(PStore->getPointerOperandIndex()), 3960 /*IsSplittable*/ false)); 3961 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset() 3962 << ", " << NewSlices.back().endOffset() 3963 << "): " << *PStore << "\n"); 3964 if (!SplitLoads) { 3965 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n"); 3966 } 3967 3968 // See if we've finished all the splits. 3969 if (Idx >= Size) 3970 break; 3971 3972 // Setup the next partition. 3973 PartOffset = Offsets.Splits[Idx]; 3974 ++Idx; 3975 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset; 3976 } 3977 3978 // We want to immediately iterate on any allocas impacted by splitting 3979 // this load, which is only relevant if it isn't a load of this alloca and 3980 // thus we didn't already split the loads above. We also have to keep track 3981 // of any promotable allocas we split loads on as they can no longer be 3982 // promoted. 3983 if (!SplitLoads) { 3984 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) { 3985 assert(OtherAI != &AI && "We can't re-split our own alloca!"); 3986 ResplitPromotableAllocas.insert(OtherAI); 3987 Worklist.insert(OtherAI); 3988 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>( 3989 LoadBasePtr->stripInBoundsOffsets())) { 3990 assert(OtherAI != &AI && "We can't re-split our own alloca!"); 3991 Worklist.insert(OtherAI); 3992 } 3993 } 3994 3995 // Mark the original store as dead now that we've split it up and kill its 3996 // slice. Note that we leave the original load in place unless this store 3997 // was its only use. It may in turn be split up if it is an alloca load 3998 // for some other alloca, but it may be a normal load. This may introduce 3999 // redundant loads, but where those can be merged the rest of the optimizer 4000 // should handle the merging, and this uncovers SSA splits which is more 4001 // important. In practice, the original loads will almost always be fully 4002 // split and removed eventually, and the splits will be merged by any 4003 // trivial CSE, including instcombine. 4004 if (LI->hasOneUse()) { 4005 assert(*LI->user_begin() == SI && "Single use isn't this store!"); 4006 DeadInsts.insert(LI); 4007 } 4008 DeadInsts.insert(SI); 4009 Offsets.S->kill(); 4010 } 4011 4012 // Remove the killed slices that have ben pre-split. 4013 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }), 4014 AS.end()); 4015 4016 // Insert our new slices. This will sort and merge them into the sorted 4017 // sequence. 4018 AS.insert(NewSlices); 4019 4020 LLVM_DEBUG(dbgs() << " Pre-split slices:\n"); 4021 #ifndef NDEBUG 4022 for (auto I = AS.begin(), E = AS.end(); I != E; ++I) 4023 LLVM_DEBUG(AS.print(dbgs(), I, " ")); 4024 #endif 4025 4026 // Finally, don't try to promote any allocas that new require re-splitting. 4027 // They have already been added to the worklist above. 4028 PromotableAllocas.erase( 4029 llvm::remove_if( 4030 PromotableAllocas, 4031 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }), 4032 PromotableAllocas.end()); 4033 4034 return true; 4035 } 4036 4037 /// Rewrite an alloca partition's users. 4038 /// 4039 /// This routine drives both of the rewriting goals of the SROA pass. It tries 4040 /// to rewrite uses of an alloca partition to be conducive for SSA value 4041 /// promotion. If the partition needs a new, more refined alloca, this will 4042 /// build that new alloca, preserving as much type information as possible, and 4043 /// rewrite the uses of the old alloca to point at the new one and have the 4044 /// appropriate new offsets. It also evaluates how successful the rewrite was 4045 /// at enabling promotion and if it was successful queues the alloca to be 4046 /// promoted. 4047 AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS, 4048 Partition &P) { 4049 // Try to compute a friendly type for this partition of the alloca. This 4050 // won't always succeed, in which case we fall back to a legal integer type 4051 // or an i8 array of an appropriate size. 4052 Type *SliceTy = nullptr; 4053 const DataLayout &DL = AI.getModule()->getDataLayout(); 4054 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset())) 4055 if (DL.getTypeAllocSize(CommonUseTy) >= P.size()) 4056 SliceTy = CommonUseTy; 4057 if (!SliceTy) 4058 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(), 4059 P.beginOffset(), P.size())) 4060 SliceTy = TypePartitionTy; 4061 if ((!SliceTy || (SliceTy->isArrayTy() && 4062 SliceTy->getArrayElementType()->isIntegerTy())) && 4063 DL.isLegalInteger(P.size() * 8)) 4064 SliceTy = Type::getIntNTy(*C, P.size() * 8); 4065 if (!SliceTy) 4066 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size()); 4067 assert(DL.getTypeAllocSize(SliceTy) >= P.size()); 4068 4069 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL); 4070 4071 VectorType *VecTy = 4072 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL); 4073 if (VecTy) 4074 SliceTy = VecTy; 4075 4076 // Check for the case where we're going to rewrite to a new alloca of the 4077 // exact same type as the original, and with the same access offsets. In that 4078 // case, re-use the existing alloca, but still run through the rewriter to 4079 // perform phi and select speculation. 4080 // P.beginOffset() can be non-zero even with the same type in a case with 4081 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll). 4082 AllocaInst *NewAI; 4083 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) { 4084 NewAI = &AI; 4085 // FIXME: We should be able to bail at this point with "nothing changed". 4086 // FIXME: We might want to defer PHI speculation until after here. 4087 // FIXME: return nullptr; 4088 } else { 4089 unsigned Alignment = AI.getAlignment(); 4090 if (!Alignment) { 4091 // The minimum alignment which users can rely on when the explicit 4092 // alignment is omitted or zero is that required by the ABI for this 4093 // type. 4094 Alignment = DL.getABITypeAlignment(AI.getAllocatedType()); 4095 } 4096 Alignment = MinAlign(Alignment, P.beginOffset()); 4097 // If we will get at least this much alignment from the type alone, leave 4098 // the alloca's alignment unconstrained. 4099 if (Alignment <= DL.getABITypeAlignment(SliceTy)) 4100 Alignment = 0; 4101 NewAI = new AllocaInst( 4102 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment, 4103 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI); 4104 // Copy the old AI debug location over to the new one. 4105 NewAI->setDebugLoc(AI.getDebugLoc()); 4106 ++NumNewAllocas; 4107 } 4108 4109 LLVM_DEBUG(dbgs() << "Rewriting alloca partition " 4110 << "[" << P.beginOffset() << "," << P.endOffset() 4111 << ") to: " << *NewAI << "\n"); 4112 4113 // Track the high watermark on the worklist as it is only relevant for 4114 // promoted allocas. We will reset it to this point if the alloca is not in 4115 // fact scheduled for promotion. 4116 unsigned PPWOldSize = PostPromotionWorklist.size(); 4117 unsigned NumUses = 0; 4118 SmallSetVector<PHINode *, 8> PHIUsers; 4119 SmallSetVector<SelectInst *, 8> SelectUsers; 4120 4121 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(), 4122 P.endOffset(), IsIntegerPromotable, VecTy, 4123 PHIUsers, SelectUsers); 4124 bool Promotable = true; 4125 for (Slice *S : P.splitSliceTails()) { 4126 Promotable &= Rewriter.visit(S); 4127 ++NumUses; 4128 } 4129 for (Slice &S : P) { 4130 Promotable &= Rewriter.visit(&S); 4131 ++NumUses; 4132 } 4133 4134 NumAllocaPartitionUses += NumUses; 4135 MaxUsesPerAllocaPartition.updateMax(NumUses); 4136 4137 // Now that we've processed all the slices in the new partition, check if any 4138 // PHIs or Selects would block promotion. 4139 for (PHINode *PHI : PHIUsers) 4140 if (!isSafePHIToSpeculate(*PHI)) { 4141 Promotable = false; 4142 PHIUsers.clear(); 4143 SelectUsers.clear(); 4144 break; 4145 } 4146 4147 for (SelectInst *Sel : SelectUsers) 4148 if (!isSafeSelectToSpeculate(*Sel)) { 4149 Promotable = false; 4150 PHIUsers.clear(); 4151 SelectUsers.clear(); 4152 break; 4153 } 4154 4155 if (Promotable) { 4156 if (PHIUsers.empty() && SelectUsers.empty()) { 4157 // Promote the alloca. 4158 PromotableAllocas.push_back(NewAI); 4159 } else { 4160 // If we have either PHIs or Selects to speculate, add them to those 4161 // worklists and re-queue the new alloca so that we promote in on the 4162 // next iteration. 4163 for (PHINode *PHIUser : PHIUsers) 4164 SpeculatablePHIs.insert(PHIUser); 4165 for (SelectInst *SelectUser : SelectUsers) 4166 SpeculatableSelects.insert(SelectUser); 4167 Worklist.insert(NewAI); 4168 } 4169 } else { 4170 // Drop any post-promotion work items if promotion didn't happen. 4171 while (PostPromotionWorklist.size() > PPWOldSize) 4172 PostPromotionWorklist.pop_back(); 4173 4174 // We couldn't promote and we didn't create a new partition, nothing 4175 // happened. 4176 if (NewAI == &AI) 4177 return nullptr; 4178 4179 // If we can't promote the alloca, iterate on it to check for new 4180 // refinements exposed by splitting the current alloca. Don't iterate on an 4181 // alloca which didn't actually change and didn't get promoted. 4182 Worklist.insert(NewAI); 4183 } 4184 4185 return NewAI; 4186 } 4187 4188 /// Walks the slices of an alloca and form partitions based on them, 4189 /// rewriting each of their uses. 4190 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) { 4191 if (AS.begin() == AS.end()) 4192 return false; 4193 4194 unsigned NumPartitions = 0; 4195 bool Changed = false; 4196 const DataLayout &DL = AI.getModule()->getDataLayout(); 4197 4198 // First try to pre-split loads and stores. 4199 Changed |= presplitLoadsAndStores(AI, AS); 4200 4201 // Now that we have identified any pre-splitting opportunities, 4202 // mark loads and stores unsplittable except for the following case. 4203 // We leave a slice splittable if all other slices are disjoint or fully 4204 // included in the slice, such as whole-alloca loads and stores. 4205 // If we fail to split these during pre-splitting, we want to force them 4206 // to be rewritten into a partition. 4207 bool IsSorted = true; 4208 4209 uint64_t AllocaSize = DL.getTypeAllocSize(AI.getAllocatedType()); 4210 const uint64_t MaxBitVectorSize = 1024; 4211 if (AllocaSize <= MaxBitVectorSize) { 4212 // If a byte boundary is included in any load or store, a slice starting or 4213 // ending at the boundary is not splittable. 4214 SmallBitVector SplittableOffset(AllocaSize + 1, true); 4215 for (Slice &S : AS) 4216 for (unsigned O = S.beginOffset() + 1; 4217 O < S.endOffset() && O < AllocaSize; O++) 4218 SplittableOffset.reset(O); 4219 4220 for (Slice &S : AS) { 4221 if (!S.isSplittable()) 4222 continue; 4223 4224 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) && 4225 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()])) 4226 continue; 4227 4228 if (isa<LoadInst>(S.getUse()->getUser()) || 4229 isa<StoreInst>(S.getUse()->getUser())) { 4230 S.makeUnsplittable(); 4231 IsSorted = false; 4232 } 4233 } 4234 } 4235 else { 4236 // We only allow whole-alloca splittable loads and stores 4237 // for a large alloca to avoid creating too large BitVector. 4238 for (Slice &S : AS) { 4239 if (!S.isSplittable()) 4240 continue; 4241 4242 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize) 4243 continue; 4244 4245 if (isa<LoadInst>(S.getUse()->getUser()) || 4246 isa<StoreInst>(S.getUse()->getUser())) { 4247 S.makeUnsplittable(); 4248 IsSorted = false; 4249 } 4250 } 4251 } 4252 4253 if (!IsSorted) 4254 llvm::sort(AS); 4255 4256 /// Describes the allocas introduced by rewritePartition in order to migrate 4257 /// the debug info. 4258 struct Fragment { 4259 AllocaInst *Alloca; 4260 uint64_t Offset; 4261 uint64_t Size; 4262 Fragment(AllocaInst *AI, uint64_t O, uint64_t S) 4263 : Alloca(AI), Offset(O), Size(S) {} 4264 }; 4265 SmallVector<Fragment, 4> Fragments; 4266 4267 // Rewrite each partition. 4268 for (auto &P : AS.partitions()) { 4269 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) { 4270 Changed = true; 4271 if (NewAI != &AI) { 4272 uint64_t SizeOfByte = 8; 4273 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType()); 4274 // Don't include any padding. 4275 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte); 4276 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size)); 4277 } 4278 } 4279 ++NumPartitions; 4280 } 4281 4282 NumAllocaPartitions += NumPartitions; 4283 MaxPartitionsPerAlloca.updateMax(NumPartitions); 4284 4285 // Migrate debug information from the old alloca to the new alloca(s) 4286 // and the individual partitions. 4287 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI); 4288 if (!DbgDeclares.empty()) { 4289 auto *Var = DbgDeclares.front()->getVariable(); 4290 auto *Expr = DbgDeclares.front()->getExpression(); 4291 auto VarSize = Var->getSizeInBits(); 4292 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false); 4293 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType()); 4294 for (auto Fragment : Fragments) { 4295 // Create a fragment expression describing the new partition or reuse AI's 4296 // expression if there is only one partition. 4297 auto *FragmentExpr = Expr; 4298 if (Fragment.Size < AllocaSize || Expr->isFragment()) { 4299 // If this alloca is already a scalar replacement of a larger aggregate, 4300 // Fragment.Offset describes the offset inside the scalar. 4301 auto ExprFragment = Expr->getFragmentInfo(); 4302 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0; 4303 uint64_t Start = Offset + Fragment.Offset; 4304 uint64_t Size = Fragment.Size; 4305 if (ExprFragment) { 4306 uint64_t AbsEnd = 4307 ExprFragment->OffsetInBits + ExprFragment->SizeInBits; 4308 if (Start >= AbsEnd) 4309 // No need to describe a SROAed padding. 4310 continue; 4311 Size = std::min(Size, AbsEnd - Start); 4312 } 4313 // The new, smaller fragment is stenciled out from the old fragment. 4314 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) { 4315 assert(Start >= OrigFragment->OffsetInBits && 4316 "new fragment is outside of original fragment"); 4317 Start -= OrigFragment->OffsetInBits; 4318 } 4319 4320 // The alloca may be larger than the variable. 4321 if (VarSize) { 4322 if (Size > *VarSize) 4323 Size = *VarSize; 4324 if (Size == 0 || Start + Size > *VarSize) 4325 continue; 4326 } 4327 4328 // Avoid creating a fragment expression that covers the entire variable. 4329 if (!VarSize || *VarSize != Size) { 4330 if (auto E = 4331 DIExpression::createFragmentExpression(Expr, Start, Size)) 4332 FragmentExpr = *E; 4333 else 4334 continue; 4335 } 4336 } 4337 4338 // Remove any existing intrinsics describing the same alloca. 4339 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca)) 4340 OldDII->eraseFromParent(); 4341 4342 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr, 4343 DbgDeclares.front()->getDebugLoc(), &AI); 4344 } 4345 } 4346 return Changed; 4347 } 4348 4349 /// Clobber a use with undef, deleting the used value if it becomes dead. 4350 void SROA::clobberUse(Use &U) { 4351 Value *OldV = U; 4352 // Replace the use with an undef value. 4353 U = UndefValue::get(OldV->getType()); 4354 4355 // Check for this making an instruction dead. We have to garbage collect 4356 // all the dead instructions to ensure the uses of any alloca end up being 4357 // minimal. 4358 if (Instruction *OldI = dyn_cast<Instruction>(OldV)) 4359 if (isInstructionTriviallyDead(OldI)) { 4360 DeadInsts.insert(OldI); 4361 } 4362 } 4363 4364 /// Analyze an alloca for SROA. 4365 /// 4366 /// This analyzes the alloca to ensure we can reason about it, builds 4367 /// the slices of the alloca, and then hands it off to be split and 4368 /// rewritten as needed. 4369 bool SROA::runOnAlloca(AllocaInst &AI) { 4370 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n"); 4371 ++NumAllocasAnalyzed; 4372 4373 // Special case dead allocas, as they're trivial. 4374 if (AI.use_empty()) { 4375 AI.eraseFromParent(); 4376 return true; 4377 } 4378 const DataLayout &DL = AI.getModule()->getDataLayout(); 4379 4380 // Skip alloca forms that this analysis can't handle. 4381 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() || 4382 DL.getTypeAllocSize(AI.getAllocatedType()) == 0) 4383 return false; 4384 4385 bool Changed = false; 4386 4387 // First, split any FCA loads and stores touching this alloca to promote 4388 // better splitting and promotion opportunities. 4389 AggLoadStoreRewriter AggRewriter(DL); 4390 Changed |= AggRewriter.rewrite(AI); 4391 4392 // Build the slices using a recursive instruction-visiting builder. 4393 AllocaSlices AS(DL, AI); 4394 LLVM_DEBUG(AS.print(dbgs())); 4395 if (AS.isEscaped()) 4396 return Changed; 4397 4398 // Delete all the dead users of this alloca before splitting and rewriting it. 4399 for (Instruction *DeadUser : AS.getDeadUsers()) { 4400 // Free up everything used by this instruction. 4401 for (Use &DeadOp : DeadUser->operands()) 4402 clobberUse(DeadOp); 4403 4404 // Now replace the uses of this instruction. 4405 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType())); 4406 4407 // And mark it for deletion. 4408 DeadInsts.insert(DeadUser); 4409 Changed = true; 4410 } 4411 for (Use *DeadOp : AS.getDeadOperands()) { 4412 clobberUse(*DeadOp); 4413 Changed = true; 4414 } 4415 4416 // No slices to split. Leave the dead alloca for a later pass to clean up. 4417 if (AS.begin() == AS.end()) 4418 return Changed; 4419 4420 Changed |= splitAlloca(AI, AS); 4421 4422 LLVM_DEBUG(dbgs() << " Speculating PHIs\n"); 4423 while (!SpeculatablePHIs.empty()) 4424 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val()); 4425 4426 LLVM_DEBUG(dbgs() << " Speculating Selects\n"); 4427 while (!SpeculatableSelects.empty()) 4428 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val()); 4429 4430 return Changed; 4431 } 4432 4433 /// Delete the dead instructions accumulated in this run. 4434 /// 4435 /// Recursively deletes the dead instructions we've accumulated. This is done 4436 /// at the very end to maximize locality of the recursive delete and to 4437 /// minimize the problems of invalidated instruction pointers as such pointers 4438 /// are used heavily in the intermediate stages of the algorithm. 4439 /// 4440 /// We also record the alloca instructions deleted here so that they aren't 4441 /// subsequently handed to mem2reg to promote. 4442 bool SROA::deleteDeadInstructions( 4443 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) { 4444 bool Changed = false; 4445 while (!DeadInsts.empty()) { 4446 Instruction *I = DeadInsts.pop_back_val(); 4447 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n"); 4448 4449 // If the instruction is an alloca, find the possible dbg.declare connected 4450 // to it, and remove it too. We must do this before calling RAUW or we will 4451 // not be able to find it. 4452 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { 4453 DeletedAllocas.insert(AI); 4454 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI)) 4455 OldDII->eraseFromParent(); 4456 } 4457 4458 I->replaceAllUsesWith(UndefValue::get(I->getType())); 4459 4460 for (Use &Operand : I->operands()) 4461 if (Instruction *U = dyn_cast<Instruction>(Operand)) { 4462 // Zero out the operand and see if it becomes trivially dead. 4463 Operand = nullptr; 4464 if (isInstructionTriviallyDead(U)) 4465 DeadInsts.insert(U); 4466 } 4467 4468 ++NumDeleted; 4469 I->eraseFromParent(); 4470 Changed = true; 4471 } 4472 return Changed; 4473 } 4474 4475 /// Promote the allocas, using the best available technique. 4476 /// 4477 /// This attempts to promote whatever allocas have been identified as viable in 4478 /// the PromotableAllocas list. If that list is empty, there is nothing to do. 4479 /// This function returns whether any promotion occurred. 4480 bool SROA::promoteAllocas(Function &F) { 4481 if (PromotableAllocas.empty()) 4482 return false; 4483 4484 NumPromoted += PromotableAllocas.size(); 4485 4486 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n"); 4487 PromoteMemToReg(PromotableAllocas, *DT, AC); 4488 PromotableAllocas.clear(); 4489 return true; 4490 } 4491 4492 PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT, 4493 AssumptionCache &RunAC) { 4494 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n"); 4495 C = &F.getContext(); 4496 DT = &RunDT; 4497 AC = &RunAC; 4498 4499 BasicBlock &EntryBB = F.getEntryBlock(); 4500 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end()); 4501 I != E; ++I) { 4502 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 4503 Worklist.insert(AI); 4504 } 4505 4506 bool Changed = false; 4507 // A set of deleted alloca instruction pointers which should be removed from 4508 // the list of promotable allocas. 4509 SmallPtrSet<AllocaInst *, 4> DeletedAllocas; 4510 4511 do { 4512 while (!Worklist.empty()) { 4513 Changed |= runOnAlloca(*Worklist.pop_back_val()); 4514 Changed |= deleteDeadInstructions(DeletedAllocas); 4515 4516 // Remove the deleted allocas from various lists so that we don't try to 4517 // continue processing them. 4518 if (!DeletedAllocas.empty()) { 4519 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); }; 4520 Worklist.remove_if(IsInSet); 4521 PostPromotionWorklist.remove_if(IsInSet); 4522 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet), 4523 PromotableAllocas.end()); 4524 DeletedAllocas.clear(); 4525 } 4526 } 4527 4528 Changed |= promoteAllocas(F); 4529 4530 Worklist = PostPromotionWorklist; 4531 PostPromotionWorklist.clear(); 4532 } while (!Worklist.empty()); 4533 4534 if (!Changed) 4535 return PreservedAnalyses::all(); 4536 4537 PreservedAnalyses PA; 4538 PA.preserveSet<CFGAnalyses>(); 4539 PA.preserve<GlobalsAA>(); 4540 return PA; 4541 } 4542 4543 PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) { 4544 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F), 4545 AM.getResult<AssumptionAnalysis>(F)); 4546 } 4547 4548 /// A legacy pass for the legacy pass manager that wraps the \c SROA pass. 4549 /// 4550 /// This is in the llvm namespace purely to allow it to be a friend of the \c 4551 /// SROA pass. 4552 class llvm::sroa::SROALegacyPass : public FunctionPass { 4553 /// The SROA implementation. 4554 SROA Impl; 4555 4556 public: 4557 static char ID; 4558 4559 SROALegacyPass() : FunctionPass(ID) { 4560 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry()); 4561 } 4562 4563 bool runOnFunction(Function &F) override { 4564 if (skipFunction(F)) 4565 return false; 4566 4567 auto PA = Impl.runImpl( 4568 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 4569 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F)); 4570 return !PA.areAllPreserved(); 4571 } 4572 4573 void getAnalysisUsage(AnalysisUsage &AU) const override { 4574 AU.addRequired<AssumptionCacheTracker>(); 4575 AU.addRequired<DominatorTreeWrapperPass>(); 4576 AU.addPreserved<GlobalsAAWrapperPass>(); 4577 AU.setPreservesCFG(); 4578 } 4579 4580 StringRef getPassName() const override { return "SROA"; } 4581 }; 4582 4583 char SROALegacyPass::ID = 0; 4584 4585 FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); } 4586 4587 INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa", 4588 "Scalar Replacement Of Aggregates", false, false) 4589 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 4590 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 4591 INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates", 4592 false, false) 4593