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