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