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