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