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