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