ScalarReplAggregates.cpp revision d0f56132cfa6e25fb9692e84ea12444c86b92ae4
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() : AI(0) {}
848
849  void run(AllocaInst *AI, SSAUpdater &SSA) {
850    // Remember which alloca we're promoting (for isInstInList).
851    this->AI = AI;
852
853    // Build the list of instructions to promote.
854    SmallVector<Instruction*, 64> Insts;
855    for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
856         UI != E; ++UI)
857      Insts.push_back(cast<Instruction>(*UI));
858
859    LoadAndStorePromoter::run(AI->getName(), Insts, &SSA);
860
861    AI->eraseFromParent();
862  }
863
864  virtual bool isInstInList(Instruction *I,
865                            const SmallVectorImpl<Instruction*> &Insts) const {
866    if (LoadInst *LI = dyn_cast<LoadInst>(I))
867      return LI->getOperand(0) == AI;
868    return cast<StoreInst>(I)->getPointerOperand() == AI;
869  }
870};
871} // end anon namespace
872
873bool SROA::performPromotion(Function &F) {
874  std::vector<AllocaInst*> Allocas;
875  DominatorTree *DT = 0;
876  DominanceFrontier *DF = 0;
877  if (HasDomFrontiers) {
878    DT = &getAnalysis<DominatorTree>();
879    DF = &getAnalysis<DominanceFrontier>();
880  }
881
882  BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
883
884  bool Changed = false;
885
886  while (1) {
887    Allocas.clear();
888
889    // Find allocas that are safe to promote, by looking at all instructions in
890    // the entry node
891    for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
892      if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
893        if (isAllocaPromotable(AI))
894          Allocas.push_back(AI);
895
896    if (Allocas.empty()) break;
897
898    if (HasDomFrontiers)
899      PromoteMemToReg(Allocas, *DT, *DF);
900    else {
901      SSAUpdater SSA;
902      AllocaPromoter Promoter;
903      for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
904        Promoter.run(Allocas[i], SSA);
905    }
906    NumPromoted += Allocas.size();
907    Changed = true;
908  }
909
910  return Changed;
911}
912
913
914/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
915/// SROA.  It must be a struct or array type with a small number of elements.
916static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
917  const Type *T = AI->getAllocatedType();
918  // Do not promote any struct into more than 32 separate vars.
919  if (const StructType *ST = dyn_cast<StructType>(T))
920    return ST->getNumElements() <= 32;
921  // Arrays are much less likely to be safe for SROA; only consider
922  // them if they are very small.
923  if (const ArrayType *AT = dyn_cast<ArrayType>(T))
924    return AT->getNumElements() <= 8;
925  return false;
926}
927
928
929// performScalarRepl - This algorithm is a simple worklist driven algorithm,
930// which runs on all of the malloc/alloca instructions in the function, removing
931// them if they are only used by getelementptr instructions.
932//
933bool SROA::performScalarRepl(Function &F) {
934  std::vector<AllocaInst*> WorkList;
935
936  // Scan the entry basic block, adding allocas to the worklist.
937  BasicBlock &BB = F.getEntryBlock();
938  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
939    if (AllocaInst *A = dyn_cast<AllocaInst>(I))
940      WorkList.push_back(A);
941
942  // Process the worklist
943  bool Changed = false;
944  while (!WorkList.empty()) {
945    AllocaInst *AI = WorkList.back();
946    WorkList.pop_back();
947
948    // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
949    // with unused elements.
950    if (AI->use_empty()) {
951      AI->eraseFromParent();
952      Changed = true;
953      continue;
954    }
955
956    // If this alloca is impossible for us to promote, reject it early.
957    if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
958      continue;
959
960    // Check to see if this allocation is only modified by a memcpy/memmove from
961    // a constant global.  If this is the case, we can change all users to use
962    // the constant global instead.  This is commonly produced by the CFE by
963    // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
964    // is only subsequently read.
965    if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
966      DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
967      DEBUG(dbgs() << "  memcpy = " << *TheCopy << '\n');
968      Constant *TheSrc = cast<Constant>(TheCopy->getSource());
969      AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
970      TheCopy->eraseFromParent();  // Don't mutate the global.
971      AI->eraseFromParent();
972      ++NumGlobals;
973      Changed = true;
974      continue;
975    }
976
977    // Check to see if we can perform the core SROA transformation.  We cannot
978    // transform the allocation instruction if it is an array allocation
979    // (allocations OF arrays are ok though), and an allocation of a scalar
980    // value cannot be decomposed at all.
981    uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
982
983    // Do not promote [0 x %struct].
984    if (AllocaSize == 0) continue;
985
986    // Do not promote any struct whose size is too big.
987    if (AllocaSize > SRThreshold) continue;
988
989    // If the alloca looks like a good candidate for scalar replacement, and if
990    // all its users can be transformed, then split up the aggregate into its
991    // separate elements.
992    if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
993      DoScalarReplacement(AI, WorkList);
994      Changed = true;
995      continue;
996    }
997
998    // If we can turn this aggregate value (potentially with casts) into a
999    // simple scalar value that can be mem2reg'd into a register value.
1000    // IsNotTrivial tracks whether this is something that mem2reg could have
1001    // promoted itself.  If so, we don't want to transform it needlessly.  Note
1002    // that we can't just check based on the type: the alloca may be of an i32
1003    // but that has pointer arithmetic to set byte 3 of it or something.
1004    if (AllocaInst *NewAI =
1005          ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
1006      NewAI->takeName(AI);
1007      AI->eraseFromParent();
1008      ++NumConverted;
1009      Changed = true;
1010      continue;
1011    }
1012
1013    // Otherwise, couldn't process this alloca.
1014  }
1015
1016  return Changed;
1017}
1018
1019/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1020/// predicate, do SROA now.
1021void SROA::DoScalarReplacement(AllocaInst *AI,
1022                               std::vector<AllocaInst*> &WorkList) {
1023  DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1024  SmallVector<AllocaInst*, 32> ElementAllocas;
1025  if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1026    ElementAllocas.reserve(ST->getNumContainedTypes());
1027    for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1028      AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1029                                      AI->getAlignment(),
1030                                      AI->getName() + "." + Twine(i), AI);
1031      ElementAllocas.push_back(NA);
1032      WorkList.push_back(NA);  // Add to worklist for recursive processing
1033    }
1034  } else {
1035    const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1036    ElementAllocas.reserve(AT->getNumElements());
1037    const Type *ElTy = AT->getElementType();
1038    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1039      AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1040                                      AI->getName() + "." + Twine(i), AI);
1041      ElementAllocas.push_back(NA);
1042      WorkList.push_back(NA);  // Add to worklist for recursive processing
1043    }
1044  }
1045
1046  // Now that we have created the new alloca instructions, rewrite all the
1047  // uses of the old alloca.
1048  RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1049
1050  // Now erase any instructions that were made dead while rewriting the alloca.
1051  DeleteDeadInstructions();
1052  AI->eraseFromParent();
1053
1054  ++NumReplaced;
1055}
1056
1057/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1058/// recursively including all their operands that become trivially dead.
1059void SROA::DeleteDeadInstructions() {
1060  while (!DeadInsts.empty()) {
1061    Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1062
1063    for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1064      if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1065        // Zero out the operand and see if it becomes trivially dead.
1066        // (But, don't add allocas to the dead instruction list -- they are
1067        // already on the worklist and will be deleted separately.)
1068        *OI = 0;
1069        if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1070          DeadInsts.push_back(U);
1071      }
1072
1073    I->eraseFromParent();
1074  }
1075}
1076
1077/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1078/// performing scalar replacement of alloca AI.  The results are flagged in
1079/// the Info parameter.  Offset indicates the position within AI that is
1080/// referenced by this instruction.
1081void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1082                               AllocaInfo &Info) {
1083  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1084    Instruction *User = cast<Instruction>(*UI);
1085
1086    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1087      isSafeForScalarRepl(BC, AI, Offset, Info);
1088    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1089      uint64_t GEPOffset = Offset;
1090      isSafeGEP(GEPI, AI, GEPOffset, Info);
1091      if (!Info.isUnsafe)
1092        isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
1093    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1094      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1095      if (Length)
1096        isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
1097                        UI.getOperandNo() == 0, Info);
1098      else
1099        MarkUnsafe(Info);
1100    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1101      if (!LI->isVolatile()) {
1102        const Type *LIType = LI->getType();
1103        isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
1104                        LIType, false, Info);
1105      } else
1106        MarkUnsafe(Info);
1107    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1108      // Store is ok if storing INTO the pointer, not storing the pointer
1109      if (!SI->isVolatile() && SI->getOperand(0) != I) {
1110        const Type *SIType = SI->getOperand(0)->getType();
1111        isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
1112                        SIType, true, Info);
1113      } else
1114        MarkUnsafe(Info);
1115    } else {
1116      DEBUG(errs() << "  Transformation preventing inst: " << *User << '\n');
1117      MarkUnsafe(Info);
1118    }
1119    if (Info.isUnsafe) return;
1120  }
1121}
1122
1123/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1124/// replacement.  It is safe when all the indices are constant, in-bounds
1125/// references, and when the resulting offset corresponds to an element within
1126/// the alloca type.  The results are flagged in the Info parameter.  Upon
1127/// return, Offset is adjusted as specified by the GEP indices.
1128void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
1129                     uint64_t &Offset, AllocaInfo &Info) {
1130  gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1131  if (GEPIt == E)
1132    return;
1133
1134  // Walk through the GEP type indices, checking the types that this indexes
1135  // into.
1136  for (; GEPIt != E; ++GEPIt) {
1137    // Ignore struct elements, no extra checking needed for these.
1138    if ((*GEPIt)->isStructTy())
1139      continue;
1140
1141    ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1142    if (!IdxVal)
1143      return MarkUnsafe(Info);
1144  }
1145
1146  // Compute the offset due to this GEP and check if the alloca has a
1147  // component element at that offset.
1148  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1149  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1150                                 &Indices[0], Indices.size());
1151  if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1152    MarkUnsafe(Info);
1153}
1154
1155/// isHomogeneousAggregate - Check if type T is a struct or array containing
1156/// elements of the same type (which is always true for arrays).  If so,
1157/// return true with NumElts and EltTy set to the number of elements and the
1158/// element type, respectively.
1159static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1160                                   const Type *&EltTy) {
1161  if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1162    NumElts = AT->getNumElements();
1163    EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1164    return true;
1165  }
1166  if (const StructType *ST = dyn_cast<StructType>(T)) {
1167    NumElts = ST->getNumContainedTypes();
1168    EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1169    for (unsigned n = 1; n < NumElts; ++n) {
1170      if (ST->getContainedType(n) != EltTy)
1171        return false;
1172    }
1173    return true;
1174  }
1175  return false;
1176}
1177
1178/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1179/// "homogeneous" aggregates with the same element type and number of elements.
1180static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1181  if (T1 == T2)
1182    return true;
1183
1184  unsigned NumElts1, NumElts2;
1185  const Type *EltTy1, *EltTy2;
1186  if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1187      isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1188      NumElts1 == NumElts2 &&
1189      EltTy1 == EltTy2)
1190    return true;
1191
1192  return false;
1193}
1194
1195/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1196/// alloca or has an offset and size that corresponds to a component element
1197/// within it.  The offset checked here may have been formed from a GEP with a
1198/// pointer bitcasted to a different type.
1199void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
1200                           const Type *MemOpType, bool isStore,
1201                           AllocaInfo &Info) {
1202  // Check if this is a load/store of the entire alloca.
1203  if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
1204    // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1205    // loads/stores (which are essentially the same as the MemIntrinsics with
1206    // regard to copying padding between elements).  But, if an alloca is
1207    // flagged as both a source and destination of such operations, we'll need
1208    // to check later for padding between elements.
1209    if (!MemOpType || MemOpType->isIntegerTy()) {
1210      if (isStore)
1211        Info.isMemCpyDst = true;
1212      else
1213        Info.isMemCpySrc = true;
1214      return;
1215    }
1216    // This is also safe for references using a type that is compatible with
1217    // the type of the alloca, so that loads/stores can be rewritten using
1218    // insertvalue/extractvalue.
1219    if (isCompatibleAggregate(MemOpType, AI->getAllocatedType()))
1220      return;
1221  }
1222  // Check if the offset/size correspond to a component within the alloca type.
1223  const Type *T = AI->getAllocatedType();
1224  if (TypeHasComponent(T, Offset, MemSize))
1225    return;
1226
1227  return MarkUnsafe(Info);
1228}
1229
1230/// TypeHasComponent - Return true if T has a component type with the
1231/// specified offset and size.  If Size is zero, do not check the size.
1232bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1233  const Type *EltTy;
1234  uint64_t EltSize;
1235  if (const StructType *ST = dyn_cast<StructType>(T)) {
1236    const StructLayout *Layout = TD->getStructLayout(ST);
1237    unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1238    EltTy = ST->getContainedType(EltIdx);
1239    EltSize = TD->getTypeAllocSize(EltTy);
1240    Offset -= Layout->getElementOffset(EltIdx);
1241  } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1242    EltTy = AT->getElementType();
1243    EltSize = TD->getTypeAllocSize(EltTy);
1244    if (Offset >= AT->getNumElements() * EltSize)
1245      return false;
1246    Offset %= EltSize;
1247  } else {
1248    return false;
1249  }
1250  if (Offset == 0 && (Size == 0 || EltSize == Size))
1251    return true;
1252  // Check if the component spans multiple elements.
1253  if (Offset + Size > EltSize)
1254    return false;
1255  return TypeHasComponent(EltTy, Offset, Size);
1256}
1257
1258/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1259/// the instruction I, which references it, to use the separate elements.
1260/// Offset indicates the position within AI that is referenced by this
1261/// instruction.
1262void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1263                                SmallVector<AllocaInst*, 32> &NewElts) {
1264  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1265    Instruction *User = cast<Instruction>(*UI);
1266
1267    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1268      RewriteBitCast(BC, AI, Offset, NewElts);
1269    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1270      RewriteGEP(GEPI, AI, Offset, NewElts);
1271    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1272      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1273      uint64_t MemSize = Length->getZExtValue();
1274      if (Offset == 0 &&
1275          MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1276        RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1277      // Otherwise the intrinsic can only touch a single element and the
1278      // address operand will be updated, so nothing else needs to be done.
1279    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1280      const Type *LIType = LI->getType();
1281      if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1282        // Replace:
1283        //   %res = load { i32, i32 }* %alloc
1284        // with:
1285        //   %load.0 = load i32* %alloc.0
1286        //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1287        //   %load.1 = load i32* %alloc.1
1288        //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1289        // (Also works for arrays instead of structs)
1290        Value *Insert = UndefValue::get(LIType);
1291        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1292          Value *Load = new LoadInst(NewElts[i], "load", LI);
1293          Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1294        }
1295        LI->replaceAllUsesWith(Insert);
1296        DeadInsts.push_back(LI);
1297      } else if (LIType->isIntegerTy() &&
1298                 TD->getTypeAllocSize(LIType) ==
1299                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1300        // If this is a load of the entire alloca to an integer, rewrite it.
1301        RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1302      }
1303    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1304      Value *Val = SI->getOperand(0);
1305      const Type *SIType = Val->getType();
1306      if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1307        // Replace:
1308        //   store { i32, i32 } %val, { i32, i32 }* %alloc
1309        // with:
1310        //   %val.0 = extractvalue { i32, i32 } %val, 0
1311        //   store i32 %val.0, i32* %alloc.0
1312        //   %val.1 = extractvalue { i32, i32 } %val, 1
1313        //   store i32 %val.1, i32* %alloc.1
1314        // (Also works for arrays instead of structs)
1315        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1316          Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1317          new StoreInst(Extract, NewElts[i], SI);
1318        }
1319        DeadInsts.push_back(SI);
1320      } else if (SIType->isIntegerTy() &&
1321                 TD->getTypeAllocSize(SIType) ==
1322                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1323        // If this is a store of the entire alloca from an integer, rewrite it.
1324        RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1325      }
1326    }
1327  }
1328}
1329
1330/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1331/// and recursively continue updating all of its uses.
1332void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1333                          SmallVector<AllocaInst*, 32> &NewElts) {
1334  RewriteForScalarRepl(BC, AI, Offset, NewElts);
1335  if (BC->getOperand(0) != AI)
1336    return;
1337
1338  // The bitcast references the original alloca.  Replace its uses with
1339  // references to the first new element alloca.
1340  Instruction *Val = NewElts[0];
1341  if (Val->getType() != BC->getDestTy()) {
1342    Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1343    Val->takeName(BC);
1344  }
1345  BC->replaceAllUsesWith(Val);
1346  DeadInsts.push_back(BC);
1347}
1348
1349/// FindElementAndOffset - Return the index of the element containing Offset
1350/// within the specified type, which must be either a struct or an array.
1351/// Sets T to the type of the element and Offset to the offset within that
1352/// element.  IdxTy is set to the type of the index result to be used in a
1353/// GEP instruction.
1354uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1355                                    const Type *&IdxTy) {
1356  uint64_t Idx = 0;
1357  if (const StructType *ST = dyn_cast<StructType>(T)) {
1358    const StructLayout *Layout = TD->getStructLayout(ST);
1359    Idx = Layout->getElementContainingOffset(Offset);
1360    T = ST->getContainedType(Idx);
1361    Offset -= Layout->getElementOffset(Idx);
1362    IdxTy = Type::getInt32Ty(T->getContext());
1363    return Idx;
1364  }
1365  const ArrayType *AT = cast<ArrayType>(T);
1366  T = AT->getElementType();
1367  uint64_t EltSize = TD->getTypeAllocSize(T);
1368  Idx = Offset / EltSize;
1369  Offset -= Idx * EltSize;
1370  IdxTy = Type::getInt64Ty(T->getContext());
1371  return Idx;
1372}
1373
1374/// RewriteGEP - Check if this GEP instruction moves the pointer across
1375/// elements of the alloca that are being split apart, and if so, rewrite
1376/// the GEP to be relative to the new element.
1377void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1378                      SmallVector<AllocaInst*, 32> &NewElts) {
1379  uint64_t OldOffset = Offset;
1380  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1381  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1382                                 &Indices[0], Indices.size());
1383
1384  RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1385
1386  const Type *T = AI->getAllocatedType();
1387  const Type *IdxTy;
1388  uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1389  if (GEPI->getOperand(0) == AI)
1390    OldIdx = ~0ULL; // Force the GEP to be rewritten.
1391
1392  T = AI->getAllocatedType();
1393  uint64_t EltOffset = Offset;
1394  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1395
1396  // If this GEP does not move the pointer across elements of the alloca
1397  // being split, then it does not needs to be rewritten.
1398  if (Idx == OldIdx)
1399    return;
1400
1401  const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1402  SmallVector<Value*, 8> NewArgs;
1403  NewArgs.push_back(Constant::getNullValue(i32Ty));
1404  while (EltOffset != 0) {
1405    uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1406    NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1407  }
1408  Instruction *Val = NewElts[Idx];
1409  if (NewArgs.size() > 1) {
1410    Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1411                                            NewArgs.end(), "", GEPI);
1412    Val->takeName(GEPI);
1413  }
1414  if (Val->getType() != GEPI->getType())
1415    Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1416  GEPI->replaceAllUsesWith(Val);
1417  DeadInsts.push_back(GEPI);
1418}
1419
1420/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1421/// Rewrite it to copy or set the elements of the scalarized memory.
1422void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
1423                                        AllocaInst *AI,
1424                                        SmallVector<AllocaInst*, 32> &NewElts) {
1425  // If this is a memcpy/memmove, construct the other pointer as the
1426  // appropriate type.  The "Other" pointer is the pointer that goes to memory
1427  // that doesn't have anything to do with the alloca that we are promoting. For
1428  // memset, this Value* stays null.
1429  Value *OtherPtr = 0;
1430  unsigned MemAlignment = MI->getAlignment();
1431  if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
1432    if (Inst == MTI->getRawDest())
1433      OtherPtr = MTI->getRawSource();
1434    else {
1435      assert(Inst == MTI->getRawSource());
1436      OtherPtr = MTI->getRawDest();
1437    }
1438  }
1439
1440  // If there is an other pointer, we want to convert it to the same pointer
1441  // type as AI has, so we can GEP through it safely.
1442  if (OtherPtr) {
1443    unsigned AddrSpace =
1444      cast<PointerType>(OtherPtr->getType())->getAddressSpace();
1445
1446    // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
1447    // optimization, but it's also required to detect the corner case where
1448    // both pointer operands are referencing the same memory, and where
1449    // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
1450    // function is only called for mem intrinsics that access the whole
1451    // aggregate, so non-zero GEPs are not an issue here.)
1452    OtherPtr = OtherPtr->stripPointerCasts();
1453
1454    // Copying the alloca to itself is a no-op: just delete it.
1455    if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1456      // This code will run twice for a no-op memcpy -- once for each operand.
1457      // Put only one reference to MI on the DeadInsts list.
1458      for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1459             E = DeadInsts.end(); I != E; ++I)
1460        if (*I == MI) return;
1461      DeadInsts.push_back(MI);
1462      return;
1463    }
1464
1465    // If the pointer is not the right type, insert a bitcast to the right
1466    // type.
1467    const Type *NewTy =
1468      PointerType::get(AI->getType()->getElementType(), AddrSpace);
1469
1470    if (OtherPtr->getType() != NewTy)
1471      OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
1472  }
1473
1474  // Process each element of the aggregate.
1475  bool SROADest = MI->getRawDest() == Inst;
1476
1477  Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
1478
1479  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1480    // If this is a memcpy/memmove, emit a GEP of the other element address.
1481    Value *OtherElt = 0;
1482    unsigned OtherEltAlign = MemAlignment;
1483
1484    if (OtherPtr) {
1485      Value *Idx[2] = { Zero,
1486                      ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
1487      OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
1488                                              OtherPtr->getName()+"."+Twine(i),
1489                                                   MI);
1490      uint64_t EltOffset;
1491      const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
1492      const Type *OtherTy = OtherPtrTy->getElementType();
1493      if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
1494        EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1495      } else {
1496        const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
1497        EltOffset = TD->getTypeAllocSize(EltTy)*i;
1498      }
1499
1500      // The alignment of the other pointer is the guaranteed alignment of the
1501      // element, which is affected by both the known alignment of the whole
1502      // mem intrinsic and the alignment of the element.  If the alignment of
1503      // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1504      // known alignment is just 4 bytes.
1505      OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
1506    }
1507
1508    Value *EltPtr = NewElts[i];
1509    const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
1510
1511    // If we got down to a scalar, insert a load or store as appropriate.
1512    if (EltTy->isSingleValueType()) {
1513      if (isa<MemTransferInst>(MI)) {
1514        if (SROADest) {
1515          // From Other to Alloca.
1516          Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1517          new StoreInst(Elt, EltPtr, MI);
1518        } else {
1519          // From Alloca to Other.
1520          Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1521          new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1522        }
1523        continue;
1524      }
1525      assert(isa<MemSetInst>(MI));
1526
1527      // If the stored element is zero (common case), just store a null
1528      // constant.
1529      Constant *StoreVal;
1530      if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
1531        if (CI->isZero()) {
1532          StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
1533        } else {
1534          // If EltTy is a vector type, get the element type.
1535          const Type *ValTy = EltTy->getScalarType();
1536
1537          // Construct an integer with the right value.
1538          unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1539          APInt OneVal(EltSize, CI->getZExtValue());
1540          APInt TotalVal(OneVal);
1541          // Set each byte.
1542          for (unsigned i = 0; 8*i < EltSize; ++i) {
1543            TotalVal = TotalVal.shl(8);
1544            TotalVal |= OneVal;
1545          }
1546
1547          // Convert the integer value to the appropriate type.
1548          StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
1549          if (ValTy->isPointerTy())
1550            StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
1551          else if (ValTy->isFloatingPointTy())
1552            StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
1553          assert(StoreVal->getType() == ValTy && "Type mismatch!");
1554
1555          // If the requested value was a vector constant, create it.
1556          if (EltTy != ValTy) {
1557            unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1558            SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
1559            StoreVal = ConstantVector::get(&Elts[0], NumElts);
1560          }
1561        }
1562        new StoreInst(StoreVal, EltPtr, MI);
1563        continue;
1564      }
1565      // Otherwise, if we're storing a byte variable, use a memset call for
1566      // this element.
1567    }
1568
1569    unsigned EltSize = TD->getTypeAllocSize(EltTy);
1570
1571    IRBuilder<> Builder(MI);
1572
1573    // Finally, insert the meminst for this element.
1574    if (isa<MemSetInst>(MI)) {
1575      Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1576                           MI->isVolatile());
1577    } else {
1578      assert(isa<MemTransferInst>(MI));
1579      Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
1580      Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
1581
1582      if (isa<MemCpyInst>(MI))
1583        Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1584      else
1585        Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
1586    }
1587  }
1588  DeadInsts.push_back(MI);
1589}
1590
1591/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
1592/// overwrites the entire allocation.  Extract out the pieces of the stored
1593/// integer and store them individually.
1594void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
1595                                         SmallVector<AllocaInst*, 32> &NewElts){
1596  // Extract each element out of the integer according to its structure offset
1597  // and store the element value to the individual alloca.
1598  Value *SrcVal = SI->getOperand(0);
1599  const Type *AllocaEltTy = AI->getAllocatedType();
1600  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1601
1602  // Handle tail padding by extending the operand
1603  if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
1604    SrcVal = new ZExtInst(SrcVal,
1605                          IntegerType::get(SI->getContext(), AllocaSizeBits),
1606                          "", SI);
1607
1608  DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
1609               << '\n');
1610
1611  // There are two forms here: AI could be an array or struct.  Both cases
1612  // have different ways to compute the element offset.
1613  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1614    const StructLayout *Layout = TD->getStructLayout(EltSTy);
1615
1616    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1617      // Get the number of bits to shift SrcVal to get the value.
1618      const Type *FieldTy = EltSTy->getElementType(i);
1619      uint64_t Shift = Layout->getElementOffsetInBits(i);
1620
1621      if (TD->isBigEndian())
1622        Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
1623
1624      Value *EltVal = SrcVal;
1625      if (Shift) {
1626        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1627        EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1628                                            "sroa.store.elt", SI);
1629      }
1630
1631      // Truncate down to an integer of the right size.
1632      uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1633
1634      // Ignore zero sized fields like {}, they obviously contain no data.
1635      if (FieldSizeBits == 0) continue;
1636
1637      if (FieldSizeBits != AllocaSizeBits)
1638        EltVal = new TruncInst(EltVal,
1639                             IntegerType::get(SI->getContext(), FieldSizeBits),
1640                              "", SI);
1641      Value *DestField = NewElts[i];
1642      if (EltVal->getType() == FieldTy) {
1643        // Storing to an integer field of this size, just do it.
1644      } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
1645        // Bitcast to the right element type (for fp/vector values).
1646        EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1647      } else {
1648        // Otherwise, bitcast the dest pointer (for aggregates).
1649        DestField = new BitCastInst(DestField,
1650                              PointerType::getUnqual(EltVal->getType()),
1651                                    "", SI);
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 = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1677                                            "sroa.store.elt", SI);
1678      }
1679
1680      // Truncate down to an integer of the right size.
1681      if (ElementSizeBits != AllocaSizeBits)
1682        EltVal = new TruncInst(EltVal,
1683                               IntegerType::get(SI->getContext(),
1684                                                ElementSizeBits), "", SI);
1685      Value *DestField = NewElts[i];
1686      if (EltVal->getType() == ArrayEltTy) {
1687        // Storing to an integer field of this size, just do it.
1688      } else if (ArrayEltTy->isFloatingPointTy() ||
1689                 ArrayEltTy->isVectorTy()) {
1690        // Bitcast to the right element type (for fp/vector values).
1691        EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1692      } else {
1693        // Otherwise, bitcast the dest pointer (for aggregates).
1694        DestField = new BitCastInst(DestField,
1695                              PointerType::getUnqual(EltVal->getType()),
1696                                    "", SI);
1697      }
1698      new StoreInst(EltVal, DestField, SI);
1699
1700      if (TD->isBigEndian())
1701        Shift -= ElementOffset;
1702      else
1703        Shift += ElementOffset;
1704    }
1705  }
1706
1707  DeadInsts.push_back(SI);
1708}
1709
1710/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
1711/// an integer.  Load the individual pieces to form the aggregate value.
1712void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1713                                        SmallVector<AllocaInst*, 32> &NewElts) {
1714  // Extract each element out of the NewElts according to its structure offset
1715  // and form the result value.
1716  const Type *AllocaEltTy = AI->getAllocatedType();
1717  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1718
1719  DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1720               << '\n');
1721
1722  // There are two forms here: AI could be an array or struct.  Both cases
1723  // have different ways to compute the element offset.
1724  const StructLayout *Layout = 0;
1725  uint64_t ArrayEltBitOffset = 0;
1726  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1727    Layout = TD->getStructLayout(EltSTy);
1728  } else {
1729    const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1730    ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1731  }
1732
1733  Value *ResultVal =
1734    Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1735
1736  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1737    // Load the value from the alloca.  If the NewElt is an aggregate, cast
1738    // the pointer to an integer of the same size before doing the load.
1739    Value *SrcField = NewElts[i];
1740    const Type *FieldTy =
1741      cast<PointerType>(SrcField->getType())->getElementType();
1742    uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1743
1744    // Ignore zero sized fields like {}, they obviously contain no data.
1745    if (FieldSizeBits == 0) continue;
1746
1747    const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1748                                                     FieldSizeBits);
1749    if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1750        !FieldTy->isVectorTy())
1751      SrcField = new BitCastInst(SrcField,
1752                                 PointerType::getUnqual(FieldIntTy),
1753                                 "", LI);
1754    SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1755
1756    // If SrcField is a fp or vector of the right size but that isn't an
1757    // integer type, bitcast to an integer so we can shift it.
1758    if (SrcField->getType() != FieldIntTy)
1759      SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1760
1761    // Zero extend the field to be the same size as the final alloca so that
1762    // we can shift and insert it.
1763    if (SrcField->getType() != ResultVal->getType())
1764      SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1765
1766    // Determine the number of bits to shift SrcField.
1767    uint64_t Shift;
1768    if (Layout) // Struct case.
1769      Shift = Layout->getElementOffsetInBits(i);
1770    else  // Array case.
1771      Shift = i*ArrayEltBitOffset;
1772
1773    if (TD->isBigEndian())
1774      Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1775
1776    if (Shift) {
1777      Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1778      SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1779    }
1780
1781    // Don't create an 'or x, 0' on the first iteration.
1782    if (!isa<Constant>(ResultVal) ||
1783        !cast<Constant>(ResultVal)->isNullValue())
1784      ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1785    else
1786      ResultVal = SrcField;
1787  }
1788
1789  // Handle tail padding by truncating the result
1790  if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1791    ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1792
1793  LI->replaceAllUsesWith(ResultVal);
1794  DeadInsts.push_back(LI);
1795}
1796
1797/// HasPadding - Return true if the specified type has any structure or
1798/// alignment padding in between the elements that would be split apart
1799/// by SROA; return false otherwise.
1800static bool HasPadding(const Type *Ty, const TargetData &TD) {
1801  if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1802    Ty = ATy->getElementType();
1803    return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1804  }
1805
1806  // SROA currently handles only Arrays and Structs.
1807  const StructType *STy = cast<StructType>(Ty);
1808  const StructLayout *SL = TD.getStructLayout(STy);
1809  unsigned PrevFieldBitOffset = 0;
1810  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1811    unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1812
1813    // Check to see if there is any padding between this element and the
1814    // previous one.
1815    if (i) {
1816      unsigned PrevFieldEnd =
1817        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1818      if (PrevFieldEnd < FieldBitOffset)
1819        return true;
1820    }
1821    PrevFieldBitOffset = FieldBitOffset;
1822  }
1823  // Check for tail padding.
1824  if (unsigned EltCount = STy->getNumElements()) {
1825    unsigned PrevFieldEnd = PrevFieldBitOffset +
1826      TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1827    if (PrevFieldEnd < SL->getSizeInBits())
1828      return true;
1829  }
1830  return false;
1831}
1832
1833/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1834/// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
1835/// or 1 if safe after canonicalization has been performed.
1836bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1837  // Loop over the use list of the alloca.  We can only transform it if all of
1838  // the users are safe to transform.
1839  AllocaInfo Info;
1840
1841  isSafeForScalarRepl(AI, AI, 0, Info);
1842  if (Info.isUnsafe) {
1843    DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
1844    return false;
1845  }
1846
1847  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
1848  // source and destination, we have to be careful.  In particular, the memcpy
1849  // could be moving around elements that live in structure padding of the LLVM
1850  // types, but may actually be used.  In these cases, we refuse to promote the
1851  // struct.
1852  if (Info.isMemCpySrc && Info.isMemCpyDst &&
1853      HasPadding(AI->getAllocatedType(), *TD))
1854    return false;
1855
1856  return true;
1857}
1858
1859
1860
1861/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1862/// some part of a constant global variable.  This intentionally only accepts
1863/// constant expressions because we don't can't rewrite arbitrary instructions.
1864static bool PointsToConstantGlobal(Value *V) {
1865  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1866    return GV->isConstant();
1867  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1868    if (CE->getOpcode() == Instruction::BitCast ||
1869        CE->getOpcode() == Instruction::GetElementPtr)
1870      return PointsToConstantGlobal(CE->getOperand(0));
1871  return false;
1872}
1873
1874/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1875/// pointer to an alloca.  Ignore any reads of the pointer, return false if we
1876/// see any stores or other unknown uses.  If we see pointer arithmetic, keep
1877/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1878/// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
1879/// the alloca, and if the source pointer is a pointer to a constant global, we
1880/// can optimize this.
1881static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
1882                                           bool isOffset) {
1883  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1884    User *U = cast<Instruction>(*UI);
1885
1886    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1887      // Ignore non-volatile loads, they are always ok.
1888      if (LI->isVolatile()) return false;
1889      continue;
1890    }
1891
1892    if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1893      // If uses of the bitcast are ok, we are ok.
1894      if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1895        return false;
1896      continue;
1897    }
1898    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
1899      // If the GEP has all zero indices, it doesn't offset the pointer.  If it
1900      // doesn't, it does.
1901      if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1902                                         isOffset || !GEP->hasAllZeroIndices()))
1903        return false;
1904      continue;
1905    }
1906
1907    if (CallSite CS = U) {
1908      // If this is a readonly/readnone call site, then we know it is just a
1909      // load and we can ignore it.
1910      if (CS.onlyReadsMemory())
1911        continue;
1912
1913      // If this is the function being called then we treat it like a load and
1914      // ignore it.
1915      if (CS.isCallee(UI))
1916        continue;
1917
1918      // If this is being passed as a byval argument, the caller is making a
1919      // copy, so it is only a read of the alloca.
1920      unsigned ArgNo = CS.getArgumentNo(UI);
1921      if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
1922        continue;
1923    }
1924
1925    // If this is isn't our memcpy/memmove, reject it as something we can't
1926    // handle.
1927    MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1928    if (MI == 0)
1929      return false;
1930
1931    // If the transfer is using the alloca as a source of the transfer, then
1932    // ignore it since it is a load (unless the transfer is volatile).
1933    if (UI.getOperandNo() == 1) {
1934      if (MI->isVolatile()) return false;
1935      continue;
1936    }
1937
1938    // If we already have seen a copy, reject the second one.
1939    if (TheCopy) return false;
1940
1941    // If the pointer has been offset from the start of the alloca, we can't
1942    // safely handle this.
1943    if (isOffset) return false;
1944
1945    // If the memintrinsic isn't using the alloca as the dest, reject it.
1946    if (UI.getOperandNo() != 0) return false;
1947
1948    // If the source of the memcpy/move is not a constant global, reject it.
1949    if (!PointsToConstantGlobal(MI->getSource()))
1950      return false;
1951
1952    // Otherwise, the transform is safe.  Remember the copy instruction.
1953    TheCopy = MI;
1954  }
1955  return true;
1956}
1957
1958/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1959/// modified by a copy from a constant global.  If we can prove this, we can
1960/// replace any uses of the alloca with uses of the global directly.
1961MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1962  MemTransferInst *TheCopy = 0;
1963  if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1964    return TheCopy;
1965  return 0;
1966}
1967