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