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