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