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