ScalarReplAggregates.cpp revision 85a7c690852d6151acff0d8821762d75bc774ab4
1//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation.  This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
13// each member (if possible).  Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs.  As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "scalarrepl"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Function.h"
27#include "llvm/GlobalVariable.h"
28#include "llvm/Instructions.h"
29#include "llvm/IntrinsicInst.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/Module.h"
32#include "llvm/Pass.h"
33#include "llvm/Analysis/Dominators.h"
34#include "llvm/Analysis/ValueTracking.h"
35#include "llvm/Target/TargetData.h"
36#include "llvm/Transforms/Utils/PromoteMemToReg.h"
37#include "llvm/Transforms/Utils/Local.h"
38#include "llvm/Transforms/Utils/SSAUpdater.h"
39#include "llvm/Support/CallSite.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/GetElementPtrTypeIterator.h"
43#include "llvm/Support/IRBuilder.h"
44#include "llvm/Support/MathExtras.h"
45#include "llvm/Support/raw_ostream.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/ADT/Statistic.h"
48using namespace llvm;
49
50STATISTIC(NumReplaced,  "Number of allocas broken up");
51STATISTIC(NumPromoted,  "Number of allocas promoted");
52STATISTIC(NumConverted, "Number of aggregates converted to scalar");
53STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
54
55namespace {
56  struct SROA : public FunctionPass {
57    SROA(int T, bool hasDT, char &ID)
58      : FunctionPass(ID), HasDomTree(hasDT) {
59      if (T == -1)
60        SRThreshold = 128;
61      else
62        SRThreshold = T;
63    }
64
65    bool runOnFunction(Function &F);
66
67    bool performScalarRepl(Function &F);
68    bool performPromotion(Function &F);
69
70  private:
71    bool HasDomTree;
72    TargetData *TD;
73
74    /// DeadInsts - Keep track of instructions we have made dead, so that
75    /// we can remove them after we are done working.
76    SmallVector<Value*, 32> DeadInsts;
77
78    /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
79    /// information about the uses.  All these fields are initialized to false
80    /// and set to true when something is learned.
81    struct AllocaInfo {
82      /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
83      bool isUnsafe : 1;
84
85      /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
86      bool isMemCpySrc : 1;
87
88      /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
89      bool isMemCpyDst : 1;
90
91      /// hasSubelementAccess - This is true if a subelement of the alloca is
92      /// ever accessed, or false if the alloca is only accessed with mem
93      /// intrinsics or load/store that only access the entire alloca at once.
94      bool hasSubelementAccess : 1;
95
96      /// hasALoadOrStore - This is true if there are any loads or stores to it.
97      /// The alloca may just be accessed with memcpy, for example, which would
98      /// not set this.
99      bool hasALoadOrStore : 1;
100
101      AllocaInfo()
102        : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
103          hasSubelementAccess(false), hasALoadOrStore(false) {}
104    };
105
106    unsigned SRThreshold;
107
108    void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
109
110    bool isSafeAllocaToScalarRepl(AllocaInst *AI);
111
112    void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
113                             AllocaInfo &Info);
114    void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
115                   AllocaInfo &Info);
116    void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
117                         const Type *MemOpType, bool isStore, AllocaInfo &Info);
118    bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
119    uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
120                                  const Type *&IdxTy);
121
122    void DoScalarReplacement(AllocaInst *AI,
123                             std::vector<AllocaInst*> &WorkList);
124    void DeleteDeadInstructions();
125
126    void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
127                              SmallVector<AllocaInst*, 32> &NewElts);
128    void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
129                        SmallVector<AllocaInst*, 32> &NewElts);
130    void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
131                    SmallVector<AllocaInst*, 32> &NewElts);
132    void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
133                                      AllocaInst *AI,
134                                      SmallVector<AllocaInst*, 32> &NewElts);
135    void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
136                                       SmallVector<AllocaInst*, 32> &NewElts);
137    void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
138                                      SmallVector<AllocaInst*, 32> &NewElts);
139
140    static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
141  };
142
143  // SROA_DT - SROA that uses DominatorTree.
144  struct SROA_DT : public SROA {
145    static char ID;
146  public:
147    SROA_DT(int T = -1) : SROA(T, true, ID) {
148      initializeSROA_DTPass(*PassRegistry::getPassRegistry());
149    }
150
151    // getAnalysisUsage - This pass does not require any passes, but we know it
152    // will not alter the CFG, so say so.
153    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154      AU.addRequired<DominatorTree>();
155      AU.setPreservesCFG();
156    }
157  };
158
159  // SROA_SSAUp - SROA that uses SSAUpdater.
160  struct SROA_SSAUp : public SROA {
161    static char ID;
162  public:
163    SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
164      initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
165    }
166
167    // getAnalysisUsage - This pass does not require any passes, but we know it
168    // will not alter the CFG, so say so.
169    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
170      AU.setPreservesCFG();
171    }
172  };
173
174}
175
176char SROA_DT::ID = 0;
177char SROA_SSAUp::ID = 0;
178
179INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
180                "Scalar Replacement of Aggregates (DT)", false, false)
181INITIALIZE_PASS_DEPENDENCY(DominatorTree)
182INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
183                "Scalar Replacement of Aggregates (DT)", false, false)
184
185INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
186                      "Scalar Replacement of Aggregates (SSAUp)", false, false)
187INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
188                    "Scalar Replacement of Aggregates (SSAUp)", false, false)
189
190// Public interface to the ScalarReplAggregates pass
191FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
192                                                   bool UseDomTree) {
193  if (UseDomTree)
194    return new SROA_DT(Threshold);
195  return new SROA_SSAUp(Threshold);
196}
197
198
199//===----------------------------------------------------------------------===//
200// Convert To Scalar Optimization.
201//===----------------------------------------------------------------------===//
202
203namespace {
204/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
205/// optimization, which scans the uses of an alloca and determines if it can
206/// rewrite it in terms of a single new alloca that can be mem2reg'd.
207class ConvertToScalarInfo {
208  /// AllocaSize - The size of the alloca being considered.
209  unsigned AllocaSize;
210  const TargetData &TD;
211
212  /// IsNotTrivial - This is set to true if there is some access to the object
213  /// which means that mem2reg can't promote it.
214  bool IsNotTrivial;
215
216  /// VectorTy - This tracks the type that we should promote the vector to if
217  /// it is possible to turn it into a vector.  This starts out null, and if it
218  /// isn't possible to turn into a vector type, it gets set to VoidTy.
219  const Type *VectorTy;
220
221  /// HadAVector - True if there is at least one vector access to the alloca.
222  /// We don't want to turn random arrays into vectors and use vector element
223  /// insert/extract, but if there are element accesses to something that is
224  /// also declared as a vector, we do want to promote to a vector.
225  bool HadAVector;
226
227public:
228  explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
229    : AllocaSize(Size), TD(td) {
230    IsNotTrivial = false;
231    VectorTy = 0;
232    HadAVector = false;
233  }
234
235  AllocaInst *TryConvert(AllocaInst *AI);
236
237private:
238  bool CanConvertToScalar(Value *V, uint64_t Offset);
239  void MergeInType(const Type *In, uint64_t Offset);
240  void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
241
242  Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
243                                    uint64_t Offset, IRBuilder<> &Builder);
244  Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
245                                   uint64_t Offset, IRBuilder<> &Builder);
246};
247} // end anonymous namespace.
248
249
250/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
251/// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
252/// alloca if possible or null if not.
253AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
254  // If we can't convert this scalar, or if mem2reg can trivially do it, bail
255  // out.
256  if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
257    return 0;
258
259  // If we were able to find a vector type that can handle this with
260  // insert/extract elements, and if there was at least one use that had
261  // a vector type, promote this to a vector.  We don't want to promote
262  // random stuff that doesn't use vectors (e.g. <9 x double>) because then
263  // we just get a lot of insert/extracts.  If at least one vector is
264  // involved, then we probably really do have a union of vector/array.
265  const Type *NewTy;
266  if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
267    DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
268          << *VectorTy << '\n');
269    NewTy = VectorTy;  // Use the vector type.
270  } else {
271    DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
272    // Create and insert the integer alloca.
273    NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
274  }
275  AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
276  ConvertUsesToScalar(AI, NewAI, 0);
277  return NewAI;
278}
279
280/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
281/// so far at the offset specified by Offset (which is specified in bytes).
282///
283/// There are two cases we handle here:
284///   1) A union of vector types of the same size and potentially its elements.
285///      Here we turn element accesses into insert/extract element operations.
286///      This promotes a <4 x float> with a store of float to the third element
287///      into a <4 x float> that uses insert element.
288///   2) A fully general blob of memory, which we turn into some (potentially
289///      large) integer type with extract and insert operations where the loads
290///      and stores would mutate the memory.  We mark this by setting VectorTy
291///      to VoidTy.
292void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
293  // If we already decided to turn this into a blob of integer memory, there is
294  // nothing to be done.
295  if (VectorTy && VectorTy->isVoidTy())
296    return;
297
298  // If this could be contributing to a vector, analyze it.
299
300  // If the In type is a vector that is the same size as the alloca, see if it
301  // matches the existing VecTy.
302  if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
303    // Remember if we saw a vector type.
304    HadAVector = true;
305
306    if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
307      // If we're storing/loading a vector of the right size, allow it as a
308      // vector.  If this the first vector we see, remember the type so that
309      // we know the element size.  If this is a subsequent access, ignore it
310      // even if it is a differing type but the same size.  Worst case we can
311      // bitcast the resultant vectors.
312      if (VectorTy == 0)
313        VectorTy = VInTy;
314      return;
315    }
316  } else if (In->isFloatTy() || In->isDoubleTy() ||
317             (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
318              isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
319    // If we're accessing something that could be an element of a vector, see
320    // if the implied vector agrees with what we already have and if Offset is
321    // compatible with it.
322    unsigned EltSize = In->getPrimitiveSizeInBits()/8;
323    if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
324        (VectorTy == 0 ||
325         cast<VectorType>(VectorTy)->getElementType()
326               ->getPrimitiveSizeInBits()/8 == EltSize)) {
327      if (VectorTy == 0)
328        VectorTy = VectorType::get(In, AllocaSize/EltSize);
329      return;
330    }
331  }
332
333  // Otherwise, we have a case that we can't handle with an optimized vector
334  // form.  We can still turn this into a large integer.
335  VectorTy = Type::getVoidTy(In->getContext());
336}
337
338/// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
339/// its accesses to a single vector type, return true and set VecTy to
340/// the new type.  If we could convert the alloca into a single promotable
341/// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
342/// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
343/// is the current offset from the base of the alloca being analyzed.
344///
345/// If we see at least one access to the value that is as a vector type, set the
346/// SawVec flag.
347bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
348  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
349    Instruction *User = cast<Instruction>(*UI);
350
351    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
352      // Don't break volatile loads.
353      if (LI->isVolatile())
354        return false;
355      // Don't touch MMX operations.
356      if (LI->getType()->isX86_MMXTy())
357        return false;
358      MergeInType(LI->getType(), Offset);
359      continue;
360    }
361
362    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
363      // Storing the pointer, not into the value?
364      if (SI->getOperand(0) == V || SI->isVolatile()) return false;
365      // Don't touch MMX operations.
366      if (SI->getOperand(0)->getType()->isX86_MMXTy())
367        return false;
368      MergeInType(SI->getOperand(0)->getType(), Offset);
369      continue;
370    }
371
372    if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
373      IsNotTrivial = true;  // Can't be mem2reg'd.
374      if (!CanConvertToScalar(BCI, Offset))
375        return false;
376      continue;
377    }
378
379    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
380      // If this is a GEP with a variable indices, we can't handle it.
381      if (!GEP->hasAllConstantIndices())
382        return false;
383
384      // Compute the offset that this GEP adds to the pointer.
385      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
386      uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
387                                               &Indices[0], Indices.size());
388      // See if all uses can be converted.
389      if (!CanConvertToScalar(GEP, Offset+GEPOffset))
390        return false;
391      IsNotTrivial = true;  // Can't be mem2reg'd.
392      continue;
393    }
394
395    // If this is a constant sized memset of a constant value (e.g. 0) we can
396    // handle it.
397    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
398      // Store of constant value and constant size.
399      if (!isa<ConstantInt>(MSI->getValue()) ||
400          !isa<ConstantInt>(MSI->getLength()))
401        return false;
402      IsNotTrivial = true;  // Can't be mem2reg'd.
403      continue;
404    }
405
406    // If this is a memcpy or memmove into or out of the whole allocation, we
407    // can handle it like a load or store of the scalar type.
408    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
409      ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
410      if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
411        return false;
412
413      IsNotTrivial = true;  // Can't be mem2reg'd.
414      continue;
415    }
416
417    // Otherwise, we cannot handle this!
418    return false;
419  }
420
421  return true;
422}
423
424/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
425/// directly.  This happens when we are converting an "integer union" to a
426/// single integer scalar, or when we are converting a "vector union" to a
427/// vector with insert/extractelement instructions.
428///
429/// Offset is an offset from the original alloca, in bits that need to be
430/// shifted to the right.  By the end of this, there should be no uses of Ptr.
431void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
432                                              uint64_t Offset) {
433  while (!Ptr->use_empty()) {
434    Instruction *User = cast<Instruction>(Ptr->use_back());
435
436    if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
437      ConvertUsesToScalar(CI, NewAI, Offset);
438      CI->eraseFromParent();
439      continue;
440    }
441
442    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
443      // Compute the offset that this GEP adds to the pointer.
444      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
445      uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
446                                               &Indices[0], Indices.size());
447      ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
448      GEP->eraseFromParent();
449      continue;
450    }
451
452    IRBuilder<> Builder(User);
453
454    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
455      // The load is a bit extract from NewAI shifted right by Offset bits.
456      Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
457      Value *NewLoadVal
458        = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
459      LI->replaceAllUsesWith(NewLoadVal);
460      LI->eraseFromParent();
461      continue;
462    }
463
464    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
465      assert(SI->getOperand(0) != Ptr && "Consistency error!");
466      Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
467      Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
468                                             Builder);
469      Builder.CreateStore(New, NewAI);
470      SI->eraseFromParent();
471
472      // If the load we just inserted is now dead, then the inserted store
473      // overwrote the entire thing.
474      if (Old->use_empty())
475        Old->eraseFromParent();
476      continue;
477    }
478
479    // If this is a constant sized memset of a constant value (e.g. 0) we can
480    // transform it into a store of the expanded constant value.
481    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
482      assert(MSI->getRawDest() == Ptr && "Consistency error!");
483      unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
484      if (NumBytes != 0) {
485        unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
486
487        // Compute the value replicated the right number of times.
488        APInt APVal(NumBytes*8, Val);
489
490        // Splat the value if non-zero.
491        if (Val)
492          for (unsigned i = 1; i != NumBytes; ++i)
493            APVal |= APVal << 8;
494
495        Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
496        Value *New = ConvertScalar_InsertValue(
497                                    ConstantInt::get(User->getContext(), APVal),
498                                               Old, Offset, Builder);
499        Builder.CreateStore(New, NewAI);
500
501        // If the load we just inserted is now dead, then the memset overwrote
502        // the entire thing.
503        if (Old->use_empty())
504          Old->eraseFromParent();
505      }
506      MSI->eraseFromParent();
507      continue;
508    }
509
510    // If this is a memcpy or memmove into or out of the whole allocation, we
511    // can handle it like a load or store of the scalar type.
512    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
513      assert(Offset == 0 && "must be store to start of alloca");
514
515      // If the source and destination are both to the same alloca, then this is
516      // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
517      // as appropriate.
518      AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, 0));
519
520      if (GetUnderlyingObject(MTI->getSource(), 0) != OrigAI) {
521        // Dest must be OrigAI, change this to be a load from the original
522        // pointer (bitcasted), then a store to our new alloca.
523        assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
524        Value *SrcPtr = MTI->getSource();
525        const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
526        const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
527        if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
528          AIPTy = PointerType::get(AIPTy->getElementType(),
529                                   SPTy->getAddressSpace());
530        }
531        SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
532
533        LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
534        SrcVal->setAlignment(MTI->getAlignment());
535        Builder.CreateStore(SrcVal, NewAI);
536      } else if (GetUnderlyingObject(MTI->getDest(), 0) != OrigAI) {
537        // Src must be OrigAI, change this to be a load from NewAI then a store
538        // through the original dest pointer (bitcasted).
539        assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
540        LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
541
542        const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
543        const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
544        if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
545          AIPTy = PointerType::get(AIPTy->getElementType(),
546                                   DPTy->getAddressSpace());
547        }
548        Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
549
550        StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
551        NewStore->setAlignment(MTI->getAlignment());
552      } else {
553        // Noop transfer. Src == Dst
554      }
555
556      MTI->eraseFromParent();
557      continue;
558    }
559
560    llvm_unreachable("Unsupported operation!");
561  }
562}
563
564/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
565/// or vector value FromVal, extracting the bits from the offset specified by
566/// Offset.  This returns the value, which is of type ToType.
567///
568/// This happens when we are converting an "integer union" to a single
569/// integer scalar, or when we are converting a "vector union" to a vector with
570/// insert/extractelement instructions.
571///
572/// Offset is an offset from the original alloca, in bits that need to be
573/// shifted to the right.
574Value *ConvertToScalarInfo::
575ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
576                           uint64_t Offset, IRBuilder<> &Builder) {
577  // If the load is of the whole new alloca, no conversion is needed.
578  if (FromVal->getType() == ToType && Offset == 0)
579    return FromVal;
580
581  // If the result alloca is a vector type, this is either an element
582  // access or a bitcast to another vector type of the same size.
583  if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
584    if (ToType->isVectorTy())
585      return Builder.CreateBitCast(FromVal, ToType, "tmp");
586
587    // Otherwise it must be an element access.
588    unsigned Elt = 0;
589    if (Offset) {
590      unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
591      Elt = Offset/EltSize;
592      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
593    }
594    // Return the element extracted out of it.
595    Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
596                    Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
597    if (V->getType() != ToType)
598      V = Builder.CreateBitCast(V, ToType, "tmp");
599    return V;
600  }
601
602  // If ToType is a first class aggregate, extract out each of the pieces and
603  // use insertvalue's to form the FCA.
604  if (const StructType *ST = dyn_cast<StructType>(ToType)) {
605    const StructLayout &Layout = *TD.getStructLayout(ST);
606    Value *Res = UndefValue::get(ST);
607    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
608      Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
609                                        Offset+Layout.getElementOffsetInBits(i),
610                                              Builder);
611      Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
612    }
613    return Res;
614  }
615
616  if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
617    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
618    Value *Res = UndefValue::get(AT);
619    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
620      Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
621                                              Offset+i*EltSize, Builder);
622      Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
623    }
624    return Res;
625  }
626
627  // Otherwise, this must be a union that was converted to an integer value.
628  const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
629
630  // If this is a big-endian system and the load is narrower than the
631  // full alloca type, we need to do a shift to get the right bits.
632  int ShAmt = 0;
633  if (TD.isBigEndian()) {
634    // On big-endian machines, the lowest bit is stored at the bit offset
635    // from the pointer given by getTypeStoreSizeInBits.  This matters for
636    // integers with a bitwidth that is not a multiple of 8.
637    ShAmt = TD.getTypeStoreSizeInBits(NTy) -
638            TD.getTypeStoreSizeInBits(ToType) - Offset;
639  } else {
640    ShAmt = Offset;
641  }
642
643  // Note: we support negative bitwidths (with shl) which are not defined.
644  // We do this to support (f.e.) loads off the end of a structure where
645  // only some bits are used.
646  if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
647    FromVal = Builder.CreateLShr(FromVal,
648                                 ConstantInt::get(FromVal->getType(),
649                                                           ShAmt), "tmp");
650  else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
651    FromVal = Builder.CreateShl(FromVal,
652                                ConstantInt::get(FromVal->getType(),
653                                                          -ShAmt), "tmp");
654
655  // Finally, unconditionally truncate the integer to the right width.
656  unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
657  if (LIBitWidth < NTy->getBitWidth())
658    FromVal =
659      Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
660                                                    LIBitWidth), "tmp");
661  else if (LIBitWidth > NTy->getBitWidth())
662    FromVal =
663       Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
664                                                    LIBitWidth), "tmp");
665
666  // If the result is an integer, this is a trunc or bitcast.
667  if (ToType->isIntegerTy()) {
668    // Should be done.
669  } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
670    // Just do a bitcast, we know the sizes match up.
671    FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
672  } else {
673    // Otherwise must be a pointer.
674    FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
675  }
676  assert(FromVal->getType() == ToType && "Didn't convert right?");
677  return FromVal;
678}
679
680/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
681/// or vector value "Old" at the offset specified by Offset.
682///
683/// This happens when we are converting an "integer union" to a
684/// single integer scalar, or when we are converting a "vector union" to a
685/// vector with insert/extractelement instructions.
686///
687/// Offset is an offset from the original alloca, in bits that need to be
688/// shifted to the right.
689Value *ConvertToScalarInfo::
690ConvertScalar_InsertValue(Value *SV, Value *Old,
691                          uint64_t Offset, IRBuilder<> &Builder) {
692  // Convert the stored type to the actual type, shift it left to insert
693  // then 'or' into place.
694  const Type *AllocaType = Old->getType();
695  LLVMContext &Context = Old->getContext();
696
697  if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
698    uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
699    uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
700
701    // Changing the whole vector with memset or with an access of a different
702    // vector type?
703    if (ValSize == VecSize)
704      return Builder.CreateBitCast(SV, AllocaType, "tmp");
705
706    uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
707
708    // Must be an element insertion.
709    unsigned Elt = Offset/EltSize;
710
711    if (SV->getType() != VTy->getElementType())
712      SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
713
714    SV = Builder.CreateInsertElement(Old, SV,
715                     ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
716                                     "tmp");
717    return SV;
718  }
719
720  // If SV is a first-class aggregate value, insert each value recursively.
721  if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
722    const StructLayout &Layout = *TD.getStructLayout(ST);
723    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
724      Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
725      Old = ConvertScalar_InsertValue(Elt, Old,
726                                      Offset+Layout.getElementOffsetInBits(i),
727                                      Builder);
728    }
729    return Old;
730  }
731
732  if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
733    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
734    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
735      Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
736      Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
737    }
738    return Old;
739  }
740
741  // If SV is a float, convert it to the appropriate integer type.
742  // If it is a pointer, do the same.
743  unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
744  unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
745  unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
746  unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
747  if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
748    SV = Builder.CreateBitCast(SV,
749                            IntegerType::get(SV->getContext(),SrcWidth), "tmp");
750  else if (SV->getType()->isPointerTy())
751    SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
752
753  // Zero extend or truncate the value if needed.
754  if (SV->getType() != AllocaType) {
755    if (SV->getType()->getPrimitiveSizeInBits() <
756             AllocaType->getPrimitiveSizeInBits())
757      SV = Builder.CreateZExt(SV, AllocaType, "tmp");
758    else {
759      // Truncation may be needed if storing more than the alloca can hold
760      // (undefined behavior).
761      SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
762      SrcWidth = DestWidth;
763      SrcStoreWidth = DestStoreWidth;
764    }
765  }
766
767  // If this is a big-endian system and the store is narrower than the
768  // full alloca type, we need to do a shift to get the right bits.
769  int ShAmt = 0;
770  if (TD.isBigEndian()) {
771    // On big-endian machines, the lowest bit is stored at the bit offset
772    // from the pointer given by getTypeStoreSizeInBits.  This matters for
773    // integers with a bitwidth that is not a multiple of 8.
774    ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
775  } else {
776    ShAmt = Offset;
777  }
778
779  // Note: we support negative bitwidths (with shr) which are not defined.
780  // We do this to support (f.e.) stores off the end of a structure where
781  // only some bits in the structure are set.
782  APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
783  if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
784    SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
785                           ShAmt), "tmp");
786    Mask <<= ShAmt;
787  } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
788    SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
789                            -ShAmt), "tmp");
790    Mask = Mask.lshr(-ShAmt);
791  }
792
793  // Mask out the bits we are about to insert from the old value, and or
794  // in the new bits.
795  if (SrcWidth != DestWidth) {
796    assert(DestWidth > SrcWidth);
797    Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
798    SV = Builder.CreateOr(Old, SV, "ins");
799  }
800  return SV;
801}
802
803
804//===----------------------------------------------------------------------===//
805// SRoA Driver
806//===----------------------------------------------------------------------===//
807
808
809bool SROA::runOnFunction(Function &F) {
810  TD = getAnalysisIfAvailable<TargetData>();
811
812  bool Changed = performPromotion(F);
813
814  // FIXME: ScalarRepl currently depends on TargetData more than it
815  // theoretically needs to. It should be refactored in order to support
816  // target-independent IR. Until this is done, just skip the actual
817  // scalar-replacement portion of this pass.
818  if (!TD) return Changed;
819
820  while (1) {
821    bool LocalChange = performScalarRepl(F);
822    if (!LocalChange) break;   // No need to repromote if no scalarrepl
823    Changed = true;
824    LocalChange = performPromotion(F);
825    if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
826  }
827
828  return Changed;
829}
830
831namespace {
832class AllocaPromoter : public LoadAndStorePromoter {
833  AllocaInst *AI;
834public:
835  AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
836    : LoadAndStorePromoter(Insts, S), AI(0) {}
837
838  void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
839    // Remember which alloca we're promoting (for isInstInList).
840    this->AI = AI;
841    LoadAndStorePromoter::run(Insts);
842    AI->eraseFromParent();
843  }
844
845  virtual bool isInstInList(Instruction *I,
846                            const SmallVectorImpl<Instruction*> &Insts) const {
847    if (LoadInst *LI = dyn_cast<LoadInst>(I))
848      return LI->getOperand(0) == AI;
849    return cast<StoreInst>(I)->getPointerOperand() == AI;
850  }
851};
852} // end anon namespace
853
854bool SROA::performPromotion(Function &F) {
855  std::vector<AllocaInst*> Allocas;
856  DominatorTree *DT = 0;
857  if (HasDomTree)
858    DT = &getAnalysis<DominatorTree>();
859
860  BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
861
862  bool Changed = false;
863  SmallVector<Instruction*, 64> Insts;
864  while (1) {
865    Allocas.clear();
866
867    // Find allocas that are safe to promote, by looking at all instructions in
868    // the entry node
869    for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
870      if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
871        if (isAllocaPromotable(AI))
872          Allocas.push_back(AI);
873
874    if (Allocas.empty()) break;
875
876    if (HasDomTree)
877      PromoteMemToReg(Allocas, *DT);
878    else {
879      SSAUpdater SSA;
880      for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
881        AllocaInst *AI = Allocas[i];
882
883        // Build list of instructions to promote.
884        for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
885             UI != E; ++UI)
886          Insts.push_back(cast<Instruction>(*UI));
887
888        AllocaPromoter(Insts, SSA).run(AI, Insts);
889        Insts.clear();
890      }
891    }
892    NumPromoted += Allocas.size();
893    Changed = true;
894  }
895
896  return Changed;
897}
898
899
900/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
901/// SROA.  It must be a struct or array type with a small number of elements.
902static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
903  const Type *T = AI->getAllocatedType();
904  // Do not promote any struct into more than 32 separate vars.
905  if (const StructType *ST = dyn_cast<StructType>(T))
906    return ST->getNumElements() <= 32;
907  // Arrays are much less likely to be safe for SROA; only consider
908  // them if they are very small.
909  if (const ArrayType *AT = dyn_cast<ArrayType>(T))
910    return AT->getNumElements() <= 8;
911  return false;
912}
913
914
915// performScalarRepl - This algorithm is a simple worklist driven algorithm,
916// which runs on all of the malloc/alloca instructions in the function, removing
917// them if they are only used by getelementptr instructions.
918//
919bool SROA::performScalarRepl(Function &F) {
920  std::vector<AllocaInst*> WorkList;
921
922  // Scan the entry basic block, adding allocas to the worklist.
923  BasicBlock &BB = F.getEntryBlock();
924  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
925    if (AllocaInst *A = dyn_cast<AllocaInst>(I))
926      WorkList.push_back(A);
927
928  // Process the worklist
929  bool Changed = false;
930  while (!WorkList.empty()) {
931    AllocaInst *AI = WorkList.back();
932    WorkList.pop_back();
933
934    // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
935    // with unused elements.
936    if (AI->use_empty()) {
937      AI->eraseFromParent();
938      Changed = true;
939      continue;
940    }
941
942    // If this alloca is impossible for us to promote, reject it early.
943    if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
944      continue;
945
946    // Check to see if this allocation is only modified by a memcpy/memmove from
947    // a constant global.  If this is the case, we can change all users to use
948    // the constant global instead.  This is commonly produced by the CFE by
949    // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
950    // is only subsequently read.
951    if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
952      DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
953      DEBUG(dbgs() << "  memcpy = " << *TheCopy << '\n');
954      Constant *TheSrc = cast<Constant>(TheCopy->getSource());
955      AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
956      TheCopy->eraseFromParent();  // Don't mutate the global.
957      AI->eraseFromParent();
958      ++NumGlobals;
959      Changed = true;
960      continue;
961    }
962
963    // Check to see if we can perform the core SROA transformation.  We cannot
964    // transform the allocation instruction if it is an array allocation
965    // (allocations OF arrays are ok though), and an allocation of a scalar
966    // value cannot be decomposed at all.
967    uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
968
969    // Do not promote [0 x %struct].
970    if (AllocaSize == 0) continue;
971
972    // Do not promote any struct whose size is too big.
973    if (AllocaSize > SRThreshold) continue;
974
975    // If the alloca looks like a good candidate for scalar replacement, and if
976    // all its users can be transformed, then split up the aggregate into its
977    // separate elements.
978    if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
979      DoScalarReplacement(AI, WorkList);
980      Changed = true;
981      continue;
982    }
983
984    // If we can turn this aggregate value (potentially with casts) into a
985    // simple scalar value that can be mem2reg'd into a register value.
986    // IsNotTrivial tracks whether this is something that mem2reg could have
987    // promoted itself.  If so, we don't want to transform it needlessly.  Note
988    // that we can't just check based on the type: the alloca may be of an i32
989    // but that has pointer arithmetic to set byte 3 of it or something.
990    if (AllocaInst *NewAI =
991          ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
992      NewAI->takeName(AI);
993      AI->eraseFromParent();
994      ++NumConverted;
995      Changed = true;
996      continue;
997    }
998
999    // Otherwise, couldn't process this alloca.
1000  }
1001
1002  return Changed;
1003}
1004
1005/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1006/// predicate, do SROA now.
1007void SROA::DoScalarReplacement(AllocaInst *AI,
1008                               std::vector<AllocaInst*> &WorkList) {
1009  DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1010  SmallVector<AllocaInst*, 32> ElementAllocas;
1011  if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1012    ElementAllocas.reserve(ST->getNumContainedTypes());
1013    for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1014      AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1015                                      AI->getAlignment(),
1016                                      AI->getName() + "." + Twine(i), AI);
1017      ElementAllocas.push_back(NA);
1018      WorkList.push_back(NA);  // Add to worklist for recursive processing
1019    }
1020  } else {
1021    const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1022    ElementAllocas.reserve(AT->getNumElements());
1023    const Type *ElTy = AT->getElementType();
1024    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1025      AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1026                                      AI->getName() + "." + Twine(i), AI);
1027      ElementAllocas.push_back(NA);
1028      WorkList.push_back(NA);  // Add to worklist for recursive processing
1029    }
1030  }
1031
1032  // Now that we have created the new alloca instructions, rewrite all the
1033  // uses of the old alloca.
1034  RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1035
1036  // Now erase any instructions that were made dead while rewriting the alloca.
1037  DeleteDeadInstructions();
1038  AI->eraseFromParent();
1039
1040  ++NumReplaced;
1041}
1042
1043/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1044/// recursively including all their operands that become trivially dead.
1045void SROA::DeleteDeadInstructions() {
1046  while (!DeadInsts.empty()) {
1047    Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1048
1049    for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1050      if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1051        // Zero out the operand and see if it becomes trivially dead.
1052        // (But, don't add allocas to the dead instruction list -- they are
1053        // already on the worklist and will be deleted separately.)
1054        *OI = 0;
1055        if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1056          DeadInsts.push_back(U);
1057      }
1058
1059    I->eraseFromParent();
1060  }
1061}
1062
1063/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1064/// performing scalar replacement of alloca AI.  The results are flagged in
1065/// the Info parameter.  Offset indicates the position within AI that is
1066/// referenced by this instruction.
1067void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1068                               AllocaInfo &Info) {
1069  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1070    Instruction *User = cast<Instruction>(*UI);
1071
1072    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1073      isSafeForScalarRepl(BC, AI, Offset, Info);
1074    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1075      uint64_t GEPOffset = Offset;
1076      isSafeGEP(GEPI, AI, GEPOffset, Info);
1077      if (!Info.isUnsafe)
1078        isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
1079    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1080      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1081      if (Length)
1082        isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
1083                        UI.getOperandNo() == 0, Info);
1084      else
1085        MarkUnsafe(Info);
1086    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1087      if (!LI->isVolatile()) {
1088        const Type *LIType = LI->getType();
1089        isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
1090                        LIType, false, Info);
1091        Info.hasALoadOrStore = true;
1092      } else
1093        MarkUnsafe(Info);
1094    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1095      // Store is ok if storing INTO the pointer, not storing the pointer
1096      if (!SI->isVolatile() && SI->getOperand(0) != I) {
1097        const Type *SIType = SI->getOperand(0)->getType();
1098        isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
1099                        SIType, true, Info);
1100        Info.hasALoadOrStore = true;
1101      } else
1102        MarkUnsafe(Info);
1103    } else {
1104      DEBUG(errs() << "  Transformation preventing inst: " << *User << '\n');
1105      MarkUnsafe(Info);
1106    }
1107    if (Info.isUnsafe) return;
1108  }
1109}
1110
1111/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1112/// replacement.  It is safe when all the indices are constant, in-bounds
1113/// references, and when the resulting offset corresponds to an element within
1114/// the alloca type.  The results are flagged in the Info parameter.  Upon
1115/// return, Offset is adjusted as specified by the GEP indices.
1116void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
1117                     uint64_t &Offset, AllocaInfo &Info) {
1118  gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1119  if (GEPIt == E)
1120    return;
1121
1122  // Walk through the GEP type indices, checking the types that this indexes
1123  // into.
1124  for (; GEPIt != E; ++GEPIt) {
1125    // Ignore struct elements, no extra checking needed for these.
1126    if ((*GEPIt)->isStructTy())
1127      continue;
1128
1129    ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1130    if (!IdxVal)
1131      return MarkUnsafe(Info);
1132  }
1133
1134  // Compute the offset due to this GEP and check if the alloca has a
1135  // component element at that offset.
1136  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1137  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1138                                 &Indices[0], Indices.size());
1139  if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1140    MarkUnsafe(Info);
1141}
1142
1143/// isHomogeneousAggregate - Check if type T is a struct or array containing
1144/// elements of the same type (which is always true for arrays).  If so,
1145/// return true with NumElts and EltTy set to the number of elements and the
1146/// element type, respectively.
1147static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1148                                   const Type *&EltTy) {
1149  if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1150    NumElts = AT->getNumElements();
1151    EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1152    return true;
1153  }
1154  if (const StructType *ST = dyn_cast<StructType>(T)) {
1155    NumElts = ST->getNumContainedTypes();
1156    EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1157    for (unsigned n = 1; n < NumElts; ++n) {
1158      if (ST->getContainedType(n) != EltTy)
1159        return false;
1160    }
1161    return true;
1162  }
1163  return false;
1164}
1165
1166/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1167/// "homogeneous" aggregates with the same element type and number of elements.
1168static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1169  if (T1 == T2)
1170    return true;
1171
1172  unsigned NumElts1, NumElts2;
1173  const Type *EltTy1, *EltTy2;
1174  if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1175      isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1176      NumElts1 == NumElts2 &&
1177      EltTy1 == EltTy2)
1178    return true;
1179
1180  return false;
1181}
1182
1183/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1184/// alloca or has an offset and size that corresponds to a component element
1185/// within it.  The offset checked here may have been formed from a GEP with a
1186/// pointer bitcasted to a different type.
1187void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
1188                           const Type *MemOpType, bool isStore,
1189                           AllocaInfo &Info) {
1190  // Check if this is a load/store of the entire alloca.
1191  if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
1192    // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1193    // loads/stores (which are essentially the same as the MemIntrinsics with
1194    // regard to copying padding between elements).  But, if an alloca is
1195    // flagged as both a source and destination of such operations, we'll need
1196    // to check later for padding between elements.
1197    if (!MemOpType || MemOpType->isIntegerTy()) {
1198      if (isStore)
1199        Info.isMemCpyDst = true;
1200      else
1201        Info.isMemCpySrc = true;
1202      return;
1203    }
1204    // This is also safe for references using a type that is compatible with
1205    // the type of the alloca, so that loads/stores can be rewritten using
1206    // insertvalue/extractvalue.
1207    if (isCompatibleAggregate(MemOpType, AI->getAllocatedType())) {
1208      Info.hasSubelementAccess = true;
1209      return;
1210    }
1211  }
1212  // Check if the offset/size correspond to a component within the alloca type.
1213  const Type *T = AI->getAllocatedType();
1214  if (TypeHasComponent(T, Offset, MemSize)) {
1215    Info.hasSubelementAccess = true;
1216    return;
1217  }
1218
1219  return MarkUnsafe(Info);
1220}
1221
1222/// TypeHasComponent - Return true if T has a component type with the
1223/// specified offset and size.  If Size is zero, do not check the size.
1224bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1225  const Type *EltTy;
1226  uint64_t EltSize;
1227  if (const StructType *ST = dyn_cast<StructType>(T)) {
1228    const StructLayout *Layout = TD->getStructLayout(ST);
1229    unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1230    EltTy = ST->getContainedType(EltIdx);
1231    EltSize = TD->getTypeAllocSize(EltTy);
1232    Offset -= Layout->getElementOffset(EltIdx);
1233  } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1234    EltTy = AT->getElementType();
1235    EltSize = TD->getTypeAllocSize(EltTy);
1236    if (Offset >= AT->getNumElements() * EltSize)
1237      return false;
1238    Offset %= EltSize;
1239  } else {
1240    return false;
1241  }
1242  if (Offset == 0 && (Size == 0 || EltSize == Size))
1243    return true;
1244  // Check if the component spans multiple elements.
1245  if (Offset + Size > EltSize)
1246    return false;
1247  return TypeHasComponent(EltTy, Offset, Size);
1248}
1249
1250/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1251/// the instruction I, which references it, to use the separate elements.
1252/// Offset indicates the position within AI that is referenced by this
1253/// instruction.
1254void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1255                                SmallVector<AllocaInst*, 32> &NewElts) {
1256  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1257    Instruction *User = cast<Instruction>(*UI);
1258
1259    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1260      RewriteBitCast(BC, AI, Offset, NewElts);
1261    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1262      RewriteGEP(GEPI, AI, Offset, NewElts);
1263    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1264      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1265      uint64_t MemSize = Length->getZExtValue();
1266      if (Offset == 0 &&
1267          MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1268        RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1269      // Otherwise the intrinsic can only touch a single element and the
1270      // address operand will be updated, so nothing else needs to be done.
1271    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1272      const Type *LIType = LI->getType();
1273
1274      if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1275        // Replace:
1276        //   %res = load { i32, i32 }* %alloc
1277        // with:
1278        //   %load.0 = load i32* %alloc.0
1279        //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1280        //   %load.1 = load i32* %alloc.1
1281        //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1282        // (Also works for arrays instead of structs)
1283        Value *Insert = UndefValue::get(LIType);
1284        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1285          Value *Load = new LoadInst(NewElts[i], "load", LI);
1286          Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1287        }
1288        LI->replaceAllUsesWith(Insert);
1289        DeadInsts.push_back(LI);
1290      } else if (LIType->isIntegerTy() &&
1291                 TD->getTypeAllocSize(LIType) ==
1292                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1293        // If this is a load of the entire alloca to an integer, rewrite it.
1294        RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1295      }
1296    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1297      Value *Val = SI->getOperand(0);
1298      const Type *SIType = Val->getType();
1299      if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1300        // Replace:
1301        //   store { i32, i32 } %val, { i32, i32 }* %alloc
1302        // with:
1303        //   %val.0 = extractvalue { i32, i32 } %val, 0
1304        //   store i32 %val.0, i32* %alloc.0
1305        //   %val.1 = extractvalue { i32, i32 } %val, 1
1306        //   store i32 %val.1, i32* %alloc.1
1307        // (Also works for arrays instead of structs)
1308        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1309          Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1310          new StoreInst(Extract, NewElts[i], SI);
1311        }
1312        DeadInsts.push_back(SI);
1313      } else if (SIType->isIntegerTy() &&
1314                 TD->getTypeAllocSize(SIType) ==
1315                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1316        // If this is a store of the entire alloca from an integer, rewrite it.
1317        RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1318      }
1319    }
1320  }
1321}
1322
1323/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1324/// and recursively continue updating all of its uses.
1325void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1326                          SmallVector<AllocaInst*, 32> &NewElts) {
1327  RewriteForScalarRepl(BC, AI, Offset, NewElts);
1328  if (BC->getOperand(0) != AI)
1329    return;
1330
1331  // The bitcast references the original alloca.  Replace its uses with
1332  // references to the first new element alloca.
1333  Instruction *Val = NewElts[0];
1334  if (Val->getType() != BC->getDestTy()) {
1335    Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1336    Val->takeName(BC);
1337  }
1338  BC->replaceAllUsesWith(Val);
1339  DeadInsts.push_back(BC);
1340}
1341
1342/// FindElementAndOffset - Return the index of the element containing Offset
1343/// within the specified type, which must be either a struct or an array.
1344/// Sets T to the type of the element and Offset to the offset within that
1345/// element.  IdxTy is set to the type of the index result to be used in a
1346/// GEP instruction.
1347uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1348                                    const Type *&IdxTy) {
1349  uint64_t Idx = 0;
1350  if (const StructType *ST = dyn_cast<StructType>(T)) {
1351    const StructLayout *Layout = TD->getStructLayout(ST);
1352    Idx = Layout->getElementContainingOffset(Offset);
1353    T = ST->getContainedType(Idx);
1354    Offset -= Layout->getElementOffset(Idx);
1355    IdxTy = Type::getInt32Ty(T->getContext());
1356    return Idx;
1357  }
1358  const ArrayType *AT = cast<ArrayType>(T);
1359  T = AT->getElementType();
1360  uint64_t EltSize = TD->getTypeAllocSize(T);
1361  Idx = Offset / EltSize;
1362  Offset -= Idx * EltSize;
1363  IdxTy = Type::getInt64Ty(T->getContext());
1364  return Idx;
1365}
1366
1367/// RewriteGEP - Check if this GEP instruction moves the pointer across
1368/// elements of the alloca that are being split apart, and if so, rewrite
1369/// the GEP to be relative to the new element.
1370void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1371                      SmallVector<AllocaInst*, 32> &NewElts) {
1372  uint64_t OldOffset = Offset;
1373  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1374  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1375                                 &Indices[0], Indices.size());
1376
1377  RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1378
1379  const Type *T = AI->getAllocatedType();
1380  const Type *IdxTy;
1381  uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1382  if (GEPI->getOperand(0) == AI)
1383    OldIdx = ~0ULL; // Force the GEP to be rewritten.
1384
1385  T = AI->getAllocatedType();
1386  uint64_t EltOffset = Offset;
1387  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1388
1389  // If this GEP does not move the pointer across elements of the alloca
1390  // being split, then it does not needs to be rewritten.
1391  if (Idx == OldIdx)
1392    return;
1393
1394  const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1395  SmallVector<Value*, 8> NewArgs;
1396  NewArgs.push_back(Constant::getNullValue(i32Ty));
1397  while (EltOffset != 0) {
1398    uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1399    NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1400  }
1401  Instruction *Val = NewElts[Idx];
1402  if (NewArgs.size() > 1) {
1403    Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1404                                            NewArgs.end(), "", GEPI);
1405    Val->takeName(GEPI);
1406  }
1407  if (Val->getType() != GEPI->getType())
1408    Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1409  GEPI->replaceAllUsesWith(Val);
1410  DeadInsts.push_back(GEPI);
1411}
1412
1413/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1414/// Rewrite it to copy or set the elements of the scalarized memory.
1415void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
1416                                        AllocaInst *AI,
1417                                        SmallVector<AllocaInst*, 32> &NewElts) {
1418  // If this is a memcpy/memmove, construct the other pointer as the
1419  // appropriate type.  The "Other" pointer is the pointer that goes to memory
1420  // that doesn't have anything to do with the alloca that we are promoting. For
1421  // memset, this Value* stays null.
1422  Value *OtherPtr = 0;
1423  unsigned MemAlignment = MI->getAlignment();
1424  if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
1425    if (Inst == MTI->getRawDest())
1426      OtherPtr = MTI->getRawSource();
1427    else {
1428      assert(Inst == MTI->getRawSource());
1429      OtherPtr = MTI->getRawDest();
1430    }
1431  }
1432
1433  // If there is an other pointer, we want to convert it to the same pointer
1434  // type as AI has, so we can GEP through it safely.
1435  if (OtherPtr) {
1436    unsigned AddrSpace =
1437      cast<PointerType>(OtherPtr->getType())->getAddressSpace();
1438
1439    // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
1440    // optimization, but it's also required to detect the corner case where
1441    // both pointer operands are referencing the same memory, and where
1442    // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
1443    // function is only called for mem intrinsics that access the whole
1444    // aggregate, so non-zero GEPs are not an issue here.)
1445    OtherPtr = OtherPtr->stripPointerCasts();
1446
1447    // Copying the alloca to itself is a no-op: just delete it.
1448    if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1449      // This code will run twice for a no-op memcpy -- once for each operand.
1450      // Put only one reference to MI on the DeadInsts list.
1451      for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1452             E = DeadInsts.end(); I != E; ++I)
1453        if (*I == MI) return;
1454      DeadInsts.push_back(MI);
1455      return;
1456    }
1457
1458    // If the pointer is not the right type, insert a bitcast to the right
1459    // type.
1460    const Type *NewTy =
1461      PointerType::get(AI->getType()->getElementType(), AddrSpace);
1462
1463    if (OtherPtr->getType() != NewTy)
1464      OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
1465  }
1466
1467  // Process each element of the aggregate.
1468  bool SROADest = MI->getRawDest() == Inst;
1469
1470  Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
1471
1472  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1473    // If this is a memcpy/memmove, emit a GEP of the other element address.
1474    Value *OtherElt = 0;
1475    unsigned OtherEltAlign = MemAlignment;
1476
1477    if (OtherPtr) {
1478      Value *Idx[2] = { Zero,
1479                      ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
1480      OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
1481                                              OtherPtr->getName()+"."+Twine(i),
1482                                                   MI);
1483      uint64_t EltOffset;
1484      const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
1485      const Type *OtherTy = OtherPtrTy->getElementType();
1486      if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
1487        EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1488      } else {
1489        const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
1490        EltOffset = TD->getTypeAllocSize(EltTy)*i;
1491      }
1492
1493      // The alignment of the other pointer is the guaranteed alignment of the
1494      // element, which is affected by both the known alignment of the whole
1495      // mem intrinsic and the alignment of the element.  If the alignment of
1496      // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1497      // known alignment is just 4 bytes.
1498      OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
1499    }
1500
1501    Value *EltPtr = NewElts[i];
1502    const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
1503
1504    // If we got down to a scalar, insert a load or store as appropriate.
1505    if (EltTy->isSingleValueType()) {
1506      if (isa<MemTransferInst>(MI)) {
1507        if (SROADest) {
1508          // From Other to Alloca.
1509          Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1510          new StoreInst(Elt, EltPtr, MI);
1511        } else {
1512          // From Alloca to Other.
1513          Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1514          new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1515        }
1516        continue;
1517      }
1518      assert(isa<MemSetInst>(MI));
1519
1520      // If the stored element is zero (common case), just store a null
1521      // constant.
1522      Constant *StoreVal;
1523      if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
1524        if (CI->isZero()) {
1525          StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
1526        } else {
1527          // If EltTy is a vector type, get the element type.
1528          const Type *ValTy = EltTy->getScalarType();
1529
1530          // Construct an integer with the right value.
1531          unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1532          APInt OneVal(EltSize, CI->getZExtValue());
1533          APInt TotalVal(OneVal);
1534          // Set each byte.
1535          for (unsigned i = 0; 8*i < EltSize; ++i) {
1536            TotalVal = TotalVal.shl(8);
1537            TotalVal |= OneVal;
1538          }
1539
1540          // Convert the integer value to the appropriate type.
1541          StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
1542          if (ValTy->isPointerTy())
1543            StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
1544          else if (ValTy->isFloatingPointTy())
1545            StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
1546          assert(StoreVal->getType() == ValTy && "Type mismatch!");
1547
1548          // If the requested value was a vector constant, create it.
1549          if (EltTy != ValTy) {
1550            unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1551            SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
1552            StoreVal = ConstantVector::get(&Elts[0], NumElts);
1553          }
1554        }
1555        new StoreInst(StoreVal, EltPtr, MI);
1556        continue;
1557      }
1558      // Otherwise, if we're storing a byte variable, use a memset call for
1559      // this element.
1560    }
1561
1562    unsigned EltSize = TD->getTypeAllocSize(EltTy);
1563
1564    IRBuilder<> Builder(MI);
1565
1566    // Finally, insert the meminst for this element.
1567    if (isa<MemSetInst>(MI)) {
1568      Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1569                           MI->isVolatile());
1570    } else {
1571      assert(isa<MemTransferInst>(MI));
1572      Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
1573      Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
1574
1575      if (isa<MemCpyInst>(MI))
1576        Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1577      else
1578        Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
1579    }
1580  }
1581  DeadInsts.push_back(MI);
1582}
1583
1584/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
1585/// overwrites the entire allocation.  Extract out the pieces of the stored
1586/// integer and store them individually.
1587void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
1588                                         SmallVector<AllocaInst*, 32> &NewElts){
1589  // Extract each element out of the integer according to its structure offset
1590  // and store the element value to the individual alloca.
1591  Value *SrcVal = SI->getOperand(0);
1592  const Type *AllocaEltTy = AI->getAllocatedType();
1593  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1594
1595  IRBuilder<> Builder(SI);
1596
1597  // Handle tail padding by extending the operand
1598  if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
1599    SrcVal = Builder.CreateZExt(SrcVal,
1600                            IntegerType::get(SI->getContext(), AllocaSizeBits));
1601
1602  DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
1603               << '\n');
1604
1605  // There are two forms here: AI could be an array or struct.  Both cases
1606  // have different ways to compute the element offset.
1607  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1608    const StructLayout *Layout = TD->getStructLayout(EltSTy);
1609
1610    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1611      // Get the number of bits to shift SrcVal to get the value.
1612      const Type *FieldTy = EltSTy->getElementType(i);
1613      uint64_t Shift = Layout->getElementOffsetInBits(i);
1614
1615      if (TD->isBigEndian())
1616        Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
1617
1618      Value *EltVal = SrcVal;
1619      if (Shift) {
1620        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1621        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
1622      }
1623
1624      // Truncate down to an integer of the right size.
1625      uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1626
1627      // Ignore zero sized fields like {}, they obviously contain no data.
1628      if (FieldSizeBits == 0) continue;
1629
1630      if (FieldSizeBits != AllocaSizeBits)
1631        EltVal = Builder.CreateTrunc(EltVal,
1632                             IntegerType::get(SI->getContext(), FieldSizeBits));
1633      Value *DestField = NewElts[i];
1634      if (EltVal->getType() == FieldTy) {
1635        // Storing to an integer field of this size, just do it.
1636      } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
1637        // Bitcast to the right element type (for fp/vector values).
1638        EltVal = Builder.CreateBitCast(EltVal, FieldTy);
1639      } else {
1640        // Otherwise, bitcast the dest pointer (for aggregates).
1641        DestField = Builder.CreateBitCast(DestField,
1642                                     PointerType::getUnqual(EltVal->getType()));
1643      }
1644      new StoreInst(EltVal, DestField, SI);
1645    }
1646
1647  } else {
1648    const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1649    const Type *ArrayEltTy = ATy->getElementType();
1650    uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1651    uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1652
1653    uint64_t Shift;
1654
1655    if (TD->isBigEndian())
1656      Shift = AllocaSizeBits-ElementOffset;
1657    else
1658      Shift = 0;
1659
1660    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1661      // Ignore zero sized fields like {}, they obviously contain no data.
1662      if (ElementSizeBits == 0) continue;
1663
1664      Value *EltVal = SrcVal;
1665      if (Shift) {
1666        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1667        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
1668      }
1669
1670      // Truncate down to an integer of the right size.
1671      if (ElementSizeBits != AllocaSizeBits)
1672        EltVal = Builder.CreateTrunc(EltVal,
1673                                     IntegerType::get(SI->getContext(),
1674                                                      ElementSizeBits));
1675      Value *DestField = NewElts[i];
1676      if (EltVal->getType() == ArrayEltTy) {
1677        // Storing to an integer field of this size, just do it.
1678      } else if (ArrayEltTy->isFloatingPointTy() ||
1679                 ArrayEltTy->isVectorTy()) {
1680        // Bitcast to the right element type (for fp/vector values).
1681        EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
1682      } else {
1683        // Otherwise, bitcast the dest pointer (for aggregates).
1684        DestField = Builder.CreateBitCast(DestField,
1685                                     PointerType::getUnqual(EltVal->getType()));
1686      }
1687      new StoreInst(EltVal, DestField, SI);
1688
1689      if (TD->isBigEndian())
1690        Shift -= ElementOffset;
1691      else
1692        Shift += ElementOffset;
1693    }
1694  }
1695
1696  DeadInsts.push_back(SI);
1697}
1698
1699/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
1700/// an integer.  Load the individual pieces to form the aggregate value.
1701void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1702                                        SmallVector<AllocaInst*, 32> &NewElts) {
1703  // Extract each element out of the NewElts according to its structure offset
1704  // and form the result value.
1705  const Type *AllocaEltTy = AI->getAllocatedType();
1706  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1707
1708  DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1709               << '\n');
1710
1711  // There are two forms here: AI could be an array or struct.  Both cases
1712  // have different ways to compute the element offset.
1713  const StructLayout *Layout = 0;
1714  uint64_t ArrayEltBitOffset = 0;
1715  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1716    Layout = TD->getStructLayout(EltSTy);
1717  } else {
1718    const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1719    ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1720  }
1721
1722  Value *ResultVal =
1723    Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1724
1725  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1726    // Load the value from the alloca.  If the NewElt is an aggregate, cast
1727    // the pointer to an integer of the same size before doing the load.
1728    Value *SrcField = NewElts[i];
1729    const Type *FieldTy =
1730      cast<PointerType>(SrcField->getType())->getElementType();
1731    uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1732
1733    // Ignore zero sized fields like {}, they obviously contain no data.
1734    if (FieldSizeBits == 0) continue;
1735
1736    const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1737                                                     FieldSizeBits);
1738    if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1739        !FieldTy->isVectorTy())
1740      SrcField = new BitCastInst(SrcField,
1741                                 PointerType::getUnqual(FieldIntTy),
1742                                 "", LI);
1743    SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1744
1745    // If SrcField is a fp or vector of the right size but that isn't an
1746    // integer type, bitcast to an integer so we can shift it.
1747    if (SrcField->getType() != FieldIntTy)
1748      SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1749
1750    // Zero extend the field to be the same size as the final alloca so that
1751    // we can shift and insert it.
1752    if (SrcField->getType() != ResultVal->getType())
1753      SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1754
1755    // Determine the number of bits to shift SrcField.
1756    uint64_t Shift;
1757    if (Layout) // Struct case.
1758      Shift = Layout->getElementOffsetInBits(i);
1759    else  // Array case.
1760      Shift = i*ArrayEltBitOffset;
1761
1762    if (TD->isBigEndian())
1763      Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1764
1765    if (Shift) {
1766      Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1767      SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1768    }
1769
1770    // Don't create an 'or x, 0' on the first iteration.
1771    if (!isa<Constant>(ResultVal) ||
1772        !cast<Constant>(ResultVal)->isNullValue())
1773      ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1774    else
1775      ResultVal = SrcField;
1776  }
1777
1778  // Handle tail padding by truncating the result
1779  if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1780    ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1781
1782  LI->replaceAllUsesWith(ResultVal);
1783  DeadInsts.push_back(LI);
1784}
1785
1786/// HasPadding - Return true if the specified type has any structure or
1787/// alignment padding in between the elements that would be split apart
1788/// by SROA; return false otherwise.
1789static bool HasPadding(const Type *Ty, const TargetData &TD) {
1790  if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1791    Ty = ATy->getElementType();
1792    return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1793  }
1794
1795  // SROA currently handles only Arrays and Structs.
1796  const StructType *STy = cast<StructType>(Ty);
1797  const StructLayout *SL = TD.getStructLayout(STy);
1798  unsigned PrevFieldBitOffset = 0;
1799  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1800    unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1801
1802    // Check to see if there is any padding between this element and the
1803    // previous one.
1804    if (i) {
1805      unsigned PrevFieldEnd =
1806        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1807      if (PrevFieldEnd < FieldBitOffset)
1808        return true;
1809    }
1810    PrevFieldBitOffset = FieldBitOffset;
1811  }
1812  // Check for tail padding.
1813  if (unsigned EltCount = STy->getNumElements()) {
1814    unsigned PrevFieldEnd = PrevFieldBitOffset +
1815      TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1816    if (PrevFieldEnd < SL->getSizeInBits())
1817      return true;
1818  }
1819  return false;
1820}
1821
1822/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1823/// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
1824/// or 1 if safe after canonicalization has been performed.
1825bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1826  // Loop over the use list of the alloca.  We can only transform it if all of
1827  // the users are safe to transform.
1828  AllocaInfo Info;
1829
1830  isSafeForScalarRepl(AI, AI, 0, Info);
1831  if (Info.isUnsafe) {
1832    DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
1833    return false;
1834  }
1835
1836  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
1837  // source and destination, we have to be careful.  In particular, the memcpy
1838  // could be moving around elements that live in structure padding of the LLVM
1839  // types, but may actually be used.  In these cases, we refuse to promote the
1840  // struct.
1841  if (Info.isMemCpySrc && Info.isMemCpyDst &&
1842      HasPadding(AI->getAllocatedType(), *TD))
1843    return false;
1844
1845  // If the alloca never has an access to just *part* of it, but is accessed
1846  // via loads and stores, then we should use ConvertToScalarInfo to promote
1847  // the alloca instead of promoting each piece at a time and inserting fission
1848  // and fusion code.
1849  if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
1850    // If the struct/array just has one element, use basic SRoA.
1851    if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1852      if (ST->getNumElements() > 1) return false;
1853    } else {
1854      if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
1855        return false;
1856    }
1857  }
1858  return true;
1859}
1860
1861
1862
1863/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1864/// some part of a constant global variable.  This intentionally only accepts
1865/// constant expressions because we don't can't rewrite arbitrary instructions.
1866static bool PointsToConstantGlobal(Value *V) {
1867  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1868    return GV->isConstant();
1869  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1870    if (CE->getOpcode() == Instruction::BitCast ||
1871        CE->getOpcode() == Instruction::GetElementPtr)
1872      return PointsToConstantGlobal(CE->getOperand(0));
1873  return false;
1874}
1875
1876/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1877/// pointer to an alloca.  Ignore any reads of the pointer, return false if we
1878/// see any stores or other unknown uses.  If we see pointer arithmetic, keep
1879/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1880/// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
1881/// the alloca, and if the source pointer is a pointer to a constant global, we
1882/// can optimize this.
1883static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
1884                                           bool isOffset) {
1885  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1886    User *U = cast<Instruction>(*UI);
1887
1888    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1889      // Ignore non-volatile loads, they are always ok.
1890      if (LI->isVolatile()) return false;
1891      continue;
1892    }
1893
1894    if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1895      // If uses of the bitcast are ok, we are ok.
1896      if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1897        return false;
1898      continue;
1899    }
1900    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
1901      // If the GEP has all zero indices, it doesn't offset the pointer.  If it
1902      // doesn't, it does.
1903      if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1904                                         isOffset || !GEP->hasAllZeroIndices()))
1905        return false;
1906      continue;
1907    }
1908
1909    if (CallSite CS = U) {
1910      // If this is a readonly/readnone call site, then we know it is just a
1911      // load and we can ignore it.
1912      if (CS.onlyReadsMemory())
1913        continue;
1914
1915      // If this is the function being called then we treat it like a load and
1916      // ignore it.
1917      if (CS.isCallee(UI))
1918        continue;
1919
1920      // If this is being passed as a byval argument, the caller is making a
1921      // copy, so it is only a read of the alloca.
1922      unsigned ArgNo = CS.getArgumentNo(UI);
1923      if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
1924        continue;
1925    }
1926
1927    // If this is isn't our memcpy/memmove, reject it as something we can't
1928    // handle.
1929    MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1930    if (MI == 0)
1931      return false;
1932
1933    // If the transfer is using the alloca as a source of the transfer, then
1934    // ignore it since it is a load (unless the transfer is volatile).
1935    if (UI.getOperandNo() == 1) {
1936      if (MI->isVolatile()) return false;
1937      continue;
1938    }
1939
1940    // If we already have seen a copy, reject the second one.
1941    if (TheCopy) return false;
1942
1943    // If the pointer has been offset from the start of the alloca, we can't
1944    // safely handle this.
1945    if (isOffset) return false;
1946
1947    // If the memintrinsic isn't using the alloca as the dest, reject it.
1948    if (UI.getOperandNo() != 0) return false;
1949
1950    // If the source of the memcpy/move is not a constant global, reject it.
1951    if (!PointsToConstantGlobal(MI->getSource()))
1952      return false;
1953
1954    // Otherwise, the transform is safe.  Remember the copy instruction.
1955    TheCopy = MI;
1956  }
1957  return true;
1958}
1959
1960/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1961/// modified by a copy from a constant global.  If we can prove this, we can
1962/// replace any uses of the alloca with uses of the global directly.
1963MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1964  MemTransferInst *TheCopy = 0;
1965  if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1966    return TheCopy;
1967  return 0;
1968}
1969