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