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