ScalarReplAggregates.cpp revision aab3ea244cb014beb21c112729034879a5d4e5ee
1//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation.  This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
13// each member (if possible).  Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs.  As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "scalarrepl"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Function.h"
27#include "llvm/GlobalVariable.h"
28#include "llvm/Instructions.h"
29#include "llvm/IntrinsicInst.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/Module.h"
32#include "llvm/Pass.h"
33#include "llvm/Analysis/DIBuilder.h"
34#include "llvm/Analysis/Dominators.h"
35#include "llvm/Analysis/Loads.h"
36#include "llvm/Analysis/ValueTracking.h"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Transforms/Utils/PromoteMemToReg.h"
39#include "llvm/Transforms/Utils/Local.h"
40#include "llvm/Transforms/Utils/SSAUpdater.h"
41#include "llvm/Support/CallSite.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/GetElementPtrTypeIterator.h"
45#include "llvm/Support/IRBuilder.h"
46#include "llvm/Support/MathExtras.h"
47#include "llvm/Support/raw_ostream.h"
48#include "llvm/ADT/SetVector.h"
49#include "llvm/ADT/SmallVector.h"
50#include "llvm/ADT/Statistic.h"
51using namespace llvm;
52
53STATISTIC(NumReplaced,  "Number of allocas broken up");
54STATISTIC(NumPromoted,  "Number of allocas promoted");
55STATISTIC(NumAdjusted,  "Number of scalar allocas adjusted to allow promotion");
56STATISTIC(NumConverted, "Number of aggregates converted to scalar");
57STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
58
59namespace {
60  struct SROA : public FunctionPass {
61    SROA(int T, bool hasDT, char &ID)
62      : FunctionPass(ID), HasDomTree(hasDT) {
63      if (T == -1)
64        SRThreshold = 128;
65      else
66        SRThreshold = T;
67    }
68
69    bool runOnFunction(Function &F);
70
71    bool performScalarRepl(Function &F);
72    bool performPromotion(Function &F);
73
74  private:
75    bool HasDomTree;
76    TargetData *TD;
77
78    /// DeadInsts - Keep track of instructions we have made dead, so that
79    /// we can remove them after we are done working.
80    SmallVector<Value*, 32> DeadInsts;
81
82    /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
83    /// information about the uses.  All these fields are initialized to false
84    /// and set to true when something is learned.
85    struct AllocaInfo {
86      /// The alloca to promote.
87      AllocaInst *AI;
88
89      /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
90      /// looping and avoid redundant work.
91      SmallPtrSet<PHINode*, 8> CheckedPHIs;
92
93      /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
94      bool isUnsafe : 1;
95
96      /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
97      bool isMemCpySrc : 1;
98
99      /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
100      bool isMemCpyDst : 1;
101
102      /// hasSubelementAccess - This is true if a subelement of the alloca is
103      /// ever accessed, or false if the alloca is only accessed with mem
104      /// intrinsics or load/store that only access the entire alloca at once.
105      bool hasSubelementAccess : 1;
106
107      /// hasALoadOrStore - This is true if there are any loads or stores to it.
108      /// The alloca may just be accessed with memcpy, for example, which would
109      /// not set this.
110      bool hasALoadOrStore : 1;
111
112      explicit AllocaInfo(AllocaInst *ai)
113        : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
114          hasSubelementAccess(false), hasALoadOrStore(false) {}
115    };
116
117    unsigned SRThreshold;
118
119    void MarkUnsafe(AllocaInfo &I, Instruction *User) {
120      I.isUnsafe = true;
121      DEBUG(dbgs() << "  Transformation preventing inst: " << *User << '\n');
122    }
123
124    bool isSafeAllocaToScalarRepl(AllocaInst *AI);
125
126    void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
127    void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
128                                         AllocaInfo &Info);
129    void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
130    void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
131                         const Type *MemOpType, bool isStore, AllocaInfo &Info,
132                         Instruction *TheAccess, bool AllowWholeAccess);
133    bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
134    uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
135                                  const Type *&IdxTy);
136
137    void DoScalarReplacement(AllocaInst *AI,
138                             std::vector<AllocaInst*> &WorkList);
139    void DeleteDeadInstructions();
140
141    void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
142                              SmallVector<AllocaInst*, 32> &NewElts);
143    void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
144                        SmallVector<AllocaInst*, 32> &NewElts);
145    void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
146                    SmallVector<AllocaInst*, 32> &NewElts);
147    void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
148                                      AllocaInst *AI,
149                                      SmallVector<AllocaInst*, 32> &NewElts);
150    void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
151                                       SmallVector<AllocaInst*, 32> &NewElts);
152    void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
153                                      SmallVector<AllocaInst*, 32> &NewElts);
154
155    static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
156  };
157
158  // SROA_DT - SROA that uses DominatorTree.
159  struct SROA_DT : public SROA {
160    static char ID;
161  public:
162    SROA_DT(int T = -1) : SROA(T, true, ID) {
163      initializeSROA_DTPass(*PassRegistry::getPassRegistry());
164    }
165
166    // getAnalysisUsage - This pass does not require any passes, but we know it
167    // will not alter the CFG, so say so.
168    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
169      AU.addRequired<DominatorTree>();
170      AU.setPreservesCFG();
171    }
172  };
173
174  // SROA_SSAUp - SROA that uses SSAUpdater.
175  struct SROA_SSAUp : public SROA {
176    static char ID;
177  public:
178    SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
179      initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
180    }
181
182    // getAnalysisUsage - This pass does not require any passes, but we know it
183    // will not alter the CFG, so say so.
184    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
185      AU.setPreservesCFG();
186    }
187  };
188
189}
190
191char SROA_DT::ID = 0;
192char SROA_SSAUp::ID = 0;
193
194INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
195                "Scalar Replacement of Aggregates (DT)", false, false)
196INITIALIZE_PASS_DEPENDENCY(DominatorTree)
197INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
198                "Scalar Replacement of Aggregates (DT)", false, false)
199
200INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
201                      "Scalar Replacement of Aggregates (SSAUp)", false, false)
202INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
203                    "Scalar Replacement of Aggregates (SSAUp)", false, false)
204
205// Public interface to the ScalarReplAggregates pass
206FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
207                                                   bool UseDomTree) {
208  if (UseDomTree)
209    return new SROA_DT(Threshold);
210  return new SROA_SSAUp(Threshold);
211}
212
213
214//===----------------------------------------------------------------------===//
215// Convert To Scalar Optimization.
216//===----------------------------------------------------------------------===//
217
218namespace {
219/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
220/// optimization, which scans the uses of an alloca and determines if it can
221/// rewrite it in terms of a single new alloca that can be mem2reg'd.
222class ConvertToScalarInfo {
223  /// AllocaSize - The size of the alloca being considered in bytes.
224  unsigned AllocaSize;
225  const TargetData &TD;
226
227  /// IsNotTrivial - This is set to true if there is some access to the object
228  /// which means that mem2reg can't promote it.
229  bool IsNotTrivial;
230
231  /// ScalarKind - Tracks the kind of alloca being considered for promotion,
232  /// computed based on the uses of the alloca rather than the LLVM type system.
233  enum {
234    Unknown,
235
236    // Accesses via GEPs that are consistent with element access of a vector
237    // type. This will not be converted into a vector unless there is a later
238    // access using an actual vector type.
239    ImplicitVector,
240
241    // Accesses via vector operations and GEPs that are consistent with the
242    // layout of a vector type.
243    Vector,
244
245    // An integer bag-of-bits with bitwise operations for insertion and
246    // extraction. Any combination of types can be converted into this kind
247    // of scalar.
248    Integer
249  } ScalarKind;
250
251  /// VectorTy - This tracks the type that we should promote the vector to if
252  /// it is possible to turn it into a vector.  This starts out null, and if it
253  /// isn't possible to turn into a vector type, it gets set to VoidTy.
254  const VectorType *VectorTy;
255
256  /// HadNonMemTransferAccess - True if there is at least one access to the
257  /// alloca that is not a MemTransferInst.  We don't want to turn structs into
258  /// large integers unless there is some potential for optimization.
259  bool HadNonMemTransferAccess;
260
261public:
262  explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
263    : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
264      VectorTy(0), HadNonMemTransferAccess(false) { }
265
266  AllocaInst *TryConvert(AllocaInst *AI);
267
268private:
269  bool CanConvertToScalar(Value *V, uint64_t Offset);
270  void MergeInTypeForLoadOrStore(const Type *In, uint64_t Offset);
271  bool MergeInVectorType(const VectorType *VInTy, uint64_t Offset);
272  void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
273
274  Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
275                                    uint64_t Offset, IRBuilder<> &Builder);
276  Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
277                                   uint64_t Offset, IRBuilder<> &Builder);
278};
279} // end anonymous namespace.
280
281
282/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
283/// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
284/// alloca if possible or null if not.
285AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
286  // If we can't convert this scalar, or if mem2reg can trivially do it, bail
287  // out.
288  if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
289    return 0;
290
291  // If an alloca has only memset / memcpy uses, it may still have an Unknown
292  // ScalarKind. Treat it as an Integer below.
293  if (ScalarKind == Unknown)
294    ScalarKind = Integer;
295
296  // If we were able to find a vector type that can handle this with
297  // insert/extract elements, and if there was at least one use that had
298  // a vector type, promote this to a vector.  We don't want to promote
299  // random stuff that doesn't use vectors (e.g. <9 x double>) because then
300  // we just get a lot of insert/extracts.  If at least one vector is
301  // involved, then we probably really do have a union of vector/array.
302  const Type *NewTy;
303  if (ScalarKind == Vector) {
304    assert(VectorTy && "Missing type for vector scalar.");
305    DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
306          << *VectorTy << '\n');
307    NewTy = VectorTy;  // Use the vector type.
308  } else {
309    unsigned BitWidth = AllocaSize * 8;
310    if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
311        !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
312      return 0;
313
314    DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
315    // Create and insert the integer alloca.
316    NewTy = IntegerType::get(AI->getContext(), BitWidth);
317  }
318  AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
319  ConvertUsesToScalar(AI, NewAI, 0);
320  return NewAI;
321}
322
323/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
324/// (VectorTy) so far at the offset specified by Offset (which is specified in
325/// bytes).
326///
327/// There are three cases we handle here:
328///   1) A union of vector types of the same size and potentially its elements.
329///      Here we turn element accesses into insert/extract element operations.
330///      This promotes a <4 x float> with a store of float to the third element
331///      into a <4 x float> that uses insert element.
332///   2) A union of vector types with power-of-2 size differences, e.g. a float,
333///      <2 x float> and <4 x float>.  Here we turn element accesses into insert
334///      and extract element operations, and <2 x float> accesses into a cast to
335///      <2 x double>, an extract, and a cast back to <2 x float>.
336///   3) A fully general blob of memory, which we turn into some (potentially
337///      large) integer type with extract and insert operations where the loads
338///      and stores would mutate the memory.  We mark this by setting VectorTy
339///      to VoidTy.
340void ConvertToScalarInfo::MergeInTypeForLoadOrStore(const Type *In,
341                                                    uint64_t Offset) {
342  // If we already decided to turn this into a blob of integer memory, there is
343  // nothing to be done.
344  if (ScalarKind == Integer)
345    return;
346
347  // If this could be contributing to a vector, analyze it.
348
349  // If the In type is a vector that is the same size as the alloca, see if it
350  // matches the existing VecTy.
351  if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
352    if (MergeInVectorType(VInTy, Offset))
353      return;
354  } else if (In->isFloatTy() || In->isDoubleTy() ||
355             (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
356              isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
357    // Full width accesses can be ignored, because they can always be turned
358    // into bitcasts.
359    unsigned EltSize = In->getPrimitiveSizeInBits()/8;
360    if (EltSize == AllocaSize)
361      return;
362
363    // If we're accessing something that could be an element of a vector, see
364    // if the implied vector agrees with what we already have and if Offset is
365    // compatible with it.
366    if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
367        (!VectorTy || Offset * 8 < VectorTy->getPrimitiveSizeInBits())) {
368      if (!VectorTy) {
369        ScalarKind = ImplicitVector;
370        VectorTy = VectorType::get(In, AllocaSize/EltSize);
371        return;
372      }
373
374      unsigned CurrentEltSize = VectorTy->getElementType()
375                                ->getPrimitiveSizeInBits()/8;
376      if (EltSize == CurrentEltSize)
377        return;
378
379      if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
380        return;
381    }
382  }
383
384  // Otherwise, we have a case that we can't handle with an optimized vector
385  // form.  We can still turn this into a large integer.
386  ScalarKind = Integer;
387}
388
389/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
390/// returning true if the type was successfully merged and false otherwise.
391bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
392                                            uint64_t Offset) {
393  // TODO: Support nonzero offsets?
394  if (Offset != 0)
395    return false;
396
397  // Only allow vectors that are a power-of-2 away from the size of the alloca.
398  if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
399    return false;
400
401  // If this the first vector we see, remember the type so that we know the
402  // element size.
403  if (!VectorTy) {
404    ScalarKind = Vector;
405    VectorTy = VInTy;
406    return true;
407  }
408
409  unsigned BitWidth = VectorTy->getBitWidth();
410  unsigned InBitWidth = VInTy->getBitWidth();
411
412  // Vectors of the same size can be converted using a simple bitcast.
413  if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8)) {
414    ScalarKind = Vector;
415    return true;
416  }
417
418  const Type *ElementTy = VectorTy->getElementType();
419  const Type *InElementTy = VInTy->getElementType();
420
421  // Do not allow mixed integer and floating-point accesses from vectors of
422  // different sizes.
423  if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
424    return false;
425
426  if (ElementTy->isFloatingPointTy()) {
427    // Only allow floating-point vectors of different sizes if they have the
428    // same element type.
429    // TODO: This could be loosened a bit, but would anything benefit?
430    if (ElementTy != InElementTy)
431      return false;
432
433    // There are no arbitrary-precision floating-point types, which limits the
434    // number of legal vector types with larger element types that we can form
435    // to bitcast and extract a subvector.
436    // TODO: We could support some more cases with mixed fp128 and double here.
437    if (!(BitWidth == 64 || BitWidth == 128) ||
438        !(InBitWidth == 64 || InBitWidth == 128))
439      return false;
440  } else {
441    assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
442                                       "or floating-point.");
443    unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
444    unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
445
446    // Do not allow integer types smaller than a byte or types whose widths are
447    // not a multiple of a byte.
448    if (BitWidth < 8 || InBitWidth < 8 ||
449        BitWidth % 8 != 0 || InBitWidth % 8 != 0)
450      return false;
451  }
452
453  // Pick the largest of the two vector types.
454  ScalarKind = Vector;
455  if (InBitWidth > BitWidth)
456    VectorTy = VInTy;
457
458  return true;
459}
460
461/// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
462/// its accesses to a single vector type, return true and set VecTy to
463/// the new type.  If we could convert the alloca into a single promotable
464/// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
465/// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
466/// is the current offset from the base of the alloca being analyzed.
467///
468/// If we see at least one access to the value that is as a vector type, set the
469/// SawVec flag.
470bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
471  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
472    Instruction *User = cast<Instruction>(*UI);
473
474    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
475      // Don't break volatile loads.
476      if (LI->isVolatile())
477        return false;
478      // Don't touch MMX operations.
479      if (LI->getType()->isX86_MMXTy())
480        return false;
481      HadNonMemTransferAccess = true;
482      MergeInTypeForLoadOrStore(LI->getType(), Offset);
483      continue;
484    }
485
486    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
487      // Storing the pointer, not into the value?
488      if (SI->getOperand(0) == V || SI->isVolatile()) return false;
489      // Don't touch MMX operations.
490      if (SI->getOperand(0)->getType()->isX86_MMXTy())
491        return false;
492      HadNonMemTransferAccess = true;
493      MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
494      continue;
495    }
496
497    if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
498      IsNotTrivial = true;  // Can't be mem2reg'd.
499      if (!CanConvertToScalar(BCI, Offset))
500        return false;
501      continue;
502    }
503
504    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
505      // If this is a GEP with a variable indices, we can't handle it.
506      if (!GEP->hasAllConstantIndices())
507        return false;
508
509      // Compute the offset that this GEP adds to the pointer.
510      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
511      uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
512                                               &Indices[0], Indices.size());
513      // See if all uses can be converted.
514      if (!CanConvertToScalar(GEP, Offset+GEPOffset))
515        return false;
516      IsNotTrivial = true;  // Can't be mem2reg'd.
517      HadNonMemTransferAccess = true;
518      continue;
519    }
520
521    // If this is a constant sized memset of a constant value (e.g. 0) we can
522    // handle it.
523    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
524      // Store of constant value and constant size.
525      if (!isa<ConstantInt>(MSI->getValue()) ||
526          !isa<ConstantInt>(MSI->getLength()))
527        return false;
528      IsNotTrivial = true;  // Can't be mem2reg'd.
529      HadNonMemTransferAccess = true;
530      continue;
531    }
532
533    // If this is a memcpy or memmove into or out of the whole allocation, we
534    // can handle it like a load or store of the scalar type.
535    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
536      ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
537      if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
538        return false;
539
540      IsNotTrivial = true;  // Can't be mem2reg'd.
541      continue;
542    }
543
544    // Otherwise, we cannot handle this!
545    return false;
546  }
547
548  return true;
549}
550
551/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
552/// directly.  This happens when we are converting an "integer union" to a
553/// single integer scalar, or when we are converting a "vector union" to a
554/// vector with insert/extractelement instructions.
555///
556/// Offset is an offset from the original alloca, in bits that need to be
557/// shifted to the right.  By the end of this, there should be no uses of Ptr.
558void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
559                                              uint64_t Offset) {
560  while (!Ptr->use_empty()) {
561    Instruction *User = cast<Instruction>(Ptr->use_back());
562
563    if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
564      ConvertUsesToScalar(CI, NewAI, Offset);
565      CI->eraseFromParent();
566      continue;
567    }
568
569    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
570      // Compute the offset that this GEP adds to the pointer.
571      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
572      uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
573                                               &Indices[0], Indices.size());
574      ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
575      GEP->eraseFromParent();
576      continue;
577    }
578
579    IRBuilder<> Builder(User);
580
581    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
582      // The load is a bit extract from NewAI shifted right by Offset bits.
583      Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
584      Value *NewLoadVal
585        = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
586      LI->replaceAllUsesWith(NewLoadVal);
587      LI->eraseFromParent();
588      continue;
589    }
590
591    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
592      assert(SI->getOperand(0) != Ptr && "Consistency error!");
593      Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
594      Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
595                                             Builder);
596      Builder.CreateStore(New, NewAI);
597      SI->eraseFromParent();
598
599      // If the load we just inserted is now dead, then the inserted store
600      // overwrote the entire thing.
601      if (Old->use_empty())
602        Old->eraseFromParent();
603      continue;
604    }
605
606    // If this is a constant sized memset of a constant value (e.g. 0) we can
607    // transform it into a store of the expanded constant value.
608    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
609      assert(MSI->getRawDest() == Ptr && "Consistency error!");
610      unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
611      if (NumBytes != 0) {
612        unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
613
614        // Compute the value replicated the right number of times.
615        APInt APVal(NumBytes*8, Val);
616
617        // Splat the value if non-zero.
618        if (Val)
619          for (unsigned i = 1; i != NumBytes; ++i)
620            APVal |= APVal << 8;
621
622        Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
623        Value *New = ConvertScalar_InsertValue(
624                                    ConstantInt::get(User->getContext(), APVal),
625                                               Old, Offset, Builder);
626        Builder.CreateStore(New, NewAI);
627
628        // If the load we just inserted is now dead, then the memset overwrote
629        // the entire thing.
630        if (Old->use_empty())
631          Old->eraseFromParent();
632      }
633      MSI->eraseFromParent();
634      continue;
635    }
636
637    // If this is a memcpy or memmove into or out of the whole allocation, we
638    // can handle it like a load or store of the scalar type.
639    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
640      assert(Offset == 0 && "must be store to start of alloca");
641
642      // If the source and destination are both to the same alloca, then this is
643      // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
644      // as appropriate.
645      AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
646
647      if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
648        // Dest must be OrigAI, change this to be a load from the original
649        // pointer (bitcasted), then a store to our new alloca.
650        assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
651        Value *SrcPtr = MTI->getSource();
652        const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
653        const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
654        if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
655          AIPTy = PointerType::get(AIPTy->getElementType(),
656                                   SPTy->getAddressSpace());
657        }
658        SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
659
660        LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
661        SrcVal->setAlignment(MTI->getAlignment());
662        Builder.CreateStore(SrcVal, NewAI);
663      } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
664        // Src must be OrigAI, change this to be a load from NewAI then a store
665        // through the original dest pointer (bitcasted).
666        assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
667        LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
668
669        const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
670        const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
671        if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
672          AIPTy = PointerType::get(AIPTy->getElementType(),
673                                   DPTy->getAddressSpace());
674        }
675        Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
676
677        StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
678        NewStore->setAlignment(MTI->getAlignment());
679      } else {
680        // Noop transfer. Src == Dst
681      }
682
683      MTI->eraseFromParent();
684      continue;
685    }
686
687    llvm_unreachable("Unsupported operation!");
688  }
689}
690
691/// getScaledElementType - Gets a scaled element type for a partial vector
692/// access of an alloca. The input types must be integer or floating-point
693/// scalar or vector types, and the resulting type is an integer, float or
694/// double.
695static const Type *getScaledElementType(const Type *Ty1, const Type *Ty2,
696                                        unsigned NewBitWidth) {
697  bool IsFP1 = Ty1->isFloatingPointTy() ||
698               (Ty1->isVectorTy() &&
699                cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
700  bool IsFP2 = Ty2->isFloatingPointTy() ||
701               (Ty2->isVectorTy() &&
702                cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
703
704  LLVMContext &Context = Ty1->getContext();
705
706  // Prefer floating-point types over integer types, as integer types may have
707  // been created by earlier scalar replacement.
708  if (IsFP1 || IsFP2) {
709    if (NewBitWidth == 32)
710      return Type::getFloatTy(Context);
711    if (NewBitWidth == 64)
712      return Type::getDoubleTy(Context);
713  }
714
715  return Type::getIntNTy(Context, NewBitWidth);
716}
717
718/// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
719/// to another vector of the same element type which has the same allocation
720/// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
721static Value *CreateShuffleVectorCast(Value *FromVal, const Type *ToType,
722                                      IRBuilder<> &Builder) {
723  const Type *FromType = FromVal->getType();
724  const VectorType *FromVTy = cast<VectorType>(FromType);
725  const VectorType *ToVTy = cast<VectorType>(ToType);
726  assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
727         "Vectors must have the same element type");
728   Value *UnV = UndefValue::get(FromType);
729   unsigned numEltsFrom = FromVTy->getNumElements();
730   unsigned numEltsTo = ToVTy->getNumElements();
731
732   SmallVector<Constant*, 3> Args;
733   const Type* Int32Ty = Builder.getInt32Ty();
734   unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
735   unsigned i;
736   for (i=0; i != minNumElts; ++i)
737     Args.push_back(ConstantInt::get(Int32Ty, i));
738
739   if (i < numEltsTo) {
740     Constant* UnC = UndefValue::get(Int32Ty);
741     for (; i != numEltsTo; ++i)
742       Args.push_back(UnC);
743   }
744   Constant *Mask = ConstantVector::get(Args);
745   return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
746}
747
748/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
749/// or vector value FromVal, extracting the bits from the offset specified by
750/// Offset.  This returns the value, which is of type ToType.
751///
752/// This happens when we are converting an "integer union" to a single
753/// integer scalar, or when we are converting a "vector union" to a vector with
754/// insert/extractelement instructions.
755///
756/// Offset is an offset from the original alloca, in bits that need to be
757/// shifted to the right.
758Value *ConvertToScalarInfo::
759ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
760                           uint64_t Offset, IRBuilder<> &Builder) {
761  // If the load is of the whole new alloca, no conversion is needed.
762  const Type *FromType = FromVal->getType();
763  if (FromType == ToType && Offset == 0)
764    return FromVal;
765
766  // If the result alloca is a vector type, this is either an element
767  // access or a bitcast to another vector type of the same size.
768  if (const VectorType *VTy = dyn_cast<VectorType>(FromType)) {
769    unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
770    unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
771    if (FromTypeSize == ToTypeSize) {
772      // If the two types have the same primitive size, use a bit cast.
773      // Otherwise, it is two vectors with the same element type that has
774      // the same allocation size but different number of elements so use
775      // a shuffle vector.
776      if (FromType->getPrimitiveSizeInBits() ==
777          ToType->getPrimitiveSizeInBits())
778        return Builder.CreateBitCast(FromVal, ToType, "tmp");
779      else
780        return CreateShuffleVectorCast(FromVal, ToType, Builder);
781    }
782
783    if (isPowerOf2_64(FromTypeSize / ToTypeSize)) {
784      assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
785             "of a smaller vector type at a nonzero offset.");
786
787      const Type *CastElementTy = getScaledElementType(FromType, ToType,
788                                                       ToTypeSize * 8);
789      unsigned NumCastVectorElements = FromTypeSize / ToTypeSize;
790
791      LLVMContext &Context = FromVal->getContext();
792      const Type *CastTy = VectorType::get(CastElementTy,
793                                           NumCastVectorElements);
794      Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
795
796      unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
797      unsigned Elt = Offset/EltSize;
798      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
799      Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
800                                        Type::getInt32Ty(Context), Elt), "tmp");
801      return Builder.CreateBitCast(Extract, ToType, "tmp");
802    }
803
804    // Otherwise it must be an element access.
805    unsigned Elt = 0;
806    if (Offset) {
807      unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
808      Elt = Offset/EltSize;
809      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
810    }
811    // Return the element extracted out of it.
812    Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
813                    Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
814    if (V->getType() != ToType)
815      V = Builder.CreateBitCast(V, ToType, "tmp");
816    return V;
817  }
818
819  // If ToType is a first class aggregate, extract out each of the pieces and
820  // use insertvalue's to form the FCA.
821  if (const StructType *ST = dyn_cast<StructType>(ToType)) {
822    const StructLayout &Layout = *TD.getStructLayout(ST);
823    Value *Res = UndefValue::get(ST);
824    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
825      Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
826                                        Offset+Layout.getElementOffsetInBits(i),
827                                              Builder);
828      Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
829    }
830    return Res;
831  }
832
833  if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
834    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
835    Value *Res = UndefValue::get(AT);
836    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
837      Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
838                                              Offset+i*EltSize, Builder);
839      Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
840    }
841    return Res;
842  }
843
844  // Otherwise, this must be a union that was converted to an integer value.
845  const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
846
847  // If this is a big-endian system and the load is narrower than the
848  // full alloca type, we need to do a shift to get the right bits.
849  int ShAmt = 0;
850  if (TD.isBigEndian()) {
851    // On big-endian machines, the lowest bit is stored at the bit offset
852    // from the pointer given by getTypeStoreSizeInBits.  This matters for
853    // integers with a bitwidth that is not a multiple of 8.
854    ShAmt = TD.getTypeStoreSizeInBits(NTy) -
855            TD.getTypeStoreSizeInBits(ToType) - Offset;
856  } else {
857    ShAmt = Offset;
858  }
859
860  // Note: we support negative bitwidths (with shl) which are not defined.
861  // We do this to support (f.e.) loads off the end of a structure where
862  // only some bits are used.
863  if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
864    FromVal = Builder.CreateLShr(FromVal,
865                                 ConstantInt::get(FromVal->getType(),
866                                                           ShAmt), "tmp");
867  else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
868    FromVal = Builder.CreateShl(FromVal,
869                                ConstantInt::get(FromVal->getType(),
870                                                          -ShAmt), "tmp");
871
872  // Finally, unconditionally truncate the integer to the right width.
873  unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
874  if (LIBitWidth < NTy->getBitWidth())
875    FromVal =
876      Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
877                                                    LIBitWidth), "tmp");
878  else if (LIBitWidth > NTy->getBitWidth())
879    FromVal =
880       Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
881                                                    LIBitWidth), "tmp");
882
883  // If the result is an integer, this is a trunc or bitcast.
884  if (ToType->isIntegerTy()) {
885    // Should be done.
886  } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
887    // Just do a bitcast, we know the sizes match up.
888    FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
889  } else {
890    // Otherwise must be a pointer.
891    FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
892  }
893  assert(FromVal->getType() == ToType && "Didn't convert right?");
894  return FromVal;
895}
896
897/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
898/// or vector value "Old" at the offset specified by Offset.
899///
900/// This happens when we are converting an "integer union" to a
901/// single integer scalar, or when we are converting a "vector union" to a
902/// vector with insert/extractelement instructions.
903///
904/// Offset is an offset from the original alloca, in bits that need to be
905/// shifted to the right.
906Value *ConvertToScalarInfo::
907ConvertScalar_InsertValue(Value *SV, Value *Old,
908                          uint64_t Offset, IRBuilder<> &Builder) {
909  // Convert the stored type to the actual type, shift it left to insert
910  // then 'or' into place.
911  const Type *AllocaType = Old->getType();
912  LLVMContext &Context = Old->getContext();
913
914  if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
915    uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
916    uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
917
918    // Changing the whole vector with memset or with an access of a different
919    // vector type?
920    if (ValSize == VecSize) {
921      // If the two types have the same primitive size, use a bit cast.
922      // Otherwise, it is two vectors with the same element type that has
923      // the same allocation size but different number of elements so use
924      // a shuffle vector.
925      if (VTy->getPrimitiveSizeInBits() ==
926          SV->getType()->getPrimitiveSizeInBits())
927        return Builder.CreateBitCast(SV, AllocaType, "tmp");
928      else
929        return CreateShuffleVectorCast(SV, VTy, Builder);
930    }
931
932    if (isPowerOf2_64(VecSize / ValSize)) {
933      assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
934             "value of a smaller vector type at a nonzero offset.");
935
936      const Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
937                                                       ValSize);
938      unsigned NumCastVectorElements = VecSize / ValSize;
939
940      LLVMContext &Context = SV->getContext();
941      const Type *OldCastTy = VectorType::get(CastElementTy,
942                                              NumCastVectorElements);
943      Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
944
945      Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
946
947      unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
948      unsigned Elt = Offset/EltSize;
949      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
950      Value *Insert =
951        Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
952                                        Type::getInt32Ty(Context), Elt), "tmp");
953      return Builder.CreateBitCast(Insert, AllocaType, "tmp");
954    }
955
956    // Must be an element insertion.
957    assert(SV->getType() == VTy->getElementType());
958    uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
959    unsigned Elt = Offset/EltSize;
960    return Builder.CreateInsertElement(Old, SV,
961                     ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
962                                     "tmp");
963  }
964
965  // If SV is a first-class aggregate value, insert each value recursively.
966  if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
967    const StructLayout &Layout = *TD.getStructLayout(ST);
968    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
969      Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
970      Old = ConvertScalar_InsertValue(Elt, Old,
971                                      Offset+Layout.getElementOffsetInBits(i),
972                                      Builder);
973    }
974    return Old;
975  }
976
977  if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
978    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
979    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
980      Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
981      Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
982    }
983    return Old;
984  }
985
986  // If SV is a float, convert it to the appropriate integer type.
987  // If it is a pointer, do the same.
988  unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
989  unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
990  unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
991  unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
992  if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
993    SV = Builder.CreateBitCast(SV,
994                            IntegerType::get(SV->getContext(),SrcWidth), "tmp");
995  else if (SV->getType()->isPointerTy())
996    SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
997
998  // Zero extend or truncate the value if needed.
999  if (SV->getType() != AllocaType) {
1000    if (SV->getType()->getPrimitiveSizeInBits() <
1001             AllocaType->getPrimitiveSizeInBits())
1002      SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1003    else {
1004      // Truncation may be needed if storing more than the alloca can hold
1005      // (undefined behavior).
1006      SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1007      SrcWidth = DestWidth;
1008      SrcStoreWidth = DestStoreWidth;
1009    }
1010  }
1011
1012  // If this is a big-endian system and the store is narrower than the
1013  // full alloca type, we need to do a shift to get the right bits.
1014  int ShAmt = 0;
1015  if (TD.isBigEndian()) {
1016    // On big-endian machines, the lowest bit is stored at the bit offset
1017    // from the pointer given by getTypeStoreSizeInBits.  This matters for
1018    // integers with a bitwidth that is not a multiple of 8.
1019    ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1020  } else {
1021    ShAmt = Offset;
1022  }
1023
1024  // Note: we support negative bitwidths (with shr) which are not defined.
1025  // We do this to support (f.e.) stores off the end of a structure where
1026  // only some bits in the structure are set.
1027  APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1028  if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1029    SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1030                           ShAmt), "tmp");
1031    Mask <<= ShAmt;
1032  } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1033    SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1034                            -ShAmt), "tmp");
1035    Mask = Mask.lshr(-ShAmt);
1036  }
1037
1038  // Mask out the bits we are about to insert from the old value, and or
1039  // in the new bits.
1040  if (SrcWidth != DestWidth) {
1041    assert(DestWidth > SrcWidth);
1042    Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1043    SV = Builder.CreateOr(Old, SV, "ins");
1044  }
1045  return SV;
1046}
1047
1048
1049//===----------------------------------------------------------------------===//
1050// SRoA Driver
1051//===----------------------------------------------------------------------===//
1052
1053
1054bool SROA::runOnFunction(Function &F) {
1055  TD = getAnalysisIfAvailable<TargetData>();
1056
1057  bool Changed = performPromotion(F);
1058
1059  // FIXME: ScalarRepl currently depends on TargetData more than it
1060  // theoretically needs to. It should be refactored in order to support
1061  // target-independent IR. Until this is done, just skip the actual
1062  // scalar-replacement portion of this pass.
1063  if (!TD) return Changed;
1064
1065  while (1) {
1066    bool LocalChange = performScalarRepl(F);
1067    if (!LocalChange) break;   // No need to repromote if no scalarrepl
1068    Changed = true;
1069    LocalChange = performPromotion(F);
1070    if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
1071  }
1072
1073  return Changed;
1074}
1075
1076namespace {
1077class AllocaPromoter : public LoadAndStorePromoter {
1078  AllocaInst *AI;
1079public:
1080  AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1081                 DbgDeclareInst *DD, DIBuilder *&DB)
1082    : LoadAndStorePromoter(Insts, S, DD, DB), AI(0) {}
1083
1084  void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
1085    // Remember which alloca we're promoting (for isInstInList).
1086    this->AI = AI;
1087    LoadAndStorePromoter::run(Insts);
1088    AI->eraseFromParent();
1089  }
1090
1091  virtual bool isInstInList(Instruction *I,
1092                            const SmallVectorImpl<Instruction*> &Insts) const {
1093    if (LoadInst *LI = dyn_cast<LoadInst>(I))
1094      return LI->getOperand(0) == AI;
1095    return cast<StoreInst>(I)->getPointerOperand() == AI;
1096  }
1097};
1098} // end anon namespace
1099
1100/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1101/// subsequently loaded can be rewritten to load both input pointers and then
1102/// select between the result, allowing the load of the alloca to be promoted.
1103/// From this:
1104///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1105///   %V = load i32* %P2
1106/// to:
1107///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1108///   %V2 = load i32* %Other
1109///   %V = select i1 %cond, i32 %V1, i32 %V2
1110///
1111/// We can do this to a select if its only uses are loads and if the operand to
1112/// the select can be loaded unconditionally.
1113static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1114  bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1115  bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1116
1117  for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1118       UI != UE; ++UI) {
1119    LoadInst *LI = dyn_cast<LoadInst>(*UI);
1120    if (LI == 0 || LI->isVolatile()) return false;
1121
1122    // Both operands to the select need to be dereferencable, either absolutely
1123    // (e.g. allocas) or at this point because we can see other accesses to it.
1124    if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1125                                                    LI->getAlignment(), TD))
1126      return false;
1127    if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1128                                                    LI->getAlignment(), TD))
1129      return false;
1130  }
1131
1132  return true;
1133}
1134
1135/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1136/// subsequently loaded can be rewritten to load both input pointers in the pred
1137/// blocks and then PHI the results, allowing the load of the alloca to be
1138/// promoted.
1139/// From this:
1140///   %P2 = phi [i32* %Alloca, i32* %Other]
1141///   %V = load i32* %P2
1142/// to:
1143///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1144///   ...
1145///   %V2 = load i32* %Other
1146///   ...
1147///   %V = phi [i32 %V1, i32 %V2]
1148///
1149/// We can do this to a select if its only uses are loads and if the operand to
1150/// the select can be loaded unconditionally.
1151static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1152  // For now, we can only do this promotion if the load is in the same block as
1153  // the PHI, and if there are no stores between the phi and load.
1154  // TODO: Allow recursive phi users.
1155  // TODO: Allow stores.
1156  BasicBlock *BB = PN->getParent();
1157  unsigned MaxAlign = 0;
1158  for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1159       UI != UE; ++UI) {
1160    LoadInst *LI = dyn_cast<LoadInst>(*UI);
1161    if (LI == 0 || LI->isVolatile()) return false;
1162
1163    // For now we only allow loads in the same block as the PHI.  This is a
1164    // common case that happens when instcombine merges two loads through a PHI.
1165    if (LI->getParent() != BB) return false;
1166
1167    // Ensure that there are no instructions between the PHI and the load that
1168    // could store.
1169    for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1170      if (BBI->mayWriteToMemory())
1171        return false;
1172
1173    MaxAlign = std::max(MaxAlign, LI->getAlignment());
1174  }
1175
1176  // Okay, we know that we have one or more loads in the same block as the PHI.
1177  // We can transform this if it is safe to push the loads into the predecessor
1178  // blocks.  The only thing to watch out for is that we can't put a possibly
1179  // trapping load in the predecessor if it is a critical edge.
1180  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1181    BasicBlock *Pred = PN->getIncomingBlock(i);
1182
1183    // If the predecessor has a single successor, then the edge isn't critical.
1184    if (Pred->getTerminator()->getNumSuccessors() == 1)
1185      continue;
1186
1187    Value *InVal = PN->getIncomingValue(i);
1188
1189    // If the InVal is an invoke in the pred, we can't put a load on the edge.
1190    if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1191      if (II->getParent() == Pred)
1192        return false;
1193
1194    // If this pointer is always safe to load, or if we can prove that there is
1195    // already a load in the block, then we can move the load to the pred block.
1196    if (InVal->isDereferenceablePointer() ||
1197        isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1198      continue;
1199
1200    return false;
1201  }
1202
1203  return true;
1204}
1205
1206
1207/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1208/// direct (non-volatile) loads and stores to it.  If the alloca is close but
1209/// not quite there, this will transform the code to allow promotion.  As such,
1210/// it is a non-pure predicate.
1211static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1212  SetVector<Instruction*, SmallVector<Instruction*, 4>,
1213            SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1214
1215  for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1216       UI != UE; ++UI) {
1217    User *U = *UI;
1218    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1219      if (LI->isVolatile())
1220        return false;
1221      continue;
1222    }
1223
1224    if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1225      if (SI->getOperand(0) == AI || SI->isVolatile())
1226        return false;   // Don't allow a store OF the AI, only INTO the AI.
1227      continue;
1228    }
1229
1230    if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1231      // If the condition being selected on is a constant, fold the select, yes
1232      // this does (rarely) happen early on.
1233      if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1234        Value *Result = SI->getOperand(1+CI->isZero());
1235        SI->replaceAllUsesWith(Result);
1236        SI->eraseFromParent();
1237
1238        // This is very rare and we just scrambled the use list of AI, start
1239        // over completely.
1240        return tryToMakeAllocaBePromotable(AI, TD);
1241      }
1242
1243      // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1244      // loads, then we can transform this by rewriting the select.
1245      if (!isSafeSelectToSpeculate(SI, TD))
1246        return false;
1247
1248      InstsToRewrite.insert(SI);
1249      continue;
1250    }
1251
1252    if (PHINode *PN = dyn_cast<PHINode>(U)) {
1253      if (PN->use_empty()) {  // Dead PHIs can be stripped.
1254        InstsToRewrite.insert(PN);
1255        continue;
1256      }
1257
1258      // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1259      // in the pred blocks, then we can transform this by rewriting the PHI.
1260      if (!isSafePHIToSpeculate(PN, TD))
1261        return false;
1262
1263      InstsToRewrite.insert(PN);
1264      continue;
1265    }
1266
1267    return false;
1268  }
1269
1270  // If there are no instructions to rewrite, then all uses are load/stores and
1271  // we're done!
1272  if (InstsToRewrite.empty())
1273    return true;
1274
1275  // If we have instructions that need to be rewritten for this to be promotable
1276  // take care of it now.
1277  for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1278    if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1279      // Selects in InstsToRewrite only have load uses.  Rewrite each as two
1280      // loads with a new select.
1281      while (!SI->use_empty()) {
1282        LoadInst *LI = cast<LoadInst>(SI->use_back());
1283
1284        IRBuilder<> Builder(LI);
1285        LoadInst *TrueLoad =
1286          Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1287        LoadInst *FalseLoad =
1288          Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1289
1290        // Transfer alignment and TBAA info if present.
1291        TrueLoad->setAlignment(LI->getAlignment());
1292        FalseLoad->setAlignment(LI->getAlignment());
1293        if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1294          TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1295          FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1296        }
1297
1298        Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1299        V->takeName(LI);
1300        LI->replaceAllUsesWith(V);
1301        LI->eraseFromParent();
1302      }
1303
1304      // Now that all the loads are gone, the select is gone too.
1305      SI->eraseFromParent();
1306      continue;
1307    }
1308
1309    // Otherwise, we have a PHI node which allows us to push the loads into the
1310    // predecessors.
1311    PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1312    if (PN->use_empty()) {
1313      PN->eraseFromParent();
1314      continue;
1315    }
1316
1317    const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1318    PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1319                                     PN->getName()+".ld", PN);
1320
1321    // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
1322    // matter which one we get and if any differ, it doesn't matter.
1323    LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1324    MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1325    unsigned Align = SomeLoad->getAlignment();
1326
1327    // Rewrite all loads of the PN to use the new PHI.
1328    while (!PN->use_empty()) {
1329      LoadInst *LI = cast<LoadInst>(PN->use_back());
1330      LI->replaceAllUsesWith(NewPN);
1331      LI->eraseFromParent();
1332    }
1333
1334    // Inject loads into all of the pred blocks.  Keep track of which blocks we
1335    // insert them into in case we have multiple edges from the same block.
1336    DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1337
1338    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1339      BasicBlock *Pred = PN->getIncomingBlock(i);
1340      LoadInst *&Load = InsertedLoads[Pred];
1341      if (Load == 0) {
1342        Load = new LoadInst(PN->getIncomingValue(i),
1343                            PN->getName() + "." + Pred->getName(),
1344                            Pred->getTerminator());
1345        Load->setAlignment(Align);
1346        if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1347      }
1348
1349      NewPN->addIncoming(Load, Pred);
1350    }
1351
1352    PN->eraseFromParent();
1353  }
1354
1355  ++NumAdjusted;
1356  return true;
1357}
1358
1359bool SROA::performPromotion(Function &F) {
1360  std::vector<AllocaInst*> Allocas;
1361  DominatorTree *DT = 0;
1362  if (HasDomTree)
1363    DT = &getAnalysis<DominatorTree>();
1364
1365  BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
1366
1367  bool Changed = false;
1368  SmallVector<Instruction*, 64> Insts;
1369  DIBuilder *DIB = 0;
1370  while (1) {
1371    Allocas.clear();
1372
1373    // Find allocas that are safe to promote, by looking at all instructions in
1374    // the entry node
1375    for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1376      if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
1377        if (tryToMakeAllocaBePromotable(AI, TD))
1378          Allocas.push_back(AI);
1379
1380    if (Allocas.empty()) break;
1381
1382    if (HasDomTree)
1383      PromoteMemToReg(Allocas, *DT);
1384    else {
1385      SSAUpdater SSA;
1386      for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1387        AllocaInst *AI = Allocas[i];
1388
1389        // Build list of instructions to promote.
1390        for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1391             UI != E; ++UI)
1392          Insts.push_back(cast<Instruction>(*UI));
1393
1394        DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
1395        if (DDI && !DIB)
1396          DIB = new DIBuilder(*AI->getParent()->getParent()->getParent());
1397        AllocaPromoter(Insts, SSA, DDI, DIB).run(AI, Insts);
1398        Insts.clear();
1399      }
1400    }
1401    NumPromoted += Allocas.size();
1402    Changed = true;
1403  }
1404
1405  // FIXME: Is there a better way to handle the lazy initialization of DIB
1406  // so that there doesn't need to be an explicit delete?
1407  delete DIB;
1408
1409  return Changed;
1410}
1411
1412
1413/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1414/// SROA.  It must be a struct or array type with a small number of elements.
1415static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1416  const Type *T = AI->getAllocatedType();
1417  // Do not promote any struct into more than 32 separate vars.
1418  if (const StructType *ST = dyn_cast<StructType>(T))
1419    return ST->getNumElements() <= 32;
1420  // Arrays are much less likely to be safe for SROA; only consider
1421  // them if they are very small.
1422  if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1423    return AT->getNumElements() <= 8;
1424  return false;
1425}
1426
1427
1428// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1429// which runs on all of the malloc/alloca instructions in the function, removing
1430// them if they are only used by getelementptr instructions.
1431//
1432bool SROA::performScalarRepl(Function &F) {
1433  std::vector<AllocaInst*> WorkList;
1434
1435  // Scan the entry basic block, adding allocas to the worklist.
1436  BasicBlock &BB = F.getEntryBlock();
1437  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1438    if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1439      WorkList.push_back(A);
1440
1441  // Process the worklist
1442  bool Changed = false;
1443  while (!WorkList.empty()) {
1444    AllocaInst *AI = WorkList.back();
1445    WorkList.pop_back();
1446
1447    // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
1448    // with unused elements.
1449    if (AI->use_empty()) {
1450      AI->eraseFromParent();
1451      Changed = true;
1452      continue;
1453    }
1454
1455    // If this alloca is impossible for us to promote, reject it early.
1456    if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1457      continue;
1458
1459    // Check to see if this allocation is only modified by a memcpy/memmove from
1460    // a constant global.  If this is the case, we can change all users to use
1461    // the constant global instead.  This is commonly produced by the CFE by
1462    // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1463    // is only subsequently read.
1464    if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
1465      DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1466      DEBUG(dbgs() << "  memcpy = " << *TheCopy << '\n');
1467      Constant *TheSrc = cast<Constant>(TheCopy->getSource());
1468      AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1469      TheCopy->eraseFromParent();  // Don't mutate the global.
1470      AI->eraseFromParent();
1471      ++NumGlobals;
1472      Changed = true;
1473      continue;
1474    }
1475
1476    // Check to see if we can perform the core SROA transformation.  We cannot
1477    // transform the allocation instruction if it is an array allocation
1478    // (allocations OF arrays are ok though), and an allocation of a scalar
1479    // value cannot be decomposed at all.
1480    uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
1481
1482    // Do not promote [0 x %struct].
1483    if (AllocaSize == 0) continue;
1484
1485    // Do not promote any struct whose size is too big.
1486    if (AllocaSize > SRThreshold) continue;
1487
1488    // If the alloca looks like a good candidate for scalar replacement, and if
1489    // all its users can be transformed, then split up the aggregate into its
1490    // separate elements.
1491    if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1492      DoScalarReplacement(AI, WorkList);
1493      Changed = true;
1494      continue;
1495    }
1496
1497    // If we can turn this aggregate value (potentially with casts) into a
1498    // simple scalar value that can be mem2reg'd into a register value.
1499    // IsNotTrivial tracks whether this is something that mem2reg could have
1500    // promoted itself.  If so, we don't want to transform it needlessly.  Note
1501    // that we can't just check based on the type: the alloca may be of an i32
1502    // but that has pointer arithmetic to set byte 3 of it or something.
1503    if (AllocaInst *NewAI =
1504          ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
1505      NewAI->takeName(AI);
1506      AI->eraseFromParent();
1507      ++NumConverted;
1508      Changed = true;
1509      continue;
1510    }
1511
1512    // Otherwise, couldn't process this alloca.
1513  }
1514
1515  return Changed;
1516}
1517
1518/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1519/// predicate, do SROA now.
1520void SROA::DoScalarReplacement(AllocaInst *AI,
1521                               std::vector<AllocaInst*> &WorkList) {
1522  DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1523  SmallVector<AllocaInst*, 32> ElementAllocas;
1524  if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1525    ElementAllocas.reserve(ST->getNumContainedTypes());
1526    for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1527      AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1528                                      AI->getAlignment(),
1529                                      AI->getName() + "." + Twine(i), AI);
1530      ElementAllocas.push_back(NA);
1531      WorkList.push_back(NA);  // Add to worklist for recursive processing
1532    }
1533  } else {
1534    const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1535    ElementAllocas.reserve(AT->getNumElements());
1536    const Type *ElTy = AT->getElementType();
1537    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1538      AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1539                                      AI->getName() + "." + Twine(i), AI);
1540      ElementAllocas.push_back(NA);
1541      WorkList.push_back(NA);  // Add to worklist for recursive processing
1542    }
1543  }
1544
1545  // Now that we have created the new alloca instructions, rewrite all the
1546  // uses of the old alloca.
1547  RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1548
1549  // Now erase any instructions that were made dead while rewriting the alloca.
1550  DeleteDeadInstructions();
1551  AI->eraseFromParent();
1552
1553  ++NumReplaced;
1554}
1555
1556/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1557/// recursively including all their operands that become trivially dead.
1558void SROA::DeleteDeadInstructions() {
1559  while (!DeadInsts.empty()) {
1560    Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1561
1562    for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1563      if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1564        // Zero out the operand and see if it becomes trivially dead.
1565        // (But, don't add allocas to the dead instruction list -- they are
1566        // already on the worklist and will be deleted separately.)
1567        *OI = 0;
1568        if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1569          DeadInsts.push_back(U);
1570      }
1571
1572    I->eraseFromParent();
1573  }
1574}
1575
1576/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1577/// performing scalar replacement of alloca AI.  The results are flagged in
1578/// the Info parameter.  Offset indicates the position within AI that is
1579/// referenced by this instruction.
1580void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1581                               AllocaInfo &Info) {
1582  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1583    Instruction *User = cast<Instruction>(*UI);
1584
1585    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1586      isSafeForScalarRepl(BC, Offset, Info);
1587    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1588      uint64_t GEPOffset = Offset;
1589      isSafeGEP(GEPI, GEPOffset, Info);
1590      if (!Info.isUnsafe)
1591        isSafeForScalarRepl(GEPI, GEPOffset, Info);
1592    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1593      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1594      if (Length == 0)
1595        return MarkUnsafe(Info, User);
1596      isSafeMemAccess(Offset, Length->getZExtValue(), 0,
1597                      UI.getOperandNo() == 0, Info, MI,
1598                      true /*AllowWholeAccess*/);
1599    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1600      if (LI->isVolatile())
1601        return MarkUnsafe(Info, User);
1602      const Type *LIType = LI->getType();
1603      isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1604                      LIType, false, Info, LI, true /*AllowWholeAccess*/);
1605      Info.hasALoadOrStore = true;
1606
1607    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1608      // Store is ok if storing INTO the pointer, not storing the pointer
1609      if (SI->isVolatile() || SI->getOperand(0) == I)
1610        return MarkUnsafe(Info, User);
1611
1612      const Type *SIType = SI->getOperand(0)->getType();
1613      isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1614                      SIType, true, Info, SI, true /*AllowWholeAccess*/);
1615      Info.hasALoadOrStore = true;
1616    } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1617      isSafePHISelectUseForScalarRepl(User, Offset, Info);
1618    } else {
1619      return MarkUnsafe(Info, User);
1620    }
1621    if (Info.isUnsafe) return;
1622  }
1623}
1624
1625
1626/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1627/// derived from the alloca, we can often still split the alloca into elements.
1628/// This is useful if we have a large alloca where one element is phi'd
1629/// together somewhere: we can SRoA and promote all the other elements even if
1630/// we end up not being able to promote this one.
1631///
1632/// All we require is that the uses of the PHI do not index into other parts of
1633/// the alloca.  The most important use case for this is single load and stores
1634/// that are PHI'd together, which can happen due to code sinking.
1635void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1636                                           AllocaInfo &Info) {
1637  // If we've already checked this PHI, don't do it again.
1638  if (PHINode *PN = dyn_cast<PHINode>(I))
1639    if (!Info.CheckedPHIs.insert(PN))
1640      return;
1641
1642  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1643    Instruction *User = cast<Instruction>(*UI);
1644
1645    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1646      isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1647    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1648      // Only allow "bitcast" GEPs for simplicity.  We could generalize this,
1649      // but would have to prove that we're staying inside of an element being
1650      // promoted.
1651      if (!GEPI->hasAllZeroIndices())
1652        return MarkUnsafe(Info, User);
1653      isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1654    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1655      if (LI->isVolatile())
1656        return MarkUnsafe(Info, User);
1657      const Type *LIType = LI->getType();
1658      isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1659                      LIType, false, Info, LI, false /*AllowWholeAccess*/);
1660      Info.hasALoadOrStore = true;
1661
1662    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1663      // Store is ok if storing INTO the pointer, not storing the pointer
1664      if (SI->isVolatile() || SI->getOperand(0) == I)
1665        return MarkUnsafe(Info, User);
1666
1667      const Type *SIType = SI->getOperand(0)->getType();
1668      isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1669                      SIType, true, Info, SI, false /*AllowWholeAccess*/);
1670      Info.hasALoadOrStore = true;
1671    } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1672      isSafePHISelectUseForScalarRepl(User, Offset, Info);
1673    } else {
1674      return MarkUnsafe(Info, User);
1675    }
1676    if (Info.isUnsafe) return;
1677  }
1678}
1679
1680/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1681/// replacement.  It is safe when all the indices are constant, in-bounds
1682/// references, and when the resulting offset corresponds to an element within
1683/// the alloca type.  The results are flagged in the Info parameter.  Upon
1684/// return, Offset is adjusted as specified by the GEP indices.
1685void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1686                     uint64_t &Offset, AllocaInfo &Info) {
1687  gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1688  if (GEPIt == E)
1689    return;
1690
1691  // Walk through the GEP type indices, checking the types that this indexes
1692  // into.
1693  for (; GEPIt != E; ++GEPIt) {
1694    // Ignore struct elements, no extra checking needed for these.
1695    if ((*GEPIt)->isStructTy())
1696      continue;
1697
1698    ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1699    if (!IdxVal)
1700      return MarkUnsafe(Info, GEPI);
1701  }
1702
1703  // Compute the offset due to this GEP and check if the alloca has a
1704  // component element at that offset.
1705  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1706  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1707                                 &Indices[0], Indices.size());
1708  if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
1709    MarkUnsafe(Info, GEPI);
1710}
1711
1712/// isHomogeneousAggregate - Check if type T is a struct or array containing
1713/// elements of the same type (which is always true for arrays).  If so,
1714/// return true with NumElts and EltTy set to the number of elements and the
1715/// element type, respectively.
1716static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1717                                   const Type *&EltTy) {
1718  if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1719    NumElts = AT->getNumElements();
1720    EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1721    return true;
1722  }
1723  if (const StructType *ST = dyn_cast<StructType>(T)) {
1724    NumElts = ST->getNumContainedTypes();
1725    EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1726    for (unsigned n = 1; n < NumElts; ++n) {
1727      if (ST->getContainedType(n) != EltTy)
1728        return false;
1729    }
1730    return true;
1731  }
1732  return false;
1733}
1734
1735/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1736/// "homogeneous" aggregates with the same element type and number of elements.
1737static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1738  if (T1 == T2)
1739    return true;
1740
1741  unsigned NumElts1, NumElts2;
1742  const Type *EltTy1, *EltTy2;
1743  if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1744      isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1745      NumElts1 == NumElts2 &&
1746      EltTy1 == EltTy2)
1747    return true;
1748
1749  return false;
1750}
1751
1752/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1753/// alloca or has an offset and size that corresponds to a component element
1754/// within it.  The offset checked here may have been formed from a GEP with a
1755/// pointer bitcasted to a different type.
1756///
1757/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1758/// unit.  If false, it only allows accesses known to be in a single element.
1759void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1760                           const Type *MemOpType, bool isStore,
1761                           AllocaInfo &Info, Instruction *TheAccess,
1762                           bool AllowWholeAccess) {
1763  // Check if this is a load/store of the entire alloca.
1764  if (Offset == 0 && AllowWholeAccess &&
1765      MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
1766    // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1767    // loads/stores (which are essentially the same as the MemIntrinsics with
1768    // regard to copying padding between elements).  But, if an alloca is
1769    // flagged as both a source and destination of such operations, we'll need
1770    // to check later for padding between elements.
1771    if (!MemOpType || MemOpType->isIntegerTy()) {
1772      if (isStore)
1773        Info.isMemCpyDst = true;
1774      else
1775        Info.isMemCpySrc = true;
1776      return;
1777    }
1778    // This is also safe for references using a type that is compatible with
1779    // the type of the alloca, so that loads/stores can be rewritten using
1780    // insertvalue/extractvalue.
1781    if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1782      Info.hasSubelementAccess = true;
1783      return;
1784    }
1785  }
1786  // Check if the offset/size correspond to a component within the alloca type.
1787  const Type *T = Info.AI->getAllocatedType();
1788  if (TypeHasComponent(T, Offset, MemSize)) {
1789    Info.hasSubelementAccess = true;
1790    return;
1791  }
1792
1793  return MarkUnsafe(Info, TheAccess);
1794}
1795
1796/// TypeHasComponent - Return true if T has a component type with the
1797/// specified offset and size.  If Size is zero, do not check the size.
1798bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1799  const Type *EltTy;
1800  uint64_t EltSize;
1801  if (const StructType *ST = dyn_cast<StructType>(T)) {
1802    const StructLayout *Layout = TD->getStructLayout(ST);
1803    unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1804    EltTy = ST->getContainedType(EltIdx);
1805    EltSize = TD->getTypeAllocSize(EltTy);
1806    Offset -= Layout->getElementOffset(EltIdx);
1807  } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1808    EltTy = AT->getElementType();
1809    EltSize = TD->getTypeAllocSize(EltTy);
1810    if (Offset >= AT->getNumElements() * EltSize)
1811      return false;
1812    Offset %= EltSize;
1813  } else {
1814    return false;
1815  }
1816  if (Offset == 0 && (Size == 0 || EltSize == Size))
1817    return true;
1818  // Check if the component spans multiple elements.
1819  if (Offset + Size > EltSize)
1820    return false;
1821  return TypeHasComponent(EltTy, Offset, Size);
1822}
1823
1824/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1825/// the instruction I, which references it, to use the separate elements.
1826/// Offset indicates the position within AI that is referenced by this
1827/// instruction.
1828void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1829                                SmallVector<AllocaInst*, 32> &NewElts) {
1830  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1831    Use &TheUse = UI.getUse();
1832    Instruction *User = cast<Instruction>(*UI++);
1833
1834    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1835      RewriteBitCast(BC, AI, Offset, NewElts);
1836      continue;
1837    }
1838
1839    if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1840      RewriteGEP(GEPI, AI, Offset, NewElts);
1841      continue;
1842    }
1843
1844    if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1845      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1846      uint64_t MemSize = Length->getZExtValue();
1847      if (Offset == 0 &&
1848          MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1849        RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1850      // Otherwise the intrinsic can only touch a single element and the
1851      // address operand will be updated, so nothing else needs to be done.
1852      continue;
1853    }
1854
1855    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1856      const Type *LIType = LI->getType();
1857
1858      if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1859        // Replace:
1860        //   %res = load { i32, i32 }* %alloc
1861        // with:
1862        //   %load.0 = load i32* %alloc.0
1863        //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1864        //   %load.1 = load i32* %alloc.1
1865        //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1866        // (Also works for arrays instead of structs)
1867        Value *Insert = UndefValue::get(LIType);
1868        IRBuilder<> Builder(LI);
1869        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1870          Value *Load = Builder.CreateLoad(NewElts[i], "load");
1871          Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
1872        }
1873        LI->replaceAllUsesWith(Insert);
1874        DeadInsts.push_back(LI);
1875      } else if (LIType->isIntegerTy() &&
1876                 TD->getTypeAllocSize(LIType) ==
1877                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1878        // If this is a load of the entire alloca to an integer, rewrite it.
1879        RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1880      }
1881      continue;
1882    }
1883
1884    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1885      Value *Val = SI->getOperand(0);
1886      const Type *SIType = Val->getType();
1887      if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1888        // Replace:
1889        //   store { i32, i32 } %val, { i32, i32 }* %alloc
1890        // with:
1891        //   %val.0 = extractvalue { i32, i32 } %val, 0
1892        //   store i32 %val.0, i32* %alloc.0
1893        //   %val.1 = extractvalue { i32, i32 } %val, 1
1894        //   store i32 %val.1, i32* %alloc.1
1895        // (Also works for arrays instead of structs)
1896        IRBuilder<> Builder(SI);
1897        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1898          Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1899          Builder.CreateStore(Extract, NewElts[i]);
1900        }
1901        DeadInsts.push_back(SI);
1902      } else if (SIType->isIntegerTy() &&
1903                 TD->getTypeAllocSize(SIType) ==
1904                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1905        // If this is a store of the entire alloca from an integer, rewrite it.
1906        RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1907      }
1908      continue;
1909    }
1910
1911    if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1912      // If we have a PHI user of the alloca itself (as opposed to a GEP or
1913      // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
1914      // the new pointer.
1915      if (!isa<AllocaInst>(I)) continue;
1916
1917      assert(Offset == 0 && NewElts[0] &&
1918             "Direct alloca use should have a zero offset");
1919
1920      // If we have a use of the alloca, we know the derived uses will be
1921      // utilizing just the first element of the scalarized result.  Insert a
1922      // bitcast of the first alloca before the user as required.
1923      AllocaInst *NewAI = NewElts[0];
1924      BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1925      NewAI->moveBefore(BCI);
1926      TheUse = BCI;
1927      continue;
1928    }
1929  }
1930}
1931
1932/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1933/// and recursively continue updating all of its uses.
1934void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1935                          SmallVector<AllocaInst*, 32> &NewElts) {
1936  RewriteForScalarRepl(BC, AI, Offset, NewElts);
1937  if (BC->getOperand(0) != AI)
1938    return;
1939
1940  // The bitcast references the original alloca.  Replace its uses with
1941  // references to the first new element alloca.
1942  Instruction *Val = NewElts[0];
1943  if (Val->getType() != BC->getDestTy()) {
1944    Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1945    Val->takeName(BC);
1946  }
1947  BC->replaceAllUsesWith(Val);
1948  DeadInsts.push_back(BC);
1949}
1950
1951/// FindElementAndOffset - Return the index of the element containing Offset
1952/// within the specified type, which must be either a struct or an array.
1953/// Sets T to the type of the element and Offset to the offset within that
1954/// element.  IdxTy is set to the type of the index result to be used in a
1955/// GEP instruction.
1956uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1957                                    const Type *&IdxTy) {
1958  uint64_t Idx = 0;
1959  if (const StructType *ST = dyn_cast<StructType>(T)) {
1960    const StructLayout *Layout = TD->getStructLayout(ST);
1961    Idx = Layout->getElementContainingOffset(Offset);
1962    T = ST->getContainedType(Idx);
1963    Offset -= Layout->getElementOffset(Idx);
1964    IdxTy = Type::getInt32Ty(T->getContext());
1965    return Idx;
1966  }
1967  const ArrayType *AT = cast<ArrayType>(T);
1968  T = AT->getElementType();
1969  uint64_t EltSize = TD->getTypeAllocSize(T);
1970  Idx = Offset / EltSize;
1971  Offset -= Idx * EltSize;
1972  IdxTy = Type::getInt64Ty(T->getContext());
1973  return Idx;
1974}
1975
1976/// RewriteGEP - Check if this GEP instruction moves the pointer across
1977/// elements of the alloca that are being split apart, and if so, rewrite
1978/// the GEP to be relative to the new element.
1979void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1980                      SmallVector<AllocaInst*, 32> &NewElts) {
1981  uint64_t OldOffset = Offset;
1982  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1983  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1984                                 &Indices[0], Indices.size());
1985
1986  RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1987
1988  const Type *T = AI->getAllocatedType();
1989  const Type *IdxTy;
1990  uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1991  if (GEPI->getOperand(0) == AI)
1992    OldIdx = ~0ULL; // Force the GEP to be rewritten.
1993
1994  T = AI->getAllocatedType();
1995  uint64_t EltOffset = Offset;
1996  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1997
1998  // If this GEP does not move the pointer across elements of the alloca
1999  // being split, then it does not needs to be rewritten.
2000  if (Idx == OldIdx)
2001    return;
2002
2003  const Type *i32Ty = Type::getInt32Ty(AI->getContext());
2004  SmallVector<Value*, 8> NewArgs;
2005  NewArgs.push_back(Constant::getNullValue(i32Ty));
2006  while (EltOffset != 0) {
2007    uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2008    NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
2009  }
2010  Instruction *Val = NewElts[Idx];
2011  if (NewArgs.size() > 1) {
2012    Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
2013                                            NewArgs.end(), "", GEPI);
2014    Val->takeName(GEPI);
2015  }
2016  if (Val->getType() != GEPI->getType())
2017    Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
2018  GEPI->replaceAllUsesWith(Val);
2019  DeadInsts.push_back(GEPI);
2020}
2021
2022/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2023/// Rewrite it to copy or set the elements of the scalarized memory.
2024void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2025                                        AllocaInst *AI,
2026                                        SmallVector<AllocaInst*, 32> &NewElts) {
2027  // If this is a memcpy/memmove, construct the other pointer as the
2028  // appropriate type.  The "Other" pointer is the pointer that goes to memory
2029  // that doesn't have anything to do with the alloca that we are promoting. For
2030  // memset, this Value* stays null.
2031  Value *OtherPtr = 0;
2032  unsigned MemAlignment = MI->getAlignment();
2033  if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
2034    if (Inst == MTI->getRawDest())
2035      OtherPtr = MTI->getRawSource();
2036    else {
2037      assert(Inst == MTI->getRawSource());
2038      OtherPtr = MTI->getRawDest();
2039    }
2040  }
2041
2042  // If there is an other pointer, we want to convert it to the same pointer
2043  // type as AI has, so we can GEP through it safely.
2044  if (OtherPtr) {
2045    unsigned AddrSpace =
2046      cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2047
2048    // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
2049    // optimization, but it's also required to detect the corner case where
2050    // both pointer operands are referencing the same memory, and where
2051    // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
2052    // function is only called for mem intrinsics that access the whole
2053    // aggregate, so non-zero GEPs are not an issue here.)
2054    OtherPtr = OtherPtr->stripPointerCasts();
2055
2056    // Copying the alloca to itself is a no-op: just delete it.
2057    if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2058      // This code will run twice for a no-op memcpy -- once for each operand.
2059      // Put only one reference to MI on the DeadInsts list.
2060      for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2061             E = DeadInsts.end(); I != E; ++I)
2062        if (*I == MI) return;
2063      DeadInsts.push_back(MI);
2064      return;
2065    }
2066
2067    // If the pointer is not the right type, insert a bitcast to the right
2068    // type.
2069    const Type *NewTy =
2070      PointerType::get(AI->getType()->getElementType(), AddrSpace);
2071
2072    if (OtherPtr->getType() != NewTy)
2073      OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2074  }
2075
2076  // Process each element of the aggregate.
2077  bool SROADest = MI->getRawDest() == Inst;
2078
2079  Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2080
2081  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2082    // If this is a memcpy/memmove, emit a GEP of the other element address.
2083    Value *OtherElt = 0;
2084    unsigned OtherEltAlign = MemAlignment;
2085
2086    if (OtherPtr) {
2087      Value *Idx[2] = { Zero,
2088                      ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2089      OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
2090                                              OtherPtr->getName()+"."+Twine(i),
2091                                                   MI);
2092      uint64_t EltOffset;
2093      const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2094      const Type *OtherTy = OtherPtrTy->getElementType();
2095      if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
2096        EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2097      } else {
2098        const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2099        EltOffset = TD->getTypeAllocSize(EltTy)*i;
2100      }
2101
2102      // The alignment of the other pointer is the guaranteed alignment of the
2103      // element, which is affected by both the known alignment of the whole
2104      // mem intrinsic and the alignment of the element.  If the alignment of
2105      // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2106      // known alignment is just 4 bytes.
2107      OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2108    }
2109
2110    Value *EltPtr = NewElts[i];
2111    const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2112
2113    // If we got down to a scalar, insert a load or store as appropriate.
2114    if (EltTy->isSingleValueType()) {
2115      if (isa<MemTransferInst>(MI)) {
2116        if (SROADest) {
2117          // From Other to Alloca.
2118          Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2119          new StoreInst(Elt, EltPtr, MI);
2120        } else {
2121          // From Alloca to Other.
2122          Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2123          new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2124        }
2125        continue;
2126      }
2127      assert(isa<MemSetInst>(MI));
2128
2129      // If the stored element is zero (common case), just store a null
2130      // constant.
2131      Constant *StoreVal;
2132      if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2133        if (CI->isZero()) {
2134          StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
2135        } else {
2136          // If EltTy is a vector type, get the element type.
2137          const Type *ValTy = EltTy->getScalarType();
2138
2139          // Construct an integer with the right value.
2140          unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2141          APInt OneVal(EltSize, CI->getZExtValue());
2142          APInt TotalVal(OneVal);
2143          // Set each byte.
2144          for (unsigned i = 0; 8*i < EltSize; ++i) {
2145            TotalVal = TotalVal.shl(8);
2146            TotalVal |= OneVal;
2147          }
2148
2149          // Convert the integer value to the appropriate type.
2150          StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2151          if (ValTy->isPointerTy())
2152            StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2153          else if (ValTy->isFloatingPointTy())
2154            StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2155          assert(StoreVal->getType() == ValTy && "Type mismatch!");
2156
2157          // If the requested value was a vector constant, create it.
2158          if (EltTy != ValTy) {
2159            unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2160            SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
2161            StoreVal = ConstantVector::get(Elts);
2162          }
2163        }
2164        new StoreInst(StoreVal, EltPtr, MI);
2165        continue;
2166      }
2167      // Otherwise, if we're storing a byte variable, use a memset call for
2168      // this element.
2169    }
2170
2171    unsigned EltSize = TD->getTypeAllocSize(EltTy);
2172
2173    IRBuilder<> Builder(MI);
2174
2175    // Finally, insert the meminst for this element.
2176    if (isa<MemSetInst>(MI)) {
2177      Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2178                           MI->isVolatile());
2179    } else {
2180      assert(isa<MemTransferInst>(MI));
2181      Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
2182      Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
2183
2184      if (isa<MemCpyInst>(MI))
2185        Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2186      else
2187        Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2188    }
2189  }
2190  DeadInsts.push_back(MI);
2191}
2192
2193/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2194/// overwrites the entire allocation.  Extract out the pieces of the stored
2195/// integer and store them individually.
2196void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2197                                         SmallVector<AllocaInst*, 32> &NewElts){
2198  // Extract each element out of the integer according to its structure offset
2199  // and store the element value to the individual alloca.
2200  Value *SrcVal = SI->getOperand(0);
2201  const Type *AllocaEltTy = AI->getAllocatedType();
2202  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2203
2204  IRBuilder<> Builder(SI);
2205
2206  // Handle tail padding by extending the operand
2207  if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2208    SrcVal = Builder.CreateZExt(SrcVal,
2209                            IntegerType::get(SI->getContext(), AllocaSizeBits));
2210
2211  DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2212               << '\n');
2213
2214  // There are two forms here: AI could be an array or struct.  Both cases
2215  // have different ways to compute the element offset.
2216  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2217    const StructLayout *Layout = TD->getStructLayout(EltSTy);
2218
2219    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2220      // Get the number of bits to shift SrcVal to get the value.
2221      const Type *FieldTy = EltSTy->getElementType(i);
2222      uint64_t Shift = Layout->getElementOffsetInBits(i);
2223
2224      if (TD->isBigEndian())
2225        Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
2226
2227      Value *EltVal = SrcVal;
2228      if (Shift) {
2229        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2230        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2231      }
2232
2233      // Truncate down to an integer of the right size.
2234      uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2235
2236      // Ignore zero sized fields like {}, they obviously contain no data.
2237      if (FieldSizeBits == 0) continue;
2238
2239      if (FieldSizeBits != AllocaSizeBits)
2240        EltVal = Builder.CreateTrunc(EltVal,
2241                             IntegerType::get(SI->getContext(), FieldSizeBits));
2242      Value *DestField = NewElts[i];
2243      if (EltVal->getType() == FieldTy) {
2244        // Storing to an integer field of this size, just do it.
2245      } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2246        // Bitcast to the right element type (for fp/vector values).
2247        EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2248      } else {
2249        // Otherwise, bitcast the dest pointer (for aggregates).
2250        DestField = Builder.CreateBitCast(DestField,
2251                                     PointerType::getUnqual(EltVal->getType()));
2252      }
2253      new StoreInst(EltVal, DestField, SI);
2254    }
2255
2256  } else {
2257    const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2258    const Type *ArrayEltTy = ATy->getElementType();
2259    uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2260    uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2261
2262    uint64_t Shift;
2263
2264    if (TD->isBigEndian())
2265      Shift = AllocaSizeBits-ElementOffset;
2266    else
2267      Shift = 0;
2268
2269    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2270      // Ignore zero sized fields like {}, they obviously contain no data.
2271      if (ElementSizeBits == 0) continue;
2272
2273      Value *EltVal = SrcVal;
2274      if (Shift) {
2275        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2276        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2277      }
2278
2279      // Truncate down to an integer of the right size.
2280      if (ElementSizeBits != AllocaSizeBits)
2281        EltVal = Builder.CreateTrunc(EltVal,
2282                                     IntegerType::get(SI->getContext(),
2283                                                      ElementSizeBits));
2284      Value *DestField = NewElts[i];
2285      if (EltVal->getType() == ArrayEltTy) {
2286        // Storing to an integer field of this size, just do it.
2287      } else if (ArrayEltTy->isFloatingPointTy() ||
2288                 ArrayEltTy->isVectorTy()) {
2289        // Bitcast to the right element type (for fp/vector values).
2290        EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2291      } else {
2292        // Otherwise, bitcast the dest pointer (for aggregates).
2293        DestField = Builder.CreateBitCast(DestField,
2294                                     PointerType::getUnqual(EltVal->getType()));
2295      }
2296      new StoreInst(EltVal, DestField, SI);
2297
2298      if (TD->isBigEndian())
2299        Shift -= ElementOffset;
2300      else
2301        Shift += ElementOffset;
2302    }
2303  }
2304
2305  DeadInsts.push_back(SI);
2306}
2307
2308/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2309/// an integer.  Load the individual pieces to form the aggregate value.
2310void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2311                                        SmallVector<AllocaInst*, 32> &NewElts) {
2312  // Extract each element out of the NewElts according to its structure offset
2313  // and form the result value.
2314  const Type *AllocaEltTy = AI->getAllocatedType();
2315  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2316
2317  DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2318               << '\n');
2319
2320  // There are two forms here: AI could be an array or struct.  Both cases
2321  // have different ways to compute the element offset.
2322  const StructLayout *Layout = 0;
2323  uint64_t ArrayEltBitOffset = 0;
2324  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2325    Layout = TD->getStructLayout(EltSTy);
2326  } else {
2327    const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2328    ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2329  }
2330
2331  Value *ResultVal =
2332    Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2333
2334  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2335    // Load the value from the alloca.  If the NewElt is an aggregate, cast
2336    // the pointer to an integer of the same size before doing the load.
2337    Value *SrcField = NewElts[i];
2338    const Type *FieldTy =
2339      cast<PointerType>(SrcField->getType())->getElementType();
2340    uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2341
2342    // Ignore zero sized fields like {}, they obviously contain no data.
2343    if (FieldSizeBits == 0) continue;
2344
2345    const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2346                                                     FieldSizeBits);
2347    if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2348        !FieldTy->isVectorTy())
2349      SrcField = new BitCastInst(SrcField,
2350                                 PointerType::getUnqual(FieldIntTy),
2351                                 "", LI);
2352    SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2353
2354    // If SrcField is a fp or vector of the right size but that isn't an
2355    // integer type, bitcast to an integer so we can shift it.
2356    if (SrcField->getType() != FieldIntTy)
2357      SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2358
2359    // Zero extend the field to be the same size as the final alloca so that
2360    // we can shift and insert it.
2361    if (SrcField->getType() != ResultVal->getType())
2362      SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2363
2364    // Determine the number of bits to shift SrcField.
2365    uint64_t Shift;
2366    if (Layout) // Struct case.
2367      Shift = Layout->getElementOffsetInBits(i);
2368    else  // Array case.
2369      Shift = i*ArrayEltBitOffset;
2370
2371    if (TD->isBigEndian())
2372      Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2373
2374    if (Shift) {
2375      Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2376      SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2377    }
2378
2379    // Don't create an 'or x, 0' on the first iteration.
2380    if (!isa<Constant>(ResultVal) ||
2381        !cast<Constant>(ResultVal)->isNullValue())
2382      ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2383    else
2384      ResultVal = SrcField;
2385  }
2386
2387  // Handle tail padding by truncating the result
2388  if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2389    ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2390
2391  LI->replaceAllUsesWith(ResultVal);
2392  DeadInsts.push_back(LI);
2393}
2394
2395/// HasPadding - Return true if the specified type has any structure or
2396/// alignment padding in between the elements that would be split apart
2397/// by SROA; return false otherwise.
2398static bool HasPadding(const Type *Ty, const TargetData &TD) {
2399  if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2400    Ty = ATy->getElementType();
2401    return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
2402  }
2403
2404  // SROA currently handles only Arrays and Structs.
2405  const StructType *STy = cast<StructType>(Ty);
2406  const StructLayout *SL = TD.getStructLayout(STy);
2407  unsigned PrevFieldBitOffset = 0;
2408  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2409    unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2410
2411    // Check to see if there is any padding between this element and the
2412    // previous one.
2413    if (i) {
2414      unsigned PrevFieldEnd =
2415        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2416      if (PrevFieldEnd < FieldBitOffset)
2417        return true;
2418    }
2419    PrevFieldBitOffset = FieldBitOffset;
2420  }
2421  // Check for tail padding.
2422  if (unsigned EltCount = STy->getNumElements()) {
2423    unsigned PrevFieldEnd = PrevFieldBitOffset +
2424      TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2425    if (PrevFieldEnd < SL->getSizeInBits())
2426      return true;
2427  }
2428  return false;
2429}
2430
2431/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2432/// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
2433/// or 1 if safe after canonicalization has been performed.
2434bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2435  // Loop over the use list of the alloca.  We can only transform it if all of
2436  // the users are safe to transform.
2437  AllocaInfo Info(AI);
2438
2439  isSafeForScalarRepl(AI, 0, Info);
2440  if (Info.isUnsafe) {
2441    DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2442    return false;
2443  }
2444
2445  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
2446  // source and destination, we have to be careful.  In particular, the memcpy
2447  // could be moving around elements that live in structure padding of the LLVM
2448  // types, but may actually be used.  In these cases, we refuse to promote the
2449  // struct.
2450  if (Info.isMemCpySrc && Info.isMemCpyDst &&
2451      HasPadding(AI->getAllocatedType(), *TD))
2452    return false;
2453
2454  // If the alloca never has an access to just *part* of it, but is accessed
2455  // via loads and stores, then we should use ConvertToScalarInfo to promote
2456  // the alloca instead of promoting each piece at a time and inserting fission
2457  // and fusion code.
2458  if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2459    // If the struct/array just has one element, use basic SRoA.
2460    if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2461      if (ST->getNumElements() > 1) return false;
2462    } else {
2463      if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2464        return false;
2465    }
2466  }
2467
2468  return true;
2469}
2470
2471
2472
2473/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2474/// some part of a constant global variable.  This intentionally only accepts
2475/// constant expressions because we don't can't rewrite arbitrary instructions.
2476static bool PointsToConstantGlobal(Value *V) {
2477  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2478    return GV->isConstant();
2479  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2480    if (CE->getOpcode() == Instruction::BitCast ||
2481        CE->getOpcode() == Instruction::GetElementPtr)
2482      return PointsToConstantGlobal(CE->getOperand(0));
2483  return false;
2484}
2485
2486/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2487/// pointer to an alloca.  Ignore any reads of the pointer, return false if we
2488/// see any stores or other unknown uses.  If we see pointer arithmetic, keep
2489/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2490/// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
2491/// the alloca, and if the source pointer is a pointer to a constant global, we
2492/// can optimize this.
2493static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2494                                           bool isOffset) {
2495  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
2496    User *U = cast<Instruction>(*UI);
2497
2498    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2499      // Ignore non-volatile loads, they are always ok.
2500      if (LI->isVolatile()) return false;
2501      continue;
2502    }
2503
2504    if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
2505      // If uses of the bitcast are ok, we are ok.
2506      if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2507        return false;
2508      continue;
2509    }
2510    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
2511      // If the GEP has all zero indices, it doesn't offset the pointer.  If it
2512      // doesn't, it does.
2513      if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2514                                         isOffset || !GEP->hasAllZeroIndices()))
2515        return false;
2516      continue;
2517    }
2518
2519    if (CallSite CS = U) {
2520      // If this is the function being called then we treat it like a load and
2521      // ignore it.
2522      if (CS.isCallee(UI))
2523        continue;
2524
2525      // If this is a readonly/readnone call site, then we know it is just a
2526      // load (but one that potentially returns the value itself), so we can
2527      // ignore it if we know that the value isn't captured.
2528      unsigned ArgNo = CS.getArgumentNo(UI);
2529      if (CS.onlyReadsMemory() &&
2530          (CS.getInstruction()->use_empty() ||
2531           CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
2532        continue;
2533
2534      // If this is being passed as a byval argument, the caller is making a
2535      // copy, so it is only a read of the alloca.
2536      if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2537        continue;
2538    }
2539
2540    // If this is isn't our memcpy/memmove, reject it as something we can't
2541    // handle.
2542    MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2543    if (MI == 0)
2544      return false;
2545
2546    // If the transfer is using the alloca as a source of the transfer, then
2547    // ignore it since it is a load (unless the transfer is volatile).
2548    if (UI.getOperandNo() == 1) {
2549      if (MI->isVolatile()) return false;
2550      continue;
2551    }
2552
2553    // If we already have seen a copy, reject the second one.
2554    if (TheCopy) return false;
2555
2556    // If the pointer has been offset from the start of the alloca, we can't
2557    // safely handle this.
2558    if (isOffset) return false;
2559
2560    // If the memintrinsic isn't using the alloca as the dest, reject it.
2561    if (UI.getOperandNo() != 0) return false;
2562
2563    // If the source of the memcpy/move is not a constant global, reject it.
2564    if (!PointsToConstantGlobal(MI->getSource()))
2565      return false;
2566
2567    // Otherwise, the transform is safe.  Remember the copy instruction.
2568    TheCopy = MI;
2569  }
2570  return true;
2571}
2572
2573/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2574/// modified by a copy from a constant global.  If we can prove this, we can
2575/// replace any uses of the alloca with uses of the global directly.
2576MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2577  MemTransferInst *TheCopy = 0;
2578  if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2579    return TheCopy;
2580  return 0;
2581}
2582