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