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