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