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