eliminate the "Value" printing methods that print to a std::ostream.
[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/Pass.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/IRBuilder.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/Statistic.h"
45 using namespace llvm;
46
47 STATISTIC(NumReplaced,  "Number of allocas broken up");
48 STATISTIC(NumPromoted,  "Number of allocas promoted");
49 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
50 STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
51
52 namespace {
53   struct VISIBILITY_HIDDEN SROA : public FunctionPass {
54     static char ID; // Pass identification, replacement for typeid
55     explicit SROA(signed T = -1) : FunctionPass(&ID) {
56       if (T == -1)
57         SRThreshold = 128;
58       else
59         SRThreshold = T;
60     }
61
62     bool runOnFunction(Function &F);
63
64     bool performScalarRepl(Function &F);
65     bool performPromotion(Function &F);
66
67     // getAnalysisUsage - This pass does not require any passes, but we know it
68     // will not alter the CFG, so say so.
69     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70       AU.addRequired<DominatorTree>();
71       AU.addRequired<DominanceFrontier>();
72       AU.setPreservesCFG();
73     }
74
75   private:
76     TargetData *TD;
77     
78     /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
79     /// information about the uses.  All these fields are initialized to false
80     /// and set to true when something is learned.
81     struct AllocaInfo {
82       /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
83       bool isUnsafe : 1;
84       
85       /// needsCleanup - This is set to true if there is some use of the alloca
86       /// that requires cleanup.
87       bool needsCleanup : 1;
88       
89       /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
90       bool isMemCpySrc : 1;
91
92       /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
93       bool isMemCpyDst : 1;
94
95       AllocaInfo()
96         : isUnsafe(false), needsCleanup(false), 
97           isMemCpySrc(false), isMemCpyDst(false) {}
98     };
99     
100     unsigned SRThreshold;
101
102     void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
103
104     int isSafeAllocaToScalarRepl(AllocationInst *AI);
105
106     void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
107                                AllocaInfo &Info);
108     void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
109                          AllocaInfo &Info);
110     void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
111                                         unsigned OpNo, AllocaInfo &Info);
112     void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
113                                         AllocaInfo &Info);
114     
115     void DoScalarReplacement(AllocationInst *AI, 
116                              std::vector<AllocationInst*> &WorkList);
117     void CleanupGEP(GetElementPtrInst *GEP);
118     void CleanupAllocaUsers(AllocationInst *AI);
119     AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
120     
121     void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
122                                     SmallVector<AllocaInst*, 32> &NewElts);
123     
124     void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
125                                       AllocationInst *AI,
126                                       SmallVector<AllocaInst*, 32> &NewElts);
127     void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
128                                        SmallVector<AllocaInst*, 32> &NewElts);
129     void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
130                                       SmallVector<AllocaInst*, 32> &NewElts);
131     
132     bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
133                             bool &SawVec, uint64_t Offset, unsigned AllocaSize);
134     void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
135     Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
136                                      uint64_t Offset, IRBuilder<> &Builder);
137     Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
138                                      uint64_t Offset, IRBuilder<> &Builder);
139     static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
140   };
141 }
142
143 char SROA::ID = 0;
144 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
145
146 // Public interface to the ScalarReplAggregates pass
147 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) { 
148   return new SROA(Threshold);
149 }
150
151
152 bool SROA::runOnFunction(Function &F) {
153   TD = getAnalysisIfAvailable<TargetData>();
154
155   bool Changed = performPromotion(F);
156
157   // FIXME: ScalarRepl currently depends on TargetData more than it
158   // theoretically needs to. It should be refactored in order to support
159   // target-independent IR. Until this is done, just skip the actual
160   // scalar-replacement portion of this pass.
161   if (!TD) return Changed;
162
163   while (1) {
164     bool LocalChange = performScalarRepl(F);
165     if (!LocalChange) break;   // No need to repromote if no scalarrepl
166     Changed = true;
167     LocalChange = performPromotion(F);
168     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
169   }
170
171   return Changed;
172 }
173
174
175 bool SROA::performPromotion(Function &F) {
176   std::vector<AllocaInst*> Allocas;
177   DominatorTree         &DT = getAnalysis<DominatorTree>();
178   DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
179
180   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
181
182   bool Changed = false;
183
184   while (1) {
185     Allocas.clear();
186
187     // Find allocas that are safe to promote, by looking at all instructions in
188     // the entry node
189     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
190       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
191         if (isAllocaPromotable(AI))
192           Allocas.push_back(AI);
193
194     if (Allocas.empty()) break;
195
196     PromoteMemToReg(Allocas, DT, DF, F.getContext());
197     NumPromoted += Allocas.size();
198     Changed = true;
199   }
200
201   return Changed;
202 }
203
204 /// getNumSAElements - Return the number of elements in the specific struct or
205 /// array.
206 static uint64_t getNumSAElements(const Type *T) {
207   if (const StructType *ST = dyn_cast<StructType>(T))
208     return ST->getNumElements();
209   return cast<ArrayType>(T)->getNumElements();
210 }
211
212 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
213 // which runs on all of the malloc/alloca instructions in the function, removing
214 // them if they are only used by getelementptr instructions.
215 //
216 bool SROA::performScalarRepl(Function &F) {
217   std::vector<AllocationInst*> WorkList;
218
219   // Scan the entry basic block, adding any alloca's and mallocs to the worklist
220   BasicBlock &BB = F.getEntryBlock();
221   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
222     if (AllocationInst *A = dyn_cast<AllocationInst>(I))
223       WorkList.push_back(A);
224
225   // Process the worklist
226   bool Changed = false;
227   while (!WorkList.empty()) {
228     AllocationInst *AI = WorkList.back();
229     WorkList.pop_back();
230     
231     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
232     // with unused elements.
233     if (AI->use_empty()) {
234       AI->eraseFromParent();
235       continue;
236     }
237
238     // If this alloca is impossible for us to promote, reject it early.
239     if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
240       continue;
241     
242     // Check to see if this allocation is only modified by a memcpy/memmove from
243     // a constant global.  If this is the case, we can change all users to use
244     // the constant global instead.  This is commonly produced by the CFE by
245     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
246     // is only subsequently read.
247     if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
248       DEBUG(errs() << "Found alloca equal to global: " << *AI);
249       DEBUG(errs() << "  memcpy = " << *TheCopy);
250       Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
251       AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
252       TheCopy->eraseFromParent();  // Don't mutate the global.
253       AI->eraseFromParent();
254       ++NumGlobals;
255       Changed = true;
256       continue;
257     }
258     
259     // Check to see if we can perform the core SROA transformation.  We cannot
260     // transform the allocation instruction if it is an array allocation
261     // (allocations OF arrays are ok though), and an allocation of a scalar
262     // value cannot be decomposed at all.
263     uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
264
265     // Do not promote [0 x %struct].
266     if (AllocaSize == 0) continue;
267
268     // Do not promote any struct whose size is too big.
269     if (AllocaSize > SRThreshold) continue;
270
271     if ((isa<StructType>(AI->getAllocatedType()) ||
272          isa<ArrayType>(AI->getAllocatedType())) &&
273         // Do not promote any struct into more than "32" separate vars.
274         getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
275       // Check that all of the users of the allocation are capable of being
276       // transformed.
277       switch (isSafeAllocaToScalarRepl(AI)) {
278       default: llvm_unreachable("Unexpected value!");
279       case 0:  // Not safe to scalar replace.
280         break;
281       case 1:  // Safe, but requires cleanup/canonicalizations first
282         CleanupAllocaUsers(AI);
283         // FALL THROUGH.
284       case 3:  // Safe to scalar replace.
285         DoScalarReplacement(AI, WorkList);
286         Changed = true;
287         continue;
288       }
289     }
290
291     // If we can turn this aggregate value (potentially with casts) into a
292     // simple scalar value that can be mem2reg'd into a register value.
293     // IsNotTrivial tracks whether this is something that mem2reg could have
294     // promoted itself.  If so, we don't want to transform it needlessly.  Note
295     // that we can't just check based on the type: the alloca may be of an i32
296     // but that has pointer arithmetic to set byte 3 of it or something.
297     bool IsNotTrivial = false;
298     const Type *VectorTy = 0;
299     bool HadAVector = false;
300     if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector, 
301                            0, unsigned(AllocaSize)) && IsNotTrivial) {
302       AllocaInst *NewAI;
303       // If we were able to find a vector type that can handle this with
304       // insert/extract elements, and if there was at least one use that had
305       // a vector type, promote this to a vector.  We don't want to promote
306       // random stuff that doesn't use vectors (e.g. <9 x double>) because then
307       // we just get a lot of insert/extracts.  If at least one vector is
308       // involved, then we probably really do have a union of vector/array.
309       if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
310         DEBUG(errs() << "CONVERT TO VECTOR: " << *AI << "  TYPE = "
311                      << *VectorTy << '\n');
312         
313         // Create and insert the vector alloca.
314         NewAI = new AllocaInst(VectorTy, 0, "",  AI->getParent()->begin());
315         ConvertUsesToScalar(AI, NewAI, 0);
316       } else {
317         DEBUG(errs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
318         
319         // Create and insert the integer alloca.
320         const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
321         NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
322         ConvertUsesToScalar(AI, NewAI, 0);
323       }
324       NewAI->takeName(AI);
325       AI->eraseFromParent();
326       ++NumConverted;
327       Changed = true;
328       continue;
329     }
330     
331     // Otherwise, couldn't process this alloca.
332   }
333
334   return Changed;
335 }
336
337 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
338 /// predicate, do SROA now.
339 void SROA::DoScalarReplacement(AllocationInst *AI, 
340                                std::vector<AllocationInst*> &WorkList) {
341   DEBUG(errs() << "Found inst to SROA: " << *AI);
342   SmallVector<AllocaInst*, 32> ElementAllocas;
343   if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
344     ElementAllocas.reserve(ST->getNumContainedTypes());
345     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
346       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 
347                                       AI->getAlignment(),
348                                       AI->getName() + "." + Twine(i), AI);
349       ElementAllocas.push_back(NA);
350       WorkList.push_back(NA);  // Add to worklist for recursive processing
351     }
352   } else {
353     const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
354     ElementAllocas.reserve(AT->getNumElements());
355     const Type *ElTy = AT->getElementType();
356     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
357       AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
358                                       AI->getName() + "." + Twine(i), AI);
359       ElementAllocas.push_back(NA);
360       WorkList.push_back(NA);  // Add to worklist for recursive processing
361     }
362   }
363
364   // Now that we have created the alloca instructions that we want to use,
365   // expand the getelementptr instructions to use them.
366   //
367   while (!AI->use_empty()) {
368     Instruction *User = cast<Instruction>(AI->use_back());
369     if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
370       RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
371       BCInst->eraseFromParent();
372       continue;
373     }
374     
375     // Replace:
376     //   %res = load { i32, i32 }* %alloc
377     // with:
378     //   %load.0 = load i32* %alloc.0
379     //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0 
380     //   %load.1 = load i32* %alloc.1
381     //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1 
382     // (Also works for arrays instead of structs)
383     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
384       Value *Insert = UndefValue::get(LI->getType());
385       for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
386         Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
387         Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
388       }
389       LI->replaceAllUsesWith(Insert);
390       LI->eraseFromParent();
391       continue;
392     }
393
394     // Replace:
395     //   store { i32, i32 } %val, { i32, i32 }* %alloc
396     // with:
397     //   %val.0 = extractvalue { i32, i32 } %val, 0 
398     //   store i32 %val.0, i32* %alloc.0
399     //   %val.1 = extractvalue { i32, i32 } %val, 1 
400     //   store i32 %val.1, i32* %alloc.1
401     // (Also works for arrays instead of structs)
402     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
403       Value *Val = SI->getOperand(0);
404       for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
405         Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
406         new StoreInst(Extract, ElementAllocas[i], SI);
407       }
408       SI->eraseFromParent();
409       continue;
410     }
411     
412     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
413     // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
414     unsigned Idx =
415        (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
416
417     assert(Idx < ElementAllocas.size() && "Index out of range?");
418     AllocaInst *AllocaToUse = ElementAllocas[Idx];
419
420     Value *RepValue;
421     if (GEPI->getNumOperands() == 3) {
422       // Do not insert a new getelementptr instruction with zero indices, only
423       // to have it optimized out later.
424       RepValue = AllocaToUse;
425     } else {
426       // We are indexing deeply into the structure, so we still need a
427       // getelement ptr instruction to finish the indexing.  This may be
428       // expanded itself once the worklist is rerun.
429       //
430       SmallVector<Value*, 8> NewArgs;
431       NewArgs.push_back(Constant::getNullValue(
432                                            Type::getInt32Ty(AI->getContext())));
433       NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
434       RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
435                                            NewArgs.end(), "", GEPI);
436       RepValue->takeName(GEPI);
437     }
438     
439     // If this GEP is to the start of the aggregate, check for memcpys.
440     if (Idx == 0 && GEPI->hasAllZeroIndices())
441       RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
442
443     // Move all of the users over to the new GEP.
444     GEPI->replaceAllUsesWith(RepValue);
445     // Delete the old GEP
446     GEPI->eraseFromParent();
447   }
448
449   // Finally, delete the Alloca instruction
450   AI->eraseFromParent();
451   NumReplaced++;
452 }
453
454
455 /// isSafeElementUse - Check to see if this use is an allowed use for a
456 /// getelementptr instruction of an array aggregate allocation.  isFirstElt
457 /// indicates whether Ptr is known to the start of the aggregate.
458 ///
459 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
460                             AllocaInfo &Info) {
461   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
462        I != E; ++I) {
463     Instruction *User = cast<Instruction>(*I);
464     switch (User->getOpcode()) {
465     case Instruction::Load:  break;
466     case Instruction::Store:
467       // Store is ok if storing INTO the pointer, not storing the pointer
468       if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
469       break;
470     case Instruction::GetElementPtr: {
471       GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
472       bool AreAllZeroIndices = isFirstElt;
473       if (GEP->getNumOperands() > 1) {
474         if (!isa<ConstantInt>(GEP->getOperand(1)) ||
475             !cast<ConstantInt>(GEP->getOperand(1))->isZero())
476           // Using pointer arithmetic to navigate the array.
477           return MarkUnsafe(Info);
478        
479         if (AreAllZeroIndices)
480           AreAllZeroIndices = GEP->hasAllZeroIndices();
481       }
482       isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
483       if (Info.isUnsafe) return;
484       break;
485     }
486     case Instruction::BitCast:
487       if (isFirstElt) {
488         isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
489         if (Info.isUnsafe) return;
490         break;
491       }
492       DEBUG(errs() << "  Transformation preventing inst: " << *User);
493       return MarkUnsafe(Info);
494     case Instruction::Call:
495       if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
496         if (isFirstElt) {
497           isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
498           if (Info.isUnsafe) return;
499           break;
500         }
501       }
502       DEBUG(errs() << "  Transformation preventing inst: " << *User);
503       return MarkUnsafe(Info);
504     default:
505       DEBUG(errs() << "  Transformation preventing inst: " << *User);
506       return MarkUnsafe(Info);
507     }
508   }
509   return;  // All users look ok :)
510 }
511
512 /// AllUsersAreLoads - Return true if all users of this value are loads.
513 static bool AllUsersAreLoads(Value *Ptr) {
514   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
515        I != E; ++I)
516     if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
517       return false;
518   return true;
519 }
520
521 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
522 /// aggregate allocation.
523 ///
524 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
525                                  AllocaInfo &Info) {
526   if (BitCastInst *C = dyn_cast<BitCastInst>(User))
527     return isSafeUseOfBitCastedAllocation(C, AI, Info);
528
529   if (LoadInst *LI = dyn_cast<LoadInst>(User))
530     if (!LI->isVolatile())
531       return;// Loads (returning a first class aggregrate) are always rewritable
532
533   if (StoreInst *SI = dyn_cast<StoreInst>(User))
534     if (!SI->isVolatile() && SI->getOperand(0) != AI)
535       return;// Store is ok if storing INTO the pointer, not storing the pointer
536  
537   GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
538   if (GEPI == 0)
539     return MarkUnsafe(Info);
540
541   gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
542
543   // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
544   if (I == E ||
545       I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
546     return MarkUnsafe(Info);
547   }
548
549   ++I;
550   if (I == E) return MarkUnsafe(Info);  // ran out of GEP indices??
551
552   bool IsAllZeroIndices = true;
553   
554   // If the first index is a non-constant index into an array, see if we can
555   // handle it as a special case.
556   if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
557     if (!isa<ConstantInt>(I.getOperand())) {
558       IsAllZeroIndices = 0;
559       uint64_t NumElements = AT->getNumElements();
560       
561       // If this is an array index and the index is not constant, we cannot
562       // promote... that is unless the array has exactly one or two elements in
563       // it, in which case we CAN promote it, but we have to canonicalize this
564       // out if this is the only problem.
565       if ((NumElements == 1 || NumElements == 2) &&
566           AllUsersAreLoads(GEPI)) {
567         Info.needsCleanup = true;
568         return;  // Canonicalization required!
569       }
570       return MarkUnsafe(Info);
571     }
572   }
573  
574   // Walk through the GEP type indices, checking the types that this indexes
575   // into.
576   for (; I != E; ++I) {
577     // Ignore struct elements, no extra checking needed for these.
578     if (isa<StructType>(*I))
579       continue;
580     
581     ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
582     if (!IdxVal) return MarkUnsafe(Info);
583
584     // Are all indices still zero?
585     IsAllZeroIndices &= IdxVal->isZero();
586     
587     if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
588       // This GEP indexes an array.  Verify that this is an in-range constant
589       // integer. Specifically, consider A[0][i]. We cannot know that the user
590       // isn't doing invalid things like allowing i to index an out-of-range
591       // subscript that accesses A[1].  Because of this, we have to reject SROA
592       // of any accesses into structs where any of the components are variables. 
593       if (IdxVal->getZExtValue() >= AT->getNumElements())
594         return MarkUnsafe(Info);
595     } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
596       if (IdxVal->getZExtValue() >= VT->getNumElements())
597         return MarkUnsafe(Info);
598     }
599   }
600   
601   // If there are any non-simple uses of this getelementptr, make sure to reject
602   // them.
603   return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
604 }
605
606 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
607 /// intrinsic can be promoted by SROA.  At this point, we know that the operand
608 /// of the memintrinsic is a pointer to the beginning of the allocation.
609 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
610                                           unsigned OpNo, AllocaInfo &Info) {
611   // If not constant length, give up.
612   ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
613   if (!Length) return MarkUnsafe(Info);
614   
615   // If not the whole aggregate, give up.
616   if (Length->getZExtValue() !=
617       TD->getTypeAllocSize(AI->getType()->getElementType()))
618     return MarkUnsafe(Info);
619   
620   // We only know about memcpy/memset/memmove.
621   if (!isa<MemIntrinsic>(MI))
622     return MarkUnsafe(Info);
623   
624   // Otherwise, we can transform it.  Determine whether this is a memcpy/set
625   // into or out of the aggregate.
626   if (OpNo == 1)
627     Info.isMemCpyDst = true;
628   else {
629     assert(OpNo == 2);
630     Info.isMemCpySrc = true;
631   }
632 }
633
634 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
635 /// are 
636 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
637                                           AllocaInfo &Info) {
638   for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
639        UI != E; ++UI) {
640     if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
641       isSafeUseOfBitCastedAllocation(BCU, AI, Info);
642     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
643       isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
644     } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
645       if (SI->isVolatile())
646         return MarkUnsafe(Info);
647       
648       // If storing the entire alloca in one chunk through a bitcasted pointer
649       // to integer, we can transform it.  This happens (for example) when you
650       // cast a {i32,i32}* to i64* and store through it.  This is similar to the
651       // memcpy case and occurs in various "byval" cases and emulated memcpys.
652       if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
653           TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
654           TD->getTypeAllocSize(AI->getType()->getElementType())) {
655         Info.isMemCpyDst = true;
656         continue;
657       }
658       return MarkUnsafe(Info);
659     } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
660       if (LI->isVolatile())
661         return MarkUnsafe(Info);
662
663       // If loading the entire alloca in one chunk through a bitcasted pointer
664       // to integer, we can transform it.  This happens (for example) when you
665       // cast a {i32,i32}* to i64* and load through it.  This is similar to the
666       // memcpy case and occurs in various "byval" cases and emulated memcpys.
667       if (isa<IntegerType>(LI->getType()) &&
668           TD->getTypeAllocSize(LI->getType()) ==
669           TD->getTypeAllocSize(AI->getType()->getElementType())) {
670         Info.isMemCpySrc = true;
671         continue;
672       }
673       return MarkUnsafe(Info);
674     } else if (isa<DbgInfoIntrinsic>(UI)) {
675       // If one user is DbgInfoIntrinsic then check if all users are
676       // DbgInfoIntrinsics.
677       if (OnlyUsedByDbgInfoIntrinsics(BC)) {
678         Info.needsCleanup = true;
679         return;
680       }
681       else
682         MarkUnsafe(Info);
683     }
684     else {
685       return MarkUnsafe(Info);
686     }
687     if (Info.isUnsafe) return;
688   }
689 }
690
691 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
692 /// to its first element.  Transform users of the cast to use the new values
693 /// instead.
694 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
695                                       SmallVector<AllocaInst*, 32> &NewElts) {
696   Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
697   while (UI != UE) {
698     Instruction *User = cast<Instruction>(*UI++);
699     if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
700       RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
701       if (BCU->use_empty()) BCU->eraseFromParent();
702       continue;
703     }
704
705     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
706       // This must be memcpy/memmove/memset of the entire aggregate.
707       // Split into one per element.
708       RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
709       continue;
710     }
711       
712     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
713       // If this is a store of the entire alloca from an integer, rewrite it.
714       RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
715       continue;
716     }
717
718     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
719       // If this is a load of the entire alloca to an integer, rewrite it.
720       RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
721       continue;
722     }
723     
724     // Otherwise it must be some other user of a gep of the first pointer.  Just
725     // leave these alone.
726     continue;
727   }
728 }
729
730 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
731 /// Rewrite it to copy or set the elements of the scalarized memory.
732 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
733                                         AllocationInst *AI,
734                                         SmallVector<AllocaInst*, 32> &NewElts) {
735   
736   // If this is a memcpy/memmove, construct the other pointer as the
737   // appropriate type.  The "Other" pointer is the pointer that goes to memory
738   // that doesn't have anything to do with the alloca that we are promoting. For
739   // memset, this Value* stays null.
740   Value *OtherPtr = 0;
741   LLVMContext &Context = MI->getContext();
742   unsigned MemAlignment = MI->getAlignment();
743   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
744     if (BCInst == MTI->getRawDest())
745       OtherPtr = MTI->getRawSource();
746     else {
747       assert(BCInst == MTI->getRawSource());
748       OtherPtr = MTI->getRawDest();
749     }
750   }
751   
752   // If there is an other pointer, we want to convert it to the same pointer
753   // type as AI has, so we can GEP through it safely.
754   if (OtherPtr) {
755     // It is likely that OtherPtr is a bitcast, if so, remove it.
756     if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
757       OtherPtr = BC->getOperand(0);
758     // All zero GEPs are effectively bitcasts.
759     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
760       if (GEP->hasAllZeroIndices())
761         OtherPtr = GEP->getOperand(0);
762     
763     if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
764       if (BCE->getOpcode() == Instruction::BitCast)
765         OtherPtr = BCE->getOperand(0);
766     
767     // If the pointer is not the right type, insert a bitcast to the right
768     // type.
769     if (OtherPtr->getType() != AI->getType())
770       OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
771                                  MI);
772   }
773   
774   // Process each element of the aggregate.
775   Value *TheFn = MI->getOperand(0);
776   const Type *BytePtrTy = MI->getRawDest()->getType();
777   bool SROADest = MI->getRawDest() == BCInst;
778   
779   Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
780
781   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
782     // If this is a memcpy/memmove, emit a GEP of the other element address.
783     Value *OtherElt = 0;
784     unsigned OtherEltAlign = MemAlignment;
785     
786     if (OtherPtr) {
787       Value *Idx[2] = { Zero,
788                       ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
789       OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
790                                            OtherPtr->getNameStr()+"."+Twine(i),
791                                            MI);
792       uint64_t EltOffset;
793       const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
794       if (const StructType *ST =
795             dyn_cast<StructType>(OtherPtrTy->getElementType())) {
796         EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
797       } else {
798         const Type *EltTy =
799           cast<SequentialType>(OtherPtr->getType())->getElementType();
800         EltOffset = TD->getTypeAllocSize(EltTy)*i;
801       }
802       
803       // The alignment of the other pointer is the guaranteed alignment of the
804       // element, which is affected by both the known alignment of the whole
805       // mem intrinsic and the alignment of the element.  If the alignment of
806       // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
807       // known alignment is just 4 bytes.
808       OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
809     }
810     
811     Value *EltPtr = NewElts[i];
812     const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
813     
814     // If we got down to a scalar, insert a load or store as appropriate.
815     if (EltTy->isSingleValueType()) {
816       if (isa<MemTransferInst>(MI)) {
817         if (SROADest) {
818           // From Other to Alloca.
819           Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
820           new StoreInst(Elt, EltPtr, MI);
821         } else {
822           // From Alloca to Other.
823           Value *Elt = new LoadInst(EltPtr, "tmp", MI);
824           new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
825         }
826         continue;
827       }
828       assert(isa<MemSetInst>(MI));
829       
830       // If the stored element is zero (common case), just store a null
831       // constant.
832       Constant *StoreVal;
833       if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
834         if (CI->isZero()) {
835           StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
836         } else {
837           // If EltTy is a vector type, get the element type.
838           const Type *ValTy = EltTy->getScalarType();
839
840           // Construct an integer with the right value.
841           unsigned EltSize = TD->getTypeSizeInBits(ValTy);
842           APInt OneVal(EltSize, CI->getZExtValue());
843           APInt TotalVal(OneVal);
844           // Set each byte.
845           for (unsigned i = 0; 8*i < EltSize; ++i) {
846             TotalVal = TotalVal.shl(8);
847             TotalVal |= OneVal;
848           }
849           
850           // Convert the integer value to the appropriate type.
851           StoreVal = ConstantInt::get(Context, TotalVal);
852           if (isa<PointerType>(ValTy))
853             StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
854           else if (ValTy->isFloatingPoint())
855             StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
856           assert(StoreVal->getType() == ValTy && "Type mismatch!");
857           
858           // If the requested value was a vector constant, create it.
859           if (EltTy != ValTy) {
860             unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
861             SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
862             StoreVal = ConstantVector::get(&Elts[0], NumElts);
863           }
864         }
865         new StoreInst(StoreVal, EltPtr, MI);
866         continue;
867       }
868       // Otherwise, if we're storing a byte variable, use a memset call for
869       // this element.
870     }
871     
872     // Cast the element pointer to BytePtrTy.
873     if (EltPtr->getType() != BytePtrTy)
874       EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
875     
876     // Cast the other pointer (if we have one) to BytePtrTy. 
877     if (OtherElt && OtherElt->getType() != BytePtrTy)
878       OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
879                                  MI);
880     
881     unsigned EltSize = TD->getTypeAllocSize(EltTy);
882     
883     // Finally, insert the meminst for this element.
884     if (isa<MemTransferInst>(MI)) {
885       Value *Ops[] = {
886         SROADest ? EltPtr : OtherElt,  // Dest ptr
887         SROADest ? OtherElt : EltPtr,  // Src ptr
888         ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
889         // Align
890         ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
891       };
892       CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
893     } else {
894       assert(isa<MemSetInst>(MI));
895       Value *Ops[] = {
896         EltPtr, MI->getOperand(2),  // Dest, Value,
897         ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
898         Zero  // Align
899       };
900       CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
901     }
902   }
903   MI->eraseFromParent();
904 }
905
906 /// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
907 /// overwrites the entire allocation.  Extract out the pieces of the stored
908 /// integer and store them individually.
909 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
910                                          AllocationInst *AI,
911                                          SmallVector<AllocaInst*, 32> &NewElts){
912   // Extract each element out of the integer according to its structure offset
913   // and store the element value to the individual alloca.
914   Value *SrcVal = SI->getOperand(0);
915   const Type *AllocaEltTy = AI->getType()->getElementType();
916   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
917   
918   // If this isn't a store of an integer to the whole alloca, it may be a store
919   // to the first element.  Just ignore the store in this case and normal SROA
920   // will handle it.
921   if (!isa<IntegerType>(SrcVal->getType()) ||
922       TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
923     return;
924   // Handle tail padding by extending the operand
925   if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
926     SrcVal = new ZExtInst(SrcVal,
927                           IntegerType::get(SI->getContext(), AllocaSizeBits), 
928                           "", SI);
929
930   DEBUG(errs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI);
931
932   // There are two forms here: AI could be an array or struct.  Both cases
933   // have different ways to compute the element offset.
934   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
935     const StructLayout *Layout = TD->getStructLayout(EltSTy);
936     
937     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
938       // Get the number of bits to shift SrcVal to get the value.
939       const Type *FieldTy = EltSTy->getElementType(i);
940       uint64_t Shift = Layout->getElementOffsetInBits(i);
941       
942       if (TD->isBigEndian())
943         Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
944       
945       Value *EltVal = SrcVal;
946       if (Shift) {
947         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
948         EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
949                                             "sroa.store.elt", SI);
950       }
951       
952       // Truncate down to an integer of the right size.
953       uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
954       
955       // Ignore zero sized fields like {}, they obviously contain no data.
956       if (FieldSizeBits == 0) continue;
957       
958       if (FieldSizeBits != AllocaSizeBits)
959         EltVal = new TruncInst(EltVal,
960                              IntegerType::get(SI->getContext(), FieldSizeBits),
961                               "", SI);
962       Value *DestField = NewElts[i];
963       if (EltVal->getType() == FieldTy) {
964         // Storing to an integer field of this size, just do it.
965       } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
966         // Bitcast to the right element type (for fp/vector values).
967         EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
968       } else {
969         // Otherwise, bitcast the dest pointer (for aggregates).
970         DestField = new BitCastInst(DestField,
971                               PointerType::getUnqual(EltVal->getType()),
972                                     "", SI);
973       }
974       new StoreInst(EltVal, DestField, SI);
975     }
976     
977   } else {
978     const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
979     const Type *ArrayEltTy = ATy->getElementType();
980     uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
981     uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
982
983     uint64_t Shift;
984     
985     if (TD->isBigEndian())
986       Shift = AllocaSizeBits-ElementOffset;
987     else 
988       Shift = 0;
989     
990     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
991       // Ignore zero sized fields like {}, they obviously contain no data.
992       if (ElementSizeBits == 0) continue;
993       
994       Value *EltVal = SrcVal;
995       if (Shift) {
996         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
997         EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
998                                             "sroa.store.elt", SI);
999       }
1000       
1001       // Truncate down to an integer of the right size.
1002       if (ElementSizeBits != AllocaSizeBits)
1003         EltVal = new TruncInst(EltVal, 
1004                                IntegerType::get(SI->getContext(), 
1005                                                 ElementSizeBits),"",SI);
1006       Value *DestField = NewElts[i];
1007       if (EltVal->getType() == ArrayEltTy) {
1008         // Storing to an integer field of this size, just do it.
1009       } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1010         // Bitcast to the right element type (for fp/vector values).
1011         EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1012       } else {
1013         // Otherwise, bitcast the dest pointer (for aggregates).
1014         DestField = new BitCastInst(DestField,
1015                               PointerType::getUnqual(EltVal->getType()),
1016                                     "", SI);
1017       }
1018       new StoreInst(EltVal, DestField, SI);
1019       
1020       if (TD->isBigEndian())
1021         Shift -= ElementOffset;
1022       else 
1023         Shift += ElementOffset;
1024     }
1025   }
1026   
1027   SI->eraseFromParent();
1028 }
1029
1030 /// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
1031 /// an integer.  Load the individual pieces to form the aggregate value.
1032 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
1033                                         SmallVector<AllocaInst*, 32> &NewElts) {
1034   // Extract each element out of the NewElts according to its structure offset
1035   // and form the result value.
1036   const Type *AllocaEltTy = AI->getType()->getElementType();
1037   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1038   
1039   // If this isn't a load of the whole alloca to an integer, it may be a load
1040   // of the first element.  Just ignore the load in this case and normal SROA
1041   // will handle it.
1042   if (!isa<IntegerType>(LI->getType()) ||
1043       TD->getTypeAllocSizeInBits(LI->getType()) != AllocaSizeBits)
1044     return;
1045   
1046   DEBUG(errs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI);
1047   
1048   // There are two forms here: AI could be an array or struct.  Both cases
1049   // have different ways to compute the element offset.
1050   const StructLayout *Layout = 0;
1051   uint64_t ArrayEltBitOffset = 0;
1052   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1053     Layout = TD->getStructLayout(EltSTy);
1054   } else {
1055     const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1056     ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1057   }    
1058   
1059   Value *ResultVal = 
1060     Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1061   
1062   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1063     // Load the value from the alloca.  If the NewElt is an aggregate, cast
1064     // the pointer to an integer of the same size before doing the load.
1065     Value *SrcField = NewElts[i];
1066     const Type *FieldTy =
1067       cast<PointerType>(SrcField->getType())->getElementType();
1068     uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1069     
1070     // Ignore zero sized fields like {}, they obviously contain no data.
1071     if (FieldSizeBits == 0) continue;
1072     
1073     const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(), 
1074                                                      FieldSizeBits);
1075     if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1076         !isa<VectorType>(FieldTy))
1077       SrcField = new BitCastInst(SrcField,
1078                                  PointerType::getUnqual(FieldIntTy),
1079                                  "", LI);
1080     SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1081
1082     // If SrcField is a fp or vector of the right size but that isn't an
1083     // integer type, bitcast to an integer so we can shift it.
1084     if (SrcField->getType() != FieldIntTy)
1085       SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1086
1087     // Zero extend the field to be the same size as the final alloca so that
1088     // we can shift and insert it.
1089     if (SrcField->getType() != ResultVal->getType())
1090       SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1091     
1092     // Determine the number of bits to shift SrcField.
1093     uint64_t Shift;
1094     if (Layout) // Struct case.
1095       Shift = Layout->getElementOffsetInBits(i);
1096     else  // Array case.
1097       Shift = i*ArrayEltBitOffset;
1098     
1099     if (TD->isBigEndian())
1100       Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1101     
1102     if (Shift) {
1103       Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1104       SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1105     }
1106
1107     ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1108   }
1109
1110   // Handle tail padding by truncating the result
1111   if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1112     ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1113
1114   LI->replaceAllUsesWith(ResultVal);
1115   LI->eraseFromParent();
1116 }
1117
1118
1119 /// HasPadding - Return true if the specified type has any structure or
1120 /// alignment padding, false otherwise.
1121 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1122   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1123     const StructLayout *SL = TD.getStructLayout(STy);
1124     unsigned PrevFieldBitOffset = 0;
1125     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1126       unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1127
1128       // Padding in sub-elements?
1129       if (HasPadding(STy->getElementType(i), TD))
1130         return true;
1131
1132       // Check to see if there is any padding between this element and the
1133       // previous one.
1134       if (i) {
1135         unsigned PrevFieldEnd =
1136         PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1137         if (PrevFieldEnd < FieldBitOffset)
1138           return true;
1139       }
1140
1141       PrevFieldBitOffset = FieldBitOffset;
1142     }
1143
1144     //  Check for tail padding.
1145     if (unsigned EltCount = STy->getNumElements()) {
1146       unsigned PrevFieldEnd = PrevFieldBitOffset +
1147                    TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1148       if (PrevFieldEnd < SL->getSizeInBits())
1149         return true;
1150     }
1151
1152   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1153     return HasPadding(ATy->getElementType(), TD);
1154   } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1155     return HasPadding(VTy->getElementType(), TD);
1156   }
1157   return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1158 }
1159
1160 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1161 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
1162 /// or 1 if safe after canonicalization has been performed.
1163 ///
1164 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1165   // Loop over the use list of the alloca.  We can only transform it if all of
1166   // the users are safe to transform.
1167   AllocaInfo Info;
1168   
1169   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1170        I != E; ++I) {
1171     isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1172     if (Info.isUnsafe) {
1173       DEBUG(errs() << "Cannot transform: " << *AI << "  due to user: " << **I);
1174       return 0;
1175     }
1176   }
1177   
1178   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
1179   // source and destination, we have to be careful.  In particular, the memcpy
1180   // could be moving around elements that live in structure padding of the LLVM
1181   // types, but may actually be used.  In these cases, we refuse to promote the
1182   // struct.
1183   if (Info.isMemCpySrc && Info.isMemCpyDst &&
1184       HasPadding(AI->getType()->getElementType(), *TD))
1185     return 0;
1186
1187   // If we require cleanup, return 1, otherwise return 3.
1188   return Info.needsCleanup ? 1 : 3;
1189 }
1190
1191 /// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1192 /// is canonicalized here.
1193 void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1194   gep_type_iterator I = gep_type_begin(GEPI);
1195   ++I;
1196   
1197   const ArrayType *AT = dyn_cast<ArrayType>(*I);
1198   if (!AT) 
1199     return;
1200
1201   uint64_t NumElements = AT->getNumElements();
1202   
1203   if (isa<ConstantInt>(I.getOperand()))
1204     return;
1205
1206   if (NumElements == 1) {
1207     GEPI->setOperand(2, 
1208                   Constant::getNullValue(Type::getInt32Ty(GEPI->getContext())));
1209     return;
1210   } 
1211     
1212   assert(NumElements == 2 && "Unhandled case!");
1213   // All users of the GEP must be loads.  At each use of the GEP, insert
1214   // two loads of the appropriate indexed GEP and select between them.
1215   Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(), 
1216                               Constant::getNullValue(I.getOperand()->getType()),
1217                               "isone");
1218   // Insert the new GEP instructions, which are properly indexed.
1219   SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1220   Indices[1] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
1221   Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1222                                              Indices.begin(),
1223                                              Indices.end(),
1224                                              GEPI->getName()+".0", GEPI);
1225   Indices[1] = ConstantInt::get(Type::getInt32Ty(GEPI->getContext()), 1);
1226   Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1227                                             Indices.begin(),
1228                                             Indices.end(),
1229                                             GEPI->getName()+".1", GEPI);
1230   // Replace all loads of the variable index GEP with loads from both
1231   // indexes and a select.
1232   while (!GEPI->use_empty()) {
1233     LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1234     Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1235     Value *One  = new LoadInst(OneIdx , LI->getName()+".1", LI);
1236     Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1237     LI->replaceAllUsesWith(R);
1238     LI->eraseFromParent();
1239   }
1240   GEPI->eraseFromParent();
1241 }
1242
1243
1244 /// CleanupAllocaUsers - If SROA reported that it can promote the specified
1245 /// allocation, but only if cleaned up, perform the cleanups required.
1246 void SROA::CleanupAllocaUsers(AllocationInst *AI) {
1247   // At this point, we know that the end result will be SROA'd and promoted, so
1248   // we can insert ugly code if required so long as sroa+mem2reg will clean it
1249   // up.
1250   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1251        UI != E; ) {
1252     User *U = *UI++;
1253     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1254       CleanupGEP(GEPI);
1255     else {
1256       Instruction *I = cast<Instruction>(U);
1257       SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1258       if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1259         // Safe to remove debug info uses.
1260         while (!DbgInUses.empty()) {
1261           DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1262           DI->eraseFromParent();
1263         }
1264         I->eraseFromParent();
1265       }
1266     }
1267   }
1268 }
1269
1270 /// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1271 /// the offset specified by Offset (which is specified in bytes).
1272 ///
1273 /// There are two cases we handle here:
1274 ///   1) A union of vector types of the same size and potentially its elements.
1275 ///      Here we turn element accesses into insert/extract element operations.
1276 ///      This promotes a <4 x float> with a store of float to the third element
1277 ///      into a <4 x float> that uses insert element.
1278 ///   2) A fully general blob of memory, which we turn into some (potentially
1279 ///      large) integer type with extract and insert operations where the loads
1280 ///      and stores would mutate the memory.
1281 static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1282                         unsigned AllocaSize, const TargetData &TD,
1283                         LLVMContext &Context) {
1284   // If this could be contributing to a vector, analyze it.
1285   if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
1286
1287     // If the In type is a vector that is the same size as the alloca, see if it
1288     // matches the existing VecTy.
1289     if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1290       if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1291         // If we're storing/loading a vector of the right size, allow it as a
1292         // vector.  If this the first vector we see, remember the type so that
1293         // we know the element size.
1294         if (VecTy == 0)
1295           VecTy = VInTy;
1296         return;
1297       }
1298     } else if (In == Type::getFloatTy(Context) ||
1299                In == Type::getDoubleTy(Context) ||
1300                (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1301                 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1302       // If we're accessing something that could be an element of a vector, see
1303       // if the implied vector agrees with what we already have and if Offset is
1304       // compatible with it.
1305       unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1306       if (Offset % EltSize == 0 &&
1307           AllocaSize % EltSize == 0 &&
1308           (VecTy == 0 || 
1309            cast<VectorType>(VecTy)->getElementType()
1310                  ->getPrimitiveSizeInBits()/8 == EltSize)) {
1311         if (VecTy == 0)
1312           VecTy = VectorType::get(In, AllocaSize/EltSize);
1313         return;
1314       }
1315     }
1316   }
1317   
1318   // Otherwise, we have a case that we can't handle with an optimized vector
1319   // form.  We can still turn this into a large integer.
1320   VecTy = Type::getVoidTy(Context);
1321 }
1322
1323 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
1324 /// its accesses to use a to single vector type, return true, and set VecTy to
1325 /// the new type.  If we could convert the alloca into a single promotable
1326 /// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
1327 /// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
1328 /// is the current offset from the base of the alloca being analyzed.
1329 ///
1330 /// If we see at least one access to the value that is as a vector type, set the
1331 /// SawVec flag.
1332 ///
1333 bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1334                               bool &SawVec, uint64_t Offset,
1335                               unsigned AllocaSize) {
1336   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1337     Instruction *User = cast<Instruction>(*UI);
1338     
1339     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1340       // Don't break volatile loads.
1341       if (LI->isVolatile())
1342         return false;
1343       MergeInType(LI->getType(), Offset, VecTy,
1344                   AllocaSize, *TD, V->getContext());
1345       SawVec |= isa<VectorType>(LI->getType());
1346       continue;
1347     }
1348     
1349     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1350       // Storing the pointer, not into the value?
1351       if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
1352       MergeInType(SI->getOperand(0)->getType(), Offset,
1353                   VecTy, AllocaSize, *TD, V->getContext());
1354       SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
1355       continue;
1356     }
1357     
1358     if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1359       if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1360                               AllocaSize))
1361         return false;
1362       IsNotTrivial = true;
1363       continue;
1364     }
1365
1366     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1367       // If this is a GEP with a variable indices, we can't handle it.
1368       if (!GEP->hasAllConstantIndices())
1369         return false;
1370       
1371       // Compute the offset that this GEP adds to the pointer.
1372       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1373       uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1374                                                 &Indices[0], Indices.size());
1375       // See if all uses can be converted.
1376       if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
1377                               AllocaSize))
1378         return false;
1379       IsNotTrivial = true;
1380       continue;
1381     }
1382
1383     // If this is a constant sized memset of a constant value (e.g. 0) we can
1384     // handle it.
1385     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1386       // Store of constant value and constant size.
1387       if (isa<ConstantInt>(MSI->getValue()) &&
1388           isa<ConstantInt>(MSI->getLength())) {
1389         IsNotTrivial = true;
1390         continue;
1391       }
1392     }
1393
1394     // If this is a memcpy or memmove into or out of the whole allocation, we
1395     // can handle it like a load or store of the scalar type.
1396     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1397       if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1398         if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1399           IsNotTrivial = true;
1400           continue;
1401         }
1402     }
1403     
1404     // Ignore dbg intrinsic.
1405     if (isa<DbgInfoIntrinsic>(User))
1406       continue;
1407
1408     // Otherwise, we cannot handle this!
1409     return false;
1410   }
1411   
1412   return true;
1413 }
1414
1415
1416 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1417 /// directly.  This happens when we are converting an "integer union" to a
1418 /// single integer scalar, or when we are converting a "vector union" to a
1419 /// vector with insert/extractelement instructions.
1420 ///
1421 /// Offset is an offset from the original alloca, in bits that need to be
1422 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
1423 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
1424   while (!Ptr->use_empty()) {
1425     Instruction *User = cast<Instruction>(Ptr->use_back());
1426
1427     if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1428       ConvertUsesToScalar(CI, NewAI, Offset);
1429       CI->eraseFromParent();
1430       continue;
1431     }
1432
1433     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1434       // Compute the offset that this GEP adds to the pointer.
1435       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1436       uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1437                                                 &Indices[0], Indices.size());
1438       ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
1439       GEP->eraseFromParent();
1440       continue;
1441     }
1442     
1443     IRBuilder<> Builder(User->getParent(), User);
1444     
1445     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1446       // The load is a bit extract from NewAI shifted right by Offset bits.
1447       Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1448       Value *NewLoadVal
1449         = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1450       LI->replaceAllUsesWith(NewLoadVal);
1451       LI->eraseFromParent();
1452       continue;
1453     }
1454     
1455     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1456       assert(SI->getOperand(0) != Ptr && "Consistency error!");
1457       // FIXME: Remove once builder has Twine API.
1458       Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
1459       Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1460                                              Builder);
1461       Builder.CreateStore(New, NewAI);
1462       SI->eraseFromParent();
1463       continue;
1464     }
1465     
1466     // If this is a constant sized memset of a constant value (e.g. 0) we can
1467     // transform it into a store of the expanded constant value.
1468     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1469       assert(MSI->getRawDest() == Ptr && "Consistency error!");
1470       unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
1471       if (NumBytes != 0) {
1472         unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1473         
1474         // Compute the value replicated the right number of times.
1475         APInt APVal(NumBytes*8, Val);
1476
1477         // Splat the value if non-zero.
1478         if (Val)
1479           for (unsigned i = 1; i != NumBytes; ++i)
1480             APVal |= APVal << 8;
1481         
1482         // FIXME: Remove once builder has Twine API.
1483         Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
1484         Value *New = ConvertScalar_InsertValue(
1485                                     ConstantInt::get(User->getContext(), APVal),
1486                                                Old, Offset, Builder);
1487         Builder.CreateStore(New, NewAI);
1488       }
1489       MSI->eraseFromParent();
1490       continue;
1491     }
1492
1493     // If this is a memcpy or memmove into or out of the whole allocation, we
1494     // can handle it like a load or store of the scalar type.
1495     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1496       assert(Offset == 0 && "must be store to start of alloca");
1497       
1498       // If the source and destination are both to the same alloca, then this is
1499       // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
1500       // as appropriate.
1501       AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1502       
1503       if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1504         // Dest must be OrigAI, change this to be a load from the original
1505         // pointer (bitcasted), then a store to our new alloca.
1506         assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1507         Value *SrcPtr = MTI->getSource();
1508         SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1509         
1510         LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1511         SrcVal->setAlignment(MTI->getAlignment());
1512         Builder.CreateStore(SrcVal, NewAI);
1513       } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1514         // Src must be OrigAI, change this to be a load from NewAI then a store
1515         // through the original dest pointer (bitcasted).
1516         assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1517         LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1518
1519         Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1520         StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1521         NewStore->setAlignment(MTI->getAlignment());
1522       } else {
1523         // Noop transfer. Src == Dst
1524       }
1525           
1526
1527       MTI->eraseFromParent();
1528       continue;
1529     }
1530     
1531     // If user is a dbg info intrinsic then it is safe to remove it.
1532     if (isa<DbgInfoIntrinsic>(User)) {
1533       User->eraseFromParent();
1534       continue;
1535     }
1536
1537     llvm_unreachable("Unsupported operation!");
1538   }
1539 }
1540
1541 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1542 /// or vector value FromVal, extracting the bits from the offset specified by
1543 /// Offset.  This returns the value, which is of type ToType.
1544 ///
1545 /// This happens when we are converting an "integer union" to a single
1546 /// integer scalar, or when we are converting a "vector union" to a vector with
1547 /// insert/extractelement instructions.
1548 ///
1549 /// Offset is an offset from the original alloca, in bits that need to be
1550 /// shifted to the right.
1551 Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1552                                         uint64_t Offset, IRBuilder<> &Builder) {
1553   // If the load is of the whole new alloca, no conversion is needed.
1554   if (FromVal->getType() == ToType && Offset == 0)
1555     return FromVal;
1556
1557   // If the result alloca is a vector type, this is either an element
1558   // access or a bitcast to another vector type of the same size.
1559   if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1560     if (isa<VectorType>(ToType))
1561       return Builder.CreateBitCast(FromVal, ToType, "tmp");
1562
1563     // Otherwise it must be an element access.
1564     unsigned Elt = 0;
1565     if (Offset) {
1566       unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1567       Elt = Offset/EltSize;
1568       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
1569     }
1570     // Return the element extracted out of it.
1571     Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1572                     Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
1573     if (V->getType() != ToType)
1574       V = Builder.CreateBitCast(V, ToType, "tmp");
1575     return V;
1576   }
1577   
1578   // If ToType is a first class aggregate, extract out each of the pieces and
1579   // use insertvalue's to form the FCA.
1580   if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1581     const StructLayout &Layout = *TD->getStructLayout(ST);
1582     Value *Res = UndefValue::get(ST);
1583     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1584       Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
1585                                         Offset+Layout.getElementOffsetInBits(i),
1586                                               Builder);
1587       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1588     }
1589     return Res;
1590   }
1591   
1592   if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1593     uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1594     Value *Res = UndefValue::get(AT);
1595     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1596       Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1597                                               Offset+i*EltSize, Builder);
1598       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1599     }
1600     return Res;
1601   }
1602
1603   // Otherwise, this must be a union that was converted to an integer value.
1604   const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
1605
1606   // If this is a big-endian system and the load is narrower than the
1607   // full alloca type, we need to do a shift to get the right bits.
1608   int ShAmt = 0;
1609   if (TD->isBigEndian()) {
1610     // On big-endian machines, the lowest bit is stored at the bit offset
1611     // from the pointer given by getTypeStoreSizeInBits.  This matters for
1612     // integers with a bitwidth that is not a multiple of 8.
1613     ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1614             TD->getTypeStoreSizeInBits(ToType) - Offset;
1615   } else {
1616     ShAmt = Offset;
1617   }
1618
1619   // Note: we support negative bitwidths (with shl) which are not defined.
1620   // We do this to support (f.e.) loads off the end of a structure where
1621   // only some bits are used.
1622   if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1623     FromVal = Builder.CreateLShr(FromVal,
1624                                  ConstantInt::get(FromVal->getType(),
1625                                                            ShAmt), "tmp");
1626   else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1627     FromVal = Builder.CreateShl(FromVal, 
1628                                 ConstantInt::get(FromVal->getType(),
1629                                                           -ShAmt), "tmp");
1630
1631   // Finally, unconditionally truncate the integer to the right width.
1632   unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
1633   if (LIBitWidth < NTy->getBitWidth())
1634     FromVal =
1635       Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(), 
1636                                                     LIBitWidth), "tmp");
1637   else if (LIBitWidth > NTy->getBitWidth())
1638     FromVal =
1639        Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(), 
1640                                                     LIBitWidth), "tmp");
1641
1642   // If the result is an integer, this is a trunc or bitcast.
1643   if (isa<IntegerType>(ToType)) {
1644     // Should be done.
1645   } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
1646     // Just do a bitcast, we know the sizes match up.
1647     FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
1648   } else {
1649     // Otherwise must be a pointer.
1650     FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
1651   }
1652   assert(FromVal->getType() == ToType && "Didn't convert right?");
1653   return FromVal;
1654 }
1655
1656
1657 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1658 /// or vector value "Old" at the offset specified by Offset.
1659 ///
1660 /// This happens when we are converting an "integer union" to a
1661 /// single integer scalar, or when we are converting a "vector union" to a
1662 /// vector with insert/extractelement instructions.
1663 ///
1664 /// Offset is an offset from the original alloca, in bits that need to be
1665 /// shifted to the right.
1666 Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
1667                                        uint64_t Offset, IRBuilder<> &Builder) {
1668
1669   // Convert the stored type to the actual type, shift it left to insert
1670   // then 'or' into place.
1671   const Type *AllocaType = Old->getType();
1672   LLVMContext &Context = Old->getContext();
1673
1674   if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
1675     uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1676     uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
1677     
1678     // Changing the whole vector with memset or with an access of a different
1679     // vector type?
1680     if (ValSize == VecSize)
1681       return Builder.CreateBitCast(SV, AllocaType, "tmp");
1682
1683     uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1684
1685     // Must be an element insertion.
1686     unsigned Elt = Offset/EltSize;
1687     
1688     if (SV->getType() != VTy->getElementType())
1689       SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1690     
1691     SV = Builder.CreateInsertElement(Old, SV, 
1692                      ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
1693                                      "tmp");
1694     return SV;
1695   }
1696   
1697   // If SV is a first-class aggregate value, insert each value recursively.
1698   if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1699     const StructLayout &Layout = *TD->getStructLayout(ST);
1700     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1701       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1702       Old = ConvertScalar_InsertValue(Elt, Old, 
1703                                       Offset+Layout.getElementOffsetInBits(i),
1704                                       Builder);
1705     }
1706     return Old;
1707   }
1708   
1709   if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1710     uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1711     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1712       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1713       Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1714     }
1715     return Old;
1716   }
1717
1718   // If SV is a float, convert it to the appropriate integer type.
1719   // If it is a pointer, do the same.
1720   unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1721   unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1722   unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1723   unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1724   if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
1725     SV = Builder.CreateBitCast(SV,
1726                             IntegerType::get(SV->getContext(),SrcWidth), "tmp");
1727   else if (isa<PointerType>(SV->getType()))
1728     SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
1729
1730   // Zero extend or truncate the value if needed.
1731   if (SV->getType() != AllocaType) {
1732     if (SV->getType()->getPrimitiveSizeInBits() <
1733              AllocaType->getPrimitiveSizeInBits())
1734       SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1735     else {
1736       // Truncation may be needed if storing more than the alloca can hold
1737       // (undefined behavior).
1738       SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1739       SrcWidth = DestWidth;
1740       SrcStoreWidth = DestStoreWidth;
1741     }
1742   }
1743
1744   // If this is a big-endian system and the store is narrower than the
1745   // full alloca type, we need to do a shift to get the right bits.
1746   int ShAmt = 0;
1747   if (TD->isBigEndian()) {
1748     // On big-endian machines, the lowest bit is stored at the bit offset
1749     // from the pointer given by getTypeStoreSizeInBits.  This matters for
1750     // integers with a bitwidth that is not a multiple of 8.
1751     ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1752   } else {
1753     ShAmt = Offset;
1754   }
1755
1756   // Note: we support negative bitwidths (with shr) which are not defined.
1757   // We do this to support (f.e.) stores off the end of a structure where
1758   // only some bits in the structure are set.
1759   APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1760   if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1761     SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1762                            ShAmt), "tmp");
1763     Mask <<= ShAmt;
1764   } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1765     SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1766                             -ShAmt), "tmp");
1767     Mask = Mask.lshr(-ShAmt);
1768   }
1769
1770   // Mask out the bits we are about to insert from the old value, and or
1771   // in the new bits.
1772   if (SrcWidth != DestWidth) {
1773     assert(DestWidth > SrcWidth);
1774     Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1775     SV = Builder.CreateOr(Old, SV, "ins");
1776   }
1777   return SV;
1778 }
1779
1780
1781
1782 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1783 /// some part of a constant global variable.  This intentionally only accepts
1784 /// constant expressions because we don't can't rewrite arbitrary instructions.
1785 static bool PointsToConstantGlobal(Value *V) {
1786   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1787     return GV->isConstant();
1788   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1789     if (CE->getOpcode() == Instruction::BitCast || 
1790         CE->getOpcode() == Instruction::GetElementPtr)
1791       return PointsToConstantGlobal(CE->getOperand(0));
1792   return false;
1793 }
1794
1795 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1796 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
1797 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
1798 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1799 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
1800 /// the alloca, and if the source pointer is a pointer to a constant  global, we
1801 /// can optimize this.
1802 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1803                                            bool isOffset) {
1804   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1805     if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1806       // Ignore non-volatile loads, they are always ok.
1807       if (!LI->isVolatile())
1808         continue;
1809     
1810     if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1811       // If uses of the bitcast are ok, we are ok.
1812       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1813         return false;
1814       continue;
1815     }
1816     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1817       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
1818       // doesn't, it does.
1819       if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1820                                          isOffset || !GEP->hasAllZeroIndices()))
1821         return false;
1822       continue;
1823     }
1824     
1825     // If this is isn't our memcpy/memmove, reject it as something we can't
1826     // handle.
1827     if (!isa<MemTransferInst>(*UI))
1828       return false;
1829
1830     // If we already have seen a copy, reject the second one.
1831     if (TheCopy) return false;
1832     
1833     // If the pointer has been offset from the start of the alloca, we can't
1834     // safely handle this.
1835     if (isOffset) return false;
1836
1837     // If the memintrinsic isn't using the alloca as the dest, reject it.
1838     if (UI.getOperandNo() != 1) return false;
1839     
1840     MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1841     
1842     // If the source of the memcpy/move is not a constant global, reject it.
1843     if (!PointsToConstantGlobal(MI->getOperand(2)))
1844       return false;
1845     
1846     // Otherwise, the transform is safe.  Remember the copy instruction.
1847     TheCopy = MI;
1848   }
1849   return true;
1850 }
1851
1852 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1853 /// modified by a copy from a constant global.  If we can prove this, we can
1854 /// replace any uses of the alloca with uses of the global directly.
1855 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1856   Instruction *TheCopy = 0;
1857   if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1858     return TheCopy;
1859   return 0;
1860 }