LLVM API Documentation

SROA.cpp
Go to the documentation of this file.
00001 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 /// This transformation implements the well known scalar replacement of
00011 /// aggregates transformation. It tries to identify promotable elements of an
00012 /// aggregate alloca, and promote them to registers. It will also try to
00013 /// convert uses of an element (or set of elements) of an alloca into a vector
00014 /// or bitfield-style integer scalar if appropriate.
00015 ///
00016 /// It works to do this with minimal slicing of the alloca so that regions
00017 /// which are merely transferred in and out of external memory remain unchanged
00018 /// and are not decomposed to scalar code.
00019 ///
00020 /// Because this also performs alloca promotion, it can be thought of as also
00021 /// serving the purpose of SSA formation. The algorithm iterates on the
00022 /// function until all opportunities for promotion have been realized.
00023 ///
00024 //===----------------------------------------------------------------------===//
00025 
00026 #define DEBUG_TYPE "sroa"
00027 #include "llvm/Transforms/Scalar.h"
00028 #include "llvm/ADT/STLExtras.h"
00029 #include "llvm/ADT/SetVector.h"
00030 #include "llvm/ADT/SmallVector.h"
00031 #include "llvm/ADT/Statistic.h"
00032 #include "llvm/Analysis/Loads.h"
00033 #include "llvm/Analysis/PtrUseVisitor.h"
00034 #include "llvm/Analysis/ValueTracking.h"
00035 #include "llvm/IR/Constants.h"
00036 #include "llvm/IR/DIBuilder.h"
00037 #include "llvm/IR/DataLayout.h"
00038 #include "llvm/IR/DebugInfo.h"
00039 #include "llvm/IR/DerivedTypes.h"
00040 #include "llvm/IR/Dominators.h"
00041 #include "llvm/IR/Function.h"
00042 #include "llvm/IR/IRBuilder.h"
00043 #include "llvm/IR/InstVisitor.h"
00044 #include "llvm/IR/Instructions.h"
00045 #include "llvm/IR/IntrinsicInst.h"
00046 #include "llvm/IR/LLVMContext.h"
00047 #include "llvm/IR/Operator.h"
00048 #include "llvm/Pass.h"
00049 #include "llvm/Support/CommandLine.h"
00050 #include "llvm/Support/Compiler.h"
00051 #include "llvm/Support/Debug.h"
00052 #include "llvm/Support/ErrorHandling.h"
00053 #include "llvm/Support/MathExtras.h"
00054 #include "llvm/Support/TimeValue.h"
00055 #include "llvm/Support/raw_ostream.h"
00056 #include "llvm/Transforms/Utils/Local.h"
00057 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00058 #include "llvm/Transforms/Utils/SSAUpdater.h"
00059 
00060 #if __cplusplus >= 201103L && !defined(NDEBUG)
00061 // We only use this for a debug check in C++11
00062 #include <random>
00063 #endif
00064 
00065 using namespace llvm;
00066 
00067 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
00068 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
00069 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
00070 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
00071 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
00072 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
00073 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
00074 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
00075 STATISTIC(NumDeleted, "Number of instructions deleted");
00076 STATISTIC(NumVectorized, "Number of vectorized aggregates");
00077 
00078 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
00079 /// forming SSA values through the SSAUpdater infrastructure.
00080 static cl::opt<bool>
00081 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
00082 
00083 /// Hidden option to enable randomly shuffling the slices to help uncover
00084 /// instability in their order.
00085 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
00086                                              cl::init(false), cl::Hidden);
00087 
00088 /// Hidden option to experiment with completely strict handling of inbounds
00089 /// GEPs.
00090 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds",
00091                                         cl::init(false), cl::Hidden);
00092 
00093 namespace {
00094 /// \brief A custom IRBuilder inserter which prefixes all names if they are
00095 /// preserved.
00096 template <bool preserveNames = true>
00097 class IRBuilderPrefixedInserter :
00098     public IRBuilderDefaultInserter<preserveNames> {
00099   std::string Prefix;
00100 
00101 public:
00102   void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
00103 
00104 protected:
00105   void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
00106                     BasicBlock::iterator InsertPt) const {
00107     IRBuilderDefaultInserter<preserveNames>::InsertHelper(
00108         I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
00109   }
00110 };
00111 
00112 // Specialization for not preserving the name is trivial.
00113 template <>
00114 class IRBuilderPrefixedInserter<false> :
00115     public IRBuilderDefaultInserter<false> {
00116 public:
00117   void SetNamePrefix(const Twine &P) {}
00118 };
00119 
00120 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
00121 #ifndef NDEBUG
00122 typedef llvm::IRBuilder<true, ConstantFolder,
00123                         IRBuilderPrefixedInserter<true> > IRBuilderTy;
00124 #else
00125 typedef llvm::IRBuilder<false, ConstantFolder,
00126                         IRBuilderPrefixedInserter<false> > IRBuilderTy;
00127 #endif
00128 }
00129 
00130 namespace {
00131 /// \brief A used slice of an alloca.
00132 ///
00133 /// This structure represents a slice of an alloca used by some instruction. It
00134 /// stores both the begin and end offsets of this use, a pointer to the use
00135 /// itself, and a flag indicating whether we can classify the use as splittable
00136 /// or not when forming partitions of the alloca.
00137 class Slice {
00138   /// \brief The beginning offset of the range.
00139   uint64_t BeginOffset;
00140 
00141   /// \brief The ending offset, not included in the range.
00142   uint64_t EndOffset;
00143 
00144   /// \brief Storage for both the use of this slice and whether it can be
00145   /// split.
00146   PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
00147 
00148 public:
00149   Slice() : BeginOffset(), EndOffset() {}
00150   Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
00151       : BeginOffset(BeginOffset), EndOffset(EndOffset),
00152         UseAndIsSplittable(U, IsSplittable) {}
00153 
00154   uint64_t beginOffset() const { return BeginOffset; }
00155   uint64_t endOffset() const { return EndOffset; }
00156 
00157   bool isSplittable() const { return UseAndIsSplittable.getInt(); }
00158   void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
00159 
00160   Use *getUse() const { return UseAndIsSplittable.getPointer(); }
00161 
00162   bool isDead() const { return getUse() == 0; }
00163   void kill() { UseAndIsSplittable.setPointer(0); }
00164 
00165   /// \brief Support for ordering ranges.
00166   ///
00167   /// This provides an ordering over ranges such that start offsets are
00168   /// always increasing, and within equal start offsets, the end offsets are
00169   /// decreasing. Thus the spanning range comes first in a cluster with the
00170   /// same start position.
00171   bool operator<(const Slice &RHS) const {
00172     if (beginOffset() < RHS.beginOffset()) return true;
00173     if (beginOffset() > RHS.beginOffset()) return false;
00174     if (isSplittable() != RHS.isSplittable()) return !isSplittable();
00175     if (endOffset() > RHS.endOffset()) return true;
00176     return false;
00177   }
00178 
00179   /// \brief Support comparison with a single offset to allow binary searches.
00180   friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
00181                                               uint64_t RHSOffset) {
00182     return LHS.beginOffset() < RHSOffset;
00183   }
00184   friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
00185                                               const Slice &RHS) {
00186     return LHSOffset < RHS.beginOffset();
00187   }
00188 
00189   bool operator==(const Slice &RHS) const {
00190     return isSplittable() == RHS.isSplittable() &&
00191            beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
00192   }
00193   bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
00194 };
00195 } // end anonymous namespace
00196 
00197 namespace llvm {
00198 template <typename T> struct isPodLike;
00199 template <> struct isPodLike<Slice> {
00200    static const bool value = true;
00201 };
00202 }
00203 
00204 namespace {
00205 /// \brief Representation of the alloca slices.
00206 ///
00207 /// This class represents the slices of an alloca which are formed by its
00208 /// various uses. If a pointer escapes, we can't fully build a representation
00209 /// for the slices used and we reflect that in this structure. The uses are
00210 /// stored, sorted by increasing beginning offset and with unsplittable slices
00211 /// starting at a particular offset before splittable slices.
00212 class AllocaSlices {
00213 public:
00214   /// \brief Construct the slices of a particular alloca.
00215   AllocaSlices(const DataLayout &DL, AllocaInst &AI);
00216 
00217   /// \brief Test whether a pointer to the allocation escapes our analysis.
00218   ///
00219   /// If this is true, the slices are never fully built and should be
00220   /// ignored.
00221   bool isEscaped() const { return PointerEscapingInstr; }
00222 
00223   /// \brief Support for iterating over the slices.
00224   /// @{
00225   typedef SmallVectorImpl<Slice>::iterator iterator;
00226   iterator begin() { return Slices.begin(); }
00227   iterator end() { return Slices.end(); }
00228 
00229   typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
00230   const_iterator begin() const { return Slices.begin(); }
00231   const_iterator end() const { return Slices.end(); }
00232   /// @}
00233 
00234   /// \brief Allow iterating the dead users for this alloca.
00235   ///
00236   /// These are instructions which will never actually use the alloca as they
00237   /// are outside the allocated range. They are safe to replace with undef and
00238   /// delete.
00239   /// @{
00240   typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
00241   dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
00242   dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
00243   /// @}
00244 
00245   /// \brief Allow iterating the dead expressions referring to this alloca.
00246   ///
00247   /// These are operands which have cannot actually be used to refer to the
00248   /// alloca as they are outside its range and the user doesn't correct for
00249   /// that. These mostly consist of PHI node inputs and the like which we just
00250   /// need to replace with undef.
00251   /// @{
00252   typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
00253   dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
00254   dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
00255   /// @}
00256 
00257 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00258   void print(raw_ostream &OS, const_iterator I, StringRef Indent = "  ") const;
00259   void printSlice(raw_ostream &OS, const_iterator I,
00260                   StringRef Indent = "  ") const;
00261   void printUse(raw_ostream &OS, const_iterator I,
00262                 StringRef Indent = "  ") const;
00263   void print(raw_ostream &OS) const;
00264   void dump(const_iterator I) const;
00265   void dump() const;
00266 #endif
00267 
00268 private:
00269   template <typename DerivedT, typename RetT = void> class BuilderBase;
00270   class SliceBuilder;
00271   friend class AllocaSlices::SliceBuilder;
00272 
00273 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00274   /// \brief Handle to alloca instruction to simplify method interfaces.
00275   AllocaInst &AI;
00276 #endif
00277 
00278   /// \brief The instruction responsible for this alloca not having a known set
00279   /// of slices.
00280   ///
00281   /// When an instruction (potentially) escapes the pointer to the alloca, we
00282   /// store a pointer to that here and abort trying to form slices of the
00283   /// alloca. This will be null if the alloca slices are analyzed successfully.
00284   Instruction *PointerEscapingInstr;
00285 
00286   /// \brief The slices of the alloca.
00287   ///
00288   /// We store a vector of the slices formed by uses of the alloca here. This
00289   /// vector is sorted by increasing begin offset, and then the unsplittable
00290   /// slices before the splittable ones. See the Slice inner class for more
00291   /// details.
00292   SmallVector<Slice, 8> Slices;
00293 
00294   /// \brief Instructions which will become dead if we rewrite the alloca.
00295   ///
00296   /// Note that these are not separated by slice. This is because we expect an
00297   /// alloca to be completely rewritten or not rewritten at all. If rewritten,
00298   /// all these instructions can simply be removed and replaced with undef as
00299   /// they come from outside of the allocated space.
00300   SmallVector<Instruction *, 8> DeadUsers;
00301 
00302   /// \brief Operands which will become dead if we rewrite the alloca.
00303   ///
00304   /// These are operands that in their particular use can be replaced with
00305   /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
00306   /// to PHI nodes and the like. They aren't entirely dead (there might be
00307   /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
00308   /// want to swap this particular input for undef to simplify the use lists of
00309   /// the alloca.
00310   SmallVector<Use *, 8> DeadOperands;
00311 };
00312 }
00313 
00314 static Value *foldSelectInst(SelectInst &SI) {
00315   // If the condition being selected on is a constant or the same value is
00316   // being selected between, fold the select. Yes this does (rarely) happen
00317   // early on.
00318   if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
00319     return SI.getOperand(1+CI->isZero());
00320   if (SI.getOperand(1) == SI.getOperand(2))
00321     return SI.getOperand(1);
00322 
00323   return 0;
00324 }
00325 
00326 /// \brief Builder for the alloca slices.
00327 ///
00328 /// This class builds a set of alloca slices by recursively visiting the uses
00329 /// of an alloca and making a slice for each load and store at each offset.
00330 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
00331   friend class PtrUseVisitor<SliceBuilder>;
00332   friend class InstVisitor<SliceBuilder>;
00333   typedef PtrUseVisitor<SliceBuilder> Base;
00334 
00335   const uint64_t AllocSize;
00336   AllocaSlices &S;
00337 
00338   SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
00339   SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
00340 
00341   /// \brief Set to de-duplicate dead instructions found in the use walk.
00342   SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
00343 
00344 public:
00345   SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
00346       : PtrUseVisitor<SliceBuilder>(DL),
00347         AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
00348 
00349 private:
00350   void markAsDead(Instruction &I) {
00351     if (VisitedDeadInsts.insert(&I))
00352       S.DeadUsers.push_back(&I);
00353   }
00354 
00355   void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
00356                  bool IsSplittable = false) {
00357     // Completely skip uses which have a zero size or start either before or
00358     // past the end of the allocation.
00359     if (Size == 0 || Offset.uge(AllocSize)) {
00360       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
00361                    << " which has zero size or starts outside of the "
00362                    << AllocSize << " byte alloca:\n"
00363                    << "    alloca: " << S.AI << "\n"
00364                    << "       use: " << I << "\n");
00365       return markAsDead(I);
00366     }
00367 
00368     uint64_t BeginOffset = Offset.getZExtValue();
00369     uint64_t EndOffset = BeginOffset + Size;
00370 
00371     // Clamp the end offset to the end of the allocation. Note that this is
00372     // formulated to handle even the case where "BeginOffset + Size" overflows.
00373     // This may appear superficially to be something we could ignore entirely,
00374     // but that is not so! There may be widened loads or PHI-node uses where
00375     // some instructions are dead but not others. We can't completely ignore
00376     // them, and so have to record at least the information here.
00377     assert(AllocSize >= BeginOffset); // Established above.
00378     if (Size > AllocSize - BeginOffset) {
00379       DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
00380                    << " to remain within the " << AllocSize << " byte alloca:\n"
00381                    << "    alloca: " << S.AI << "\n"
00382                    << "       use: " << I << "\n");
00383       EndOffset = AllocSize;
00384     }
00385 
00386     S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
00387   }
00388 
00389   void visitBitCastInst(BitCastInst &BC) {
00390     if (BC.use_empty())
00391       return markAsDead(BC);
00392 
00393     return Base::visitBitCastInst(BC);
00394   }
00395 
00396   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
00397     if (GEPI.use_empty())
00398       return markAsDead(GEPI);
00399 
00400     if (SROAStrictInbounds && GEPI.isInBounds()) {
00401       // FIXME: This is a manually un-factored variant of the basic code inside
00402       // of GEPs with checking of the inbounds invariant specified in the
00403       // langref in a very strict sense. If we ever want to enable
00404       // SROAStrictInbounds, this code should be factored cleanly into
00405       // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
00406       // by writing out the code here where we have tho underlying allocation
00407       // size readily available.
00408       APInt GEPOffset = Offset;
00409       for (gep_type_iterator GTI = gep_type_begin(GEPI),
00410                              GTE = gep_type_end(GEPI);
00411            GTI != GTE; ++GTI) {
00412         ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
00413         if (!OpC)
00414           break;
00415 
00416         // Handle a struct index, which adds its field offset to the pointer.
00417         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00418           unsigned ElementIdx = OpC->getZExtValue();
00419           const StructLayout *SL = DL.getStructLayout(STy);
00420           GEPOffset +=
00421               APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
00422         } else {
00423           // For array or vector indices, scale the index by the size of the type.
00424           APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
00425           GEPOffset += Index * APInt(Offset.getBitWidth(),
00426                                      DL.getTypeAllocSize(GTI.getIndexedType()));
00427         }
00428 
00429         // If this index has computed an intermediate pointer which is not
00430         // inbounds, then the result of the GEP is a poison value and we can
00431         // delete it and all uses.
00432         if (GEPOffset.ugt(AllocSize))
00433           return markAsDead(GEPI);
00434       }
00435     }
00436 
00437     return Base::visitGetElementPtrInst(GEPI);
00438   }
00439 
00440   void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
00441                          uint64_t Size, bool IsVolatile) {
00442     // We allow splitting of loads and stores where the type is an integer type
00443     // and cover the entire alloca. This prevents us from splitting over
00444     // eagerly.
00445     // FIXME: In the great blue eventually, we should eagerly split all integer
00446     // loads and stores, and then have a separate step that merges adjacent
00447     // alloca partitions into a single partition suitable for integer widening.
00448     // Or we should skip the merge step and rely on GVN and other passes to
00449     // merge adjacent loads and stores that survive mem2reg.
00450     bool IsSplittable =
00451         Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
00452 
00453     insertUse(I, Offset, Size, IsSplittable);
00454   }
00455 
00456   void visitLoadInst(LoadInst &LI) {
00457     assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
00458            "All simple FCA loads should have been pre-split");
00459 
00460     if (!IsOffsetKnown)
00461       return PI.setAborted(&LI);
00462 
00463     uint64_t Size = DL.getTypeStoreSize(LI.getType());
00464     return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
00465   }
00466 
00467   void visitStoreInst(StoreInst &SI) {
00468     Value *ValOp = SI.getValueOperand();
00469     if (ValOp == *U)
00470       return PI.setEscapedAndAborted(&SI);
00471     if (!IsOffsetKnown)
00472       return PI.setAborted(&SI);
00473 
00474     uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
00475 
00476     // If this memory access can be shown to *statically* extend outside the
00477     // bounds of of the allocation, it's behavior is undefined, so simply
00478     // ignore it. Note that this is more strict than the generic clamping
00479     // behavior of insertUse. We also try to handle cases which might run the
00480     // risk of overflow.
00481     // FIXME: We should instead consider the pointer to have escaped if this
00482     // function is being instrumented for addressing bugs or race conditions.
00483     if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
00484       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
00485                    << " which extends past the end of the " << AllocSize
00486                    << " byte alloca:\n"
00487                    << "    alloca: " << S.AI << "\n"
00488                    << "       use: " << SI << "\n");
00489       return markAsDead(SI);
00490     }
00491 
00492     assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
00493            "All simple FCA stores should have been pre-split");
00494     handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
00495   }
00496 
00497 
00498   void visitMemSetInst(MemSetInst &II) {
00499     assert(II.getRawDest() == *U && "Pointer use is not the destination?");
00500     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
00501     if ((Length && Length->getValue() == 0) ||
00502         (IsOffsetKnown && Offset.uge(AllocSize)))
00503       // Zero-length mem transfer intrinsics can be ignored entirely.
00504       return markAsDead(II);
00505 
00506     if (!IsOffsetKnown)
00507       return PI.setAborted(&II);
00508 
00509     insertUse(II, Offset,
00510               Length ? Length->getLimitedValue()
00511                      : AllocSize - Offset.getLimitedValue(),
00512               (bool)Length);
00513   }
00514 
00515   void visitMemTransferInst(MemTransferInst &II) {
00516     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
00517     if (Length && Length->getValue() == 0)
00518       // Zero-length mem transfer intrinsics can be ignored entirely.
00519       return markAsDead(II);
00520 
00521     // Because we can visit these intrinsics twice, also check to see if the
00522     // first time marked this instruction as dead. If so, skip it.
00523     if (VisitedDeadInsts.count(&II))
00524       return;
00525 
00526     if (!IsOffsetKnown)
00527       return PI.setAborted(&II);
00528 
00529     // This side of the transfer is completely out-of-bounds, and so we can
00530     // nuke the entire transfer. However, we also need to nuke the other side
00531     // if already added to our partitions.
00532     // FIXME: Yet another place we really should bypass this when
00533     // instrumenting for ASan.
00534     if (Offset.uge(AllocSize)) {
00535       SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
00536       if (MTPI != MemTransferSliceMap.end())
00537         S.Slices[MTPI->second].kill();
00538       return markAsDead(II);
00539     }
00540 
00541     uint64_t RawOffset = Offset.getLimitedValue();
00542     uint64_t Size = Length ? Length->getLimitedValue()
00543                            : AllocSize - RawOffset;
00544 
00545     // Check for the special case where the same exact value is used for both
00546     // source and dest.
00547     if (*U == II.getRawDest() && *U == II.getRawSource()) {
00548       // For non-volatile transfers this is a no-op.
00549       if (!II.isVolatile())
00550         return markAsDead(II);
00551 
00552       return insertUse(II, Offset, Size, /*IsSplittable=*/false);
00553     }
00554 
00555     // If we have seen both source and destination for a mem transfer, then
00556     // they both point to the same alloca.
00557     bool Inserted;
00558     SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
00559     std::tie(MTPI, Inserted) =
00560         MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
00561     unsigned PrevIdx = MTPI->second;
00562     if (!Inserted) {
00563       Slice &PrevP = S.Slices[PrevIdx];
00564 
00565       // Check if the begin offsets match and this is a non-volatile transfer.
00566       // In that case, we can completely elide the transfer.
00567       if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
00568         PrevP.kill();
00569         return markAsDead(II);
00570       }
00571 
00572       // Otherwise we have an offset transfer within the same alloca. We can't
00573       // split those.
00574       PrevP.makeUnsplittable();
00575     }
00576 
00577     // Insert the use now that we've fixed up the splittable nature.
00578     insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
00579 
00580     // Check that we ended up with a valid index in the map.
00581     assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
00582            "Map index doesn't point back to a slice with this user.");
00583   }
00584 
00585   // Disable SRoA for any intrinsics except for lifetime invariants.
00586   // FIXME: What about debug intrinsics? This matches old behavior, but
00587   // doesn't make sense.
00588   void visitIntrinsicInst(IntrinsicInst &II) {
00589     if (!IsOffsetKnown)
00590       return PI.setAborted(&II);
00591 
00592     if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
00593         II.getIntrinsicID() == Intrinsic::lifetime_end) {
00594       ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
00595       uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
00596                                Length->getLimitedValue());
00597       insertUse(II, Offset, Size, true);
00598       return;
00599     }
00600 
00601     Base::visitIntrinsicInst(II);
00602   }
00603 
00604   Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
00605     // We consider any PHI or select that results in a direct load or store of
00606     // the same offset to be a viable use for slicing purposes. These uses
00607     // are considered unsplittable and the size is the maximum loaded or stored
00608     // size.
00609     SmallPtrSet<Instruction *, 4> Visited;
00610     SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
00611     Visited.insert(Root);
00612     Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
00613     // If there are no loads or stores, the access is dead. We mark that as
00614     // a size zero access.
00615     Size = 0;
00616     do {
00617       Instruction *I, *UsedI;
00618       std::tie(UsedI, I) = Uses.pop_back_val();
00619 
00620       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00621         Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
00622         continue;
00623       }
00624       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00625         Value *Op = SI->getOperand(0);
00626         if (Op == UsedI)
00627           return SI;
00628         Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
00629         continue;
00630       }
00631 
00632       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00633         if (!GEP->hasAllZeroIndices())
00634           return GEP;
00635       } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
00636                  !isa<SelectInst>(I)) {
00637         return I;
00638       }
00639 
00640       for (User *U : I->users())
00641         if (Visited.insert(cast<Instruction>(U)))
00642           Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
00643     } while (!Uses.empty());
00644 
00645     return 0;
00646   }
00647 
00648   void visitPHINode(PHINode &PN) {
00649     if (PN.use_empty())
00650       return markAsDead(PN);
00651     if (!IsOffsetKnown)
00652       return PI.setAborted(&PN);
00653 
00654     // See if we already have computed info on this node.
00655     uint64_t &PHISize = PHIOrSelectSizes[&PN];
00656     if (!PHISize) {
00657       // This is a new PHI node, check for an unsafe use of the PHI node.
00658       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
00659         return PI.setAborted(UnsafeI);
00660     }
00661 
00662     // For PHI and select operands outside the alloca, we can't nuke the entire
00663     // phi or select -- the other side might still be relevant, so we special
00664     // case them here and use a separate structure to track the operands
00665     // themselves which should be replaced with undef.
00666     // FIXME: This should instead be escaped in the event we're instrumenting
00667     // for address sanitization.
00668     if (Offset.uge(AllocSize)) {
00669       S.DeadOperands.push_back(U);
00670       return;
00671     }
00672 
00673     insertUse(PN, Offset, PHISize);
00674   }
00675 
00676   void visitSelectInst(SelectInst &SI) {
00677     if (SI.use_empty())
00678       return markAsDead(SI);
00679     if (Value *Result = foldSelectInst(SI)) {
00680       if (Result == *U)
00681         // If the result of the constant fold will be the pointer, recurse
00682         // through the select as if we had RAUW'ed it.
00683         enqueueUsers(SI);
00684       else
00685         // Otherwise the operand to the select is dead, and we can replace it
00686         // with undef.
00687         S.DeadOperands.push_back(U);
00688 
00689       return;
00690     }
00691     if (!IsOffsetKnown)
00692       return PI.setAborted(&SI);
00693 
00694     // See if we already have computed info on this node.
00695     uint64_t &SelectSize = PHIOrSelectSizes[&SI];
00696     if (!SelectSize) {
00697       // This is a new Select, check for an unsafe use of it.
00698       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
00699         return PI.setAborted(UnsafeI);
00700     }
00701 
00702     // For PHI and select operands outside the alloca, we can't nuke the entire
00703     // phi or select -- the other side might still be relevant, so we special
00704     // case them here and use a separate structure to track the operands
00705     // themselves which should be replaced with undef.
00706     // FIXME: This should instead be escaped in the event we're instrumenting
00707     // for address sanitization.
00708     if (Offset.uge(AllocSize)) {
00709       S.DeadOperands.push_back(U);
00710       return;
00711     }
00712 
00713     insertUse(SI, Offset, SelectSize);
00714   }
00715 
00716   /// \brief Disable SROA entirely if there are unhandled users of the alloca.
00717   void visitInstruction(Instruction &I) {
00718     PI.setAborted(&I);
00719   }
00720 };
00721 
00722 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
00723     :
00724 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00725       AI(AI),
00726 #endif
00727       PointerEscapingInstr(0) {
00728   SliceBuilder PB(DL, AI, *this);
00729   SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
00730   if (PtrI.isEscaped() || PtrI.isAborted()) {
00731     // FIXME: We should sink the escape vs. abort info into the caller nicely,
00732     // possibly by just storing the PtrInfo in the AllocaSlices.
00733     PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
00734                                                   : PtrI.getAbortingInst();
00735     assert(PointerEscapingInstr && "Did not track a bad instruction");
00736     return;
00737   }
00738 
00739   Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
00740                               std::mem_fun_ref(&Slice::isDead)),
00741                Slices.end());
00742 
00743 #if __cplusplus >= 201103L && !defined(NDEBUG)
00744   if (SROARandomShuffleSlices) {
00745     std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
00746     std::shuffle(Slices.begin(), Slices.end(), MT);
00747   }
00748 #endif
00749 
00750   // Sort the uses. This arranges for the offsets to be in ascending order,
00751   // and the sizes to be in descending order.
00752   std::sort(Slices.begin(), Slices.end());
00753 }
00754 
00755 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00756 
00757 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
00758                          StringRef Indent) const {
00759   printSlice(OS, I, Indent);
00760   printUse(OS, I, Indent);
00761 }
00762 
00763 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
00764                               StringRef Indent) const {
00765   OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
00766      << " slice #" << (I - begin())
00767      << (I->isSplittable() ? " (splittable)" : "") << "\n";
00768 }
00769 
00770 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
00771                             StringRef Indent) const {
00772   OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
00773 }
00774 
00775 void AllocaSlices::print(raw_ostream &OS) const {
00776   if (PointerEscapingInstr) {
00777     OS << "Can't analyze slices for alloca: " << AI << "\n"
00778        << "  A pointer to this alloca escaped by:\n"
00779        << "  " << *PointerEscapingInstr << "\n";
00780     return;
00781   }
00782 
00783   OS << "Slices of alloca: " << AI << "\n";
00784   for (const_iterator I = begin(), E = end(); I != E; ++I)
00785     print(OS, I);
00786 }
00787 
00788 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
00789   print(dbgs(), I);
00790 }
00791 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
00792 
00793 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00794 
00795 namespace {
00796 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
00797 ///
00798 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
00799 /// the loads and stores of an alloca instruction, as well as updating its
00800 /// debug information. This is used when a domtree is unavailable and thus
00801 /// mem2reg in its full form can't be used to handle promotion of allocas to
00802 /// scalar values.
00803 class AllocaPromoter : public LoadAndStorePromoter {
00804   AllocaInst &AI;
00805   DIBuilder &DIB;
00806 
00807   SmallVector<DbgDeclareInst *, 4> DDIs;
00808   SmallVector<DbgValueInst *, 4> DVIs;
00809 
00810 public:
00811   AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
00812                  AllocaInst &AI, DIBuilder &DIB)
00813       : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
00814 
00815   void run(const SmallVectorImpl<Instruction*> &Insts) {
00816     // Retain the debug information attached to the alloca for use when
00817     // rewriting loads and stores.
00818     if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
00819       for (User *U : DebugNode->users())
00820         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
00821           DDIs.push_back(DDI);
00822         else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
00823           DVIs.push_back(DVI);
00824     }
00825 
00826     LoadAndStorePromoter::run(Insts);
00827 
00828     // While we have the debug information, clear it off of the alloca. The
00829     // caller takes care of deleting the alloca.
00830     while (!DDIs.empty())
00831       DDIs.pop_back_val()->eraseFromParent();
00832     while (!DVIs.empty())
00833       DVIs.pop_back_val()->eraseFromParent();
00834   }
00835 
00836   bool isInstInList(Instruction *I,
00837                     const SmallVectorImpl<Instruction*> &Insts) const override {
00838     Value *Ptr;
00839     if (LoadInst *LI = dyn_cast<LoadInst>(I))
00840       Ptr = LI->getOperand(0);
00841     else
00842       Ptr = cast<StoreInst>(I)->getPointerOperand();
00843 
00844     // Only used to detect cycles, which will be rare and quickly found as
00845     // we're walking up a chain of defs rather than down through uses.
00846     SmallPtrSet<Value *, 4> Visited;
00847 
00848     do {
00849       if (Ptr == &AI)
00850         return true;
00851 
00852       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
00853         Ptr = BCI->getOperand(0);
00854       else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
00855         Ptr = GEPI->getPointerOperand();
00856       else
00857         return false;
00858 
00859     } while (Visited.insert(Ptr));
00860 
00861     return false;
00862   }
00863 
00864   void updateDebugInfo(Instruction *Inst) const override {
00865     for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
00866            E = DDIs.end(); I != E; ++I) {
00867       DbgDeclareInst *DDI = *I;
00868       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
00869         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
00870       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
00871         ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
00872     }
00873     for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
00874            E = DVIs.end(); I != E; ++I) {
00875       DbgValueInst *DVI = *I;
00876       Value *Arg = 0;
00877       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00878         // If an argument is zero extended then use argument directly. The ZExt
00879         // may be zapped by an optimization pass in future.
00880         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
00881           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
00882         else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
00883           Arg = dyn_cast<Argument>(SExt->getOperand(0));
00884         if (!Arg)
00885           Arg = SI->getValueOperand();
00886       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
00887         Arg = LI->getPointerOperand();
00888       } else {
00889         continue;
00890       }
00891       Instruction *DbgVal =
00892         DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
00893                                      Inst);
00894       DbgVal->setDebugLoc(DVI->getDebugLoc());
00895     }
00896   }
00897 };
00898 } // end anon namespace
00899 
00900 
00901 namespace {
00902 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
00903 ///
00904 /// This pass takes allocations which can be completely analyzed (that is, they
00905 /// don't escape) and tries to turn them into scalar SSA values. There are
00906 /// a few steps to this process.
00907 ///
00908 /// 1) It takes allocations of aggregates and analyzes the ways in which they
00909 ///    are used to try to split them into smaller allocations, ideally of
00910 ///    a single scalar data type. It will split up memcpy and memset accesses
00911 ///    as necessary and try to isolate individual scalar accesses.
00912 /// 2) It will transform accesses into forms which are suitable for SSA value
00913 ///    promotion. This can be replacing a memset with a scalar store of an
00914 ///    integer value, or it can involve speculating operations on a PHI or
00915 ///    select to be a PHI or select of the results.
00916 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
00917 ///    onto insert and extract operations on a vector value, and convert them to
00918 ///    this form. By doing so, it will enable promotion of vector aggregates to
00919 ///    SSA vector values.
00920 class SROA : public FunctionPass {
00921   const bool RequiresDomTree;
00922 
00923   LLVMContext *C;
00924   const DataLayout *DL;
00925   DominatorTree *DT;
00926 
00927   /// \brief Worklist of alloca instructions to simplify.
00928   ///
00929   /// Each alloca in the function is added to this. Each new alloca formed gets
00930   /// added to it as well to recursively simplify unless that alloca can be
00931   /// directly promoted. Finally, each time we rewrite a use of an alloca other
00932   /// the one being actively rewritten, we add it back onto the list if not
00933   /// already present to ensure it is re-visited.
00934   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
00935 
00936   /// \brief A collection of instructions to delete.
00937   /// We try to batch deletions to simplify code and make things a bit more
00938   /// efficient.
00939   SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
00940 
00941   /// \brief Post-promotion worklist.
00942   ///
00943   /// Sometimes we discover an alloca which has a high probability of becoming
00944   /// viable for SROA after a round of promotion takes place. In those cases,
00945   /// the alloca is enqueued here for re-processing.
00946   ///
00947   /// Note that we have to be very careful to clear allocas out of this list in
00948   /// the event they are deleted.
00949   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
00950 
00951   /// \brief A collection of alloca instructions we can directly promote.
00952   std::vector<AllocaInst *> PromotableAllocas;
00953 
00954   /// \brief A worklist of PHIs to speculate prior to promoting allocas.
00955   ///
00956   /// All of these PHIs have been checked for the safety of speculation and by
00957   /// being speculated will allow promoting allocas currently in the promotable
00958   /// queue.
00959   SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
00960 
00961   /// \brief A worklist of select instructions to speculate prior to promoting
00962   /// allocas.
00963   ///
00964   /// All of these select instructions have been checked for the safety of
00965   /// speculation and by being speculated will allow promoting allocas
00966   /// currently in the promotable queue.
00967   SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
00968 
00969 public:
00970   SROA(bool RequiresDomTree = true)
00971       : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
00972         C(0), DL(0), DT(0) {
00973     initializeSROAPass(*PassRegistry::getPassRegistry());
00974   }
00975   bool runOnFunction(Function &F) override;
00976   void getAnalysisUsage(AnalysisUsage &AU) const override;
00977 
00978   const char *getPassName() const override { return "SROA"; }
00979   static char ID;
00980 
00981 private:
00982   friend class PHIOrSelectSpeculator;
00983   friend class AllocaSliceRewriter;
00984 
00985   bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
00986                         AllocaSlices::iterator B, AllocaSlices::iterator E,
00987                         int64_t BeginOffset, int64_t EndOffset,
00988                         ArrayRef<AllocaSlices::iterator> SplitUses);
00989   bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
00990   bool runOnAlloca(AllocaInst &AI);
00991   void clobberUse(Use &U);
00992   void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
00993   bool promoteAllocas(Function &F);
00994 };
00995 }
00996 
00997 char SROA::ID = 0;
00998 
00999 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
01000   return new SROA(RequiresDomTree);
01001 }
01002 
01003 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
01004                       false, false)
01005 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
01006 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
01007                     false, false)
01008 
01009 /// Walk the range of a partitioning looking for a common type to cover this
01010 /// sequence of slices.
01011 static Type *findCommonType(AllocaSlices::const_iterator B,
01012                             AllocaSlices::const_iterator E,
01013                             uint64_t EndOffset) {
01014   Type *Ty = 0;
01015   bool TyIsCommon = true;
01016   IntegerType *ITy = 0;
01017 
01018   // Note that we need to look at *every* alloca slice's Use to ensure we
01019   // always get consistent results regardless of the order of slices.
01020   for (AllocaSlices::const_iterator I = B; I != E; ++I) {
01021     Use *U = I->getUse();
01022     if (isa<IntrinsicInst>(*U->getUser()))
01023       continue;
01024     if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
01025       continue;
01026 
01027     Type *UserTy = 0;
01028     if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01029       UserTy = LI->getType();
01030     } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01031       UserTy = SI->getValueOperand()->getType();
01032     }
01033 
01034     if (!UserTy || (Ty && Ty != UserTy))
01035       TyIsCommon = false; // Give up on anything but an iN type.
01036     else
01037       Ty = UserTy;
01038 
01039     if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
01040       // If the type is larger than the partition, skip it. We only encounter
01041       // this for split integer operations where we want to use the type of the
01042       // entity causing the split. Also skip if the type is not a byte width
01043       // multiple.
01044       if (UserITy->getBitWidth() % 8 != 0 ||
01045           UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
01046         continue;
01047 
01048       // Track the largest bitwidth integer type used in this way in case there
01049       // is no common type.
01050       if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
01051         ITy = UserITy;
01052     }
01053   }
01054 
01055   return TyIsCommon ? Ty : ITy;
01056 }
01057 
01058 /// PHI instructions that use an alloca and are subsequently loaded can be
01059 /// rewritten to load both input pointers in the pred blocks and then PHI the
01060 /// results, allowing the load of the alloca to be promoted.
01061 /// From this:
01062 ///   %P2 = phi [i32* %Alloca, i32* %Other]
01063 ///   %V = load i32* %P2
01064 /// to:
01065 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01066 ///   ...
01067 ///   %V2 = load i32* %Other
01068 ///   ...
01069 ///   %V = phi [i32 %V1, i32 %V2]
01070 ///
01071 /// We can do this to a select if its only uses are loads and if the operands
01072 /// to the select can be loaded unconditionally.
01073 ///
01074 /// FIXME: This should be hoisted into a generic utility, likely in
01075 /// Transforms/Util/Local.h
01076 static bool isSafePHIToSpeculate(PHINode &PN,
01077                                  const DataLayout *DL = 0) {
01078   // For now, we can only do this promotion if the load is in the same block
01079   // as the PHI, and if there are no stores between the phi and load.
01080   // TODO: Allow recursive phi users.
01081   // TODO: Allow stores.
01082   BasicBlock *BB = PN.getParent();
01083   unsigned MaxAlign = 0;
01084   bool HaveLoad = false;
01085   for (User *U : PN.users()) {
01086     LoadInst *LI = dyn_cast<LoadInst>(U);
01087     if (LI == 0 || !LI->isSimple())
01088       return false;
01089 
01090     // For now we only allow loads in the same block as the PHI.  This is
01091     // a common case that happens when instcombine merges two loads through
01092     // a PHI.
01093     if (LI->getParent() != BB)
01094       return false;
01095 
01096     // Ensure that there are no instructions between the PHI and the load that
01097     // could store.
01098     for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
01099       if (BBI->mayWriteToMemory())
01100         return false;
01101 
01102     MaxAlign = std::max(MaxAlign, LI->getAlignment());
01103     HaveLoad = true;
01104   }
01105 
01106   if (!HaveLoad)
01107     return false;
01108 
01109   // We can only transform this if it is safe to push the loads into the
01110   // predecessor blocks. The only thing to watch out for is that we can't put
01111   // a possibly trapping load in the predecessor if it is a critical edge.
01112   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
01113     TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
01114     Value *InVal = PN.getIncomingValue(Idx);
01115 
01116     // If the value is produced by the terminator of the predecessor (an
01117     // invoke) or it has side-effects, there is no valid place to put a load
01118     // in the predecessor.
01119     if (TI == InVal || TI->mayHaveSideEffects())
01120       return false;
01121 
01122     // If the predecessor has a single successor, then the edge isn't
01123     // critical.
01124     if (TI->getNumSuccessors() == 1)
01125       continue;
01126 
01127     // If this pointer is always safe to load, or if we can prove that there
01128     // is already a load in the block, then we can move the load to the pred
01129     // block.
01130     if (InVal->isDereferenceablePointer() ||
01131         isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
01132       continue;
01133 
01134     return false;
01135   }
01136 
01137   return true;
01138 }
01139 
01140 static void speculatePHINodeLoads(PHINode &PN) {
01141   DEBUG(dbgs() << "    original: " << PN << "\n");
01142 
01143   Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
01144   IRBuilderTy PHIBuilder(&PN);
01145   PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
01146                                         PN.getName() + ".sroa.speculated");
01147 
01148   // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
01149   // matter which one we get and if any differ.
01150   LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
01151   MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
01152   unsigned Align = SomeLoad->getAlignment();
01153 
01154   // Rewrite all loads of the PN to use the new PHI.
01155   while (!PN.use_empty()) {
01156     LoadInst *LI = cast<LoadInst>(PN.user_back());
01157     LI->replaceAllUsesWith(NewPN);
01158     LI->eraseFromParent();
01159   }
01160 
01161   // Inject loads into all of the pred blocks.
01162   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
01163     BasicBlock *Pred = PN.getIncomingBlock(Idx);
01164     TerminatorInst *TI = Pred->getTerminator();
01165     Value *InVal = PN.getIncomingValue(Idx);
01166     IRBuilderTy PredBuilder(TI);
01167 
01168     LoadInst *Load = PredBuilder.CreateLoad(
01169         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
01170     ++NumLoadsSpeculated;
01171     Load->setAlignment(Align);
01172     if (TBAATag)
01173       Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
01174     NewPN->addIncoming(Load, Pred);
01175   }
01176 
01177   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
01178   PN.eraseFromParent();
01179 }
01180 
01181 /// Select instructions that use an alloca and are subsequently loaded can be
01182 /// rewritten to load both input pointers and then select between the result,
01183 /// allowing the load of the alloca to be promoted.
01184 /// From this:
01185 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
01186 ///   %V = load i32* %P2
01187 /// to:
01188 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01189 ///   %V2 = load i32* %Other
01190 ///   %V = select i1 %cond, i32 %V1, i32 %V2
01191 ///
01192 /// We can do this to a select if its only uses are loads and if the operand
01193 /// to the select can be loaded unconditionally.
01194 static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
01195   Value *TValue = SI.getTrueValue();
01196   Value *FValue = SI.getFalseValue();
01197   bool TDerefable = TValue->isDereferenceablePointer();
01198   bool FDerefable = FValue->isDereferenceablePointer();
01199 
01200   for (User *U : SI.users()) {
01201     LoadInst *LI = dyn_cast<LoadInst>(U);
01202     if (LI == 0 || !LI->isSimple())
01203       return false;
01204 
01205     // Both operands to the select need to be dereferencable, either
01206     // absolutely (e.g. allocas) or at this point because we can see other
01207     // accesses to it.
01208     if (!TDerefable &&
01209         !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
01210       return false;
01211     if (!FDerefable &&
01212         !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
01213       return false;
01214   }
01215 
01216   return true;
01217 }
01218 
01219 static void speculateSelectInstLoads(SelectInst &SI) {
01220   DEBUG(dbgs() << "    original: " << SI << "\n");
01221 
01222   IRBuilderTy IRB(&SI);
01223   Value *TV = SI.getTrueValue();
01224   Value *FV = SI.getFalseValue();
01225   // Replace the loads of the select with a select of two loads.
01226   while (!SI.use_empty()) {
01227     LoadInst *LI = cast<LoadInst>(SI.user_back());
01228     assert(LI->isSimple() && "We only speculate simple loads");
01229 
01230     IRB.SetInsertPoint(LI);
01231     LoadInst *TL =
01232         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
01233     LoadInst *FL =
01234         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
01235     NumLoadsSpeculated += 2;
01236 
01237     // Transfer alignment and TBAA info if present.
01238     TL->setAlignment(LI->getAlignment());
01239     FL->setAlignment(LI->getAlignment());
01240     if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
01241       TL->setMetadata(LLVMContext::MD_tbaa, Tag);
01242       FL->setMetadata(LLVMContext::MD_tbaa, Tag);
01243     }
01244 
01245     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
01246                                 LI->getName() + ".sroa.speculated");
01247 
01248     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
01249     LI->replaceAllUsesWith(V);
01250     LI->eraseFromParent();
01251   }
01252   SI.eraseFromParent();
01253 }
01254 
01255 /// \brief Build a GEP out of a base pointer and indices.
01256 ///
01257 /// This will return the BasePtr if that is valid, or build a new GEP
01258 /// instruction using the IRBuilder if GEP-ing is needed.
01259 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
01260                        SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
01261   if (Indices.empty())
01262     return BasePtr;
01263 
01264   // A single zero index is a no-op, so check for this and avoid building a GEP
01265   // in that case.
01266   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
01267     return BasePtr;
01268 
01269   return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
01270 }
01271 
01272 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
01273 /// TargetTy without changing the offset of the pointer.
01274 ///
01275 /// This routine assumes we've already established a properly offset GEP with
01276 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
01277 /// zero-indices down through type layers until we find one the same as
01278 /// TargetTy. If we can't find one with the same type, we at least try to use
01279 /// one with the same size. If none of that works, we just produce the GEP as
01280 /// indicated by Indices to have the correct offset.
01281 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
01282                                     Value *BasePtr, Type *Ty, Type *TargetTy,
01283                                     SmallVectorImpl<Value *> &Indices,
01284                                     Twine NamePrefix) {
01285   if (Ty == TargetTy)
01286     return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01287 
01288   // Pointer size to use for the indices.
01289   unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
01290 
01291   // See if we can descend into a struct and locate a field with the correct
01292   // type.
01293   unsigned NumLayers = 0;
01294   Type *ElementTy = Ty;
01295   do {
01296     if (ElementTy->isPointerTy())
01297       break;
01298 
01299     if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
01300       ElementTy = ArrayTy->getElementType();
01301       Indices.push_back(IRB.getIntN(PtrSize, 0));
01302     } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
01303       ElementTy = VectorTy->getElementType();
01304       Indices.push_back(IRB.getInt32(0));
01305     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
01306       if (STy->element_begin() == STy->element_end())
01307         break; // Nothing left to descend into.
01308       ElementTy = *STy->element_begin();
01309       Indices.push_back(IRB.getInt32(0));
01310     } else {
01311       break;
01312     }
01313     ++NumLayers;
01314   } while (ElementTy != TargetTy);
01315   if (ElementTy != TargetTy)
01316     Indices.erase(Indices.end() - NumLayers, Indices.end());
01317 
01318   return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01319 }
01320 
01321 /// \brief Recursively compute indices for a natural GEP.
01322 ///
01323 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
01324 /// element types adding appropriate indices for the GEP.
01325 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
01326                                        Value *Ptr, Type *Ty, APInt &Offset,
01327                                        Type *TargetTy,
01328                                        SmallVectorImpl<Value *> &Indices,
01329                                        Twine NamePrefix) {
01330   if (Offset == 0)
01331     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
01332 
01333   // We can't recurse through pointer types.
01334   if (Ty->isPointerTy())
01335     return 0;
01336 
01337   // We try to analyze GEPs over vectors here, but note that these GEPs are
01338   // extremely poorly defined currently. The long-term goal is to remove GEPing
01339   // over a vector from the IR completely.
01340   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
01341     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
01342     if (ElementSizeInBits % 8)
01343       return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
01344     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
01345     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01346     if (NumSkippedElements.ugt(VecTy->getNumElements()))
01347       return 0;
01348     Offset -= NumSkippedElements * ElementSize;
01349     Indices.push_back(IRB.getInt(NumSkippedElements));
01350     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
01351                                     Offset, TargetTy, Indices, NamePrefix);
01352   }
01353 
01354   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
01355     Type *ElementTy = ArrTy->getElementType();
01356     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01357     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01358     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
01359       return 0;
01360 
01361     Offset -= NumSkippedElements * ElementSize;
01362     Indices.push_back(IRB.getInt(NumSkippedElements));
01363     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01364                                     Indices, NamePrefix);
01365   }
01366 
01367   StructType *STy = dyn_cast<StructType>(Ty);
01368   if (!STy)
01369     return 0;
01370 
01371   const StructLayout *SL = DL.getStructLayout(STy);
01372   uint64_t StructOffset = Offset.getZExtValue();
01373   if (StructOffset >= SL->getSizeInBytes())
01374     return 0;
01375   unsigned Index = SL->getElementContainingOffset(StructOffset);
01376   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
01377   Type *ElementTy = STy->getElementType(Index);
01378   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
01379     return 0; // The offset points into alignment padding.
01380 
01381   Indices.push_back(IRB.getInt32(Index));
01382   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01383                                   Indices, NamePrefix);
01384 }
01385 
01386 /// \brief Get a natural GEP from a base pointer to a particular offset and
01387 /// resulting in a particular type.
01388 ///
01389 /// The goal is to produce a "natural" looking GEP that works with the existing
01390 /// composite types to arrive at the appropriate offset and element type for
01391 /// a pointer. TargetTy is the element type the returned GEP should point-to if
01392 /// possible. We recurse by decreasing Offset, adding the appropriate index to
01393 /// Indices, and setting Ty to the result subtype.
01394 ///
01395 /// If no natural GEP can be constructed, this function returns null.
01396 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
01397                                       Value *Ptr, APInt Offset, Type *TargetTy,
01398                                       SmallVectorImpl<Value *> &Indices,
01399                                       Twine NamePrefix) {
01400   PointerType *Ty = cast<PointerType>(Ptr->getType());
01401 
01402   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
01403   // an i8.
01404   if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
01405     return 0;
01406 
01407   Type *ElementTy = Ty->getElementType();
01408   if (!ElementTy->isSized())
01409     return 0; // We can't GEP through an unsized element.
01410   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01411   if (ElementSize == 0)
01412     return 0; // Zero-length arrays can't help us build a natural GEP.
01413   APInt NumSkippedElements = Offset.sdiv(ElementSize);
01414 
01415   Offset -= NumSkippedElements * ElementSize;
01416   Indices.push_back(IRB.getInt(NumSkippedElements));
01417   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01418                                   Indices, NamePrefix);
01419 }
01420 
01421 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
01422 /// resulting pointer has PointerTy.
01423 ///
01424 /// This tries very hard to compute a "natural" GEP which arrives at the offset
01425 /// and produces the pointer type desired. Where it cannot, it will try to use
01426 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
01427 /// fails, it will try to use an existing i8* and GEP to the byte offset and
01428 /// bitcast to the type.
01429 ///
01430 /// The strategy for finding the more natural GEPs is to peel off layers of the
01431 /// pointer, walking back through bit casts and GEPs, searching for a base
01432 /// pointer from which we can compute a natural GEP with the desired
01433 /// properties. The algorithm tries to fold as many constant indices into
01434 /// a single GEP as possible, thus making each GEP more independent of the
01435 /// surrounding code.
01436 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
01437                              APInt Offset, Type *PointerTy,
01438                              Twine NamePrefix) {
01439   // Even though we don't look through PHI nodes, we could be called on an
01440   // instruction in an unreachable block, which may be on a cycle.
01441   SmallPtrSet<Value *, 4> Visited;
01442   Visited.insert(Ptr);
01443   SmallVector<Value *, 4> Indices;
01444 
01445   // We may end up computing an offset pointer that has the wrong type. If we
01446   // never are able to compute one directly that has the correct type, we'll
01447   // fall back to it, so keep it around here.
01448   Value *OffsetPtr = 0;
01449 
01450   // Remember any i8 pointer we come across to re-use if we need to do a raw
01451   // byte offset.
01452   Value *Int8Ptr = 0;
01453   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
01454 
01455   Type *TargetTy = PointerTy->getPointerElementType();
01456 
01457   do {
01458     // First fold any existing GEPs into the offset.
01459     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
01460       APInt GEPOffset(Offset.getBitWidth(), 0);
01461       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
01462         break;
01463       Offset += GEPOffset;
01464       Ptr = GEP->getPointerOperand();
01465       if (!Visited.insert(Ptr))
01466         break;
01467     }
01468 
01469     // See if we can perform a natural GEP here.
01470     Indices.clear();
01471     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
01472                                            Indices, NamePrefix)) {
01473       if (P->getType() == PointerTy) {
01474         // Zap any offset pointer that we ended up computing in previous rounds.
01475         if (OffsetPtr && OffsetPtr->use_empty())
01476           if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
01477             I->eraseFromParent();
01478         return P;
01479       }
01480       if (!OffsetPtr) {
01481         OffsetPtr = P;
01482       }
01483     }
01484 
01485     // Stash this pointer if we've found an i8*.
01486     if (Ptr->getType()->isIntegerTy(8)) {
01487       Int8Ptr = Ptr;
01488       Int8PtrOffset = Offset;
01489     }
01490 
01491     // Peel off a layer of the pointer and update the offset appropriately.
01492     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
01493       Ptr = cast<Operator>(Ptr)->getOperand(0);
01494     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
01495       if (GA->mayBeOverridden())
01496         break;
01497       Ptr = GA->getAliasee();
01498     } else {
01499       break;
01500     }
01501     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
01502   } while (Visited.insert(Ptr));
01503 
01504   if (!OffsetPtr) {
01505     if (!Int8Ptr) {
01506       Int8Ptr = IRB.CreateBitCast(
01507           Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
01508           NamePrefix + "sroa_raw_cast");
01509       Int8PtrOffset = Offset;
01510     }
01511 
01512     OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
01513       IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
01514                             NamePrefix + "sroa_raw_idx");
01515   }
01516   Ptr = OffsetPtr;
01517 
01518   // On the off chance we were targeting i8*, guard the bitcast here.
01519   if (Ptr->getType() != PointerTy)
01520     Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
01521 
01522   return Ptr;
01523 }
01524 
01525 /// \brief Test whether we can convert a value from the old to the new type.
01526 ///
01527 /// This predicate should be used to guard calls to convertValue in order to
01528 /// ensure that we only try to convert viable values. The strategy is that we
01529 /// will peel off single element struct and array wrappings to get to an
01530 /// underlying value, and convert that value.
01531 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
01532   if (OldTy == NewTy)
01533     return true;
01534   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01535     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01536       if (NewITy->getBitWidth() >= OldITy->getBitWidth())
01537         return true;
01538   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
01539     return false;
01540   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
01541     return false;
01542 
01543   // We can convert pointers to integers and vice-versa. Same for vectors
01544   // of pointers and integers.
01545   OldTy = OldTy->getScalarType();
01546   NewTy = NewTy->getScalarType();
01547   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
01548     if (NewTy->isPointerTy() && OldTy->isPointerTy())
01549       return true;
01550     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
01551       return true;
01552     return false;
01553   }
01554 
01555   return true;
01556 }
01557 
01558 /// \brief Generic routine to convert an SSA value to a value of a different
01559 /// type.
01560 ///
01561 /// This will try various different casting techniques, such as bitcasts,
01562 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
01563 /// two types for viability with this routine.
01564 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
01565                            Type *NewTy) {
01566   Type *OldTy = V->getType();
01567   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
01568 
01569   if (OldTy == NewTy)
01570     return V;
01571 
01572   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01573     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01574       if (NewITy->getBitWidth() > OldITy->getBitWidth())
01575         return IRB.CreateZExt(V, NewITy);
01576 
01577   // See if we need inttoptr for this type pair. A cast involving both scalars
01578   // and vectors requires and additional bitcast.
01579   if (OldTy->getScalarType()->isIntegerTy() &&
01580       NewTy->getScalarType()->isPointerTy()) {
01581     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
01582     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01583       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01584                                 NewTy);
01585 
01586     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
01587     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01588       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01589                                 NewTy);
01590 
01591     return IRB.CreateIntToPtr(V, NewTy);
01592   }
01593 
01594   // See if we need ptrtoint for this type pair. A cast involving both scalars
01595   // and vectors requires and additional bitcast.
01596   if (OldTy->getScalarType()->isPointerTy() &&
01597       NewTy->getScalarType()->isIntegerTy()) {
01598     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
01599     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01600       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01601                                NewTy);
01602 
01603     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
01604     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01605       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01606                                NewTy);
01607 
01608     return IRB.CreatePtrToInt(V, NewTy);
01609   }
01610 
01611   return IRB.CreateBitCast(V, NewTy);
01612 }
01613 
01614 /// \brief Test whether the given slice use can be promoted to a vector.
01615 ///
01616 /// This function is called to test each entry in a partioning which is slated
01617 /// for a single slice.
01618 static bool isVectorPromotionViableForSlice(
01619     const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
01620     uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
01621     AllocaSlices::const_iterator I) {
01622   // First validate the slice offsets.
01623   uint64_t BeginOffset =
01624       std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
01625   uint64_t BeginIndex = BeginOffset / ElementSize;
01626   if (BeginIndex * ElementSize != BeginOffset ||
01627       BeginIndex >= Ty->getNumElements())
01628     return false;
01629   uint64_t EndOffset =
01630       std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
01631   uint64_t EndIndex = EndOffset / ElementSize;
01632   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
01633     return false;
01634 
01635   assert(EndIndex > BeginIndex && "Empty vector!");
01636   uint64_t NumElements = EndIndex - BeginIndex;
01637   Type *SliceTy =
01638       (NumElements == 1) ? Ty->getElementType()
01639                          : VectorType::get(Ty->getElementType(), NumElements);
01640 
01641   Type *SplitIntTy =
01642       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
01643 
01644   Use *U = I->getUse();
01645 
01646   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
01647     if (MI->isVolatile())
01648       return false;
01649     if (!I->isSplittable())
01650       return false; // Skip any unsplittable intrinsics.
01651   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
01652     // Disable vector promotion when there are loads or stores of an FCA.
01653     return false;
01654   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01655     if (LI->isVolatile())
01656       return false;
01657     Type *LTy = LI->getType();
01658     if (SliceBeginOffset > I->beginOffset() ||
01659         SliceEndOffset < I->endOffset()) {
01660       assert(LTy->isIntegerTy());
01661       LTy = SplitIntTy;
01662     }
01663     if (!canConvertValue(DL, SliceTy, LTy))
01664       return false;
01665   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01666     if (SI->isVolatile())
01667       return false;
01668     Type *STy = SI->getValueOperand()->getType();
01669     if (SliceBeginOffset > I->beginOffset() ||
01670         SliceEndOffset < I->endOffset()) {
01671       assert(STy->isIntegerTy());
01672       STy = SplitIntTy;
01673     }
01674     if (!canConvertValue(DL, STy, SliceTy))
01675       return false;
01676   } else {
01677     return false;
01678   }
01679 
01680   return true;
01681 }
01682 
01683 /// \brief Test whether the given alloca partitioning and range of slices can be
01684 /// promoted to a vector.
01685 ///
01686 /// This is a quick test to check whether we can rewrite a particular alloca
01687 /// partition (and its newly formed alloca) into a vector alloca with only
01688 /// whole-vector loads and stores such that it could be promoted to a vector
01689 /// SSA value. We only can ensure this for a limited set of operations, and we
01690 /// don't want to do the rewrites unless we are confident that the result will
01691 /// be promotable, so we have an early test here.
01692 static bool
01693 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
01694                         uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
01695                         AllocaSlices::const_iterator I,
01696                         AllocaSlices::const_iterator E,
01697                         ArrayRef<AllocaSlices::iterator> SplitUses) {
01698   VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
01699   if (!Ty)
01700     return false;
01701 
01702   uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
01703 
01704   // While the definition of LLVM vectors is bitpacked, we don't support sizes
01705   // that aren't byte sized.
01706   if (ElementSize % 8)
01707     return false;
01708   assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
01709          "vector size not a multiple of element size?");
01710   ElementSize /= 8;
01711 
01712   for (; I != E; ++I)
01713     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
01714                                          SliceEndOffset, Ty, ElementSize, I))
01715       return false;
01716 
01717   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
01718                                                         SUE = SplitUses.end();
01719        SUI != SUE; ++SUI)
01720     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
01721                                          SliceEndOffset, Ty, ElementSize, *SUI))
01722       return false;
01723 
01724   return true;
01725 }
01726 
01727 /// \brief Test whether a slice of an alloca is valid for integer widening.
01728 ///
01729 /// This implements the necessary checking for the \c isIntegerWideningViable
01730 /// test below on a single slice of the alloca.
01731 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
01732                                             Type *AllocaTy,
01733                                             uint64_t AllocBeginOffset,
01734                                             uint64_t Size, AllocaSlices &S,
01735                                             AllocaSlices::const_iterator I,
01736                                             bool &WholeAllocaOp) {
01737   uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
01738   uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
01739 
01740   // We can't reasonably handle cases where the load or store extends past
01741   // the end of the aloca's type and into its padding.
01742   if (RelEnd > Size)
01743     return false;
01744 
01745   Use *U = I->getUse();
01746 
01747   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01748     if (LI->isVolatile())
01749       return false;
01750     if (RelBegin == 0 && RelEnd == Size)
01751       WholeAllocaOp = true;
01752     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
01753       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
01754         return false;
01755     } else if (RelBegin != 0 || RelEnd != Size ||
01756                !canConvertValue(DL, AllocaTy, LI->getType())) {
01757       // Non-integer loads need to be convertible from the alloca type so that
01758       // they are promotable.
01759       return false;
01760     }
01761   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01762     Type *ValueTy = SI->getValueOperand()->getType();
01763     if (SI->isVolatile())
01764       return false;
01765     if (RelBegin == 0 && RelEnd == Size)
01766       WholeAllocaOp = true;
01767     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
01768       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
01769         return false;
01770     } else if (RelBegin != 0 || RelEnd != Size ||
01771                !canConvertValue(DL, ValueTy, AllocaTy)) {
01772       // Non-integer stores need to be convertible to the alloca type so that
01773       // they are promotable.
01774       return false;
01775     }
01776   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
01777     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
01778       return false;
01779     if (!I->isSplittable())
01780       return false; // Skip any unsplittable intrinsics.
01781   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
01782     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
01783         II->getIntrinsicID() != Intrinsic::lifetime_end)
01784       return false;
01785   } else {
01786     return false;
01787   }
01788 
01789   return true;
01790 }
01791 
01792 /// \brief Test whether the given alloca partition's integer operations can be
01793 /// widened to promotable ones.
01794 ///
01795 /// This is a quick test to check whether we can rewrite the integer loads and
01796 /// stores to a particular alloca into wider loads and stores and be able to
01797 /// promote the resulting alloca.
01798 static bool
01799 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
01800                         uint64_t AllocBeginOffset, AllocaSlices &S,
01801                         AllocaSlices::const_iterator I,
01802                         AllocaSlices::const_iterator E,
01803                         ArrayRef<AllocaSlices::iterator> SplitUses) {
01804   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
01805   // Don't create integer types larger than the maximum bitwidth.
01806   if (SizeInBits > IntegerType::MAX_INT_BITS)
01807     return false;
01808 
01809   // Don't try to handle allocas with bit-padding.
01810   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
01811     return false;
01812 
01813   // We need to ensure that an integer type with the appropriate bitwidth can
01814   // be converted to the alloca type, whatever that is. We don't want to force
01815   // the alloca itself to have an integer type if there is a more suitable one.
01816   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
01817   if (!canConvertValue(DL, AllocaTy, IntTy) ||
01818       !canConvertValue(DL, IntTy, AllocaTy))
01819     return false;
01820 
01821   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
01822 
01823   // While examining uses, we ensure that the alloca has a covering load or
01824   // store. We don't want to widen the integer operations only to fail to
01825   // promote due to some other unsplittable entry (which we may make splittable
01826   // later). However, if there are only splittable uses, go ahead and assume
01827   // that we cover the alloca.
01828   bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
01829 
01830   for (; I != E; ++I)
01831     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
01832                                          S, I, WholeAllocaOp))
01833       return false;
01834 
01835   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
01836                                                         SUE = SplitUses.end();
01837        SUI != SUE; ++SUI)
01838     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
01839                                          S, *SUI, WholeAllocaOp))
01840       return false;
01841 
01842   return WholeAllocaOp;
01843 }
01844 
01845 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
01846                              IntegerType *Ty, uint64_t Offset,
01847                              const Twine &Name) {
01848   DEBUG(dbgs() << "       start: " << *V << "\n");
01849   IntegerType *IntTy = cast<IntegerType>(V->getType());
01850   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
01851          "Element extends past full value");
01852   uint64_t ShAmt = 8*Offset;
01853   if (DL.isBigEndian())
01854     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
01855   if (ShAmt) {
01856     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
01857     DEBUG(dbgs() << "     shifted: " << *V << "\n");
01858   }
01859   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
01860          "Cannot extract to a larger integer!");
01861   if (Ty != IntTy) {
01862     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
01863     DEBUG(dbgs() << "     trunced: " << *V << "\n");
01864   }
01865   return V;
01866 }
01867 
01868 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
01869                             Value *V, uint64_t Offset, const Twine &Name) {
01870   IntegerType *IntTy = cast<IntegerType>(Old->getType());
01871   IntegerType *Ty = cast<IntegerType>(V->getType());
01872   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
01873          "Cannot insert a larger integer!");
01874   DEBUG(dbgs() << "       start: " << *V << "\n");
01875   if (Ty != IntTy) {
01876     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
01877     DEBUG(dbgs() << "    extended: " << *V << "\n");
01878   }
01879   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
01880          "Element store outside of alloca store");
01881   uint64_t ShAmt = 8*Offset;
01882   if (DL.isBigEndian())
01883     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
01884   if (ShAmt) {
01885     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
01886     DEBUG(dbgs() << "     shifted: " << *V << "\n");
01887   }
01888 
01889   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
01890     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
01891     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
01892     DEBUG(dbgs() << "      masked: " << *Old << "\n");
01893     V = IRB.CreateOr(Old, V, Name + ".insert");
01894     DEBUG(dbgs() << "    inserted: " << *V << "\n");
01895   }
01896   return V;
01897 }
01898 
01899 static Value *extractVector(IRBuilderTy &IRB, Value *V,
01900                             unsigned BeginIndex, unsigned EndIndex,
01901                             const Twine &Name) {
01902   VectorType *VecTy = cast<VectorType>(V->getType());
01903   unsigned NumElements = EndIndex - BeginIndex;
01904   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
01905 
01906   if (NumElements == VecTy->getNumElements())
01907     return V;
01908 
01909   if (NumElements == 1) {
01910     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
01911                                  Name + ".extract");
01912     DEBUG(dbgs() << "     extract: " << *V << "\n");
01913     return V;
01914   }
01915 
01916   SmallVector<Constant*, 8> Mask;
01917   Mask.reserve(NumElements);
01918   for (unsigned i = BeginIndex; i != EndIndex; ++i)
01919     Mask.push_back(IRB.getInt32(i));
01920   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
01921                               ConstantVector::get(Mask),
01922                               Name + ".extract");
01923   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
01924   return V;
01925 }
01926 
01927 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
01928                            unsigned BeginIndex, const Twine &Name) {
01929   VectorType *VecTy = cast<VectorType>(Old->getType());
01930   assert(VecTy && "Can only insert a vector into a vector");
01931 
01932   VectorType *Ty = dyn_cast<VectorType>(V->getType());
01933   if (!Ty) {
01934     // Single element to insert.
01935     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
01936                                 Name + ".insert");
01937     DEBUG(dbgs() <<  "     insert: " << *V << "\n");
01938     return V;
01939   }
01940 
01941   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
01942          "Too many elements!");
01943   if (Ty->getNumElements() == VecTy->getNumElements()) {
01944     assert(V->getType() == VecTy && "Vector type mismatch");
01945     return V;
01946   }
01947   unsigned EndIndex = BeginIndex + Ty->getNumElements();
01948 
01949   // When inserting a smaller vector into the larger to store, we first
01950   // use a shuffle vector to widen it with undef elements, and then
01951   // a second shuffle vector to select between the loaded vector and the
01952   // incoming vector.
01953   SmallVector<Constant*, 8> Mask;
01954   Mask.reserve(VecTy->getNumElements());
01955   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
01956     if (i >= BeginIndex && i < EndIndex)
01957       Mask.push_back(IRB.getInt32(i - BeginIndex));
01958     else
01959       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
01960   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
01961                               ConstantVector::get(Mask),
01962                               Name + ".expand");
01963   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
01964 
01965   Mask.clear();
01966   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
01967     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
01968 
01969   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
01970 
01971   DEBUG(dbgs() << "    blend: " << *V << "\n");
01972   return V;
01973 }
01974 
01975 namespace {
01976 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
01977 /// to use a new alloca.
01978 ///
01979 /// Also implements the rewriting to vector-based accesses when the partition
01980 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
01981 /// lives here.
01982 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
01983   // Befriend the base class so it can delegate to private visit methods.
01984   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
01985   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
01986 
01987   const DataLayout &DL;
01988   AllocaSlices &S;
01989   SROA &Pass;
01990   AllocaInst &OldAI, &NewAI;
01991   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
01992   Type *NewAllocaTy;
01993 
01994   // If we are rewriting an alloca partition which can be written as pure
01995   // vector operations, we stash extra information here. When VecTy is
01996   // non-null, we have some strict guarantees about the rewritten alloca:
01997   //   - The new alloca is exactly the size of the vector type here.
01998   //   - The accesses all either map to the entire vector or to a single
01999   //     element.
02000   //   - The set of accessing instructions is only one of those handled above
02001   //     in isVectorPromotionViable. Generally these are the same access kinds
02002   //     which are promotable via mem2reg.
02003   VectorType *VecTy;
02004   Type *ElementTy;
02005   uint64_t ElementSize;
02006 
02007   // This is a convenience and flag variable that will be null unless the new
02008   // alloca's integer operations should be widened to this integer type due to
02009   // passing isIntegerWideningViable above. If it is non-null, the desired
02010   // integer type will be stored here for easy access during rewriting.
02011   IntegerType *IntTy;
02012 
02013   // The original offset of the slice currently being rewritten relative to
02014   // the original alloca.
02015   uint64_t BeginOffset, EndOffset;
02016   // The new offsets of the slice currently being rewritten relative to the
02017   // original alloca.
02018   uint64_t NewBeginOffset, NewEndOffset;
02019 
02020   uint64_t SliceSize;
02021   bool IsSplittable;
02022   bool IsSplit;
02023   Use *OldUse;
02024   Instruction *OldPtr;
02025 
02026   // Track post-rewrite users which are PHI nodes and Selects.
02027   SmallPtrSetImpl<PHINode *> &PHIUsers;
02028   SmallPtrSetImpl<SelectInst *> &SelectUsers;
02029 
02030   // Utility IR builder, whose name prefix is setup for each visited use, and
02031   // the insertion point is set to point to the user.
02032   IRBuilderTy IRB;
02033 
02034 public:
02035   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
02036                       AllocaInst &OldAI, AllocaInst &NewAI,
02037                       uint64_t NewAllocaBeginOffset,
02038                       uint64_t NewAllocaEndOffset, bool IsVectorPromotable,
02039                       bool IsIntegerPromotable,
02040                       SmallPtrSetImpl<PHINode *> &PHIUsers,
02041                       SmallPtrSetImpl<SelectInst *> &SelectUsers)
02042       : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
02043         NewAllocaBeginOffset(NewAllocaBeginOffset),
02044         NewAllocaEndOffset(NewAllocaEndOffset),
02045         NewAllocaTy(NewAI.getAllocatedType()),
02046         VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
02047         ElementTy(VecTy ? VecTy->getElementType() : 0),
02048         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
02049         IntTy(IsIntegerPromotable
02050                   ? Type::getIntNTy(
02051                         NewAI.getContext(),
02052                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
02053                   : 0),
02054         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
02055         OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
02056         IRB(NewAI.getContext(), ConstantFolder()) {
02057     if (VecTy) {
02058       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
02059              "Only multiple-of-8 sized vector elements are viable");
02060       ++NumVectorized;
02061     }
02062     assert((!IsVectorPromotable && !IsIntegerPromotable) ||
02063            IsVectorPromotable != IsIntegerPromotable);
02064   }
02065 
02066   bool visit(AllocaSlices::const_iterator I) {
02067     bool CanSROA = true;
02068     BeginOffset = I->beginOffset();
02069     EndOffset = I->endOffset();
02070     IsSplittable = I->isSplittable();
02071     IsSplit =
02072         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
02073 
02074     // Compute the intersecting offset range.
02075     assert(BeginOffset < NewAllocaEndOffset);
02076     assert(EndOffset > NewAllocaBeginOffset);
02077     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
02078     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
02079 
02080     SliceSize = NewEndOffset - NewBeginOffset;
02081 
02082     OldUse = I->getUse();
02083     OldPtr = cast<Instruction>(OldUse->get());
02084 
02085     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
02086     IRB.SetInsertPoint(OldUserI);
02087     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
02088     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
02089 
02090     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
02091     if (VecTy || IntTy)
02092       assert(CanSROA);
02093     return CanSROA;
02094   }
02095 
02096 private:
02097   // Make sure the other visit overloads are visible.
02098   using Base::visit;
02099 
02100   // Every instruction which can end up as a user must have a rewrite rule.
02101   bool visitInstruction(Instruction &I) {
02102     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
02103     llvm_unreachable("No rewrite rule for this instruction!");
02104   }
02105 
02106   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
02107     // Note that the offset computation can use BeginOffset or NewBeginOffset
02108     // interchangeably for unsplit slices.
02109     assert(IsSplit || BeginOffset == NewBeginOffset);
02110     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02111 
02112 #ifndef NDEBUG
02113     StringRef OldName = OldPtr->getName();
02114     // Skip through the last '.sroa.' component of the name.
02115     size_t LastSROAPrefix = OldName.rfind(".sroa.");
02116     if (LastSROAPrefix != StringRef::npos) {
02117       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
02118       // Look for an SROA slice index.
02119       size_t IndexEnd = OldName.find_first_not_of("0123456789");
02120       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
02121         // Strip the index and look for the offset.
02122         OldName = OldName.substr(IndexEnd + 1);
02123         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
02124         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
02125           // Strip the offset.
02126           OldName = OldName.substr(OffsetEnd + 1);
02127       }
02128     }
02129     // Strip any SROA suffixes as well.
02130     OldName = OldName.substr(0, OldName.find(".sroa_"));
02131 #endif
02132 
02133     return getAdjustedPtr(IRB, DL, &NewAI,
02134                           APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
02135 #ifndef NDEBUG
02136                           Twine(OldName) + "."
02137 #else
02138                           Twine()
02139 #endif
02140                           );
02141   }
02142 
02143   /// \brief Compute suitable alignment to access this slice of the *new* alloca.
02144   ///
02145   /// You can optionally pass a type to this routine and if that type's ABI
02146   /// alignment is itself suitable, this will return zero.
02147   unsigned getSliceAlign(Type *Ty = 0) {
02148     unsigned NewAIAlign = NewAI.getAlignment();
02149     if (!NewAIAlign)
02150       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
02151     unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
02152     return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
02153   }
02154 
02155   unsigned getIndex(uint64_t Offset) {
02156     assert(VecTy && "Can only call getIndex when rewriting a vector");
02157     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
02158     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
02159     uint32_t Index = RelOffset / ElementSize;
02160     assert(Index * ElementSize == RelOffset);
02161     return Index;
02162   }
02163 
02164   void deleteIfTriviallyDead(Value *V) {
02165     Instruction *I = cast<Instruction>(V);
02166     if (isInstructionTriviallyDead(I))
02167       Pass.DeadInsts.insert(I);
02168   }
02169 
02170   Value *rewriteVectorizedLoadInst() {
02171     unsigned BeginIndex = getIndex(NewBeginOffset);
02172     unsigned EndIndex = getIndex(NewEndOffset);
02173     assert(EndIndex > BeginIndex && "Empty vector!");
02174 
02175     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02176                                      "load");
02177     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
02178   }
02179 
02180   Value *rewriteIntegerLoad(LoadInst &LI) {
02181     assert(IntTy && "We cannot insert an integer to the alloca");
02182     assert(!LI.isVolatile());
02183     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02184                                      "load");
02185     V = convertValue(DL, IRB, V, IntTy);
02186     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02187     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02188     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
02189       V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
02190                          "extract");
02191     return V;
02192   }
02193 
02194   bool visitLoadInst(LoadInst &LI) {
02195     DEBUG(dbgs() << "    original: " << LI << "\n");
02196     Value *OldOp = LI.getOperand(0);
02197     assert(OldOp == OldPtr);
02198 
02199     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
02200                              : LI.getType();
02201     bool IsPtrAdjusted = false;
02202     Value *V;
02203     if (VecTy) {
02204       V = rewriteVectorizedLoadInst();
02205     } else if (IntTy && LI.getType()->isIntegerTy()) {
02206       V = rewriteIntegerLoad(LI);
02207     } else if (NewBeginOffset == NewAllocaBeginOffset &&
02208                canConvertValue(DL, NewAllocaTy, LI.getType())) {
02209       V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02210                                 LI.isVolatile(), LI.getName());
02211     } else {
02212       Type *LTy = TargetTy->getPointerTo();
02213       V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
02214                                 getSliceAlign(TargetTy), LI.isVolatile(),
02215                                 LI.getName());
02216       IsPtrAdjusted = true;
02217     }
02218     V = convertValue(DL, IRB, V, TargetTy);
02219 
02220     if (IsSplit) {
02221       assert(!LI.isVolatile());
02222       assert(LI.getType()->isIntegerTy() &&
02223              "Only integer type loads and stores are split");
02224       assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
02225              "Split load isn't smaller than original load");
02226       assert(LI.getType()->getIntegerBitWidth() ==
02227              DL.getTypeStoreSizeInBits(LI.getType()) &&
02228              "Non-byte-multiple bit width");
02229       // Move the insertion point just past the load so that we can refer to it.
02230       IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
02231       // Create a placeholder value with the same type as LI to use as the
02232       // basis for the new value. This allows us to replace the uses of LI with
02233       // the computed value, and then replace the placeholder with LI, leaving
02234       // LI only used for this computation.
02235       Value *Placeholder
02236         = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
02237       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
02238                         "insert");
02239       LI.replaceAllUsesWith(V);
02240       Placeholder->replaceAllUsesWith(&LI);
02241       delete Placeholder;
02242     } else {
02243       LI.replaceAllUsesWith(V);
02244     }
02245 
02246     Pass.DeadInsts.insert(&LI);
02247     deleteIfTriviallyDead(OldOp);
02248     DEBUG(dbgs() << "          to: " << *V << "\n");
02249     return !LI.isVolatile() && !IsPtrAdjusted;
02250   }
02251 
02252   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
02253     if (V->getType() != VecTy) {
02254       unsigned BeginIndex = getIndex(NewBeginOffset);
02255       unsigned EndIndex = getIndex(NewEndOffset);
02256       assert(EndIndex > BeginIndex && "Empty vector!");
02257       unsigned NumElements = EndIndex - BeginIndex;
02258       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02259       Type *SliceTy =
02260           (NumElements == 1) ? ElementTy
02261                              : VectorType::get(ElementTy, NumElements);
02262       if (V->getType() != SliceTy)
02263         V = convertValue(DL, IRB, V, SliceTy);
02264 
02265       // Mix in the existing elements.
02266       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02267                                          "load");
02268       V = insertVector(IRB, Old, V, BeginIndex, "vec");
02269     }
02270     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02271     Pass.DeadInsts.insert(&SI);
02272 
02273     (void)Store;
02274     DEBUG(dbgs() << "          to: " << *Store << "\n");
02275     return true;
02276   }
02277 
02278   bool rewriteIntegerStore(Value *V, StoreInst &SI) {
02279     assert(IntTy && "We cannot extract an integer from the alloca");
02280     assert(!SI.isVolatile());
02281     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
02282       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02283                                          "oldload");
02284       Old = convertValue(DL, IRB, Old, IntTy);
02285       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02286       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
02287       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
02288                         "insert");
02289     }
02290     V = convertValue(DL, IRB, V, NewAllocaTy);
02291     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02292     Pass.DeadInsts.insert(&SI);
02293     (void)Store;
02294     DEBUG(dbgs() << "          to: " << *Store << "\n");
02295     return true;
02296   }
02297 
02298   bool visitStoreInst(StoreInst &SI) {
02299     DEBUG(dbgs() << "    original: " << SI << "\n");
02300     Value *OldOp = SI.getOperand(1);
02301     assert(OldOp == OldPtr);
02302 
02303     Value *V = SI.getValueOperand();
02304 
02305     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02306     // alloca that should be re-examined after promoting this alloca.
02307     if (V->getType()->isPointerTy())
02308       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
02309         Pass.PostPromotionWorklist.insert(AI);
02310 
02311     if (SliceSize < DL.getTypeStoreSize(V->getType())) {
02312       assert(!SI.isVolatile());
02313       assert(V->getType()->isIntegerTy() &&
02314              "Only integer type loads and stores are split");
02315       assert(V->getType()->getIntegerBitWidth() ==
02316              DL.getTypeStoreSizeInBits(V->getType()) &&
02317              "Non-byte-multiple bit width");
02318       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
02319       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
02320                          "extract");
02321     }
02322 
02323     if (VecTy)
02324       return rewriteVectorizedStoreInst(V, SI, OldOp);
02325     if (IntTy && V->getType()->isIntegerTy())
02326       return rewriteIntegerStore(V, SI);
02327 
02328     StoreInst *NewSI;
02329     if (NewBeginOffset == NewAllocaBeginOffset &&
02330         NewEndOffset == NewAllocaEndOffset &&
02331         canConvertValue(DL, V->getType(), NewAllocaTy)) {
02332       V = convertValue(DL, IRB, V, NewAllocaTy);
02333       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02334                                      SI.isVolatile());
02335     } else {
02336       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
02337       NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
02338                                      SI.isVolatile());
02339     }
02340     (void)NewSI;
02341     Pass.DeadInsts.insert(&SI);
02342     deleteIfTriviallyDead(OldOp);
02343 
02344     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
02345     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
02346   }
02347 
02348   /// \brief Compute an integer value from splatting an i8 across the given
02349   /// number of bytes.
02350   ///
02351   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
02352   /// call this routine.
02353   /// FIXME: Heed the advice above.
02354   ///
02355   /// \param V The i8 value to splat.
02356   /// \param Size The number of bytes in the output (assuming i8 is one byte)
02357   Value *getIntegerSplat(Value *V, unsigned Size) {
02358     assert(Size > 0 && "Expected a positive number of bytes.");
02359     IntegerType *VTy = cast<IntegerType>(V->getType());
02360     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
02361     if (Size == 1)
02362       return V;
02363 
02364     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
02365     V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
02366                       ConstantExpr::getUDiv(
02367                         Constant::getAllOnesValue(SplatIntTy),
02368                         ConstantExpr::getZExt(
02369                           Constant::getAllOnesValue(V->getType()),
02370                           SplatIntTy)),
02371                       "isplat");
02372     return V;
02373   }
02374 
02375   /// \brief Compute a vector splat for a given element value.
02376   Value *getVectorSplat(Value *V, unsigned NumElements) {
02377     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
02378     DEBUG(dbgs() << "       splat: " << *V << "\n");
02379     return V;
02380   }
02381 
02382   bool visitMemSetInst(MemSetInst &II) {
02383     DEBUG(dbgs() << "    original: " << II << "\n");
02384     assert(II.getRawDest() == OldPtr);
02385 
02386     // If the memset has a variable size, it cannot be split, just adjust the
02387     // pointer to the new alloca.
02388     if (!isa<Constant>(II.getLength())) {
02389       assert(!IsSplit);
02390       assert(NewBeginOffset == BeginOffset);
02391       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
02392       Type *CstTy = II.getAlignmentCst()->getType();
02393       II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
02394 
02395       deleteIfTriviallyDead(OldPtr);
02396       return false;
02397     }
02398 
02399     // Record this instruction for deletion.
02400     Pass.DeadInsts.insert(&II);
02401 
02402     Type *AllocaTy = NewAI.getAllocatedType();
02403     Type *ScalarTy = AllocaTy->getScalarType();
02404 
02405     // If this doesn't map cleanly onto the alloca type, and that type isn't
02406     // a single value type, just emit a memset.
02407     if (!VecTy && !IntTy &&
02408         (BeginOffset > NewAllocaBeginOffset ||
02409          EndOffset < NewAllocaEndOffset ||
02410          !AllocaTy->isSingleValueType() ||
02411          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
02412          DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
02413       Type *SizeTy = II.getLength()->getType();
02414       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02415       CallInst *New = IRB.CreateMemSet(
02416           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
02417           getSliceAlign(), II.isVolatile());
02418       (void)New;
02419       DEBUG(dbgs() << "          to: " << *New << "\n");
02420       return false;
02421     }
02422 
02423     // If we can represent this as a simple value, we have to build the actual
02424     // value to store, which requires expanding the byte present in memset to
02425     // a sensible representation for the alloca type. This is essentially
02426     // splatting the byte to a sufficiently wide integer, splatting it across
02427     // any desired vector width, and bitcasting to the final type.
02428     Value *V;
02429 
02430     if (VecTy) {
02431       // If this is a memset of a vectorized alloca, insert it.
02432       assert(ElementTy == ScalarTy);
02433 
02434       unsigned BeginIndex = getIndex(NewBeginOffset);
02435       unsigned EndIndex = getIndex(NewEndOffset);
02436       assert(EndIndex > BeginIndex && "Empty vector!");
02437       unsigned NumElements = EndIndex - BeginIndex;
02438       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02439 
02440       Value *Splat =
02441           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
02442       Splat = convertValue(DL, IRB, Splat, ElementTy);
02443       if (NumElements > 1)
02444         Splat = getVectorSplat(Splat, NumElements);
02445 
02446       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02447                                          "oldload");
02448       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
02449     } else if (IntTy) {
02450       // If this is a memset on an alloca where we can widen stores, insert the
02451       // set integer.
02452       assert(!II.isVolatile());
02453 
02454       uint64_t Size = NewEndOffset - NewBeginOffset;
02455       V = getIntegerSplat(II.getValue(), Size);
02456 
02457       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
02458                     EndOffset != NewAllocaBeginOffset)) {
02459         Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02460                                            "oldload");
02461         Old = convertValue(DL, IRB, Old, IntTy);
02462         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02463         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
02464       } else {
02465         assert(V->getType() == IntTy &&
02466                "Wrong type for an alloca wide integer!");
02467       }
02468       V = convertValue(DL, IRB, V, AllocaTy);
02469     } else {
02470       // Established these invariants above.
02471       assert(NewBeginOffset == NewAllocaBeginOffset);
02472       assert(NewEndOffset == NewAllocaEndOffset);
02473 
02474       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
02475       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
02476         V = getVectorSplat(V, AllocaVecTy->getNumElements());
02477 
02478       V = convertValue(DL, IRB, V, AllocaTy);
02479     }
02480 
02481     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02482                                         II.isVolatile());
02483     (void)New;
02484     DEBUG(dbgs() << "          to: " << *New << "\n");
02485     return !II.isVolatile();
02486   }
02487 
02488   bool visitMemTransferInst(MemTransferInst &II) {
02489     // Rewriting of memory transfer instructions can be a bit tricky. We break
02490     // them into two categories: split intrinsics and unsplit intrinsics.
02491 
02492     DEBUG(dbgs() << "    original: " << II << "\n");
02493 
02494     bool IsDest = &II.getRawDestUse() == OldUse;
02495     assert((IsDest && II.getRawDest() == OldPtr) ||
02496            (!IsDest && II.getRawSource() == OldPtr));
02497 
02498     unsigned SliceAlign = getSliceAlign();
02499 
02500     // For unsplit intrinsics, we simply modify the source and destination
02501     // pointers in place. This isn't just an optimization, it is a matter of
02502     // correctness. With unsplit intrinsics we may be dealing with transfers
02503     // within a single alloca before SROA ran, or with transfers that have
02504     // a variable length. We may also be dealing with memmove instead of
02505     // memcpy, and so simply updating the pointers is the necessary for us to
02506     // update both source and dest of a single call.
02507     if (!IsSplittable) {
02508       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02509       if (IsDest)
02510         II.setDest(AdjustedPtr);
02511       else
02512         II.setSource(AdjustedPtr);
02513 
02514       if (II.getAlignment() > SliceAlign) {
02515         Type *CstTy = II.getAlignmentCst()->getType();
02516         II.setAlignment(
02517             ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
02518       }
02519 
02520       DEBUG(dbgs() << "          to: " << II << "\n");
02521       deleteIfTriviallyDead(OldPtr);
02522       return false;
02523     }
02524     // For split transfer intrinsics we have an incredibly useful assurance:
02525     // the source and destination do not reside within the same alloca, and at
02526     // least one of them does not escape. This means that we can replace
02527     // memmove with memcpy, and we don't need to worry about all manner of
02528     // downsides to splitting and transforming the operations.
02529 
02530     // If this doesn't map cleanly onto the alloca type, and that type isn't
02531     // a single value type, just emit a memcpy.
02532     bool EmitMemCpy
02533       = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
02534                              EndOffset < NewAllocaEndOffset ||
02535                              !NewAI.getAllocatedType()->isSingleValueType());
02536 
02537     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
02538     // size hasn't been shrunk based on analysis of the viable range, this is
02539     // a no-op.
02540     if (EmitMemCpy && &OldAI == &NewAI) {
02541       // Ensure the start lines up.
02542       assert(NewBeginOffset == BeginOffset);
02543 
02544       // Rewrite the size as needed.
02545       if (NewEndOffset != EndOffset)
02546         II.setLength(ConstantInt::get(II.getLength()->getType(),
02547                                       NewEndOffset - NewBeginOffset));
02548       return false;
02549     }
02550     // Record this instruction for deletion.
02551     Pass.DeadInsts.insert(&II);
02552 
02553     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02554     // alloca that should be re-examined after rewriting this instruction.
02555     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
02556     if (AllocaInst *AI
02557           = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
02558       assert(AI != &OldAI && AI != &NewAI &&
02559              "Splittable transfers cannot reach the same alloca on both ends.");
02560       Pass.Worklist.insert(AI);
02561     }
02562 
02563     Type *OtherPtrTy = OtherPtr->getType();
02564     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
02565 
02566     // Compute the relative offset for the other pointer within the transfer.
02567     unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
02568     APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
02569     unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
02570                                    OtherOffset.zextOrTrunc(64).getZExtValue());
02571 
02572     if (EmitMemCpy) {
02573       // Compute the other pointer, folding as much as possible to produce
02574       // a single, simple GEP in most cases.
02575       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02576                                 OtherPtr->getName() + ".");
02577 
02578       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02579       Type *SizeTy = II.getLength()->getType();
02580       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02581 
02582       CallInst *New = IRB.CreateMemCpy(
02583           IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
02584           MinAlign(SliceAlign, OtherAlign), II.isVolatile());
02585       (void)New;
02586       DEBUG(dbgs() << "          to: " << *New << "\n");
02587       return false;
02588     }
02589 
02590     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
02591                          NewEndOffset == NewAllocaEndOffset;
02592     uint64_t Size = NewEndOffset - NewBeginOffset;
02593     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
02594     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
02595     unsigned NumElements = EndIndex - BeginIndex;
02596     IntegerType *SubIntTy
02597       = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
02598 
02599     // Reset the other pointer type to match the register type we're going to
02600     // use, but using the address space of the original other pointer.
02601     if (VecTy && !IsWholeAlloca) {
02602       if (NumElements == 1)
02603         OtherPtrTy = VecTy->getElementType();
02604       else
02605         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
02606 
02607       OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
02608     } else if (IntTy && !IsWholeAlloca) {
02609       OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
02610     } else {
02611       OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
02612     }
02613 
02614     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02615                                    OtherPtr->getName() + ".");
02616     unsigned SrcAlign = OtherAlign;
02617     Value *DstPtr = &NewAI;
02618     unsigned DstAlign = SliceAlign;
02619     if (!IsDest) {
02620       std::swap(SrcPtr, DstPtr);
02621       std::swap(SrcAlign, DstAlign);
02622     }
02623 
02624     Value *Src;
02625     if (VecTy && !IsWholeAlloca && !IsDest) {
02626       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02627                                   "load");
02628       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
02629     } else if (IntTy && !IsWholeAlloca && !IsDest) {
02630       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02631                                   "load");
02632       Src = convertValue(DL, IRB, Src, IntTy);
02633       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02634       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
02635     } else {
02636       Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
02637                                   "copyload");
02638     }
02639 
02640     if (VecTy && !IsWholeAlloca && IsDest) {
02641       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02642                                          "oldload");
02643       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
02644     } else if (IntTy && !IsWholeAlloca && IsDest) {
02645       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02646                                          "oldload");
02647       Old = convertValue(DL, IRB, Old, IntTy);
02648       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02649       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
02650       Src = convertValue(DL, IRB, Src, NewAllocaTy);
02651     }
02652 
02653     StoreInst *Store = cast<StoreInst>(
02654         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
02655     (void)Store;
02656     DEBUG(dbgs() << "          to: " << *Store << "\n");
02657     return !II.isVolatile();
02658   }
02659 
02660   bool visitIntrinsicInst(IntrinsicInst &II) {
02661     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
02662            II.getIntrinsicID() == Intrinsic::lifetime_end);
02663     DEBUG(dbgs() << "    original: " << II << "\n");
02664     assert(II.getArgOperand(1) == OldPtr);
02665 
02666     // Record this instruction for deletion.
02667     Pass.DeadInsts.insert(&II);
02668 
02669     ConstantInt *Size
02670       = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
02671                          NewEndOffset - NewBeginOffset);
02672     Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02673     Value *New;
02674     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
02675       New = IRB.CreateLifetimeStart(Ptr, Size);
02676     else
02677       New = IRB.CreateLifetimeEnd(Ptr, Size);
02678 
02679     (void)New;
02680     DEBUG(dbgs() << "          to: " << *New << "\n");
02681     return true;
02682   }
02683 
02684   bool visitPHINode(PHINode &PN) {
02685     DEBUG(dbgs() << "    original: " << PN << "\n");
02686     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
02687     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
02688 
02689     // We would like to compute a new pointer in only one place, but have it be
02690     // as local as possible to the PHI. To do that, we re-use the location of
02691     // the old pointer, which necessarily must be in the right position to
02692     // dominate the PHI.
02693     IRBuilderTy PtrBuilder(IRB);
02694     PtrBuilder.SetInsertPoint(OldPtr);
02695     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
02696 
02697     Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
02698     // Replace the operands which were using the old pointer.
02699     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
02700 
02701     DEBUG(dbgs() << "          to: " << PN << "\n");
02702     deleteIfTriviallyDead(OldPtr);
02703 
02704     // PHIs can't be promoted on their own, but often can be speculated. We
02705     // check the speculation outside of the rewriter so that we see the
02706     // fully-rewritten alloca.
02707     PHIUsers.insert(&PN);
02708     return true;
02709   }
02710 
02711   bool visitSelectInst(SelectInst &SI) {
02712     DEBUG(dbgs() << "    original: " << SI << "\n");
02713     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
02714            "Pointer isn't an operand!");
02715     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
02716     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
02717 
02718     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02719     // Replace the operands which were using the old pointer.
02720     if (SI.getOperand(1) == OldPtr)
02721       SI.setOperand(1, NewPtr);
02722     if (SI.getOperand(2) == OldPtr)
02723       SI.setOperand(2, NewPtr);
02724 
02725     DEBUG(dbgs() << "          to: " << SI << "\n");
02726     deleteIfTriviallyDead(OldPtr);
02727 
02728     // Selects can't be promoted on their own, but often can be speculated. We
02729     // check the speculation outside of the rewriter so that we see the
02730     // fully-rewritten alloca.
02731     SelectUsers.insert(&SI);
02732     return true;
02733   }
02734 
02735 };
02736 }
02737 
02738 namespace {
02739 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
02740 ///
02741 /// This pass aggressively rewrites all aggregate loads and stores on
02742 /// a particular pointer (or any pointer derived from it which we can identify)
02743 /// with scalar loads and stores.
02744 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
02745   // Befriend the base class so it can delegate to private visit methods.
02746   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
02747 
02748   const DataLayout &DL;
02749 
02750   /// Queue of pointer uses to analyze and potentially rewrite.
02751   SmallVector<Use *, 8> Queue;
02752 
02753   /// Set to prevent us from cycling with phi nodes and loops.
02754   SmallPtrSet<User *, 8> Visited;
02755 
02756   /// The current pointer use being rewritten. This is used to dig up the used
02757   /// value (as opposed to the user).
02758   Use *U;
02759 
02760 public:
02761   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
02762 
02763   /// Rewrite loads and stores through a pointer and all pointers derived from
02764   /// it.
02765   bool rewrite(Instruction &I) {
02766     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
02767     enqueueUsers(I);
02768     bool Changed = false;
02769     while (!Queue.empty()) {
02770       U = Queue.pop_back_val();
02771       Changed |= visit(cast<Instruction>(U->getUser()));
02772     }
02773     return Changed;
02774   }
02775 
02776 private:
02777   /// Enqueue all the users of the given instruction for further processing.
02778   /// This uses a set to de-duplicate users.
02779   void enqueueUsers(Instruction &I) {
02780     for (Use &U : I.uses())
02781       if (Visited.insert(U.getUser()))
02782         Queue.push_back(&U);
02783   }
02784 
02785   // Conservative default is to not rewrite anything.
02786   bool visitInstruction(Instruction &I) { return false; }
02787 
02788   /// \brief Generic recursive split emission class.
02789   template <typename Derived>
02790   class OpSplitter {
02791   protected:
02792     /// The builder used to form new instructions.
02793     IRBuilderTy IRB;
02794     /// The indices which to be used with insert- or extractvalue to select the
02795     /// appropriate value within the aggregate.
02796     SmallVector<unsigned, 4> Indices;
02797     /// The indices to a GEP instruction which will move Ptr to the correct slot
02798     /// within the aggregate.
02799     SmallVector<Value *, 4> GEPIndices;
02800     /// The base pointer of the original op, used as a base for GEPing the
02801     /// split operations.
02802     Value *Ptr;
02803 
02804     /// Initialize the splitter with an insertion point, Ptr and start with a
02805     /// single zero GEP index.
02806     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
02807       : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
02808 
02809   public:
02810     /// \brief Generic recursive split emission routine.
02811     ///
02812     /// This method recursively splits an aggregate op (load or store) into
02813     /// scalar or vector ops. It splits recursively until it hits a single value
02814     /// and emits that single value operation via the template argument.
02815     ///
02816     /// The logic of this routine relies on GEPs and insertvalue and
02817     /// extractvalue all operating with the same fundamental index list, merely
02818     /// formatted differently (GEPs need actual values).
02819     ///
02820     /// \param Ty  The type being split recursively into smaller ops.
02821     /// \param Agg The aggregate value being built up or stored, depending on
02822     /// whether this is splitting a load or a store respectively.
02823     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
02824       if (Ty->isSingleValueType())
02825         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
02826 
02827       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
02828         unsigned OldSize = Indices.size();
02829         (void)OldSize;
02830         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
02831              ++Idx) {
02832           assert(Indices.size() == OldSize && "Did not return to the old size");
02833           Indices.push_back(Idx);
02834           GEPIndices.push_back(IRB.getInt32(Idx));
02835           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
02836           GEPIndices.pop_back();
02837           Indices.pop_back();
02838         }
02839         return;
02840       }
02841 
02842       if (StructType *STy = dyn_cast<StructType>(Ty)) {
02843         unsigned OldSize = Indices.size();
02844         (void)OldSize;
02845         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
02846              ++Idx) {
02847           assert(Indices.size() == OldSize && "Did not return to the old size");
02848           Indices.push_back(Idx);
02849           GEPIndices.push_back(IRB.getInt32(Idx));
02850           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
02851           GEPIndices.pop_back();
02852           Indices.pop_back();
02853         }
02854         return;
02855       }
02856 
02857       llvm_unreachable("Only arrays and structs are aggregate loadable types");
02858     }
02859   };
02860 
02861   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
02862     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
02863       : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
02864 
02865     /// Emit a leaf load of a single value. This is called at the leaves of the
02866     /// recursive emission to actually load values.
02867     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
02868       assert(Ty->isSingleValueType());
02869       // Load the single value and insert it using the indices.
02870       Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
02871       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
02872       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
02873       DEBUG(dbgs() << "          to: " << *Load << "\n");
02874     }
02875   };
02876 
02877   bool visitLoadInst(LoadInst &LI) {
02878     assert(LI.getPointerOperand() == *U);
02879     if (!LI.isSimple() || LI.getType()->isSingleValueType())
02880       return false;
02881 
02882     // We have an aggregate being loaded, split it apart.
02883     DEBUG(dbgs() << "    original: " << LI << "\n");
02884     LoadOpSplitter Splitter(&LI, *U);
02885     Value *V = UndefValue::get(LI.getType());
02886     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
02887     LI.replaceAllUsesWith(V);
02888     LI.eraseFromParent();
02889     return true;
02890   }
02891 
02892   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
02893     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
02894       : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
02895 
02896     /// Emit a leaf store of a single value. This is called at the leaves of the
02897     /// recursive emission to actually produce stores.
02898     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
02899       assert(Ty->isSingleValueType());
02900       // Extract the single value and store it using the indices.
02901       Value *Store = IRB.CreateStore(
02902         IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
02903         IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
02904       (void)Store;
02905       DEBUG(dbgs() << "          to: " << *Store << "\n");
02906     }
02907   };
02908 
02909   bool visitStoreInst(StoreInst &SI) {
02910     if (!SI.isSimple() || SI.getPointerOperand() != *U)
02911       return false;
02912     Value *V = SI.getValueOperand();
02913     if (V->getType()->isSingleValueType())
02914       return false;
02915 
02916     // We have an aggregate being stored, split it apart.
02917     DEBUG(dbgs() << "    original: " << SI << "\n");
02918     StoreOpSplitter Splitter(&SI, *U);
02919     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
02920     SI.eraseFromParent();
02921     return true;
02922   }
02923 
02924   bool visitBitCastInst(BitCastInst &BC) {
02925     enqueueUsers(BC);
02926     return false;
02927   }
02928 
02929   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
02930     enqueueUsers(GEPI);
02931     return false;
02932   }
02933 
02934   bool visitPHINode(PHINode &PN) {
02935     enqueueUsers(PN);
02936     return false;
02937   }
02938 
02939   bool visitSelectInst(SelectInst &SI) {
02940     enqueueUsers(SI);
02941     return false;
02942   }
02943 };
02944 }
02945 
02946 /// \brief Strip aggregate type wrapping.
02947 ///
02948 /// This removes no-op aggregate types wrapping an underlying type. It will
02949 /// strip as many layers of types as it can without changing either the type
02950 /// size or the allocated size.
02951 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
02952   if (Ty->isSingleValueType())
02953     return Ty;
02954 
02955   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
02956   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
02957 
02958   Type *InnerTy;
02959   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
02960     InnerTy = ArrTy->getElementType();
02961   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
02962     const StructLayout *SL = DL.getStructLayout(STy);
02963     unsigned Index = SL->getElementContainingOffset(0);
02964     InnerTy = STy->getElementType(Index);
02965   } else {
02966     return Ty;
02967   }
02968 
02969   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
02970       TypeSize > DL.getTypeSizeInBits(InnerTy))
02971     return Ty;
02972 
02973   return stripAggregateTypeWrapping(DL, InnerTy);
02974 }
02975 
02976 /// \brief Try to find a partition of the aggregate type passed in for a given
02977 /// offset and size.
02978 ///
02979 /// This recurses through the aggregate type and tries to compute a subtype
02980 /// based on the offset and size. When the offset and size span a sub-section
02981 /// of an array, it will even compute a new array type for that sub-section,
02982 /// and the same for structs.
02983 ///
02984 /// Note that this routine is very strict and tries to find a partition of the
02985 /// type which produces the *exact* right offset and size. It is not forgiving
02986 /// when the size or offset cause either end of type-based partition to be off.
02987 /// Also, this is a best-effort routine. It is reasonable to give up and not
02988 /// return a type if necessary.
02989 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
02990                               uint64_t Offset, uint64_t Size) {
02991   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
02992     return stripAggregateTypeWrapping(DL, Ty);
02993   if (Offset > DL.getTypeAllocSize(Ty) ||
02994       (DL.getTypeAllocSize(Ty) - Offset) < Size)
02995     return 0;
02996 
02997   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
02998     // We can't partition pointers...
02999     if (SeqTy->isPointerTy())
03000       return 0;
03001 
03002     Type *ElementTy = SeqTy->getElementType();
03003     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03004     uint64_t NumSkippedElements = Offset / ElementSize;
03005     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
03006       if (NumSkippedElements >= ArrTy->getNumElements())
03007         return 0;
03008     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
03009       if (NumSkippedElements >= VecTy->getNumElements())
03010         return 0;
03011     }
03012     Offset -= NumSkippedElements * ElementSize;
03013 
03014     // First check if we need to recurse.
03015     if (Offset > 0 || Size < ElementSize) {
03016       // Bail if the partition ends in a different array element.
03017       if ((Offset + Size) > ElementSize)
03018         return 0;
03019       // Recurse through the element type trying to peel off offset bytes.
03020       return getTypePartition(DL, ElementTy, Offset, Size);
03021     }
03022     assert(Offset == 0);
03023 
03024     if (Size == ElementSize)
03025       return stripAggregateTypeWrapping(DL, ElementTy);
03026     assert(Size > ElementSize);
03027     uint64_t NumElements = Size / ElementSize;
03028     if (NumElements * ElementSize != Size)
03029       return 0;
03030     return ArrayType::get(ElementTy, NumElements);
03031   }
03032 
03033   StructType *STy = dyn_cast<StructType>(Ty);
03034   if (!STy)
03035     return 0;
03036 
03037   const StructLayout *SL = DL.getStructLayout(STy);
03038   if (Offset >= SL->getSizeInBytes())
03039     return 0;
03040   uint64_t EndOffset = Offset + Size;
03041   if (EndOffset > SL->getSizeInBytes())
03042     return 0;
03043 
03044   unsigned Index = SL->getElementContainingOffset(Offset);
03045   Offset -= SL->getElementOffset(Index);
03046 
03047   Type *ElementTy = STy->getElementType(Index);
03048   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03049   if (Offset >= ElementSize)
03050     return 0; // The offset points into alignment padding.
03051 
03052   // See if any partition must be contained by the element.
03053   if (Offset > 0 || Size < ElementSize) {
03054     if ((Offset + Size) > ElementSize)
03055       return 0;
03056     return getTypePartition(DL, ElementTy, Offset, Size);
03057   }
03058   assert(Offset == 0);
03059 
03060   if (Size == ElementSize)
03061     return stripAggregateTypeWrapping(DL, ElementTy);
03062 
03063   StructType::element_iterator EI = STy->element_begin() + Index,
03064                                EE = STy->element_end();
03065   if (EndOffset < SL->getSizeInBytes()) {
03066     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
03067     if (Index == EndIndex)
03068       return 0; // Within a single element and its padding.
03069 
03070     // Don't try to form "natural" types if the elements don't line up with the
03071     // expected size.
03072     // FIXME: We could potentially recurse down through the last element in the
03073     // sub-struct to find a natural end point.
03074     if (SL->getElementOffset(EndIndex) != EndOffset)
03075       return 0;
03076 
03077     assert(Index < EndIndex);
03078     EE = STy->element_begin() + EndIndex;
03079   }
03080 
03081   // Try to build up a sub-structure.
03082   StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
03083                                       STy->isPacked());
03084   const StructLayout *SubSL = DL.getStructLayout(SubTy);
03085   if (Size != SubSL->getSizeInBytes())
03086     return 0; // The sub-struct doesn't have quite the size needed.
03087 
03088   return SubTy;
03089 }
03090 
03091 /// \brief Rewrite an alloca partition's users.
03092 ///
03093 /// This routine drives both of the rewriting goals of the SROA pass. It tries
03094 /// to rewrite uses of an alloca partition to be conducive for SSA value
03095 /// promotion. If the partition needs a new, more refined alloca, this will
03096 /// build that new alloca, preserving as much type information as possible, and
03097 /// rewrite the uses of the old alloca to point at the new one and have the
03098 /// appropriate new offsets. It also evaluates how successful the rewrite was
03099 /// at enabling promotion and if it was successful queues the alloca to be
03100 /// promoted.
03101 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
03102                             AllocaSlices::iterator B, AllocaSlices::iterator E,
03103                             int64_t BeginOffset, int64_t EndOffset,
03104                             ArrayRef<AllocaSlices::iterator> SplitUses) {
03105   assert(BeginOffset < EndOffset);
03106   uint64_t SliceSize = EndOffset - BeginOffset;
03107 
03108   // Try to compute a friendly type for this partition of the alloca. This
03109   // won't always succeed, in which case we fall back to a legal integer type
03110   // or an i8 array of an appropriate size.
03111   Type *SliceTy = 0;
03112   if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
03113     if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
03114       SliceTy = CommonUseTy;
03115   if (!SliceTy)
03116     if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
03117                                                  BeginOffset, SliceSize))
03118       SliceTy = TypePartitionTy;
03119   if ((!SliceTy || (SliceTy->isArrayTy() &&
03120                     SliceTy->getArrayElementType()->isIntegerTy())) &&
03121       DL->isLegalInteger(SliceSize * 8))
03122     SliceTy = Type::getIntNTy(*C, SliceSize * 8);
03123   if (!SliceTy)
03124     SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
03125   assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
03126 
03127   bool IsVectorPromotable = isVectorPromotionViable(
03128       *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
03129 
03130   bool IsIntegerPromotable =
03131       !IsVectorPromotable &&
03132       isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
03133 
03134   // Check for the case where we're going to rewrite to a new alloca of the
03135   // exact same type as the original, and with the same access offsets. In that
03136   // case, re-use the existing alloca, but still run through the rewriter to
03137   // perform phi and select speculation.
03138   AllocaInst *NewAI;
03139   if (SliceTy == AI.getAllocatedType()) {
03140     assert(BeginOffset == 0 &&
03141            "Non-zero begin offset but same alloca type");
03142     NewAI = &AI;
03143     // FIXME: We should be able to bail at this point with "nothing changed".
03144     // FIXME: We might want to defer PHI speculation until after here.
03145   } else {
03146     unsigned Alignment = AI.getAlignment();
03147     if (!Alignment) {
03148       // The minimum alignment which users can rely on when the explicit
03149       // alignment is omitted or zero is that required by the ABI for this
03150       // type.
03151       Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
03152     }
03153     Alignment = MinAlign(Alignment, BeginOffset);
03154     // If we will get at least this much alignment from the type alone, leave
03155     // the alloca's alignment unconstrained.
03156     if (Alignment <= DL->getABITypeAlignment(SliceTy))
03157       Alignment = 0;
03158     NewAI = new AllocaInst(SliceTy, 0, Alignment,
03159                            AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
03160     ++NumNewAllocas;
03161   }
03162 
03163   DEBUG(dbgs() << "Rewriting alloca partition "
03164                << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
03165                << "\n");
03166 
03167   // Track the high watermark on the worklist as it is only relevant for
03168   // promoted allocas. We will reset it to this point if the alloca is not in
03169   // fact scheduled for promotion.
03170   unsigned PPWOldSize = PostPromotionWorklist.size();
03171   unsigned NumUses = 0;
03172   SmallPtrSet<PHINode *, 8> PHIUsers;
03173   SmallPtrSet<SelectInst *, 8> SelectUsers;
03174 
03175   AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
03176                                EndOffset, IsVectorPromotable,
03177                                IsIntegerPromotable, PHIUsers, SelectUsers);
03178   bool Promotable = true;
03179   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
03180                                                         SUE = SplitUses.end();
03181        SUI != SUE; ++SUI) {
03182     DEBUG(dbgs() << "  rewriting split ");
03183     DEBUG(S.printSlice(dbgs(), *SUI, ""));
03184     Promotable &= Rewriter.visit(*SUI);
03185     ++NumUses;
03186   }
03187   for (AllocaSlices::iterator I = B; I != E; ++I) {
03188     DEBUG(dbgs() << "  rewriting ");
03189     DEBUG(S.printSlice(dbgs(), I, ""));
03190     Promotable &= Rewriter.visit(I);
03191     ++NumUses;
03192   }
03193 
03194   NumAllocaPartitionUses += NumUses;
03195   MaxUsesPerAllocaPartition =
03196       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
03197 
03198   // Now that we've processed all the slices in the new partition, check if any
03199   // PHIs or Selects would block promotion.
03200   for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
03201                                             E = PHIUsers.end();
03202        I != E; ++I)
03203     if (!isSafePHIToSpeculate(**I, DL)) {
03204       Promotable = false;
03205       PHIUsers.clear();
03206       SelectUsers.clear();
03207       break;
03208     }
03209   for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
03210                                                E = SelectUsers.end();
03211        I != E; ++I)
03212     if (!isSafeSelectToSpeculate(**I, DL)) {
03213       Promotable = false;
03214       PHIUsers.clear();
03215       SelectUsers.clear();
03216       break;
03217     }
03218 
03219   if (Promotable) {
03220     if (PHIUsers.empty() && SelectUsers.empty()) {
03221       // Promote the alloca.
03222       PromotableAllocas.push_back(NewAI);
03223     } else {
03224       // If we have either PHIs or Selects to speculate, add them to those
03225       // worklists and re-queue the new alloca so that we promote in on the
03226       // next iteration.
03227       for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
03228                                                 E = PHIUsers.end();
03229            I != E; ++I)
03230         SpeculatablePHIs.insert(*I);
03231       for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
03232                                                    E = SelectUsers.end();
03233            I != E; ++I)
03234         SpeculatableSelects.insert(*I);
03235       Worklist.insert(NewAI);
03236     }
03237   } else {
03238     // If we can't promote the alloca, iterate on it to check for new
03239     // refinements exposed by splitting the current alloca. Don't iterate on an
03240     // alloca which didn't actually change and didn't get promoted.
03241     if (NewAI != &AI)
03242       Worklist.insert(NewAI);
03243 
03244     // Drop any post-promotion work items if promotion didn't happen.
03245     while (PostPromotionWorklist.size() > PPWOldSize)
03246       PostPromotionWorklist.pop_back();
03247   }
03248 
03249   return true;
03250 }
03251 
03252 static void
03253 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
03254                         uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
03255   if (Offset >= MaxSplitUseEndOffset) {
03256     SplitUses.clear();
03257     MaxSplitUseEndOffset = 0;
03258     return;
03259   }
03260 
03261   size_t SplitUsesOldSize = SplitUses.size();
03262   SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
03263                                  [Offset](const AllocaSlices::iterator &I) {
03264                     return I->endOffset() <= Offset;
03265                   }),
03266                   SplitUses.end());
03267   if (SplitUsesOldSize == SplitUses.size())
03268     return;
03269 
03270   // Recompute the max. While this is linear, so is remove_if.
03271   MaxSplitUseEndOffset = 0;
03272   for (SmallVectorImpl<AllocaSlices::iterator>::iterator
03273            SUI = SplitUses.begin(),
03274            SUE = SplitUses.end();
03275        SUI != SUE; ++SUI)
03276     MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
03277 }
03278 
03279 /// \brief Walks the slices of an alloca and form partitions based on them,
03280 /// rewriting each of their uses.
03281 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
03282   if (S.begin() == S.end())
03283     return false;
03284 
03285   unsigned NumPartitions = 0;
03286   bool Changed = false;
03287   SmallVector<AllocaSlices::iterator, 4> SplitUses;
03288   uint64_t MaxSplitUseEndOffset = 0;
03289 
03290   uint64_t BeginOffset = S.begin()->beginOffset();
03291 
03292   for (AllocaSlices::iterator SI = S.begin(), SJ = std::next(SI), SE = S.end();
03293        SI != SE; SI = SJ) {
03294     uint64_t MaxEndOffset = SI->endOffset();
03295 
03296     if (!SI->isSplittable()) {
03297       // When we're forming an unsplittable region, it must always start at the
03298       // first slice and will extend through its end.
03299       assert(BeginOffset == SI->beginOffset());
03300 
03301       // Form a partition including all of the overlapping slices with this
03302       // unsplittable slice.
03303       while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
03304         if (!SJ->isSplittable())
03305           MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
03306         ++SJ;
03307       }
03308     } else {
03309       assert(SI->isSplittable()); // Established above.
03310 
03311       // Collect all of the overlapping splittable slices.
03312       while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
03313              SJ->isSplittable()) {
03314         MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
03315         ++SJ;
03316       }
03317 
03318       // Back up MaxEndOffset and SJ if we ended the span early when
03319       // encountering an unsplittable slice.
03320       if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
03321         assert(!SJ->isSplittable());
03322         MaxEndOffset = SJ->beginOffset();
03323       }
03324     }
03325 
03326     // Check if we have managed to move the end offset forward yet. If so,
03327     // we'll have to rewrite uses and erase old split uses.
03328     if (BeginOffset < MaxEndOffset) {
03329       // Rewrite a sequence of overlapping slices.
03330       Changed |=
03331           rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
03332       ++NumPartitions;
03333 
03334       removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
03335     }
03336 
03337     // Accumulate all the splittable slices from the [SI,SJ) region which
03338     // overlap going forward.
03339     for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
03340       if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
03341         SplitUses.push_back(SK);
03342         MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
03343       }
03344 
03345     // If we're already at the end and we have no split uses, we're done.
03346     if (SJ == SE && SplitUses.empty())
03347       break;
03348 
03349     // If we have no split uses or no gap in offsets, we're ready to move to
03350     // the next slice.
03351     if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
03352       BeginOffset = SJ->beginOffset();
03353       continue;
03354     }
03355 
03356     // Even if we have split slices, if the next slice is splittable and the
03357     // split slices reach it, we can simply set up the beginning offset of the
03358     // next iteration to bridge between them.
03359     if (SJ != SE && SJ->isSplittable() &&
03360         MaxSplitUseEndOffset > SJ->beginOffset()) {
03361       BeginOffset = MaxEndOffset;
03362       continue;
03363     }
03364 
03365     // Otherwise, we have a tail of split slices. Rewrite them with an empty
03366     // range of slices.
03367     uint64_t PostSplitEndOffset =
03368         SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
03369 
03370     Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
03371                                 SplitUses);
03372     ++NumPartitions;
03373 
03374     if (SJ == SE)
03375       break; // Skip the rest, we don't need to do any cleanup.
03376 
03377     removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
03378                             PostSplitEndOffset);
03379 
03380     // Now just reset the begin offset for the next iteration.
03381     BeginOffset = SJ->beginOffset();
03382   }
03383 
03384   NumAllocaPartitions += NumPartitions;
03385   MaxPartitionsPerAlloca =
03386       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
03387 
03388   return Changed;
03389 }
03390 
03391 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
03392 void SROA::clobberUse(Use &U) {
03393   Value *OldV = U;
03394   // Replace the use with an undef value.
03395   U = UndefValue::get(OldV->getType());
03396 
03397   // Check for this making an instruction dead. We have to garbage collect
03398   // all the dead instructions to ensure the uses of any alloca end up being
03399   // minimal.
03400   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
03401     if (isInstructionTriviallyDead(OldI)) {
03402       DeadInsts.insert(OldI);
03403     }
03404 }
03405 
03406 /// \brief Analyze an alloca for SROA.
03407 ///
03408 /// This analyzes the alloca to ensure we can reason about it, builds
03409 /// the slices of the alloca, and then hands it off to be split and
03410 /// rewritten as needed.
03411 bool SROA::runOnAlloca(AllocaInst &AI) {
03412   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
03413   ++NumAllocasAnalyzed;
03414 
03415   // Special case dead allocas, as they're trivial.
03416   if (AI.use_empty()) {
03417     AI.eraseFromParent();
03418     return true;
03419   }
03420 
03421   // Skip alloca forms that this analysis can't handle.
03422   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
03423       DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
03424     return false;
03425 
03426   bool Changed = false;
03427 
03428   // First, split any FCA loads and stores touching this alloca to promote
03429   // better splitting and promotion opportunities.
03430   AggLoadStoreRewriter AggRewriter(*DL);
03431   Changed |= AggRewriter.rewrite(AI);
03432 
03433   // Build the slices using a recursive instruction-visiting builder.
03434   AllocaSlices S(*DL, AI);
03435   DEBUG(S.print(dbgs()));
03436   if (S.isEscaped())
03437     return Changed;
03438 
03439   // Delete all the dead users of this alloca before splitting and rewriting it.
03440   for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
03441                                         DE = S.dead_user_end();
03442        DI != DE; ++DI) {
03443     // Free up everything used by this instruction.
03444     for (Use &DeadOp : (*DI)->operands())
03445       clobberUse(DeadOp);
03446 
03447     // Now replace the uses of this instruction.
03448     (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
03449 
03450     // And mark it for deletion.
03451     DeadInsts.insert(*DI);
03452     Changed = true;
03453   }
03454   for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
03455                                       DE = S.dead_op_end();
03456        DO != DE; ++DO) {
03457     clobberUse(**DO);
03458     Changed = true;
03459   }
03460 
03461   // No slices to split. Leave the dead alloca for a later pass to clean up.
03462   if (S.begin() == S.end())
03463     return Changed;
03464 
03465   Changed |= splitAlloca(AI, S);
03466 
03467   DEBUG(dbgs() << "  Speculating PHIs\n");
03468   while (!SpeculatablePHIs.empty())
03469     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
03470 
03471   DEBUG(dbgs() << "  Speculating Selects\n");
03472   while (!SpeculatableSelects.empty())
03473     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
03474 
03475   return Changed;
03476 }
03477 
03478 /// \brief Delete the dead instructions accumulated in this run.
03479 ///
03480 /// Recursively deletes the dead instructions we've accumulated. This is done
03481 /// at the very end to maximize locality of the recursive delete and to
03482 /// minimize the problems of invalidated instruction pointers as such pointers
03483 /// are used heavily in the intermediate stages of the algorithm.
03484 ///
03485 /// We also record the alloca instructions deleted here so that they aren't
03486 /// subsequently handed to mem2reg to promote.
03487 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
03488   while (!DeadInsts.empty()) {
03489     Instruction *I = DeadInsts.pop_back_val();
03490     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
03491 
03492     I->replaceAllUsesWith(UndefValue::get(I->getType()));
03493 
03494     for (Use &Operand : I->operands())
03495       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
03496         // Zero out the operand and see if it becomes trivially dead.
03497         Operand = 0;
03498         if (isInstructionTriviallyDead(U))
03499           DeadInsts.insert(U);
03500       }
03501 
03502     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
03503       DeletedAllocas.insert(AI);
03504 
03505     ++NumDeleted;
03506     I->eraseFromParent();
03507   }
03508 }
03509 
03510 static void enqueueUsersInWorklist(Instruction &I,
03511                                    SmallVectorImpl<Instruction *> &Worklist,
03512                                    SmallPtrSet<Instruction *, 8> &Visited) {
03513   for (User *U : I.users())
03514     if (Visited.insert(cast<Instruction>(U)))
03515       Worklist.push_back(cast<Instruction>(U));
03516 }
03517 
03518 /// \brief Promote the allocas, using the best available technique.
03519 ///
03520 /// This attempts to promote whatever allocas have been identified as viable in
03521 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
03522 /// If there is a domtree available, we attempt to promote using the full power
03523 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
03524 /// based on the SSAUpdater utilities. This function returns whether any
03525 /// promotion occurred.
03526 bool SROA::promoteAllocas(Function &F) {
03527   if (PromotableAllocas.empty())
03528     return false;
03529 
03530   NumPromoted += PromotableAllocas.size();
03531 
03532   if (DT && !ForceSSAUpdater) {
03533     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
03534     PromoteMemToReg(PromotableAllocas, *DT);
03535     PromotableAllocas.clear();
03536     return true;
03537   }
03538 
03539   DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
03540   SSAUpdater SSA;
03541   DIBuilder DIB(*F.getParent());
03542   SmallVector<Instruction *, 64> Insts;
03543 
03544   // We need a worklist to walk the uses of each alloca.
03545   SmallVector<Instruction *, 8> Worklist;
03546   SmallPtrSet<Instruction *, 8> Visited;
03547   SmallVector<Instruction *, 32> DeadInsts;
03548 
03549   for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
03550     AllocaInst *AI = PromotableAllocas[Idx];
03551     Insts.clear();
03552     Worklist.clear();
03553     Visited.clear();
03554 
03555     enqueueUsersInWorklist(*AI, Worklist, Visited);
03556 
03557     while (!Worklist.empty()) {
03558       Instruction *I = Worklist.pop_back_val();
03559 
03560       // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
03561       // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
03562       // leading to them) here. Eventually it should use them to optimize the
03563       // scalar values produced.
03564       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
03565         assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
03566                II->getIntrinsicID() == Intrinsic::lifetime_end);
03567         II->eraseFromParent();
03568         continue;
03569       }
03570 
03571       // Push the loads and stores we find onto the list. SROA will already
03572       // have validated that all loads and stores are viable candidates for
03573       // promotion.
03574       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
03575         assert(LI->getType() == AI->getAllocatedType());
03576         Insts.push_back(LI);
03577         continue;
03578       }
03579       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
03580         assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
03581         Insts.push_back(SI);
03582         continue;
03583       }
03584 
03585       // For everything else, we know that only no-op bitcasts and GEPs will
03586       // make it this far, just recurse through them and recall them for later
03587       // removal.
03588       DeadInsts.push_back(I);
03589       enqueueUsersInWorklist(*I, Worklist, Visited);
03590     }
03591     AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
03592     while (!DeadInsts.empty())
03593       DeadInsts.pop_back_val()->eraseFromParent();
03594     AI->eraseFromParent();
03595   }
03596 
03597   PromotableAllocas.clear();
03598   return true;
03599 }
03600 
03601 bool SROA::runOnFunction(Function &F) {
03602   if (skipOptnoneFunction(F))
03603     return false;
03604 
03605   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
03606   C = &F.getContext();
03607   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
03608   if (!DLP) {
03609     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
03610     return false;
03611   }
03612   DL = &DLP->getDataLayout();
03613   DominatorTreeWrapperPass *DTWP =
03614       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
03615   DT = DTWP ? &DTWP->getDomTree() : 0;
03616 
03617   BasicBlock &EntryBB = F.getEntryBlock();
03618   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
03619        I != E; ++I)
03620     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
03621       Worklist.insert(AI);
03622 
03623   bool Changed = false;
03624   // A set of deleted alloca instruction pointers which should be removed from
03625   // the list of promotable allocas.
03626   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
03627 
03628   do {
03629     while (!Worklist.empty()) {
03630       Changed |= runOnAlloca(*Worklist.pop_back_val());
03631       deleteDeadInstructions(DeletedAllocas);
03632 
03633       // Remove the deleted allocas from various lists so that we don't try to
03634       // continue processing them.
03635       if (!DeletedAllocas.empty()) {
03636         auto IsInSet = [&](AllocaInst *AI) {
03637           return DeletedAllocas.count(AI);
03638         };
03639         Worklist.remove_if(IsInSet);
03640         PostPromotionWorklist.remove_if(IsInSet);
03641         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
03642                                                PromotableAllocas.end(),
03643                                                IsInSet),
03644                                 PromotableAllocas.end());
03645         DeletedAllocas.clear();
03646       }
03647     }
03648 
03649     Changed |= promoteAllocas(F);
03650 
03651     Worklist = PostPromotionWorklist;
03652     PostPromotionWorklist.clear();
03653   } while (!Worklist.empty());
03654 
03655   return Changed;
03656 }
03657 
03658 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
03659   if (RequiresDomTree)
03660     AU.addRequired<DominatorTreeWrapperPass>();
03661   AU.setPreservesCFG();
03662 }