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